1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for declarations.
12 //===----------------------------------------------------------------------===//
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
51 using namespace clang;
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68 bool AllowTemplates=false)
69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70 AllowTemplates(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 = AllowTemplates && getAsTypeTemplateDecl(ND);
80 return (IsType || AllowedTemplate) &&
81 (AllowInvalidDecl || !ND->isInvalidDecl());
83 return !WantClassName && candidate.isKeyword();
87 bool AllowInvalidDecl;
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___float128:
112 case tok::kw_wchar_t:
114 case tok::kw___underlying_type:
115 case tok::kw___auto_type:
118 case tok::annot_typename:
119 case tok::kw_char16_t:
120 case tok::kw_char32_t:
122 case tok::annot_decltype:
123 case tok::kw_decltype:
124 return getLangOpts().CPlusPlus;
134 enum class UnqualifiedTypeNameLookupResult {
139 } // end anonymous namespace
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147 SourceLocation NameLoc,
148 const CXXRecordDecl *RD) {
149 if (!RD->hasDefinition())
150 return UnqualifiedTypeNameLookupResult::NotFound;
151 // Look for type decls in base classes.
152 UnqualifiedTypeNameLookupResult FoundTypeDecl =
153 UnqualifiedTypeNameLookupResult::NotFound;
154 for (const auto &Base : RD->bases()) {
155 const CXXRecordDecl *BaseRD = nullptr;
156 if (auto *BaseTT = Base.getType()->getAs<TagType>())
157 BaseRD = BaseTT->getAsCXXRecordDecl();
158 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159 // Look for type decls in dependent base classes that have known primary
161 if (!TST || !TST->isDependentType())
163 auto *TD = TST->getTemplateName().getAsTemplateDecl();
166 if (auto *BasePrimaryTemplate =
167 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169 BaseRD = BasePrimaryTemplate;
170 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171 if (const ClassTemplatePartialSpecializationDecl *PS =
172 CTD->findPartialSpecialization(Base.getType()))
173 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
179 for (NamedDecl *ND : BaseRD->lookup(&II)) {
180 if (!isa<TypeDecl>(ND))
181 return UnqualifiedTypeNameLookupResult::FoundNonType;
182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
184 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186 case UnqualifiedTypeNameLookupResult::FoundNonType:
187 return UnqualifiedTypeNameLookupResult::FoundNonType;
188 case UnqualifiedTypeNameLookupResult::FoundType:
189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
191 case UnqualifiedTypeNameLookupResult::NotFound:
198 return FoundTypeDecl;
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202 const IdentifierInfo &II,
203 SourceLocation NameLoc) {
204 // Lookup in the parent class template context, if any.
205 const CXXRecordDecl *RD = nullptr;
206 UnqualifiedTypeNameLookupResult FoundTypeDecl =
207 UnqualifiedTypeNameLookupResult::NotFound;
208 for (DeclContext *DC = S.CurContext;
209 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210 DC = DC->getParent()) {
211 // Look for type decls in dependent base classes that have known primary
213 RD = dyn_cast<CXXRecordDecl>(DC);
214 if (RD && RD->getDescribedClassTemplate())
215 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
217 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
220 // We found some types in dependent base classes. Recover as if the user
221 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
222 // lookup during template instantiation.
223 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
225 ASTContext &Context = S.Context;
226 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227 cast<Type>(Context.getRecordType(RD)));
228 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
231 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
233 TypeLocBuilder Builder;
234 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235 DepTL.setNameLoc(NameLoc);
236 DepTL.setElaboratedKeywordLoc(SourceLocation());
237 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250 Scope *S, CXXScopeSpec *SS,
251 bool isClassName, bool HasTrailingDot,
252 ParsedType ObjectTypePtr,
253 bool IsCtorOrDtorName,
254 bool WantNontrivialTypeSourceInfo,
255 bool IsClassTemplateDeductionContext,
256 IdentifierInfo **CorrectedII) {
257 // FIXME: Consider allowing this outside C++1z mode as an extension.
258 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
259 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
260 !isClassName && !HasTrailingDot;
262 // Determine where we will perform name lookup.
263 DeclContext *LookupCtx = nullptr;
265 QualType ObjectType = ObjectTypePtr.get();
266 if (ObjectType->isRecordType())
267 LookupCtx = computeDeclContext(ObjectType);
268 } else if (SS && SS->isNotEmpty()) {
269 LookupCtx = computeDeclContext(*SS, false);
272 if (isDependentScopeSpecifier(*SS)) {
274 // A qualified-id that refers to a type and in which the
275 // nested-name-specifier depends on a template-parameter (14.6.2)
276 // shall be prefixed by the keyword typename to indicate that the
277 // qualified-id denotes a type, forming an
278 // elaborated-type-specifier (7.1.5.3).
280 // We therefore do not perform any name lookup if the result would
281 // refer to a member of an unknown specialization.
282 if (!isClassName && !IsCtorOrDtorName)
285 // We know from the grammar that this name refers to a type,
286 // so build a dependent node to describe the type.
287 if (WantNontrivialTypeSourceInfo)
288 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
290 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
291 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
293 return ParsedType::make(T);
299 if (!LookupCtx->isDependentContext() &&
300 RequireCompleteDeclContext(*SS, LookupCtx))
304 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
305 // lookup for class-names.
306 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
308 LookupResult Result(*this, &II, NameLoc, Kind);
310 // Perform "qualified" name lookup into the declaration context we
311 // computed, which is either the type of the base of a member access
312 // expression or the declaration context associated with a prior
313 // nested-name-specifier.
314 LookupQualifiedName(Result, LookupCtx);
316 if (ObjectTypePtr && Result.empty()) {
317 // C++ [basic.lookup.classref]p3:
318 // If the unqualified-id is ~type-name, the type-name is looked up
319 // in the context of the entire postfix-expression. If the type T of
320 // the object expression is of a class type C, the type-name is also
321 // looked up in the scope of class C. At least one of the lookups shall
322 // find a name that refers to (possibly cv-qualified) T.
323 LookupName(Result, S);
326 // Perform unqualified name lookup.
327 LookupName(Result, S);
329 // For unqualified lookup in a class template in MSVC mode, look into
330 // dependent base classes where the primary class template is known.
331 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
332 if (ParsedType TypeInBase =
333 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
338 NamedDecl *IIDecl = nullptr;
339 switch (Result.getResultKind()) {
340 case LookupResult::NotFound:
341 case LookupResult::NotFoundInCurrentInstantiation:
343 TypoCorrection Correction =
344 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
345 llvm::make_unique<TypeNameValidatorCCC>(
346 true, isClassName, AllowDeducedTemplate),
348 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
350 bool MemberOfUnknownSpecialization;
351 UnqualifiedId TemplateName;
352 TemplateName.setIdentifier(NewII, NameLoc);
353 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
354 CXXScopeSpec NewSS, *NewSSPtr = SS;
356 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
359 if (Correction && (NNS || NewII != &II) &&
360 // Ignore a correction to a template type as the to-be-corrected
361 // identifier is not a template (typo correction for template names
362 // is handled elsewhere).
363 !(getLangOpts().CPlusPlus && NewSSPtr &&
364 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
365 Template, MemberOfUnknownSpecialization))) {
366 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
367 isClassName, HasTrailingDot, ObjectTypePtr,
369 WantNontrivialTypeSourceInfo,
370 IsClassTemplateDeductionContext);
372 diagnoseTypo(Correction,
373 PDiag(diag::err_unknown_type_or_class_name_suggest)
374 << Result.getLookupName() << isClassName);
376 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
377 *CorrectedII = NewII;
382 // If typo correction failed or was not performed, fall through
383 case LookupResult::FoundOverloaded:
384 case LookupResult::FoundUnresolvedValue:
385 Result.suppressDiagnostics();
388 case LookupResult::Ambiguous:
389 // Recover from type-hiding ambiguities by hiding the type. We'll
390 // do the lookup again when looking for an object, and we can
391 // diagnose the error then. If we don't do this, then the error
392 // about hiding the type will be immediately followed by an error
393 // that only makes sense if the identifier was treated like a type.
394 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
395 Result.suppressDiagnostics();
399 // Look to see if we have a type anywhere in the list of results.
400 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
401 Res != ResEnd; ++Res) {
402 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
403 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
405 (*Res)->getLocation().getRawEncoding() <
406 IIDecl->getLocation().getRawEncoding())
412 // None of the entities we found is a type, so there is no way
413 // to even assume that the result is a type. In this case, don't
414 // complain about the ambiguity. The parser will either try to
415 // perform this lookup again (e.g., as an object name), which
416 // will produce the ambiguity, or will complain that it expected
418 Result.suppressDiagnostics();
422 // We found a type within the ambiguous lookup; diagnose the
423 // ambiguity and then return that type. This might be the right
424 // answer, or it might not be, but it suppresses any attempt to
425 // perform the name lookup again.
428 case LookupResult::Found:
429 IIDecl = Result.getFoundDecl();
433 assert(IIDecl && "Didn't find decl");
436 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
437 // C++ [class.qual]p2: A lookup that would find the injected-class-name
438 // instead names the constructors of the class, except when naming a class.
439 // This is ill-formed when we're not actually forming a ctor or dtor name.
440 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
441 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
442 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
443 FoundRD->isInjectedClassName() &&
444 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
445 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
448 DiagnoseUseOfDecl(IIDecl, NameLoc);
450 T = Context.getTypeDeclType(TD);
451 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
452 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
453 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
455 T = Context.getObjCInterfaceType(IDecl);
456 } else if (AllowDeducedTemplate) {
457 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
458 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
463 // If it's not plausibly a type, suppress diagnostics.
464 Result.suppressDiagnostics();
468 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
469 // constructor or destructor name (in such a case, the scope specifier
470 // will be attached to the enclosing Expr or Decl node).
471 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
472 !isa<ObjCInterfaceDecl>(IIDecl)) {
473 if (WantNontrivialTypeSourceInfo) {
474 // Construct a type with type-source information.
475 TypeLocBuilder Builder;
476 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
478 T = getElaboratedType(ETK_None, *SS, T);
479 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
480 ElabTL.setElaboratedKeywordLoc(SourceLocation());
481 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
482 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
484 T = getElaboratedType(ETK_None, *SS, T);
488 return ParsedType::make(T);
491 // Builds a fake NNS for the given decl context.
492 static NestedNameSpecifier *
493 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
494 for (;; DC = DC->getLookupParent()) {
495 DC = DC->getPrimaryContext();
496 auto *ND = dyn_cast<NamespaceDecl>(DC);
497 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
498 return NestedNameSpecifier::Create(Context, nullptr, ND);
499 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
500 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
501 RD->getTypeForDecl());
502 else if (isa<TranslationUnitDecl>(DC))
503 return NestedNameSpecifier::GlobalSpecifier(Context);
505 llvm_unreachable("something isn't in TU scope?");
508 /// Find the parent class with dependent bases of the innermost enclosing method
509 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
510 /// up allowing unqualified dependent type names at class-level, which MSVC
511 /// correctly rejects.
512 static const CXXRecordDecl *
513 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
514 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
515 DC = DC->getPrimaryContext();
516 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
517 if (MD->getParent()->hasAnyDependentBases())
518 return MD->getParent();
523 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
524 SourceLocation NameLoc,
525 bool IsTemplateTypeArg) {
526 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
528 NestedNameSpecifier *NNS = nullptr;
529 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
530 // If we weren't able to parse a default template argument, delay lookup
531 // until instantiation time by making a non-dependent DependentTypeName. We
532 // pretend we saw a NestedNameSpecifier referring to the current scope, and
533 // lookup is retried.
534 // FIXME: This hurts our diagnostic quality, since we get errors like "no
535 // type named 'Foo' in 'current_namespace'" when the user didn't write any
537 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
538 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
539 } else if (const CXXRecordDecl *RD =
540 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
541 // Build a DependentNameType that will perform lookup into RD at
542 // instantiation time.
543 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
544 RD->getTypeForDecl());
546 // Diagnose that this identifier was undeclared, and retry the lookup during
547 // template instantiation.
548 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
551 // This is not a situation that we should recover from.
555 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
557 // Build type location information. We synthesized the qualifier, so we have
558 // to build a fake NestedNameSpecifierLoc.
559 NestedNameSpecifierLocBuilder NNSLocBuilder;
560 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
561 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
563 TypeLocBuilder Builder;
564 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
565 DepTL.setNameLoc(NameLoc);
566 DepTL.setElaboratedKeywordLoc(SourceLocation());
567 DepTL.setQualifierLoc(QualifierLoc);
568 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
571 /// isTagName() - This method is called *for error recovery purposes only*
572 /// to determine if the specified name is a valid tag name ("struct foo"). If
573 /// so, this returns the TST for the tag corresponding to it (TST_enum,
574 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
575 /// cases in C where the user forgot to specify the tag.
576 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
577 // Do a tag name lookup in this scope.
578 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
579 LookupName(R, S, false);
580 R.suppressDiagnostics();
581 if (R.getResultKind() == LookupResult::Found)
582 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
583 switch (TD->getTagKind()) {
584 case TTK_Struct: return DeclSpec::TST_struct;
585 case TTK_Interface: return DeclSpec::TST_interface;
586 case TTK_Union: return DeclSpec::TST_union;
587 case TTK_Class: return DeclSpec::TST_class;
588 case TTK_Enum: return DeclSpec::TST_enum;
592 return DeclSpec::TST_unspecified;
595 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
596 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
597 /// then downgrade the missing typename error to a warning.
598 /// This is needed for MSVC compatibility; Example:
600 /// template<class T> class A {
602 /// typedef int TYPE;
604 /// template<class T> class B : public A<T> {
606 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
609 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
610 if (CurContext->isRecord()) {
611 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
614 const Type *Ty = SS->getScopeRep()->getAsType();
616 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
617 for (const auto &Base : RD->bases())
618 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
620 return S->isFunctionPrototypeScope();
622 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
625 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
626 SourceLocation IILoc,
629 ParsedType &SuggestedType,
630 bool AllowClassTemplates) {
631 // We don't have anything to suggest (yet).
632 SuggestedType = nullptr;
634 // There may have been a typo in the name of the type. Look up typo
635 // results, in case we have something that we can suggest.
636 if (TypoCorrection Corrected =
637 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
638 llvm::make_unique<TypeNameValidatorCCC>(
639 false, false, AllowClassTemplates),
640 CTK_ErrorRecovery)) {
641 if (Corrected.isKeyword()) {
642 // We corrected to a keyword.
643 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
644 II = Corrected.getCorrectionAsIdentifierInfo();
646 // We found a similarly-named type or interface; suggest that.
647 if (!SS || !SS->isSet()) {
648 diagnoseTypo(Corrected,
649 PDiag(diag::err_unknown_typename_suggest) << II);
650 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
651 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
652 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
653 II->getName().equals(CorrectedStr);
654 diagnoseTypo(Corrected,
655 PDiag(diag::err_unknown_nested_typename_suggest)
656 << II << DC << DroppedSpecifier << SS->getRange());
658 llvm_unreachable("could not have corrected a typo here");
662 if (Corrected.getCorrectionSpecifier())
663 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
665 // FIXME: Support class template argument deduction here.
667 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
668 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
669 /*IsCtorOrDtorName=*/false,
670 /*NonTrivialTypeSourceInfo=*/true);
675 if (getLangOpts().CPlusPlus) {
676 // See if II is a class template that the user forgot to pass arguments to.
678 Name.setIdentifier(II, IILoc);
679 CXXScopeSpec EmptySS;
680 TemplateTy TemplateResult;
681 bool MemberOfUnknownSpecialization;
682 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
683 Name, nullptr, true, TemplateResult,
684 MemberOfUnknownSpecialization) == TNK_Type_template) {
685 TemplateName TplName = TemplateResult.get();
686 Diag(IILoc, diag::err_template_missing_args)
687 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
688 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
689 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
690 << TplDecl->getTemplateParameters()->getSourceRange();
696 // FIXME: Should we move the logic that tries to recover from a missing tag
697 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
699 if (!SS || (!SS->isSet() && !SS->isInvalid()))
700 Diag(IILoc, diag::err_unknown_typename) << II;
701 else if (DeclContext *DC = computeDeclContext(*SS, false))
702 Diag(IILoc, diag::err_typename_nested_not_found)
703 << II << DC << SS->getRange();
704 else if (isDependentScopeSpecifier(*SS)) {
705 unsigned DiagID = diag::err_typename_missing;
706 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
707 DiagID = diag::ext_typename_missing;
709 Diag(SS->getRange().getBegin(), DiagID)
710 << SS->getScopeRep() << II->getName()
711 << SourceRange(SS->getRange().getBegin(), IILoc)
712 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
713 SuggestedType = ActOnTypenameType(S, SourceLocation(),
714 *SS, *II, IILoc).get();
716 assert(SS && SS->isInvalid() &&
717 "Invalid scope specifier has already been diagnosed");
721 /// \brief Determine whether the given result set contains either a type name
723 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
724 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
725 NextToken.is(tok::less);
727 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
728 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
731 if (CheckTemplate && isa<TemplateDecl>(*I))
738 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
739 Scope *S, CXXScopeSpec &SS,
740 IdentifierInfo *&Name,
741 SourceLocation NameLoc) {
742 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
743 SemaRef.LookupParsedName(R, S, &SS);
744 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
745 StringRef FixItTagName;
746 switch (Tag->getTagKind()) {
748 FixItTagName = "class ";
752 FixItTagName = "enum ";
756 FixItTagName = "struct ";
760 FixItTagName = "__interface ";
764 FixItTagName = "union ";
768 StringRef TagName = FixItTagName.drop_back();
769 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
770 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
771 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
773 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
775 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
778 // Replace lookup results with just the tag decl.
779 Result.clear(Sema::LookupTagName);
780 SemaRef.LookupParsedName(Result, S, &SS);
787 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
788 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
789 QualType T, SourceLocation NameLoc) {
790 ASTContext &Context = S.Context;
792 TypeLocBuilder Builder;
793 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
795 T = S.getElaboratedType(ETK_None, SS, T);
796 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
797 ElabTL.setElaboratedKeywordLoc(SourceLocation());
798 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
799 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
802 Sema::NameClassification
803 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
804 SourceLocation NameLoc, const Token &NextToken,
805 bool IsAddressOfOperand,
806 std::unique_ptr<CorrectionCandidateCallback> CCC) {
807 DeclarationNameInfo NameInfo(Name, NameLoc);
808 ObjCMethodDecl *CurMethod = getCurMethodDecl();
810 if (NextToken.is(tok::coloncolon)) {
811 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
812 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
813 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
814 isCurrentClassName(*Name, S, &SS)) {
815 // Per [class.qual]p2, this names the constructors of SS, not the
816 // injected-class-name. We don't have a classification for that.
817 // There's not much point caching this result, since the parser
818 // will reject it later.
819 return NameClassification::Unknown();
822 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
823 LookupParsedName(Result, S, &SS, !CurMethod);
825 // For unqualified lookup in a class template in MSVC mode, look into
826 // dependent base classes where the primary class template is known.
827 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
828 if (ParsedType TypeInBase =
829 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
833 // Perform lookup for Objective-C instance variables (including automatically
834 // synthesized instance variables), if we're in an Objective-C method.
835 // FIXME: This lookup really, really needs to be folded in to the normal
836 // unqualified lookup mechanism.
837 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
838 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
839 if (E.get() || E.isInvalid())
843 bool SecondTry = false;
844 bool IsFilteredTemplateName = false;
847 switch (Result.getResultKind()) {
848 case LookupResult::NotFound:
849 // If an unqualified-id is followed by a '(', then we have a function
851 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
852 // In C++, this is an ADL-only call.
854 if (getLangOpts().CPlusPlus)
855 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
858 // If the expression that precedes the parenthesized argument list in a
859 // function call consists solely of an identifier, and if no
860 // declaration is visible for this identifier, the identifier is
861 // implicitly declared exactly as if, in the innermost block containing
862 // the function call, the declaration
864 // extern int identifier ();
868 // We also allow this in C99 as an extension.
869 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
871 Result.resolveKind();
872 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
876 // In C, we first see whether there is a tag type by the same name, in
877 // which case it's likely that the user just forgot to write "enum",
878 // "struct", or "union".
879 if (!getLangOpts().CPlusPlus && !SecondTry &&
880 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
884 // Perform typo correction to determine if there is another name that is
885 // close to this name.
886 if (!SecondTry && CCC) {
888 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
889 Result.getLookupKind(), S,
891 CTK_ErrorRecovery)) {
892 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
893 unsigned QualifiedDiag = diag::err_no_member_suggest;
895 NamedDecl *FirstDecl = Corrected.getFoundDecl();
896 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
897 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
898 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
899 UnqualifiedDiag = diag::err_no_template_suggest;
900 QualifiedDiag = diag::err_no_member_template_suggest;
901 } else if (UnderlyingFirstDecl &&
902 (isa<TypeDecl>(UnderlyingFirstDecl) ||
903 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
904 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
905 UnqualifiedDiag = diag::err_unknown_typename_suggest;
906 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
910 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
911 } else {// FIXME: is this even reachable? Test it.
912 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
913 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
914 Name->getName().equals(CorrectedStr);
915 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
916 << Name << computeDeclContext(SS, false)
917 << DroppedSpecifier << SS.getRange());
920 // Update the name, so that the caller has the new name.
921 Name = Corrected.getCorrectionAsIdentifierInfo();
923 // Typo correction corrected to a keyword.
924 if (Corrected.isKeyword())
927 // Also update the LookupResult...
928 // FIXME: This should probably go away at some point
930 Result.setLookupName(Corrected.getCorrection());
932 Result.addDecl(FirstDecl);
934 // If we found an Objective-C instance variable, let
935 // LookupInObjCMethod build the appropriate expression to
936 // reference the ivar.
937 // FIXME: This is a gross hack.
938 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
940 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
948 // We failed to correct; just fall through and let the parser deal with it.
949 Result.suppressDiagnostics();
950 return NameClassification::Unknown();
952 case LookupResult::NotFoundInCurrentInstantiation: {
953 // We performed name lookup into the current instantiation, and there were
954 // dependent bases, so we treat this result the same way as any other
955 // dependent nested-name-specifier.
958 // A name used in a template declaration or definition and that is
959 // dependent on a template-parameter is assumed not to name a type
960 // unless the applicable name lookup finds a type name or the name is
961 // qualified by the keyword typename.
963 // FIXME: If the next token is '<', we might want to ask the parser to
964 // perform some heroics to see if we actually have a
965 // template-argument-list, which would indicate a missing 'template'
967 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
968 NameInfo, IsAddressOfOperand,
969 /*TemplateArgs=*/nullptr);
972 case LookupResult::Found:
973 case LookupResult::FoundOverloaded:
974 case LookupResult::FoundUnresolvedValue:
977 case LookupResult::Ambiguous:
978 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
979 hasAnyAcceptableTemplateNames(Result)) {
980 // C++ [temp.local]p3:
981 // A lookup that finds an injected-class-name (10.2) can result in an
982 // ambiguity in certain cases (for example, if it is found in more than
983 // one base class). If all of the injected-class-names that are found
984 // refer to specializations of the same class template, and if the name
985 // is followed by a template-argument-list, the reference refers to the
986 // class template itself and not a specialization thereof, and is not
989 // This filtering can make an ambiguous result into an unambiguous one,
990 // so try again after filtering out template names.
991 FilterAcceptableTemplateNames(Result);
992 if (!Result.isAmbiguous()) {
993 IsFilteredTemplateName = true;
998 // Diagnose the ambiguity and return an error.
999 return NameClassification::Error();
1002 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1003 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1004 // C++ [temp.names]p3:
1005 // After name lookup (3.4) finds that a name is a template-name or that
1006 // an operator-function-id or a literal- operator-id refers to a set of
1007 // overloaded functions any member of which is a function template if
1008 // this is followed by a <, the < is always taken as the delimiter of a
1009 // template-argument-list and never as the less-than operator.
1010 if (!IsFilteredTemplateName)
1011 FilterAcceptableTemplateNames(Result);
1013 if (!Result.empty()) {
1014 bool IsFunctionTemplate;
1016 TemplateName Template;
1017 if (Result.end() - Result.begin() > 1) {
1018 IsFunctionTemplate = true;
1019 Template = Context.getOverloadedTemplateName(Result.begin(),
1023 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1024 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1025 IsVarTemplate = isa<VarTemplateDecl>(TD);
1027 if (SS.isSet() && !SS.isInvalid())
1028 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1029 /*TemplateKeyword=*/false,
1032 Template = TemplateName(TD);
1035 if (IsFunctionTemplate) {
1036 // Function templates always go through overload resolution, at which
1037 // point we'll perform the various checks (e.g., accessibility) we need
1038 // to based on which function we selected.
1039 Result.suppressDiagnostics();
1041 return NameClassification::FunctionTemplate(Template);
1044 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1045 : NameClassification::TypeTemplate(Template);
1049 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1050 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1051 DiagnoseUseOfDecl(Type, NameLoc);
1052 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1053 QualType T = Context.getTypeDeclType(Type);
1054 if (SS.isNotEmpty())
1055 return buildNestedType(*this, SS, T, NameLoc);
1056 return ParsedType::make(T);
1059 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1061 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1062 if (ObjCCompatibleAliasDecl *Alias =
1063 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1064 Class = Alias->getClassInterface();
1068 DiagnoseUseOfDecl(Class, NameLoc);
1070 if (NextToken.is(tok::period)) {
1071 // Interface. <something> is parsed as a property reference expression.
1072 // Just return "unknown" as a fall-through for now.
1073 Result.suppressDiagnostics();
1074 return NameClassification::Unknown();
1077 QualType T = Context.getObjCInterfaceType(Class);
1078 return ParsedType::make(T);
1081 // We can have a type template here if we're classifying a template argument.
1082 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1083 !isa<VarTemplateDecl>(FirstDecl))
1084 return NameClassification::TypeTemplate(
1085 TemplateName(cast<TemplateDecl>(FirstDecl)));
1087 // Check for a tag type hidden by a non-type decl in a few cases where it
1088 // seems likely a type is wanted instead of the non-type that was found.
1089 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1090 if ((NextToken.is(tok::identifier) ||
1092 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1093 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1094 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1095 DiagnoseUseOfDecl(Type, NameLoc);
1096 QualType T = Context.getTypeDeclType(Type);
1097 if (SS.isNotEmpty())
1098 return buildNestedType(*this, SS, T, NameLoc);
1099 return ParsedType::make(T);
1102 if (FirstDecl->isCXXClassMember())
1103 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1106 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1107 return BuildDeclarationNameExpr(SS, Result, ADL);
1110 Sema::TemplateNameKindForDiagnostics
1111 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1112 auto *TD = Name.getAsTemplateDecl();
1114 return TemplateNameKindForDiagnostics::DependentTemplate;
1115 if (isa<ClassTemplateDecl>(TD))
1116 return TemplateNameKindForDiagnostics::ClassTemplate;
1117 if (isa<FunctionTemplateDecl>(TD))
1118 return TemplateNameKindForDiagnostics::FunctionTemplate;
1119 if (isa<VarTemplateDecl>(TD))
1120 return TemplateNameKindForDiagnostics::VarTemplate;
1121 if (isa<TypeAliasTemplateDecl>(TD))
1122 return TemplateNameKindForDiagnostics::AliasTemplate;
1123 if (isa<TemplateTemplateParmDecl>(TD))
1124 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1125 return TemplateNameKindForDiagnostics::DependentTemplate;
1128 // Determines the context to return to after temporarily entering a
1129 // context. This depends in an unnecessarily complicated way on the
1130 // exact ordering of callbacks from the parser.
1131 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1133 // Functions defined inline within classes aren't parsed until we've
1134 // finished parsing the top-level class, so the top-level class is
1135 // the context we'll need to return to.
1136 // A Lambda call operator whose parent is a class must not be treated
1137 // as an inline member function. A Lambda can be used legally
1138 // either as an in-class member initializer or a default argument. These
1139 // are parsed once the class has been marked complete and so the containing
1140 // context would be the nested class (when the lambda is defined in one);
1141 // If the class is not complete, then the lambda is being used in an
1142 // ill-formed fashion (such as to specify the width of a bit-field, or
1143 // in an array-bound) - in which case we still want to return the
1144 // lexically containing DC (which could be a nested class).
1145 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1146 DC = DC->getLexicalParent();
1148 // A function not defined within a class will always return to its
1150 if (!isa<CXXRecordDecl>(DC))
1153 // A C++ inline method/friend is parsed *after* the topmost class
1154 // it was declared in is fully parsed ("complete"); the topmost
1155 // class is the context we need to return to.
1156 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1159 // Return the declaration context of the topmost class the inline method is
1164 return DC->getLexicalParent();
1167 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1168 assert(getContainingDC(DC) == CurContext &&
1169 "The next DeclContext should be lexically contained in the current one.");
1174 void Sema::PopDeclContext() {
1175 assert(CurContext && "DeclContext imbalance!");
1177 CurContext = getContainingDC(CurContext);
1178 assert(CurContext && "Popped translation unit!");
1181 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1183 // Unlike PushDeclContext, the context to which we return is not necessarily
1184 // the containing DC of TD, because the new context will be some pre-existing
1185 // TagDecl definition instead of a fresh one.
1186 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1187 CurContext = cast<TagDecl>(D)->getDefinition();
1188 assert(CurContext && "skipping definition of undefined tag");
1189 // Start lookups from the parent of the current context; we don't want to look
1190 // into the pre-existing complete definition.
1191 S->setEntity(CurContext->getLookupParent());
1195 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1196 CurContext = static_cast<decltype(CurContext)>(Context);
1199 /// EnterDeclaratorContext - Used when we must lookup names in the context
1200 /// of a declarator's nested name specifier.
1202 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1203 // C++0x [basic.lookup.unqual]p13:
1204 // A name used in the definition of a static data member of class
1205 // X (after the qualified-id of the static member) is looked up as
1206 // if the name was used in a member function of X.
1207 // C++0x [basic.lookup.unqual]p14:
1208 // If a variable member of a namespace is defined outside of the
1209 // scope of its namespace then any name used in the definition of
1210 // the variable member (after the declarator-id) is looked up as
1211 // if the definition of the variable member occurred in its
1213 // Both of these imply that we should push a scope whose context
1214 // is the semantic context of the declaration. We can't use
1215 // PushDeclContext here because that context is not necessarily
1216 // lexically contained in the current context. Fortunately,
1217 // the containing scope should have the appropriate information.
1219 assert(!S->getEntity() && "scope already has entity");
1222 Scope *Ancestor = S->getParent();
1223 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1224 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1231 void Sema::ExitDeclaratorContext(Scope *S) {
1232 assert(S->getEntity() == CurContext && "Context imbalance!");
1234 // Switch back to the lexical context. The safety of this is
1235 // enforced by an assert in EnterDeclaratorContext.
1236 Scope *Ancestor = S->getParent();
1237 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1238 CurContext = Ancestor->getEntity();
1240 // We don't need to do anything with the scope, which is going to
1244 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1245 // We assume that the caller has already called
1246 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1247 FunctionDecl *FD = D->getAsFunction();
1251 // Same implementation as PushDeclContext, but enters the context
1252 // from the lexical parent, rather than the top-level class.
1253 assert(CurContext == FD->getLexicalParent() &&
1254 "The next DeclContext should be lexically contained in the current one.");
1256 S->setEntity(CurContext);
1258 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1259 ParmVarDecl *Param = FD->getParamDecl(P);
1260 // If the parameter has an identifier, then add it to the scope
1261 if (Param->getIdentifier()) {
1263 IdResolver.AddDecl(Param);
1268 void Sema::ActOnExitFunctionContext() {
1269 // Same implementation as PopDeclContext, but returns to the lexical parent,
1270 // rather than the top-level class.
1271 assert(CurContext && "DeclContext imbalance!");
1272 CurContext = CurContext->getLexicalParent();
1273 assert(CurContext && "Popped translation unit!");
1276 /// \brief Determine whether we allow overloading of the function
1277 /// PrevDecl with another declaration.
1279 /// This routine determines whether overloading is possible, not
1280 /// whether some new function is actually an overload. It will return
1281 /// true in C++ (where we can always provide overloads) or, as an
1282 /// extension, in C when the previous function is already an
1283 /// overloaded function declaration or has the "overloadable"
1285 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1286 ASTContext &Context) {
1287 if (Context.getLangOpts().CPlusPlus)
1290 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1293 return (Previous.getResultKind() == LookupResult::Found
1294 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1297 /// Add this decl to the scope shadowed decl chains.
1298 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1299 // Move up the scope chain until we find the nearest enclosing
1300 // non-transparent context. The declaration will be introduced into this
1302 while (S->getEntity() && S->getEntity()->isTransparentContext())
1305 // Add scoped declarations into their context, so that they can be
1306 // found later. Declarations without a context won't be inserted
1307 // into any context.
1309 CurContext->addDecl(D);
1311 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1312 // are function-local declarations.
1313 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1314 !D->getDeclContext()->getRedeclContext()->Equals(
1315 D->getLexicalDeclContext()->getRedeclContext()) &&
1316 !D->getLexicalDeclContext()->isFunctionOrMethod())
1319 // Template instantiations should also not be pushed into scope.
1320 if (isa<FunctionDecl>(D) &&
1321 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1324 // If this replaces anything in the current scope,
1325 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1326 IEnd = IdResolver.end();
1327 for (; I != IEnd; ++I) {
1328 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1330 IdResolver.RemoveDecl(*I);
1332 // Should only need to replace one decl.
1339 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1340 // Implicitly-generated labels may end up getting generated in an order that
1341 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1342 // the label at the appropriate place in the identifier chain.
1343 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1344 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1345 if (IDC == CurContext) {
1346 if (!S->isDeclScope(*I))
1348 } else if (IDC->Encloses(CurContext))
1352 IdResolver.InsertDeclAfter(I, D);
1354 IdResolver.AddDecl(D);
1358 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1359 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1360 TUScope->AddDecl(D);
1363 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1364 bool AllowInlineNamespace) {
1365 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1368 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1369 DeclContext *TargetDC = DC->getPrimaryContext();
1371 if (DeclContext *ScopeDC = S->getEntity())
1372 if (ScopeDC->getPrimaryContext() == TargetDC)
1374 } while ((S = S->getParent()));
1379 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1383 /// Filters out lookup results that don't fall within the given scope
1384 /// as determined by isDeclInScope.
1385 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1386 bool ConsiderLinkage,
1387 bool AllowInlineNamespace) {
1388 LookupResult::Filter F = R.makeFilter();
1389 while (F.hasNext()) {
1390 NamedDecl *D = F.next();
1392 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1395 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1404 static bool isUsingDecl(NamedDecl *D) {
1405 return isa<UsingShadowDecl>(D) ||
1406 isa<UnresolvedUsingTypenameDecl>(D) ||
1407 isa<UnresolvedUsingValueDecl>(D);
1410 /// Removes using shadow declarations from the lookup results.
1411 static void RemoveUsingDecls(LookupResult &R) {
1412 LookupResult::Filter F = R.makeFilter();
1414 if (isUsingDecl(F.next()))
1420 /// \brief Check for this common pattern:
1423 /// S(const S&); // DO NOT IMPLEMENT
1424 /// void operator=(const S&); // DO NOT IMPLEMENT
1427 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1428 // FIXME: Should check for private access too but access is set after we get
1430 if (D->doesThisDeclarationHaveABody())
1433 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1434 return CD->isCopyConstructor();
1435 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1436 return Method->isCopyAssignmentOperator();
1440 // We need this to handle
1443 // void *foo() { return 0; }
1446 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1447 // for example. If 'A', foo will have external linkage. If we have '*A',
1448 // foo will have no linkage. Since we can't know until we get to the end
1449 // of the typedef, this function finds out if D might have non-external linkage.
1450 // Callers should verify at the end of the TU if it D has external linkage or
1452 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1453 const DeclContext *DC = D->getDeclContext();
1454 while (!DC->isTranslationUnit()) {
1455 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1456 if (!RD->hasNameForLinkage())
1459 DC = DC->getParent();
1462 return !D->isExternallyVisible();
1465 // FIXME: This needs to be refactored; some other isInMainFile users want
1467 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1468 if (S.TUKind != TU_Complete)
1470 return S.SourceMgr.isInMainFile(Loc);
1473 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1476 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1479 // Ignore all entities declared within templates, and out-of-line definitions
1480 // of members of class templates.
1481 if (D->getDeclContext()->isDependentContext() ||
1482 D->getLexicalDeclContext()->isDependentContext())
1485 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1486 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1489 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1490 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1493 // 'static inline' functions are defined in headers; don't warn.
1494 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1498 if (FD->doesThisDeclarationHaveABody() &&
1499 Context.DeclMustBeEmitted(FD))
1501 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1502 // Constants and utility variables are defined in headers with internal
1503 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1505 if (!isMainFileLoc(*this, VD->getLocation()))
1508 if (Context.DeclMustBeEmitted(VD))
1511 if (VD->isStaticDataMember() &&
1512 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1515 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1521 // Only warn for unused decls internal to the translation unit.
1522 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1523 // for inline functions defined in the main source file, for instance.
1524 return mightHaveNonExternalLinkage(D);
1527 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1531 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1532 const FunctionDecl *First = FD->getFirstDecl();
1533 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1534 return; // First should already be in the vector.
1537 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1538 const VarDecl *First = VD->getFirstDecl();
1539 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1540 return; // First should already be in the vector.
1543 if (ShouldWarnIfUnusedFileScopedDecl(D))
1544 UnusedFileScopedDecls.push_back(D);
1547 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1548 if (D->isInvalidDecl())
1551 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1552 D->hasAttr<ObjCPreciseLifetimeAttr>())
1555 if (isa<LabelDecl>(D))
1558 // Except for labels, we only care about unused decls that are local to
1560 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1561 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1562 // For dependent types, the diagnostic is deferred.
1564 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1565 if (!WithinFunction)
1568 if (isa<TypedefNameDecl>(D))
1571 // White-list anything that isn't a local variable.
1572 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1575 // Types of valid local variables should be complete, so this should succeed.
1576 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1578 // White-list anything with an __attribute__((unused)) type.
1579 const auto *Ty = VD->getType().getTypePtr();
1581 // Only look at the outermost level of typedef.
1582 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1583 if (TT->getDecl()->hasAttr<UnusedAttr>())
1587 // If we failed to complete the type for some reason, or if the type is
1588 // dependent, don't diagnose the variable.
1589 if (Ty->isIncompleteType() || Ty->isDependentType())
1592 // Look at the element type to ensure that the warning behaviour is
1593 // consistent for both scalars and arrays.
1594 Ty = Ty->getBaseElementTypeUnsafe();
1596 if (const TagType *TT = Ty->getAs<TagType>()) {
1597 const TagDecl *Tag = TT->getDecl();
1598 if (Tag->hasAttr<UnusedAttr>())
1601 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1602 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1605 if (const Expr *Init = VD->getInit()) {
1606 if (const ExprWithCleanups *Cleanups =
1607 dyn_cast<ExprWithCleanups>(Init))
1608 Init = Cleanups->getSubExpr();
1609 const CXXConstructExpr *Construct =
1610 dyn_cast<CXXConstructExpr>(Init);
1611 if (Construct && !Construct->isElidable()) {
1612 CXXConstructorDecl *CD = Construct->getConstructor();
1613 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1620 // TODO: __attribute__((unused)) templates?
1626 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1628 if (isa<LabelDecl>(D)) {
1629 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1630 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1631 if (AfterColon.isInvalid())
1633 Hint = FixItHint::CreateRemoval(CharSourceRange::
1634 getCharRange(D->getLocStart(), AfterColon));
1638 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1639 if (D->getTypeForDecl()->isDependentType())
1642 for (auto *TmpD : D->decls()) {
1643 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1644 DiagnoseUnusedDecl(T);
1645 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1646 DiagnoseUnusedNestedTypedefs(R);
1650 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1651 /// unless they are marked attr(unused).
1652 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1653 if (!ShouldDiagnoseUnusedDecl(D))
1656 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1657 // typedefs can be referenced later on, so the diagnostics are emitted
1658 // at end-of-translation-unit.
1659 UnusedLocalTypedefNameCandidates.insert(TD);
1664 GenerateFixForUnusedDecl(D, Context, Hint);
1667 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1668 DiagID = diag::warn_unused_exception_param;
1669 else if (isa<LabelDecl>(D))
1670 DiagID = diag::warn_unused_label;
1672 DiagID = diag::warn_unused_variable;
1674 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1677 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1678 // Verify that we have no forward references left. If so, there was a goto
1679 // or address of a label taken, but no definition of it. Label fwd
1680 // definitions are indicated with a null substmt which is also not a resolved
1681 // MS inline assembly label name.
1682 bool Diagnose = false;
1683 if (L->isMSAsmLabel())
1684 Diagnose = !L->isResolvedMSAsmLabel();
1686 Diagnose = L->getStmt() == nullptr;
1688 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1691 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1692 S->mergeNRVOIntoParent();
1694 if (S->decl_empty()) return;
1695 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1696 "Scope shouldn't contain decls!");
1698 for (auto *TmpD : S->decls()) {
1699 assert(TmpD && "This decl didn't get pushed??");
1701 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1702 NamedDecl *D = cast<NamedDecl>(TmpD);
1704 if (!D->getDeclName()) continue;
1706 // Diagnose unused variables in this scope.
1707 if (!S->hasUnrecoverableErrorOccurred()) {
1708 DiagnoseUnusedDecl(D);
1709 if (const auto *RD = dyn_cast<RecordDecl>(D))
1710 DiagnoseUnusedNestedTypedefs(RD);
1713 // If this was a forward reference to a label, verify it was defined.
1714 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1715 CheckPoppedLabel(LD, *this);
1717 // Remove this name from our lexical scope, and warn on it if we haven't
1719 IdResolver.RemoveDecl(D);
1720 auto ShadowI = ShadowingDecls.find(D);
1721 if (ShadowI != ShadowingDecls.end()) {
1722 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1723 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1724 << D << FD << FD->getParent();
1725 Diag(FD->getLocation(), diag::note_previous_declaration);
1727 ShadowingDecls.erase(ShadowI);
1732 /// \brief Look for an Objective-C class in the translation unit.
1734 /// \param Id The name of the Objective-C class we're looking for. If
1735 /// typo-correction fixes this name, the Id will be updated
1736 /// to the fixed name.
1738 /// \param IdLoc The location of the name in the translation unit.
1740 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1741 /// if there is no class with the given name.
1743 /// \returns The declaration of the named Objective-C class, or NULL if the
1744 /// class could not be found.
1745 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1746 SourceLocation IdLoc,
1747 bool DoTypoCorrection) {
1748 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1749 // creation from this context.
1750 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1752 if (!IDecl && DoTypoCorrection) {
1753 // Perform typo correction at the given location, but only if we
1754 // find an Objective-C class name.
1755 if (TypoCorrection C = CorrectTypo(
1756 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1757 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1758 CTK_ErrorRecovery)) {
1759 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1760 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1761 Id = IDecl->getIdentifier();
1764 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1765 // This routine must always return a class definition, if any.
1766 if (Def && Def->getDefinition())
1767 Def = Def->getDefinition();
1771 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1772 /// from S, where a non-field would be declared. This routine copes
1773 /// with the difference between C and C++ scoping rules in structs and
1774 /// unions. For example, the following code is well-formed in C but
1775 /// ill-formed in C++:
1781 /// void test_S6() {
1786 /// For the declaration of BAR, this routine will return a different
1787 /// scope. The scope S will be the scope of the unnamed enumeration
1788 /// within S6. In C++, this routine will return the scope associated
1789 /// with S6, because the enumeration's scope is a transparent
1790 /// context but structures can contain non-field names. In C, this
1791 /// routine will return the translation unit scope, since the
1792 /// enumeration's scope is a transparent context and structures cannot
1793 /// contain non-field names.
1794 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1795 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1796 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1797 (S->isClassScope() && !getLangOpts().CPlusPlus))
1802 /// \brief Looks up the declaration of "struct objc_super" and
1803 /// saves it for later use in building builtin declaration of
1804 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1805 /// pre-existing declaration exists no action takes place.
1806 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1807 IdentifierInfo *II) {
1808 if (!II->isStr("objc_msgSendSuper"))
1810 ASTContext &Context = ThisSema.Context;
1812 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1813 SourceLocation(), Sema::LookupTagName);
1814 ThisSema.LookupName(Result, S);
1815 if (Result.getResultKind() == LookupResult::Found)
1816 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1817 Context.setObjCSuperType(Context.getTagDeclType(TD));
1820 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1822 case ASTContext::GE_None:
1824 case ASTContext::GE_Missing_stdio:
1826 case ASTContext::GE_Missing_setjmp:
1828 case ASTContext::GE_Missing_ucontext:
1829 return "ucontext.h";
1831 llvm_unreachable("unhandled error kind");
1834 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1835 /// file scope. lazily create a decl for it. ForRedeclaration is true
1836 /// if we're creating this built-in in anticipation of redeclaring the
1838 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1839 Scope *S, bool ForRedeclaration,
1840 SourceLocation Loc) {
1841 LookupPredefedObjCSuperType(*this, S, II);
1843 ASTContext::GetBuiltinTypeError Error;
1844 QualType R = Context.GetBuiltinType(ID, Error);
1846 if (ForRedeclaration)
1847 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1848 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1852 if (!ForRedeclaration &&
1853 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1854 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1855 Diag(Loc, diag::ext_implicit_lib_function_decl)
1856 << Context.BuiltinInfo.getName(ID) << R;
1857 if (Context.BuiltinInfo.getHeaderName(ID) &&
1858 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1859 Diag(Loc, diag::note_include_header_or_declare)
1860 << Context.BuiltinInfo.getHeaderName(ID)
1861 << Context.BuiltinInfo.getName(ID);
1867 DeclContext *Parent = Context.getTranslationUnitDecl();
1868 if (getLangOpts().CPlusPlus) {
1869 LinkageSpecDecl *CLinkageDecl =
1870 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1871 LinkageSpecDecl::lang_c, false);
1872 CLinkageDecl->setImplicit();
1873 Parent->addDecl(CLinkageDecl);
1874 Parent = CLinkageDecl;
1877 FunctionDecl *New = FunctionDecl::Create(Context,
1879 Loc, Loc, II, R, /*TInfo=*/nullptr,
1882 R->isFunctionProtoType());
1885 // Create Decl objects for each parameter, adding them to the
1887 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1888 SmallVector<ParmVarDecl*, 16> Params;
1889 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1891 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1892 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1894 parm->setScopeInfo(0, i);
1895 Params.push_back(parm);
1897 New->setParams(Params);
1900 AddKnownFunctionAttributes(New);
1901 RegisterLocallyScopedExternCDecl(New, S);
1903 // TUScope is the translation-unit scope to insert this function into.
1904 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1905 // relate Scopes to DeclContexts, and probably eliminate CurContext
1906 // entirely, but we're not there yet.
1907 DeclContext *SavedContext = CurContext;
1908 CurContext = Parent;
1909 PushOnScopeChains(New, TUScope);
1910 CurContext = SavedContext;
1914 /// Typedef declarations don't have linkage, but they still denote the same
1915 /// entity if their types are the same.
1916 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1918 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1919 TypedefNameDecl *Decl,
1920 LookupResult &Previous) {
1921 // This is only interesting when modules are enabled.
1922 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1925 // Empty sets are uninteresting.
1926 if (Previous.empty())
1929 LookupResult::Filter Filter = Previous.makeFilter();
1930 while (Filter.hasNext()) {
1931 NamedDecl *Old = Filter.next();
1933 // Non-hidden declarations are never ignored.
1934 if (S.isVisible(Old))
1937 // Declarations of the same entity are not ignored, even if they have
1938 // different linkages.
1939 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1940 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1941 Decl->getUnderlyingType()))
1944 // If both declarations give a tag declaration a typedef name for linkage
1945 // purposes, then they declare the same entity.
1946 if (S.getLangOpts().CPlusPlus &&
1947 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1948 Decl->getAnonDeclWithTypedefName())
1958 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1960 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1961 OldType = OldTypedef->getUnderlyingType();
1963 OldType = Context.getTypeDeclType(Old);
1964 QualType NewType = New->getUnderlyingType();
1966 if (NewType->isVariablyModifiedType()) {
1967 // Must not redefine a typedef with a variably-modified type.
1968 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1969 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1971 if (Old->getLocation().isValid())
1972 Diag(Old->getLocation(), diag::note_previous_definition);
1973 New->setInvalidDecl();
1977 if (OldType != NewType &&
1978 !OldType->isDependentType() &&
1979 !NewType->isDependentType() &&
1980 !Context.hasSameType(OldType, NewType)) {
1981 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1982 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1983 << Kind << NewType << OldType;
1984 if (Old->getLocation().isValid())
1985 Diag(Old->getLocation(), diag::note_previous_definition);
1986 New->setInvalidDecl();
1992 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1993 /// same name and scope as a previous declaration 'Old'. Figure out
1994 /// how to resolve this situation, merging decls or emitting
1995 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1997 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1998 LookupResult &OldDecls) {
1999 // If the new decl is known invalid already, don't bother doing any
2001 if (New->isInvalidDecl()) return;
2003 // Allow multiple definitions for ObjC built-in typedefs.
2004 // FIXME: Verify the underlying types are equivalent!
2005 if (getLangOpts().ObjC1) {
2006 const IdentifierInfo *TypeID = New->getIdentifier();
2007 switch (TypeID->getLength()) {
2011 if (!TypeID->isStr("id"))
2013 QualType T = New->getUnderlyingType();
2014 if (!T->isPointerType())
2016 if (!T->isVoidPointerType()) {
2017 QualType PT = T->getAs<PointerType>()->getPointeeType();
2018 if (!PT->isStructureType())
2021 Context.setObjCIdRedefinitionType(T);
2022 // Install the built-in type for 'id', ignoring the current definition.
2023 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2027 if (!TypeID->isStr("Class"))
2029 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2030 // Install the built-in type for 'Class', ignoring the current definition.
2031 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2034 if (!TypeID->isStr("SEL"))
2036 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2037 // Install the built-in type for 'SEL', ignoring the current definition.
2038 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2041 // Fall through - the typedef name was not a builtin type.
2044 // Verify the old decl was also a type.
2045 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2047 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2048 << New->getDeclName();
2050 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2051 if (OldD->getLocation().isValid())
2052 Diag(OldD->getLocation(), diag::note_previous_definition);
2054 return New->setInvalidDecl();
2057 // If the old declaration is invalid, just give up here.
2058 if (Old->isInvalidDecl())
2059 return New->setInvalidDecl();
2061 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2062 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2063 auto *NewTag = New->getAnonDeclWithTypedefName();
2064 NamedDecl *Hidden = nullptr;
2065 if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2066 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2067 !hasVisibleDefinition(OldTag, &Hidden)) {
2068 // There is a definition of this tag, but it is not visible. Use it
2069 // instead of our tag.
2070 New->setTypeForDecl(OldTD->getTypeForDecl());
2071 if (OldTD->isModed())
2072 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2073 OldTD->getUnderlyingType());
2075 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2077 // Make the old tag definition visible.
2078 makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2080 // If this was an unscoped enumeration, yank all of its enumerators
2081 // out of the scope.
2082 if (isa<EnumDecl>(NewTag)) {
2083 Scope *EnumScope = getNonFieldDeclScope(S);
2084 for (auto *D : NewTag->decls()) {
2085 auto *ED = cast<EnumConstantDecl>(D);
2086 assert(EnumScope->isDeclScope(ED));
2087 EnumScope->RemoveDecl(ED);
2088 IdResolver.RemoveDecl(ED);
2089 ED->getLexicalDeclContext()->removeDecl(ED);
2095 // If the typedef types are not identical, reject them in all languages and
2096 // with any extensions enabled.
2097 if (isIncompatibleTypedef(Old, New))
2100 // The types match. Link up the redeclaration chain and merge attributes if
2101 // the old declaration was a typedef.
2102 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2103 New->setPreviousDecl(Typedef);
2104 mergeDeclAttributes(New, Old);
2107 if (getLangOpts().MicrosoftExt)
2110 if (getLangOpts().CPlusPlus) {
2111 // C++ [dcl.typedef]p2:
2112 // In a given non-class scope, a typedef specifier can be used to
2113 // redefine the name of any type declared in that scope to refer
2114 // to the type to which it already refers.
2115 if (!isa<CXXRecordDecl>(CurContext))
2118 // C++0x [dcl.typedef]p4:
2119 // In a given class scope, a typedef specifier can be used to redefine
2120 // any class-name declared in that scope that is not also a typedef-name
2121 // to refer to the type to which it already refers.
2123 // This wording came in via DR424, which was a correction to the
2124 // wording in DR56, which accidentally banned code like:
2127 // typedef struct A { } A;
2130 // in the C++03 standard. We implement the C++0x semantics, which
2131 // allow the above but disallow
2138 // since that was the intent of DR56.
2139 if (!isa<TypedefNameDecl>(Old))
2142 Diag(New->getLocation(), diag::err_redefinition)
2143 << New->getDeclName();
2144 Diag(Old->getLocation(), diag::note_previous_definition);
2145 return New->setInvalidDecl();
2148 // Modules always permit redefinition of typedefs, as does C11.
2149 if (getLangOpts().Modules || getLangOpts().C11)
2152 // If we have a redefinition of a typedef in C, emit a warning. This warning
2153 // is normally mapped to an error, but can be controlled with
2154 // -Wtypedef-redefinition. If either the original or the redefinition is
2155 // in a system header, don't emit this for compatibility with GCC.
2156 if (getDiagnostics().getSuppressSystemWarnings() &&
2157 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2158 (Old->isImplicit() ||
2159 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2160 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2163 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2164 << New->getDeclName();
2165 Diag(Old->getLocation(), diag::note_previous_definition);
2168 /// DeclhasAttr - returns true if decl Declaration already has the target
2170 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2171 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2172 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2173 for (const auto *i : D->attrs())
2174 if (i->getKind() == A->getKind()) {
2176 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2180 // FIXME: Don't hardcode this check
2181 if (OA && isa<OwnershipAttr>(i))
2182 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2189 static bool isAttributeTargetADefinition(Decl *D) {
2190 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2191 return VD->isThisDeclarationADefinition();
2192 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2193 return TD->isCompleteDefinition() || TD->isBeingDefined();
2197 /// Merge alignment attributes from \p Old to \p New, taking into account the
2198 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2200 /// \return \c true if any attributes were added to \p New.
2201 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2202 // Look for alignas attributes on Old, and pick out whichever attribute
2203 // specifies the strictest alignment requirement.
2204 AlignedAttr *OldAlignasAttr = nullptr;
2205 AlignedAttr *OldStrictestAlignAttr = nullptr;
2206 unsigned OldAlign = 0;
2207 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2208 // FIXME: We have no way of representing inherited dependent alignments
2210 // template<int A, int B> struct alignas(A) X;
2211 // template<int A, int B> struct alignas(B) X {};
2212 // For now, we just ignore any alignas attributes which are not on the
2213 // definition in such a case.
2214 if (I->isAlignmentDependent())
2220 unsigned Align = I->getAlignment(S.Context);
2221 if (Align > OldAlign) {
2223 OldStrictestAlignAttr = I;
2227 // Look for alignas attributes on New.
2228 AlignedAttr *NewAlignasAttr = nullptr;
2229 unsigned NewAlign = 0;
2230 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2231 if (I->isAlignmentDependent())
2237 unsigned Align = I->getAlignment(S.Context);
2238 if (Align > NewAlign)
2242 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2243 // Both declarations have 'alignas' attributes. We require them to match.
2244 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2245 // fall short. (If two declarations both have alignas, they must both match
2246 // every definition, and so must match each other if there is a definition.)
2248 // If either declaration only contains 'alignas(0)' specifiers, then it
2249 // specifies the natural alignment for the type.
2250 if (OldAlign == 0 || NewAlign == 0) {
2252 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2255 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2258 OldAlign = S.Context.getTypeAlign(Ty);
2260 NewAlign = S.Context.getTypeAlign(Ty);
2263 if (OldAlign != NewAlign) {
2264 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2265 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2266 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2267 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2271 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2272 // C++11 [dcl.align]p6:
2273 // if any declaration of an entity has an alignment-specifier,
2274 // every defining declaration of that entity shall specify an
2275 // equivalent alignment.
2277 // If the definition of an object does not have an alignment
2278 // specifier, any other declaration of that object shall also
2279 // have no alignment specifier.
2280 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2282 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2286 bool AnyAdded = false;
2288 // Ensure we have an attribute representing the strictest alignment.
2289 if (OldAlign > NewAlign) {
2290 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2291 Clone->setInherited(true);
2292 New->addAttr(Clone);
2296 // Ensure we have an alignas attribute if the old declaration had one.
2297 if (OldAlignasAttr && !NewAlignasAttr &&
2298 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2299 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2300 Clone->setInherited(true);
2301 New->addAttr(Clone);
2308 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2309 const InheritableAttr *Attr,
2310 Sema::AvailabilityMergeKind AMK) {
2311 // This function copies an attribute Attr from a previous declaration to the
2312 // new declaration D if the new declaration doesn't itself have that attribute
2313 // yet or if that attribute allows duplicates.
2314 // If you're adding a new attribute that requires logic different from
2315 // "use explicit attribute on decl if present, else use attribute from
2316 // previous decl", for example if the attribute needs to be consistent
2317 // between redeclarations, you need to call a custom merge function here.
2318 InheritableAttr *NewAttr = nullptr;
2319 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2320 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2321 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2322 AA->isImplicit(), AA->getIntroduced(),
2323 AA->getDeprecated(),
2324 AA->getObsoleted(), AA->getUnavailable(),
2325 AA->getMessage(), AA->getStrict(),
2326 AA->getReplacement(), AMK,
2327 AttrSpellingListIndex);
2328 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2329 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2330 AttrSpellingListIndex);
2331 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2332 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2333 AttrSpellingListIndex);
2334 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2335 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2336 AttrSpellingListIndex);
2337 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2338 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2339 AttrSpellingListIndex);
2340 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2341 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2342 FA->getFormatIdx(), FA->getFirstArg(),
2343 AttrSpellingListIndex);
2344 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2345 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2346 AttrSpellingListIndex);
2347 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2348 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2349 AttrSpellingListIndex,
2350 IA->getSemanticSpelling());
2351 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2352 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2353 &S.Context.Idents.get(AA->getSpelling()),
2354 AttrSpellingListIndex);
2355 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2356 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2357 isa<CUDAGlobalAttr>(Attr))) {
2358 // CUDA target attributes are part of function signature for
2359 // overloading purposes and must not be merged.
2361 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2362 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2363 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2364 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2365 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2366 NewAttr = S.mergeInternalLinkageAttr(
2367 D, InternalLinkageA->getRange(),
2368 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2369 AttrSpellingListIndex);
2370 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2371 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2372 &S.Context.Idents.get(CommonA->getSpelling()),
2373 AttrSpellingListIndex);
2374 else if (isa<AlignedAttr>(Attr))
2375 // AlignedAttrs are handled separately, because we need to handle all
2376 // such attributes on a declaration at the same time.
2378 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2379 (AMK == Sema::AMK_Override ||
2380 AMK == Sema::AMK_ProtocolImplementation))
2382 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2383 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2385 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2386 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2389 NewAttr->setInherited(true);
2390 D->addAttr(NewAttr);
2391 if (isa<MSInheritanceAttr>(NewAttr))
2392 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2399 static const Decl *getDefinition(const Decl *D) {
2400 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2401 return TD->getDefinition();
2402 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2403 const VarDecl *Def = VD->getDefinition();
2406 return VD->getActingDefinition();
2408 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2409 return FD->getDefinition();
2413 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2414 for (const auto *Attribute : D->attrs())
2415 if (Attribute->getKind() == Kind)
2420 /// checkNewAttributesAfterDef - If we already have a definition, check that
2421 /// there are no new attributes in this declaration.
2422 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2423 if (!New->hasAttrs())
2426 const Decl *Def = getDefinition(Old);
2427 if (!Def || Def == New)
2430 AttrVec &NewAttributes = New->getAttrs();
2431 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2432 const Attr *NewAttribute = NewAttributes[I];
2434 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2435 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2436 Sema::SkipBodyInfo SkipBody;
2437 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2439 // If we're skipping this definition, drop the "alias" attribute.
2440 if (SkipBody.ShouldSkip) {
2441 NewAttributes.erase(NewAttributes.begin() + I);
2446 VarDecl *VD = cast<VarDecl>(New);
2447 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2448 VarDecl::TentativeDefinition
2449 ? diag::err_alias_after_tentative
2450 : diag::err_redefinition;
2451 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2452 S.Diag(Def->getLocation(), diag::note_previous_definition);
2453 VD->setInvalidDecl();
2459 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2460 // Tentative definitions are only interesting for the alias check above.
2461 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2467 if (hasAttribute(Def, NewAttribute->getKind())) {
2469 continue; // regular attr merging will take care of validating this.
2472 if (isa<C11NoReturnAttr>(NewAttribute)) {
2473 // C's _Noreturn is allowed to be added to a function after it is defined.
2476 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2477 if (AA->isAlignas()) {
2478 // C++11 [dcl.align]p6:
2479 // if any declaration of an entity has an alignment-specifier,
2480 // every defining declaration of that entity shall specify an
2481 // equivalent alignment.
2483 // If the definition of an object does not have an alignment
2484 // specifier, any other declaration of that object shall also
2485 // have no alignment specifier.
2486 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2488 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2490 NewAttributes.erase(NewAttributes.begin() + I);
2496 S.Diag(NewAttribute->getLocation(),
2497 diag::warn_attribute_precede_definition);
2498 S.Diag(Def->getLocation(), diag::note_previous_definition);
2499 NewAttributes.erase(NewAttributes.begin() + I);
2504 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2505 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2506 AvailabilityMergeKind AMK) {
2507 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2508 UsedAttr *NewAttr = OldAttr->clone(Context);
2509 NewAttr->setInherited(true);
2510 New->addAttr(NewAttr);
2513 if (!Old->hasAttrs() && !New->hasAttrs())
2516 // Attributes declared post-definition are currently ignored.
2517 checkNewAttributesAfterDef(*this, New, Old);
2519 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2520 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2521 if (OldA->getLabel() != NewA->getLabel()) {
2522 // This redeclaration changes __asm__ label.
2523 Diag(New->getLocation(), diag::err_different_asm_label);
2524 Diag(OldA->getLocation(), diag::note_previous_declaration);
2526 } else if (Old->isUsed()) {
2527 // This redeclaration adds an __asm__ label to a declaration that has
2528 // already been ODR-used.
2529 Diag(New->getLocation(), diag::err_late_asm_label_name)
2530 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2534 // Re-declaration cannot add abi_tag's.
2535 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2536 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2537 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2538 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2539 NewTag) == OldAbiTagAttr->tags_end()) {
2540 Diag(NewAbiTagAttr->getLocation(),
2541 diag::err_new_abi_tag_on_redeclaration)
2543 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2547 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2548 Diag(Old->getLocation(), diag::note_previous_declaration);
2552 if (!Old->hasAttrs())
2555 bool foundAny = New->hasAttrs();
2557 // Ensure that any moving of objects within the allocated map is done before
2559 if (!foundAny) New->setAttrs(AttrVec());
2561 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2562 // Ignore deprecated/unavailable/availability attributes if requested.
2563 AvailabilityMergeKind LocalAMK = AMK_None;
2564 if (isa<DeprecatedAttr>(I) ||
2565 isa<UnavailableAttr>(I) ||
2566 isa<AvailabilityAttr>(I)) {
2571 case AMK_Redeclaration:
2573 case AMK_ProtocolImplementation:
2580 if (isa<UsedAttr>(I))
2583 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2587 if (mergeAlignedAttrs(*this, New, Old))
2590 if (!foundAny) New->dropAttrs();
2593 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2595 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2596 const ParmVarDecl *oldDecl,
2598 // C++11 [dcl.attr.depend]p2:
2599 // The first declaration of a function shall specify the
2600 // carries_dependency attribute for its declarator-id if any declaration
2601 // of the function specifies the carries_dependency attribute.
2602 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2603 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2604 S.Diag(CDA->getLocation(),
2605 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2606 // Find the first declaration of the parameter.
2607 // FIXME: Should we build redeclaration chains for function parameters?
2608 const FunctionDecl *FirstFD =
2609 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2610 const ParmVarDecl *FirstVD =
2611 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2612 S.Diag(FirstVD->getLocation(),
2613 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2616 if (!oldDecl->hasAttrs())
2619 bool foundAny = newDecl->hasAttrs();
2621 // Ensure that any moving of objects within the allocated map is
2622 // done before we process them.
2623 if (!foundAny) newDecl->setAttrs(AttrVec());
2625 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2626 if (!DeclHasAttr(newDecl, I)) {
2627 InheritableAttr *newAttr =
2628 cast<InheritableParamAttr>(I->clone(S.Context));
2629 newAttr->setInherited(true);
2630 newDecl->addAttr(newAttr);
2635 if (!foundAny) newDecl->dropAttrs();
2638 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2639 const ParmVarDecl *OldParam,
2641 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2642 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2643 if (*Oldnullability != *Newnullability) {
2644 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2645 << DiagNullabilityKind(
2647 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2649 << DiagNullabilityKind(
2651 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2653 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2656 QualType NewT = NewParam->getType();
2657 NewT = S.Context.getAttributedType(
2658 AttributedType::getNullabilityAttrKind(*Oldnullability),
2660 NewParam->setType(NewT);
2667 /// Used in MergeFunctionDecl to keep track of function parameters in
2669 struct GNUCompatibleParamWarning {
2670 ParmVarDecl *OldParm;
2671 ParmVarDecl *NewParm;
2672 QualType PromotedType;
2675 } // end anonymous namespace
2677 /// getSpecialMember - get the special member enum for a method.
2678 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2679 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2680 if (Ctor->isDefaultConstructor())
2681 return Sema::CXXDefaultConstructor;
2683 if (Ctor->isCopyConstructor())
2684 return Sema::CXXCopyConstructor;
2686 if (Ctor->isMoveConstructor())
2687 return Sema::CXXMoveConstructor;
2688 } else if (isa<CXXDestructorDecl>(MD)) {
2689 return Sema::CXXDestructor;
2690 } else if (MD->isCopyAssignmentOperator()) {
2691 return Sema::CXXCopyAssignment;
2692 } else if (MD->isMoveAssignmentOperator()) {
2693 return Sema::CXXMoveAssignment;
2696 return Sema::CXXInvalid;
2699 // Determine whether the previous declaration was a definition, implicit
2700 // declaration, or a declaration.
2701 template <typename T>
2702 static std::pair<diag::kind, SourceLocation>
2703 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2704 diag::kind PrevDiag;
2705 SourceLocation OldLocation = Old->getLocation();
2706 if (Old->isThisDeclarationADefinition())
2707 PrevDiag = diag::note_previous_definition;
2708 else if (Old->isImplicit()) {
2709 PrevDiag = diag::note_previous_implicit_declaration;
2710 if (OldLocation.isInvalid())
2711 OldLocation = New->getLocation();
2713 PrevDiag = diag::note_previous_declaration;
2714 return std::make_pair(PrevDiag, OldLocation);
2717 /// canRedefineFunction - checks if a function can be redefined. Currently,
2718 /// only extern inline functions can be redefined, and even then only in
2720 static bool canRedefineFunction(const FunctionDecl *FD,
2721 const LangOptions& LangOpts) {
2722 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2723 !LangOpts.CPlusPlus &&
2724 FD->isInlineSpecified() &&
2725 FD->getStorageClass() == SC_Extern);
2728 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2729 const AttributedType *AT = T->getAs<AttributedType>();
2730 while (AT && !AT->isCallingConv())
2731 AT = AT->getModifiedType()->getAs<AttributedType>();
2735 template <typename T>
2736 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2737 const DeclContext *DC = Old->getDeclContext();
2741 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2742 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2744 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2749 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2750 static bool isExternC(VarTemplateDecl *) { return false; }
2752 /// \brief Check whether a redeclaration of an entity introduced by a
2753 /// using-declaration is valid, given that we know it's not an overload
2754 /// (nor a hidden tag declaration).
2755 template<typename ExpectedDecl>
2756 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2757 ExpectedDecl *New) {
2758 // C++11 [basic.scope.declarative]p4:
2759 // Given a set of declarations in a single declarative region, each of
2760 // which specifies the same unqualified name,
2761 // -- they shall all refer to the same entity, or all refer to functions
2762 // and function templates; or
2763 // -- exactly one declaration shall declare a class name or enumeration
2764 // name that is not a typedef name and the other declarations shall all
2765 // refer to the same variable or enumerator, or all refer to functions
2766 // and function templates; in this case the class name or enumeration
2767 // name is hidden (3.3.10).
2769 // C++11 [namespace.udecl]p14:
2770 // If a function declaration in namespace scope or block scope has the
2771 // same name and the same parameter-type-list as a function introduced
2772 // by a using-declaration, and the declarations do not declare the same
2773 // function, the program is ill-formed.
2775 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2777 !Old->getDeclContext()->getRedeclContext()->Equals(
2778 New->getDeclContext()->getRedeclContext()) &&
2779 !(isExternC(Old) && isExternC(New)))
2783 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2784 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2785 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2791 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2792 const FunctionDecl *B) {
2793 assert(A->getNumParams() == B->getNumParams());
2795 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2796 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2797 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2800 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2803 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2806 /// MergeFunctionDecl - We just parsed a function 'New' from
2807 /// declarator D which has the same name and scope as a previous
2808 /// declaration 'Old'. Figure out how to resolve this situation,
2809 /// merging decls or emitting diagnostics as appropriate.
2811 /// In C++, New and Old must be declarations that are not
2812 /// overloaded. Use IsOverload to determine whether New and Old are
2813 /// overloaded, and to select the Old declaration that New should be
2816 /// Returns true if there was an error, false otherwise.
2817 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2818 Scope *S, bool MergeTypeWithOld) {
2819 // Verify the old decl was also a function.
2820 FunctionDecl *Old = OldD->getAsFunction();
2822 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2823 if (New->getFriendObjectKind()) {
2824 Diag(New->getLocation(), diag::err_using_decl_friend);
2825 Diag(Shadow->getTargetDecl()->getLocation(),
2826 diag::note_using_decl_target);
2827 Diag(Shadow->getUsingDecl()->getLocation(),
2828 diag::note_using_decl) << 0;
2832 // Check whether the two declarations might declare the same function.
2833 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2835 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2837 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2838 << New->getDeclName();
2839 Diag(OldD->getLocation(), diag::note_previous_definition);
2844 // If the old declaration is invalid, just give up here.
2845 if (Old->isInvalidDecl())
2848 diag::kind PrevDiag;
2849 SourceLocation OldLocation;
2850 std::tie(PrevDiag, OldLocation) =
2851 getNoteDiagForInvalidRedeclaration(Old, New);
2853 // Don't complain about this if we're in GNU89 mode and the old function
2854 // is an extern inline function.
2855 // Don't complain about specializations. They are not supposed to have
2857 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2858 New->getStorageClass() == SC_Static &&
2859 Old->hasExternalFormalLinkage() &&
2860 !New->getTemplateSpecializationInfo() &&
2861 !canRedefineFunction(Old, getLangOpts())) {
2862 if (getLangOpts().MicrosoftExt) {
2863 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2864 Diag(OldLocation, PrevDiag);
2866 Diag(New->getLocation(), diag::err_static_non_static) << New;
2867 Diag(OldLocation, PrevDiag);
2872 if (New->hasAttr<InternalLinkageAttr>() &&
2873 !Old->hasAttr<InternalLinkageAttr>()) {
2874 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2875 << New->getDeclName();
2876 Diag(Old->getLocation(), diag::note_previous_definition);
2877 New->dropAttr<InternalLinkageAttr>();
2880 // If a function is first declared with a calling convention, but is later
2881 // declared or defined without one, all following decls assume the calling
2882 // convention of the first.
2884 // It's OK if a function is first declared without a calling convention,
2885 // but is later declared or defined with the default calling convention.
2887 // To test if either decl has an explicit calling convention, we look for
2888 // AttributedType sugar nodes on the type as written. If they are missing or
2889 // were canonicalized away, we assume the calling convention was implicit.
2891 // Note also that we DO NOT return at this point, because we still have
2892 // other tests to run.
2893 QualType OldQType = Context.getCanonicalType(Old->getType());
2894 QualType NewQType = Context.getCanonicalType(New->getType());
2895 const FunctionType *OldType = cast<FunctionType>(OldQType);
2896 const FunctionType *NewType = cast<FunctionType>(NewQType);
2897 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2898 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2899 bool RequiresAdjustment = false;
2901 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2902 FunctionDecl *First = Old->getFirstDecl();
2903 const FunctionType *FT =
2904 First->getType().getCanonicalType()->castAs<FunctionType>();
2905 FunctionType::ExtInfo FI = FT->getExtInfo();
2906 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2907 if (!NewCCExplicit) {
2908 // Inherit the CC from the previous declaration if it was specified
2909 // there but not here.
2910 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2911 RequiresAdjustment = true;
2913 // Calling conventions aren't compatible, so complain.
2914 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2915 Diag(New->getLocation(), diag::err_cconv_change)
2916 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2918 << (!FirstCCExplicit ? "" :
2919 FunctionType::getNameForCallConv(FI.getCC()));
2921 // Put the note on the first decl, since it is the one that matters.
2922 Diag(First->getLocation(), diag::note_previous_declaration);
2927 // FIXME: diagnose the other way around?
2928 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2929 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2930 RequiresAdjustment = true;
2933 // Merge regparm attribute.
2934 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2935 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2936 if (NewTypeInfo.getHasRegParm()) {
2937 Diag(New->getLocation(), diag::err_regparm_mismatch)
2938 << NewType->getRegParmType()
2939 << OldType->getRegParmType();
2940 Diag(OldLocation, diag::note_previous_declaration);
2944 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2945 RequiresAdjustment = true;
2948 // Merge ns_returns_retained attribute.
2949 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2950 if (NewTypeInfo.getProducesResult()) {
2951 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2952 Diag(OldLocation, diag::note_previous_declaration);
2956 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2957 RequiresAdjustment = true;
2960 if (RequiresAdjustment) {
2961 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2962 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2963 New->setType(QualType(AdjustedType, 0));
2964 NewQType = Context.getCanonicalType(New->getType());
2965 NewType = cast<FunctionType>(NewQType);
2968 // If this redeclaration makes the function inline, we may need to add it to
2969 // UndefinedButUsed.
2970 if (!Old->isInlined() && New->isInlined() &&
2971 !New->hasAttr<GNUInlineAttr>() &&
2972 !getLangOpts().GNUInline &&
2973 Old->isUsed(false) &&
2974 !Old->isDefined() && !New->isThisDeclarationADefinition())
2975 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2978 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2980 if (New->hasAttr<GNUInlineAttr>() &&
2981 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2982 UndefinedButUsed.erase(Old->getCanonicalDecl());
2985 // If pass_object_size params don't match up perfectly, this isn't a valid
2987 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2988 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2989 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2990 << New->getDeclName();
2991 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2995 if (getLangOpts().CPlusPlus) {
2996 // C++1z [over.load]p2
2997 // Certain function declarations cannot be overloaded:
2998 // -- Function declarations that differ only in the return type,
2999 // the exception specification, or both cannot be overloaded.
3001 // Check the exception specifications match. This may recompute the type of
3002 // both Old and New if it resolved exception specifications, so grab the
3003 // types again after this. Because this updates the type, we do this before
3004 // any of the other checks below, which may update the "de facto" NewQType
3005 // but do not necessarily update the type of New.
3006 if (CheckEquivalentExceptionSpec(Old, New))
3008 OldQType = Context.getCanonicalType(Old->getType());
3009 NewQType = Context.getCanonicalType(New->getType());
3011 // Go back to the type source info to compare the declared return types,
3012 // per C++1y [dcl.type.auto]p13:
3013 // Redeclarations or specializations of a function or function template
3014 // with a declared return type that uses a placeholder type shall also
3015 // use that placeholder, not a deduced type.
3016 QualType OldDeclaredReturnType =
3017 (Old->getTypeSourceInfo()
3018 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3019 : OldType)->getReturnType();
3020 QualType NewDeclaredReturnType =
3021 (New->getTypeSourceInfo()
3022 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3023 : NewType)->getReturnType();
3024 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3025 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3026 New->isLocalExternDecl())) {
3028 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3029 OldDeclaredReturnType->isObjCObjectPointerType())
3030 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3031 if (ResQT.isNull()) {
3032 if (New->isCXXClassMember() && New->isOutOfLine())
3033 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3034 << New << New->getReturnTypeSourceRange();
3036 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3037 << New->getReturnTypeSourceRange();
3038 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3039 << Old->getReturnTypeSourceRange();
3046 QualType OldReturnType = OldType->getReturnType();
3047 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3048 if (OldReturnType != NewReturnType) {
3049 // If this function has a deduced return type and has already been
3050 // defined, copy the deduced value from the old declaration.
3051 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3052 if (OldAT && OldAT->isDeduced()) {
3054 SubstAutoType(New->getType(),
3055 OldAT->isDependentType() ? Context.DependentTy
3056 : OldAT->getDeducedType()));
3057 NewQType = Context.getCanonicalType(
3058 SubstAutoType(NewQType,
3059 OldAT->isDependentType() ? Context.DependentTy
3060 : OldAT->getDeducedType()));
3064 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3065 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3066 if (OldMethod && NewMethod) {
3067 // Preserve triviality.
3068 NewMethod->setTrivial(OldMethod->isTrivial());
3070 // MSVC allows explicit template specialization at class scope:
3071 // 2 CXXMethodDecls referring to the same function will be injected.
3072 // We don't want a redeclaration error.
3073 bool IsClassScopeExplicitSpecialization =
3074 OldMethod->isFunctionTemplateSpecialization() &&
3075 NewMethod->isFunctionTemplateSpecialization();
3076 bool isFriend = NewMethod->getFriendObjectKind();
3078 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3079 !IsClassScopeExplicitSpecialization) {
3080 // -- Member function declarations with the same name and the
3081 // same parameter types cannot be overloaded if any of them
3082 // is a static member function declaration.
3083 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3084 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3085 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3089 // C++ [class.mem]p1:
3090 // [...] A member shall not be declared twice in the
3091 // member-specification, except that a nested class or member
3092 // class template can be declared and then later defined.
3093 if (!inTemplateInstantiation()) {
3095 if (isa<CXXConstructorDecl>(OldMethod))
3096 NewDiag = diag::err_constructor_redeclared;
3097 else if (isa<CXXDestructorDecl>(NewMethod))
3098 NewDiag = diag::err_destructor_redeclared;
3099 else if (isa<CXXConversionDecl>(NewMethod))
3100 NewDiag = diag::err_conv_function_redeclared;
3102 NewDiag = diag::err_member_redeclared;
3104 Diag(New->getLocation(), NewDiag);
3106 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3107 << New << New->getType();
3109 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3112 // Complain if this is an explicit declaration of a special
3113 // member that was initially declared implicitly.
3115 // As an exception, it's okay to befriend such methods in order
3116 // to permit the implicit constructor/destructor/operator calls.
3117 } else if (OldMethod->isImplicit()) {
3119 NewMethod->setImplicit();
3121 Diag(NewMethod->getLocation(),
3122 diag::err_definition_of_implicitly_declared_member)
3123 << New << getSpecialMember(OldMethod);
3126 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3127 Diag(NewMethod->getLocation(),
3128 diag::err_definition_of_explicitly_defaulted_member)
3129 << getSpecialMember(OldMethod);
3134 // C++11 [dcl.attr.noreturn]p1:
3135 // The first declaration of a function shall specify the noreturn
3136 // attribute if any declaration of that function specifies the noreturn
3138 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3139 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3140 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3141 Diag(Old->getFirstDecl()->getLocation(),
3142 diag::note_noreturn_missing_first_decl);
3145 // C++11 [dcl.attr.depend]p2:
3146 // The first declaration of a function shall specify the
3147 // carries_dependency attribute for its declarator-id if any declaration
3148 // of the function specifies the carries_dependency attribute.
3149 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3150 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3151 Diag(CDA->getLocation(),
3152 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3153 Diag(Old->getFirstDecl()->getLocation(),
3154 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3158 // All declarations for a function shall agree exactly in both the
3159 // return type and the parameter-type-list.
3160 // We also want to respect all the extended bits except noreturn.
3162 // noreturn should now match unless the old type info didn't have it.
3163 QualType OldQTypeForComparison = OldQType;
3164 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3165 auto *OldType = OldQType->castAs<FunctionProtoType>();
3166 const FunctionType *OldTypeForComparison
3167 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3168 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3169 assert(OldQTypeForComparison.isCanonical());
3172 if (haveIncompatibleLanguageLinkages(Old, New)) {
3173 // As a special case, retain the language linkage from previous
3174 // declarations of a friend function as an extension.
3176 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3177 // and is useful because there's otherwise no way to specify language
3178 // linkage within class scope.
3180 // Check cautiously as the friend object kind isn't yet complete.
3181 if (New->getFriendObjectKind() != Decl::FOK_None) {
3182 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3183 Diag(OldLocation, PrevDiag);
3185 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3186 Diag(OldLocation, PrevDiag);
3191 if (OldQTypeForComparison == NewQType)
3192 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3194 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3195 New->isLocalExternDecl()) {
3196 // It's OK if we couldn't merge types for a local function declaraton
3197 // if either the old or new type is dependent. We'll merge the types
3198 // when we instantiate the function.
3202 // Fall through for conflicting redeclarations and redefinitions.
3205 // C: Function types need to be compatible, not identical. This handles
3206 // duplicate function decls like "void f(int); void f(enum X);" properly.
3207 if (!getLangOpts().CPlusPlus &&
3208 Context.typesAreCompatible(OldQType, NewQType)) {
3209 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3210 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3211 const FunctionProtoType *OldProto = nullptr;
3212 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3213 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3214 // The old declaration provided a function prototype, but the
3215 // new declaration does not. Merge in the prototype.
3216 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3217 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3219 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3220 OldProto->getExtProtoInfo());
3221 New->setType(NewQType);
3222 New->setHasInheritedPrototype();
3224 // Synthesize parameters with the same types.
3225 SmallVector<ParmVarDecl*, 16> Params;
3226 for (const auto &ParamType : OldProto->param_types()) {
3227 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3228 SourceLocation(), nullptr,
3229 ParamType, /*TInfo=*/nullptr,
3231 Param->setScopeInfo(0, Params.size());
3232 Param->setImplicit();
3233 Params.push_back(Param);
3236 New->setParams(Params);
3239 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3242 // GNU C permits a K&R definition to follow a prototype declaration
3243 // if the declared types of the parameters in the K&R definition
3244 // match the types in the prototype declaration, even when the
3245 // promoted types of the parameters from the K&R definition differ
3246 // from the types in the prototype. GCC then keeps the types from
3249 // If a variadic prototype is followed by a non-variadic K&R definition,
3250 // the K&R definition becomes variadic. This is sort of an edge case, but
3251 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3253 if (!getLangOpts().CPlusPlus &&
3254 Old->hasPrototype() && !New->hasPrototype() &&
3255 New->getType()->getAs<FunctionProtoType>() &&
3256 Old->getNumParams() == New->getNumParams()) {
3257 SmallVector<QualType, 16> ArgTypes;
3258 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3259 const FunctionProtoType *OldProto
3260 = Old->getType()->getAs<FunctionProtoType>();
3261 const FunctionProtoType *NewProto
3262 = New->getType()->getAs<FunctionProtoType>();
3264 // Determine whether this is the GNU C extension.
3265 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3266 NewProto->getReturnType());
3267 bool LooseCompatible = !MergedReturn.isNull();
3268 for (unsigned Idx = 0, End = Old->getNumParams();
3269 LooseCompatible && Idx != End; ++Idx) {
3270 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3271 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3272 if (Context.typesAreCompatible(OldParm->getType(),
3273 NewProto->getParamType(Idx))) {
3274 ArgTypes.push_back(NewParm->getType());
3275 } else if (Context.typesAreCompatible(OldParm->getType(),
3277 /*CompareUnqualified=*/true)) {
3278 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3279 NewProto->getParamType(Idx) };
3280 Warnings.push_back(Warn);
3281 ArgTypes.push_back(NewParm->getType());
3283 LooseCompatible = false;
3286 if (LooseCompatible) {
3287 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3288 Diag(Warnings[Warn].NewParm->getLocation(),
3289 diag::ext_param_promoted_not_compatible_with_prototype)
3290 << Warnings[Warn].PromotedType
3291 << Warnings[Warn].OldParm->getType();
3292 if (Warnings[Warn].OldParm->getLocation().isValid())
3293 Diag(Warnings[Warn].OldParm->getLocation(),
3294 diag::note_previous_declaration);
3297 if (MergeTypeWithOld)
3298 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3299 OldProto->getExtProtoInfo()));
3300 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3303 // Fall through to diagnose conflicting types.
3306 // A function that has already been declared has been redeclared or
3307 // defined with a different type; show an appropriate diagnostic.
3309 // If the previous declaration was an implicitly-generated builtin
3310 // declaration, then at the very least we should use a specialized note.
3312 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3313 // If it's actually a library-defined builtin function like 'malloc'
3314 // or 'printf', just warn about the incompatible redeclaration.
3315 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3316 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3317 Diag(OldLocation, diag::note_previous_builtin_declaration)
3318 << Old << Old->getType();
3320 // If this is a global redeclaration, just forget hereafter
3321 // about the "builtin-ness" of the function.
3323 // Doing this for local extern declarations is problematic. If
3324 // the builtin declaration remains visible, a second invalid
3325 // local declaration will produce a hard error; if it doesn't
3326 // remain visible, a single bogus local redeclaration (which is
3327 // actually only a warning) could break all the downstream code.
3328 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3329 New->getIdentifier()->revertBuiltin();
3334 PrevDiag = diag::note_previous_builtin_declaration;
3337 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3338 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3342 /// \brief Completes the merge of two function declarations that are
3343 /// known to be compatible.
3345 /// This routine handles the merging of attributes and other
3346 /// properties of function declarations from the old declaration to
3347 /// the new declaration, once we know that New is in fact a
3348 /// redeclaration of Old.
3351 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3352 Scope *S, bool MergeTypeWithOld) {
3353 // Merge the attributes
3354 mergeDeclAttributes(New, Old);
3356 // Merge "pure" flag.
3360 // Merge "used" flag.
3361 if (Old->getMostRecentDecl()->isUsed(false))
3364 // Merge attributes from the parameters. These can mismatch with K&R
3366 if (New->getNumParams() == Old->getNumParams())
3367 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3368 ParmVarDecl *NewParam = New->getParamDecl(i);
3369 ParmVarDecl *OldParam = Old->getParamDecl(i);
3370 mergeParamDeclAttributes(NewParam, OldParam, *this);
3371 mergeParamDeclTypes(NewParam, OldParam, *this);
3374 if (getLangOpts().CPlusPlus)
3375 return MergeCXXFunctionDecl(New, Old, S);
3377 // Merge the function types so the we get the composite types for the return
3378 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3380 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3381 if (!Merged.isNull() && MergeTypeWithOld)
3382 New->setType(Merged);
3387 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3388 ObjCMethodDecl *oldMethod) {
3389 // Merge the attributes, including deprecated/unavailable
3390 AvailabilityMergeKind MergeKind =
3391 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3392 ? AMK_ProtocolImplementation
3393 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3396 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3398 // Merge attributes from the parameters.
3399 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3400 oe = oldMethod->param_end();
3401 for (ObjCMethodDecl::param_iterator
3402 ni = newMethod->param_begin(), ne = newMethod->param_end();
3403 ni != ne && oi != oe; ++ni, ++oi)
3404 mergeParamDeclAttributes(*ni, *oi, *this);
3406 CheckObjCMethodOverride(newMethod, oldMethod);
3409 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3410 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3412 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3413 ? diag::err_redefinition_different_type
3414 : diag::err_redeclaration_different_type)
3415 << New->getDeclName() << New->getType() << Old->getType();
3417 diag::kind PrevDiag;
3418 SourceLocation OldLocation;
3419 std::tie(PrevDiag, OldLocation)
3420 = getNoteDiagForInvalidRedeclaration(Old, New);
3421 S.Diag(OldLocation, PrevDiag);
3422 New->setInvalidDecl();
3425 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3426 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3427 /// emitting diagnostics as appropriate.
3429 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3430 /// to here in AddInitializerToDecl. We can't check them before the initializer
3432 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3433 bool MergeTypeWithOld) {
3434 if (New->isInvalidDecl() || Old->isInvalidDecl())
3438 if (getLangOpts().CPlusPlus) {
3439 if (New->getType()->isUndeducedType()) {
3440 // We don't know what the new type is until the initializer is attached.
3442 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3443 // These could still be something that needs exception specs checked.
3444 return MergeVarDeclExceptionSpecs(New, Old);
3446 // C++ [basic.link]p10:
3447 // [...] the types specified by all declarations referring to a given
3448 // object or function shall be identical, except that declarations for an
3449 // array object can specify array types that differ by the presence or
3450 // absence of a major array bound (8.3.4).
3451 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3452 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3453 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3455 // We are merging a variable declaration New into Old. If it has an array
3456 // bound, and that bound differs from Old's bound, we should diagnose the
3458 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3459 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3460 PrevVD = PrevVD->getPreviousDecl()) {
3461 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3462 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3465 if (!Context.hasSameType(NewArray, PrevVDTy))
3466 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3470 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3471 if (Context.hasSameType(OldArray->getElementType(),
3472 NewArray->getElementType()))
3473 MergedT = New->getType();
3475 // FIXME: Check visibility. New is hidden but has a complete type. If New
3476 // has no array bound, it should not inherit one from Old, if Old is not
3478 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3479 if (Context.hasSameType(OldArray->getElementType(),
3480 NewArray->getElementType()))
3481 MergedT = Old->getType();
3484 else if (New->getType()->isObjCObjectPointerType() &&
3485 Old->getType()->isObjCObjectPointerType()) {
3486 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3491 // All declarations that refer to the same object or function shall have
3493 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3495 if (MergedT.isNull()) {
3496 // It's OK if we couldn't merge types if either type is dependent, for a
3497 // block-scope variable. In other cases (static data members of class
3498 // templates, variable templates, ...), we require the types to be
3500 // FIXME: The C++ standard doesn't say anything about this.
3501 if ((New->getType()->isDependentType() ||
3502 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3503 // If the old type was dependent, we can't merge with it, so the new type
3504 // becomes dependent for now. We'll reproduce the original type when we
3505 // instantiate the TypeSourceInfo for the variable.
3506 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3507 New->setType(Context.DependentTy);
3510 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3513 // Don't actually update the type on the new declaration if the old
3514 // declaration was an extern declaration in a different scope.
3515 if (MergeTypeWithOld)
3516 New->setType(MergedT);
3519 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3520 LookupResult &Previous) {
3522 // For an identifier with internal or external linkage declared
3523 // in a scope in which a prior declaration of that identifier is
3524 // visible, if the prior declaration specifies internal or
3525 // external linkage, the type of the identifier at the later
3526 // declaration becomes the composite type.
3528 // If the variable isn't visible, we do not merge with its type.
3529 if (Previous.isShadowed())
3532 if (S.getLangOpts().CPlusPlus) {
3533 // C++11 [dcl.array]p3:
3534 // If there is a preceding declaration of the entity in the same
3535 // scope in which the bound was specified, an omitted array bound
3536 // is taken to be the same as in that earlier declaration.
3537 return NewVD->isPreviousDeclInSameBlockScope() ||
3538 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3539 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3541 // If the old declaration was function-local, don't merge with its
3542 // type unless we're in the same function.
3543 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3544 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3548 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3549 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3550 /// situation, merging decls or emitting diagnostics as appropriate.
3552 /// Tentative definition rules (C99 6.9.2p2) are checked by
3553 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3554 /// definitions here, since the initializer hasn't been attached.
3556 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3557 // If the new decl is already invalid, don't do any other checking.
3558 if (New->isInvalidDecl())
3561 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3564 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3566 // Verify the old decl was also a variable or variable template.
3567 VarDecl *Old = nullptr;
3568 VarTemplateDecl *OldTemplate = nullptr;
3569 if (Previous.isSingleResult()) {
3571 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3572 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3575 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3576 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3577 return New->setInvalidDecl();
3579 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3582 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3583 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3584 return New->setInvalidDecl();
3588 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3589 << New->getDeclName();
3590 Diag(Previous.getRepresentativeDecl()->getLocation(),
3591 diag::note_previous_definition);
3592 return New->setInvalidDecl();
3595 // Ensure the template parameters are compatible.
3597 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3598 OldTemplate->getTemplateParameters(),
3599 /*Complain=*/true, TPL_TemplateMatch))
3600 return New->setInvalidDecl();
3602 // C++ [class.mem]p1:
3603 // A member shall not be declared twice in the member-specification [...]
3605 // Here, we need only consider static data members.
3606 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3607 Diag(New->getLocation(), diag::err_duplicate_member)
3608 << New->getIdentifier();
3609 Diag(Old->getLocation(), diag::note_previous_declaration);
3610 New->setInvalidDecl();
3613 mergeDeclAttributes(New, Old);
3614 // Warn if an already-declared variable is made a weak_import in a subsequent
3616 if (New->hasAttr<WeakImportAttr>() &&
3617 Old->getStorageClass() == SC_None &&
3618 !Old->hasAttr<WeakImportAttr>()) {
3619 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3620 Diag(Old->getLocation(), diag::note_previous_definition);
3621 // Remove weak_import attribute on new declaration.
3622 New->dropAttr<WeakImportAttr>();
3625 if (New->hasAttr<InternalLinkageAttr>() &&
3626 !Old->hasAttr<InternalLinkageAttr>()) {
3627 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3628 << New->getDeclName();
3629 Diag(Old->getLocation(), diag::note_previous_definition);
3630 New->dropAttr<InternalLinkageAttr>();
3634 VarDecl *MostRecent = Old->getMostRecentDecl();
3635 if (MostRecent != Old) {
3636 MergeVarDeclTypes(New, MostRecent,
3637 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3638 if (New->isInvalidDecl())
3642 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3643 if (New->isInvalidDecl())
3646 diag::kind PrevDiag;
3647 SourceLocation OldLocation;
3648 std::tie(PrevDiag, OldLocation) =
3649 getNoteDiagForInvalidRedeclaration(Old, New);
3651 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3652 if (New->getStorageClass() == SC_Static &&
3653 !New->isStaticDataMember() &&
3654 Old->hasExternalFormalLinkage()) {
3655 if (getLangOpts().MicrosoftExt) {
3656 Diag(New->getLocation(), diag::ext_static_non_static)
3657 << New->getDeclName();
3658 Diag(OldLocation, PrevDiag);
3660 Diag(New->getLocation(), diag::err_static_non_static)
3661 << New->getDeclName();
3662 Diag(OldLocation, PrevDiag);
3663 return New->setInvalidDecl();
3667 // For an identifier declared with the storage-class specifier
3668 // extern in a scope in which a prior declaration of that
3669 // identifier is visible,23) if the prior declaration specifies
3670 // internal or external linkage, the linkage of the identifier at
3671 // the later declaration is the same as the linkage specified at
3672 // the prior declaration. If no prior declaration is visible, or
3673 // if the prior declaration specifies no linkage, then the
3674 // identifier has external linkage.
3675 if (New->hasExternalStorage() && Old->hasLinkage())
3677 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3678 !New->isStaticDataMember() &&
3679 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3680 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3681 Diag(OldLocation, PrevDiag);
3682 return New->setInvalidDecl();
3685 // Check if extern is followed by non-extern and vice-versa.
3686 if (New->hasExternalStorage() &&
3687 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3688 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3689 Diag(OldLocation, PrevDiag);
3690 return New->setInvalidDecl();
3692 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3693 !New->hasExternalStorage()) {
3694 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3695 Diag(OldLocation, PrevDiag);
3696 return New->setInvalidDecl();
3699 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3701 // FIXME: The test for external storage here seems wrong? We still
3702 // need to check for mismatches.
3703 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3704 // Don't complain about out-of-line definitions of static members.
3705 !(Old->getLexicalDeclContext()->isRecord() &&
3706 !New->getLexicalDeclContext()->isRecord())) {
3707 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3708 Diag(OldLocation, PrevDiag);
3709 return New->setInvalidDecl();
3712 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3713 if (VarDecl *Def = Old->getDefinition()) {
3714 // C++1z [dcl.fcn.spec]p4:
3715 // If the definition of a variable appears in a translation unit before
3716 // its first declaration as inline, the program is ill-formed.
3717 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3718 Diag(Def->getLocation(), diag::note_previous_definition);
3722 // If this redeclaration makes the function inline, we may need to add it to
3723 // UndefinedButUsed.
3724 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3725 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3726 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3729 if (New->getTLSKind() != Old->getTLSKind()) {
3730 if (!Old->getTLSKind()) {
3731 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3732 Diag(OldLocation, PrevDiag);
3733 } else if (!New->getTLSKind()) {
3734 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3735 Diag(OldLocation, PrevDiag);
3737 // Do not allow redeclaration to change the variable between requiring
3738 // static and dynamic initialization.
3739 // FIXME: GCC allows this, but uses the TLS keyword on the first
3740 // declaration to determine the kind. Do we need to be compatible here?
3741 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3742 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3743 Diag(OldLocation, PrevDiag);
3747 // C++ doesn't have tentative definitions, so go right ahead and check here.
3748 if (getLangOpts().CPlusPlus &&
3749 New->isThisDeclarationADefinition() == VarDecl::Definition) {
3750 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3751 Old->getCanonicalDecl()->isConstexpr()) {
3752 // This definition won't be a definition any more once it's been merged.
3753 Diag(New->getLocation(),
3754 diag::warn_deprecated_redundant_constexpr_static_def);
3755 } else if (VarDecl *Def = Old->getDefinition()) {
3756 if (checkVarDeclRedefinition(Def, New))
3761 if (haveIncompatibleLanguageLinkages(Old, New)) {
3762 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3763 Diag(OldLocation, PrevDiag);
3764 New->setInvalidDecl();
3768 // Merge "used" flag.
3769 if (Old->getMostRecentDecl()->isUsed(false))
3772 // Keep a chain of previous declarations.
3773 New->setPreviousDecl(Old);
3775 NewTemplate->setPreviousDecl(OldTemplate);
3777 // Inherit access appropriately.
3778 New->setAccess(Old->getAccess());
3780 NewTemplate->setAccess(New->getAccess());
3782 if (Old->isInline())
3783 New->setImplicitlyInline();
3786 /// We've just determined that \p Old and \p New both appear to be definitions
3787 /// of the same variable. Either diagnose or fix the problem.
3788 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3789 if (!hasVisibleDefinition(Old) &&
3790 (New->getFormalLinkage() == InternalLinkage ||
3792 New->getDescribedVarTemplate() ||
3793 New->getNumTemplateParameterLists() ||
3794 New->getDeclContext()->isDependentContext())) {
3795 // The previous definition is hidden, and multiple definitions are
3796 // permitted (in separate TUs). Demote this to a declaration.
3797 New->demoteThisDefinitionToDeclaration();
3799 // Make the canonical definition visible.
3800 if (auto *OldTD = Old->getDescribedVarTemplate())
3801 makeMergedDefinitionVisible(OldTD, New->getLocation());
3802 makeMergedDefinitionVisible(Old, New->getLocation());
3805 Diag(New->getLocation(), diag::err_redefinition) << New;
3806 Diag(Old->getLocation(), diag::note_previous_definition);
3807 New->setInvalidDecl();
3812 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3813 /// no declarator (e.g. "struct foo;") is parsed.
3815 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3816 RecordDecl *&AnonRecord) {
3817 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3821 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3822 // disambiguate entities defined in different scopes.
3823 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3825 // We will pick our mangling number depending on which version of MSVC is being
3827 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3828 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3829 ? S->getMSCurManglingNumber()
3830 : S->getMSLastManglingNumber();
3833 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3834 if (!Context.getLangOpts().CPlusPlus)
3837 if (isa<CXXRecordDecl>(Tag->getParent())) {
3838 // If this tag is the direct child of a class, number it if
3840 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3842 MangleNumberingContext &MCtx =
3843 Context.getManglingNumberContext(Tag->getParent());
3844 Context.setManglingNumber(
3845 Tag, MCtx.getManglingNumber(
3846 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3850 // If this tag isn't a direct child of a class, number it if it is local.
3851 Decl *ManglingContextDecl;
3852 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3853 Tag->getDeclContext(), ManglingContextDecl)) {
3854 Context.setManglingNumber(
3855 Tag, MCtx->getManglingNumber(
3856 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3860 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3861 TypedefNameDecl *NewTD) {
3862 if (TagFromDeclSpec->isInvalidDecl())
3865 // Do nothing if the tag already has a name for linkage purposes.
3866 if (TagFromDeclSpec->hasNameForLinkage())
3869 // A well-formed anonymous tag must always be a TUK_Definition.
3870 assert(TagFromDeclSpec->isThisDeclarationADefinition());
3872 // The type must match the tag exactly; no qualifiers allowed.
3873 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3874 Context.getTagDeclType(TagFromDeclSpec))) {
3875 if (getLangOpts().CPlusPlus)
3876 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3880 // If we've already computed linkage for the anonymous tag, then
3881 // adding a typedef name for the anonymous decl can change that
3882 // linkage, which might be a serious problem. Diagnose this as
3883 // unsupported and ignore the typedef name. TODO: we should
3884 // pursue this as a language defect and establish a formal rule
3885 // for how to handle it.
3886 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3887 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3889 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3890 tagLoc = getLocForEndOfToken(tagLoc);
3892 llvm::SmallString<40> textToInsert;
3893 textToInsert += ' ';
3894 textToInsert += NewTD->getIdentifier()->getName();
3895 Diag(tagLoc, diag::note_typedef_changes_linkage)
3896 << FixItHint::CreateInsertion(tagLoc, textToInsert);
3900 // Otherwise, set this is the anon-decl typedef for the tag.
3901 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3904 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3906 case DeclSpec::TST_class:
3908 case DeclSpec::TST_struct:
3910 case DeclSpec::TST_interface:
3912 case DeclSpec::TST_union:
3914 case DeclSpec::TST_enum:
3917 llvm_unreachable("unexpected type specifier");
3921 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3922 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3923 /// parameters to cope with template friend declarations.
3925 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3926 MultiTemplateParamsArg TemplateParams,
3927 bool IsExplicitInstantiation,
3928 RecordDecl *&AnonRecord) {
3929 Decl *TagD = nullptr;
3930 TagDecl *Tag = nullptr;
3931 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3932 DS.getTypeSpecType() == DeclSpec::TST_struct ||
3933 DS.getTypeSpecType() == DeclSpec::TST_interface ||
3934 DS.getTypeSpecType() == DeclSpec::TST_union ||
3935 DS.getTypeSpecType() == DeclSpec::TST_enum) {
3936 TagD = DS.getRepAsDecl();
3938 if (!TagD) // We probably had an error
3941 // Note that the above type specs guarantee that the
3942 // type rep is a Decl, whereas in many of the others
3944 if (isa<TagDecl>(TagD))
3945 Tag = cast<TagDecl>(TagD);
3946 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3947 Tag = CTD->getTemplatedDecl();
3951 handleTagNumbering(Tag, S);
3952 Tag->setFreeStanding();
3953 if (Tag->isInvalidDecl())
3957 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3958 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3959 // or incomplete types shall not be restrict-qualified."
3960 if (TypeQuals & DeclSpec::TQ_restrict)
3961 Diag(DS.getRestrictSpecLoc(),
3962 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3963 << DS.getSourceRange();
3966 if (DS.isInlineSpecified())
3967 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3968 << getLangOpts().CPlusPlus1z;
3970 if (DS.isConstexprSpecified()) {
3971 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3972 // and definitions of functions and variables.
3974 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3975 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3977 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3978 // Don't emit warnings after this error.
3982 if (DS.isConceptSpecified()) {
3983 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3984 // either a function concept and its definition or a variable concept and
3986 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3990 DiagnoseFunctionSpecifiers(DS);
3992 if (DS.isFriendSpecified()) {
3993 // If we're dealing with a decl but not a TagDecl, assume that
3994 // whatever routines created it handled the friendship aspect.
3997 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4000 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4001 bool IsExplicitSpecialization =
4002 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4003 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4004 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4005 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4006 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4007 // nested-name-specifier unless it is an explicit instantiation
4008 // or an explicit specialization.
4010 // FIXME: We allow class template partial specializations here too, per the
4011 // obvious intent of DR1819.
4013 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4014 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4015 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4019 // Track whether this decl-specifier declares anything.
4020 bool DeclaresAnything = true;
4022 // Handle anonymous struct definitions.
4023 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4024 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4025 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4026 if (getLangOpts().CPlusPlus ||
4027 Record->getDeclContext()->isRecord()) {
4028 // If CurContext is a DeclContext that can contain statements,
4029 // RecursiveASTVisitor won't visit the decls that
4030 // BuildAnonymousStructOrUnion() will put into CurContext.
4031 // Also store them here so that they can be part of the
4032 // DeclStmt that gets created in this case.
4033 // FIXME: Also return the IndirectFieldDecls created by
4034 // BuildAnonymousStructOr union, for the same reason?
4035 if (CurContext->isFunctionOrMethod())
4036 AnonRecord = Record;
4037 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4038 Context.getPrintingPolicy());
4041 DeclaresAnything = false;
4046 // A struct-declaration that does not declare an anonymous structure or
4047 // anonymous union shall contain a struct-declarator-list.
4049 // This rule also existed in C89 and C99; the grammar for struct-declaration
4050 // did not permit a struct-declaration without a struct-declarator-list.
4051 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4052 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4053 // Check for Microsoft C extension: anonymous struct/union member.
4054 // Handle 2 kinds of anonymous struct/union:
4058 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4059 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4060 if ((Tag && Tag->getDeclName()) ||
4061 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4062 RecordDecl *Record = nullptr;
4064 Record = dyn_cast<RecordDecl>(Tag);
4065 else if (const RecordType *RT =
4066 DS.getRepAsType().get()->getAsStructureType())
4067 Record = RT->getDecl();
4068 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4069 Record = UT->getDecl();
4071 if (Record && getLangOpts().MicrosoftExt) {
4072 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4073 << Record->isUnion() << DS.getSourceRange();
4074 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4077 DeclaresAnything = false;
4081 // Skip all the checks below if we have a type error.
4082 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4083 (TagD && TagD->isInvalidDecl()))
4086 if (getLangOpts().CPlusPlus &&
4087 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4088 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4089 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4090 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4091 DeclaresAnything = false;
4093 if (!DS.isMissingDeclaratorOk()) {
4094 // Customize diagnostic for a typedef missing a name.
4095 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4096 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4097 << DS.getSourceRange();
4099 DeclaresAnything = false;
4102 if (DS.isModulePrivateSpecified() &&
4103 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4104 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4105 << Tag->getTagKind()
4106 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4108 ActOnDocumentableDecl(TagD);
4111 // A declaration [...] shall declare at least a declarator [...], a tag,
4112 // or the members of an enumeration.
4114 // [If there are no declarators], and except for the declaration of an
4115 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4116 // names into the program, or shall redeclare a name introduced by a
4117 // previous declaration.
4118 if (!DeclaresAnything) {
4119 // In C, we allow this as a (popular) extension / bug. Don't bother
4120 // producing further diagnostics for redundant qualifiers after this.
4121 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4126 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4127 // init-declarator-list of the declaration shall not be empty.
4128 // C++ [dcl.fct.spec]p1:
4129 // If a cv-qualifier appears in a decl-specifier-seq, the
4130 // init-declarator-list of the declaration shall not be empty.
4132 // Spurious qualifiers here appear to be valid in C.
4133 unsigned DiagID = diag::warn_standalone_specifier;
4134 if (getLangOpts().CPlusPlus)
4135 DiagID = diag::ext_standalone_specifier;
4137 // Note that a linkage-specification sets a storage class, but
4138 // 'extern "C" struct foo;' is actually valid and not theoretically
4140 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4141 if (SCS == DeclSpec::SCS_mutable)
4142 // Since mutable is not a viable storage class specifier in C, there is
4143 // no reason to treat it as an extension. Instead, diagnose as an error.
4144 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4145 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4146 Diag(DS.getStorageClassSpecLoc(), DiagID)
4147 << DeclSpec::getSpecifierName(SCS);
4150 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4151 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4152 << DeclSpec::getSpecifierName(TSCS);
4153 if (DS.getTypeQualifiers()) {
4154 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4155 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4156 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4157 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4158 // Restrict is covered above.
4159 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4160 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4161 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4162 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4165 // Warn about ignored type attributes, for example:
4166 // __attribute__((aligned)) struct A;
4167 // Attributes should be placed after tag to apply to type declaration.
4168 if (!DS.getAttributes().empty()) {
4169 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4170 if (TypeSpecType == DeclSpec::TST_class ||
4171 TypeSpecType == DeclSpec::TST_struct ||
4172 TypeSpecType == DeclSpec::TST_interface ||
4173 TypeSpecType == DeclSpec::TST_union ||
4174 TypeSpecType == DeclSpec::TST_enum) {
4175 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4176 attrs = attrs->getNext())
4177 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4178 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4185 /// We are trying to inject an anonymous member into the given scope;
4186 /// check if there's an existing declaration that can't be overloaded.
4188 /// \return true if this is a forbidden redeclaration
4189 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4192 DeclarationName Name,
4193 SourceLocation NameLoc,
4195 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4196 Sema::ForRedeclaration);
4197 if (!SemaRef.LookupName(R, S)) return false;
4199 // Pick a representative declaration.
4200 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4201 assert(PrevDecl && "Expected a non-null Decl");
4203 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4206 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4208 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4213 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4214 /// anonymous struct or union AnonRecord into the owning context Owner
4215 /// and scope S. This routine will be invoked just after we realize
4216 /// that an unnamed union or struct is actually an anonymous union or
4223 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4224 /// // f into the surrounding scope.x
4227 /// This routine is recursive, injecting the names of nested anonymous
4228 /// structs/unions into the owning context and scope as well.
4230 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4231 RecordDecl *AnonRecord, AccessSpecifier AS,
4232 SmallVectorImpl<NamedDecl *> &Chaining) {
4233 bool Invalid = false;
4235 // Look every FieldDecl and IndirectFieldDecl with a name.
4236 for (auto *D : AnonRecord->decls()) {
4237 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4238 cast<NamedDecl>(D)->getDeclName()) {
4239 ValueDecl *VD = cast<ValueDecl>(D);
4240 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4242 AnonRecord->isUnion())) {
4243 // C++ [class.union]p2:
4244 // The names of the members of an anonymous union shall be
4245 // distinct from the names of any other entity in the
4246 // scope in which the anonymous union is declared.
4249 // C++ [class.union]p2:
4250 // For the purpose of name lookup, after the anonymous union
4251 // definition, the members of the anonymous union are
4252 // considered to have been defined in the scope in which the
4253 // anonymous union is declared.
4254 unsigned OldChainingSize = Chaining.size();
4255 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4256 Chaining.append(IF->chain_begin(), IF->chain_end());
4258 Chaining.push_back(VD);
4260 assert(Chaining.size() >= 2);
4261 NamedDecl **NamedChain =
4262 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4263 for (unsigned i = 0; i < Chaining.size(); i++)
4264 NamedChain[i] = Chaining[i];
4266 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4267 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4268 VD->getType(), {NamedChain, Chaining.size()});
4270 for (const auto *Attr : VD->attrs())
4271 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4273 IndirectField->setAccess(AS);
4274 IndirectField->setImplicit();
4275 SemaRef.PushOnScopeChains(IndirectField, S);
4277 // That includes picking up the appropriate access specifier.
4278 if (AS != AS_none) IndirectField->setAccess(AS);
4280 Chaining.resize(OldChainingSize);
4288 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4289 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4290 /// illegal input values are mapped to SC_None.
4292 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4293 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4294 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4295 "Parser allowed 'typedef' as storage class VarDecl.");
4296 switch (StorageClassSpec) {
4297 case DeclSpec::SCS_unspecified: return SC_None;
4298 case DeclSpec::SCS_extern:
4299 if (DS.isExternInLinkageSpec())
4302 case DeclSpec::SCS_static: return SC_Static;
4303 case DeclSpec::SCS_auto: return SC_Auto;
4304 case DeclSpec::SCS_register: return SC_Register;
4305 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4306 // Illegal SCSs map to None: error reporting is up to the caller.
4307 case DeclSpec::SCS_mutable: // Fall through.
4308 case DeclSpec::SCS_typedef: return SC_None;
4310 llvm_unreachable("unknown storage class specifier");
4313 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4314 assert(Record->hasInClassInitializer());
4316 for (const auto *I : Record->decls()) {
4317 const auto *FD = dyn_cast<FieldDecl>(I);
4318 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4319 FD = IFD->getAnonField();
4320 if (FD && FD->hasInClassInitializer())
4321 return FD->getLocation();
4324 llvm_unreachable("couldn't find in-class initializer");
4327 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4328 SourceLocation DefaultInitLoc) {
4329 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4332 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4333 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4336 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4337 CXXRecordDecl *AnonUnion) {
4338 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4341 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4344 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4345 /// anonymous structure or union. Anonymous unions are a C++ feature
4346 /// (C++ [class.union]) and a C11 feature; anonymous structures
4347 /// are a C11 feature and GNU C++ extension.
4348 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4351 const PrintingPolicy &Policy) {
4352 DeclContext *Owner = Record->getDeclContext();
4354 // Diagnose whether this anonymous struct/union is an extension.
4355 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4356 Diag(Record->getLocation(), diag::ext_anonymous_union);
4357 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4358 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4359 else if (!Record->isUnion() && !getLangOpts().C11)
4360 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4362 // C and C++ require different kinds of checks for anonymous
4364 bool Invalid = false;
4365 if (getLangOpts().CPlusPlus) {
4366 const char *PrevSpec = nullptr;
4368 if (Record->isUnion()) {
4369 // C++ [class.union]p6:
4370 // Anonymous unions declared in a named namespace or in the
4371 // global namespace shall be declared static.
4372 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4373 (isa<TranslationUnitDecl>(Owner) ||
4374 (isa<NamespaceDecl>(Owner) &&
4375 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4376 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4377 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4379 // Recover by adding 'static'.
4380 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4381 PrevSpec, DiagID, Policy);
4383 // C++ [class.union]p6:
4384 // A storage class is not allowed in a declaration of an
4385 // anonymous union in a class scope.
4386 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4387 isa<RecordDecl>(Owner)) {
4388 Diag(DS.getStorageClassSpecLoc(),
4389 diag::err_anonymous_union_with_storage_spec)
4390 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4392 // Recover by removing the storage specifier.
4393 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4395 PrevSpec, DiagID, Context.getPrintingPolicy());
4399 // Ignore const/volatile/restrict qualifiers.
4400 if (DS.getTypeQualifiers()) {
4401 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4402 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4403 << Record->isUnion() << "const"
4404 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4405 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4406 Diag(DS.getVolatileSpecLoc(),
4407 diag::ext_anonymous_struct_union_qualified)
4408 << Record->isUnion() << "volatile"
4409 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4410 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4411 Diag(DS.getRestrictSpecLoc(),
4412 diag::ext_anonymous_struct_union_qualified)
4413 << Record->isUnion() << "restrict"
4414 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4415 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4416 Diag(DS.getAtomicSpecLoc(),
4417 diag::ext_anonymous_struct_union_qualified)
4418 << Record->isUnion() << "_Atomic"
4419 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4420 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4421 Diag(DS.getUnalignedSpecLoc(),
4422 diag::ext_anonymous_struct_union_qualified)
4423 << Record->isUnion() << "__unaligned"
4424 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4426 DS.ClearTypeQualifiers();
4429 // C++ [class.union]p2:
4430 // The member-specification of an anonymous union shall only
4431 // define non-static data members. [Note: nested types and
4432 // functions cannot be declared within an anonymous union. ]
4433 for (auto *Mem : Record->decls()) {
4434 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4435 // C++ [class.union]p3:
4436 // An anonymous union shall not have private or protected
4437 // members (clause 11).
4438 assert(FD->getAccess() != AS_none);
4439 if (FD->getAccess() != AS_public) {
4440 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4441 << Record->isUnion() << (FD->getAccess() == AS_protected);
4445 // C++ [class.union]p1
4446 // An object of a class with a non-trivial constructor, a non-trivial
4447 // copy constructor, a non-trivial destructor, or a non-trivial copy
4448 // assignment operator cannot be a member of a union, nor can an
4449 // array of such objects.
4450 if (CheckNontrivialField(FD))
4452 } else if (Mem->isImplicit()) {
4453 // Any implicit members are fine.
4454 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4455 // This is a type that showed up in an
4456 // elaborated-type-specifier inside the anonymous struct or
4457 // union, but which actually declares a type outside of the
4458 // anonymous struct or union. It's okay.
4459 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4460 if (!MemRecord->isAnonymousStructOrUnion() &&
4461 MemRecord->getDeclName()) {
4462 // Visual C++ allows type definition in anonymous struct or union.
4463 if (getLangOpts().MicrosoftExt)
4464 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4465 << Record->isUnion();
4467 // This is a nested type declaration.
4468 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4469 << Record->isUnion();
4473 // This is an anonymous type definition within another anonymous type.
4474 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4475 // not part of standard C++.
4476 Diag(MemRecord->getLocation(),
4477 diag::ext_anonymous_record_with_anonymous_type)
4478 << Record->isUnion();
4480 } else if (isa<AccessSpecDecl>(Mem)) {
4481 // Any access specifier is fine.
4482 } else if (isa<StaticAssertDecl>(Mem)) {
4483 // In C++1z, static_assert declarations are also fine.
4485 // We have something that isn't a non-static data
4486 // member. Complain about it.
4487 unsigned DK = diag::err_anonymous_record_bad_member;
4488 if (isa<TypeDecl>(Mem))
4489 DK = diag::err_anonymous_record_with_type;
4490 else if (isa<FunctionDecl>(Mem))
4491 DK = diag::err_anonymous_record_with_function;
4492 else if (isa<VarDecl>(Mem))
4493 DK = diag::err_anonymous_record_with_static;
4495 // Visual C++ allows type definition in anonymous struct or union.
4496 if (getLangOpts().MicrosoftExt &&
4497 DK == diag::err_anonymous_record_with_type)
4498 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4499 << Record->isUnion();
4501 Diag(Mem->getLocation(), DK) << Record->isUnion();
4507 // C++11 [class.union]p8 (DR1460):
4508 // At most one variant member of a union may have a
4509 // brace-or-equal-initializer.
4510 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4512 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4513 cast<CXXRecordDecl>(Record));
4516 if (!Record->isUnion() && !Owner->isRecord()) {
4517 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4518 << getLangOpts().CPlusPlus;
4522 // Mock up a declarator.
4523 Declarator Dc(DS, Declarator::MemberContext);
4524 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4525 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4527 // Create a declaration for this anonymous struct/union.
4528 NamedDecl *Anon = nullptr;
4529 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4530 Anon = FieldDecl::Create(Context, OwningClass,
4532 Record->getLocation(),
4533 /*IdentifierInfo=*/nullptr,
4534 Context.getTypeDeclType(Record),
4536 /*BitWidth=*/nullptr, /*Mutable=*/false,
4537 /*InitStyle=*/ICIS_NoInit);
4538 Anon->setAccess(AS);
4539 if (getLangOpts().CPlusPlus)
4540 FieldCollector->Add(cast<FieldDecl>(Anon));
4542 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4543 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4544 if (SCSpec == DeclSpec::SCS_mutable) {
4545 // mutable can only appear on non-static class members, so it's always
4547 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4552 Anon = VarDecl::Create(Context, Owner,
4554 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4555 Context.getTypeDeclType(Record),
4558 // Default-initialize the implicit variable. This initialization will be
4559 // trivial in almost all cases, except if a union member has an in-class
4561 // union { int n = 0; };
4562 ActOnUninitializedDecl(Anon);
4564 Anon->setImplicit();
4566 // Mark this as an anonymous struct/union type.
4567 Record->setAnonymousStructOrUnion(true);
4569 // Add the anonymous struct/union object to the current
4570 // context. We'll be referencing this object when we refer to one of
4572 Owner->addDecl(Anon);
4574 // Inject the members of the anonymous struct/union into the owning
4575 // context and into the identifier resolver chain for name lookup
4577 SmallVector<NamedDecl*, 2> Chain;
4578 Chain.push_back(Anon);
4580 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4583 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4584 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4585 Decl *ManglingContextDecl;
4586 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4587 NewVD->getDeclContext(), ManglingContextDecl)) {
4588 Context.setManglingNumber(
4589 NewVD, MCtx->getManglingNumber(
4590 NewVD, getMSManglingNumber(getLangOpts(), S)));
4591 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4597 Anon->setInvalidDecl();
4602 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4603 /// Microsoft C anonymous structure.
4604 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4607 /// struct A { int a; };
4608 /// struct B { struct A; int b; };
4615 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4616 RecordDecl *Record) {
4617 assert(Record && "expected a record!");
4619 // Mock up a declarator.
4620 Declarator Dc(DS, Declarator::TypeNameContext);
4621 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4622 assert(TInfo && "couldn't build declarator info for anonymous struct");
4624 auto *ParentDecl = cast<RecordDecl>(CurContext);
4625 QualType RecTy = Context.getTypeDeclType(Record);
4627 // Create a declaration for this anonymous struct.
4628 NamedDecl *Anon = FieldDecl::Create(Context,
4632 /*IdentifierInfo=*/nullptr,
4635 /*BitWidth=*/nullptr, /*Mutable=*/false,
4636 /*InitStyle=*/ICIS_NoInit);
4637 Anon->setImplicit();
4639 // Add the anonymous struct object to the current context.
4640 CurContext->addDecl(Anon);
4642 // Inject the members of the anonymous struct into the current
4643 // context and into the identifier resolver chain for name lookup
4645 SmallVector<NamedDecl*, 2> Chain;
4646 Chain.push_back(Anon);
4648 RecordDecl *RecordDef = Record->getDefinition();
4649 if (RequireCompleteType(Anon->getLocation(), RecTy,
4650 diag::err_field_incomplete) ||
4651 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4653 Anon->setInvalidDecl();
4654 ParentDecl->setInvalidDecl();
4660 /// GetNameForDeclarator - Determine the full declaration name for the
4661 /// given Declarator.
4662 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4663 return GetNameFromUnqualifiedId(D.getName());
4666 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4668 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4669 DeclarationNameInfo NameInfo;
4670 NameInfo.setLoc(Name.StartLocation);
4672 switch (Name.getKind()) {
4674 case UnqualifiedId::IK_ImplicitSelfParam:
4675 case UnqualifiedId::IK_Identifier:
4676 NameInfo.setName(Name.Identifier);
4677 NameInfo.setLoc(Name.StartLocation);
4680 case UnqualifiedId::IK_DeductionGuideName: {
4681 // C++ [temp.deduct.guide]p3:
4682 // The simple-template-id shall name a class template specialization.
4683 // The template-name shall be the same identifier as the template-name
4684 // of the simple-template-id.
4685 // These together intend to imply that the template-name shall name a
4687 // FIXME: template<typename T> struct X {};
4688 // template<typename T> using Y = X<T>;
4689 // Y(int) -> Y<int>;
4690 // satisfies these rules but does not name a class template.
4691 TemplateName TN = Name.TemplateName.get().get();
4692 auto *Template = TN.getAsTemplateDecl();
4693 if (!Template || !isa<ClassTemplateDecl>(Template)) {
4694 Diag(Name.StartLocation,
4695 diag::err_deduction_guide_name_not_class_template)
4696 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4698 Diag(Template->getLocation(), diag::note_template_decl_here);
4699 return DeclarationNameInfo();
4703 Context.DeclarationNames.getCXXDeductionGuideName(Template));
4704 NameInfo.setLoc(Name.StartLocation);
4708 case UnqualifiedId::IK_OperatorFunctionId:
4709 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4710 Name.OperatorFunctionId.Operator));
4711 NameInfo.setLoc(Name.StartLocation);
4712 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4713 = Name.OperatorFunctionId.SymbolLocations[0];
4714 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4715 = Name.EndLocation.getRawEncoding();
4718 case UnqualifiedId::IK_LiteralOperatorId:
4719 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4721 NameInfo.setLoc(Name.StartLocation);
4722 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4725 case UnqualifiedId::IK_ConversionFunctionId: {
4726 TypeSourceInfo *TInfo;
4727 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4729 return DeclarationNameInfo();
4730 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4731 Context.getCanonicalType(Ty)));
4732 NameInfo.setLoc(Name.StartLocation);
4733 NameInfo.setNamedTypeInfo(TInfo);
4737 case UnqualifiedId::IK_ConstructorName: {
4738 TypeSourceInfo *TInfo;
4739 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4741 return DeclarationNameInfo();
4742 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4743 Context.getCanonicalType(Ty)));
4744 NameInfo.setLoc(Name.StartLocation);
4745 NameInfo.setNamedTypeInfo(TInfo);
4749 case UnqualifiedId::IK_ConstructorTemplateId: {
4750 // In well-formed code, we can only have a constructor
4751 // template-id that refers to the current context, so go there
4752 // to find the actual type being constructed.
4753 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4754 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4755 return DeclarationNameInfo();
4757 // Determine the type of the class being constructed.
4758 QualType CurClassType = Context.getTypeDeclType(CurClass);
4760 // FIXME: Check two things: that the template-id names the same type as
4761 // CurClassType, and that the template-id does not occur when the name
4764 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4765 Context.getCanonicalType(CurClassType)));
4766 NameInfo.setLoc(Name.StartLocation);
4767 // FIXME: should we retrieve TypeSourceInfo?
4768 NameInfo.setNamedTypeInfo(nullptr);
4772 case UnqualifiedId::IK_DestructorName: {
4773 TypeSourceInfo *TInfo;
4774 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4776 return DeclarationNameInfo();
4777 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4778 Context.getCanonicalType(Ty)));
4779 NameInfo.setLoc(Name.StartLocation);
4780 NameInfo.setNamedTypeInfo(TInfo);
4784 case UnqualifiedId::IK_TemplateId: {
4785 TemplateName TName = Name.TemplateId->Template.get();
4786 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4787 return Context.getNameForTemplate(TName, TNameLoc);
4790 } // switch (Name.getKind())
4792 llvm_unreachable("Unknown name kind");
4795 static QualType getCoreType(QualType Ty) {
4797 if (Ty->isPointerType() || Ty->isReferenceType())
4798 Ty = Ty->getPointeeType();
4799 else if (Ty->isArrayType())
4800 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4802 return Ty.withoutLocalFastQualifiers();
4806 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4807 /// and Definition have "nearly" matching parameters. This heuristic is
4808 /// used to improve diagnostics in the case where an out-of-line function
4809 /// definition doesn't match any declaration within the class or namespace.
4810 /// Also sets Params to the list of indices to the parameters that differ
4811 /// between the declaration and the definition. If hasSimilarParameters
4812 /// returns true and Params is empty, then all of the parameters match.
4813 static bool hasSimilarParameters(ASTContext &Context,
4814 FunctionDecl *Declaration,
4815 FunctionDecl *Definition,
4816 SmallVectorImpl<unsigned> &Params) {
4818 if (Declaration->param_size() != Definition->param_size())
4820 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4821 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4822 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4824 // The parameter types are identical
4825 if (Context.hasSameType(DefParamTy, DeclParamTy))
4828 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4829 QualType DefParamBaseTy = getCoreType(DefParamTy);
4830 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4831 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4833 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4834 (DeclTyName && DeclTyName == DefTyName))
4835 Params.push_back(Idx);
4836 else // The two parameters aren't even close
4843 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4844 /// declarator needs to be rebuilt in the current instantiation.
4845 /// Any bits of declarator which appear before the name are valid for
4846 /// consideration here. That's specifically the type in the decl spec
4847 /// and the base type in any member-pointer chunks.
4848 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4849 DeclarationName Name) {
4850 // The types we specifically need to rebuild are:
4851 // - typenames, typeofs, and decltypes
4852 // - types which will become injected class names
4853 // Of course, we also need to rebuild any type referencing such a
4854 // type. It's safest to just say "dependent", but we call out a
4857 DeclSpec &DS = D.getMutableDeclSpec();
4858 switch (DS.getTypeSpecType()) {
4859 case DeclSpec::TST_typename:
4860 case DeclSpec::TST_typeofType:
4861 case DeclSpec::TST_underlyingType:
4862 case DeclSpec::TST_atomic: {
4863 // Grab the type from the parser.
4864 TypeSourceInfo *TSI = nullptr;
4865 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4866 if (T.isNull() || !T->isDependentType()) break;
4868 // Make sure there's a type source info. This isn't really much
4869 // of a waste; most dependent types should have type source info
4870 // attached already.
4872 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4874 // Rebuild the type in the current instantiation.
4875 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4876 if (!TSI) return true;
4878 // Store the new type back in the decl spec.
4879 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4880 DS.UpdateTypeRep(LocType);
4884 case DeclSpec::TST_decltype:
4885 case DeclSpec::TST_typeofExpr: {
4886 Expr *E = DS.getRepAsExpr();
4887 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4888 if (Result.isInvalid()) return true;
4889 DS.UpdateExprRep(Result.get());
4894 // Nothing to do for these decl specs.
4898 // It doesn't matter what order we do this in.
4899 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4900 DeclaratorChunk &Chunk = D.getTypeObject(I);
4902 // The only type information in the declarator which can come
4903 // before the declaration name is the base type of a member
4905 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4908 // Rebuild the scope specifier in-place.
4909 CXXScopeSpec &SS = Chunk.Mem.Scope();
4910 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4917 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4918 D.setFunctionDefinitionKind(FDK_Declaration);
4919 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4921 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4922 Dcl && Dcl->getDeclContext()->isFileContext())
4923 Dcl->setTopLevelDeclInObjCContainer();
4925 if (getLangOpts().OpenCL)
4926 setCurrentOpenCLExtensionForDecl(Dcl);
4931 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4932 /// If T is the name of a class, then each of the following shall have a
4933 /// name different from T:
4934 /// - every static data member of class T;
4935 /// - every member function of class T
4936 /// - every member of class T that is itself a type;
4937 /// \returns true if the declaration name violates these rules.
4938 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4939 DeclarationNameInfo NameInfo) {
4940 DeclarationName Name = NameInfo.getName();
4942 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4943 while (Record && Record->isAnonymousStructOrUnion())
4944 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4945 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4946 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4953 /// \brief Diagnose a declaration whose declarator-id has the given
4954 /// nested-name-specifier.
4956 /// \param SS The nested-name-specifier of the declarator-id.
4958 /// \param DC The declaration context to which the nested-name-specifier
4961 /// \param Name The name of the entity being declared.
4963 /// \param Loc The location of the name of the entity being declared.
4965 /// \returns true if we cannot safely recover from this error, false otherwise.
4966 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4967 DeclarationName Name,
4968 SourceLocation Loc) {
4969 DeclContext *Cur = CurContext;
4970 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4971 Cur = Cur->getParent();
4973 // If the user provided a superfluous scope specifier that refers back to the
4974 // class in which the entity is already declared, diagnose and ignore it.
4980 // Note, it was once ill-formed to give redundant qualification in all
4981 // contexts, but that rule was removed by DR482.
4982 if (Cur->Equals(DC)) {
4983 if (Cur->isRecord()) {
4984 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4985 : diag::err_member_extra_qualification)
4986 << Name << FixItHint::CreateRemoval(SS.getRange());
4989 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4994 // Check whether the qualifying scope encloses the scope of the original
4996 if (!Cur->Encloses(DC)) {
4997 if (Cur->isRecord())
4998 Diag(Loc, diag::err_member_qualification)
4999 << Name << SS.getRange();
5000 else if (isa<TranslationUnitDecl>(DC))
5001 Diag(Loc, diag::err_invalid_declarator_global_scope)
5002 << Name << SS.getRange();
5003 else if (isa<FunctionDecl>(Cur))
5004 Diag(Loc, diag::err_invalid_declarator_in_function)
5005 << Name << SS.getRange();
5006 else if (isa<BlockDecl>(Cur))
5007 Diag(Loc, diag::err_invalid_declarator_in_block)
5008 << Name << SS.getRange();
5010 Diag(Loc, diag::err_invalid_declarator_scope)
5011 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5016 if (Cur->isRecord()) {
5017 // Cannot qualify members within a class.
5018 Diag(Loc, diag::err_member_qualification)
5019 << Name << SS.getRange();
5022 // C++ constructors and destructors with incorrect scopes can break
5023 // our AST invariants by having the wrong underlying types. If
5024 // that's the case, then drop this declaration entirely.
5025 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5026 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5027 !Context.hasSameType(Name.getCXXNameType(),
5028 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5034 // C++11 [dcl.meaning]p1:
5035 // [...] "The nested-name-specifier of the qualified declarator-id shall
5036 // not begin with a decltype-specifer"
5037 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5038 while (SpecLoc.getPrefix())
5039 SpecLoc = SpecLoc.getPrefix();
5040 if (dyn_cast_or_null<DecltypeType>(
5041 SpecLoc.getNestedNameSpecifier()->getAsType()))
5042 Diag(Loc, diag::err_decltype_in_declarator)
5043 << SpecLoc.getTypeLoc().getSourceRange();
5048 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5049 MultiTemplateParamsArg TemplateParamLists) {
5050 // TODO: consider using NameInfo for diagnostic.
5051 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5052 DeclarationName Name = NameInfo.getName();
5054 // All of these full declarators require an identifier. If it doesn't have
5055 // one, the ParsedFreeStandingDeclSpec action should be used.
5056 if (D.isDecompositionDeclarator()) {
5057 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5059 if (!D.isInvalidType()) // Reject this if we think it is valid.
5060 Diag(D.getDeclSpec().getLocStart(),
5061 diag::err_declarator_need_ident)
5062 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5064 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5067 // The scope passed in may not be a decl scope. Zip up the scope tree until
5068 // we find one that is.
5069 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5070 (S->getFlags() & Scope::TemplateParamScope) != 0)
5073 DeclContext *DC = CurContext;
5074 if (D.getCXXScopeSpec().isInvalid())
5076 else if (D.getCXXScopeSpec().isSet()) {
5077 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5078 UPPC_DeclarationQualifier))
5081 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5082 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5083 if (!DC || isa<EnumDecl>(DC)) {
5084 // If we could not compute the declaration context, it's because the
5085 // declaration context is dependent but does not refer to a class,
5086 // class template, or class template partial specialization. Complain
5087 // and return early, to avoid the coming semantic disaster.
5088 Diag(D.getIdentifierLoc(),
5089 diag::err_template_qualified_declarator_no_match)
5090 << D.getCXXScopeSpec().getScopeRep()
5091 << D.getCXXScopeSpec().getRange();
5094 bool IsDependentContext = DC->isDependentContext();
5096 if (!IsDependentContext &&
5097 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5100 // If a class is incomplete, do not parse entities inside it.
5101 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5102 Diag(D.getIdentifierLoc(),
5103 diag::err_member_def_undefined_record)
5104 << Name << DC << D.getCXXScopeSpec().getRange();
5107 if (!D.getDeclSpec().isFriendSpecified()) {
5108 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5109 Name, D.getIdentifierLoc())) {
5117 // Check whether we need to rebuild the type of the given
5118 // declaration in the current instantiation.
5119 if (EnteringContext && IsDependentContext &&
5120 TemplateParamLists.size() != 0) {
5121 ContextRAII SavedContext(*this, DC);
5122 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5127 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5128 QualType R = TInfo->getType();
5130 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5131 // If this is a typedef, we'll end up spewing multiple diagnostics.
5132 // Just return early; it's safer. If this is a function, let the
5133 // "constructor cannot have a return type" diagnostic handle it.
5134 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5137 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5138 UPPC_DeclarationType))
5141 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5144 // See if this is a redefinition of a variable in the same scope.
5145 if (!D.getCXXScopeSpec().isSet()) {
5146 bool IsLinkageLookup = false;
5147 bool CreateBuiltins = false;
5149 // If the declaration we're planning to build will be a function
5150 // or object with linkage, then look for another declaration with
5151 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5153 // If the declaration we're planning to build will be declared with
5154 // external linkage in the translation unit, create any builtin with
5156 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5158 else if (CurContext->isFunctionOrMethod() &&
5159 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5160 R->isFunctionType())) {
5161 IsLinkageLookup = true;
5163 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5164 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5165 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5166 CreateBuiltins = true;
5168 if (IsLinkageLookup)
5169 Previous.clear(LookupRedeclarationWithLinkage);
5171 LookupName(Previous, S, CreateBuiltins);
5172 } else { // Something like "int foo::x;"
5173 LookupQualifiedName(Previous, DC);
5175 // C++ [dcl.meaning]p1:
5176 // When the declarator-id is qualified, the declaration shall refer to a
5177 // previously declared member of the class or namespace to which the
5178 // qualifier refers (or, in the case of a namespace, of an element of the
5179 // inline namespace set of that namespace (7.3.1)) or to a specialization
5182 // Note that we already checked the context above, and that we do not have
5183 // enough information to make sure that Previous contains the declaration
5184 // we want to match. For example, given:
5191 // void X::f(int) { } // ill-formed
5193 // In this case, Previous will point to the overload set
5194 // containing the two f's declared in X, but neither of them
5197 // C++ [dcl.meaning]p1:
5198 // [...] the member shall not merely have been introduced by a
5199 // using-declaration in the scope of the class or namespace nominated by
5200 // the nested-name-specifier of the declarator-id.
5201 RemoveUsingDecls(Previous);
5204 if (Previous.isSingleResult() &&
5205 Previous.getFoundDecl()->isTemplateParameter()) {
5206 // Maybe we will complain about the shadowed template parameter.
5207 if (!D.isInvalidType())
5208 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5209 Previous.getFoundDecl());
5211 // Just pretend that we didn't see the previous declaration.
5215 // In C++, the previous declaration we find might be a tag type
5216 // (class or enum). In this case, the new declaration will hide the
5217 // tag type. Note that this does does not apply if we're declaring a
5218 // typedef (C++ [dcl.typedef]p4).
5219 if (Previous.isSingleTagDecl() &&
5220 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5223 // Check that there are no default arguments other than in the parameters
5224 // of a function declaration (C++ only).
5225 if (getLangOpts().CPlusPlus)
5226 CheckExtraCXXDefaultArguments(D);
5228 if (D.getDeclSpec().isConceptSpecified()) {
5229 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5230 // applied only to the definition of a function template or variable
5231 // template, declared in namespace scope
5232 if (!TemplateParamLists.size()) {
5233 Diag(D.getDeclSpec().getConceptSpecLoc(),
5234 diag:: err_concept_wrong_decl_kind);
5238 if (!DC->getRedeclContext()->isFileContext()) {
5239 Diag(D.getIdentifierLoc(),
5240 diag::err_concept_decls_may_only_appear_in_namespace_scope);
5247 bool AddToScope = true;
5248 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5249 if (TemplateParamLists.size()) {
5250 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5254 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5255 } else if (R->isFunctionType()) {
5256 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5260 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5267 // If this has an identifier and is not a function template specialization,
5268 // add it to the scope stack.
5269 if (New->getDeclName() && AddToScope) {
5270 // Only make a locally-scoped extern declaration visible if it is the first
5271 // declaration of this entity. Qualified lookup for such an entity should
5272 // only find this declaration if there is no visible declaration of it.
5273 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5274 PushOnScopeChains(New, S, AddToContext);
5276 CurContext->addHiddenDecl(New);
5279 if (isInOpenMPDeclareTargetContext())
5280 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5285 /// Helper method to turn variable array types into constant array
5286 /// types in certain situations which would otherwise be errors (for
5287 /// GCC compatibility).
5288 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5289 ASTContext &Context,
5290 bool &SizeIsNegative,
5291 llvm::APSInt &Oversized) {
5292 // This method tries to turn a variable array into a constant
5293 // array even when the size isn't an ICE. This is necessary
5294 // for compatibility with code that depends on gcc's buggy
5295 // constant expression folding, like struct {char x[(int)(char*)2];}
5296 SizeIsNegative = false;
5299 if (T->isDependentType())
5302 QualifierCollector Qs;
5303 const Type *Ty = Qs.strip(T);
5305 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5306 QualType Pointee = PTy->getPointeeType();
5307 QualType FixedType =
5308 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5310 if (FixedType.isNull()) return FixedType;
5311 FixedType = Context.getPointerType(FixedType);
5312 return Qs.apply(Context, FixedType);
5314 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5315 QualType Inner = PTy->getInnerType();
5316 QualType FixedType =
5317 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5319 if (FixedType.isNull()) return FixedType;
5320 FixedType = Context.getParenType(FixedType);
5321 return Qs.apply(Context, FixedType);
5324 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5327 // FIXME: We should probably handle this case
5328 if (VLATy->getElementType()->isVariablyModifiedType())
5332 if (!VLATy->getSizeExpr() ||
5333 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5336 // Check whether the array size is negative.
5337 if (Res.isSigned() && Res.isNegative()) {
5338 SizeIsNegative = true;
5342 // Check whether the array is too large to be addressed.
5343 unsigned ActiveSizeBits
5344 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5346 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5351 return Context.getConstantArrayType(VLATy->getElementType(),
5352 Res, ArrayType::Normal, 0);
5356 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5357 SrcTL = SrcTL.getUnqualifiedLoc();
5358 DstTL = DstTL.getUnqualifiedLoc();
5359 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5360 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5361 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5362 DstPTL.getPointeeLoc());
5363 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5366 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5367 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5368 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5369 DstPTL.getInnerLoc());
5370 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5371 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5374 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5375 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5376 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5377 TypeLoc DstElemTL = DstATL.getElementLoc();
5378 DstElemTL.initializeFullCopy(SrcElemTL);
5379 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5380 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5381 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5384 /// Helper method to turn variable array types into constant array
5385 /// types in certain situations which would otherwise be errors (for
5386 /// GCC compatibility).
5387 static TypeSourceInfo*
5388 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5389 ASTContext &Context,
5390 bool &SizeIsNegative,
5391 llvm::APSInt &Oversized) {
5393 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5394 SizeIsNegative, Oversized);
5395 if (FixedTy.isNull())
5397 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5398 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5399 FixedTInfo->getTypeLoc());
5403 /// \brief Register the given locally-scoped extern "C" declaration so
5404 /// that it can be found later for redeclarations. We include any extern "C"
5405 /// declaration that is not visible in the translation unit here, not just
5406 /// function-scope declarations.
5408 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5409 if (!getLangOpts().CPlusPlus &&
5410 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5411 // Don't need to track declarations in the TU in C.
5414 // Note that we have a locally-scoped external with this name.
5415 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5418 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5419 // FIXME: We can have multiple results via __attribute__((overloadable)).
5420 auto Result = Context.getExternCContextDecl()->lookup(Name);
5421 return Result.empty() ? nullptr : *Result.begin();
5424 /// \brief Diagnose function specifiers on a declaration of an identifier that
5425 /// does not identify a function.
5426 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5427 // FIXME: We should probably indicate the identifier in question to avoid
5428 // confusion for constructs like "virtual int a(), b;"
5429 if (DS.isVirtualSpecified())
5430 Diag(DS.getVirtualSpecLoc(),
5431 diag::err_virtual_non_function);
5433 if (DS.isExplicitSpecified())
5434 Diag(DS.getExplicitSpecLoc(),
5435 diag::err_explicit_non_function);
5437 if (DS.isNoreturnSpecified())
5438 Diag(DS.getNoreturnSpecLoc(),
5439 diag::err_noreturn_non_function);
5443 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5444 TypeSourceInfo *TInfo, LookupResult &Previous) {
5445 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5446 if (D.getCXXScopeSpec().isSet()) {
5447 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5448 << D.getCXXScopeSpec().getRange();
5450 // Pretend we didn't see the scope specifier.
5455 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5457 if (D.getDeclSpec().isInlineSpecified())
5458 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5459 << getLangOpts().CPlusPlus1z;
5460 if (D.getDeclSpec().isConstexprSpecified())
5461 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5463 if (D.getDeclSpec().isConceptSpecified())
5464 Diag(D.getDeclSpec().getConceptSpecLoc(),
5465 diag::err_concept_wrong_decl_kind);
5467 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5468 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5469 Diag(D.getName().StartLocation,
5470 diag::err_deduction_guide_invalid_specifier)
5473 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5474 << D.getName().getSourceRange();
5478 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5479 if (!NewTD) return nullptr;
5481 // Handle attributes prior to checking for duplicates in MergeVarDecl
5482 ProcessDeclAttributes(S, NewTD, D);
5484 CheckTypedefForVariablyModifiedType(S, NewTD);
5486 bool Redeclaration = D.isRedeclaration();
5487 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5488 D.setRedeclaration(Redeclaration);
5493 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5494 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5495 // then it shall have block scope.
5496 // Note that variably modified types must be fixed before merging the decl so
5497 // that redeclarations will match.
5498 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5499 QualType T = TInfo->getType();
5500 if (T->isVariablyModifiedType()) {
5501 getCurFunction()->setHasBranchProtectedScope();
5503 if (S->getFnParent() == nullptr) {
5504 bool SizeIsNegative;
5505 llvm::APSInt Oversized;
5506 TypeSourceInfo *FixedTInfo =
5507 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5511 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5512 NewTD->setTypeSourceInfo(FixedTInfo);
5515 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5516 else if (T->isVariableArrayType())
5517 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5518 else if (Oversized.getBoolValue())
5519 Diag(NewTD->getLocation(), diag::err_array_too_large)
5520 << Oversized.toString(10);
5522 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5523 NewTD->setInvalidDecl();
5529 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5530 /// declares a typedef-name, either using the 'typedef' type specifier or via
5531 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5533 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5534 LookupResult &Previous, bool &Redeclaration) {
5536 // Find the shadowed declaration before filtering for scope.
5537 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5539 // Merge the decl with the existing one if appropriate. If the decl is
5540 // in an outer scope, it isn't the same thing.
5541 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5542 /*AllowInlineNamespace*/false);
5543 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5544 if (!Previous.empty()) {
5545 Redeclaration = true;
5546 MergeTypedefNameDecl(S, NewTD, Previous);
5549 if (ShadowedDecl && !Redeclaration)
5550 CheckShadow(NewTD, ShadowedDecl, Previous);
5552 // If this is the C FILE type, notify the AST context.
5553 if (IdentifierInfo *II = NewTD->getIdentifier())
5554 if (!NewTD->isInvalidDecl() &&
5555 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5556 if (II->isStr("FILE"))
5557 Context.setFILEDecl(NewTD);
5558 else if (II->isStr("jmp_buf"))
5559 Context.setjmp_bufDecl(NewTD);
5560 else if (II->isStr("sigjmp_buf"))
5561 Context.setsigjmp_bufDecl(NewTD);
5562 else if (II->isStr("ucontext_t"))
5563 Context.setucontext_tDecl(NewTD);
5569 /// \brief Determines whether the given declaration is an out-of-scope
5570 /// previous declaration.
5572 /// This routine should be invoked when name lookup has found a
5573 /// previous declaration (PrevDecl) that is not in the scope where a
5574 /// new declaration by the same name is being introduced. If the new
5575 /// declaration occurs in a local scope, previous declarations with
5576 /// linkage may still be considered previous declarations (C99
5577 /// 6.2.2p4-5, C++ [basic.link]p6).
5579 /// \param PrevDecl the previous declaration found by name
5582 /// \param DC the context in which the new declaration is being
5585 /// \returns true if PrevDecl is an out-of-scope previous declaration
5586 /// for a new delcaration with the same name.
5588 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5589 ASTContext &Context) {
5593 if (!PrevDecl->hasLinkage())
5596 if (Context.getLangOpts().CPlusPlus) {
5597 // C++ [basic.link]p6:
5598 // If there is a visible declaration of an entity with linkage
5599 // having the same name and type, ignoring entities declared
5600 // outside the innermost enclosing namespace scope, the block
5601 // scope declaration declares that same entity and receives the
5602 // linkage of the previous declaration.
5603 DeclContext *OuterContext = DC->getRedeclContext();
5604 if (!OuterContext->isFunctionOrMethod())
5605 // This rule only applies to block-scope declarations.
5608 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5609 if (PrevOuterContext->isRecord())
5610 // We found a member function: ignore it.
5613 // Find the innermost enclosing namespace for the new and
5614 // previous declarations.
5615 OuterContext = OuterContext->getEnclosingNamespaceContext();
5616 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5618 // The previous declaration is in a different namespace, so it
5619 // isn't the same function.
5620 if (!OuterContext->Equals(PrevOuterContext))
5627 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5628 CXXScopeSpec &SS = D.getCXXScopeSpec();
5629 if (!SS.isSet()) return;
5630 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5633 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5634 QualType type = decl->getType();
5635 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5636 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5637 // Various kinds of declaration aren't allowed to be __autoreleasing.
5638 unsigned kind = -1U;
5639 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5640 if (var->hasAttr<BlocksAttr>())
5641 kind = 0; // __block
5642 else if (!var->hasLocalStorage())
5644 } else if (isa<ObjCIvarDecl>(decl)) {
5646 } else if (isa<FieldDecl>(decl)) {
5651 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5654 } else if (lifetime == Qualifiers::OCL_None) {
5655 // Try to infer lifetime.
5656 if (!type->isObjCLifetimeType())
5659 lifetime = type->getObjCARCImplicitLifetime();
5660 type = Context.getLifetimeQualifiedType(type, lifetime);
5661 decl->setType(type);
5664 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5665 // Thread-local variables cannot have lifetime.
5666 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5667 var->getTLSKind()) {
5668 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5677 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5678 // Ensure that an auto decl is deduced otherwise the checks below might cache
5679 // the wrong linkage.
5680 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5682 // 'weak' only applies to declarations with external linkage.
5683 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5684 if (!ND.isExternallyVisible()) {
5685 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5686 ND.dropAttr<WeakAttr>();
5689 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5690 if (ND.isExternallyVisible()) {
5691 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5692 ND.dropAttr<WeakRefAttr>();
5693 ND.dropAttr<AliasAttr>();
5697 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5698 if (VD->hasInit()) {
5699 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5700 assert(VD->isThisDeclarationADefinition() &&
5701 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5702 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5703 VD->dropAttr<AliasAttr>();
5708 // 'selectany' only applies to externally visible variable declarations.
5709 // It does not apply to functions.
5710 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5711 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5712 S.Diag(Attr->getLocation(),
5713 diag::err_attribute_selectany_non_extern_data);
5714 ND.dropAttr<SelectAnyAttr>();
5718 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5719 // dll attributes require external linkage. Static locals may have external
5720 // linkage but still cannot be explicitly imported or exported.
5721 auto *VD = dyn_cast<VarDecl>(&ND);
5722 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5723 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5725 ND.setInvalidDecl();
5729 // Virtual functions cannot be marked as 'notail'.
5730 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5731 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5732 if (MD->isVirtual()) {
5733 S.Diag(ND.getLocation(),
5734 diag::err_invalid_attribute_on_virtual_function)
5736 ND.dropAttr<NotTailCalledAttr>();
5740 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5742 bool IsSpecialization,
5743 bool IsDefinition) {
5744 if (OldDecl->isInvalidDecl())
5747 bool IsTemplate = false;
5748 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5749 OldDecl = OldTD->getTemplatedDecl();
5751 if (!IsSpecialization)
5752 IsDefinition = false;
5754 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5755 NewDecl = NewTD->getTemplatedDecl();
5759 if (!OldDecl || !NewDecl)
5762 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5763 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5764 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5765 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5767 // dllimport and dllexport are inheritable attributes so we have to exclude
5768 // inherited attribute instances.
5769 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5770 (NewExportAttr && !NewExportAttr->isInherited());
5772 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5773 // the only exception being explicit specializations.
5774 // Implicitly generated declarations are also excluded for now because there
5775 // is no other way to switch these to use dllimport or dllexport.
5776 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5778 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5779 // Allow with a warning for free functions and global variables.
5780 bool JustWarn = false;
5781 if (!OldDecl->isCXXClassMember()) {
5782 auto *VD = dyn_cast<VarDecl>(OldDecl);
5783 if (VD && !VD->getDescribedVarTemplate())
5785 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5786 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5790 // We cannot change a declaration that's been used because IR has already
5791 // been emitted. Dllimported functions will still work though (modulo
5792 // address equality) as they can use the thunk.
5793 if (OldDecl->isUsed())
5794 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5797 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5798 : diag::err_attribute_dll_redeclaration;
5799 S.Diag(NewDecl->getLocation(), DiagID)
5801 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5802 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5804 NewDecl->setInvalidDecl();
5809 // A redeclaration is not allowed to drop a dllimport attribute, the only
5810 // exceptions being inline function definitions (except for function
5811 // templates), local extern declarations, qualified friend declarations or
5812 // special MSVC extension: in the last case, the declaration is treated as if
5813 // it were marked dllexport.
5814 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5815 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5816 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5817 // Ignore static data because out-of-line definitions are diagnosed
5819 IsStaticDataMember = VD->isStaticDataMember();
5820 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5821 VarDecl::DeclarationOnly;
5822 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5823 IsInline = FD->isInlined();
5824 IsQualifiedFriend = FD->getQualifier() &&
5825 FD->getFriendObjectKind() == Decl::FOK_Declared;
5828 if (OldImportAttr && !HasNewAttr &&
5829 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5830 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5831 if (IsMicrosoft && IsDefinition) {
5832 S.Diag(NewDecl->getLocation(),
5833 diag::warn_redeclaration_without_import_attribute)
5835 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5836 NewDecl->dropAttr<DLLImportAttr>();
5837 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5838 NewImportAttr->getRange(), S.Context,
5839 NewImportAttr->getSpellingListIndex()));
5841 S.Diag(NewDecl->getLocation(),
5842 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5843 << NewDecl << OldImportAttr;
5844 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5845 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5846 OldDecl->dropAttr<DLLImportAttr>();
5847 NewDecl->dropAttr<DLLImportAttr>();
5849 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5850 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5851 OldDecl->dropAttr<DLLImportAttr>();
5852 NewDecl->dropAttr<DLLImportAttr>();
5853 S.Diag(NewDecl->getLocation(),
5854 diag::warn_dllimport_dropped_from_inline_function)
5855 << NewDecl << OldImportAttr;
5859 /// Given that we are within the definition of the given function,
5860 /// will that definition behave like C99's 'inline', where the
5861 /// definition is discarded except for optimization purposes?
5862 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5863 // Try to avoid calling GetGVALinkageForFunction.
5865 // All cases of this require the 'inline' keyword.
5866 if (!FD->isInlined()) return false;
5868 // This is only possible in C++ with the gnu_inline attribute.
5869 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5872 // Okay, go ahead and call the relatively-more-expensive function.
5873 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5876 /// Determine whether a variable is extern "C" prior to attaching
5877 /// an initializer. We can't just call isExternC() here, because that
5878 /// will also compute and cache whether the declaration is externally
5879 /// visible, which might change when we attach the initializer.
5881 /// This can only be used if the declaration is known to not be a
5882 /// redeclaration of an internal linkage declaration.
5888 /// Attaching the initializer here makes this declaration not externally
5889 /// visible, because its type has internal linkage.
5891 /// FIXME: This is a hack.
5892 template<typename T>
5893 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5894 if (S.getLangOpts().CPlusPlus) {
5895 // In C++, the overloadable attribute negates the effects of extern "C".
5896 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5899 // So do CUDA's host/device attributes.
5900 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5901 D->template hasAttr<CUDAHostAttr>()))
5904 return D->isExternC();
5907 static bool shouldConsiderLinkage(const VarDecl *VD) {
5908 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5909 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5910 return VD->hasExternalStorage();
5911 if (DC->isFileContext())
5915 llvm_unreachable("Unexpected context");
5918 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5919 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5920 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5921 isa<OMPDeclareReductionDecl>(DC))
5925 llvm_unreachable("Unexpected context");
5928 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5929 AttributeList::Kind Kind) {
5930 for (const AttributeList *L = AttrList; L; L = L->getNext())
5931 if (L->getKind() == Kind)
5936 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5937 AttributeList::Kind Kind) {
5938 // Check decl attributes on the DeclSpec.
5939 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5942 // Walk the declarator structure, checking decl attributes that were in a type
5943 // position to the decl itself.
5944 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5945 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5949 // Finally, check attributes on the decl itself.
5950 return hasParsedAttr(S, PD.getAttributes(), Kind);
5953 /// Adjust the \c DeclContext for a function or variable that might be a
5954 /// function-local external declaration.
5955 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5956 if (!DC->isFunctionOrMethod())
5959 // If this is a local extern function or variable declared within a function
5960 // template, don't add it into the enclosing namespace scope until it is
5961 // instantiated; it might have a dependent type right now.
5962 if (DC->isDependentContext())
5965 // C++11 [basic.link]p7:
5966 // When a block scope declaration of an entity with linkage is not found to
5967 // refer to some other declaration, then that entity is a member of the
5968 // innermost enclosing namespace.
5970 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5971 // semantically-enclosing namespace, not a lexically-enclosing one.
5972 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5973 DC = DC->getParent();
5977 /// \brief Returns true if given declaration has external C language linkage.
5978 static bool isDeclExternC(const Decl *D) {
5979 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5980 return FD->isExternC();
5981 if (const auto *VD = dyn_cast<VarDecl>(D))
5982 return VD->isExternC();
5984 llvm_unreachable("Unknown type of decl!");
5987 NamedDecl *Sema::ActOnVariableDeclarator(
5988 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5989 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5990 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5991 QualType R = TInfo->getType();
5992 DeclarationName Name = GetNameForDeclarator(D).getName();
5994 IdentifierInfo *II = Name.getAsIdentifierInfo();
5996 if (D.isDecompositionDeclarator()) {
5998 // Take the name of the first declarator as our name for diagnostic
6000 auto &Decomp = D.getDecompositionDeclarator();
6001 if (!Decomp.bindings().empty()) {
6002 II = Decomp.bindings()[0].Name;
6006 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6010 if (getLangOpts().OpenCL) {
6011 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6012 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6014 if (R->isImageType() || R->isPipeType()) {
6015 Diag(D.getIdentifierLoc(),
6016 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6022 // OpenCL v1.2 s6.9.r:
6023 // The event type cannot be used to declare a program scope variable.
6024 // OpenCL v2.0 s6.9.q:
6025 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6026 if (NULL == S->getParent()) {
6027 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6028 Diag(D.getIdentifierLoc(),
6029 diag::err_invalid_type_for_program_scope_var) << R;
6035 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6037 while (NR->isPointerType()) {
6038 if (NR->isFunctionPointerType()) {
6039 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6043 NR = NR->getPointeeType();
6046 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6047 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6048 // half array type (unless the cl_khr_fp16 extension is enabled).
6049 if (Context.getBaseElementType(R)->isHalfType()) {
6050 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6055 // OpenCL v1.2 s6.9.b p4:
6056 // The sampler type cannot be used with the __local and __global address
6057 // space qualifiers.
6058 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
6059 R.getAddressSpace() == LangAS::opencl_global)) {
6060 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6063 // OpenCL v1.2 s6.9.r:
6064 // The event type cannot be used with the __local, __constant and __global
6065 // address space qualifiers.
6066 if (R->isEventT()) {
6067 if (R.getAddressSpace()) {
6068 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6074 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6075 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6077 // dllimport globals without explicit storage class are treated as extern. We
6078 // have to change the storage class this early to get the right DeclContext.
6079 if (SC == SC_None && !DC->isRecord() &&
6080 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6081 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6084 DeclContext *OriginalDC = DC;
6085 bool IsLocalExternDecl = SC == SC_Extern &&
6086 adjustContextForLocalExternDecl(DC);
6088 if (SCSpec == DeclSpec::SCS_mutable) {
6089 // mutable can only appear on non-static class members, so it's always
6091 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6096 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6097 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6098 D.getDeclSpec().getStorageClassSpecLoc())) {
6099 // In C++11, the 'register' storage class specifier is deprecated.
6100 // Suppress the warning in system macros, it's used in macros in some
6101 // popular C system headers, such as in glibc's htonl() macro.
6102 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6103 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6104 : diag::warn_deprecated_register)
6105 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6108 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6110 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6111 // C99 6.9p2: The storage-class specifiers auto and register shall not
6112 // appear in the declaration specifiers in an external declaration.
6113 // Global Register+Asm is a GNU extension we support.
6114 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6115 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6120 bool IsMemberSpecialization = false;
6121 bool IsVariableTemplateSpecialization = false;
6122 bool IsPartialSpecialization = false;
6123 bool IsVariableTemplate = false;
6124 VarDecl *NewVD = nullptr;
6125 VarTemplateDecl *NewTemplate = nullptr;
6126 TemplateParameterList *TemplateParams = nullptr;
6127 if (!getLangOpts().CPlusPlus) {
6128 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6129 D.getIdentifierLoc(), II,
6132 if (R->getContainedDeducedType())
6133 ParsingInitForAutoVars.insert(NewVD);
6135 if (D.isInvalidType())
6136 NewVD->setInvalidDecl();
6138 bool Invalid = false;
6140 if (DC->isRecord() && !CurContext->isRecord()) {
6141 // This is an out-of-line definition of a static data member.
6146 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6147 diag::err_static_out_of_line)
6148 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6153 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6154 // to names of variables declared in a block or to function parameters.
6155 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6158 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6159 diag::err_storage_class_for_static_member)
6160 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6162 case SC_PrivateExtern:
6163 llvm_unreachable("C storage class in c++!");
6167 if (SC == SC_Static && CurContext->isRecord()) {
6168 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6169 if (RD->isLocalClass())
6170 Diag(D.getIdentifierLoc(),
6171 diag::err_static_data_member_not_allowed_in_local_class)
6172 << Name << RD->getDeclName();
6174 // C++98 [class.union]p1: If a union contains a static data member,
6175 // the program is ill-formed. C++11 drops this restriction.
6177 Diag(D.getIdentifierLoc(),
6178 getLangOpts().CPlusPlus11
6179 ? diag::warn_cxx98_compat_static_data_member_in_union
6180 : diag::ext_static_data_member_in_union) << Name;
6181 // We conservatively disallow static data members in anonymous structs.
6182 else if (!RD->getDeclName())
6183 Diag(D.getIdentifierLoc(),
6184 diag::err_static_data_member_not_allowed_in_anon_struct)
6185 << Name << RD->isUnion();
6189 // Match up the template parameter lists with the scope specifier, then
6190 // determine whether we have a template or a template specialization.
6191 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6192 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6193 D.getCXXScopeSpec(),
6194 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6195 ? D.getName().TemplateId
6198 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6200 if (TemplateParams) {
6201 if (!TemplateParams->size() &&
6202 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6203 // There is an extraneous 'template<>' for this variable. Complain
6204 // about it, but allow the declaration of the variable.
6205 Diag(TemplateParams->getTemplateLoc(),
6206 diag::err_template_variable_noparams)
6208 << SourceRange(TemplateParams->getTemplateLoc(),
6209 TemplateParams->getRAngleLoc());
6210 TemplateParams = nullptr;
6212 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6213 // This is an explicit specialization or a partial specialization.
6214 // FIXME: Check that we can declare a specialization here.
6215 IsVariableTemplateSpecialization = true;
6216 IsPartialSpecialization = TemplateParams->size() > 0;
6217 } else { // if (TemplateParams->size() > 0)
6218 // This is a template declaration.
6219 IsVariableTemplate = true;
6221 // Check that we can declare a template here.
6222 if (CheckTemplateDeclScope(S, TemplateParams))
6225 // Only C++1y supports variable templates (N3651).
6226 Diag(D.getIdentifierLoc(),
6227 getLangOpts().CPlusPlus14
6228 ? diag::warn_cxx11_compat_variable_template
6229 : diag::ext_variable_template);
6234 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6235 "should have a 'template<>' for this decl");
6238 if (IsVariableTemplateSpecialization) {
6239 SourceLocation TemplateKWLoc =
6240 TemplateParamLists.size() > 0
6241 ? TemplateParamLists[0]->getTemplateLoc()
6243 DeclResult Res = ActOnVarTemplateSpecialization(
6244 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6245 IsPartialSpecialization);
6246 if (Res.isInvalid())
6248 NewVD = cast<VarDecl>(Res.get());
6250 } else if (D.isDecompositionDeclarator()) {
6251 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6252 D.getIdentifierLoc(), R, TInfo, SC,
6255 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6256 D.getIdentifierLoc(), II, R, TInfo, SC);
6258 // If this is supposed to be a variable template, create it as such.
6259 if (IsVariableTemplate) {
6261 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6262 TemplateParams, NewVD);
6263 NewVD->setDescribedVarTemplate(NewTemplate);
6266 // If this decl has an auto type in need of deduction, make a note of the
6267 // Decl so we can diagnose uses of it in its own initializer.
6268 if (R->getContainedDeducedType())
6269 ParsingInitForAutoVars.insert(NewVD);
6271 if (D.isInvalidType() || Invalid) {
6272 NewVD->setInvalidDecl();
6274 NewTemplate->setInvalidDecl();
6277 SetNestedNameSpecifier(NewVD, D);
6279 // If we have any template parameter lists that don't directly belong to
6280 // the variable (matching the scope specifier), store them.
6281 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6282 if (TemplateParamLists.size() > VDTemplateParamLists)
6283 NewVD->setTemplateParameterListsInfo(
6284 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6286 if (D.getDeclSpec().isConstexprSpecified()) {
6287 NewVD->setConstexpr(true);
6288 // C++1z [dcl.spec.constexpr]p1:
6289 // A static data member declared with the constexpr specifier is
6290 // implicitly an inline variable.
6291 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6292 NewVD->setImplicitlyInline();
6295 if (D.getDeclSpec().isConceptSpecified()) {
6296 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6299 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6300 // be declared with the thread_local, inline, friend, or constexpr
6301 // specifiers, [...]
6302 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6303 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6304 diag::err_concept_decl_invalid_specifiers)
6306 NewVD->setInvalidDecl(true);
6309 if (D.getDeclSpec().isConstexprSpecified()) {
6310 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6311 diag::err_concept_decl_invalid_specifiers)
6313 NewVD->setInvalidDecl(true);
6316 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6317 // applied only to the definition of a function template or variable
6318 // template, declared in namespace scope.
6319 if (IsVariableTemplateSpecialization) {
6320 Diag(D.getDeclSpec().getConceptSpecLoc(),
6321 diag::err_concept_specified_specialization)
6322 << (IsPartialSpecialization ? 2 : 1);
6325 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6326 // following restrictions:
6327 // - The declared type shall have the type bool.
6328 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6329 !NewVD->isInvalidDecl()) {
6330 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6331 NewVD->setInvalidDecl(true);
6336 if (D.getDeclSpec().isInlineSpecified()) {
6337 if (!getLangOpts().CPlusPlus) {
6338 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6340 } else if (CurContext->isFunctionOrMethod()) {
6341 // 'inline' is not allowed on block scope variable declaration.
6342 Diag(D.getDeclSpec().getInlineSpecLoc(),
6343 diag::err_inline_declaration_block_scope) << Name
6344 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6346 Diag(D.getDeclSpec().getInlineSpecLoc(),
6347 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6348 : diag::ext_inline_variable);
6349 NewVD->setInlineSpecified();
6353 // Set the lexical context. If the declarator has a C++ scope specifier, the
6354 // lexical context will be different from the semantic context.
6355 NewVD->setLexicalDeclContext(CurContext);
6357 NewTemplate->setLexicalDeclContext(CurContext);
6359 if (IsLocalExternDecl) {
6360 if (D.isDecompositionDeclarator())
6361 for (auto *B : Bindings)
6362 B->setLocalExternDecl();
6364 NewVD->setLocalExternDecl();
6367 bool EmitTLSUnsupportedError = false;
6368 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6369 // C++11 [dcl.stc]p4:
6370 // When thread_local is applied to a variable of block scope the
6371 // storage-class-specifier static is implied if it does not appear
6373 // Core issue: 'static' is not implied if the variable is declared
6375 if (NewVD->hasLocalStorage() &&
6376 (SCSpec != DeclSpec::SCS_unspecified ||
6377 TSCS != DeclSpec::TSCS_thread_local ||
6378 !DC->isFunctionOrMethod()))
6379 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6380 diag::err_thread_non_global)
6381 << DeclSpec::getSpecifierName(TSCS);
6382 else if (!Context.getTargetInfo().isTLSSupported()) {
6383 if (getLangOpts().CUDA) {
6384 // Postpone error emission until we've collected attributes required to
6385 // figure out whether it's a host or device variable and whether the
6386 // error should be ignored.
6387 EmitTLSUnsupportedError = true;
6388 // We still need to mark the variable as TLS so it shows up in AST with
6389 // proper storage class for other tools to use even if we're not going
6390 // to emit any code for it.
6391 NewVD->setTSCSpec(TSCS);
6393 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6394 diag::err_thread_unsupported);
6396 NewVD->setTSCSpec(TSCS);
6400 // An inline definition of a function with external linkage shall
6401 // not contain a definition of a modifiable object with static or
6402 // thread storage duration...
6403 // We only apply this when the function is required to be defined
6404 // elsewhere, i.e. when the function is not 'extern inline'. Note
6405 // that a local variable with thread storage duration still has to
6406 // be marked 'static'. Also note that it's possible to get these
6407 // semantics in C++ using __attribute__((gnu_inline)).
6408 if (SC == SC_Static && S->getFnParent() != nullptr &&
6409 !NewVD->getType().isConstQualified()) {
6410 FunctionDecl *CurFD = getCurFunctionDecl();
6411 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6412 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6413 diag::warn_static_local_in_extern_inline);
6414 MaybeSuggestAddingStaticToDecl(CurFD);
6418 if (D.getDeclSpec().isModulePrivateSpecified()) {
6419 if (IsVariableTemplateSpecialization)
6420 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6421 << (IsPartialSpecialization ? 1 : 0)
6422 << FixItHint::CreateRemoval(
6423 D.getDeclSpec().getModulePrivateSpecLoc());
6424 else if (IsMemberSpecialization)
6425 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6427 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6428 else if (NewVD->hasLocalStorage())
6429 Diag(NewVD->getLocation(), diag::err_module_private_local)
6430 << 0 << NewVD->getDeclName()
6431 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6432 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6434 NewVD->setModulePrivate();
6436 NewTemplate->setModulePrivate();
6437 for (auto *B : Bindings)
6438 B->setModulePrivate();
6442 // Handle attributes prior to checking for duplicates in MergeVarDecl
6443 ProcessDeclAttributes(S, NewVD, D);
6445 if (getLangOpts().CUDA) {
6446 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6447 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6448 diag::err_thread_unsupported);
6449 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6450 // storage [duration]."
6451 if (SC == SC_None && S->getFnParent() != nullptr &&
6452 (NewVD->hasAttr<CUDASharedAttr>() ||
6453 NewVD->hasAttr<CUDAConstantAttr>())) {
6454 NewVD->setStorageClass(SC_Static);
6458 // Ensure that dllimport globals without explicit storage class are treated as
6459 // extern. The storage class is set above using parsed attributes. Now we can
6460 // check the VarDecl itself.
6461 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6462 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6463 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6465 // In auto-retain/release, infer strong retension for variables of
6467 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6468 NewVD->setInvalidDecl();
6470 // Handle GNU asm-label extension (encoded as an attribute).
6471 if (Expr *E = (Expr*)D.getAsmLabel()) {
6472 // The parser guarantees this is a string.
6473 StringLiteral *SE = cast<StringLiteral>(E);
6474 StringRef Label = SE->getString();
6475 if (S->getFnParent() != nullptr) {
6479 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6482 // Local Named register
6483 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6484 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6485 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6489 case SC_PrivateExtern:
6492 } else if (SC == SC_Register) {
6493 // Global Named register
6494 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6495 const auto &TI = Context.getTargetInfo();
6496 bool HasSizeMismatch;
6498 if (!TI.isValidGCCRegisterName(Label))
6499 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6500 else if (!TI.validateGlobalRegisterVariable(Label,
6501 Context.getTypeSize(R),
6503 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6504 else if (HasSizeMismatch)
6505 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6508 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6509 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6510 NewVD->setInvalidDecl(true);
6514 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6515 Context, Label, 0));
6516 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6517 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6518 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6519 if (I != ExtnameUndeclaredIdentifiers.end()) {
6520 if (isDeclExternC(NewVD)) {
6521 NewVD->addAttr(I->second);
6522 ExtnameUndeclaredIdentifiers.erase(I);
6524 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6525 << /*Variable*/1 << NewVD;
6529 // Find the shadowed declaration before filtering for scope.
6530 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6531 ? getShadowedDeclaration(NewVD, Previous)
6534 // Don't consider existing declarations that are in a different
6535 // scope and are out-of-semantic-context declarations (if the new
6536 // declaration has linkage).
6537 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6538 D.getCXXScopeSpec().isNotEmpty() ||
6539 IsMemberSpecialization ||
6540 IsVariableTemplateSpecialization);
6542 // Check whether the previous declaration is in the same block scope. This
6543 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6544 if (getLangOpts().CPlusPlus &&
6545 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6546 NewVD->setPreviousDeclInSameBlockScope(
6547 Previous.isSingleResult() && !Previous.isShadowed() &&
6548 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6550 if (!getLangOpts().CPlusPlus) {
6551 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6553 // If this is an explicit specialization of a static data member, check it.
6554 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6555 CheckMemberSpecialization(NewVD, Previous))
6556 NewVD->setInvalidDecl();
6558 // Merge the decl with the existing one if appropriate.
6559 if (!Previous.empty()) {
6560 if (Previous.isSingleResult() &&
6561 isa<FieldDecl>(Previous.getFoundDecl()) &&
6562 D.getCXXScopeSpec().isSet()) {
6563 // The user tried to define a non-static data member
6564 // out-of-line (C++ [dcl.meaning]p1).
6565 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6566 << D.getCXXScopeSpec().getRange();
6568 NewVD->setInvalidDecl();
6570 } else if (D.getCXXScopeSpec().isSet()) {
6571 // No previous declaration in the qualifying scope.
6572 Diag(D.getIdentifierLoc(), diag::err_no_member)
6573 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6574 << D.getCXXScopeSpec().getRange();
6575 NewVD->setInvalidDecl();
6578 if (!IsVariableTemplateSpecialization)
6579 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6581 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6582 // an explicit specialization (14.8.3) or a partial specialization of a
6583 // concept definition.
6584 if (IsVariableTemplateSpecialization &&
6585 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6586 Previous.isSingleResult()) {
6587 NamedDecl *PreviousDecl = Previous.getFoundDecl();
6588 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6589 if (VarTmpl->isConcept()) {
6590 Diag(NewVD->getLocation(), diag::err_concept_specialized)
6592 << (IsPartialSpecialization ? 2 /*partially specialized*/
6593 : 1 /*explicitly specialized*/);
6594 Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6595 NewVD->setInvalidDecl();
6601 VarTemplateDecl *PrevVarTemplate =
6602 NewVD->getPreviousDecl()
6603 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6606 // Check the template parameter list of this declaration, possibly
6607 // merging in the template parameter list from the previous variable
6608 // template declaration.
6609 if (CheckTemplateParameterList(
6611 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6613 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6614 DC->isDependentContext())
6615 ? TPC_ClassTemplateMember
6617 NewVD->setInvalidDecl();
6619 // If we are providing an explicit specialization of a static variable
6620 // template, make a note of that.
6621 if (PrevVarTemplate &&
6622 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6623 PrevVarTemplate->setMemberSpecialization();
6627 // Diagnose shadowed variables iff this isn't a redeclaration.
6628 if (ShadowedDecl && !D.isRedeclaration())
6629 CheckShadow(NewVD, ShadowedDecl, Previous);
6631 ProcessPragmaWeak(S, NewVD);
6633 // If this is the first declaration of an extern C variable, update
6634 // the map of such variables.
6635 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6636 isIncompleteDeclExternC(*this, NewVD))
6637 RegisterLocallyScopedExternCDecl(NewVD, S);
6639 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6640 Decl *ManglingContextDecl;
6641 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6642 NewVD->getDeclContext(), ManglingContextDecl)) {
6643 Context.setManglingNumber(
6644 NewVD, MCtx->getManglingNumber(
6645 NewVD, getMSManglingNumber(getLangOpts(), S)));
6646 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6650 // Special handling of variable named 'main'.
6651 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6652 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6653 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6655 // C++ [basic.start.main]p3
6656 // A program that declares a variable main at global scope is ill-formed.
6657 if (getLangOpts().CPlusPlus)
6658 Diag(D.getLocStart(), diag::err_main_global_variable);
6660 // In C, and external-linkage variable named main results in undefined
6662 else if (NewVD->hasExternalFormalLinkage())
6663 Diag(D.getLocStart(), diag::warn_main_redefined);
6666 if (D.isRedeclaration() && !Previous.empty()) {
6667 checkDLLAttributeRedeclaration(
6668 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6669 IsMemberSpecialization, D.isFunctionDefinition());
6673 if (NewVD->isInvalidDecl())
6674 NewTemplate->setInvalidDecl();
6675 ActOnDocumentableDecl(NewTemplate);
6682 /// Enum describing the %select options in diag::warn_decl_shadow.
6683 enum ShadowedDeclKind {
6692 /// Determine what kind of declaration we're shadowing.
6693 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6694 const DeclContext *OldDC) {
6695 if (isa<TypeAliasDecl>(ShadowedDecl))
6697 else if (isa<TypedefDecl>(ShadowedDecl))
6699 else if (isa<RecordDecl>(OldDC))
6700 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6702 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6705 /// Return the location of the capture if the given lambda captures the given
6706 /// variable \p VD, or an invalid source location otherwise.
6707 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6708 const VarDecl *VD) {
6709 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6710 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6711 return Capture.getLocation();
6713 return SourceLocation();
6716 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6717 const LookupResult &R) {
6718 // Only diagnose if we're shadowing an unambiguous field or variable.
6719 if (R.getResultKind() != LookupResult::Found)
6722 // Return false if warning is ignored.
6723 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6726 /// \brief Return the declaration shadowed by the given variable \p D, or null
6727 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6728 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6729 const LookupResult &R) {
6730 if (!shouldWarnIfShadowedDecl(Diags, R))
6733 // Don't diagnose declarations at file scope.
6734 if (D->hasGlobalStorage())
6737 NamedDecl *ShadowedDecl = R.getFoundDecl();
6738 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6743 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6744 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6745 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6746 const LookupResult &R) {
6747 // Don't warn if typedef declaration is part of a class
6748 if (D->getDeclContext()->isRecord())
6751 if (!shouldWarnIfShadowedDecl(Diags, R))
6754 NamedDecl *ShadowedDecl = R.getFoundDecl();
6755 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6758 /// \brief Diagnose variable or built-in function shadowing. Implements
6761 /// This method is called whenever a VarDecl is added to a "useful"
6764 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6765 /// \param R the lookup of the name
6767 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6768 const LookupResult &R) {
6769 DeclContext *NewDC = D->getDeclContext();
6771 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6772 // Fields are not shadowed by variables in C++ static methods.
6773 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6777 // Fields shadowed by constructor parameters are a special case. Usually
6778 // the constructor initializes the field with the parameter.
6779 if (isa<CXXConstructorDecl>(NewDC))
6780 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6781 // Remember that this was shadowed so we can either warn about its
6782 // modification or its existence depending on warning settings.
6783 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6788 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6789 if (shadowedVar->isExternC()) {
6790 // For shadowing external vars, make sure that we point to the global
6791 // declaration, not a locally scoped extern declaration.
6792 for (auto I : shadowedVar->redecls())
6793 if (I->isFileVarDecl()) {
6799 DeclContext *OldDC = ShadowedDecl->getDeclContext();
6801 unsigned WarningDiag = diag::warn_decl_shadow;
6802 SourceLocation CaptureLoc;
6803 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6804 isa<CXXMethodDecl>(NewDC)) {
6805 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6806 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6807 if (RD->getLambdaCaptureDefault() == LCD_None) {
6808 // Try to avoid warnings for lambdas with an explicit capture list.
6809 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6810 // Warn only when the lambda captures the shadowed decl explicitly.
6811 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6812 if (CaptureLoc.isInvalid())
6813 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6815 // Remember that this was shadowed so we can avoid the warning if the
6816 // shadowed decl isn't captured and the warning settings allow it.
6817 cast<LambdaScopeInfo>(getCurFunction())
6818 ->ShadowingDecls.push_back(
6819 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6826 // Only warn about certain kinds of shadowing for class members.
6827 if (NewDC && NewDC->isRecord()) {
6828 // In particular, don't warn about shadowing non-class members.
6829 if (!OldDC->isRecord())
6832 // TODO: should we warn about static data members shadowing
6833 // static data members from base classes?
6835 // TODO: don't diagnose for inaccessible shadowed members.
6836 // This is hard to do perfectly because we might friend the
6837 // shadowing context, but that's just a false negative.
6841 DeclarationName Name = R.getLookupName();
6843 // Emit warning and note.
6844 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6846 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6847 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6848 if (!CaptureLoc.isInvalid())
6849 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6850 << Name << /*explicitly*/ 1;
6851 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6854 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6855 /// when these variables are captured by the lambda.
6856 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6857 for (const auto &Shadow : LSI->ShadowingDecls) {
6858 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6859 // Try to avoid the warning when the shadowed decl isn't captured.
6860 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6861 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6862 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6863 ? diag::warn_decl_shadow_uncaptured_local
6864 : diag::warn_decl_shadow)
6865 << Shadow.VD->getDeclName()
6866 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6867 if (!CaptureLoc.isInvalid())
6868 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6869 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6870 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6874 /// \brief Check -Wshadow without the advantage of a previous lookup.
6875 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6876 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6879 LookupResult R(*this, D->getDeclName(), D->getLocation(),
6880 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6882 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6883 CheckShadow(D, ShadowedDecl, R);
6886 /// Check if 'E', which is an expression that is about to be modified, refers
6887 /// to a constructor parameter that shadows a field.
6888 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6889 // Quickly ignore expressions that can't be shadowing ctor parameters.
6890 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6892 E = E->IgnoreParenImpCasts();
6893 auto *DRE = dyn_cast<DeclRefExpr>(E);
6896 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6897 auto I = ShadowingDecls.find(D);
6898 if (I == ShadowingDecls.end())
6900 const NamedDecl *ShadowedDecl = I->second;
6901 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6902 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6903 Diag(D->getLocation(), diag::note_var_declared_here) << D;
6904 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6906 // Avoid issuing multiple warnings about the same decl.
6907 ShadowingDecls.erase(I);
6910 /// Check for conflict between this global or extern "C" declaration and
6911 /// previous global or extern "C" declarations. This is only used in C++.
6912 template<typename T>
6913 static bool checkGlobalOrExternCConflict(
6914 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6915 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6916 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6918 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6919 // The common case: this global doesn't conflict with any extern "C"
6925 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6926 // Both the old and new declarations have C language linkage. This is a
6929 Previous.addDecl(Prev);
6933 // This is a global, non-extern "C" declaration, and there is a previous
6934 // non-global extern "C" declaration. Diagnose if this is a variable
6936 if (!isa<VarDecl>(ND))
6939 // The declaration is extern "C". Check for any declaration in the
6940 // translation unit which might conflict.
6942 // We have already performed the lookup into the translation unit.
6944 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6946 if (isa<VarDecl>(*I)) {
6952 DeclContext::lookup_result R =
6953 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6954 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6956 if (isa<VarDecl>(*I)) {
6960 // FIXME: If we have any other entity with this name in global scope,
6961 // the declaration is ill-formed, but that is a defect: it breaks the
6962 // 'stat' hack, for instance. Only variables can have mangled name
6963 // clashes with extern "C" declarations, so only they deserve a
6972 // Use the first declaration's location to ensure we point at something which
6973 // is lexically inside an extern "C" linkage-spec.
6974 assert(Prev && "should have found a previous declaration to diagnose");
6975 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6976 Prev = FD->getFirstDecl();
6978 Prev = cast<VarDecl>(Prev)->getFirstDecl();
6980 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6982 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6987 /// Apply special rules for handling extern "C" declarations. Returns \c true
6988 /// if we have found that this is a redeclaration of some prior entity.
6990 /// Per C++ [dcl.link]p6:
6991 /// Two declarations [for a function or variable] with C language linkage
6992 /// with the same name that appear in different scopes refer to the same
6993 /// [entity]. An entity with C language linkage shall not be declared with
6994 /// the same name as an entity in global scope.
6995 template<typename T>
6996 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6997 LookupResult &Previous) {
6998 if (!S.getLangOpts().CPlusPlus) {
6999 // In C, when declaring a global variable, look for a corresponding 'extern'
7000 // variable declared in function scope. We don't need this in C++, because
7001 // we find local extern decls in the surrounding file-scope DeclContext.
7002 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7003 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7005 Previous.addDecl(Prev);
7012 // A declaration in the translation unit can conflict with an extern "C"
7014 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7015 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7017 // An extern "C" declaration can conflict with a declaration in the
7018 // translation unit or can be a redeclaration of an extern "C" declaration
7019 // in another scope.
7020 if (isIncompleteDeclExternC(S,ND))
7021 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7023 // Neither global nor extern "C": nothing to do.
7027 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7028 // If the decl is already known invalid, don't check it.
7029 if (NewVD->isInvalidDecl())
7032 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7033 QualType T = TInfo->getType();
7035 // Defer checking an 'auto' type until its initializer is attached.
7036 if (T->isUndeducedType())
7039 if (NewVD->hasAttrs())
7040 CheckAlignasUnderalignment(NewVD);
7042 if (T->isObjCObjectType()) {
7043 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7044 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7045 T = Context.getObjCObjectPointerType(T);
7049 // Emit an error if an address space was applied to decl with local storage.
7050 // This includes arrays of objects with address space qualifiers, but not
7051 // automatic variables that point to other address spaces.
7052 // ISO/IEC TR 18037 S5.1.2
7053 if (!getLangOpts().OpenCL
7054 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7055 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
7056 NewVD->setInvalidDecl();
7060 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7062 if (getLangOpts().OpenCLVersion == 120 &&
7063 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7064 NewVD->isStaticLocal()) {
7065 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7066 NewVD->setInvalidDecl();
7070 if (getLangOpts().OpenCL) {
7071 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7072 if (NewVD->hasAttr<BlocksAttr>()) {
7073 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7077 if (T->isBlockPointerType()) {
7078 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7079 // can't use 'extern' storage class.
7080 if (!T.isConstQualified()) {
7081 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7083 NewVD->setInvalidDecl();
7086 if (NewVD->hasExternalStorage()) {
7087 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7088 NewVD->setInvalidDecl();
7092 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7093 // __constant address space.
7094 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7095 // variables inside a function can also be declared in the global
7097 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7098 NewVD->hasExternalStorage()) {
7099 if (!T->isSamplerT() &&
7100 !(T.getAddressSpace() == LangAS::opencl_constant ||
7101 (T.getAddressSpace() == LangAS::opencl_global &&
7102 getLangOpts().OpenCLVersion == 200))) {
7103 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7104 if (getLangOpts().OpenCLVersion == 200)
7105 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7106 << Scope << "global or constant";
7108 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7109 << Scope << "constant";
7110 NewVD->setInvalidDecl();
7114 if (T.getAddressSpace() == LangAS::opencl_global) {
7115 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7116 << 1 /*is any function*/ << "global";
7117 NewVD->setInvalidDecl();
7120 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7122 if (T.getAddressSpace() == LangAS::opencl_constant ||
7123 T.getAddressSpace() == LangAS::opencl_local) {
7124 FunctionDecl *FD = getCurFunctionDecl();
7125 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7126 if (T.getAddressSpace() == LangAS::opencl_constant)
7127 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7128 << 0 /*non-kernel only*/ << "constant";
7130 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7131 << 0 /*non-kernel only*/ << "local";
7132 NewVD->setInvalidDecl();
7139 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7140 && !NewVD->hasAttr<BlocksAttr>()) {
7141 if (getLangOpts().getGC() != LangOptions::NonGC)
7142 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7144 assert(!getLangOpts().ObjCAutoRefCount);
7145 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7149 bool isVM = T->isVariablyModifiedType();
7150 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7151 NewVD->hasAttr<BlocksAttr>())
7152 getCurFunction()->setHasBranchProtectedScope();
7154 if ((isVM && NewVD->hasLinkage()) ||
7155 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7156 bool SizeIsNegative;
7157 llvm::APSInt Oversized;
7158 TypeSourceInfo *FixedTInfo =
7159 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7160 SizeIsNegative, Oversized);
7161 if (!FixedTInfo && T->isVariableArrayType()) {
7162 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7163 // FIXME: This won't give the correct result for
7165 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7167 if (NewVD->isFileVarDecl())
7168 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7170 else if (NewVD->isStaticLocal())
7171 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7174 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7176 NewVD->setInvalidDecl();
7181 if (NewVD->isFileVarDecl())
7182 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7184 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7185 NewVD->setInvalidDecl();
7189 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7190 NewVD->setType(FixedTInfo->getType());
7191 NewVD->setTypeSourceInfo(FixedTInfo);
7194 if (T->isVoidType()) {
7195 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7196 // of objects and functions.
7197 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7198 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7200 NewVD->setInvalidDecl();
7205 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7206 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7207 NewVD->setInvalidDecl();
7211 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7212 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7213 NewVD->setInvalidDecl();
7217 if (NewVD->isConstexpr() && !T->isDependentType() &&
7218 RequireLiteralType(NewVD->getLocation(), T,
7219 diag::err_constexpr_var_non_literal)) {
7220 NewVD->setInvalidDecl();
7225 /// \brief Perform semantic checking on a newly-created variable
7228 /// This routine performs all of the type-checking required for a
7229 /// variable declaration once it has been built. It is used both to
7230 /// check variables after they have been parsed and their declarators
7231 /// have been translated into a declaration, and to check variables
7232 /// that have been instantiated from a template.
7234 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7236 /// Returns true if the variable declaration is a redeclaration.
7237 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7238 CheckVariableDeclarationType(NewVD);
7240 // If the decl is already known invalid, don't check it.
7241 if (NewVD->isInvalidDecl())
7244 // If we did not find anything by this name, look for a non-visible
7245 // extern "C" declaration with the same name.
7246 if (Previous.empty() &&
7247 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7248 Previous.setShadowed();
7250 if (!Previous.empty()) {
7251 MergeVarDecl(NewVD, Previous);
7258 struct FindOverriddenMethod {
7260 CXXMethodDecl *Method;
7262 /// Member lookup function that determines whether a given C++
7263 /// method overrides a method in a base class, to be used with
7264 /// CXXRecordDecl::lookupInBases().
7265 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7266 RecordDecl *BaseRecord =
7267 Specifier->getType()->getAs<RecordType>()->getDecl();
7269 DeclarationName Name = Method->getDeclName();
7271 // FIXME: Do we care about other names here too?
7272 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7273 // We really want to find the base class destructor here.
7274 QualType T = S->Context.getTypeDeclType(BaseRecord);
7275 CanQualType CT = S->Context.getCanonicalType(T);
7277 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7280 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7281 Path.Decls = Path.Decls.slice(1)) {
7282 NamedDecl *D = Path.Decls.front();
7283 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7284 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7293 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7294 } // end anonymous namespace
7296 /// \brief Report an error regarding overriding, along with any relevant
7297 /// overriden methods.
7299 /// \param DiagID the primary error to report.
7300 /// \param MD the overriding method.
7301 /// \param OEK which overrides to include as notes.
7302 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7303 OverrideErrorKind OEK = OEK_All) {
7304 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7305 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7306 E = MD->end_overridden_methods();
7308 // This check (& the OEK parameter) could be replaced by a predicate, but
7309 // without lambdas that would be overkill. This is still nicer than writing
7310 // out the diag loop 3 times.
7311 if ((OEK == OEK_All) ||
7312 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7313 (OEK == OEK_Deleted && (*I)->isDeleted()))
7314 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7318 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7319 /// and if so, check that it's a valid override and remember it.
7320 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7321 // Look for methods in base classes that this method might override.
7323 FindOverriddenMethod FOM;
7326 bool hasDeletedOverridenMethods = false;
7327 bool hasNonDeletedOverridenMethods = false;
7328 bool AddedAny = false;
7329 if (DC->lookupInBases(FOM, Paths)) {
7330 for (auto *I : Paths.found_decls()) {
7331 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7332 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7333 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7334 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7335 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7336 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7337 hasDeletedOverridenMethods |= OldMD->isDeleted();
7338 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7345 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7346 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7348 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7349 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7356 // Struct for holding all of the extra arguments needed by
7357 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7358 struct ActOnFDArgs {
7361 MultiTemplateParamsArg TemplateParamLists;
7364 } // end anonymous namespace
7368 // Callback to only accept typo corrections that have a non-zero edit distance.
7369 // Also only accept corrections that have the same parent decl.
7370 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7372 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7373 CXXRecordDecl *Parent)
7374 : Context(Context), OriginalFD(TypoFD),
7375 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7377 bool ValidateCandidate(const TypoCorrection &candidate) override {
7378 if (candidate.getEditDistance() == 0)
7381 SmallVector<unsigned, 1> MismatchedParams;
7382 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7383 CDeclEnd = candidate.end();
7384 CDecl != CDeclEnd; ++CDecl) {
7385 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7387 if (FD && !FD->hasBody() &&
7388 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7389 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7390 CXXRecordDecl *Parent = MD->getParent();
7391 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7393 } else if (!ExpectedParent) {
7403 ASTContext &Context;
7404 FunctionDecl *OriginalFD;
7405 CXXRecordDecl *ExpectedParent;
7408 } // end anonymous namespace
7410 /// \brief Generate diagnostics for an invalid function redeclaration.
7412 /// This routine handles generating the diagnostic messages for an invalid
7413 /// function redeclaration, including finding possible similar declarations
7414 /// or performing typo correction if there are no previous declarations with
7417 /// Returns a NamedDecl iff typo correction was performed and substituting in
7418 /// the new declaration name does not cause new errors.
7419 static NamedDecl *DiagnoseInvalidRedeclaration(
7420 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7421 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7422 DeclarationName Name = NewFD->getDeclName();
7423 DeclContext *NewDC = NewFD->getDeclContext();
7424 SmallVector<unsigned, 1> MismatchedParams;
7425 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7426 TypoCorrection Correction;
7427 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7428 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7429 : diag::err_member_decl_does_not_match;
7430 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7431 IsLocalFriend ? Sema::LookupLocalFriendName
7432 : Sema::LookupOrdinaryName,
7433 Sema::ForRedeclaration);
7435 NewFD->setInvalidDecl();
7437 SemaRef.LookupName(Prev, S);
7439 SemaRef.LookupQualifiedName(Prev, NewDC);
7440 assert(!Prev.isAmbiguous() &&
7441 "Cannot have an ambiguity in previous-declaration lookup");
7442 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7443 if (!Prev.empty()) {
7444 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7445 Func != FuncEnd; ++Func) {
7446 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7448 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7449 // Add 1 to the index so that 0 can mean the mismatch didn't
7450 // involve a parameter
7452 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7453 NearMatches.push_back(std::make_pair(FD, ParamNum));
7456 // If the qualified name lookup yielded nothing, try typo correction
7457 } else if ((Correction = SemaRef.CorrectTypo(
7458 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7459 &ExtraArgs.D.getCXXScopeSpec(),
7460 llvm::make_unique<DifferentNameValidatorCCC>(
7461 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7462 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7463 // Set up everything for the call to ActOnFunctionDeclarator
7464 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7465 ExtraArgs.D.getIdentifierLoc());
7467 Previous.setLookupName(Correction.getCorrection());
7468 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7469 CDeclEnd = Correction.end();
7470 CDecl != CDeclEnd; ++CDecl) {
7471 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7472 if (FD && !FD->hasBody() &&
7473 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7474 Previous.addDecl(FD);
7477 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7480 // Retry building the function declaration with the new previous
7481 // declarations, and with errors suppressed.
7484 Sema::SFINAETrap Trap(SemaRef);
7486 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7487 // pieces need to verify the typo-corrected C++ declaration and hopefully
7488 // eliminate the need for the parameter pack ExtraArgs.
7489 Result = SemaRef.ActOnFunctionDeclarator(
7490 ExtraArgs.S, ExtraArgs.D,
7491 Correction.getCorrectionDecl()->getDeclContext(),
7492 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7493 ExtraArgs.AddToScope);
7495 if (Trap.hasErrorOccurred())
7500 // Determine which correction we picked.
7501 Decl *Canonical = Result->getCanonicalDecl();
7502 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7504 if ((*I)->getCanonicalDecl() == Canonical)
7505 Correction.setCorrectionDecl(*I);
7507 SemaRef.diagnoseTypo(
7509 SemaRef.PDiag(IsLocalFriend
7510 ? diag::err_no_matching_local_friend_suggest
7511 : diag::err_member_decl_does_not_match_suggest)
7512 << Name << NewDC << IsDefinition);
7516 // Pretend the typo correction never occurred
7517 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7518 ExtraArgs.D.getIdentifierLoc());
7519 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7521 Previous.setLookupName(Name);
7524 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7525 << Name << NewDC << IsDefinition << NewFD->getLocation();
7527 bool NewFDisConst = false;
7528 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7529 NewFDisConst = NewMD->isConst();
7531 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7532 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7533 NearMatch != NearMatchEnd; ++NearMatch) {
7534 FunctionDecl *FD = NearMatch->first;
7535 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7536 bool FDisConst = MD && MD->isConst();
7537 bool IsMember = MD || !IsLocalFriend;
7539 // FIXME: These notes are poorly worded for the local friend case.
7540 if (unsigned Idx = NearMatch->second) {
7541 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7542 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7543 if (Loc.isInvalid()) Loc = FD->getLocation();
7544 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7545 : diag::note_local_decl_close_param_match)
7546 << Idx << FDParam->getType()
7547 << NewFD->getParamDecl(Idx - 1)->getType();
7548 } else if (FDisConst != NewFDisConst) {
7549 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7550 << NewFDisConst << FD->getSourceRange().getEnd();
7552 SemaRef.Diag(FD->getLocation(),
7553 IsMember ? diag::note_member_def_close_match
7554 : diag::note_local_decl_close_match);
7559 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7560 switch (D.getDeclSpec().getStorageClassSpec()) {
7561 default: llvm_unreachable("Unknown storage class!");
7562 case DeclSpec::SCS_auto:
7563 case DeclSpec::SCS_register:
7564 case DeclSpec::SCS_mutable:
7565 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7566 diag::err_typecheck_sclass_func);
7567 D.getMutableDeclSpec().ClearStorageClassSpecs();
7570 case DeclSpec::SCS_unspecified: break;
7571 case DeclSpec::SCS_extern:
7572 if (D.getDeclSpec().isExternInLinkageSpec())
7575 case DeclSpec::SCS_static: {
7576 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7578 // The declaration of an identifier for a function that has
7579 // block scope shall have no explicit storage-class specifier
7580 // other than extern
7581 // See also (C++ [dcl.stc]p4).
7582 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7583 diag::err_static_block_func);
7588 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7591 // No explicit storage class has already been returned
7595 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7596 DeclContext *DC, QualType &R,
7597 TypeSourceInfo *TInfo,
7599 bool &IsVirtualOkay) {
7600 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7601 DeclarationName Name = NameInfo.getName();
7603 FunctionDecl *NewFD = nullptr;
7604 bool isInline = D.getDeclSpec().isInlineSpecified();
7606 if (!SemaRef.getLangOpts().CPlusPlus) {
7607 // Determine whether the function was written with a
7608 // prototype. This true when:
7609 // - there is a prototype in the declarator, or
7610 // - the type R of the function is some kind of typedef or other non-
7611 // attributed reference to a type name (which eventually refers to a
7614 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7615 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7617 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7618 D.getLocStart(), NameInfo, R,
7619 TInfo, SC, isInline,
7620 HasPrototype, false);
7621 if (D.isInvalidType())
7622 NewFD->setInvalidDecl();
7627 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7628 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7630 // Check that the return type is not an abstract class type.
7631 // For record types, this is done by the AbstractClassUsageDiagnoser once
7632 // the class has been completely parsed.
7633 if (!DC->isRecord() &&
7634 SemaRef.RequireNonAbstractType(
7635 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7636 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7639 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7640 // This is a C++ constructor declaration.
7641 assert(DC->isRecord() &&
7642 "Constructors can only be declared in a member context");
7644 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7645 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7646 D.getLocStart(), NameInfo,
7647 R, TInfo, isExplicit, isInline,
7648 /*isImplicitlyDeclared=*/false,
7651 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7652 // This is a C++ destructor declaration.
7653 if (DC->isRecord()) {
7654 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7655 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7656 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7657 SemaRef.Context, Record,
7659 NameInfo, R, TInfo, isInline,
7660 /*isImplicitlyDeclared=*/false);
7662 // If the class is complete, then we now create the implicit exception
7663 // specification. If the class is incomplete or dependent, we can't do
7665 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7666 Record->getDefinition() && !Record->isBeingDefined() &&
7667 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7668 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7671 IsVirtualOkay = true;
7675 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7678 // Create a FunctionDecl to satisfy the function definition parsing
7680 return FunctionDecl::Create(SemaRef.Context, DC,
7682 D.getIdentifierLoc(), Name, R, TInfo,
7684 /*hasPrototype=*/true, isConstexpr);
7687 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7688 if (!DC->isRecord()) {
7689 SemaRef.Diag(D.getIdentifierLoc(),
7690 diag::err_conv_function_not_member);
7694 SemaRef.CheckConversionDeclarator(D, R, SC);
7695 IsVirtualOkay = true;
7696 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7697 D.getLocStart(), NameInfo,
7698 R, TInfo, isInline, isExplicit,
7699 isConstexpr, SourceLocation());
7701 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7702 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7704 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7705 isExplicit, NameInfo, R, TInfo,
7707 } else if (DC->isRecord()) {
7708 // If the name of the function is the same as the name of the record,
7709 // then this must be an invalid constructor that has a return type.
7710 // (The parser checks for a return type and makes the declarator a
7711 // constructor if it has no return type).
7712 if (Name.getAsIdentifierInfo() &&
7713 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7714 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7715 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7716 << SourceRange(D.getIdentifierLoc());
7720 // This is a C++ method declaration.
7721 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7722 cast<CXXRecordDecl>(DC),
7723 D.getLocStart(), NameInfo, R,
7724 TInfo, SC, isInline,
7725 isConstexpr, SourceLocation());
7726 IsVirtualOkay = !Ret->isStatic();
7730 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7731 if (!isFriend && SemaRef.CurContext->isRecord())
7734 // Determine whether the function was written with a
7735 // prototype. This true when:
7736 // - we're in C++ (where every function has a prototype),
7737 return FunctionDecl::Create(SemaRef.Context, DC,
7739 NameInfo, R, TInfo, SC, isInline,
7740 true/*HasPrototype*/, isConstexpr);
7744 enum OpenCLParamType {
7748 InvalidAddrSpacePtrKernelParam,
7753 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7754 if (PT->isPointerType()) {
7755 QualType PointeeType = PT->getPointeeType();
7756 if (PointeeType->isPointerType())
7757 return PtrPtrKernelParam;
7758 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7759 PointeeType.getAddressSpace() == 0)
7760 return InvalidAddrSpacePtrKernelParam;
7761 return PtrKernelParam;
7764 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7765 // be used as builtin types.
7767 if (PT->isImageType())
7768 return PtrKernelParam;
7770 if (PT->isBooleanType())
7771 return InvalidKernelParam;
7774 return InvalidKernelParam;
7776 // OpenCL extension spec v1.2 s9.5:
7777 // This extension adds support for half scalar and vector types as built-in
7778 // types that can be used for arithmetic operations, conversions etc.
7779 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7780 return InvalidKernelParam;
7782 if (PT->isRecordType())
7783 return RecordKernelParam;
7785 return ValidKernelParam;
7788 static void checkIsValidOpenCLKernelParameter(
7792 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7793 QualType PT = Param->getType();
7795 // Cache the valid types we encounter to avoid rechecking structs that are
7797 if (ValidTypes.count(PT.getTypePtr()))
7800 switch (getOpenCLKernelParameterType(S, PT)) {
7801 case PtrPtrKernelParam:
7802 // OpenCL v1.2 s6.9.a:
7803 // A kernel function argument cannot be declared as a
7804 // pointer to a pointer type.
7805 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7809 case InvalidAddrSpacePtrKernelParam:
7810 // OpenCL v1.0 s6.5:
7811 // __kernel function arguments declared to be a pointer of a type can point
7812 // to one of the following address spaces only : __global, __local or
7814 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7818 // OpenCL v1.2 s6.9.k:
7819 // Arguments to kernel functions in a program cannot be declared with the
7820 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7821 // uintptr_t or a struct and/or union that contain fields declared to be
7822 // one of these built-in scalar types.
7824 case InvalidKernelParam:
7825 // OpenCL v1.2 s6.8 n:
7826 // A kernel function argument cannot be declared
7828 // Do not diagnose half type since it is diagnosed as invalid argument
7829 // type for any function elsewhere.
7830 if (!PT->isHalfType())
7831 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7835 case PtrKernelParam:
7836 case ValidKernelParam:
7837 ValidTypes.insert(PT.getTypePtr());
7840 case RecordKernelParam:
7844 // Track nested structs we will inspect
7845 SmallVector<const Decl *, 4> VisitStack;
7847 // Track where we are in the nested structs. Items will migrate from
7848 // VisitStack to HistoryStack as we do the DFS for bad field.
7849 SmallVector<const FieldDecl *, 4> HistoryStack;
7850 HistoryStack.push_back(nullptr);
7852 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7853 VisitStack.push_back(PD);
7855 assert(VisitStack.back() && "First decl null?");
7858 const Decl *Next = VisitStack.pop_back_val();
7860 assert(!HistoryStack.empty());
7861 // Found a marker, we have gone up a level
7862 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7863 ValidTypes.insert(Hist->getType().getTypePtr());
7868 // Adds everything except the original parameter declaration (which is not a
7869 // field itself) to the history stack.
7870 const RecordDecl *RD;
7871 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7872 HistoryStack.push_back(Field);
7873 RD = Field->getType()->castAs<RecordType>()->getDecl();
7875 RD = cast<RecordDecl>(Next);
7878 // Add a null marker so we know when we've gone back up a level
7879 VisitStack.push_back(nullptr);
7881 for (const auto *FD : RD->fields()) {
7882 QualType QT = FD->getType();
7884 if (ValidTypes.count(QT.getTypePtr()))
7887 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7888 if (ParamType == ValidKernelParam)
7891 if (ParamType == RecordKernelParam) {
7892 VisitStack.push_back(FD);
7896 // OpenCL v1.2 s6.9.p:
7897 // Arguments to kernel functions that are declared to be a struct or union
7898 // do not allow OpenCL objects to be passed as elements of the struct or
7900 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7901 ParamType == InvalidAddrSpacePtrKernelParam) {
7902 S.Diag(Param->getLocation(),
7903 diag::err_record_with_pointers_kernel_param)
7904 << PT->isUnionType()
7907 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7910 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7911 << PD->getDeclName();
7913 // We have an error, now let's go back up through history and show where
7914 // the offending field came from
7915 for (ArrayRef<const FieldDecl *>::const_iterator
7916 I = HistoryStack.begin() + 1,
7917 E = HistoryStack.end();
7919 const FieldDecl *OuterField = *I;
7920 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7921 << OuterField->getType();
7924 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7925 << QT->isPointerType()
7930 } while (!VisitStack.empty());
7933 /// Find the DeclContext in which a tag is implicitly declared if we see an
7934 /// elaborated type specifier in the specified context, and lookup finds
7936 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7937 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7938 DC = DC->getParent();
7942 /// Find the Scope in which a tag is implicitly declared if we see an
7943 /// elaborated type specifier in the specified context, and lookup finds
7945 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7946 while (S->isClassScope() ||
7947 (LangOpts.CPlusPlus &&
7948 S->isFunctionPrototypeScope()) ||
7949 ((S->getFlags() & Scope::DeclScope) == 0) ||
7950 (S->getEntity() && S->getEntity()->isTransparentContext()))
7956 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7957 TypeSourceInfo *TInfo, LookupResult &Previous,
7958 MultiTemplateParamsArg TemplateParamLists,
7960 QualType R = TInfo->getType();
7962 assert(R.getTypePtr()->isFunctionType());
7964 // TODO: consider using NameInfo for diagnostic.
7965 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7966 DeclarationName Name = NameInfo.getName();
7967 StorageClass SC = getFunctionStorageClass(*this, D);
7969 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7970 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7971 diag::err_invalid_thread)
7972 << DeclSpec::getSpecifierName(TSCS);
7974 if (D.isFirstDeclarationOfMember())
7975 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7976 D.getIdentifierLoc());
7978 bool isFriend = false;
7979 FunctionTemplateDecl *FunctionTemplate = nullptr;
7980 bool isMemberSpecialization = false;
7981 bool isFunctionTemplateSpecialization = false;
7983 bool isDependentClassScopeExplicitSpecialization = false;
7984 bool HasExplicitTemplateArgs = false;
7985 TemplateArgumentListInfo TemplateArgs;
7987 bool isVirtualOkay = false;
7989 DeclContext *OriginalDC = DC;
7990 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7992 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7994 if (!NewFD) return nullptr;
7996 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7997 NewFD->setTopLevelDeclInObjCContainer();
7999 // Set the lexical context. If this is a function-scope declaration, or has a
8000 // C++ scope specifier, or is the object of a friend declaration, the lexical
8001 // context will be different from the semantic context.
8002 NewFD->setLexicalDeclContext(CurContext);
8004 if (IsLocalExternDecl)
8005 NewFD->setLocalExternDecl();
8007 if (getLangOpts().CPlusPlus) {
8008 bool isInline = D.getDeclSpec().isInlineSpecified();
8009 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8010 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8011 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8012 bool isConcept = D.getDeclSpec().isConceptSpecified();
8013 isFriend = D.getDeclSpec().isFriendSpecified();
8014 if (isFriend && !isInline && D.isFunctionDefinition()) {
8015 // C++ [class.friend]p5
8016 // A function can be defined in a friend declaration of a
8017 // class . . . . Such a function is implicitly inline.
8018 NewFD->setImplicitlyInline();
8021 // If this is a method defined in an __interface, and is not a constructor
8022 // or an overloaded operator, then set the pure flag (isVirtual will already
8024 if (const CXXRecordDecl *Parent =
8025 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8026 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8027 NewFD->setPure(true);
8029 // C++ [class.union]p2
8030 // A union can have member functions, but not virtual functions.
8031 if (isVirtual && Parent->isUnion())
8032 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8035 SetNestedNameSpecifier(NewFD, D);
8036 isMemberSpecialization = false;
8037 isFunctionTemplateSpecialization = false;
8038 if (D.isInvalidType())
8039 NewFD->setInvalidDecl();
8041 // Match up the template parameter lists with the scope specifier, then
8042 // determine whether we have a template or a template specialization.
8043 bool Invalid = false;
8044 if (TemplateParameterList *TemplateParams =
8045 MatchTemplateParametersToScopeSpecifier(
8046 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8047 D.getCXXScopeSpec(),
8048 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8049 ? D.getName().TemplateId
8051 TemplateParamLists, isFriend, isMemberSpecialization,
8053 if (TemplateParams->size() > 0) {
8054 // This is a function template
8056 // Check that we can declare a template here.
8057 if (CheckTemplateDeclScope(S, TemplateParams))
8058 NewFD->setInvalidDecl();
8060 // A destructor cannot be a template.
8061 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8062 Diag(NewFD->getLocation(), diag::err_destructor_template);
8063 NewFD->setInvalidDecl();
8066 // If we're adding a template to a dependent context, we may need to
8067 // rebuilding some of the types used within the template parameter list,
8068 // now that we know what the current instantiation is.
8069 if (DC->isDependentContext()) {
8070 ContextRAII SavedContext(*this, DC);
8071 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8075 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8076 NewFD->getLocation(),
8077 Name, TemplateParams,
8079 FunctionTemplate->setLexicalDeclContext(CurContext);
8080 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8082 // For source fidelity, store the other template param lists.
8083 if (TemplateParamLists.size() > 1) {
8084 NewFD->setTemplateParameterListsInfo(Context,
8085 TemplateParamLists.drop_back(1));
8088 // This is a function template specialization.
8089 isFunctionTemplateSpecialization = true;
8090 // For source fidelity, store all the template param lists.
8091 if (TemplateParamLists.size() > 0)
8092 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8094 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8096 // We want to remove the "template<>", found here.
8097 SourceRange RemoveRange = TemplateParams->getSourceRange();
8099 // If we remove the template<> and the name is not a
8100 // template-id, we're actually silently creating a problem:
8101 // the friend declaration will refer to an untemplated decl,
8102 // and clearly the user wants a template specialization. So
8103 // we need to insert '<>' after the name.
8104 SourceLocation InsertLoc;
8105 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8106 InsertLoc = D.getName().getSourceRange().getEnd();
8107 InsertLoc = getLocForEndOfToken(InsertLoc);
8110 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8111 << Name << RemoveRange
8112 << FixItHint::CreateRemoval(RemoveRange)
8113 << FixItHint::CreateInsertion(InsertLoc, "<>");
8118 // All template param lists were matched against the scope specifier:
8119 // this is NOT (an explicit specialization of) a template.
8120 if (TemplateParamLists.size() > 0)
8121 // For source fidelity, store all the template param lists.
8122 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8126 NewFD->setInvalidDecl();
8127 if (FunctionTemplate)
8128 FunctionTemplate->setInvalidDecl();
8131 // C++ [dcl.fct.spec]p5:
8132 // The virtual specifier shall only be used in declarations of
8133 // nonstatic class member functions that appear within a
8134 // member-specification of a class declaration; see 10.3.
8136 if (isVirtual && !NewFD->isInvalidDecl()) {
8137 if (!isVirtualOkay) {
8138 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8139 diag::err_virtual_non_function);
8140 } else if (!CurContext->isRecord()) {
8141 // 'virtual' was specified outside of the class.
8142 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8143 diag::err_virtual_out_of_class)
8144 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8145 } else if (NewFD->getDescribedFunctionTemplate()) {
8146 // C++ [temp.mem]p3:
8147 // A member function template shall not be virtual.
8148 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8149 diag::err_virtual_member_function_template)
8150 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8152 // Okay: Add virtual to the method.
8153 NewFD->setVirtualAsWritten(true);
8156 if (getLangOpts().CPlusPlus14 &&
8157 NewFD->getReturnType()->isUndeducedType())
8158 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8161 if (getLangOpts().CPlusPlus14 &&
8162 (NewFD->isDependentContext() ||
8163 (isFriend && CurContext->isDependentContext())) &&
8164 NewFD->getReturnType()->isUndeducedType()) {
8165 // If the function template is referenced directly (for instance, as a
8166 // member of the current instantiation), pretend it has a dependent type.
8167 // This is not really justified by the standard, but is the only sane
8169 // FIXME: For a friend function, we have not marked the function as being
8170 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8171 const FunctionProtoType *FPT =
8172 NewFD->getType()->castAs<FunctionProtoType>();
8174 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8175 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8176 FPT->getExtProtoInfo()));
8179 // C++ [dcl.fct.spec]p3:
8180 // The inline specifier shall not appear on a block scope function
8182 if (isInline && !NewFD->isInvalidDecl()) {
8183 if (CurContext->isFunctionOrMethod()) {
8184 // 'inline' is not allowed on block scope function declaration.
8185 Diag(D.getDeclSpec().getInlineSpecLoc(),
8186 diag::err_inline_declaration_block_scope) << Name
8187 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8191 // C++ [dcl.fct.spec]p6:
8192 // The explicit specifier shall be used only in the declaration of a
8193 // constructor or conversion function within its class definition;
8194 // see 12.3.1 and 12.3.2.
8195 if (isExplicit && !NewFD->isInvalidDecl() &&
8196 !isa<CXXDeductionGuideDecl>(NewFD)) {
8197 if (!CurContext->isRecord()) {
8198 // 'explicit' was specified outside of the class.
8199 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8200 diag::err_explicit_out_of_class)
8201 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8202 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8203 !isa<CXXConversionDecl>(NewFD)) {
8204 // 'explicit' was specified on a function that wasn't a constructor
8205 // or conversion function.
8206 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8207 diag::err_explicit_non_ctor_or_conv_function)
8208 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8213 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8214 // are implicitly inline.
8215 NewFD->setImplicitlyInline();
8217 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8218 // be either constructors or to return a literal type. Therefore,
8219 // destructors cannot be declared constexpr.
8220 if (isa<CXXDestructorDecl>(NewFD))
8221 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8225 // This is a function concept.
8226 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8229 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8230 // applied only to the definition of a function template [...]
8231 if (!D.isFunctionDefinition()) {
8232 Diag(D.getDeclSpec().getConceptSpecLoc(),
8233 diag::err_function_concept_not_defined);
8234 NewFD->setInvalidDecl();
8237 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8238 // have no exception-specification and is treated as if it were specified
8239 // with noexcept(true) (15.4). [...]
8240 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8241 if (FPT->hasExceptionSpec()) {
8243 if (D.isFunctionDeclarator())
8244 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8245 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8246 << FixItHint::CreateRemoval(Range);
8247 NewFD->setInvalidDecl();
8249 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8252 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8253 // following restrictions:
8254 // - The declared return type shall have the type bool.
8255 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8256 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8257 NewFD->setInvalidDecl();
8260 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8261 // following restrictions:
8262 // - The declaration's parameter list shall be equivalent to an empty
8264 if (FPT->getNumParams() > 0 || FPT->isVariadic())
8265 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8268 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8269 // implicity defined to be a constexpr declaration (implicitly inline)
8270 NewFD->setImplicitlyInline();
8272 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8273 // be declared with the thread_local, inline, friend, or constexpr
8274 // specifiers, [...]
8276 Diag(D.getDeclSpec().getInlineSpecLoc(),
8277 diag::err_concept_decl_invalid_specifiers)
8279 NewFD->setInvalidDecl(true);
8283 Diag(D.getDeclSpec().getFriendSpecLoc(),
8284 diag::err_concept_decl_invalid_specifiers)
8286 NewFD->setInvalidDecl(true);
8290 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8291 diag::err_concept_decl_invalid_specifiers)
8293 NewFD->setInvalidDecl(true);
8296 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8297 // applied only to the definition of a function template or variable
8298 // template, declared in namespace scope.
8299 if (isFunctionTemplateSpecialization) {
8300 Diag(D.getDeclSpec().getConceptSpecLoc(),
8301 diag::err_concept_specified_specialization) << 1;
8302 NewFD->setInvalidDecl(true);
8307 // If __module_private__ was specified, mark the function accordingly.
8308 if (D.getDeclSpec().isModulePrivateSpecified()) {
8309 if (isFunctionTemplateSpecialization) {
8310 SourceLocation ModulePrivateLoc
8311 = D.getDeclSpec().getModulePrivateSpecLoc();
8312 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8314 << FixItHint::CreateRemoval(ModulePrivateLoc);
8316 NewFD->setModulePrivate();
8317 if (FunctionTemplate)
8318 FunctionTemplate->setModulePrivate();
8323 if (FunctionTemplate) {
8324 FunctionTemplate->setObjectOfFriendDecl();
8325 FunctionTemplate->setAccess(AS_public);
8327 NewFD->setObjectOfFriendDecl();
8328 NewFD->setAccess(AS_public);
8331 // If a function is defined as defaulted or deleted, mark it as such now.
8332 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8333 // definition kind to FDK_Definition.
8334 switch (D.getFunctionDefinitionKind()) {
8335 case FDK_Declaration:
8336 case FDK_Definition:
8340 NewFD->setDefaulted();
8344 NewFD->setDeletedAsWritten();
8348 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8349 D.isFunctionDefinition()) {
8350 // C++ [class.mfct]p2:
8351 // A member function may be defined (8.4) in its class definition, in
8352 // which case it is an inline member function (7.1.2)
8353 NewFD->setImplicitlyInline();
8356 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8357 !CurContext->isRecord()) {
8358 // C++ [class.static]p1:
8359 // A data or function member of a class may be declared static
8360 // in a class definition, in which case it is a static member of
8363 // Complain about the 'static' specifier if it's on an out-of-line
8364 // member function definition.
8365 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8366 diag::err_static_out_of_line)
8367 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8370 // C++11 [except.spec]p15:
8371 // A deallocation function with no exception-specification is treated
8372 // as if it were specified with noexcept(true).
8373 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8374 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8375 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8376 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8377 NewFD->setType(Context.getFunctionType(
8378 FPT->getReturnType(), FPT->getParamTypes(),
8379 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8382 // Filter out previous declarations that don't match the scope.
8383 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8384 D.getCXXScopeSpec().isNotEmpty() ||
8385 isMemberSpecialization ||
8386 isFunctionTemplateSpecialization);
8388 // Handle GNU asm-label extension (encoded as an attribute).
8389 if (Expr *E = (Expr*) D.getAsmLabel()) {
8390 // The parser guarantees this is a string.
8391 StringLiteral *SE = cast<StringLiteral>(E);
8392 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8393 SE->getString(), 0));
8394 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8395 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8396 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8397 if (I != ExtnameUndeclaredIdentifiers.end()) {
8398 if (isDeclExternC(NewFD)) {
8399 NewFD->addAttr(I->second);
8400 ExtnameUndeclaredIdentifiers.erase(I);
8402 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8403 << /*Variable*/0 << NewFD;
8407 // Copy the parameter declarations from the declarator D to the function
8408 // declaration NewFD, if they are available. First scavenge them into Params.
8409 SmallVector<ParmVarDecl*, 16> Params;
8411 if (D.isFunctionDeclarator(FTIIdx)) {
8412 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8414 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8415 // function that takes no arguments, not a function that takes a
8416 // single void argument.
8417 // We let through "const void" here because Sema::GetTypeForDeclarator
8418 // already checks for that case.
8419 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8420 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8421 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8422 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8423 Param->setDeclContext(NewFD);
8424 Params.push_back(Param);
8426 if (Param->isInvalidDecl())
8427 NewFD->setInvalidDecl();
8431 if (!getLangOpts().CPlusPlus) {
8432 // In C, find all the tag declarations from the prototype and move them
8433 // into the function DeclContext. Remove them from the surrounding tag
8434 // injection context of the function, which is typically but not always
8436 DeclContext *PrototypeTagContext =
8437 getTagInjectionContext(NewFD->getLexicalDeclContext());
8438 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8439 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8441 // We don't want to reparent enumerators. Look at their parent enum
8444 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8445 TD = cast<EnumDecl>(ECD->getDeclContext());
8449 DeclContext *TagDC = TD->getLexicalDeclContext();
8450 if (!TagDC->containsDecl(TD))
8452 TagDC->removeDecl(TD);
8453 TD->setDeclContext(NewFD);
8456 // Preserve the lexical DeclContext if it is not the surrounding tag
8457 // injection context of the FD. In this example, the semantic context of
8458 // E will be f and the lexical context will be S, while both the
8459 // semantic and lexical contexts of S will be f:
8460 // void f(struct S { enum E { a } f; } s);
8461 if (TagDC != PrototypeTagContext)
8462 TD->setLexicalDeclContext(TagDC);
8465 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8466 // When we're declaring a function with a typedef, typeof, etc as in the
8467 // following example, we'll need to synthesize (unnamed)
8468 // parameters for use in the declaration.
8471 // typedef void fn(int);
8475 // Synthesize a parameter for each argument type.
8476 for (const auto &AI : FT->param_types()) {
8477 ParmVarDecl *Param =
8478 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8479 Param->setScopeInfo(0, Params.size());
8480 Params.push_back(Param);
8483 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8484 "Should not need args for typedef of non-prototype fn");
8487 // Finally, we know we have the right number of parameters, install them.
8488 NewFD->setParams(Params);
8490 if (D.getDeclSpec().isNoreturnSpecified())
8492 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8495 // Functions returning a variably modified type violate C99 6.7.5.2p2
8496 // because all functions have linkage.
8497 if (!NewFD->isInvalidDecl() &&
8498 NewFD->getReturnType()->isVariablyModifiedType()) {
8499 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8500 NewFD->setInvalidDecl();
8503 // Apply an implicit SectionAttr if #pragma code_seg is active.
8504 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8505 !NewFD->hasAttr<SectionAttr>()) {
8507 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8508 CodeSegStack.CurrentValue->getString(),
8509 CodeSegStack.CurrentPragmaLocation));
8510 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8511 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8512 ASTContext::PSF_Read,
8514 NewFD->dropAttr<SectionAttr>();
8517 // Handle attributes.
8518 ProcessDeclAttributes(S, NewFD, D);
8520 if (getLangOpts().OpenCL) {
8521 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8522 // type declaration will generate a compilation error.
8523 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8524 if (AddressSpace == LangAS::opencl_local ||
8525 AddressSpace == LangAS::opencl_global ||
8526 AddressSpace == LangAS::opencl_constant) {
8527 Diag(NewFD->getLocation(),
8528 diag::err_opencl_return_value_with_address_space);
8529 NewFD->setInvalidDecl();
8533 if (!getLangOpts().CPlusPlus) {
8534 // Perform semantic checking on the function declaration.
8535 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8536 CheckMain(NewFD, D.getDeclSpec());
8538 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8539 CheckMSVCRTEntryPoint(NewFD);
8541 if (!NewFD->isInvalidDecl())
8542 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8543 isMemberSpecialization));
8544 else if (!Previous.empty())
8545 // Recover gracefully from an invalid redeclaration.
8546 D.setRedeclaration(true);
8547 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8548 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8549 "previous declaration set still overloaded");
8551 // Diagnose no-prototype function declarations with calling conventions that
8552 // don't support variadic calls. Only do this in C and do it after merging
8553 // possibly prototyped redeclarations.
8554 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8555 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8556 CallingConv CC = FT->getExtInfo().getCC();
8557 if (!supportsVariadicCall(CC)) {
8558 // Windows system headers sometimes accidentally use stdcall without
8559 // (void) parameters, so we relax this to a warning.
8561 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8562 Diag(NewFD->getLocation(), DiagID)
8563 << FunctionType::getNameForCallConv(CC);
8567 // C++11 [replacement.functions]p3:
8568 // The program's definitions shall not be specified as inline.
8570 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8572 // Suppress the diagnostic if the function is __attribute__((used)), since
8573 // that forces an external definition to be emitted.
8574 if (D.getDeclSpec().isInlineSpecified() &&
8575 NewFD->isReplaceableGlobalAllocationFunction() &&
8576 !NewFD->hasAttr<UsedAttr>())
8577 Diag(D.getDeclSpec().getInlineSpecLoc(),
8578 diag::ext_operator_new_delete_declared_inline)
8579 << NewFD->getDeclName();
8581 // If the declarator is a template-id, translate the parser's template
8582 // argument list into our AST format.
8583 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8584 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8585 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8586 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8587 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8588 TemplateId->NumArgs);
8589 translateTemplateArguments(TemplateArgsPtr,
8592 HasExplicitTemplateArgs = true;
8594 if (NewFD->isInvalidDecl()) {
8595 HasExplicitTemplateArgs = false;
8596 } else if (FunctionTemplate) {
8597 // Function template with explicit template arguments.
8598 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8599 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8601 HasExplicitTemplateArgs = false;
8603 assert((isFunctionTemplateSpecialization ||
8604 D.getDeclSpec().isFriendSpecified()) &&
8605 "should have a 'template<>' for this decl");
8606 // "friend void foo<>(int);" is an implicit specialization decl.
8607 isFunctionTemplateSpecialization = true;
8609 } else if (isFriend && isFunctionTemplateSpecialization) {
8610 // This combination is only possible in a recovery case; the user
8611 // wrote something like:
8612 // template <> friend void foo(int);
8613 // which we're recovering from as if the user had written:
8614 // friend void foo<>(int);
8615 // Go ahead and fake up a template id.
8616 HasExplicitTemplateArgs = true;
8617 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8618 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8621 // We do not add HD attributes to specializations here because
8622 // they may have different constexpr-ness compared to their
8623 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8624 // may end up with different effective targets. Instead, a
8625 // specialization inherits its target attributes from its template
8626 // in the CheckFunctionTemplateSpecialization() call below.
8627 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8628 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8630 // If it's a friend (and only if it's a friend), it's possible
8631 // that either the specialized function type or the specialized
8632 // template is dependent, and therefore matching will fail. In
8633 // this case, don't check the specialization yet.
8634 bool InstantiationDependent = false;
8635 if (isFunctionTemplateSpecialization && isFriend &&
8636 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8637 TemplateSpecializationType::anyDependentTemplateArguments(
8639 InstantiationDependent))) {
8640 assert(HasExplicitTemplateArgs &&
8641 "friend function specialization without template args");
8642 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8644 NewFD->setInvalidDecl();
8645 } else if (isFunctionTemplateSpecialization) {
8646 if (CurContext->isDependentContext() && CurContext->isRecord()
8648 isDependentClassScopeExplicitSpecialization = true;
8649 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8650 diag::ext_function_specialization_in_class :
8651 diag::err_function_specialization_in_class)
8652 << NewFD->getDeclName();
8653 } else if (CheckFunctionTemplateSpecialization(NewFD,
8654 (HasExplicitTemplateArgs ? &TemplateArgs
8657 NewFD->setInvalidDecl();
8660 // A storage-class-specifier shall not be specified in an explicit
8661 // specialization (14.7.3)
8662 FunctionTemplateSpecializationInfo *Info =
8663 NewFD->getTemplateSpecializationInfo();
8664 if (Info && SC != SC_None) {
8665 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8666 Diag(NewFD->getLocation(),
8667 diag::err_explicit_specialization_inconsistent_storage_class)
8669 << FixItHint::CreateRemoval(
8670 D.getDeclSpec().getStorageClassSpecLoc());
8673 Diag(NewFD->getLocation(),
8674 diag::ext_explicit_specialization_storage_class)
8675 << FixItHint::CreateRemoval(
8676 D.getDeclSpec().getStorageClassSpecLoc());
8678 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8679 if (CheckMemberSpecialization(NewFD, Previous))
8680 NewFD->setInvalidDecl();
8683 // Perform semantic checking on the function declaration.
8684 if (!isDependentClassScopeExplicitSpecialization) {
8685 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8686 CheckMain(NewFD, D.getDeclSpec());
8688 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8689 CheckMSVCRTEntryPoint(NewFD);
8691 if (!NewFD->isInvalidDecl())
8692 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8693 isMemberSpecialization));
8694 else if (!Previous.empty())
8695 // Recover gracefully from an invalid redeclaration.
8696 D.setRedeclaration(true);
8699 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8700 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8701 "previous declaration set still overloaded");
8703 NamedDecl *PrincipalDecl = (FunctionTemplate
8704 ? cast<NamedDecl>(FunctionTemplate)
8707 if (isFriend && NewFD->getPreviousDecl()) {
8708 AccessSpecifier Access = AS_public;
8709 if (!NewFD->isInvalidDecl())
8710 Access = NewFD->getPreviousDecl()->getAccess();
8712 NewFD->setAccess(Access);
8713 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8716 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8717 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8718 PrincipalDecl->setNonMemberOperator();
8720 // If we have a function template, check the template parameter
8721 // list. This will check and merge default template arguments.
8722 if (FunctionTemplate) {
8723 FunctionTemplateDecl *PrevTemplate =
8724 FunctionTemplate->getPreviousDecl();
8725 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8726 PrevTemplate ? PrevTemplate->getTemplateParameters()
8728 D.getDeclSpec().isFriendSpecified()
8729 ? (D.isFunctionDefinition()
8730 ? TPC_FriendFunctionTemplateDefinition
8731 : TPC_FriendFunctionTemplate)
8732 : (D.getCXXScopeSpec().isSet() &&
8733 DC && DC->isRecord() &&
8734 DC->isDependentContext())
8735 ? TPC_ClassTemplateMember
8736 : TPC_FunctionTemplate);
8739 if (NewFD->isInvalidDecl()) {
8740 // Ignore all the rest of this.
8741 } else if (!D.isRedeclaration()) {
8742 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8744 // Fake up an access specifier if it's supposed to be a class member.
8745 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8746 NewFD->setAccess(AS_public);
8748 // Qualified decls generally require a previous declaration.
8749 if (D.getCXXScopeSpec().isSet()) {
8750 // ...with the major exception of templated-scope or
8751 // dependent-scope friend declarations.
8753 // TODO: we currently also suppress this check in dependent
8754 // contexts because (1) the parameter depth will be off when
8755 // matching friend templates and (2) we might actually be
8756 // selecting a friend based on a dependent factor. But there
8757 // are situations where these conditions don't apply and we
8758 // can actually do this check immediately.
8760 (TemplateParamLists.size() ||
8761 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8762 CurContext->isDependentContext())) {
8765 // The user tried to provide an out-of-line definition for a
8766 // function that is a member of a class or namespace, but there
8767 // was no such member function declared (C++ [class.mfct]p2,
8768 // C++ [namespace.memdef]p2). For example:
8774 // void X::f() { } // ill-formed
8776 // Complain about this problem, and attempt to suggest close
8777 // matches (e.g., those that differ only in cv-qualifiers and
8778 // whether the parameter types are references).
8780 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8781 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8782 AddToScope = ExtraArgs.AddToScope;
8787 // Unqualified local friend declarations are required to resolve
8789 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8790 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8791 *this, Previous, NewFD, ExtraArgs, true, S)) {
8792 AddToScope = ExtraArgs.AddToScope;
8796 } else if (!D.isFunctionDefinition() &&
8797 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8798 !isFriend && !isFunctionTemplateSpecialization &&
8799 !isMemberSpecialization) {
8800 // An out-of-line member function declaration must also be a
8801 // definition (C++ [class.mfct]p2).
8802 // Note that this is not the case for explicit specializations of
8803 // function templates or member functions of class templates, per
8804 // C++ [temp.expl.spec]p2. We also allow these declarations as an
8805 // extension for compatibility with old SWIG code which likes to
8807 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8808 << D.getCXXScopeSpec().getRange();
8812 ProcessPragmaWeak(S, NewFD);
8813 checkAttributesAfterMerging(*this, *NewFD);
8815 AddKnownFunctionAttributes(NewFD);
8817 if (NewFD->hasAttr<OverloadableAttr>() &&
8818 !NewFD->getType()->getAs<FunctionProtoType>()) {
8819 Diag(NewFD->getLocation(),
8820 diag::err_attribute_overloadable_no_prototype)
8823 // Turn this into a variadic function with no parameters.
8824 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8825 FunctionProtoType::ExtProtoInfo EPI(
8826 Context.getDefaultCallingConvention(true, false));
8827 EPI.Variadic = true;
8828 EPI.ExtInfo = FT->getExtInfo();
8830 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8834 // If there's a #pragma GCC visibility in scope, and this isn't a class
8835 // member, set the visibility of this function.
8836 if (!DC->isRecord() && NewFD->isExternallyVisible())
8837 AddPushedVisibilityAttribute(NewFD);
8839 // If there's a #pragma clang arc_cf_code_audited in scope, consider
8840 // marking the function.
8841 AddCFAuditedAttribute(NewFD);
8843 // If this is a function definition, check if we have to apply optnone due to
8845 if(D.isFunctionDefinition())
8846 AddRangeBasedOptnone(NewFD);
8848 // If this is the first declaration of an extern C variable, update
8849 // the map of such variables.
8850 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8851 isIncompleteDeclExternC(*this, NewFD))
8852 RegisterLocallyScopedExternCDecl(NewFD, S);
8854 // Set this FunctionDecl's range up to the right paren.
8855 NewFD->setRangeEnd(D.getSourceRange().getEnd());
8857 if (D.isRedeclaration() && !Previous.empty()) {
8858 checkDLLAttributeRedeclaration(
8859 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8860 isMemberSpecialization || isFunctionTemplateSpecialization,
8861 D.isFunctionDefinition());
8864 if (getLangOpts().CUDA) {
8865 IdentifierInfo *II = NewFD->getIdentifier();
8866 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8867 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8868 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8869 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8871 Context.setcudaConfigureCallDecl(NewFD);
8874 // Variadic functions, other than a *declaration* of printf, are not allowed
8875 // in device-side CUDA code, unless someone passed
8876 // -fcuda-allow-variadic-functions.
8877 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8878 (NewFD->hasAttr<CUDADeviceAttr>() ||
8879 NewFD->hasAttr<CUDAGlobalAttr>()) &&
8880 !(II && II->isStr("printf") && NewFD->isExternC() &&
8881 !D.isFunctionDefinition())) {
8882 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8886 if (getLangOpts().CPlusPlus) {
8887 if (FunctionTemplate) {
8888 if (NewFD->isInvalidDecl())
8889 FunctionTemplate->setInvalidDecl();
8890 return FunctionTemplate;
8894 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8895 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8896 if ((getLangOpts().OpenCLVersion >= 120)
8897 && (SC == SC_Static)) {
8898 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8902 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8903 if (!NewFD->getReturnType()->isVoidType()) {
8904 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8905 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8906 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8911 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8912 for (auto Param : NewFD->parameters())
8913 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8915 for (const ParmVarDecl *Param : NewFD->parameters()) {
8916 QualType PT = Param->getType();
8918 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8920 if (getLangOpts().OpenCLVersion >= 200) {
8921 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8922 QualType ElemTy = PipeTy->getElementType();
8923 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8924 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8931 MarkUnusedFileScopedDecl(NewFD);
8933 // Here we have an function template explicit specialization at class scope.
8934 // The actually specialization will be postponed to template instatiation
8935 // time via the ClassScopeFunctionSpecializationDecl node.
8936 if (isDependentClassScopeExplicitSpecialization) {
8937 ClassScopeFunctionSpecializationDecl *NewSpec =
8938 ClassScopeFunctionSpecializationDecl::Create(
8939 Context, CurContext, SourceLocation(),
8940 cast<CXXMethodDecl>(NewFD),
8941 HasExplicitTemplateArgs, TemplateArgs);
8942 CurContext->addDecl(NewSpec);
8949 /// \brief Checks if the new declaration declared in dependent context must be
8950 /// put in the same redeclaration chain as the specified declaration.
8952 /// \param D Declaration that is checked.
8953 /// \param PrevDecl Previous declaration found with proper lookup method for the
8954 /// same declaration name.
8955 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8958 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8959 // Any declarations should be put into redeclaration chains except for
8960 // friend declaration in a dependent context that names a function in
8963 // This allows to compile code like:
8966 // template<typename T> class C1 { friend void func() { } };
8967 // template<typename T> class C2 { friend void func() { } };
8969 // This code snippet is a valid code unless both templates are instantiated.
8970 return !(D->getLexicalDeclContext()->isDependentContext() &&
8971 D->getDeclContext()->isFileContext() &&
8972 D->getFriendObjectKind() != Decl::FOK_None);
8975 /// \brief Perform semantic checking of a new function declaration.
8977 /// Performs semantic analysis of the new function declaration
8978 /// NewFD. This routine performs all semantic checking that does not
8979 /// require the actual declarator involved in the declaration, and is
8980 /// used both for the declaration of functions as they are parsed
8981 /// (called via ActOnDeclarator) and for the declaration of functions
8982 /// that have been instantiated via C++ template instantiation (called
8983 /// via InstantiateDecl).
8985 /// \param IsMemberSpecialization whether this new function declaration is
8986 /// a member specialization (that replaces any definition provided by the
8987 /// previous declaration).
8989 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8991 /// \returns true if the function declaration is a redeclaration.
8992 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8993 LookupResult &Previous,
8994 bool IsMemberSpecialization) {
8995 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8996 "Variably modified return types are not handled here");
8998 // Determine whether the type of this function should be merged with
8999 // a previous visible declaration. This never happens for functions in C++,
9000 // and always happens in C if the previous declaration was visible.
9001 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9002 !Previous.isShadowed();
9004 bool Redeclaration = false;
9005 NamedDecl *OldDecl = nullptr;
9007 // Merge or overload the declaration with an existing declaration of
9008 // the same name, if appropriate.
9009 if (!Previous.empty()) {
9010 // Determine whether NewFD is an overload of PrevDecl or
9011 // a declaration that requires merging. If it's an overload,
9012 // there's no more work to do here; we'll just add the new
9013 // function to the scope.
9014 if (!AllowOverloadingOfFunction(Previous, Context)) {
9015 NamedDecl *Candidate = Previous.getRepresentativeDecl();
9016 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9017 Redeclaration = true;
9018 OldDecl = Candidate;
9021 switch (CheckOverload(S, NewFD, Previous, OldDecl,
9022 /*NewIsUsingDecl*/ false)) {
9024 Redeclaration = true;
9027 case Ovl_NonFunction:
9028 Redeclaration = true;
9032 Redeclaration = false;
9036 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9037 // If a function name is overloadable in C, then every function
9038 // with that name must be marked "overloadable".
9039 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9040 << Redeclaration << NewFD;
9041 NamedDecl *OverloadedDecl =
9042 Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
9043 Diag(OverloadedDecl->getLocation(),
9044 diag::note_attribute_overloadable_prev_overload);
9045 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9050 // Check for a previous extern "C" declaration with this name.
9051 if (!Redeclaration &&
9052 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9053 if (!Previous.empty()) {
9054 // This is an extern "C" declaration with the same name as a previous
9055 // declaration, and thus redeclares that entity...
9056 Redeclaration = true;
9057 OldDecl = Previous.getFoundDecl();
9058 MergeTypeWithPrevious = false;
9060 // ... except in the presence of __attribute__((overloadable)).
9061 if (OldDecl->hasAttr<OverloadableAttr>()) {
9062 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9063 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9064 << Redeclaration << NewFD;
9065 Diag(Previous.getFoundDecl()->getLocation(),
9066 diag::note_attribute_overloadable_prev_overload);
9067 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9069 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9070 Redeclaration = false;
9077 // C++11 [dcl.constexpr]p8:
9078 // A constexpr specifier for a non-static member function that is not
9079 // a constructor declares that member function to be const.
9081 // This needs to be delayed until we know whether this is an out-of-line
9082 // definition of a static member function.
9084 // This rule is not present in C++1y, so we produce a backwards
9085 // compatibility warning whenever it happens in C++11.
9086 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9087 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9088 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9089 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9090 CXXMethodDecl *OldMD = nullptr;
9092 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9093 if (!OldMD || !OldMD->isStatic()) {
9094 const FunctionProtoType *FPT =
9095 MD->getType()->castAs<FunctionProtoType>();
9096 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9097 EPI.TypeQuals |= Qualifiers::Const;
9098 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9099 FPT->getParamTypes(), EPI));
9101 // Warn that we did this, if we're not performing template instantiation.
9102 // In that case, we'll have warned already when the template was defined.
9103 if (!inTemplateInstantiation()) {
9104 SourceLocation AddConstLoc;
9105 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9106 .IgnoreParens().getAs<FunctionTypeLoc>())
9107 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9109 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9110 << FixItHint::CreateInsertion(AddConstLoc, " const");
9115 if (Redeclaration) {
9116 // NewFD and OldDecl represent declarations that need to be
9118 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9119 NewFD->setInvalidDecl();
9120 return Redeclaration;
9124 Previous.addDecl(OldDecl);
9126 if (FunctionTemplateDecl *OldTemplateDecl
9127 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9128 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9129 FunctionTemplateDecl *NewTemplateDecl
9130 = NewFD->getDescribedFunctionTemplate();
9131 assert(NewTemplateDecl && "Template/non-template mismatch");
9132 if (CXXMethodDecl *Method
9133 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9134 Method->setAccess(OldTemplateDecl->getAccess());
9135 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9138 // If this is an explicit specialization of a member that is a function
9139 // template, mark it as a member specialization.
9140 if (IsMemberSpecialization &&
9141 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9142 NewTemplateDecl->setMemberSpecialization();
9143 assert(OldTemplateDecl->isMemberSpecialization());
9144 // Explicit specializations of a member template do not inherit deleted
9145 // status from the parent member template that they are specializing.
9146 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9147 FunctionDecl *const OldTemplatedDecl =
9148 OldTemplateDecl->getTemplatedDecl();
9149 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9150 OldTemplatedDecl->setDeletedAsWritten(false);
9155 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9156 // This needs to happen first so that 'inline' propagates.
9157 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9158 if (isa<CXXMethodDecl>(NewFD))
9159 NewFD->setAccess(OldDecl->getAccess());
9164 // Semantic checking for this function declaration (in isolation).
9166 if (getLangOpts().CPlusPlus) {
9167 // C++-specific checks.
9168 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9169 CheckConstructor(Constructor);
9170 } else if (CXXDestructorDecl *Destructor =
9171 dyn_cast<CXXDestructorDecl>(NewFD)) {
9172 CXXRecordDecl *Record = Destructor->getParent();
9173 QualType ClassType = Context.getTypeDeclType(Record);
9175 // FIXME: Shouldn't we be able to perform this check even when the class
9176 // type is dependent? Both gcc and edg can handle that.
9177 if (!ClassType->isDependentType()) {
9178 DeclarationName Name
9179 = Context.DeclarationNames.getCXXDestructorName(
9180 Context.getCanonicalType(ClassType));
9181 if (NewFD->getDeclName() != Name) {
9182 Diag(NewFD->getLocation(), diag::err_destructor_name);
9183 NewFD->setInvalidDecl();
9184 return Redeclaration;
9187 } else if (CXXConversionDecl *Conversion
9188 = dyn_cast<CXXConversionDecl>(NewFD)) {
9189 ActOnConversionDeclarator(Conversion);
9190 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9191 if (auto *TD = Guide->getDescribedFunctionTemplate())
9192 CheckDeductionGuideTemplate(TD);
9194 // A deduction guide is not on the list of entities that can be
9195 // explicitly specialized.
9196 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9197 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9198 << /*explicit specialization*/ 1;
9201 // Find any virtual functions that this function overrides.
9202 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9203 if (!Method->isFunctionTemplateSpecialization() &&
9204 !Method->getDescribedFunctionTemplate() &&
9205 Method->isCanonicalDecl()) {
9206 if (AddOverriddenMethods(Method->getParent(), Method)) {
9207 // If the function was marked as "static", we have a problem.
9208 if (NewFD->getStorageClass() == SC_Static) {
9209 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9214 if (Method->isStatic())
9215 checkThisInStaticMemberFunctionType(Method);
9218 // Extra checking for C++ overloaded operators (C++ [over.oper]).
9219 if (NewFD->isOverloadedOperator() &&
9220 CheckOverloadedOperatorDeclaration(NewFD)) {
9221 NewFD->setInvalidDecl();
9222 return Redeclaration;
9225 // Extra checking for C++0x literal operators (C++0x [over.literal]).
9226 if (NewFD->getLiteralIdentifier() &&
9227 CheckLiteralOperatorDeclaration(NewFD)) {
9228 NewFD->setInvalidDecl();
9229 return Redeclaration;
9232 // In C++, check default arguments now that we have merged decls. Unless
9233 // the lexical context is the class, because in this case this is done
9234 // during delayed parsing anyway.
9235 if (!CurContext->isRecord())
9236 CheckCXXDefaultArguments(NewFD);
9238 // If this function declares a builtin function, check the type of this
9239 // declaration against the expected type for the builtin.
9240 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9241 ASTContext::GetBuiltinTypeError Error;
9242 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9243 QualType T = Context.GetBuiltinType(BuiltinID, Error);
9244 // If the type of the builtin differs only in its exception
9245 // specification, that's OK.
9246 // FIXME: If the types do differ in this way, it would be better to
9247 // retain the 'noexcept' form of the type.
9249 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9251 // The type of this function differs from the type of the builtin,
9252 // so forget about the builtin entirely.
9253 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9256 // If this function is declared as being extern "C", then check to see if
9257 // the function returns a UDT (class, struct, or union type) that is not C
9258 // compatible, and if it does, warn the user.
9259 // But, issue any diagnostic on the first declaration only.
9260 if (Previous.empty() && NewFD->isExternC()) {
9261 QualType R = NewFD->getReturnType();
9262 if (R->isIncompleteType() && !R->isVoidType())
9263 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9265 else if (!R.isPODType(Context) && !R->isVoidType() &&
9266 !R->isObjCObjectPointerType())
9267 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9270 // C++1z [dcl.fct]p6:
9271 // [...] whether the function has a non-throwing exception-specification
9272 // [is] part of the function type
9274 // This results in an ABI break between C++14 and C++17 for functions whose
9275 // declared type includes an exception-specification in a parameter or
9276 // return type. (Exception specifications on the function itself are OK in
9277 // most cases, and exception specifications are not permitted in most other
9278 // contexts where they could make it into a mangling.)
9279 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9280 auto HasNoexcept = [&](QualType T) -> bool {
9281 // Strip off declarator chunks that could be between us and a function
9282 // type. We don't need to look far, exception specifications are very
9283 // restricted prior to C++17.
9284 if (auto *RT = T->getAs<ReferenceType>())
9285 T = RT->getPointeeType();
9286 else if (T->isAnyPointerType())
9287 T = T->getPointeeType();
9288 else if (auto *MPT = T->getAs<MemberPointerType>())
9289 T = MPT->getPointeeType();
9290 if (auto *FPT = T->getAs<FunctionProtoType>())
9291 if (FPT->isNothrow(Context))
9296 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9297 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9298 for (QualType T : FPT->param_types())
9299 AnyNoexcept |= HasNoexcept(T);
9301 Diag(NewFD->getLocation(),
9302 diag::warn_cxx1z_compat_exception_spec_in_signature)
9306 if (!Redeclaration && LangOpts.CUDA)
9307 checkCUDATargetOverload(NewFD, Previous);
9309 return Redeclaration;
9312 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9313 // C++11 [basic.start.main]p3:
9314 // A program that [...] declares main to be inline, static or
9315 // constexpr is ill-formed.
9316 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
9317 // appear in a declaration of main.
9318 // static main is not an error under C99, but we should warn about it.
9319 // We accept _Noreturn main as an extension.
9320 if (FD->getStorageClass() == SC_Static)
9321 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9322 ? diag::err_static_main : diag::warn_static_main)
9323 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9324 if (FD->isInlineSpecified())
9325 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9326 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9327 if (DS.isNoreturnSpecified()) {
9328 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9329 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9330 Diag(NoreturnLoc, diag::ext_noreturn_main);
9331 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9332 << FixItHint::CreateRemoval(NoreturnRange);
9334 if (FD->isConstexpr()) {
9335 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9336 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9337 FD->setConstexpr(false);
9340 if (getLangOpts().OpenCL) {
9341 Diag(FD->getLocation(), diag::err_opencl_no_main)
9342 << FD->hasAttr<OpenCLKernelAttr>();
9343 FD->setInvalidDecl();
9347 QualType T = FD->getType();
9348 assert(T->isFunctionType() && "function decl is not of function type");
9349 const FunctionType* FT = T->castAs<FunctionType>();
9351 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9352 // In C with GNU extensions we allow main() to have non-integer return
9353 // type, but we should warn about the extension, and we disable the
9354 // implicit-return-zero rule.
9356 // GCC in C mode accepts qualified 'int'.
9357 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9358 FD->setHasImplicitReturnZero(true);
9360 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9361 SourceRange RTRange = FD->getReturnTypeSourceRange();
9362 if (RTRange.isValid())
9363 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9364 << FixItHint::CreateReplacement(RTRange, "int");
9367 // In C and C++, main magically returns 0 if you fall off the end;
9368 // set the flag which tells us that.
9369 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9371 // All the standards say that main() should return 'int'.
9372 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9373 FD->setHasImplicitReturnZero(true);
9375 // Otherwise, this is just a flat-out error.
9376 SourceRange RTRange = FD->getReturnTypeSourceRange();
9377 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9378 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9380 FD->setInvalidDecl(true);
9384 // Treat protoless main() as nullary.
9385 if (isa<FunctionNoProtoType>(FT)) return;
9387 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9388 unsigned nparams = FTP->getNumParams();
9389 assert(FD->getNumParams() == nparams);
9391 bool HasExtraParameters = (nparams > 3);
9393 if (FTP->isVariadic()) {
9394 Diag(FD->getLocation(), diag::ext_variadic_main);
9395 // FIXME: if we had information about the location of the ellipsis, we
9396 // could add a FixIt hint to remove it as a parameter.
9399 // Darwin passes an undocumented fourth argument of type char**. If
9400 // other platforms start sprouting these, the logic below will start
9402 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9403 HasExtraParameters = false;
9405 if (HasExtraParameters) {
9406 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9407 FD->setInvalidDecl(true);
9411 // FIXME: a lot of the following diagnostics would be improved
9412 // if we had some location information about types.
9415 Context.getPointerType(Context.getPointerType(Context.CharTy));
9416 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9418 for (unsigned i = 0; i < nparams; ++i) {
9419 QualType AT = FTP->getParamType(i);
9421 bool mismatch = true;
9423 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9425 else if (Expected[i] == CharPP) {
9426 // As an extension, the following forms are okay:
9428 // char const * const *
9431 QualifierCollector qs;
9432 const PointerType* PT;
9433 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9434 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9435 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9438 mismatch = !qs.empty();
9443 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9444 // TODO: suggest replacing given type with expected type
9445 FD->setInvalidDecl(true);
9449 if (nparams == 1 && !FD->isInvalidDecl()) {
9450 Diag(FD->getLocation(), diag::warn_main_one_arg);
9453 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9454 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9455 FD->setInvalidDecl();
9459 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9460 QualType T = FD->getType();
9461 assert(T->isFunctionType() && "function decl is not of function type");
9462 const FunctionType *FT = T->castAs<FunctionType>();
9464 // Set an implicit return of 'zero' if the function can return some integral,
9465 // enumeration, pointer or nullptr type.
9466 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9467 FT->getReturnType()->isAnyPointerType() ||
9468 FT->getReturnType()->isNullPtrType())
9469 // DllMain is exempt because a return value of zero means it failed.
9470 if (FD->getName() != "DllMain")
9471 FD->setHasImplicitReturnZero(true);
9473 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9474 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9475 FD->setInvalidDecl();
9479 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9480 // FIXME: Need strict checking. In C89, we need to check for
9481 // any assignment, increment, decrement, function-calls, or
9482 // commas outside of a sizeof. In C99, it's the same list,
9483 // except that the aforementioned are allowed in unevaluated
9484 // expressions. Everything else falls under the
9485 // "may accept other forms of constant expressions" exception.
9486 // (We never end up here for C++, so the constant expression
9487 // rules there don't matter.)
9488 const Expr *Culprit;
9489 if (Init->isConstantInitializer(Context, false, &Culprit))
9491 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9492 << Culprit->getSourceRange();
9497 // Visits an initialization expression to see if OrigDecl is evaluated in
9498 // its own initialization and throws a warning if it does.
9499 class SelfReferenceChecker
9500 : public EvaluatedExprVisitor<SelfReferenceChecker> {
9505 bool isReferenceType;
9508 llvm::SmallVector<unsigned, 4> InitFieldIndex;
9511 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9513 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9514 S(S), OrigDecl(OrigDecl) {
9516 isRecordType = false;
9517 isReferenceType = false;
9519 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9520 isPODType = VD->getType().isPODType(S.Context);
9521 isRecordType = VD->getType()->isRecordType();
9522 isReferenceType = VD->getType()->isReferenceType();
9526 // For most expressions, just call the visitor. For initializer lists,
9527 // track the index of the field being initialized since fields are
9528 // initialized in order allowing use of previously initialized fields.
9529 void CheckExpr(Expr *E) {
9530 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9536 // Track and increment the index here.
9538 InitFieldIndex.push_back(0);
9539 for (auto Child : InitList->children()) {
9540 CheckExpr(cast<Expr>(Child));
9541 ++InitFieldIndex.back();
9543 InitFieldIndex.pop_back();
9546 // Returns true if MemberExpr is checked and no further checking is needed.
9547 // Returns false if additional checking is required.
9548 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9549 llvm::SmallVector<FieldDecl*, 4> Fields;
9551 bool ReferenceField = false;
9553 // Get the field memebers used.
9554 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9555 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9558 Fields.push_back(FD);
9559 if (FD->getType()->isReferenceType())
9560 ReferenceField = true;
9561 Base = ME->getBase()->IgnoreParenImpCasts();
9564 // Keep checking only if the base Decl is the same.
9565 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9566 if (!DRE || DRE->getDecl() != OrigDecl)
9569 // A reference field can be bound to an unininitialized field.
9570 if (CheckReference && !ReferenceField)
9573 // Convert FieldDecls to their index number.
9574 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9575 for (const FieldDecl *I : llvm::reverse(Fields))
9576 UsedFieldIndex.push_back(I->getFieldIndex());
9578 // See if a warning is needed by checking the first difference in index
9579 // numbers. If field being used has index less than the field being
9580 // initialized, then the use is safe.
9581 for (auto UsedIter = UsedFieldIndex.begin(),
9582 UsedEnd = UsedFieldIndex.end(),
9583 OrigIter = InitFieldIndex.begin(),
9584 OrigEnd = InitFieldIndex.end();
9585 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9586 if (*UsedIter < *OrigIter)
9588 if (*UsedIter > *OrigIter)
9592 // TODO: Add a different warning which will print the field names.
9593 HandleDeclRefExpr(DRE);
9597 // For most expressions, the cast is directly above the DeclRefExpr.
9598 // For conditional operators, the cast can be outside the conditional
9599 // operator if both expressions are DeclRefExpr's.
9600 void HandleValue(Expr *E) {
9601 E = E->IgnoreParens();
9602 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9603 HandleDeclRefExpr(DRE);
9607 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9608 Visit(CO->getCond());
9609 HandleValue(CO->getTrueExpr());
9610 HandleValue(CO->getFalseExpr());
9614 if (BinaryConditionalOperator *BCO =
9615 dyn_cast<BinaryConditionalOperator>(E)) {
9616 Visit(BCO->getCond());
9617 HandleValue(BCO->getFalseExpr());
9621 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9622 HandleValue(OVE->getSourceExpr());
9626 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9627 if (BO->getOpcode() == BO_Comma) {
9628 Visit(BO->getLHS());
9629 HandleValue(BO->getRHS());
9634 if (isa<MemberExpr>(E)) {
9636 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9637 false /*CheckReference*/))
9641 Expr *Base = E->IgnoreParenImpCasts();
9642 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9643 // Check for static member variables and don't warn on them.
9644 if (!isa<FieldDecl>(ME->getMemberDecl()))
9646 Base = ME->getBase()->IgnoreParenImpCasts();
9648 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9649 HandleDeclRefExpr(DRE);
9656 // Reference types not handled in HandleValue are handled here since all
9657 // uses of references are bad, not just r-value uses.
9658 void VisitDeclRefExpr(DeclRefExpr *E) {
9659 if (isReferenceType)
9660 HandleDeclRefExpr(E);
9663 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9664 if (E->getCastKind() == CK_LValueToRValue) {
9665 HandleValue(E->getSubExpr());
9669 Inherited::VisitImplicitCastExpr(E);
9672 void VisitMemberExpr(MemberExpr *E) {
9674 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9678 // Don't warn on arrays since they can be treated as pointers.
9679 if (E->getType()->canDecayToPointerType()) return;
9681 // Warn when a non-static method call is followed by non-static member
9682 // field accesses, which is followed by a DeclRefExpr.
9683 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9684 bool Warn = (MD && !MD->isStatic());
9685 Expr *Base = E->getBase()->IgnoreParenImpCasts();
9686 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9687 if (!isa<FieldDecl>(ME->getMemberDecl()))
9689 Base = ME->getBase()->IgnoreParenImpCasts();
9692 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9694 HandleDeclRefExpr(DRE);
9698 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9699 // Visit that expression.
9703 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9704 Expr *Callee = E->getCallee();
9706 if (isa<UnresolvedLookupExpr>(Callee))
9707 return Inherited::VisitCXXOperatorCallExpr(E);
9710 for (auto Arg: E->arguments())
9711 HandleValue(Arg->IgnoreParenImpCasts());
9714 void VisitUnaryOperator(UnaryOperator *E) {
9715 // For POD record types, addresses of its own members are well-defined.
9716 if (E->getOpcode() == UO_AddrOf && isRecordType &&
9717 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9719 HandleValue(E->getSubExpr());
9723 if (E->isIncrementDecrementOp()) {
9724 HandleValue(E->getSubExpr());
9728 Inherited::VisitUnaryOperator(E);
9731 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9733 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9734 if (E->getConstructor()->isCopyConstructor()) {
9735 Expr *ArgExpr = E->getArg(0);
9736 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9737 if (ILE->getNumInits() == 1)
9738 ArgExpr = ILE->getInit(0);
9739 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9740 if (ICE->getCastKind() == CK_NoOp)
9741 ArgExpr = ICE->getSubExpr();
9742 HandleValue(ArgExpr);
9745 Inherited::VisitCXXConstructExpr(E);
9748 void VisitCallExpr(CallExpr *E) {
9749 // Treat std::move as a use.
9750 if (E->getNumArgs() == 1) {
9751 if (FunctionDecl *FD = E->getDirectCallee()) {
9752 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9753 FD->getIdentifier()->isStr("move")) {
9754 HandleValue(E->getArg(0));
9760 Inherited::VisitCallExpr(E);
9763 void VisitBinaryOperator(BinaryOperator *E) {
9764 if (E->isCompoundAssignmentOp()) {
9765 HandleValue(E->getLHS());
9770 Inherited::VisitBinaryOperator(E);
9773 // A custom visitor for BinaryConditionalOperator is needed because the
9774 // regular visitor would check the condition and true expression separately
9775 // but both point to the same place giving duplicate diagnostics.
9776 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9777 Visit(E->getCond());
9778 Visit(E->getFalseExpr());
9781 void HandleDeclRefExpr(DeclRefExpr *DRE) {
9782 Decl* ReferenceDecl = DRE->getDecl();
9783 if (OrigDecl != ReferenceDecl) return;
9785 if (isReferenceType) {
9786 diag = diag::warn_uninit_self_reference_in_reference_init;
9787 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9788 diag = diag::warn_static_self_reference_in_init;
9789 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9790 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9791 DRE->getDecl()->getType()->isRecordType()) {
9792 diag = diag::warn_uninit_self_reference_in_init;
9794 // Local variables will be handled by the CFG analysis.
9798 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9800 << DRE->getNameInfo().getName()
9801 << OrigDecl->getLocation()
9802 << DRE->getSourceRange());
9806 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9807 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9809 // Parameters arguments are occassionially constructed with itself,
9810 // for instance, in recursive functions. Skip them.
9811 if (isa<ParmVarDecl>(OrigDecl))
9814 E = E->IgnoreParens();
9816 // Skip checking T a = a where T is not a record or reference type.
9817 // Doing so is a way to silence uninitialized warnings.
9818 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9819 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9820 if (ICE->getCastKind() == CK_LValueToRValue)
9821 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9822 if (DRE->getDecl() == OrigDecl)
9825 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9827 } // end anonymous namespace
9830 // Simple wrapper to add the name of a variable or (if no variable is
9831 // available) a DeclarationName into a diagnostic.
9832 struct VarDeclOrName {
9834 DeclarationName Name;
9836 friend const Sema::SemaDiagnosticBuilder &
9837 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9838 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9841 } // end anonymous namespace
9843 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9844 DeclarationName Name, QualType Type,
9845 TypeSourceInfo *TSI,
9846 SourceRange Range, bool DirectInit,
9848 bool IsInitCapture = !VDecl;
9849 assert((!VDecl || !VDecl->isInitCapture()) &&
9850 "init captures are expected to be deduced prior to initialization");
9852 VarDeclOrName VN{VDecl, Name};
9854 DeducedType *Deduced = Type->getContainedDeducedType();
9855 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
9857 // C++11 [dcl.spec.auto]p3
9859 assert(VDecl && "no init for init capture deduction?");
9860 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
9861 << VDecl->getDeclName() << Type;
9865 ArrayRef<Expr*> DeduceInits = Init;
9867 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
9868 DeduceInits = PL->exprs();
9871 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
9872 assert(VDecl && "non-auto type for init capture deduction?");
9873 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9874 InitializationKind Kind = InitializationKind::CreateForInit(
9875 VDecl->getLocation(), DirectInit, Init);
9876 // FIXME: Initialization should not be taking a mutable list of inits.
9877 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
9878 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
9883 if (auto *IL = dyn_cast<InitListExpr>(Init))
9884 DeduceInits = IL->inits();
9887 // Deduction only works if we have exactly one source expression.
9888 if (DeduceInits.empty()) {
9889 // It isn't possible to write this directly, but it is possible to
9890 // end up in this situation with "auto x(some_pack...);"
9891 Diag(Init->getLocStart(), IsInitCapture
9892 ? diag::err_init_capture_no_expression
9893 : diag::err_auto_var_init_no_expression)
9894 << VN << Type << Range;
9898 if (DeduceInits.size() > 1) {
9899 Diag(DeduceInits[1]->getLocStart(),
9900 IsInitCapture ? diag::err_init_capture_multiple_expressions
9901 : diag::err_auto_var_init_multiple_expressions)
9902 << VN << Type << Range;
9906 Expr *DeduceInit = DeduceInits[0];
9907 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9908 Diag(Init->getLocStart(), IsInitCapture
9909 ? diag::err_init_capture_paren_braces
9910 : diag::err_auto_var_init_paren_braces)
9911 << isa<InitListExpr>(Init) << VN << Type << Range;
9915 // Expressions default to 'id' when we're in a debugger.
9916 bool DefaultedAnyToId = false;
9917 if (getLangOpts().DebuggerCastResultToId &&
9918 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9919 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9920 if (Result.isInvalid()) {
9923 Init = Result.get();
9924 DefaultedAnyToId = true;
9927 // C++ [dcl.decomp]p1:
9928 // If the assignment-expression [...] has array type A and no ref-qualifier
9929 // is present, e has type cv A
9930 if (VDecl && isa<DecompositionDecl>(VDecl) &&
9931 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9932 DeduceInit->getType()->isConstantArrayType())
9933 return Context.getQualifiedType(DeduceInit->getType(),
9934 Type.getQualifiers());
9936 QualType DeducedType;
9937 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9939 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9940 else if (isa<InitListExpr>(Init))
9941 Diag(Range.getBegin(),
9942 diag::err_init_capture_deduction_failure_from_init_list)
9944 << (DeduceInit->getType().isNull() ? TSI->getType()
9945 : DeduceInit->getType())
9946 << DeduceInit->getSourceRange();
9948 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9949 << VN << TSI->getType()
9950 << (DeduceInit->getType().isNull() ? TSI->getType()
9951 : DeduceInit->getType())
9952 << DeduceInit->getSourceRange();
9955 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9956 // 'id' instead of a specific object type prevents most of our usual
9958 // We only want to warn outside of template instantiations, though:
9959 // inside a template, the 'id' could have come from a parameter.
9960 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
9961 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9962 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9963 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9969 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
9971 QualType DeducedType = deduceVarTypeFromInitializer(
9972 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
9973 VDecl->getSourceRange(), DirectInit, Init);
9974 if (DeducedType.isNull()) {
9975 VDecl->setInvalidDecl();
9979 VDecl->setType(DeducedType);
9980 assert(VDecl->isLinkageValid());
9982 // In ARC, infer lifetime.
9983 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9984 VDecl->setInvalidDecl();
9986 // If this is a redeclaration, check that the type we just deduced matches
9987 // the previously declared type.
9988 if (VarDecl *Old = VDecl->getPreviousDecl()) {
9989 // We never need to merge the type, because we cannot form an incomplete
9990 // array of auto, nor deduce such a type.
9991 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9994 // Check the deduced type is valid for a variable declaration.
9995 CheckVariableDeclarationType(VDecl);
9996 return VDecl->isInvalidDecl();
9999 /// AddInitializerToDecl - Adds the initializer Init to the
10000 /// declaration dcl. If DirectInit is true, this is C++ direct
10001 /// initialization rather than copy initialization.
10002 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10003 // If there is no declaration, there was an error parsing it. Just ignore
10004 // the initializer.
10005 if (!RealDecl || RealDecl->isInvalidDecl()) {
10006 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10011 // Pure-specifiers are handled in ActOnPureSpecifier.
10012 Diag(Method->getLocation(), diag::err_member_function_initialization)
10013 << Method->getDeclName() << Init->getSourceRange();
10014 Method->setInvalidDecl();
10018 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10020 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10021 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10022 RealDecl->setInvalidDecl();
10026 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10027 if (VDecl->getType()->isUndeducedType()) {
10028 // Attempt typo correction early so that the type of the init expression can
10029 // be deduced based on the chosen correction if the original init contains a
10031 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10032 if (!Res.isUsable()) {
10033 RealDecl->setInvalidDecl();
10038 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10042 // dllimport cannot be used on variable definitions.
10043 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10044 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10045 VDecl->setInvalidDecl();
10049 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10050 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10051 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10052 VDecl->setInvalidDecl();
10056 if (!VDecl->getType()->isDependentType()) {
10057 // A definition must end up with a complete type, which means it must be
10058 // complete with the restriction that an array type might be completed by
10059 // the initializer; note that later code assumes this restriction.
10060 QualType BaseDeclType = VDecl->getType();
10061 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10062 BaseDeclType = Array->getElementType();
10063 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10064 diag::err_typecheck_decl_incomplete_type)) {
10065 RealDecl->setInvalidDecl();
10069 // The variable can not have an abstract class type.
10070 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10071 diag::err_abstract_type_in_decl,
10072 AbstractVariableType))
10073 VDecl->setInvalidDecl();
10076 // If adding the initializer will turn this declaration into a definition,
10077 // and we already have a definition for this variable, diagnose or otherwise
10078 // handle the situation.
10080 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10081 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10082 !VDecl->isThisDeclarationADemotedDefinition() &&
10083 checkVarDeclRedefinition(Def, VDecl))
10086 if (getLangOpts().CPlusPlus) {
10087 // C++ [class.static.data]p4
10088 // If a static data member is of const integral or const
10089 // enumeration type, its declaration in the class definition can
10090 // specify a constant-initializer which shall be an integral
10091 // constant expression (5.19). In that case, the member can appear
10092 // in integral constant expressions. The member shall still be
10093 // defined in a namespace scope if it is used in the program and the
10094 // namespace scope definition shall not contain an initializer.
10096 // We already performed a redefinition check above, but for static
10097 // data members we also need to check whether there was an in-class
10098 // declaration with an initializer.
10099 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10100 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10101 << VDecl->getDeclName();
10102 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10103 diag::note_previous_initializer)
10108 if (VDecl->hasLocalStorage())
10109 getCurFunction()->setHasBranchProtectedScope();
10111 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10112 VDecl->setInvalidDecl();
10117 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10118 // a kernel function cannot be initialized."
10119 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10120 Diag(VDecl->getLocation(), diag::err_local_cant_init);
10121 VDecl->setInvalidDecl();
10125 // Get the decls type and save a reference for later, since
10126 // CheckInitializerTypes may change it.
10127 QualType DclT = VDecl->getType(), SavT = DclT;
10129 // Expressions default to 'id' when we're in a debugger
10130 // and we are assigning it to a variable of Objective-C pointer type.
10131 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10132 Init->getType() == Context.UnknownAnyTy) {
10133 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10134 if (Result.isInvalid()) {
10135 VDecl->setInvalidDecl();
10138 Init = Result.get();
10141 // Perform the initialization.
10142 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10143 if (!VDecl->isInvalidDecl()) {
10144 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10145 InitializationKind Kind = InitializationKind::CreateForInit(
10146 VDecl->getLocation(), DirectInit, Init);
10148 MultiExprArg Args = Init;
10150 Args = MultiExprArg(CXXDirectInit->getExprs(),
10151 CXXDirectInit->getNumExprs());
10153 // Try to correct any TypoExprs in the initialization arguments.
10154 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10155 ExprResult Res = CorrectDelayedTyposInExpr(
10156 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10157 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10158 return Init.Failed() ? ExprError() : E;
10160 if (Res.isInvalid()) {
10161 VDecl->setInvalidDecl();
10162 } else if (Res.get() != Args[Idx]) {
10163 Args[Idx] = Res.get();
10166 if (VDecl->isInvalidDecl())
10169 InitializationSequence InitSeq(*this, Entity, Kind, Args,
10170 /*TopLevelOfInitList=*/false,
10171 /*TreatUnavailableAsInvalid=*/false);
10172 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10173 if (Result.isInvalid()) {
10174 VDecl->setInvalidDecl();
10178 Init = Result.getAs<Expr>();
10181 // Check for self-references within variable initializers.
10182 // Variables declared within a function/method body (except for references)
10183 // are handled by a dataflow analysis.
10184 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10185 VDecl->getType()->isReferenceType()) {
10186 CheckSelfReference(*this, RealDecl, Init, DirectInit);
10189 // If the type changed, it means we had an incomplete type that was
10190 // completed by the initializer. For example:
10191 // int ary[] = { 1, 3, 5 };
10192 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10193 if (!VDecl->isInvalidDecl() && (DclT != SavT))
10194 VDecl->setType(DclT);
10196 if (!VDecl->isInvalidDecl()) {
10197 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10199 if (VDecl->hasAttr<BlocksAttr>())
10200 checkRetainCycles(VDecl, Init);
10202 // It is safe to assign a weak reference into a strong variable.
10203 // Although this code can still have problems:
10204 // id x = self.weakProp;
10205 // id y = self.weakProp;
10206 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10207 // paths through the function. This should be revisited if
10208 // -Wrepeated-use-of-weak is made flow-sensitive.
10209 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10210 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10211 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10212 Init->getLocStart()))
10213 getCurFunction()->markSafeWeakUse(Init);
10216 // The initialization is usually a full-expression.
10218 // FIXME: If this is a braced initialization of an aggregate, it is not
10219 // an expression, and each individual field initializer is a separate
10220 // full-expression. For instance, in:
10222 // struct Temp { ~Temp(); };
10223 // struct S { S(Temp); };
10224 // struct T { S a, b; } t = { Temp(), Temp() }
10226 // we should destroy the first Temp before constructing the second.
10227 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10229 VDecl->isConstexpr());
10230 if (Result.isInvalid()) {
10231 VDecl->setInvalidDecl();
10234 Init = Result.get();
10236 // Attach the initializer to the decl.
10237 VDecl->setInit(Init);
10239 if (VDecl->isLocalVarDecl()) {
10240 // C99 6.7.8p4: All the expressions in an initializer for an object that has
10241 // static storage duration shall be constant expressions or string literals.
10242 // C++ does not have this restriction.
10243 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10244 const Expr *Culprit;
10245 if (VDecl->getStorageClass() == SC_Static)
10246 CheckForConstantInitializer(Init, DclT);
10247 // C89 is stricter than C99 for non-static aggregate types.
10248 // C89 6.5.7p3: All the expressions [...] in an initializer list
10249 // for an object that has aggregate or union type shall be
10250 // constant expressions.
10251 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10252 isa<InitListExpr>(Init) &&
10253 !Init->isConstantInitializer(Context, false, &Culprit))
10254 Diag(Culprit->getExprLoc(),
10255 diag::ext_aggregate_init_not_constant)
10256 << Culprit->getSourceRange();
10258 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10259 VDecl->getLexicalDeclContext()->isRecord()) {
10260 // This is an in-class initialization for a static data member, e.g.,
10263 // static const int value = 17;
10266 // C++ [class.mem]p4:
10267 // A member-declarator can contain a constant-initializer only
10268 // if it declares a static member (9.4) of const integral or
10269 // const enumeration type, see 9.4.2.
10271 // C++11 [class.static.data]p3:
10272 // If a non-volatile non-inline const static data member is of integral
10273 // or enumeration type, its declaration in the class definition can
10274 // specify a brace-or-equal-initializer in which every initializer-clause
10275 // that is an assignment-expression is a constant expression. A static
10276 // data member of literal type can be declared in the class definition
10277 // with the constexpr specifier; if so, its declaration shall specify a
10278 // brace-or-equal-initializer in which every initializer-clause that is
10279 // an assignment-expression is a constant expression.
10281 // Do nothing on dependent types.
10282 if (DclT->isDependentType()) {
10284 // Allow any 'static constexpr' members, whether or not they are of literal
10285 // type. We separately check that every constexpr variable is of literal
10287 } else if (VDecl->isConstexpr()) {
10289 // Require constness.
10290 } else if (!DclT.isConstQualified()) {
10291 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10292 << Init->getSourceRange();
10293 VDecl->setInvalidDecl();
10295 // We allow integer constant expressions in all cases.
10296 } else if (DclT->isIntegralOrEnumerationType()) {
10297 // Check whether the expression is a constant expression.
10298 SourceLocation Loc;
10299 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10300 // In C++11, a non-constexpr const static data member with an
10301 // in-class initializer cannot be volatile.
10302 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10303 else if (Init->isValueDependent())
10304 ; // Nothing to check.
10305 else if (Init->isIntegerConstantExpr(Context, &Loc))
10306 ; // Ok, it's an ICE!
10307 else if (Init->isEvaluatable(Context)) {
10308 // If we can constant fold the initializer through heroics, accept it,
10309 // but report this as a use of an extension for -pedantic.
10310 Diag(Loc, diag::ext_in_class_initializer_non_constant)
10311 << Init->getSourceRange();
10313 // Otherwise, this is some crazy unknown case. Report the issue at the
10314 // location provided by the isIntegerConstantExpr failed check.
10315 Diag(Loc, diag::err_in_class_initializer_non_constant)
10316 << Init->getSourceRange();
10317 VDecl->setInvalidDecl();
10320 // We allow foldable floating-point constants as an extension.
10321 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10322 // In C++98, this is a GNU extension. In C++11, it is not, but we support
10323 // it anyway and provide a fixit to add the 'constexpr'.
10324 if (getLangOpts().CPlusPlus11) {
10325 Diag(VDecl->getLocation(),
10326 diag::ext_in_class_initializer_float_type_cxx11)
10327 << DclT << Init->getSourceRange();
10328 Diag(VDecl->getLocStart(),
10329 diag::note_in_class_initializer_float_type_cxx11)
10330 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10332 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10333 << DclT << Init->getSourceRange();
10335 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10336 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10337 << Init->getSourceRange();
10338 VDecl->setInvalidDecl();
10342 // Suggest adding 'constexpr' in C++11 for literal types.
10343 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10344 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10345 << DclT << Init->getSourceRange()
10346 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10347 VDecl->setConstexpr(true);
10350 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10351 << DclT << Init->getSourceRange();
10352 VDecl->setInvalidDecl();
10354 } else if (VDecl->isFileVarDecl()) {
10355 // In C, extern is typically used to avoid tentative definitions when
10356 // declaring variables in headers, but adding an intializer makes it a
10357 // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10358 // In C++, extern is often used to give implictly static const variables
10359 // external linkage, so don't warn in that case. If selectany is present,
10360 // this might be header code intended for C and C++ inclusion, so apply the
10362 if (VDecl->getStorageClass() == SC_Extern &&
10363 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10364 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10365 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10366 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10367 Diag(VDecl->getLocation(), diag::warn_extern_init);
10369 // C99 6.7.8p4. All file scoped initializers need to be constant.
10370 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10371 CheckForConstantInitializer(Init, DclT);
10374 // We will represent direct-initialization similarly to copy-initialization:
10375 // int x(1); -as-> int x = 1;
10376 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10378 // Clients that want to distinguish between the two forms, can check for
10379 // direct initializer using VarDecl::getInitStyle().
10380 // A major benefit is that clients that don't particularly care about which
10381 // exactly form was it (like the CodeGen) can handle both cases without
10382 // special case code.
10385 // The form of initialization (using parentheses or '=') is generally
10386 // insignificant, but does matter when the entity being initialized has a
10388 if (CXXDirectInit) {
10389 assert(DirectInit && "Call-style initializer must be direct init.");
10390 VDecl->setInitStyle(VarDecl::CallInit);
10391 } else if (DirectInit) {
10392 // This must be list-initialization. No other way is direct-initialization.
10393 VDecl->setInitStyle(VarDecl::ListInit);
10396 CheckCompleteVariableDeclaration(VDecl);
10399 /// ActOnInitializerError - Given that there was an error parsing an
10400 /// initializer for the given declaration, try to return to some form
10402 void Sema::ActOnInitializerError(Decl *D) {
10403 // Our main concern here is re-establishing invariants like "a
10404 // variable's type is either dependent or complete".
10405 if (!D || D->isInvalidDecl()) return;
10407 VarDecl *VD = dyn_cast<VarDecl>(D);
10410 // Bindings are not usable if we can't make sense of the initializer.
10411 if (auto *DD = dyn_cast<DecompositionDecl>(D))
10412 for (auto *BD : DD->bindings())
10413 BD->setInvalidDecl();
10415 // Auto types are meaningless if we can't make sense of the initializer.
10416 if (ParsingInitForAutoVars.count(D)) {
10417 D->setInvalidDecl();
10421 QualType Ty = VD->getType();
10422 if (Ty->isDependentType()) return;
10424 // Require a complete type.
10425 if (RequireCompleteType(VD->getLocation(),
10426 Context.getBaseElementType(Ty),
10427 diag::err_typecheck_decl_incomplete_type)) {
10428 VD->setInvalidDecl();
10432 // Require a non-abstract type.
10433 if (RequireNonAbstractType(VD->getLocation(), Ty,
10434 diag::err_abstract_type_in_decl,
10435 AbstractVariableType)) {
10436 VD->setInvalidDecl();
10440 // Don't bother complaining about constructors or destructors,
10444 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10445 // If there is no declaration, there was an error parsing it. Just ignore it.
10449 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10450 QualType Type = Var->getType();
10452 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10453 if (isa<DecompositionDecl>(RealDecl)) {
10454 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10455 Var->setInvalidDecl();
10459 if (Type->isUndeducedType() &&
10460 DeduceVariableDeclarationType(Var, false, nullptr))
10463 // C++11 [class.static.data]p3: A static data member can be declared with
10464 // the constexpr specifier; if so, its declaration shall specify
10465 // a brace-or-equal-initializer.
10466 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10467 // the definition of a variable [...] or the declaration of a static data
10469 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10470 !Var->isThisDeclarationADemotedDefinition()) {
10471 if (Var->isStaticDataMember()) {
10472 // C++1z removes the relevant rule; the in-class declaration is always
10473 // a definition there.
10474 if (!getLangOpts().CPlusPlus1z) {
10475 Diag(Var->getLocation(),
10476 diag::err_constexpr_static_mem_var_requires_init)
10477 << Var->getDeclName();
10478 Var->setInvalidDecl();
10482 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10483 Var->setInvalidDecl();
10488 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
10489 // definition having the concept specifier is called a variable concept. A
10490 // concept definition refers to [...] a variable concept and its initializer.
10491 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10492 if (VTD->isConcept()) {
10493 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10494 Var->setInvalidDecl();
10499 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10501 if (!Var->isInvalidDecl() &&
10502 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10503 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10504 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10505 Var->setInvalidDecl();
10509 switch (Var->isThisDeclarationADefinition()) {
10510 case VarDecl::Definition:
10511 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10514 // We have an out-of-line definition of a static data member
10515 // that has an in-class initializer, so we type-check this like
10520 case VarDecl::DeclarationOnly:
10521 // It's only a declaration.
10523 // Block scope. C99 6.7p7: If an identifier for an object is
10524 // declared with no linkage (C99 6.2.2p6), the type for the
10525 // object shall be complete.
10526 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10527 !Var->hasLinkage() && !Var->isInvalidDecl() &&
10528 RequireCompleteType(Var->getLocation(), Type,
10529 diag::err_typecheck_decl_incomplete_type))
10530 Var->setInvalidDecl();
10532 // Make sure that the type is not abstract.
10533 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10534 RequireNonAbstractType(Var->getLocation(), Type,
10535 diag::err_abstract_type_in_decl,
10536 AbstractVariableType))
10537 Var->setInvalidDecl();
10538 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10539 Var->getStorageClass() == SC_PrivateExtern) {
10540 Diag(Var->getLocation(), diag::warn_private_extern);
10541 Diag(Var->getLocation(), diag::note_private_extern);
10546 case VarDecl::TentativeDefinition:
10547 // File scope. C99 6.9.2p2: A declaration of an identifier for an
10548 // object that has file scope without an initializer, and without a
10549 // storage-class specifier or with the storage-class specifier "static",
10550 // constitutes a tentative definition. Note: A tentative definition with
10551 // external linkage is valid (C99 6.2.2p5).
10552 if (!Var->isInvalidDecl()) {
10553 if (const IncompleteArrayType *ArrayT
10554 = Context.getAsIncompleteArrayType(Type)) {
10555 if (RequireCompleteType(Var->getLocation(),
10556 ArrayT->getElementType(),
10557 diag::err_illegal_decl_array_incomplete_type))
10558 Var->setInvalidDecl();
10559 } else if (Var->getStorageClass() == SC_Static) {
10560 // C99 6.9.2p3: If the declaration of an identifier for an object is
10561 // a tentative definition and has internal linkage (C99 6.2.2p3), the
10562 // declared type shall not be an incomplete type.
10563 // NOTE: code such as the following
10564 // static struct s;
10565 // struct s { int a; };
10566 // is accepted by gcc. Hence here we issue a warning instead of
10567 // an error and we do not invalidate the static declaration.
10568 // NOTE: to avoid multiple warnings, only check the first declaration.
10569 if (Var->isFirstDecl())
10570 RequireCompleteType(Var->getLocation(), Type,
10571 diag::ext_typecheck_decl_incomplete_type);
10575 // Record the tentative definition; we're done.
10576 if (!Var->isInvalidDecl())
10577 TentativeDefinitions.push_back(Var);
10581 // Provide a specific diagnostic for uninitialized variable
10582 // definitions with incomplete array type.
10583 if (Type->isIncompleteArrayType()) {
10584 Diag(Var->getLocation(),
10585 diag::err_typecheck_incomplete_array_needs_initializer);
10586 Var->setInvalidDecl();
10590 // Provide a specific diagnostic for uninitialized variable
10591 // definitions with reference type.
10592 if (Type->isReferenceType()) {
10593 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10594 << Var->getDeclName()
10595 << SourceRange(Var->getLocation(), Var->getLocation());
10596 Var->setInvalidDecl();
10600 // Do not attempt to type-check the default initializer for a
10601 // variable with dependent type.
10602 if (Type->isDependentType())
10605 if (Var->isInvalidDecl())
10608 if (!Var->hasAttr<AliasAttr>()) {
10609 if (RequireCompleteType(Var->getLocation(),
10610 Context.getBaseElementType(Type),
10611 diag::err_typecheck_decl_incomplete_type)) {
10612 Var->setInvalidDecl();
10619 // The variable can not have an abstract class type.
10620 if (RequireNonAbstractType(Var->getLocation(), Type,
10621 diag::err_abstract_type_in_decl,
10622 AbstractVariableType)) {
10623 Var->setInvalidDecl();
10627 // Check for jumps past the implicit initializer. C++0x
10628 // clarifies that this applies to a "variable with automatic
10629 // storage duration", not a "local variable".
10630 // C++11 [stmt.dcl]p3
10631 // A program that jumps from a point where a variable with automatic
10632 // storage duration is not in scope to a point where it is in scope is
10633 // ill-formed unless the variable has scalar type, class type with a
10634 // trivial default constructor and a trivial destructor, a cv-qualified
10635 // version of one of these types, or an array of one of the preceding
10636 // types and is declared without an initializer.
10637 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10638 if (const RecordType *Record
10639 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10640 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10641 // Mark the function for further checking even if the looser rules of
10642 // C++11 do not require such checks, so that we can diagnose
10643 // incompatibilities with C++98.
10644 if (!CXXRecord->isPOD())
10645 getCurFunction()->setHasBranchProtectedScope();
10649 // C++03 [dcl.init]p9:
10650 // If no initializer is specified for an object, and the
10651 // object is of (possibly cv-qualified) non-POD class type (or
10652 // array thereof), the object shall be default-initialized; if
10653 // the object is of const-qualified type, the underlying class
10654 // type shall have a user-declared default
10655 // constructor. Otherwise, if no initializer is specified for
10656 // a non- static object, the object and its subobjects, if
10657 // any, have an indeterminate initial value); if the object
10658 // or any of its subobjects are of const-qualified type, the
10659 // program is ill-formed.
10660 // C++0x [dcl.init]p11:
10661 // If no initializer is specified for an object, the object is
10662 // default-initialized; [...].
10663 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10664 InitializationKind Kind
10665 = InitializationKind::CreateDefault(Var->getLocation());
10667 InitializationSequence InitSeq(*this, Entity, Kind, None);
10668 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10669 if (Init.isInvalid())
10670 Var->setInvalidDecl();
10671 else if (Init.get()) {
10672 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10673 // This is important for template substitution.
10674 Var->setInitStyle(VarDecl::CallInit);
10677 CheckCompleteVariableDeclaration(Var);
10681 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10682 // If there is no declaration, there was an error parsing it. Ignore it.
10686 VarDecl *VD = dyn_cast<VarDecl>(D);
10688 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10689 D->setInvalidDecl();
10693 VD->setCXXForRangeDecl(true);
10695 // for-range-declaration cannot be given a storage class specifier.
10697 switch (VD->getStorageClass()) {
10706 case SC_PrivateExtern:
10717 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10718 << VD->getDeclName() << Error;
10719 D->setInvalidDecl();
10724 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10725 IdentifierInfo *Ident,
10726 ParsedAttributes &Attrs,
10727 SourceLocation AttrEnd) {
10728 // C++1y [stmt.iter]p1:
10729 // A range-based for statement of the form
10730 // for ( for-range-identifier : for-range-initializer ) statement
10731 // is equivalent to
10732 // for ( auto&& for-range-identifier : for-range-initializer ) statement
10733 DeclSpec DS(Attrs.getPool().getFactory());
10735 const char *PrevSpec;
10737 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10738 getPrintingPolicy());
10740 Declarator D(DS, Declarator::ForContext);
10741 D.SetIdentifier(Ident, IdentLoc);
10742 D.takeAttributes(Attrs, AttrEnd);
10744 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10745 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10746 EmptyAttrs, IdentLoc);
10747 Decl *Var = ActOnDeclarator(S, D);
10748 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10749 FinalizeDeclaration(Var);
10750 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10751 AttrEnd.isValid() ? AttrEnd : IdentLoc);
10754 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10755 if (var->isInvalidDecl()) return;
10757 if (getLangOpts().OpenCL) {
10758 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10760 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10762 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10764 var->setInvalidDecl();
10769 // In Objective-C, don't allow jumps past the implicit initialization of a
10770 // local retaining variable.
10771 if (getLangOpts().ObjC1 &&
10772 var->hasLocalStorage()) {
10773 switch (var->getType().getObjCLifetime()) {
10774 case Qualifiers::OCL_None:
10775 case Qualifiers::OCL_ExplicitNone:
10776 case Qualifiers::OCL_Autoreleasing:
10779 case Qualifiers::OCL_Weak:
10780 case Qualifiers::OCL_Strong:
10781 getCurFunction()->setHasBranchProtectedScope();
10786 // Warn about externally-visible variables being defined without a
10787 // prior declaration. We only want to do this for global
10788 // declarations, but we also specifically need to avoid doing it for
10789 // class members because the linkage of an anonymous class can
10790 // change if it's later given a typedef name.
10791 if (var->isThisDeclarationADefinition() &&
10792 var->getDeclContext()->getRedeclContext()->isFileContext() &&
10793 var->isExternallyVisible() && var->hasLinkage() &&
10794 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10795 var->getLocation())) {
10796 // Find a previous declaration that's not a definition.
10797 VarDecl *prev = var->getPreviousDecl();
10798 while (prev && prev->isThisDeclarationADefinition())
10799 prev = prev->getPreviousDecl();
10802 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10805 // Cache the result of checking for constant initialization.
10806 Optional<bool> CacheHasConstInit;
10807 const Expr *CacheCulprit;
10808 auto checkConstInit = [&]() mutable {
10809 if (!CacheHasConstInit)
10810 CacheHasConstInit = var->getInit()->isConstantInitializer(
10811 Context, var->getType()->isReferenceType(), &CacheCulprit);
10812 return *CacheHasConstInit;
10815 if (var->getTLSKind() == VarDecl::TLS_Static) {
10816 if (var->getType().isDestructedType()) {
10817 // GNU C++98 edits for __thread, [basic.start.term]p3:
10818 // The type of an object with thread storage duration shall not
10819 // have a non-trivial destructor.
10820 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10821 if (getLangOpts().CPlusPlus11)
10822 Diag(var->getLocation(), diag::note_use_thread_local);
10823 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10824 if (!checkConstInit()) {
10825 // GNU C++98 edits for __thread, [basic.start.init]p4:
10826 // An object of thread storage duration shall not require dynamic
10828 // FIXME: Need strict checking here.
10829 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10830 << CacheCulprit->getSourceRange();
10831 if (getLangOpts().CPlusPlus11)
10832 Diag(var->getLocation(), diag::note_use_thread_local);
10837 // Apply section attributes and pragmas to global variables.
10838 bool GlobalStorage = var->hasGlobalStorage();
10839 if (GlobalStorage && var->isThisDeclarationADefinition() &&
10840 !inTemplateInstantiation()) {
10841 PragmaStack<StringLiteral *> *Stack = nullptr;
10842 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10843 if (var->getType().isConstQualified())
10844 Stack = &ConstSegStack;
10845 else if (!var->getInit()) {
10846 Stack = &BSSSegStack;
10847 SectionFlags |= ASTContext::PSF_Write;
10849 Stack = &DataSegStack;
10850 SectionFlags |= ASTContext::PSF_Write;
10852 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10853 var->addAttr(SectionAttr::CreateImplicit(
10854 Context, SectionAttr::Declspec_allocate,
10855 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10857 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10858 if (UnifySection(SA->getName(), SectionFlags, var))
10859 var->dropAttr<SectionAttr>();
10861 // Apply the init_seg attribute if this has an initializer. If the
10862 // initializer turns out to not be dynamic, we'll end up ignoring this
10864 if (CurInitSeg && var->getInit())
10865 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10869 // All the following checks are C++ only.
10870 if (!getLangOpts().CPlusPlus) {
10871 // If this variable must be emitted, add it as an initializer for the
10873 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10874 Context.addModuleInitializer(ModuleScopes.back().Module, var);
10878 if (auto *DD = dyn_cast<DecompositionDecl>(var))
10879 CheckCompleteDecompositionDeclaration(DD);
10881 QualType type = var->getType();
10882 if (type->isDependentType()) return;
10884 // __block variables might require us to capture a copy-initializer.
10885 if (var->hasAttr<BlocksAttr>()) {
10886 // It's currently invalid to ever have a __block variable with an
10887 // array type; should we diagnose that here?
10889 // Regardless, we don't want to ignore array nesting when
10890 // constructing this copy.
10891 if (type->isStructureOrClassType()) {
10892 EnterExpressionEvaluationContext scope(
10893 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
10894 SourceLocation poi = var->getLocation();
10895 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10897 = PerformMoveOrCopyInitialization(
10898 InitializedEntity::InitializeBlock(poi, type, false),
10899 var, var->getType(), varRef, /*AllowNRVO=*/true);
10900 if (!result.isInvalid()) {
10901 result = MaybeCreateExprWithCleanups(result);
10902 Expr *init = result.getAs<Expr>();
10903 Context.setBlockVarCopyInits(var, init);
10908 Expr *Init = var->getInit();
10909 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10910 QualType baseType = Context.getBaseElementType(type);
10912 if (!var->getDeclContext()->isDependentContext() &&
10913 Init && !Init->isValueDependent()) {
10915 if (var->isConstexpr()) {
10916 SmallVector<PartialDiagnosticAt, 8> Notes;
10917 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10918 SourceLocation DiagLoc = var->getLocation();
10919 // If the note doesn't add any useful information other than a source
10920 // location, fold it into the primary diagnostic.
10921 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10922 diag::note_invalid_subexpr_in_const_expr) {
10923 DiagLoc = Notes[0].first;
10926 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10927 << var << Init->getSourceRange();
10928 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10929 Diag(Notes[I].first, Notes[I].second);
10931 } else if (var->isUsableInConstantExpressions(Context)) {
10932 // Check whether the initializer of a const variable of integral or
10933 // enumeration type is an ICE now, since we can't tell whether it was
10934 // initialized by a constant expression if we check later.
10935 var->checkInitIsICE();
10938 // Don't emit further diagnostics about constexpr globals since they
10939 // were just diagnosed.
10940 if (!var->isConstexpr() && GlobalStorage &&
10941 var->hasAttr<RequireConstantInitAttr>()) {
10942 // FIXME: Need strict checking in C++03 here.
10943 bool DiagErr = getLangOpts().CPlusPlus11
10944 ? !var->checkInitIsICE() : !checkConstInit();
10946 auto attr = var->getAttr<RequireConstantInitAttr>();
10947 Diag(var->getLocation(), diag::err_require_constant_init_failed)
10948 << Init->getSourceRange();
10949 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10950 << attr->getRange();
10953 else if (!var->isConstexpr() && IsGlobal &&
10954 !getDiagnostics().isIgnored(diag::warn_global_constructor,
10955 var->getLocation())) {
10956 // Warn about globals which don't have a constant initializer. Don't
10957 // warn about globals with a non-trivial destructor because we already
10958 // warned about them.
10959 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10960 if (!(RD && !RD->hasTrivialDestructor())) {
10961 if (!checkConstInit())
10962 Diag(var->getLocation(), diag::warn_global_constructor)
10963 << Init->getSourceRange();
10968 // Require the destructor.
10969 if (const RecordType *recordType = baseType->getAs<RecordType>())
10970 FinalizeVarWithDestructor(var, recordType);
10972 // If this variable must be emitted, add it as an initializer for the current
10974 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10975 Context.addModuleInitializer(ModuleScopes.back().Module, var);
10978 /// \brief Determines if a variable's alignment is dependent.
10979 static bool hasDependentAlignment(VarDecl *VD) {
10980 if (VD->getType()->isDependentType())
10982 for (auto *I : VD->specific_attrs<AlignedAttr>())
10983 if (I->isAlignmentDependent())
10988 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10989 /// any semantic actions necessary after any initializer has been attached.
10991 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10992 // Note that we are no longer parsing the initializer for this declaration.
10993 ParsingInitForAutoVars.erase(ThisDecl);
10995 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10999 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11000 for (auto *BD : DD->bindings()) {
11001 FinalizeDeclaration(BD);
11005 checkAttributesAfterMerging(*this, *VD);
11007 // Perform TLS alignment check here after attributes attached to the variable
11008 // which may affect the alignment have been processed. Only perform the check
11009 // if the target has a maximum TLS alignment (zero means no constraints).
11010 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11011 // Protect the check so that it's not performed on dependent types and
11012 // dependent alignments (we can't determine the alignment in that case).
11013 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11014 !VD->isInvalidDecl()) {
11015 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11016 if (Context.getDeclAlign(VD) > MaxAlignChars) {
11017 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11018 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11019 << (unsigned)MaxAlignChars.getQuantity();
11024 if (VD->isStaticLocal()) {
11025 if (FunctionDecl *FD =
11026 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11027 // Static locals inherit dll attributes from their function.
11028 if (Attr *A = getDLLAttr(FD)) {
11029 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11030 NewAttr->setInherited(true);
11031 VD->addAttr(NewAttr);
11033 // CUDA E.2.9.4: Within the body of a __device__ or __global__
11034 // function, only __shared__ variables may be declared with
11035 // static storage class.
11036 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11037 CUDADiagIfDeviceCode(VD->getLocation(),
11038 diag::err_device_static_local_var)
11039 << CurrentCUDATarget())
11040 VD->setInvalidDecl();
11044 // Perform check for initializers of device-side global variables.
11045 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11046 // 7.5). We must also apply the same checks to all __shared__
11047 // variables whether they are local or not. CUDA also allows
11048 // constant initializers for __constant__ and __device__ variables.
11049 if (getLangOpts().CUDA) {
11050 const Expr *Init = VD->getInit();
11051 if (Init && VD->hasGlobalStorage()) {
11052 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11053 VD->hasAttr<CUDASharedAttr>()) {
11054 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11055 bool AllowedInit = false;
11056 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11058 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11059 // We'll allow constant initializers even if it's a non-empty
11060 // constructor according to CUDA rules. This deviates from NVCC,
11061 // but allows us to handle things like constexpr constructors.
11062 if (!AllowedInit &&
11063 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11064 AllowedInit = VD->getInit()->isConstantInitializer(
11065 Context, VD->getType()->isReferenceType());
11067 // Also make sure that destructor, if there is one, is empty.
11069 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11071 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11073 if (!AllowedInit) {
11074 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11075 ? diag::err_shared_var_init
11076 : diag::err_dynamic_var_init)
11077 << Init->getSourceRange();
11078 VD->setInvalidDecl();
11081 // This is a host-side global variable. Check that the initializer is
11082 // callable from the host side.
11083 const FunctionDecl *InitFn = nullptr;
11084 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11085 InitFn = CE->getConstructor();
11086 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11087 InitFn = CE->getDirectCallee();
11090 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11091 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11092 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11093 << InitFnTarget << InitFn;
11094 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11095 VD->setInvalidDecl();
11102 // Grab the dllimport or dllexport attribute off of the VarDecl.
11103 const InheritableAttr *DLLAttr = getDLLAttr(VD);
11105 // Imported static data members cannot be defined out-of-line.
11106 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11107 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11108 VD->isThisDeclarationADefinition()) {
11109 // We allow definitions of dllimport class template static data members
11111 CXXRecordDecl *Context =
11112 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11113 bool IsClassTemplateMember =
11114 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11115 Context->getDescribedClassTemplate();
11117 Diag(VD->getLocation(),
11118 IsClassTemplateMember
11119 ? diag::warn_attribute_dllimport_static_field_definition
11120 : diag::err_attribute_dllimport_static_field_definition);
11121 Diag(IA->getLocation(), diag::note_attribute);
11122 if (!IsClassTemplateMember)
11123 VD->setInvalidDecl();
11127 // dllimport/dllexport variables cannot be thread local, their TLS index
11128 // isn't exported with the variable.
11129 if (DLLAttr && VD->getTLSKind()) {
11130 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11131 if (F && getDLLAttr(F)) {
11132 assert(VD->isStaticLocal());
11133 // But if this is a static local in a dlimport/dllexport function, the
11134 // function will never be inlined, which means the var would never be
11135 // imported, so having it marked import/export is safe.
11137 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11139 VD->setInvalidDecl();
11143 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11144 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11145 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11146 VD->dropAttr<UsedAttr>();
11150 const DeclContext *DC = VD->getDeclContext();
11151 // If there's a #pragma GCC visibility in scope, and this isn't a class
11152 // member, set the visibility of this variable.
11153 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11154 AddPushedVisibilityAttribute(VD);
11156 // FIXME: Warn on unused templates.
11157 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11158 !isa<VarTemplatePartialSpecializationDecl>(VD))
11159 MarkUnusedFileScopedDecl(VD);
11161 // Now we have parsed the initializer and can update the table of magic
11163 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11164 !VD->getType()->isIntegralOrEnumerationType())
11167 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11168 const Expr *MagicValueExpr = VD->getInit();
11169 if (!MagicValueExpr) {
11172 llvm::APSInt MagicValueInt;
11173 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11174 Diag(I->getRange().getBegin(),
11175 diag::err_type_tag_for_datatype_not_ice)
11176 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11179 if (MagicValueInt.getActiveBits() > 64) {
11180 Diag(I->getRange().getBegin(),
11181 diag::err_type_tag_for_datatype_too_large)
11182 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11185 uint64_t MagicValue = MagicValueInt.getZExtValue();
11186 RegisterTypeTagForDatatype(I->getArgumentKind(),
11188 I->getMatchingCType(),
11189 I->getLayoutCompatible(),
11190 I->getMustBeNull());
11194 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11195 auto *VD = dyn_cast<VarDecl>(DD);
11196 return VD && !VD->getType()->hasAutoForTrailingReturnType();
11199 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11200 ArrayRef<Decl *> Group) {
11201 SmallVector<Decl*, 8> Decls;
11203 if (DS.isTypeSpecOwned())
11204 Decls.push_back(DS.getRepAsDecl());
11206 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11207 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11208 bool DiagnosedMultipleDecomps = false;
11209 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11210 bool DiagnosedNonDeducedAuto = false;
11212 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11213 if (Decl *D = Group[i]) {
11214 // For declarators, there are some additional syntactic-ish checks we need
11216 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11217 if (!FirstDeclaratorInGroup)
11218 FirstDeclaratorInGroup = DD;
11219 if (!FirstDecompDeclaratorInGroup)
11220 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11221 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11222 !hasDeducedAuto(DD))
11223 FirstNonDeducedAutoInGroup = DD;
11225 if (FirstDeclaratorInGroup != DD) {
11226 // A decomposition declaration cannot be combined with any other
11227 // declaration in the same group.
11228 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11229 Diag(FirstDecompDeclaratorInGroup->getLocation(),
11230 diag::err_decomp_decl_not_alone)
11231 << FirstDeclaratorInGroup->getSourceRange()
11232 << DD->getSourceRange();
11233 DiagnosedMultipleDecomps = true;
11236 // A declarator that uses 'auto' in any way other than to declare a
11237 // variable with a deduced type cannot be combined with any other
11238 // declarator in the same group.
11239 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11240 Diag(FirstNonDeducedAutoInGroup->getLocation(),
11241 diag::err_auto_non_deduced_not_alone)
11242 << FirstNonDeducedAutoInGroup->getType()
11243 ->hasAutoForTrailingReturnType()
11244 << FirstDeclaratorInGroup->getSourceRange()
11245 << DD->getSourceRange();
11246 DiagnosedNonDeducedAuto = true;
11251 Decls.push_back(D);
11255 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11256 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11257 handleTagNumbering(Tag, S);
11258 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11259 getLangOpts().CPlusPlus)
11260 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11264 return BuildDeclaratorGroup(Decls);
11267 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11268 /// group, performing any necessary semantic checking.
11269 Sema::DeclGroupPtrTy
11270 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11271 // C++14 [dcl.spec.auto]p7: (DR1347)
11272 // If the type that replaces the placeholder type is not the same in each
11273 // deduction, the program is ill-formed.
11274 if (Group.size() > 1) {
11276 VarDecl *DeducedDecl = nullptr;
11277 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11278 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11279 if (!D || D->isInvalidDecl())
11281 DeducedType *DT = D->getType()->getContainedDeducedType();
11282 if (!DT || DT->getDeducedType().isNull())
11284 if (Deduced.isNull()) {
11285 Deduced = DT->getDeducedType();
11287 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11288 auto *AT = dyn_cast<AutoType>(DT);
11289 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11290 diag::err_auto_different_deductions)
11291 << (AT ? (unsigned)AT->getKeyword() : 3)
11292 << Deduced << DeducedDecl->getDeclName()
11293 << DT->getDeducedType() << D->getDeclName()
11294 << DeducedDecl->getInit()->getSourceRange()
11295 << D->getInit()->getSourceRange();
11296 D->setInvalidDecl();
11302 ActOnDocumentableDecls(Group);
11304 return DeclGroupPtrTy::make(
11305 DeclGroupRef::Create(Context, Group.data(), Group.size()));
11308 void Sema::ActOnDocumentableDecl(Decl *D) {
11309 ActOnDocumentableDecls(D);
11312 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11313 // Don't parse the comment if Doxygen diagnostics are ignored.
11314 if (Group.empty() || !Group[0])
11317 if (Diags.isIgnored(diag::warn_doc_param_not_found,
11318 Group[0]->getLocation()) &&
11319 Diags.isIgnored(diag::warn_unknown_comment_command_name,
11320 Group[0]->getLocation()))
11323 if (Group.size() >= 2) {
11324 // This is a decl group. Normally it will contain only declarations
11325 // produced from declarator list. But in case we have any definitions or
11326 // additional declaration references:
11327 // 'typedef struct S {} S;'
11328 // 'typedef struct S *S;'
11330 // FinalizeDeclaratorGroup adds these as separate declarations.
11331 Decl *MaybeTagDecl = Group[0];
11332 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11333 Group = Group.slice(1);
11337 // See if there are any new comments that are not attached to a decl.
11338 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11339 if (!Comments.empty() &&
11340 !Comments.back()->isAttached()) {
11341 // There is at least one comment that not attached to a decl.
11342 // Maybe it should be attached to one of these decls?
11344 // Note that this way we pick up not only comments that precede the
11345 // declaration, but also comments that *follow* the declaration -- thanks to
11346 // the lookahead in the lexer: we've consumed the semicolon and looked
11347 // ahead through comments.
11348 for (unsigned i = 0, e = Group.size(); i != e; ++i)
11349 Context.getCommentForDecl(Group[i], &PP);
11353 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11354 /// to introduce parameters into function prototype scope.
11355 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11356 const DeclSpec &DS = D.getDeclSpec();
11358 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11360 // C++03 [dcl.stc]p2 also permits 'auto'.
11361 StorageClass SC = SC_None;
11362 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11364 } else if (getLangOpts().CPlusPlus &&
11365 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11367 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11368 Diag(DS.getStorageClassSpecLoc(),
11369 diag::err_invalid_storage_class_in_func_decl);
11370 D.getMutableDeclSpec().ClearStorageClassSpecs();
11373 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11374 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11375 << DeclSpec::getSpecifierName(TSCS);
11376 if (DS.isInlineSpecified())
11377 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11378 << getLangOpts().CPlusPlus1z;
11379 if (DS.isConstexprSpecified())
11380 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11382 if (DS.isConceptSpecified())
11383 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11385 DiagnoseFunctionSpecifiers(DS);
11387 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11388 QualType parmDeclType = TInfo->getType();
11390 if (getLangOpts().CPlusPlus) {
11391 // Check that there are no default arguments inside the type of this
11393 CheckExtraCXXDefaultArguments(D);
11395 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11396 if (D.getCXXScopeSpec().isSet()) {
11397 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11398 << D.getCXXScopeSpec().getRange();
11399 D.getCXXScopeSpec().clear();
11403 // Ensure we have a valid name
11404 IdentifierInfo *II = nullptr;
11406 II = D.getIdentifier();
11408 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11409 << GetNameForDeclarator(D).getName();
11410 D.setInvalidType(true);
11414 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11416 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11419 if (R.isSingleResult()) {
11420 NamedDecl *PrevDecl = R.getFoundDecl();
11421 if (PrevDecl->isTemplateParameter()) {
11422 // Maybe we will complain about the shadowed template parameter.
11423 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11424 // Just pretend that we didn't see the previous declaration.
11425 PrevDecl = nullptr;
11426 } else if (S->isDeclScope(PrevDecl)) {
11427 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11428 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11430 // Recover by removing the name
11432 D.SetIdentifier(nullptr, D.getIdentifierLoc());
11433 D.setInvalidType(true);
11438 // Temporarily put parameter variables in the translation unit, not
11439 // the enclosing context. This prevents them from accidentally
11440 // looking like class members in C++.
11441 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11443 D.getIdentifierLoc(), II,
11444 parmDeclType, TInfo,
11447 if (D.isInvalidType())
11448 New->setInvalidDecl();
11450 assert(S->isFunctionPrototypeScope());
11451 assert(S->getFunctionPrototypeDepth() >= 1);
11452 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11453 S->getNextFunctionPrototypeIndex());
11455 // Add the parameter declaration into this scope.
11458 IdResolver.AddDecl(New);
11460 ProcessDeclAttributes(S, New, D);
11462 if (D.getDeclSpec().isModulePrivateSpecified())
11463 Diag(New->getLocation(), diag::err_module_private_local)
11464 << 1 << New->getDeclName()
11465 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11466 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11468 if (New->hasAttr<BlocksAttr>()) {
11469 Diag(New->getLocation(), diag::err_block_on_nonlocal);
11474 /// \brief Synthesizes a variable for a parameter arising from a
11476 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11477 SourceLocation Loc,
11479 /* FIXME: setting StartLoc == Loc.
11480 Would it be worth to modify callers so as to provide proper source
11481 location for the unnamed parameters, embedding the parameter's type? */
11482 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11483 T, Context.getTrivialTypeSourceInfo(T, Loc),
11485 Param->setImplicit();
11489 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11490 // Don't diagnose unused-parameter errors in template instantiations; we
11491 // will already have done so in the template itself.
11492 if (inTemplateInstantiation())
11495 for (const ParmVarDecl *Parameter : Parameters) {
11496 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11497 !Parameter->hasAttr<UnusedAttr>()) {
11498 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11499 << Parameter->getDeclName();
11504 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11505 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11506 if (LangOpts.NumLargeByValueCopy == 0) // No check.
11509 // Warn if the return value is pass-by-value and larger than the specified
11511 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11512 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11513 if (Size > LangOpts.NumLargeByValueCopy)
11514 Diag(D->getLocation(), diag::warn_return_value_size)
11515 << D->getDeclName() << Size;
11518 // Warn if any parameter is pass-by-value and larger than the specified
11520 for (const ParmVarDecl *Parameter : Parameters) {
11521 QualType T = Parameter->getType();
11522 if (T->isDependentType() || !T.isPODType(Context))
11524 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11525 if (Size > LangOpts.NumLargeByValueCopy)
11526 Diag(Parameter->getLocation(), diag::warn_parameter_size)
11527 << Parameter->getDeclName() << Size;
11531 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11532 SourceLocation NameLoc, IdentifierInfo *Name,
11533 QualType T, TypeSourceInfo *TSInfo,
11535 // In ARC, infer a lifetime qualifier for appropriate parameter types.
11536 if (getLangOpts().ObjCAutoRefCount &&
11537 T.getObjCLifetime() == Qualifiers::OCL_None &&
11538 T->isObjCLifetimeType()) {
11540 Qualifiers::ObjCLifetime lifetime;
11542 // Special cases for arrays:
11543 // - if it's const, use __unsafe_unretained
11544 // - otherwise, it's an error
11545 if (T->isArrayType()) {
11546 if (!T.isConstQualified()) {
11547 DelayedDiagnostics.add(
11548 sema::DelayedDiagnostic::makeForbiddenType(
11549 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11551 lifetime = Qualifiers::OCL_ExplicitNone;
11553 lifetime = T->getObjCARCImplicitLifetime();
11555 T = Context.getLifetimeQualifiedType(T, lifetime);
11558 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11559 Context.getAdjustedParameterType(T),
11560 TSInfo, SC, nullptr);
11562 // Parameters can not be abstract class types.
11563 // For record types, this is done by the AbstractClassUsageDiagnoser once
11564 // the class has been completely parsed.
11565 if (!CurContext->isRecord() &&
11566 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11567 AbstractParamType))
11568 New->setInvalidDecl();
11570 // Parameter declarators cannot be interface types. All ObjC objects are
11571 // passed by reference.
11572 if (T->isObjCObjectType()) {
11573 SourceLocation TypeEndLoc =
11574 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11576 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11577 << FixItHint::CreateInsertion(TypeEndLoc, "*");
11578 T = Context.getObjCObjectPointerType(T);
11582 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11583 // duration shall not be qualified by an address-space qualifier."
11584 // Since all parameters have automatic store duration, they can not have
11585 // an address space.
11586 if (T.getAddressSpace() != 0) {
11587 // OpenCL allows function arguments declared to be an array of a type
11588 // to be qualified with an address space.
11589 if (!(getLangOpts().OpenCL && T->isArrayType())) {
11590 Diag(NameLoc, diag::err_arg_with_address_space);
11591 New->setInvalidDecl();
11598 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11599 SourceLocation LocAfterDecls) {
11600 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11602 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11603 // for a K&R function.
11604 if (!FTI.hasPrototype) {
11605 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11607 if (FTI.Params[i].Param == nullptr) {
11608 SmallString<256> Code;
11609 llvm::raw_svector_ostream(Code)
11610 << " int " << FTI.Params[i].Ident->getName() << ";\n";
11611 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11612 << FTI.Params[i].Ident
11613 << FixItHint::CreateInsertion(LocAfterDecls, Code);
11615 // Implicitly declare the argument as type 'int' for lack of a better
11617 AttributeFactory attrs;
11618 DeclSpec DS(attrs);
11619 const char* PrevSpec; // unused
11620 unsigned DiagID; // unused
11621 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11622 DiagID, Context.getPrintingPolicy());
11623 // Use the identifier location for the type source range.
11624 DS.SetRangeStart(FTI.Params[i].IdentLoc);
11625 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11626 Declarator ParamD(DS, Declarator::KNRTypeListContext);
11627 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11628 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11635 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11636 MultiTemplateParamsArg TemplateParameterLists,
11637 SkipBodyInfo *SkipBody) {
11638 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11639 assert(D.isFunctionDeclarator() && "Not a function declarator!");
11640 Scope *ParentScope = FnBodyScope->getParent();
11642 D.setFunctionDefinitionKind(FDK_Definition);
11643 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11644 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11647 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11648 Consumer.HandleInlineFunctionDefinition(D);
11651 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11652 const FunctionDecl*& PossibleZeroParamPrototype) {
11653 // Don't warn about invalid declarations.
11654 if (FD->isInvalidDecl())
11657 // Or declarations that aren't global.
11658 if (!FD->isGlobal())
11661 // Don't warn about C++ member functions.
11662 if (isa<CXXMethodDecl>(FD))
11665 // Don't warn about 'main'.
11669 // Don't warn about inline functions.
11670 if (FD->isInlined())
11673 // Don't warn about function templates.
11674 if (FD->getDescribedFunctionTemplate())
11677 // Don't warn about function template specializations.
11678 if (FD->isFunctionTemplateSpecialization())
11681 // Don't warn for OpenCL kernels.
11682 if (FD->hasAttr<OpenCLKernelAttr>())
11685 // Don't warn on explicitly deleted functions.
11686 if (FD->isDeleted())
11689 bool MissingPrototype = true;
11690 for (const FunctionDecl *Prev = FD->getPreviousDecl();
11691 Prev; Prev = Prev->getPreviousDecl()) {
11692 // Ignore any declarations that occur in function or method
11693 // scope, because they aren't visible from the header.
11694 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11697 MissingPrototype = !Prev->getType()->isFunctionProtoType();
11698 if (FD->getNumParams() == 0)
11699 PossibleZeroParamPrototype = Prev;
11703 return MissingPrototype;
11707 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11708 const FunctionDecl *EffectiveDefinition,
11709 SkipBodyInfo *SkipBody) {
11710 const FunctionDecl *Definition = EffectiveDefinition;
11712 if (!FD->isDefined(Definition))
11715 if (canRedefineFunction(Definition, getLangOpts()))
11718 // If we don't have a visible definition of the function, and it's inline or
11719 // a template, skip the new definition.
11720 if (SkipBody && !hasVisibleDefinition(Definition) &&
11721 (Definition->getFormalLinkage() == InternalLinkage ||
11722 Definition->isInlined() ||
11723 Definition->getDescribedFunctionTemplate() ||
11724 Definition->getNumTemplateParameterLists())) {
11725 SkipBody->ShouldSkip = true;
11726 if (auto *TD = Definition->getDescribedFunctionTemplate())
11727 makeMergedDefinitionVisible(TD, FD->getLocation());
11728 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11729 FD->getLocation());
11733 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11734 Definition->getStorageClass() == SC_Extern)
11735 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11736 << FD->getDeclName() << getLangOpts().CPlusPlus;
11738 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11740 Diag(Definition->getLocation(), diag::note_previous_definition);
11741 FD->setInvalidDecl();
11744 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11746 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11748 LambdaScopeInfo *LSI = S.PushLambdaScope();
11749 LSI->CallOperator = CallOperator;
11750 LSI->Lambda = LambdaClass;
11751 LSI->ReturnType = CallOperator->getReturnType();
11752 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11754 if (LCD == LCD_None)
11755 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11756 else if (LCD == LCD_ByCopy)
11757 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11758 else if (LCD == LCD_ByRef)
11759 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11760 DeclarationNameInfo DNI = CallOperator->getNameInfo();
11762 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11763 LSI->Mutable = !CallOperator->isConst();
11765 // Add the captures to the LSI so they can be noted as already
11766 // captured within tryCaptureVar.
11767 auto I = LambdaClass->field_begin();
11768 for (const auto &C : LambdaClass->captures()) {
11769 if (C.capturesVariable()) {
11770 VarDecl *VD = C.getCapturedVar();
11771 if (VD->isInitCapture())
11772 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11773 QualType CaptureType = VD->getType();
11774 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11775 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11776 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11777 /*EllipsisLoc*/C.isPackExpansion()
11778 ? C.getEllipsisLoc() : SourceLocation(),
11779 CaptureType, /*Expr*/ nullptr);
11781 } else if (C.capturesThis()) {
11782 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11784 C.getCaptureKind() == LCK_StarThis);
11786 LSI->addVLATypeCapture(C.getLocation(), I->getType());
11792 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11793 SkipBodyInfo *SkipBody) {
11796 FunctionDecl *FD = nullptr;
11798 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11799 FD = FunTmpl->getTemplatedDecl();
11801 FD = cast<FunctionDecl>(D);
11803 // Check for defining attributes before the check for redefinition.
11804 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
11805 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
11806 FD->dropAttr<AliasAttr>();
11807 FD->setInvalidDecl();
11809 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
11810 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
11811 FD->dropAttr<IFuncAttr>();
11812 FD->setInvalidDecl();
11815 // See if this is a redefinition.
11816 if (!FD->isLateTemplateParsed()) {
11817 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11819 // If we're skipping the body, we're done. Don't enter the scope.
11820 if (SkipBody && SkipBody->ShouldSkip)
11824 // Mark this function as "will have a body eventually". This lets users to
11825 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11827 FD->setWillHaveBody();
11829 // If we are instantiating a generic lambda call operator, push
11830 // a LambdaScopeInfo onto the function stack. But use the information
11831 // that's already been calculated (ActOnLambdaExpr) to prime the current
11832 // LambdaScopeInfo.
11833 // When the template operator is being specialized, the LambdaScopeInfo,
11834 // has to be properly restored so that tryCaptureVariable doesn't try
11835 // and capture any new variables. In addition when calculating potential
11836 // captures during transformation of nested lambdas, it is necessary to
11837 // have the LSI properly restored.
11838 if (isGenericLambdaCallOperatorSpecialization(FD)) {
11839 assert(inTemplateInstantiation() &&
11840 "There should be an active template instantiation on the stack "
11841 "when instantiating a generic lambda!");
11842 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11844 // Enter a new function scope
11845 PushFunctionScope();
11848 // Builtin functions cannot be defined.
11849 if (unsigned BuiltinID = FD->getBuiltinID()) {
11850 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11851 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11852 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11853 FD->setInvalidDecl();
11857 // The return type of a function definition must be complete
11858 // (C99 6.9.1p3, C++ [dcl.fct]p6).
11859 QualType ResultType = FD->getReturnType();
11860 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11861 !FD->isInvalidDecl() &&
11862 RequireCompleteType(FD->getLocation(), ResultType,
11863 diag::err_func_def_incomplete_result))
11864 FD->setInvalidDecl();
11867 PushDeclContext(FnBodyScope, FD);
11869 // Check the validity of our function parameters
11870 CheckParmsForFunctionDef(FD->parameters(),
11871 /*CheckParameterNames=*/true);
11873 // Add non-parameter declarations already in the function to the current
11876 for (Decl *NPD : FD->decls()) {
11877 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11880 assert(!isa<ParmVarDecl>(NonParmDecl) &&
11881 "parameters should not be in newly created FD yet");
11883 // If the decl has a name, make it accessible in the current scope.
11884 if (NonParmDecl->getDeclName())
11885 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11887 // Similarly, dive into enums and fish their constants out, making them
11888 // accessible in this scope.
11889 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11890 for (auto *EI : ED->enumerators())
11891 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11896 // Introduce our parameters into the function scope
11897 for (auto Param : FD->parameters()) {
11898 Param->setOwningFunction(FD);
11900 // If this has an identifier, add it to the scope stack.
11901 if (Param->getIdentifier() && FnBodyScope) {
11902 CheckShadow(FnBodyScope, Param);
11904 PushOnScopeChains(Param, FnBodyScope);
11908 // Ensure that the function's exception specification is instantiated.
11909 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11910 ResolveExceptionSpec(D->getLocation(), FPT);
11912 // dllimport cannot be applied to non-inline function definitions.
11913 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11914 !FD->isTemplateInstantiation()) {
11915 assert(!FD->hasAttr<DLLExportAttr>());
11916 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11917 FD->setInvalidDecl();
11920 // We want to attach documentation to original Decl (which might be
11921 // a function template).
11922 ActOnDocumentableDecl(D);
11923 if (getCurLexicalContext()->isObjCContainer() &&
11924 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11925 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11926 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11931 /// \brief Given the set of return statements within a function body,
11932 /// compute the variables that are subject to the named return value
11935 /// Each of the variables that is subject to the named return value
11936 /// optimization will be marked as NRVO variables in the AST, and any
11937 /// return statement that has a marked NRVO variable as its NRVO candidate can
11938 /// use the named return value optimization.
11940 /// This function applies a very simplistic algorithm for NRVO: if every return
11941 /// statement in the scope of a variable has the same NRVO candidate, that
11942 /// candidate is an NRVO variable.
11943 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11944 ReturnStmt **Returns = Scope->Returns.data();
11946 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11947 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11948 if (!NRVOCandidate->isNRVOVariable())
11949 Returns[I]->setNRVOCandidate(nullptr);
11954 bool Sema::canDelayFunctionBody(const Declarator &D) {
11955 // We can't delay parsing the body of a constexpr function template (yet).
11956 if (D.getDeclSpec().isConstexprSpecified())
11959 // We can't delay parsing the body of a function template with a deduced
11960 // return type (yet).
11961 if (D.getDeclSpec().hasAutoTypeSpec()) {
11962 // If the placeholder introduces a non-deduced trailing return type,
11963 // we can still delay parsing it.
11964 if (D.getNumTypeObjects()) {
11965 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11966 if (Outer.Kind == DeclaratorChunk::Function &&
11967 Outer.Fun.hasTrailingReturnType()) {
11968 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11969 return Ty.isNull() || !Ty->isUndeducedType();
11978 bool Sema::canSkipFunctionBody(Decl *D) {
11979 // We cannot skip the body of a function (or function template) which is
11980 // constexpr, since we may need to evaluate its body in order to parse the
11981 // rest of the file.
11982 // We cannot skip the body of a function with an undeduced return type,
11983 // because any callers of that function need to know the type.
11984 if (const FunctionDecl *FD = D->getAsFunction())
11985 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11987 return Consumer.shouldSkipFunctionBody(D);
11990 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11991 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11992 FD->setHasSkippedBody();
11993 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11994 MD->setHasSkippedBody();
11998 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11999 return ActOnFinishFunctionBody(D, BodyArg, false);
12002 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12003 bool IsInstantiation) {
12004 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12006 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12007 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12009 if (getLangOpts().CoroutinesTS && getCurFunction()->CoroutinePromise)
12010 CheckCompletedCoroutineBody(FD, Body);
12015 if (getLangOpts().CPlusPlus14) {
12016 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12017 FD->getReturnType()->isUndeducedType()) {
12018 // If the function has a deduced result type but contains no 'return'
12019 // statements, the result type as written must be exactly 'auto', and
12020 // the deduced result type is 'void'.
12021 if (!FD->getReturnType()->getAs<AutoType>()) {
12022 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12023 << FD->getReturnType();
12024 FD->setInvalidDecl();
12026 // Substitute 'void' for the 'auto' in the type.
12027 TypeLoc ResultType = getReturnTypeLoc(FD);
12028 Context.adjustDeducedFunctionResultType(
12029 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12032 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12033 // In C++11, we don't use 'auto' deduction rules for lambda call
12034 // operators because we don't support return type deduction.
12035 auto *LSI = getCurLambda();
12036 if (LSI->HasImplicitReturnType) {
12037 deduceClosureReturnType(*LSI);
12039 // C++11 [expr.prim.lambda]p4:
12040 // [...] if there are no return statements in the compound-statement
12041 // [the deduced type is] the type void
12043 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12045 // Update the return type to the deduced type.
12046 const FunctionProtoType *Proto =
12047 FD->getType()->getAs<FunctionProtoType>();
12048 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12049 Proto->getExtProtoInfo()));
12053 // The only way to be included in UndefinedButUsed is if there is an
12054 // ODR use before the definition. Avoid the expensive map lookup if this
12055 // is the first declaration.
12056 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12057 if (!FD->isExternallyVisible())
12058 UndefinedButUsed.erase(FD);
12059 else if (FD->isInlined() &&
12060 !LangOpts.GNUInline &&
12061 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12062 UndefinedButUsed.erase(FD);
12065 // If the function implicitly returns zero (like 'main') or is naked,
12066 // don't complain about missing return statements.
12067 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12068 WP.disableCheckFallThrough();
12070 // MSVC permits the use of pure specifier (=0) on function definition,
12071 // defined at class scope, warn about this non-standard construct.
12072 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12073 Diag(FD->getLocation(), diag::ext_pure_function_definition);
12075 if (!FD->isInvalidDecl()) {
12076 // Don't diagnose unused parameters of defaulted or deleted functions.
12077 if (!FD->isDeleted() && !FD->isDefaulted())
12078 DiagnoseUnusedParameters(FD->parameters());
12079 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12080 FD->getReturnType(), FD);
12082 // If this is a structor, we need a vtable.
12083 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12084 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12085 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12086 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12088 // Try to apply the named return value optimization. We have to check
12089 // if we can do this here because lambdas keep return statements around
12090 // to deduce an implicit return type.
12091 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12092 !FD->isDependentContext())
12093 computeNRVO(Body, getCurFunction());
12096 // GNU warning -Wmissing-prototypes:
12097 // Warn if a global function is defined without a previous
12098 // prototype declaration. This warning is issued even if the
12099 // definition itself provides a prototype. The aim is to detect
12100 // global functions that fail to be declared in header files.
12101 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12102 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12103 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12105 if (PossibleZeroParamPrototype) {
12106 // We found a declaration that is not a prototype,
12107 // but that could be a zero-parameter prototype
12108 if (TypeSourceInfo *TI =
12109 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12110 TypeLoc TL = TI->getTypeLoc();
12111 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12112 Diag(PossibleZeroParamPrototype->getLocation(),
12113 diag::note_declaration_not_a_prototype)
12114 << PossibleZeroParamPrototype
12115 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12119 // GNU warning -Wstrict-prototypes
12120 // Warn if K&R function is defined without a previous declaration.
12121 // This warning is issued only if the definition itself does not provide
12122 // a prototype. Only K&R definitions do not provide a prototype.
12123 // An empty list in a function declarator that is part of a definition
12124 // of that function specifies that the function has no parameters
12125 // (C99 6.7.5.3p14)
12126 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12127 !LangOpts.CPlusPlus) {
12128 TypeSourceInfo *TI = FD->getTypeSourceInfo();
12129 TypeLoc TL = TI->getTypeLoc();
12130 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12131 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12135 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12136 const CXXMethodDecl *KeyFunction;
12137 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12139 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12140 MD == KeyFunction->getCanonicalDecl()) {
12141 // Update the key-function state if necessary for this ABI.
12142 if (FD->isInlined() &&
12143 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12144 Context.setNonKeyFunction(MD);
12146 // If the newly-chosen key function is already defined, then we
12147 // need to mark the vtable as used retroactively.
12148 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12149 const FunctionDecl *Definition;
12150 if (KeyFunction && KeyFunction->isDefined(Definition))
12151 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12153 // We just defined they key function; mark the vtable as used.
12154 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12159 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12160 "Function parsing confused");
12161 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12162 assert(MD == getCurMethodDecl() && "Method parsing confused");
12164 if (!MD->isInvalidDecl()) {
12165 DiagnoseUnusedParameters(MD->parameters());
12166 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12167 MD->getReturnType(), MD);
12170 computeNRVO(Body, getCurFunction());
12172 if (getCurFunction()->ObjCShouldCallSuper) {
12173 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12174 << MD->getSelector().getAsString();
12175 getCurFunction()->ObjCShouldCallSuper = false;
12177 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12178 const ObjCMethodDecl *InitMethod = nullptr;
12179 bool isDesignated =
12180 MD->isDesignatedInitializerForTheInterface(&InitMethod);
12181 assert(isDesignated && InitMethod);
12182 (void)isDesignated;
12184 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12185 auto IFace = MD->getClassInterface();
12188 auto SuperD = IFace->getSuperClass();
12191 return SuperD->getIdentifier() ==
12192 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12194 // Don't issue this warning for unavailable inits or direct subclasses
12196 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12197 Diag(MD->getLocation(),
12198 diag::warn_objc_designated_init_missing_super_call);
12199 Diag(InitMethod->getLocation(),
12200 diag::note_objc_designated_init_marked_here);
12202 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12204 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12205 // Don't issue this warning for unavaialable inits.
12206 if (!MD->isUnavailable())
12207 Diag(MD->getLocation(),
12208 diag::warn_objc_secondary_init_missing_init_call);
12209 getCurFunction()->ObjCWarnForNoInitDelegation = false;
12215 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12216 DiagnoseUnguardedAvailabilityViolations(dcl);
12218 assert(!getCurFunction()->ObjCShouldCallSuper &&
12219 "This should only be set for ObjC methods, which should have been "
12220 "handled in the block above.");
12222 // Verify and clean out per-function state.
12223 if (Body && (!FD || !FD->isDefaulted())) {
12224 // C++ constructors that have function-try-blocks can't have return
12225 // statements in the handlers of that block. (C++ [except.handle]p14)
12227 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12228 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12230 // Verify that gotos and switch cases don't jump into scopes illegally.
12231 if (getCurFunction()->NeedsScopeChecking() &&
12232 !PP.isCodeCompletionEnabled())
12233 DiagnoseInvalidJumps(Body);
12235 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12236 if (!Destructor->getParent()->isDependentType())
12237 CheckDestructor(Destructor);
12239 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12240 Destructor->getParent());
12243 // If any errors have occurred, clear out any temporaries that may have
12244 // been leftover. This ensures that these temporaries won't be picked up for
12245 // deletion in some later function.
12246 if (getDiagnostics().hasErrorOccurred() ||
12247 getDiagnostics().getSuppressAllDiagnostics()) {
12248 DiscardCleanupsInEvaluationContext();
12250 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12251 !isa<FunctionTemplateDecl>(dcl)) {
12252 // Since the body is valid, issue any analysis-based warnings that are
12254 ActivePolicy = &WP;
12257 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12258 (!CheckConstexprFunctionDecl(FD) ||
12259 !CheckConstexprFunctionBody(FD, Body)))
12260 FD->setInvalidDecl();
12262 if (FD && FD->hasAttr<NakedAttr>()) {
12263 for (const Stmt *S : Body->children()) {
12264 // Allow local register variables without initializer as they don't
12265 // require prologue.
12266 bool RegisterVariables = false;
12267 if (auto *DS = dyn_cast<DeclStmt>(S)) {
12268 for (const auto *Decl : DS->decls()) {
12269 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12270 RegisterVariables =
12271 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12272 if (!RegisterVariables)
12277 if (RegisterVariables)
12279 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12280 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12281 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12282 FD->setInvalidDecl();
12288 assert(ExprCleanupObjects.size() ==
12289 ExprEvalContexts.back().NumCleanupObjects &&
12290 "Leftover temporaries in function");
12291 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12292 assert(MaybeODRUseExprs.empty() &&
12293 "Leftover expressions for odr-use checking");
12296 if (!IsInstantiation)
12299 PopFunctionScopeInfo(ActivePolicy, dcl);
12300 // If any errors have occurred, clear out any temporaries that may have
12301 // been leftover. This ensures that these temporaries won't be picked up for
12302 // deletion in some later function.
12303 if (getDiagnostics().hasErrorOccurred()) {
12304 DiscardCleanupsInEvaluationContext();
12310 /// When we finish delayed parsing of an attribute, we must attach it to the
12312 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12313 ParsedAttributes &Attrs) {
12314 // Always attach attributes to the underlying decl.
12315 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12316 D = TD->getTemplatedDecl();
12317 ProcessDeclAttributeList(S, D, Attrs.getList());
12319 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12320 if (Method->isStatic())
12321 checkThisInStaticMemberFunctionAttributes(Method);
12324 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12325 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12326 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12327 IdentifierInfo &II, Scope *S) {
12328 // Before we produce a declaration for an implicitly defined
12329 // function, see whether there was a locally-scoped declaration of
12330 // this name as a function or variable. If so, use that
12331 // (non-visible) declaration, and complain about it.
12332 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12333 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12334 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12335 return ExternCPrev;
12338 // Extension in C99. Legal in C90, but warn about it.
12340 if (II.getName().startswith("__builtin_"))
12341 diag_id = diag::warn_builtin_unknown;
12342 else if (getLangOpts().C99)
12343 diag_id = diag::ext_implicit_function_decl;
12345 diag_id = diag::warn_implicit_function_decl;
12346 Diag(Loc, diag_id) << &II;
12348 // Because typo correction is expensive, only do it if the implicit
12349 // function declaration is going to be treated as an error.
12350 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12351 TypoCorrection Corrected;
12353 (Corrected = CorrectTypo(
12354 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12355 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12356 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12357 /*ErrorRecovery*/false);
12360 // Set a Declarator for the implicit definition: int foo();
12362 AttributeFactory attrFactory;
12363 DeclSpec DS(attrFactory);
12365 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12366 Context.getPrintingPolicy());
12367 (void)Error; // Silence warning.
12368 assert(!Error && "Error setting up implicit decl!");
12369 SourceLocation NoLoc;
12370 Declarator D(DS, Declarator::BlockContext);
12371 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12372 /*IsAmbiguous=*/false,
12373 /*LParenLoc=*/NoLoc,
12374 /*Params=*/nullptr,
12376 /*EllipsisLoc=*/NoLoc,
12377 /*RParenLoc=*/NoLoc,
12379 /*RefQualifierIsLvalueRef=*/true,
12380 /*RefQualifierLoc=*/NoLoc,
12381 /*ConstQualifierLoc=*/NoLoc,
12382 /*VolatileQualifierLoc=*/NoLoc,
12383 /*RestrictQualifierLoc=*/NoLoc,
12384 /*MutableLoc=*/NoLoc,
12386 /*ESpecRange=*/SourceRange(),
12387 /*Exceptions=*/nullptr,
12388 /*ExceptionRanges=*/nullptr,
12389 /*NumExceptions=*/0,
12390 /*NoexceptExpr=*/nullptr,
12391 /*ExceptionSpecTokens=*/nullptr,
12392 /*DeclsInPrototype=*/None,
12394 DS.getAttributes(),
12396 D.SetIdentifier(&II, Loc);
12398 // Insert this function into translation-unit scope.
12400 DeclContext *PrevDC = CurContext;
12401 CurContext = Context.getTranslationUnitDecl();
12403 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12406 CurContext = PrevDC;
12408 AddKnownFunctionAttributes(FD);
12413 /// \brief Adds any function attributes that we know a priori based on
12414 /// the declaration of this function.
12416 /// These attributes can apply both to implicitly-declared builtins
12417 /// (like __builtin___printf_chk) or to library-declared functions
12418 /// like NSLog or printf.
12420 /// We need to check for duplicate attributes both here and where user-written
12421 /// attributes are applied to declarations.
12422 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12423 if (FD->isInvalidDecl())
12426 // If this is a built-in function, map its builtin attributes to
12427 // actual attributes.
12428 if (unsigned BuiltinID = FD->getBuiltinID()) {
12429 // Handle printf-formatting attributes.
12430 unsigned FormatIdx;
12432 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12433 if (!FD->hasAttr<FormatAttr>()) {
12434 const char *fmt = "printf";
12435 unsigned int NumParams = FD->getNumParams();
12436 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12437 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12439 FD->addAttr(FormatAttr::CreateImplicit(Context,
12440 &Context.Idents.get(fmt),
12442 HasVAListArg ? 0 : FormatIdx+2,
12443 FD->getLocation()));
12446 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12448 if (!FD->hasAttr<FormatAttr>())
12449 FD->addAttr(FormatAttr::CreateImplicit(Context,
12450 &Context.Idents.get("scanf"),
12452 HasVAListArg ? 0 : FormatIdx+2,
12453 FD->getLocation()));
12456 // Mark const if we don't care about errno and that is the only
12457 // thing preventing the function from being const. This allows
12458 // IRgen to use LLVM intrinsics for such functions.
12459 if (!getLangOpts().MathErrno &&
12460 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12461 if (!FD->hasAttr<ConstAttr>())
12462 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12465 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12466 !FD->hasAttr<ReturnsTwiceAttr>())
12467 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12468 FD->getLocation()));
12469 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12470 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12471 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12472 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12473 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12474 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12475 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12476 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12477 // Add the appropriate attribute, depending on the CUDA compilation mode
12478 // and which target the builtin belongs to. For example, during host
12479 // compilation, aux builtins are __device__, while the rest are __host__.
12480 if (getLangOpts().CUDAIsDevice !=
12481 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12482 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12484 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12488 // If C++ exceptions are enabled but we are told extern "C" functions cannot
12489 // throw, add an implicit nothrow attribute to any extern "C" function we come
12491 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12492 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12493 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12494 if (!FPT || FPT->getExceptionSpecType() == EST_None)
12495 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12498 IdentifierInfo *Name = FD->getIdentifier();
12501 if ((!getLangOpts().CPlusPlus &&
12502 FD->getDeclContext()->isTranslationUnit()) ||
12503 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12504 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12505 LinkageSpecDecl::lang_c)) {
12506 // Okay: this could be a libc/libm/Objective-C function we know
12511 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12512 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12513 // target-specific builtins, perhaps?
12514 if (!FD->hasAttr<FormatAttr>())
12515 FD->addAttr(FormatAttr::CreateImplicit(Context,
12516 &Context.Idents.get("printf"), 2,
12517 Name->isStr("vasprintf") ? 0 : 3,
12518 FD->getLocation()));
12521 if (Name->isStr("__CFStringMakeConstantString")) {
12522 // We already have a __builtin___CFStringMakeConstantString,
12523 // but builds that use -fno-constant-cfstrings don't go through that.
12524 if (!FD->hasAttr<FormatArgAttr>())
12525 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12526 FD->getLocation()));
12530 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12531 TypeSourceInfo *TInfo) {
12532 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12533 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12536 assert(D.isInvalidType() && "no declarator info for valid type");
12537 TInfo = Context.getTrivialTypeSourceInfo(T);
12540 // Scope manipulation handled by caller.
12541 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12543 D.getIdentifierLoc(),
12547 // Bail out immediately if we have an invalid declaration.
12548 if (D.isInvalidType()) {
12549 NewTD->setInvalidDecl();
12553 if (D.getDeclSpec().isModulePrivateSpecified()) {
12554 if (CurContext->isFunctionOrMethod())
12555 Diag(NewTD->getLocation(), diag::err_module_private_local)
12556 << 2 << NewTD->getDeclName()
12557 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12558 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12560 NewTD->setModulePrivate();
12563 // C++ [dcl.typedef]p8:
12564 // If the typedef declaration defines an unnamed class (or
12565 // enum), the first typedef-name declared by the declaration
12566 // to be that class type (or enum type) is used to denote the
12567 // class type (or enum type) for linkage purposes only.
12568 // We need to check whether the type was declared in the declaration.
12569 switch (D.getDeclSpec().getTypeSpecType()) {
12572 case TST_interface:
12575 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12576 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12587 /// \brief Check that this is a valid underlying type for an enum declaration.
12588 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12589 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12590 QualType T = TI->getType();
12592 if (T->isDependentType())
12595 if (const BuiltinType *BT = T->getAs<BuiltinType>())
12596 if (BT->isInteger())
12599 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12603 /// Check whether this is a valid redeclaration of a previous enumeration.
12604 /// \return true if the redeclaration was invalid.
12605 bool Sema::CheckEnumRedeclaration(
12606 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12607 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12608 bool IsFixed = !EnumUnderlyingTy.isNull();
12610 if (IsScoped != Prev->isScoped()) {
12611 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12612 << Prev->isScoped();
12613 Diag(Prev->getLocation(), diag::note_previous_declaration);
12617 if (IsFixed && Prev->isFixed()) {
12618 if (!EnumUnderlyingTy->isDependentType() &&
12619 !Prev->getIntegerType()->isDependentType() &&
12620 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12621 Prev->getIntegerType())) {
12622 // TODO: Highlight the underlying type of the redeclaration.
12623 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12624 << EnumUnderlyingTy << Prev->getIntegerType();
12625 Diag(Prev->getLocation(), diag::note_previous_declaration)
12626 << Prev->getIntegerTypeRange();
12629 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12631 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12633 } else if (IsFixed != Prev->isFixed()) {
12634 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12635 << Prev->isFixed();
12636 Diag(Prev->getLocation(), diag::note_previous_declaration);
12643 /// \brief Get diagnostic %select index for tag kind for
12644 /// redeclaration diagnostic message.
12645 /// WARNING: Indexes apply to particular diagnostics only!
12647 /// \returns diagnostic %select index.
12648 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12650 case TTK_Struct: return 0;
12651 case TTK_Interface: return 1;
12652 case TTK_Class: return 2;
12653 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12657 /// \brief Determine if tag kind is a class-key compatible with
12658 /// class for redeclaration (class, struct, or __interface).
12660 /// \returns true iff the tag kind is compatible.
12661 static bool isClassCompatTagKind(TagTypeKind Tag)
12663 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12666 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12668 if (isa<TypedefDecl>(PrevDecl))
12669 return NTK_Typedef;
12670 else if (isa<TypeAliasDecl>(PrevDecl))
12671 return NTK_TypeAlias;
12672 else if (isa<ClassTemplateDecl>(PrevDecl))
12673 return NTK_Template;
12674 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12675 return NTK_TypeAliasTemplate;
12676 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12677 return NTK_TemplateTemplateArgument;
12680 case TTK_Interface:
12682 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12684 return NTK_NonUnion;
12686 return NTK_NonEnum;
12688 llvm_unreachable("invalid TTK");
12691 /// \brief Determine whether a tag with a given kind is acceptable
12692 /// as a redeclaration of the given tag declaration.
12694 /// \returns true if the new tag kind is acceptable, false otherwise.
12695 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12696 TagTypeKind NewTag, bool isDefinition,
12697 SourceLocation NewTagLoc,
12698 const IdentifierInfo *Name) {
12699 // C++ [dcl.type.elab]p3:
12700 // The class-key or enum keyword present in the
12701 // elaborated-type-specifier shall agree in kind with the
12702 // declaration to which the name in the elaborated-type-specifier
12703 // refers. This rule also applies to the form of
12704 // elaborated-type-specifier that declares a class-name or
12705 // friend class since it can be construed as referring to the
12706 // definition of the class. Thus, in any
12707 // elaborated-type-specifier, the enum keyword shall be used to
12708 // refer to an enumeration (7.2), the union class-key shall be
12709 // used to refer to a union (clause 9), and either the class or
12710 // struct class-key shall be used to refer to a class (clause 9)
12711 // declared using the class or struct class-key.
12712 TagTypeKind OldTag = Previous->getTagKind();
12713 if (!isDefinition || !isClassCompatTagKind(NewTag))
12714 if (OldTag == NewTag)
12717 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12718 // Warn about the struct/class tag mismatch.
12719 bool isTemplate = false;
12720 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12721 isTemplate = Record->getDescribedClassTemplate();
12723 if (inTemplateInstantiation()) {
12724 // In a template instantiation, do not offer fix-its for tag mismatches
12725 // since they usually mess up the template instead of fixing the problem.
12726 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12727 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12728 << getRedeclDiagFromTagKind(OldTag);
12732 if (isDefinition) {
12733 // On definitions, check previous tags and issue a fix-it for each
12734 // one that doesn't match the current tag.
12735 if (Previous->getDefinition()) {
12736 // Don't suggest fix-its for redefinitions.
12740 bool previousMismatch = false;
12741 for (auto I : Previous->redecls()) {
12742 if (I->getTagKind() != NewTag) {
12743 if (!previousMismatch) {
12744 previousMismatch = true;
12745 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12746 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12747 << getRedeclDiagFromTagKind(I->getTagKind());
12749 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12750 << getRedeclDiagFromTagKind(NewTag)
12751 << FixItHint::CreateReplacement(I->getInnerLocStart(),
12752 TypeWithKeyword::getTagTypeKindName(NewTag));
12758 // Check for a previous definition. If current tag and definition
12759 // are same type, do nothing. If no definition, but disagree with
12760 // with previous tag type, give a warning, but no fix-it.
12761 const TagDecl *Redecl = Previous->getDefinition() ?
12762 Previous->getDefinition() : Previous;
12763 if (Redecl->getTagKind() == NewTag) {
12767 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12768 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12769 << getRedeclDiagFromTagKind(OldTag);
12770 Diag(Redecl->getLocation(), diag::note_previous_use);
12772 // If there is a previous definition, suggest a fix-it.
12773 if (Previous->getDefinition()) {
12774 Diag(NewTagLoc, diag::note_struct_class_suggestion)
12775 << getRedeclDiagFromTagKind(Redecl->getTagKind())
12776 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12777 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12785 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12786 /// from an outer enclosing namespace or file scope inside a friend declaration.
12787 /// This should provide the commented out code in the following snippet:
12791 /// struct Y { friend struct /*N::*/ X; };
12794 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12795 SourceLocation NameLoc) {
12796 // While the decl is in a namespace, do repeated lookup of that name and see
12797 // if we get the same namespace back. If we do not, continue until
12798 // translation unit scope, at which point we have a fully qualified NNS.
12799 SmallVector<IdentifierInfo *, 4> Namespaces;
12800 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12801 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12802 // This tag should be declared in a namespace, which can only be enclosed by
12803 // other namespaces. Bail if there's an anonymous namespace in the chain.
12804 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12805 if (!Namespace || Namespace->isAnonymousNamespace())
12806 return FixItHint();
12807 IdentifierInfo *II = Namespace->getIdentifier();
12808 Namespaces.push_back(II);
12809 NamedDecl *Lookup = SemaRef.LookupSingleName(
12810 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12811 if (Lookup == Namespace)
12815 // Once we have all the namespaces, reverse them to go outermost first, and
12817 SmallString<64> Insertion;
12818 llvm::raw_svector_ostream OS(Insertion);
12819 if (DC->isTranslationUnit())
12821 std::reverse(Namespaces.begin(), Namespaces.end());
12822 for (auto *II : Namespaces)
12823 OS << II->getName() << "::";
12824 return FixItHint::CreateInsertion(NameLoc, Insertion);
12827 /// \brief Determine whether a tag originally declared in context \p OldDC can
12828 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12829 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12830 /// using-declaration).
12831 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12832 DeclContext *NewDC) {
12833 OldDC = OldDC->getRedeclContext();
12834 NewDC = NewDC->getRedeclContext();
12836 if (OldDC->Equals(NewDC))
12839 // In MSVC mode, we allow a redeclaration if the contexts are related (either
12840 // encloses the other).
12841 if (S.getLangOpts().MSVCCompat &&
12842 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12848 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
12849 /// former case, Name will be non-null. In the later case, Name will be null.
12850 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12851 /// reference/declaration/definition of a tag.
12853 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12854 /// trailing-type-specifier) other than one in an alias-declaration.
12856 /// \param SkipBody If non-null, will be set to indicate if the caller should
12857 /// skip the definition of this tag and treat it as if it were a declaration.
12858 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12859 SourceLocation KWLoc, CXXScopeSpec &SS,
12860 IdentifierInfo *Name, SourceLocation NameLoc,
12861 AttributeList *Attr, AccessSpecifier AS,
12862 SourceLocation ModulePrivateLoc,
12863 MultiTemplateParamsArg TemplateParameterLists,
12864 bool &OwnedDecl, bool &IsDependent,
12865 SourceLocation ScopedEnumKWLoc,
12866 bool ScopedEnumUsesClassTag,
12867 TypeResult UnderlyingType,
12868 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12869 // If this is not a definition, it must have a name.
12870 IdentifierInfo *OrigName = Name;
12871 assert((Name != nullptr || TUK == TUK_Definition) &&
12872 "Nameless record must be a definition!");
12873 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12876 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12877 bool ScopedEnum = ScopedEnumKWLoc.isValid();
12879 // FIXME: Check member specializations more carefully.
12880 bool isMemberSpecialization = false;
12881 bool Invalid = false;
12883 // We only need to do this matching if we have template parameters
12884 // or a scope specifier, which also conveniently avoids this work
12885 // for non-C++ cases.
12886 if (TemplateParameterLists.size() > 0 ||
12887 (SS.isNotEmpty() && TUK != TUK_Reference)) {
12888 if (TemplateParameterList *TemplateParams =
12889 MatchTemplateParametersToScopeSpecifier(
12890 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12891 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
12892 if (Kind == TTK_Enum) {
12893 Diag(KWLoc, diag::err_enum_template);
12897 if (TemplateParams->size() > 0) {
12898 // This is a declaration or definition of a class template (which may
12899 // be a member of another template).
12905 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12906 SS, Name, NameLoc, Attr,
12907 TemplateParams, AS,
12909 /*FriendLoc*/SourceLocation(),
12910 TemplateParameterLists.size()-1,
12911 TemplateParameterLists.data(),
12913 return Result.get();
12915 // The "template<>" header is extraneous.
12916 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12917 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12918 isMemberSpecialization = true;
12923 // Figure out the underlying type if this a enum declaration. We need to do
12924 // this early, because it's needed to detect if this is an incompatible
12926 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12927 bool EnumUnderlyingIsImplicit = false;
12929 if (Kind == TTK_Enum) {
12930 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12931 // No underlying type explicitly specified, or we failed to parse the
12932 // type, default to int.
12933 EnumUnderlying = Context.IntTy.getTypePtr();
12934 else if (UnderlyingType.get()) {
12935 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12936 // integral type; any cv-qualification is ignored.
12937 TypeSourceInfo *TI = nullptr;
12938 GetTypeFromParser(UnderlyingType.get(), &TI);
12939 EnumUnderlying = TI;
12941 if (CheckEnumUnderlyingType(TI))
12942 // Recover by falling back to int.
12943 EnumUnderlying = Context.IntTy.getTypePtr();
12945 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12946 UPPC_FixedUnderlyingType))
12947 EnumUnderlying = Context.IntTy.getTypePtr();
12949 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12950 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12951 // Microsoft enums are always of int type.
12952 EnumUnderlying = Context.IntTy.getTypePtr();
12953 EnumUnderlyingIsImplicit = true;
12958 DeclContext *SearchDC = CurContext;
12959 DeclContext *DC = CurContext;
12960 bool isStdBadAlloc = false;
12961 bool isStdAlignValT = false;
12963 RedeclarationKind Redecl = ForRedeclaration;
12964 if (TUK == TUK_Friend || TUK == TUK_Reference)
12965 Redecl = NotForRedeclaration;
12967 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12968 if (Name && SS.isNotEmpty()) {
12969 // We have a nested-name tag ('struct foo::bar').
12971 // Check for invalid 'foo::'.
12972 if (SS.isInvalid()) {
12974 goto CreateNewDecl;
12977 // If this is a friend or a reference to a class in a dependent
12978 // context, don't try to make a decl for it.
12979 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12980 DC = computeDeclContext(SS, false);
12982 IsDependent = true;
12986 DC = computeDeclContext(SS, true);
12988 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12994 if (RequireCompleteDeclContext(SS, DC))
12998 // Look-up name inside 'foo::'.
12999 LookupQualifiedName(Previous, DC);
13001 if (Previous.isAmbiguous())
13004 if (Previous.empty()) {
13005 // Name lookup did not find anything. However, if the
13006 // nested-name-specifier refers to the current instantiation,
13007 // and that current instantiation has any dependent base
13008 // classes, we might find something at instantiation time: treat
13009 // this as a dependent elaborated-type-specifier.
13010 // But this only makes any sense for reference-like lookups.
13011 if (Previous.wasNotFoundInCurrentInstantiation() &&
13012 (TUK == TUK_Reference || TUK == TUK_Friend)) {
13013 IsDependent = true;
13017 // A tag 'foo::bar' must already exist.
13018 Diag(NameLoc, diag::err_not_tag_in_scope)
13019 << Kind << Name << DC << SS.getRange();
13022 goto CreateNewDecl;
13025 // C++14 [class.mem]p14:
13026 // If T is the name of a class, then each of the following shall have a
13027 // name different from T:
13028 // -- every member of class T that is itself a type
13029 if (TUK != TUK_Reference && TUK != TUK_Friend &&
13030 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13033 // If this is a named struct, check to see if there was a previous forward
13034 // declaration or definition.
13035 // FIXME: We're looking into outer scopes here, even when we
13036 // shouldn't be. Doing so can result in ambiguities that we
13037 // shouldn't be diagnosing.
13038 LookupName(Previous, S);
13040 // When declaring or defining a tag, ignore ambiguities introduced
13041 // by types using'ed into this scope.
13042 if (Previous.isAmbiguous() &&
13043 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13044 LookupResult::Filter F = Previous.makeFilter();
13045 while (F.hasNext()) {
13046 NamedDecl *ND = F.next();
13047 if (!ND->getDeclContext()->getRedeclContext()->Equals(
13048 SearchDC->getRedeclContext()))
13054 // C++11 [namespace.memdef]p3:
13055 // If the name in a friend declaration is neither qualified nor
13056 // a template-id and the declaration is a function or an
13057 // elaborated-type-specifier, the lookup to determine whether
13058 // the entity has been previously declared shall not consider
13059 // any scopes outside the innermost enclosing namespace.
13061 // MSVC doesn't implement the above rule for types, so a friend tag
13062 // declaration may be a redeclaration of a type declared in an enclosing
13063 // scope. They do implement this rule for friend functions.
13065 // Does it matter that this should be by scope instead of by
13066 // semantic context?
13067 if (!Previous.empty() && TUK == TUK_Friend) {
13068 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13069 LookupResult::Filter F = Previous.makeFilter();
13070 bool FriendSawTagOutsideEnclosingNamespace = false;
13071 while (F.hasNext()) {
13072 NamedDecl *ND = F.next();
13073 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13074 if (DC->isFileContext() &&
13075 !EnclosingNS->Encloses(ND->getDeclContext())) {
13076 if (getLangOpts().MSVCCompat)
13077 FriendSawTagOutsideEnclosingNamespace = true;
13084 // Diagnose this MSVC extension in the easy case where lookup would have
13085 // unambiguously found something outside the enclosing namespace.
13086 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13087 NamedDecl *ND = Previous.getFoundDecl();
13088 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13089 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13093 // Note: there used to be some attempt at recovery here.
13094 if (Previous.isAmbiguous())
13097 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13098 // FIXME: This makes sure that we ignore the contexts associated
13099 // with C structs, unions, and enums when looking for a matching
13100 // tag declaration or definition. See the similar lookup tweak
13101 // in Sema::LookupName; is there a better way to deal with this?
13102 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13103 SearchDC = SearchDC->getParent();
13107 if (Previous.isSingleResult() &&
13108 Previous.getFoundDecl()->isTemplateParameter()) {
13109 // Maybe we will complain about the shadowed template parameter.
13110 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13111 // Just pretend that we didn't see the previous declaration.
13115 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13116 DC->Equals(getStdNamespace())) {
13117 if (Name->isStr("bad_alloc")) {
13118 // This is a declaration of or a reference to "std::bad_alloc".
13119 isStdBadAlloc = true;
13121 // If std::bad_alloc has been implicitly declared (but made invisible to
13122 // name lookup), fill in this implicit declaration as the previous
13123 // declaration, so that the declarations get chained appropriately.
13124 if (Previous.empty() && StdBadAlloc)
13125 Previous.addDecl(getStdBadAlloc());
13126 } else if (Name->isStr("align_val_t")) {
13127 isStdAlignValT = true;
13128 if (Previous.empty() && StdAlignValT)
13129 Previous.addDecl(getStdAlignValT());
13133 // If we didn't find a previous declaration, and this is a reference
13134 // (or friend reference), move to the correct scope. In C++, we
13135 // also need to do a redeclaration lookup there, just in case
13136 // there's a shadow friend decl.
13137 if (Name && Previous.empty() &&
13138 (TUK == TUK_Reference || TUK == TUK_Friend)) {
13139 if (Invalid) goto CreateNewDecl;
13140 assert(SS.isEmpty());
13142 if (TUK == TUK_Reference) {
13143 // C++ [basic.scope.pdecl]p5:
13144 // -- for an elaborated-type-specifier of the form
13146 // class-key identifier
13148 // if the elaborated-type-specifier is used in the
13149 // decl-specifier-seq or parameter-declaration-clause of a
13150 // function defined in namespace scope, the identifier is
13151 // declared as a class-name in the namespace that contains
13152 // the declaration; otherwise, except as a friend
13153 // declaration, the identifier is declared in the smallest
13154 // non-class, non-function-prototype scope that contains the
13157 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13158 // C structs and unions.
13160 // It is an error in C++ to declare (rather than define) an enum
13161 // type, including via an elaborated type specifier. We'll
13162 // diagnose that later; for now, declare the enum in the same
13163 // scope as we would have picked for any other tag type.
13165 // GNU C also supports this behavior as part of its incomplete
13166 // enum types extension, while GNU C++ does not.
13168 // Find the context where we'll be declaring the tag.
13169 // FIXME: We would like to maintain the current DeclContext as the
13170 // lexical context,
13171 SearchDC = getTagInjectionContext(SearchDC);
13173 // Find the scope where we'll be declaring the tag.
13174 S = getTagInjectionScope(S, getLangOpts());
13176 assert(TUK == TUK_Friend);
13177 // C++ [namespace.memdef]p3:
13178 // If a friend declaration in a non-local class first declares a
13179 // class or function, the friend class or function is a member of
13180 // the innermost enclosing namespace.
13181 SearchDC = SearchDC->getEnclosingNamespaceContext();
13184 // In C++, we need to do a redeclaration lookup to properly
13185 // diagnose some problems.
13186 // FIXME: redeclaration lookup is also used (with and without C++) to find a
13187 // hidden declaration so that we don't get ambiguity errors when using a
13188 // type declared by an elaborated-type-specifier. In C that is not correct
13189 // and we should instead merge compatible types found by lookup.
13190 if (getLangOpts().CPlusPlus) {
13191 Previous.setRedeclarationKind(ForRedeclaration);
13192 LookupQualifiedName(Previous, SearchDC);
13194 Previous.setRedeclarationKind(ForRedeclaration);
13195 LookupName(Previous, S);
13199 // If we have a known previous declaration to use, then use it.
13200 if (Previous.empty() && SkipBody && SkipBody->Previous)
13201 Previous.addDecl(SkipBody->Previous);
13203 if (!Previous.empty()) {
13204 NamedDecl *PrevDecl = Previous.getFoundDecl();
13205 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13207 // It's okay to have a tag decl in the same scope as a typedef
13208 // which hides a tag decl in the same scope. Finding this
13209 // insanity with a redeclaration lookup can only actually happen
13212 // This is also okay for elaborated-type-specifiers, which is
13213 // technically forbidden by the current standard but which is
13214 // okay according to the likely resolution of an open issue;
13215 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13216 if (getLangOpts().CPlusPlus) {
13217 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13218 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13219 TagDecl *Tag = TT->getDecl();
13220 if (Tag->getDeclName() == Name &&
13221 Tag->getDeclContext()->getRedeclContext()
13222 ->Equals(TD->getDeclContext()->getRedeclContext())) {
13225 Previous.addDecl(Tag);
13226 Previous.resolveKind();
13232 // If this is a redeclaration of a using shadow declaration, it must
13233 // declare a tag in the same context. In MSVC mode, we allow a
13234 // redefinition if either context is within the other.
13235 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13236 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13237 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13238 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13239 !(OldTag && isAcceptableTagRedeclContext(
13240 *this, OldTag->getDeclContext(), SearchDC))) {
13241 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13242 Diag(Shadow->getTargetDecl()->getLocation(),
13243 diag::note_using_decl_target);
13244 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13246 // Recover by ignoring the old declaration.
13248 goto CreateNewDecl;
13252 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13253 // If this is a use of a previous tag, or if the tag is already declared
13254 // in the same scope (so that the definition/declaration completes or
13255 // rementions the tag), reuse the decl.
13256 if (TUK == TUK_Reference || TUK == TUK_Friend ||
13257 isDeclInScope(DirectPrevDecl, SearchDC, S,
13258 SS.isNotEmpty() || isMemberSpecialization)) {
13259 // Make sure that this wasn't declared as an enum and now used as a
13260 // struct or something similar.
13261 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13262 TUK == TUK_Definition, KWLoc,
13264 bool SafeToContinue
13265 = (PrevTagDecl->getTagKind() != TTK_Enum &&
13267 if (SafeToContinue)
13268 Diag(KWLoc, diag::err_use_with_wrong_tag)
13270 << FixItHint::CreateReplacement(SourceRange(KWLoc),
13271 PrevTagDecl->getKindName());
13273 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13274 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13276 if (SafeToContinue)
13277 Kind = PrevTagDecl->getTagKind();
13279 // Recover by making this an anonymous redefinition.
13286 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13287 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13289 // If this is an elaborated-type-specifier for a scoped enumeration,
13290 // the 'class' keyword is not necessary and not permitted.
13291 if (TUK == TUK_Reference || TUK == TUK_Friend) {
13293 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13294 << PrevEnum->isScoped()
13295 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13296 return PrevTagDecl;
13299 QualType EnumUnderlyingTy;
13300 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13301 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13302 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13303 EnumUnderlyingTy = QualType(T, 0);
13305 // All conflicts with previous declarations are recovered by
13306 // returning the previous declaration, unless this is a definition,
13307 // in which case we want the caller to bail out.
13308 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13309 ScopedEnum, EnumUnderlyingTy,
13310 EnumUnderlyingIsImplicit, PrevEnum))
13311 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13314 // C++11 [class.mem]p1:
13315 // A member shall not be declared twice in the member-specification,
13316 // except that a nested class or member class template can be declared
13317 // and then later defined.
13318 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13319 S->isDeclScope(PrevDecl)) {
13320 Diag(NameLoc, diag::ext_member_redeclared);
13321 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13325 // If this is a use, just return the declaration we found, unless
13326 // we have attributes.
13327 if (TUK == TUK_Reference || TUK == TUK_Friend) {
13329 // FIXME: Diagnose these attributes. For now, we create a new
13330 // declaration to hold them.
13331 } else if (TUK == TUK_Reference &&
13332 (PrevTagDecl->getFriendObjectKind() ==
13333 Decl::FOK_Undeclared ||
13334 PP.getModuleContainingLocation(
13335 PrevDecl->getLocation()) !=
13336 PP.getModuleContainingLocation(KWLoc)) &&
13338 // This declaration is a reference to an existing entity, but
13339 // has different visibility from that entity: it either makes
13340 // a friend visible or it makes a type visible in a new module.
13341 // In either case, create a new declaration. We only do this if
13342 // the declaration would have meant the same thing if no prior
13343 // declaration were found, that is, if it was found in the same
13344 // scope where we would have injected a declaration.
13345 if (!getTagInjectionContext(CurContext)->getRedeclContext()
13346 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13347 return PrevTagDecl;
13348 // This is in the injected scope, create a new declaration in
13350 S = getTagInjectionScope(S, getLangOpts());
13352 return PrevTagDecl;
13356 // Diagnose attempts to redefine a tag.
13357 if (TUK == TUK_Definition) {
13358 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13359 // If we're defining a specialization and the previous definition
13360 // is from an implicit instantiation, don't emit an error
13361 // here; we'll catch this in the general case below.
13362 bool IsExplicitSpecializationAfterInstantiation = false;
13363 if (isMemberSpecialization) {
13364 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13365 IsExplicitSpecializationAfterInstantiation =
13366 RD->getTemplateSpecializationKind() !=
13367 TSK_ExplicitSpecialization;
13368 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13369 IsExplicitSpecializationAfterInstantiation =
13370 ED->getTemplateSpecializationKind() !=
13371 TSK_ExplicitSpecialization;
13374 NamedDecl *Hidden = nullptr;
13375 if (SkipBody && getLangOpts().CPlusPlus &&
13376 !hasVisibleDefinition(Def, &Hidden)) {
13377 // There is a definition of this tag, but it is not visible. We
13378 // explicitly make use of C++'s one definition rule here, and
13379 // assume that this definition is identical to the hidden one
13380 // we already have. Make the existing definition visible and
13381 // use it in place of this one.
13382 SkipBody->ShouldSkip = true;
13383 makeMergedDefinitionVisible(Hidden, KWLoc);
13385 } else if (!IsExplicitSpecializationAfterInstantiation) {
13386 // A redeclaration in function prototype scope in C isn't
13387 // visible elsewhere, so merely issue a warning.
13388 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13389 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13391 Diag(NameLoc, diag::err_redefinition) << Name;
13392 Diag(Def->getLocation(), diag::note_previous_definition);
13393 // If this is a redefinition, recover by making this
13394 // struct be anonymous, which will make any later
13395 // references get the previous definition.
13401 // If the type is currently being defined, complain
13402 // about a nested redefinition.
13403 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13404 if (TD->isBeingDefined()) {
13405 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13406 Diag(PrevTagDecl->getLocation(),
13407 diag::note_previous_definition);
13414 // Okay, this is definition of a previously declared or referenced
13415 // tag. We're going to create a new Decl for it.
13418 // Okay, we're going to make a redeclaration. If this is some kind
13419 // of reference, make sure we build the redeclaration in the same DC
13420 // as the original, and ignore the current access specifier.
13421 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13422 SearchDC = PrevTagDecl->getDeclContext();
13426 // If we get here we have (another) forward declaration or we
13427 // have a definition. Just create a new decl.
13430 // If we get here, this is a definition of a new tag type in a nested
13431 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13432 // new decl/type. We set PrevDecl to NULL so that the entities
13433 // have distinct types.
13436 // If we get here, we're going to create a new Decl. If PrevDecl
13437 // is non-NULL, it's a definition of the tag declared by
13438 // PrevDecl. If it's NULL, we have a new definition.
13440 // Otherwise, PrevDecl is not a tag, but was found with tag
13441 // lookup. This is only actually possible in C++, where a few
13442 // things like templates still live in the tag namespace.
13444 // Use a better diagnostic if an elaborated-type-specifier
13445 // found the wrong kind of type on the first
13446 // (non-redeclaration) lookup.
13447 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13448 !Previous.isForRedeclaration()) {
13449 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13450 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13452 Diag(PrevDecl->getLocation(), diag::note_declared_at);
13455 // Otherwise, only diagnose if the declaration is in scope.
13456 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13457 SS.isNotEmpty() || isMemberSpecialization)) {
13460 // Diagnose implicit declarations introduced by elaborated types.
13461 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13462 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13463 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13464 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13467 // Otherwise it's a declaration. Call out a particularly common
13469 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13471 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13472 Diag(NameLoc, diag::err_tag_definition_of_typedef)
13473 << Name << Kind << TND->getUnderlyingType();
13474 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13477 // Otherwise, diagnose.
13479 // The tag name clashes with something else in the target scope,
13480 // issue an error and recover by making this tag be anonymous.
13481 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13482 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13487 // The existing declaration isn't relevant to us; we're in a
13488 // new scope, so clear out the previous declaration.
13495 TagDecl *PrevDecl = nullptr;
13496 if (Previous.isSingleResult())
13497 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13499 // If there is an identifier, use the location of the identifier as the
13500 // location of the decl, otherwise use the location of the struct/union
13502 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13504 // Otherwise, create a new declaration. If there is a previous
13505 // declaration of the same entity, the two will be linked via
13509 bool IsForwardReference = false;
13510 if (Kind == TTK_Enum) {
13511 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13512 // enum X { A, B, C } D; D should chain to X.
13513 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13514 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13515 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13517 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13518 StdAlignValT = cast<EnumDecl>(New);
13520 // If this is an undefined enum, warn.
13521 if (TUK != TUK_Definition && !Invalid) {
13523 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13524 cast<EnumDecl>(New)->isFixed()) {
13525 // C++0x: 7.2p2: opaque-enum-declaration.
13526 // Conflicts are diagnosed above. Do nothing.
13528 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13529 Diag(Loc, diag::ext_forward_ref_enum_def)
13531 Diag(Def->getLocation(), diag::note_previous_definition);
13533 unsigned DiagID = diag::ext_forward_ref_enum;
13534 if (getLangOpts().MSVCCompat)
13535 DiagID = diag::ext_ms_forward_ref_enum;
13536 else if (getLangOpts().CPlusPlus)
13537 DiagID = diag::err_forward_ref_enum;
13540 // If this is a forward-declared reference to an enumeration, make a
13541 // note of it; we won't actually be introducing the declaration into
13542 // the declaration context.
13543 if (TUK == TUK_Reference)
13544 IsForwardReference = true;
13548 if (EnumUnderlying) {
13549 EnumDecl *ED = cast<EnumDecl>(New);
13550 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13551 ED->setIntegerTypeSourceInfo(TI);
13553 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13554 ED->setPromotionType(ED->getIntegerType());
13557 // struct/union/class
13559 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13560 // struct X { int A; } D; D should chain to X.
13561 if (getLangOpts().CPlusPlus) {
13562 // FIXME: Look for a way to use RecordDecl for simple structs.
13563 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13564 cast_or_null<CXXRecordDecl>(PrevDecl));
13566 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13567 StdBadAlloc = cast<CXXRecordDecl>(New);
13569 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13570 cast_or_null<RecordDecl>(PrevDecl));
13573 // C++11 [dcl.type]p3:
13574 // A type-specifier-seq shall not define a class or enumeration [...].
13575 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13576 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13577 << Context.getTagDeclType(New);
13581 // Maybe add qualifier info.
13582 if (SS.isNotEmpty()) {
13584 // If this is either a declaration or a definition, check the
13585 // nested-name-specifier against the current context. We don't do this
13586 // for explicit specializations, because they have similar checking
13587 // (with more specific diagnostics) in the call to
13588 // CheckMemberSpecialization, below.
13589 if (!isMemberSpecialization &&
13590 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13591 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13594 New->setQualifierInfo(SS.getWithLocInContext(Context));
13595 if (TemplateParameterLists.size() > 0) {
13596 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13603 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13604 // Add alignment attributes if necessary; these attributes are checked when
13605 // the ASTContext lays out the structure.
13607 // It is important for implementing the correct semantics that this
13608 // happen here (in act on tag decl). The #pragma pack stack is
13609 // maintained as a result of parser callbacks which can occur at
13610 // many points during the parsing of a struct declaration (because
13611 // the #pragma tokens are effectively skipped over during the
13612 // parsing of the struct).
13613 if (TUK == TUK_Definition) {
13614 AddAlignmentAttributesForRecord(RD);
13615 AddMsStructLayoutForRecord(RD);
13619 if (ModulePrivateLoc.isValid()) {
13620 if (isMemberSpecialization)
13621 Diag(New->getLocation(), diag::err_module_private_specialization)
13623 << FixItHint::CreateRemoval(ModulePrivateLoc);
13624 // __module_private__ does not apply to local classes. However, we only
13625 // diagnose this as an error when the declaration specifiers are
13626 // freestanding. Here, we just ignore the __module_private__.
13627 else if (!SearchDC->isFunctionOrMethod())
13628 New->setModulePrivate();
13631 // If this is a specialization of a member class (of a class template),
13632 // check the specialization.
13633 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13636 // If we're declaring or defining a tag in function prototype scope in C,
13637 // note that this type can only be used within the function and add it to
13638 // the list of decls to inject into the function definition scope.
13639 if ((Name || Kind == TTK_Enum) &&
13640 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13641 if (getLangOpts().CPlusPlus) {
13642 // C++ [dcl.fct]p6:
13643 // Types shall not be defined in return or parameter types.
13644 if (TUK == TUK_Definition && !IsTypeSpecifier) {
13645 Diag(Loc, diag::err_type_defined_in_param_type)
13649 } else if (!PrevDecl) {
13650 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13655 New->setInvalidDecl();
13657 // Set the lexical context. If the tag has a C++ scope specifier, the
13658 // lexical context will be different from the semantic context.
13659 New->setLexicalDeclContext(CurContext);
13661 // Mark this as a friend decl if applicable.
13662 // In Microsoft mode, a friend declaration also acts as a forward
13663 // declaration so we always pass true to setObjectOfFriendDecl to make
13664 // the tag name visible.
13665 if (TUK == TUK_Friend)
13666 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13668 // Set the access specifier.
13669 if (!Invalid && SearchDC->isRecord())
13670 SetMemberAccessSpecifier(New, PrevDecl, AS);
13672 if (TUK == TUK_Definition)
13673 New->startDefinition();
13676 ProcessDeclAttributeList(S, New, Attr);
13678 // If this has an identifier, add it to the scope stack.
13679 if (TUK == TUK_Friend) {
13680 // We might be replacing an existing declaration in the lookup tables;
13681 // if so, borrow its access specifier.
13683 New->setAccess(PrevDecl->getAccess());
13685 DeclContext *DC = New->getDeclContext()->getRedeclContext();
13686 DC->makeDeclVisibleInContext(New);
13687 if (Name) // can be null along some error paths
13688 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13689 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13691 S = getNonFieldDeclScope(S);
13692 PushOnScopeChains(New, S, !IsForwardReference);
13693 if (IsForwardReference)
13694 SearchDC->makeDeclVisibleInContext(New);
13696 CurContext->addDecl(New);
13699 // If this is the C FILE type, notify the AST context.
13700 if (IdentifierInfo *II = New->getIdentifier())
13701 if (!New->isInvalidDecl() &&
13702 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13704 Context.setFILEDecl(New);
13707 mergeDeclAttributes(New, PrevDecl);
13709 // If there's a #pragma GCC visibility in scope, set the visibility of this
13711 AddPushedVisibilityAttribute(New);
13714 // In C++, don't return an invalid declaration. We can't recover well from
13715 // the cases where we make the type anonymous.
13716 if (Invalid && getLangOpts().CPlusPlus) {
13717 if (New->isBeingDefined())
13718 if (auto RD = dyn_cast<RecordDecl>(New))
13719 RD->completeDefinition();
13726 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13727 AdjustDeclIfTemplate(TagD);
13728 TagDecl *Tag = cast<TagDecl>(TagD);
13730 // Enter the tag context.
13731 PushDeclContext(S, Tag);
13733 ActOnDocumentableDecl(TagD);
13735 // If there's a #pragma GCC visibility in scope, set the visibility of this
13737 AddPushedVisibilityAttribute(Tag);
13740 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13741 assert(isa<ObjCContainerDecl>(IDecl) &&
13742 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13743 DeclContext *OCD = cast<DeclContext>(IDecl);
13744 assert(getContainingDC(OCD) == CurContext &&
13745 "The next DeclContext should be lexically contained in the current one.");
13750 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13751 SourceLocation FinalLoc,
13752 bool IsFinalSpelledSealed,
13753 SourceLocation LBraceLoc) {
13754 AdjustDeclIfTemplate(TagD);
13755 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13757 FieldCollector->StartClass();
13759 if (!Record->getIdentifier())
13762 if (FinalLoc.isValid())
13763 Record->addAttr(new (Context)
13764 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13767 // [...] The class-name is also inserted into the scope of the
13768 // class itself; this is known as the injected-class-name. For
13769 // purposes of access checking, the injected-class-name is treated
13770 // as if it were a public member name.
13771 CXXRecordDecl *InjectedClassName
13772 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13773 Record->getLocStart(), Record->getLocation(),
13774 Record->getIdentifier(),
13775 /*PrevDecl=*/nullptr,
13776 /*DelayTypeCreation=*/true);
13777 Context.getTypeDeclType(InjectedClassName, Record);
13778 InjectedClassName->setImplicit();
13779 InjectedClassName->setAccess(AS_public);
13780 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13781 InjectedClassName->setDescribedClassTemplate(Template);
13782 PushOnScopeChains(InjectedClassName, S);
13783 assert(InjectedClassName->isInjectedClassName() &&
13784 "Broken injected-class-name");
13787 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13788 SourceRange BraceRange) {
13789 AdjustDeclIfTemplate(TagD);
13790 TagDecl *Tag = cast<TagDecl>(TagD);
13791 Tag->setBraceRange(BraceRange);
13793 // Make sure we "complete" the definition even it is invalid.
13794 if (Tag->isBeingDefined()) {
13795 assert(Tag->isInvalidDecl() && "We should already have completed it");
13796 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13797 RD->completeDefinition();
13800 if (isa<CXXRecordDecl>(Tag)) {
13801 FieldCollector->FinishClass();
13804 // Exit this scope of this tag's definition.
13807 if (getCurLexicalContext()->isObjCContainer() &&
13808 Tag->getDeclContext()->isFileContext())
13809 Tag->setTopLevelDeclInObjCContainer();
13811 // Notify the consumer that we've defined a tag.
13812 if (!Tag->isInvalidDecl())
13813 Consumer.HandleTagDeclDefinition(Tag);
13816 void Sema::ActOnObjCContainerFinishDefinition() {
13817 // Exit this scope of this interface definition.
13821 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13822 assert(DC == CurContext && "Mismatch of container contexts");
13823 OriginalLexicalContext = DC;
13824 ActOnObjCContainerFinishDefinition();
13827 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13828 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13829 OriginalLexicalContext = nullptr;
13832 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13833 AdjustDeclIfTemplate(TagD);
13834 TagDecl *Tag = cast<TagDecl>(TagD);
13835 Tag->setInvalidDecl();
13837 // Make sure we "complete" the definition even it is invalid.
13838 if (Tag->isBeingDefined()) {
13839 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13840 RD->completeDefinition();
13843 // We're undoing ActOnTagStartDefinition here, not
13844 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13845 // the FieldCollector.
13850 // Note that FieldName may be null for anonymous bitfields.
13851 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13852 IdentifierInfo *FieldName,
13853 QualType FieldTy, bool IsMsStruct,
13854 Expr *BitWidth, bool *ZeroWidth) {
13855 // Default to true; that shouldn't confuse checks for emptiness
13859 // C99 6.7.2.1p4 - verify the field type.
13860 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13861 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13862 // Handle incomplete types with specific error.
13863 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13864 return ExprError();
13866 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13867 << FieldName << FieldTy << BitWidth->getSourceRange();
13868 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13869 << FieldTy << BitWidth->getSourceRange();
13870 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13871 UPPC_BitFieldWidth))
13872 return ExprError();
13874 // If the bit-width is type- or value-dependent, don't try to check
13876 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13879 llvm::APSInt Value;
13880 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13881 if (ICE.isInvalid())
13883 BitWidth = ICE.get();
13885 if (Value != 0 && ZeroWidth)
13886 *ZeroWidth = false;
13888 // Zero-width bitfield is ok for anonymous field.
13889 if (Value == 0 && FieldName)
13890 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13892 if (Value.isSigned() && Value.isNegative()) {
13894 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13895 << FieldName << Value.toString(10);
13896 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13897 << Value.toString(10);
13900 if (!FieldTy->isDependentType()) {
13901 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13902 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13903 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13905 // Over-wide bitfields are an error in C or when using the MSVC bitfield
13907 bool CStdConstraintViolation =
13908 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13909 bool MSBitfieldViolation =
13910 Value.ugt(TypeStorageSize) &&
13911 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13912 if (CStdConstraintViolation || MSBitfieldViolation) {
13913 unsigned DiagWidth =
13914 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13916 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13917 << FieldName << (unsigned)Value.getZExtValue()
13918 << !CStdConstraintViolation << DiagWidth;
13920 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13921 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13925 // Warn on types where the user might conceivably expect to get all
13926 // specified bits as value bits: that's all integral types other than
13928 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13930 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13931 << FieldName << (unsigned)Value.getZExtValue()
13932 << (unsigned)TypeWidth;
13934 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13935 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13942 /// ActOnField - Each field of a C struct/union is passed into this in order
13943 /// to create a FieldDecl object for it.
13944 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13945 Declarator &D, Expr *BitfieldWidth) {
13946 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13947 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13948 /*InitStyle=*/ICIS_NoInit, AS_public);
13952 /// HandleField - Analyze a field of a C struct or a C++ data member.
13954 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13955 SourceLocation DeclStart,
13956 Declarator &D, Expr *BitWidth,
13957 InClassInitStyle InitStyle,
13958 AccessSpecifier AS) {
13959 if (D.isDecompositionDeclarator()) {
13960 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13961 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13962 << Decomp.getSourceRange();
13966 IdentifierInfo *II = D.getIdentifier();
13967 SourceLocation Loc = DeclStart;
13968 if (II) Loc = D.getIdentifierLoc();
13970 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13971 QualType T = TInfo->getType();
13972 if (getLangOpts().CPlusPlus) {
13973 CheckExtraCXXDefaultArguments(D);
13975 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13976 UPPC_DataMemberType)) {
13977 D.setInvalidType();
13979 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13983 // TR 18037 does not allow fields to be declared with address spaces.
13984 if (T.getQualifiers().hasAddressSpace()) {
13985 Diag(Loc, diag::err_field_with_address_space);
13986 D.setInvalidType();
13989 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13990 // used as structure or union field: image, sampler, event or block types.
13991 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13992 T->isSamplerT() || T->isBlockPointerType())) {
13993 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13994 D.setInvalidType();
13997 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13999 if (D.getDeclSpec().isInlineSpecified())
14000 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14001 << getLangOpts().CPlusPlus1z;
14002 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14003 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14004 diag::err_invalid_thread)
14005 << DeclSpec::getSpecifierName(TSCS);
14007 // Check to see if this name was declared as a member previously
14008 NamedDecl *PrevDecl = nullptr;
14009 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14010 LookupName(Previous, S);
14011 switch (Previous.getResultKind()) {
14012 case LookupResult::Found:
14013 case LookupResult::FoundUnresolvedValue:
14014 PrevDecl = Previous.getAsSingle<NamedDecl>();
14017 case LookupResult::FoundOverloaded:
14018 PrevDecl = Previous.getRepresentativeDecl();
14021 case LookupResult::NotFound:
14022 case LookupResult::NotFoundInCurrentInstantiation:
14023 case LookupResult::Ambiguous:
14026 Previous.suppressDiagnostics();
14028 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14029 // Maybe we will complain about the shadowed template parameter.
14030 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14031 // Just pretend that we didn't see the previous declaration.
14032 PrevDecl = nullptr;
14035 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14036 PrevDecl = nullptr;
14039 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14040 SourceLocation TSSL = D.getLocStart();
14042 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14043 TSSL, AS, PrevDecl, &D);
14045 if (NewFD->isInvalidDecl())
14046 Record->setInvalidDecl();
14048 if (D.getDeclSpec().isModulePrivateSpecified())
14049 NewFD->setModulePrivate();
14051 if (NewFD->isInvalidDecl() && PrevDecl) {
14052 // Don't introduce NewFD into scope; there's already something
14053 // with the same name in the same scope.
14055 PushOnScopeChains(NewFD, S);
14057 Record->addDecl(NewFD);
14062 /// \brief Build a new FieldDecl and check its well-formedness.
14064 /// This routine builds a new FieldDecl given the fields name, type,
14065 /// record, etc. \p PrevDecl should refer to any previous declaration
14066 /// with the same name and in the same scope as the field to be
14069 /// \returns a new FieldDecl.
14071 /// \todo The Declarator argument is a hack. It will be removed once
14072 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14073 TypeSourceInfo *TInfo,
14074 RecordDecl *Record, SourceLocation Loc,
14075 bool Mutable, Expr *BitWidth,
14076 InClassInitStyle InitStyle,
14077 SourceLocation TSSL,
14078 AccessSpecifier AS, NamedDecl *PrevDecl,
14080 IdentifierInfo *II = Name.getAsIdentifierInfo();
14081 bool InvalidDecl = false;
14082 if (D) InvalidDecl = D->isInvalidType();
14084 // If we receive a broken type, recover by assuming 'int' and
14085 // marking this declaration as invalid.
14087 InvalidDecl = true;
14091 QualType EltTy = Context.getBaseElementType(T);
14092 if (!EltTy->isDependentType()) {
14093 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14094 // Fields of incomplete type force their record to be invalid.
14095 Record->setInvalidDecl();
14096 InvalidDecl = true;
14099 EltTy->isIncompleteType(&Def);
14100 if (Def && Def->isInvalidDecl()) {
14101 Record->setInvalidDecl();
14102 InvalidDecl = true;
14107 // OpenCL v1.2 s6.9.c: bitfields are not supported.
14108 if (BitWidth && getLangOpts().OpenCL) {
14109 Diag(Loc, diag::err_opencl_bitfields);
14110 InvalidDecl = true;
14113 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14114 // than a variably modified type.
14115 if (!InvalidDecl && T->isVariablyModifiedType()) {
14116 bool SizeIsNegative;
14117 llvm::APSInt Oversized;
14119 TypeSourceInfo *FixedTInfo =
14120 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14124 Diag(Loc, diag::warn_illegal_constant_array_size);
14125 TInfo = FixedTInfo;
14126 T = FixedTInfo->getType();
14128 if (SizeIsNegative)
14129 Diag(Loc, diag::err_typecheck_negative_array_size);
14130 else if (Oversized.getBoolValue())
14131 Diag(Loc, diag::err_array_too_large)
14132 << Oversized.toString(10);
14134 Diag(Loc, diag::err_typecheck_field_variable_size);
14135 InvalidDecl = true;
14139 // Fields can not have abstract class types
14140 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14141 diag::err_abstract_type_in_decl,
14142 AbstractFieldType))
14143 InvalidDecl = true;
14145 bool ZeroWidth = false;
14147 BitWidth = nullptr;
14148 // If this is declared as a bit-field, check the bit-field.
14150 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14153 InvalidDecl = true;
14154 BitWidth = nullptr;
14159 // Check that 'mutable' is consistent with the type of the declaration.
14160 if (!InvalidDecl && Mutable) {
14161 unsigned DiagID = 0;
14162 if (T->isReferenceType())
14163 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14164 : diag::err_mutable_reference;
14165 else if (T.isConstQualified())
14166 DiagID = diag::err_mutable_const;
14169 SourceLocation ErrLoc = Loc;
14170 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14171 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14172 Diag(ErrLoc, DiagID);
14173 if (DiagID != diag::ext_mutable_reference) {
14175 InvalidDecl = true;
14180 // C++11 [class.union]p8 (DR1460):
14181 // At most one variant member of a union may have a
14182 // brace-or-equal-initializer.
14183 if (InitStyle != ICIS_NoInit)
14184 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14186 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14187 BitWidth, Mutable, InitStyle);
14189 NewFD->setInvalidDecl();
14191 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14192 Diag(Loc, diag::err_duplicate_member) << II;
14193 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14194 NewFD->setInvalidDecl();
14197 if (!InvalidDecl && getLangOpts().CPlusPlus) {
14198 if (Record->isUnion()) {
14199 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14200 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14201 if (RDecl->getDefinition()) {
14202 // C++ [class.union]p1: An object of a class with a non-trivial
14203 // constructor, a non-trivial copy constructor, a non-trivial
14204 // destructor, or a non-trivial copy assignment operator
14205 // cannot be a member of a union, nor can an array of such
14207 if (CheckNontrivialField(NewFD))
14208 NewFD->setInvalidDecl();
14212 // C++ [class.union]p1: If a union contains a member of reference type,
14213 // the program is ill-formed, except when compiling with MSVC extensions
14215 if (EltTy->isReferenceType()) {
14216 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14217 diag::ext_union_member_of_reference_type :
14218 diag::err_union_member_of_reference_type)
14219 << NewFD->getDeclName() << EltTy;
14220 if (!getLangOpts().MicrosoftExt)
14221 NewFD->setInvalidDecl();
14226 // FIXME: We need to pass in the attributes given an AST
14227 // representation, not a parser representation.
14229 // FIXME: The current scope is almost... but not entirely... correct here.
14230 ProcessDeclAttributes(getCurScope(), NewFD, *D);
14232 if (NewFD->hasAttrs())
14233 CheckAlignasUnderalignment(NewFD);
14236 // In auto-retain/release, infer strong retension for fields of
14237 // retainable type.
14238 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14239 NewFD->setInvalidDecl();
14241 if (T.isObjCGCWeak())
14242 Diag(Loc, diag::warn_attribute_weak_on_field);
14244 NewFD->setAccess(AS);
14248 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14250 assert(getLangOpts().CPlusPlus && "valid check only for C++");
14252 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14255 QualType EltTy = Context.getBaseElementType(FD->getType());
14256 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14257 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14258 if (RDecl->getDefinition()) {
14259 // We check for copy constructors before constructors
14260 // because otherwise we'll never get complaints about
14261 // copy constructors.
14263 CXXSpecialMember member = CXXInvalid;
14264 // We're required to check for any non-trivial constructors. Since the
14265 // implicit default constructor is suppressed if there are any
14266 // user-declared constructors, we just need to check that there is a
14267 // trivial default constructor and a trivial copy constructor. (We don't
14268 // worry about move constructors here, since this is a C++98 check.)
14269 if (RDecl->hasNonTrivialCopyConstructor())
14270 member = CXXCopyConstructor;
14271 else if (!RDecl->hasTrivialDefaultConstructor())
14272 member = CXXDefaultConstructor;
14273 else if (RDecl->hasNonTrivialCopyAssignment())
14274 member = CXXCopyAssignment;
14275 else if (RDecl->hasNonTrivialDestructor())
14276 member = CXXDestructor;
14278 if (member != CXXInvalid) {
14279 if (!getLangOpts().CPlusPlus11 &&
14280 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14281 // Objective-C++ ARC: it is an error to have a non-trivial field of
14282 // a union. However, system headers in Objective-C programs
14283 // occasionally have Objective-C lifetime objects within unions,
14284 // and rather than cause the program to fail, we make those
14285 // members unavailable.
14286 SourceLocation Loc = FD->getLocation();
14287 if (getSourceManager().isInSystemHeader(Loc)) {
14288 if (!FD->hasAttr<UnavailableAttr>())
14289 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14290 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14295 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14296 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14297 diag::err_illegal_union_or_anon_struct_member)
14298 << FD->getParent()->isUnion() << FD->getDeclName() << member;
14299 DiagnoseNontrivial(RDecl, member);
14300 return !getLangOpts().CPlusPlus11;
14308 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14309 /// AST enum value.
14310 static ObjCIvarDecl::AccessControl
14311 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14312 switch (ivarVisibility) {
14313 default: llvm_unreachable("Unknown visitibility kind");
14314 case tok::objc_private: return ObjCIvarDecl::Private;
14315 case tok::objc_public: return ObjCIvarDecl::Public;
14316 case tok::objc_protected: return ObjCIvarDecl::Protected;
14317 case tok::objc_package: return ObjCIvarDecl::Package;
14321 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14322 /// in order to create an IvarDecl object for it.
14323 Decl *Sema::ActOnIvar(Scope *S,
14324 SourceLocation DeclStart,
14325 Declarator &D, Expr *BitfieldWidth,
14326 tok::ObjCKeywordKind Visibility) {
14328 IdentifierInfo *II = D.getIdentifier();
14329 Expr *BitWidth = (Expr*)BitfieldWidth;
14330 SourceLocation Loc = DeclStart;
14331 if (II) Loc = D.getIdentifierLoc();
14333 // FIXME: Unnamed fields can be handled in various different ways, for
14334 // example, unnamed unions inject all members into the struct namespace!
14336 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14337 QualType T = TInfo->getType();
14340 // 6.7.2.1p3, 6.7.2.1p4
14341 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14343 D.setInvalidType();
14350 if (T->isReferenceType()) {
14351 Diag(Loc, diag::err_ivar_reference_type);
14352 D.setInvalidType();
14354 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14355 // than a variably modified type.
14356 else if (T->isVariablyModifiedType()) {
14357 Diag(Loc, diag::err_typecheck_ivar_variable_size);
14358 D.setInvalidType();
14361 // Get the visibility (access control) for this ivar.
14362 ObjCIvarDecl::AccessControl ac =
14363 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14364 : ObjCIvarDecl::None;
14365 // Must set ivar's DeclContext to its enclosing interface.
14366 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14367 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14369 ObjCContainerDecl *EnclosingContext;
14370 if (ObjCImplementationDecl *IMPDecl =
14371 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14372 if (LangOpts.ObjCRuntime.isFragile()) {
14373 // Case of ivar declared in an implementation. Context is that of its class.
14374 EnclosingContext = IMPDecl->getClassInterface();
14375 assert(EnclosingContext && "Implementation has no class interface!");
14378 EnclosingContext = EnclosingDecl;
14380 if (ObjCCategoryDecl *CDecl =
14381 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14382 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14383 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14387 EnclosingContext = EnclosingDecl;
14390 // Construct the decl.
14391 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14392 DeclStart, Loc, II, T,
14393 TInfo, ac, (Expr *)BitfieldWidth);
14396 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14398 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14399 && !isa<TagDecl>(PrevDecl)) {
14400 Diag(Loc, diag::err_duplicate_member) << II;
14401 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14402 NewID->setInvalidDecl();
14406 // Process attributes attached to the ivar.
14407 ProcessDeclAttributes(S, NewID, D);
14409 if (D.isInvalidType())
14410 NewID->setInvalidDecl();
14412 // In ARC, infer 'retaining' for ivars of retainable type.
14413 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14414 NewID->setInvalidDecl();
14416 if (D.getDeclSpec().isModulePrivateSpecified())
14417 NewID->setModulePrivate();
14420 // FIXME: When interfaces are DeclContexts, we'll need to add
14421 // these to the interface.
14423 IdResolver.AddDecl(NewID);
14426 if (LangOpts.ObjCRuntime.isNonFragile() &&
14427 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14428 Diag(Loc, diag::warn_ivars_in_interface);
14433 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14434 /// class and class extensions. For every class \@interface and class
14435 /// extension \@interface, if the last ivar is a bitfield of any type,
14436 /// then add an implicit `char :0` ivar to the end of that interface.
14437 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14438 SmallVectorImpl<Decl *> &AllIvarDecls) {
14439 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14442 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14443 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14445 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14447 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14449 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14450 if (!CD->IsClassExtension())
14453 // No need to add this to end of @implementation.
14457 // All conditions are met. Add a new bitfield to the tail end of ivars.
14458 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14459 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14461 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14462 DeclLoc, DeclLoc, nullptr,
14464 Context.getTrivialTypeSourceInfo(Context.CharTy,
14466 ObjCIvarDecl::Private, BW,
14468 AllIvarDecls.push_back(Ivar);
14471 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14472 ArrayRef<Decl *> Fields, SourceLocation LBrac,
14473 SourceLocation RBrac, AttributeList *Attr) {
14474 assert(EnclosingDecl && "missing record or interface decl");
14476 // If this is an Objective-C @implementation or category and we have
14477 // new fields here we should reset the layout of the interface since
14478 // it will now change.
14479 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14480 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14481 switch (DC->getKind()) {
14483 case Decl::ObjCCategory:
14484 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14486 case Decl::ObjCImplementation:
14488 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14493 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14495 // Start counting up the number of named members; make sure to include
14496 // members of anonymous structs and unions in the total.
14497 unsigned NumNamedMembers = 0;
14499 for (const auto *I : Record->decls()) {
14500 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14501 if (IFD->getDeclName())
14506 // Verify that all the fields are okay.
14507 SmallVector<FieldDecl*, 32> RecFields;
14509 bool ObjCFieldLifetimeErrReported = false;
14510 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14512 FieldDecl *FD = cast<FieldDecl>(*i);
14514 // Get the type for the field.
14515 const Type *FDTy = FD->getType().getTypePtr();
14517 if (!FD->isAnonymousStructOrUnion()) {
14518 // Remember all fields written by the user.
14519 RecFields.push_back(FD);
14522 // If the field is already invalid for some reason, don't emit more
14523 // diagnostics about it.
14524 if (FD->isInvalidDecl()) {
14525 EnclosingDecl->setInvalidDecl();
14530 // A structure or union shall not contain a member with
14531 // incomplete or function type (hence, a structure shall not
14532 // contain an instance of itself, but may contain a pointer to
14533 // an instance of itself), except that the last member of a
14534 // structure with more than one named member may have incomplete
14535 // array type; such a structure (and any union containing,
14536 // possibly recursively, a member that is such a structure)
14537 // shall not be a member of a structure or an element of an
14539 if (FDTy->isFunctionType()) {
14540 // Field declared as a function.
14541 Diag(FD->getLocation(), diag::err_field_declared_as_function)
14542 << FD->getDeclName();
14543 FD->setInvalidDecl();
14544 EnclosingDecl->setInvalidDecl();
14546 } else if (FDTy->isIncompleteArrayType() && Record &&
14547 ((i + 1 == Fields.end() && !Record->isUnion()) ||
14548 ((getLangOpts().MicrosoftExt ||
14549 getLangOpts().CPlusPlus) &&
14550 (i + 1 == Fields.end() || Record->isUnion())))) {
14551 // Flexible array member.
14552 // Microsoft and g++ is more permissive regarding flexible array.
14553 // It will accept flexible array in union and also
14554 // as the sole element of a struct/class.
14555 unsigned DiagID = 0;
14556 if (Record->isUnion())
14557 DiagID = getLangOpts().MicrosoftExt
14558 ? diag::ext_flexible_array_union_ms
14559 : getLangOpts().CPlusPlus
14560 ? diag::ext_flexible_array_union_gnu
14561 : diag::err_flexible_array_union;
14562 else if (NumNamedMembers < 1)
14563 DiagID = getLangOpts().MicrosoftExt
14564 ? diag::ext_flexible_array_empty_aggregate_ms
14565 : getLangOpts().CPlusPlus
14566 ? diag::ext_flexible_array_empty_aggregate_gnu
14567 : diag::err_flexible_array_empty_aggregate;
14570 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14571 << Record->getTagKind();
14572 // While the layout of types that contain virtual bases is not specified
14573 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14574 // virtual bases after the derived members. This would make a flexible
14575 // array member declared at the end of an object not adjacent to the end
14577 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14578 if (RD->getNumVBases() != 0)
14579 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14580 << FD->getDeclName() << Record->getTagKind();
14581 if (!getLangOpts().C99)
14582 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14583 << FD->getDeclName() << Record->getTagKind();
14585 // If the element type has a non-trivial destructor, we would not
14586 // implicitly destroy the elements, so disallow it for now.
14588 // FIXME: GCC allows this. We should probably either implicitly delete
14589 // the destructor of the containing class, or just allow this.
14590 QualType BaseElem = Context.getBaseElementType(FD->getType());
14591 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14592 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14593 << FD->getDeclName() << FD->getType();
14594 FD->setInvalidDecl();
14595 EnclosingDecl->setInvalidDecl();
14598 // Okay, we have a legal flexible array member at the end of the struct.
14599 Record->setHasFlexibleArrayMember(true);
14600 } else if (!FDTy->isDependentType() &&
14601 RequireCompleteType(FD->getLocation(), FD->getType(),
14602 diag::err_field_incomplete)) {
14604 FD->setInvalidDecl();
14605 EnclosingDecl->setInvalidDecl();
14607 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14608 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14609 // A type which contains a flexible array member is considered to be a
14610 // flexible array member.
14611 Record->setHasFlexibleArrayMember(true);
14612 if (!Record->isUnion()) {
14613 // If this is a struct/class and this is not the last element, reject
14614 // it. Note that GCC supports variable sized arrays in the middle of
14616 if (i + 1 != Fields.end())
14617 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14618 << FD->getDeclName() << FD->getType();
14620 // We support flexible arrays at the end of structs in
14621 // other structs as an extension.
14622 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14623 << FD->getDeclName();
14627 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14628 RequireNonAbstractType(FD->getLocation(), FD->getType(),
14629 diag::err_abstract_type_in_decl,
14630 AbstractIvarType)) {
14631 // Ivars can not have abstract class types
14632 FD->setInvalidDecl();
14634 if (Record && FDTTy->getDecl()->hasObjectMember())
14635 Record->setHasObjectMember(true);
14636 if (Record && FDTTy->getDecl()->hasVolatileMember())
14637 Record->setHasVolatileMember(true);
14638 } else if (FDTy->isObjCObjectType()) {
14639 /// A field cannot be an Objective-c object
14640 Diag(FD->getLocation(), diag::err_statically_allocated_object)
14641 << FixItHint::CreateInsertion(FD->getLocation(), "*");
14642 QualType T = Context.getObjCObjectPointerType(FD->getType());
14644 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14645 Record && !ObjCFieldLifetimeErrReported &&
14646 (!getLangOpts().CPlusPlus || Record->isUnion())) {
14647 // It's an error in ARC or Weak if a field has lifetime.
14648 // We don't want to report this in a system header, though,
14649 // so we just make the field unavailable.
14650 // FIXME: that's really not sufficient; we need to make the type
14651 // itself invalid to, say, initialize or copy.
14652 QualType T = FD->getType();
14653 if (T.hasNonTrivialObjCLifetime()) {
14654 SourceLocation loc = FD->getLocation();
14655 if (getSourceManager().isInSystemHeader(loc)) {
14656 if (!FD->hasAttr<UnavailableAttr>()) {
14657 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14658 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14661 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14662 << T->isBlockPointerType() << Record->getTagKind();
14664 ObjCFieldLifetimeErrReported = true;
14666 } else if (getLangOpts().ObjC1 &&
14667 getLangOpts().getGC() != LangOptions::NonGC &&
14668 Record && !Record->hasObjectMember()) {
14669 if (FD->getType()->isObjCObjectPointerType() ||
14670 FD->getType().isObjCGCStrong())
14671 Record->setHasObjectMember(true);
14672 else if (Context.getAsArrayType(FD->getType())) {
14673 QualType BaseType = Context.getBaseElementType(FD->getType());
14674 if (BaseType->isRecordType() &&
14675 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14676 Record->setHasObjectMember(true);
14677 else if (BaseType->isObjCObjectPointerType() ||
14678 BaseType.isObjCGCStrong())
14679 Record->setHasObjectMember(true);
14682 if (Record && FD->getType().isVolatileQualified())
14683 Record->setHasVolatileMember(true);
14684 // Keep track of the number of named members.
14685 if (FD->getIdentifier())
14689 // Okay, we successfully defined 'Record'.
14691 bool Completed = false;
14692 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14693 if (!CXXRecord->isInvalidDecl()) {
14694 // Set access bits correctly on the directly-declared conversions.
14695 for (CXXRecordDecl::conversion_iterator
14696 I = CXXRecord->conversion_begin(),
14697 E = CXXRecord->conversion_end(); I != E; ++I)
14698 I.setAccess((*I)->getAccess());
14701 if (!CXXRecord->isDependentType()) {
14702 if (CXXRecord->hasUserDeclaredDestructor()) {
14703 // Adjust user-defined destructor exception spec.
14704 if (getLangOpts().CPlusPlus11)
14705 AdjustDestructorExceptionSpec(CXXRecord,
14706 CXXRecord->getDestructor());
14709 if (!CXXRecord->isInvalidDecl()) {
14710 // Add any implicitly-declared members to this class.
14711 AddImplicitlyDeclaredMembersToClass(CXXRecord);
14713 // If we have virtual base classes, we may end up finding multiple
14714 // final overriders for a given virtual function. Check for this
14716 if (CXXRecord->getNumVBases()) {
14717 CXXFinalOverriderMap FinalOverriders;
14718 CXXRecord->getFinalOverriders(FinalOverriders);
14720 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14721 MEnd = FinalOverriders.end();
14723 for (OverridingMethods::iterator SO = M->second.begin(),
14724 SOEnd = M->second.end();
14725 SO != SOEnd; ++SO) {
14726 assert(SO->second.size() > 0 &&
14727 "Virtual function without overridding functions?");
14728 if (SO->second.size() == 1)
14731 // C++ [class.virtual]p2:
14732 // In a derived class, if a virtual member function of a base
14733 // class subobject has more than one final overrider the
14734 // program is ill-formed.
14735 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14736 << (const NamedDecl *)M->first << Record;
14737 Diag(M->first->getLocation(),
14738 diag::note_overridden_virtual_function);
14739 for (OverridingMethods::overriding_iterator
14740 OM = SO->second.begin(),
14741 OMEnd = SO->second.end();
14743 Diag(OM->Method->getLocation(), diag::note_final_overrider)
14744 << (const NamedDecl *)M->first << OM->Method->getParent();
14746 Record->setInvalidDecl();
14749 CXXRecord->completeDefinition(&FinalOverriders);
14757 Record->completeDefinition();
14759 // We may have deferred checking for a deleted destructor. Check now.
14760 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14761 auto *Dtor = CXXRecord->getDestructor();
14762 if (Dtor && Dtor->isImplicit() &&
14763 ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14764 SetDeclDeleted(Dtor, CXXRecord->getLocation());
14767 if (Record->hasAttrs()) {
14768 CheckAlignasUnderalignment(Record);
14770 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14771 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14772 IA->getRange(), IA->getBestCase(),
14773 IA->getSemanticSpelling());
14776 // Check if the structure/union declaration is a type that can have zero
14777 // size in C. For C this is a language extension, for C++ it may cause
14778 // compatibility problems.
14779 bool CheckForZeroSize;
14780 if (!getLangOpts().CPlusPlus) {
14781 CheckForZeroSize = true;
14783 // For C++ filter out types that cannot be referenced in C code.
14784 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14786 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14787 !CXXRecord->isDependentType() &&
14788 CXXRecord->isCLike();
14790 if (CheckForZeroSize) {
14791 bool ZeroSize = true;
14792 bool IsEmpty = true;
14793 unsigned NonBitFields = 0;
14794 for (RecordDecl::field_iterator I = Record->field_begin(),
14795 E = Record->field_end();
14796 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14798 if (I->isUnnamedBitfield()) {
14799 if (I->getBitWidthValue(Context) > 0)
14803 QualType FieldType = I->getType();
14804 if (FieldType->isIncompleteType() ||
14805 !Context.getTypeSizeInChars(FieldType).isZero())
14810 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14811 // allowed in C++, but warn if its declaration is inside
14812 // extern "C" block.
14814 Diag(RecLoc, getLangOpts().CPlusPlus ?
14815 diag::warn_zero_size_struct_union_in_extern_c :
14816 diag::warn_zero_size_struct_union_compat)
14817 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14820 // Structs without named members are extension in C (C99 6.7.2.1p7),
14821 // but are accepted by GCC.
14822 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14823 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14824 diag::ext_no_named_members_in_struct_union)
14825 << Record->isUnion();
14829 ObjCIvarDecl **ClsFields =
14830 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14831 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14832 ID->setEndOfDefinitionLoc(RBrac);
14833 // Add ivar's to class's DeclContext.
14834 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14835 ClsFields[i]->setLexicalDeclContext(ID);
14836 ID->addDecl(ClsFields[i]);
14838 // Must enforce the rule that ivars in the base classes may not be
14840 if (ID->getSuperClass())
14841 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14842 } else if (ObjCImplementationDecl *IMPDecl =
14843 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14844 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14845 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14846 // Ivar declared in @implementation never belongs to the implementation.
14847 // Only it is in implementation's lexical context.
14848 ClsFields[I]->setLexicalDeclContext(IMPDecl);
14849 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14850 IMPDecl->setIvarLBraceLoc(LBrac);
14851 IMPDecl->setIvarRBraceLoc(RBrac);
14852 } else if (ObjCCategoryDecl *CDecl =
14853 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14854 // case of ivars in class extension; all other cases have been
14855 // reported as errors elsewhere.
14856 // FIXME. Class extension does not have a LocEnd field.
14857 // CDecl->setLocEnd(RBrac);
14858 // Add ivar's to class extension's DeclContext.
14859 // Diagnose redeclaration of private ivars.
14860 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14861 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14863 if (const ObjCIvarDecl *ClsIvar =
14864 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14865 Diag(ClsFields[i]->getLocation(),
14866 diag::err_duplicate_ivar_declaration);
14867 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14870 for (const auto *Ext : IDecl->known_extensions()) {
14871 if (const ObjCIvarDecl *ClsExtIvar
14872 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14873 Diag(ClsFields[i]->getLocation(),
14874 diag::err_duplicate_ivar_declaration);
14875 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14880 ClsFields[i]->setLexicalDeclContext(CDecl);
14881 CDecl->addDecl(ClsFields[i]);
14883 CDecl->setIvarLBraceLoc(LBrac);
14884 CDecl->setIvarRBraceLoc(RBrac);
14889 ProcessDeclAttributeList(S, Record, Attr);
14892 /// \brief Determine whether the given integral value is representable within
14893 /// the given type T.
14894 static bool isRepresentableIntegerValue(ASTContext &Context,
14895 llvm::APSInt &Value,
14897 assert(T->isIntegralType(Context) && "Integral type required!");
14898 unsigned BitWidth = Context.getIntWidth(T);
14900 if (Value.isUnsigned() || Value.isNonNegative()) {
14901 if (T->isSignedIntegerOrEnumerationType())
14903 return Value.getActiveBits() <= BitWidth;
14905 return Value.getMinSignedBits() <= BitWidth;
14908 // \brief Given an integral type, return the next larger integral type
14909 // (or a NULL type of no such type exists).
14910 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14911 // FIXME: Int128/UInt128 support, which also needs to be introduced into
14912 // enum checking below.
14913 assert(T->isIntegralType(Context) && "Integral type required!");
14914 const unsigned NumTypes = 4;
14915 QualType SignedIntegralTypes[NumTypes] = {
14916 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14918 QualType UnsignedIntegralTypes[NumTypes] = {
14919 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14920 Context.UnsignedLongLongTy
14923 unsigned BitWidth = Context.getTypeSize(T);
14924 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14925 : UnsignedIntegralTypes;
14926 for (unsigned I = 0; I != NumTypes; ++I)
14927 if (Context.getTypeSize(Types[I]) > BitWidth)
14933 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14934 EnumConstantDecl *LastEnumConst,
14935 SourceLocation IdLoc,
14936 IdentifierInfo *Id,
14938 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14939 llvm::APSInt EnumVal(IntWidth);
14942 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14946 Val = DefaultLvalueConversion(Val).get();
14949 if (Enum->isDependentType() || Val->isTypeDependent())
14950 EltTy = Context.DependentTy;
14952 SourceLocation ExpLoc;
14953 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14954 !getLangOpts().MSVCCompat) {
14955 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14956 // constant-expression in the enumerator-definition shall be a converted
14957 // constant expression of the underlying type.
14958 EltTy = Enum->getIntegerType();
14959 ExprResult Converted =
14960 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14962 if (Converted.isInvalid())
14965 Val = Converted.get();
14966 } else if (!Val->isValueDependent() &&
14967 !(Val = VerifyIntegerConstantExpression(Val,
14968 &EnumVal).get())) {
14969 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14971 if (Enum->isFixed()) {
14972 EltTy = Enum->getIntegerType();
14974 // In Obj-C and Microsoft mode, require the enumeration value to be
14975 // representable in the underlying type of the enumeration. In C++11,
14976 // we perform a non-narrowing conversion as part of converted constant
14977 // expression checking.
14978 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14979 if (getLangOpts().MSVCCompat) {
14980 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14981 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14983 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14985 Val = ImpCastExprToType(Val, EltTy,
14986 EltTy->isBooleanType() ?
14987 CK_IntegralToBoolean : CK_IntegralCast)
14989 } else if (getLangOpts().CPlusPlus) {
14990 // C++11 [dcl.enum]p5:
14991 // If the underlying type is not fixed, the type of each enumerator
14992 // is the type of its initializing value:
14993 // - If an initializer is specified for an enumerator, the
14994 // initializing value has the same type as the expression.
14995 EltTy = Val->getType();
14998 // The expression that defines the value of an enumeration constant
14999 // shall be an integer constant expression that has a value
15000 // representable as an int.
15002 // Complain if the value is not representable in an int.
15003 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15004 Diag(IdLoc, diag::ext_enum_value_not_int)
15005 << EnumVal.toString(10) << Val->getSourceRange()
15006 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15007 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15008 // Force the type of the expression to 'int'.
15009 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15011 EltTy = Val->getType();
15018 if (Enum->isDependentType())
15019 EltTy = Context.DependentTy;
15020 else if (!LastEnumConst) {
15021 // C++0x [dcl.enum]p5:
15022 // If the underlying type is not fixed, the type of each enumerator
15023 // is the type of its initializing value:
15024 // - If no initializer is specified for the first enumerator, the
15025 // initializing value has an unspecified integral type.
15027 // GCC uses 'int' for its unspecified integral type, as does
15029 if (Enum->isFixed()) {
15030 EltTy = Enum->getIntegerType();
15033 EltTy = Context.IntTy;
15036 // Assign the last value + 1.
15037 EnumVal = LastEnumConst->getInitVal();
15039 EltTy = LastEnumConst->getType();
15041 // Check for overflow on increment.
15042 if (EnumVal < LastEnumConst->getInitVal()) {
15043 // C++0x [dcl.enum]p5:
15044 // If the underlying type is not fixed, the type of each enumerator
15045 // is the type of its initializing value:
15047 // - Otherwise the type of the initializing value is the same as
15048 // the type of the initializing value of the preceding enumerator
15049 // unless the incremented value is not representable in that type,
15050 // in which case the type is an unspecified integral type
15051 // sufficient to contain the incremented value. If no such type
15052 // exists, the program is ill-formed.
15053 QualType T = getNextLargerIntegralType(Context, EltTy);
15054 if (T.isNull() || Enum->isFixed()) {
15055 // There is no integral type larger enough to represent this
15056 // value. Complain, then allow the value to wrap around.
15057 EnumVal = LastEnumConst->getInitVal();
15058 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15060 if (Enum->isFixed())
15061 // When the underlying type is fixed, this is ill-formed.
15062 Diag(IdLoc, diag::err_enumerator_wrapped)
15063 << EnumVal.toString(10)
15066 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15067 << EnumVal.toString(10);
15072 // Retrieve the last enumerator's value, extent that type to the
15073 // type that is supposed to be large enough to represent the incremented
15074 // value, then increment.
15075 EnumVal = LastEnumConst->getInitVal();
15076 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15077 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15080 // If we're not in C++, diagnose the overflow of enumerator values,
15081 // which in C99 means that the enumerator value is not representable in
15082 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15083 // permits enumerator values that are representable in some larger
15085 if (!getLangOpts().CPlusPlus && !T.isNull())
15086 Diag(IdLoc, diag::warn_enum_value_overflow);
15087 } else if (!getLangOpts().CPlusPlus &&
15088 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15089 // Enforce C99 6.7.2.2p2 even when we compute the next value.
15090 Diag(IdLoc, diag::ext_enum_value_not_int)
15091 << EnumVal.toString(10) << 1;
15096 if (!EltTy->isDependentType()) {
15097 // Make the enumerator value match the signedness and size of the
15098 // enumerator's type.
15099 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15100 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15103 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15107 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15108 SourceLocation IILoc) {
15109 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15110 !getLangOpts().CPlusPlus)
15111 return SkipBodyInfo();
15113 // We have an anonymous enum definition. Look up the first enumerator to
15114 // determine if we should merge the definition with an existing one and
15116 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15118 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15120 return SkipBodyInfo();
15122 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15124 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15126 Skip.Previous = Hidden;
15130 return SkipBodyInfo();
15133 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15134 SourceLocation IdLoc, IdentifierInfo *Id,
15135 AttributeList *Attr,
15136 SourceLocation EqualLoc, Expr *Val) {
15137 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15138 EnumConstantDecl *LastEnumConst =
15139 cast_or_null<EnumConstantDecl>(lastEnumConst);
15141 // The scope passed in may not be a decl scope. Zip up the scope tree until
15142 // we find one that is.
15143 S = getNonFieldDeclScope(S);
15145 // Verify that there isn't already something declared with this name in this
15147 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15149 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15150 // Maybe we will complain about the shadowed template parameter.
15151 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15152 // Just pretend that we didn't see the previous declaration.
15153 PrevDecl = nullptr;
15156 // C++ [class.mem]p15:
15157 // If T is the name of a class, then each of the following shall have a name
15158 // different from T:
15159 // - every enumerator of every member of class T that is an unscoped
15161 if (!TheEnumDecl->isScoped())
15162 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15163 DeclarationNameInfo(Id, IdLoc));
15165 EnumConstantDecl *New =
15166 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15171 // When in C++, we may get a TagDecl with the same name; in this case the
15172 // enum constant will 'hide' the tag.
15173 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15174 "Received TagDecl when not in C++!");
15175 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15176 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15177 if (isa<EnumConstantDecl>(PrevDecl))
15178 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15180 Diag(IdLoc, diag::err_redefinition) << Id;
15181 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15186 // Process attributes.
15187 if (Attr) ProcessDeclAttributeList(S, New, Attr);
15189 // Register this decl in the current scope stack.
15190 New->setAccess(TheEnumDecl->getAccess());
15191 PushOnScopeChains(New, S);
15193 ActOnDocumentableDecl(New);
15198 // Returns true when the enum initial expression does not trigger the
15199 // duplicate enum warning. A few common cases are exempted as follows:
15200 // Element2 = Element1
15201 // Element2 = Element1 + 1
15202 // Element2 = Element1 - 1
15203 // Where Element2 and Element1 are from the same enum.
15204 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15205 Expr *InitExpr = ECD->getInitExpr();
15208 InitExpr = InitExpr->IgnoreImpCasts();
15210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15211 if (!BO->isAdditiveOp())
15213 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15216 if (IL->getValue() != 1)
15219 InitExpr = BO->getLHS();
15222 // This checks if the elements are from the same enum.
15223 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15227 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15231 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15241 bool isTombstoneOrEmptyKey;
15242 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15243 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15246 static DupKey GetDupKey(const llvm::APSInt& Val) {
15247 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15251 struct DenseMapInfoDupKey {
15252 static DupKey getEmptyKey() { return DupKey(0, true); }
15253 static DupKey getTombstoneKey() { return DupKey(1, true); }
15254 static unsigned getHashValue(const DupKey Key) {
15255 return (unsigned)(Key.val * 37);
15257 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15258 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15259 LHS.val == RHS.val;
15262 } // end anonymous namespace
15264 // Emits a warning when an element is implicitly set a value that
15265 // a previous element has already been set to.
15266 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15268 QualType EnumType) {
15269 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15271 // Avoid anonymous enums
15272 if (!Enum->getIdentifier())
15275 // Only check for small enums.
15276 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15279 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15280 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15282 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15283 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15286 DuplicatesVector DupVector;
15287 ValueToVectorMap EnumMap;
15289 // Populate the EnumMap with all values represented by enum constants without
15291 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15292 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15294 // Null EnumConstantDecl means a previous diagnostic has been emitted for
15295 // this constant. Skip this enum since it may be ill-formed.
15300 if (ECD->getInitExpr())
15303 DupKey Key = GetDupKey(ECD->getInitVal());
15304 DeclOrVector &Entry = EnumMap[Key];
15306 // First time encountering this value.
15307 if (Entry.isNull())
15311 // Create vectors for any values that has duplicates.
15312 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15313 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15314 if (!ValidDuplicateEnum(ECD, Enum))
15317 DupKey Key = GetDupKey(ECD->getInitVal());
15319 DeclOrVector& Entry = EnumMap[Key];
15320 if (Entry.isNull())
15323 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15324 // Ensure constants are different.
15328 // Create new vector and push values onto it.
15329 ECDVector *Vec = new ECDVector();
15331 Vec->push_back(ECD);
15333 // Update entry to point to the duplicates vector.
15336 // Store the vector somewhere we can consult later for quick emission of
15338 DupVector.push_back(Vec);
15342 ECDVector *Vec = Entry.get<ECDVector*>();
15343 // Make sure constants are not added more than once.
15344 if (*Vec->begin() == ECD)
15347 Vec->push_back(ECD);
15350 // Emit diagnostics.
15351 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15352 DupVectorEnd = DupVector.end();
15353 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15354 ECDVector *Vec = *DupVectorIter;
15355 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15357 // Emit warning for one enum constant.
15358 ECDVector::iterator I = Vec->begin();
15359 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15360 << (*I)->getName() << (*I)->getInitVal().toString(10)
15361 << (*I)->getSourceRange();
15364 // Emit one note for each of the remaining enum constants with
15366 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15367 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15368 << (*I)->getName() << (*I)->getInitVal().toString(10)
15369 << (*I)->getSourceRange();
15374 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15375 bool AllowMask) const {
15376 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15377 assert(ED->isCompleteDefinition() && "expected enum definition");
15379 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15380 llvm::APInt &FlagBits = R.first->second;
15383 for (auto *E : ED->enumerators()) {
15384 const auto &EVal = E->getInitVal();
15385 // Only single-bit enumerators introduce new flag values.
15386 if (EVal.isPowerOf2())
15387 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15391 // A value is in a flag enum if either its bits are a subset of the enum's
15392 // flag bits (the first condition) or we are allowing masks and the same is
15393 // true of its complement (the second condition). When masks are allowed, we
15394 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15396 // While it's true that any value could be used as a mask, the assumption is
15397 // that a mask will have all of the insignificant bits set. Anything else is
15398 // likely a logic error.
15399 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15400 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15403 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15405 ArrayRef<Decl *> Elements,
15406 Scope *S, AttributeList *Attr) {
15407 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15408 QualType EnumType = Context.getTypeDeclType(Enum);
15411 ProcessDeclAttributeList(S, Enum, Attr);
15413 if (Enum->isDependentType()) {
15414 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15415 EnumConstantDecl *ECD =
15416 cast_or_null<EnumConstantDecl>(Elements[i]);
15417 if (!ECD) continue;
15419 ECD->setType(EnumType);
15422 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15426 // TODO: If the result value doesn't fit in an int, it must be a long or long
15427 // long value. ISO C does not support this, but GCC does as an extension,
15429 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15430 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15431 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15433 // Verify that all the values are okay, compute the size of the values, and
15434 // reverse the list.
15435 unsigned NumNegativeBits = 0;
15436 unsigned NumPositiveBits = 0;
15438 // Keep track of whether all elements have type int.
15439 bool AllElementsInt = true;
15441 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15442 EnumConstantDecl *ECD =
15443 cast_or_null<EnumConstantDecl>(Elements[i]);
15444 if (!ECD) continue; // Already issued a diagnostic.
15446 const llvm::APSInt &InitVal = ECD->getInitVal();
15448 // Keep track of the size of positive and negative values.
15449 if (InitVal.isUnsigned() || InitVal.isNonNegative())
15450 NumPositiveBits = std::max(NumPositiveBits,
15451 (unsigned)InitVal.getActiveBits());
15453 NumNegativeBits = std::max(NumNegativeBits,
15454 (unsigned)InitVal.getMinSignedBits());
15456 // Keep track of whether every enum element has type int (very commmon).
15457 if (AllElementsInt)
15458 AllElementsInt = ECD->getType() == Context.IntTy;
15461 // Figure out the type that should be used for this enum.
15463 unsigned BestWidth;
15465 // C++0x N3000 [conv.prom]p3:
15466 // An rvalue of an unscoped enumeration type whose underlying
15467 // type is not fixed can be converted to an rvalue of the first
15468 // of the following types that can represent all the values of
15469 // the enumeration: int, unsigned int, long int, unsigned long
15470 // int, long long int, or unsigned long long int.
15472 // An identifier declared as an enumeration constant has type int.
15473 // The C99 rule is modified by a gcc extension
15474 QualType BestPromotionType;
15476 bool Packed = Enum->hasAttr<PackedAttr>();
15477 // -fshort-enums is the equivalent to specifying the packed attribute on all
15478 // enum definitions.
15479 if (LangOpts.ShortEnums)
15482 if (Enum->isFixed()) {
15483 BestType = Enum->getIntegerType();
15484 if (BestType->isPromotableIntegerType())
15485 BestPromotionType = Context.getPromotedIntegerType(BestType);
15487 BestPromotionType = BestType;
15489 BestWidth = Context.getIntWidth(BestType);
15491 else if (NumNegativeBits) {
15492 // If there is a negative value, figure out the smallest integer type (of
15493 // int/long/longlong) that fits.
15494 // If it's packed, check also if it fits a char or a short.
15495 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15496 BestType = Context.SignedCharTy;
15497 BestWidth = CharWidth;
15498 } else if (Packed && NumNegativeBits <= ShortWidth &&
15499 NumPositiveBits < ShortWidth) {
15500 BestType = Context.ShortTy;
15501 BestWidth = ShortWidth;
15502 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15503 BestType = Context.IntTy;
15504 BestWidth = IntWidth;
15506 BestWidth = Context.getTargetInfo().getLongWidth();
15508 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15509 BestType = Context.LongTy;
15511 BestWidth = Context.getTargetInfo().getLongLongWidth();
15513 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15514 Diag(Enum->getLocation(), diag::ext_enum_too_large);
15515 BestType = Context.LongLongTy;
15518 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15520 // If there is no negative value, figure out the smallest type that fits
15521 // all of the enumerator values.
15522 // If it's packed, check also if it fits a char or a short.
15523 if (Packed && NumPositiveBits <= CharWidth) {
15524 BestType = Context.UnsignedCharTy;
15525 BestPromotionType = Context.IntTy;
15526 BestWidth = CharWidth;
15527 } else if (Packed && NumPositiveBits <= ShortWidth) {
15528 BestType = Context.UnsignedShortTy;
15529 BestPromotionType = Context.IntTy;
15530 BestWidth = ShortWidth;
15531 } else if (NumPositiveBits <= IntWidth) {
15532 BestType = Context.UnsignedIntTy;
15533 BestWidth = IntWidth;
15535 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15536 ? Context.UnsignedIntTy : Context.IntTy;
15537 } else if (NumPositiveBits <=
15538 (BestWidth = Context.getTargetInfo().getLongWidth())) {
15539 BestType = Context.UnsignedLongTy;
15541 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15542 ? Context.UnsignedLongTy : Context.LongTy;
15544 BestWidth = Context.getTargetInfo().getLongLongWidth();
15545 assert(NumPositiveBits <= BestWidth &&
15546 "How could an initializer get larger than ULL?");
15547 BestType = Context.UnsignedLongLongTy;
15549 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15550 ? Context.UnsignedLongLongTy : Context.LongLongTy;
15554 // Loop over all of the enumerator constants, changing their types to match
15555 // the type of the enum if needed.
15556 for (auto *D : Elements) {
15557 auto *ECD = cast_or_null<EnumConstantDecl>(D);
15558 if (!ECD) continue; // Already issued a diagnostic.
15560 // Standard C says the enumerators have int type, but we allow, as an
15561 // extension, the enumerators to be larger than int size. If each
15562 // enumerator value fits in an int, type it as an int, otherwise type it the
15563 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
15564 // that X has type 'int', not 'unsigned'.
15566 // Determine whether the value fits into an int.
15567 llvm::APSInt InitVal = ECD->getInitVal();
15569 // If it fits into an integer type, force it. Otherwise force it to match
15570 // the enum decl type.
15574 if (!getLangOpts().CPlusPlus &&
15575 !Enum->isFixed() &&
15576 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15577 NewTy = Context.IntTy;
15578 NewWidth = IntWidth;
15580 } else if (ECD->getType() == BestType) {
15581 // Already the right type!
15582 if (getLangOpts().CPlusPlus)
15583 // C++ [dcl.enum]p4: Following the closing brace of an
15584 // enum-specifier, each enumerator has the type of its
15586 ECD->setType(EnumType);
15590 NewWidth = BestWidth;
15591 NewSign = BestType->isSignedIntegerOrEnumerationType();
15594 // Adjust the APSInt value.
15595 InitVal = InitVal.extOrTrunc(NewWidth);
15596 InitVal.setIsSigned(NewSign);
15597 ECD->setInitVal(InitVal);
15599 // Adjust the Expr initializer and type.
15600 if (ECD->getInitExpr() &&
15601 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15602 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15604 ECD->getInitExpr(),
15605 /*base paths*/ nullptr,
15607 if (getLangOpts().CPlusPlus)
15608 // C++ [dcl.enum]p4: Following the closing brace of an
15609 // enum-specifier, each enumerator has the type of its
15611 ECD->setType(EnumType);
15613 ECD->setType(NewTy);
15616 Enum->completeDefinition(BestType, BestPromotionType,
15617 NumPositiveBits, NumNegativeBits);
15619 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15621 if (Enum->isClosedFlag()) {
15622 for (Decl *D : Elements) {
15623 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15624 if (!ECD) continue; // Already issued a diagnostic.
15626 llvm::APSInt InitVal = ECD->getInitVal();
15627 if (InitVal != 0 && !InitVal.isPowerOf2() &&
15628 !IsValueInFlagEnum(Enum, InitVal, true))
15629 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15634 // Now that the enum type is defined, ensure it's not been underaligned.
15635 if (Enum->hasAttrs())
15636 CheckAlignasUnderalignment(Enum);
15639 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15640 SourceLocation StartLoc,
15641 SourceLocation EndLoc) {
15642 StringLiteral *AsmString = cast<StringLiteral>(expr);
15644 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15645 AsmString, StartLoc,
15647 CurContext->addDecl(New);
15651 static void checkModuleImportContext(Sema &S, Module *M,
15652 SourceLocation ImportLoc, DeclContext *DC,
15653 bool FromInclude = false) {
15654 SourceLocation ExternCLoc;
15656 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15657 switch (LSD->getLanguage()) {
15658 case LinkageSpecDecl::lang_c:
15659 if (ExternCLoc.isInvalid())
15660 ExternCLoc = LSD->getLocStart();
15662 case LinkageSpecDecl::lang_cxx:
15665 DC = LSD->getParent();
15668 while (isa<LinkageSpecDecl>(DC))
15669 DC = DC->getParent();
15671 if (!isa<TranslationUnitDecl>(DC)) {
15672 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15673 ? diag::ext_module_import_not_at_top_level_noop
15674 : diag::err_module_import_not_at_top_level_fatal)
15675 << M->getFullModuleName() << DC;
15676 S.Diag(cast<Decl>(DC)->getLocStart(),
15677 diag::note_module_import_not_at_top_level) << DC;
15678 } else if (!M->IsExternC && ExternCLoc.isValid()) {
15679 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15680 << M->getFullModuleName();
15681 S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15685 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15686 ModuleDeclKind MDK,
15687 ModuleIdPath Path) {
15688 // 'module implementation' requires that we are not compiling a module of any
15689 // kind. 'module' and 'module partition' require that we are compiling a
15690 // module inteface (not a module map).
15691 auto CMK = getLangOpts().getCompilingModule();
15692 if (MDK == ModuleDeclKind::Implementation
15693 ? CMK != LangOptions::CMK_None
15694 : CMK != LangOptions::CMK_ModuleInterface) {
15695 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15700 // FIXME: Create a ModuleDecl and return it.
15702 // FIXME: Most of this work should be done by the preprocessor rather than
15703 // here, in case we look ahead across something where the current
15704 // module matters (eg a #include).
15706 // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15707 // hierarchical module map modules, the dots here are just another character
15708 // that can appear in a module name. Flatten down to the actual module name.
15709 std::string ModuleName;
15710 for (auto &Piece : Path) {
15711 if (!ModuleName.empty())
15713 ModuleName += Piece.first->getName();
15716 // If a module name was explicitly specified on the command line, it must be
15718 if (!getLangOpts().CurrentModule.empty() &&
15719 getLangOpts().CurrentModule != ModuleName) {
15720 Diag(Path.front().second, diag::err_current_module_name_mismatch)
15721 << SourceRange(Path.front().second, Path.back().second)
15722 << getLangOpts().CurrentModule;
15725 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15727 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15730 case ModuleDeclKind::Module: {
15731 // FIXME: Check we're not in a submodule.
15733 // We can't have imported a definition of this module or parsed a module
15734 // map defining it already.
15735 if (auto *M = Map.findModule(ModuleName)) {
15736 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15737 if (M->DefinitionLoc.isValid())
15738 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15739 else if (const auto *FE = M->getASTFile())
15740 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15745 // Create a Module for the module that we're defining.
15746 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15747 assert(Mod && "module creation should not fail");
15749 // Enter the semantic scope of the module.
15750 ActOnModuleBegin(ModuleLoc, Mod);
15754 case ModuleDeclKind::Partition:
15755 // FIXME: Check we are in a submodule of the named module.
15758 case ModuleDeclKind::Implementation:
15759 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15760 PP.getIdentifierInfo(ModuleName), Path[0].second);
15762 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15763 if (Import.isInvalid())
15765 return ConvertDeclToDeclGroup(Import.get());
15768 llvm_unreachable("unexpected module decl kind");
15771 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15772 SourceLocation ImportLoc,
15773 ModuleIdPath Path) {
15775 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15776 /*IsIncludeDirective=*/false);
15780 VisibleModules.setVisible(Mod, ImportLoc);
15782 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15784 // FIXME: we should support importing a submodule within a different submodule
15785 // of the same top-level module. Until we do, make it an error rather than
15786 // silently ignoring the import.
15787 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15788 // warn on a redundant import of the current module?
15789 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15790 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15791 Diag(ImportLoc, getLangOpts().isCompilingModule()
15792 ? diag::err_module_self_import
15793 : diag::err_module_import_in_implementation)
15794 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15796 SmallVector<SourceLocation, 2> IdentifierLocs;
15797 Module *ModCheck = Mod;
15798 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15799 // If we've run out of module parents, just drop the remaining identifiers.
15800 // We need the length to be consistent.
15803 ModCheck = ModCheck->Parent;
15805 IdentifierLocs.push_back(Path[I].second);
15808 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15809 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15810 Mod, IdentifierLocs);
15811 if (!ModuleScopes.empty())
15812 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15813 TU->addDecl(Import);
15817 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15818 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15819 BuildModuleInclude(DirectiveLoc, Mod);
15822 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15823 // Determine whether we're in the #include buffer for a module. The #includes
15824 // in that buffer do not qualify as module imports; they're just an
15825 // implementation detail of us building the module.
15827 // FIXME: Should we even get ActOnModuleInclude calls for those?
15828 bool IsInModuleIncludes =
15829 TUKind == TU_Module &&
15830 getSourceManager().isWrittenInMainFile(DirectiveLoc);
15832 bool ShouldAddImport = !IsInModuleIncludes;
15834 // If this module import was due to an inclusion directive, create an
15835 // implicit import declaration to capture it in the AST.
15836 if (ShouldAddImport) {
15837 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15838 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15841 if (!ModuleScopes.empty())
15842 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15843 TU->addDecl(ImportD);
15844 Consumer.HandleImplicitImportDecl(ImportD);
15847 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15848 VisibleModules.setVisible(Mod, DirectiveLoc);
15851 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15852 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15854 ModuleScopes.push_back({});
15855 ModuleScopes.back().Module = Mod;
15856 if (getLangOpts().ModulesLocalVisibility)
15857 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15859 VisibleModules.setVisible(Mod, DirectiveLoc);
15862 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15863 if (getLangOpts().ModulesLocalVisibility) {
15864 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15865 // Leaving a module hides namespace names, so our visible namespace cache
15866 // is now out of date.
15867 VisibleNamespaceCache.clear();
15870 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15871 "left the wrong module scope");
15872 ModuleScopes.pop_back();
15874 // We got to the end of processing a #include of a local module. Create an
15875 // ImportDecl as we would for an imported module.
15876 FileID File = getSourceManager().getFileID(EofLoc);
15877 assert(File != getSourceManager().getMainFileID() &&
15878 "end of submodule in main source file");
15879 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15880 BuildModuleInclude(DirectiveLoc, Mod);
15883 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15885 // Bail if we're not allowed to implicitly import a module here.
15886 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15889 // Create the implicit import declaration.
15890 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15891 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15893 TU->addDecl(ImportD);
15894 Consumer.HandleImplicitImportDecl(ImportD);
15896 // Make the module visible.
15897 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15898 VisibleModules.setVisible(Mod, Loc);
15901 /// We have parsed the start of an export declaration, including the '{'
15903 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15904 SourceLocation LBraceLoc) {
15905 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15907 // C++ Modules TS draft:
15908 // An export-declaration [...] shall not contain more than one
15911 // The intent here is that an export-declaration cannot appear within another
15912 // export-declaration.
15913 if (D->isExported())
15914 Diag(ExportLoc, diag::err_export_within_export);
15916 CurContext->addDecl(D);
15917 PushDeclContext(S, D);
15921 /// Complete the definition of an export declaration.
15922 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15923 auto *ED = cast<ExportDecl>(D);
15924 if (RBraceLoc.isValid())
15925 ED->setRBraceLoc(RBraceLoc);
15927 // FIXME: Diagnose export of internal-linkage declaration (including
15928 // anonymous namespace).
15934 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15935 IdentifierInfo* AliasName,
15936 SourceLocation PragmaLoc,
15937 SourceLocation NameLoc,
15938 SourceLocation AliasNameLoc) {
15939 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15940 LookupOrdinaryName);
15941 AsmLabelAttr *Attr =
15942 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15944 // If a declaration that:
15945 // 1) declares a function or a variable
15946 // 2) has external linkage
15947 // already exists, add a label attribute to it.
15948 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15949 if (isDeclExternC(PrevDecl))
15950 PrevDecl->addAttr(Attr);
15952 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15953 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15954 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15956 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15959 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15960 SourceLocation PragmaLoc,
15961 SourceLocation NameLoc) {
15962 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15965 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15967 (void)WeakUndeclaredIdentifiers.insert(
15968 std::pair<IdentifierInfo*,WeakInfo>
15969 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15973 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15974 IdentifierInfo* AliasName,
15975 SourceLocation PragmaLoc,
15976 SourceLocation NameLoc,
15977 SourceLocation AliasNameLoc) {
15978 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15979 LookupOrdinaryName);
15980 WeakInfo W = WeakInfo(Name, NameLoc);
15982 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15983 if (!PrevDecl->hasAttr<AliasAttr>())
15984 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15985 DeclApplyPragmaWeak(TUScope, ND, W);
15987 (void)WeakUndeclaredIdentifiers.insert(
15988 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15992 Decl *Sema::getObjCDeclContext() const {
15993 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));