1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Parse/ParseDiagnostic.h"
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
51 using namespace clang;
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68 bool AllowTemplates=false)
69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70 AllowClassTemplates(AllowTemplates) {
71 WantExpressionKeywords = false;
72 WantCXXNamedCasts = false;
73 WantRemainingKeywords = false;
76 bool ValidateCandidate(const TypoCorrection &candidate) override {
77 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80 return (IsType || AllowedTemplate) &&
81 (AllowInvalidDecl || !ND->isInvalidDecl());
83 return !WantClassName && candidate.isKeyword();
87 bool AllowInvalidDecl;
89 bool AllowClassTemplates;
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
97 // FIXME: Take into account the current language when deciding whether a
98 // token kind is a valid type specifier
101 case tok::kw___int64:
102 case tok::kw___int128:
104 case tok::kw_unsigned:
111 case tok::kw_wchar_t:
113 case tok::kw___underlying_type:
116 case tok::annot_typename:
117 case tok::kw_char16_t:
118 case tok::kw_char32_t:
120 case tok::annot_decltype:
121 case tok::kw_decltype:
122 return getLangOpts().CPlusPlus;
132 enum class UnqualifiedTypeNameLookupResult {
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
143 static UnqualifiedTypeNameLookupResult
144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
145 SourceLocation NameLoc,
146 const CXXRecordDecl *RD) {
147 if (!RD->hasDefinition())
148 return UnqualifiedTypeNameLookupResult::NotFound;
149 // Look for type decls in base classes.
150 UnqualifiedTypeNameLookupResult FoundTypeDecl =
151 UnqualifiedTypeNameLookupResult::NotFound;
152 for (const auto &Base : RD->bases()) {
153 const CXXRecordDecl *BaseRD = nullptr;
154 if (auto *BaseTT = Base.getType()->getAs<TagType>())
155 BaseRD = BaseTT->getAsCXXRecordDecl();
156 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157 // Look for type decls in dependent base classes that have known primary
159 if (!TST || !TST->isDependentType())
161 auto *TD = TST->getTemplateName().getAsTemplateDecl();
164 auto *BasePrimaryTemplate =
165 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166 if (!BasePrimaryTemplate)
168 BaseRD = BasePrimaryTemplate;
171 for (NamedDecl *ND : BaseRD->lookup(&II)) {
172 if (!isa<TypeDecl>(ND))
173 return UnqualifiedTypeNameLookupResult::FoundNonType;
174 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
176 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178 case UnqualifiedTypeNameLookupResult::FoundNonType:
179 return UnqualifiedTypeNameLookupResult::FoundNonType;
180 case UnqualifiedTypeNameLookupResult::FoundType:
181 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183 case UnqualifiedTypeNameLookupResult::NotFound:
190 return FoundTypeDecl;
193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
194 const IdentifierInfo &II,
195 SourceLocation NameLoc) {
196 // Lookup in the parent class template context, if any.
197 const CXXRecordDecl *RD = nullptr;
198 UnqualifiedTypeNameLookupResult FoundTypeDecl =
199 UnqualifiedTypeNameLookupResult::NotFound;
200 for (DeclContext *DC = S.CurContext;
201 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202 DC = DC->getParent()) {
203 // Look for type decls in dependent base classes that have known primary
205 RD = dyn_cast<CXXRecordDecl>(DC);
206 if (RD && RD->getDescribedClassTemplate())
207 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
209 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
212 // We found some types in dependent base classes. Recover as if the user
213 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
214 // lookup during template instantiation.
215 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
217 ASTContext &Context = S.Context;
218 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219 cast<Type>(Context.getRecordType(RD)));
220 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
223 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
225 TypeLocBuilder Builder;
226 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227 DepTL.setNameLoc(NameLoc);
228 DepTL.setElaboratedKeywordLoc(SourceLocation());
229 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
242 Scope *S, CXXScopeSpec *SS,
243 bool isClassName, bool HasTrailingDot,
244 ParsedType ObjectTypePtr,
245 bool IsCtorOrDtorName,
246 bool WantNontrivialTypeSourceInfo,
247 IdentifierInfo **CorrectedII) {
248 // Determine where we will perform name lookup.
249 DeclContext *LookupCtx = nullptr;
251 QualType ObjectType = ObjectTypePtr.get();
252 if (ObjectType->isRecordType())
253 LookupCtx = computeDeclContext(ObjectType);
254 } else if (SS && SS->isNotEmpty()) {
255 LookupCtx = computeDeclContext(*SS, false);
258 if (isDependentScopeSpecifier(*SS)) {
260 // A qualified-id that refers to a type and in which the
261 // nested-name-specifier depends on a template-parameter (14.6.2)
262 // shall be prefixed by the keyword typename to indicate that the
263 // qualified-id denotes a type, forming an
264 // elaborated-type-specifier (7.1.5.3).
266 // We therefore do not perform any name lookup if the result would
267 // refer to a member of an unknown specialization.
268 if (!isClassName && !IsCtorOrDtorName)
271 // We know from the grammar that this name refers to a type,
272 // so build a dependent node to describe the type.
273 if (WantNontrivialTypeSourceInfo)
274 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
276 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
277 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
279 return ParsedType::make(T);
285 if (!LookupCtx->isDependentContext() &&
286 RequireCompleteDeclContext(*SS, LookupCtx))
290 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291 // lookup for class-names.
292 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
294 LookupResult Result(*this, &II, NameLoc, Kind);
296 // Perform "qualified" name lookup into the declaration context we
297 // computed, which is either the type of the base of a member access
298 // expression or the declaration context associated with a prior
299 // nested-name-specifier.
300 LookupQualifiedName(Result, LookupCtx);
302 if (ObjectTypePtr && Result.empty()) {
303 // C++ [basic.lookup.classref]p3:
304 // If the unqualified-id is ~type-name, the type-name is looked up
305 // in the context of the entire postfix-expression. If the type T of
306 // the object expression is of a class type C, the type-name is also
307 // looked up in the scope of class C. At least one of the lookups shall
308 // find a name that refers to (possibly cv-qualified) T.
309 LookupName(Result, S);
312 // Perform unqualified name lookup.
313 LookupName(Result, S);
315 // For unqualified lookup in a class template in MSVC mode, look into
316 // dependent base classes where the primary class template is known.
317 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318 if (ParsedType TypeInBase =
319 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
324 NamedDecl *IIDecl = nullptr;
325 switch (Result.getResultKind()) {
326 case LookupResult::NotFound:
327 case LookupResult::NotFoundInCurrentInstantiation:
329 TypoCorrection Correction = CorrectTypo(
330 Result.getLookupNameInfo(), Kind, S, SS,
331 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
333 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
335 bool MemberOfUnknownSpecialization;
336 UnqualifiedId TemplateName;
337 TemplateName.setIdentifier(NewII, NameLoc);
338 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339 CXXScopeSpec NewSS, *NewSSPtr = SS;
341 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
344 if (Correction && (NNS || NewII != &II) &&
345 // Ignore a correction to a template type as the to-be-corrected
346 // identifier is not a template (typo correction for template names
347 // is handled elsewhere).
348 !(getLangOpts().CPlusPlus && NewSSPtr &&
349 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350 false, Template, MemberOfUnknownSpecialization))) {
351 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352 isClassName, HasTrailingDot, ObjectTypePtr,
354 WantNontrivialTypeSourceInfo);
356 diagnoseTypo(Correction,
357 PDiag(diag::err_unknown_type_or_class_name_suggest)
358 << Result.getLookupName() << isClassName);
360 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361 *CorrectedII = NewII;
366 // If typo correction failed or was not performed, fall through
367 case LookupResult::FoundOverloaded:
368 case LookupResult::FoundUnresolvedValue:
369 Result.suppressDiagnostics();
372 case LookupResult::Ambiguous:
373 // Recover from type-hiding ambiguities by hiding the type. We'll
374 // do the lookup again when looking for an object, and we can
375 // diagnose the error then. If we don't do this, then the error
376 // about hiding the type will be immediately followed by an error
377 // that only makes sense if the identifier was treated like a type.
378 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
379 Result.suppressDiagnostics();
383 // Look to see if we have a type anywhere in the list of results.
384 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385 Res != ResEnd; ++Res) {
386 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
388 (*Res)->getLocation().getRawEncoding() <
389 IIDecl->getLocation().getRawEncoding())
395 // None of the entities we found is a type, so there is no way
396 // to even assume that the result is a type. In this case, don't
397 // complain about the ambiguity. The parser will either try to
398 // perform this lookup again (e.g., as an object name), which
399 // will produce the ambiguity, or will complain that it expected
401 Result.suppressDiagnostics();
405 // We found a type within the ambiguous lookup; diagnose the
406 // ambiguity and then return that type. This might be the right
407 // answer, or it might not be, but it suppresses any attempt to
408 // perform the name lookup again.
411 case LookupResult::Found:
412 IIDecl = Result.getFoundDecl();
416 assert(IIDecl && "Didn't find decl");
419 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420 DiagnoseUseOfDecl(IIDecl, NameLoc);
422 T = Context.getTypeDeclType(TD);
423 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
425 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426 // constructor or destructor name (in such a case, the scope specifier
427 // will be attached to the enclosing Expr or Decl node).
428 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429 if (WantNontrivialTypeSourceInfo) {
430 // Construct a type with type-source information.
431 TypeLocBuilder Builder;
432 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
434 T = getElaboratedType(ETK_None, *SS, T);
435 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
436 ElabTL.setElaboratedKeywordLoc(SourceLocation());
437 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
438 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
440 T = getElaboratedType(ETK_None, *SS, T);
443 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
446 T = Context.getObjCInterfaceType(IDecl);
450 // If it's not plausibly a type, suppress diagnostics.
451 Result.suppressDiagnostics();
454 return ParsedType::make(T);
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
460 for (;; DC = DC->getLookupParent()) {
461 DC = DC->getPrimaryContext();
462 auto *ND = dyn_cast<NamespaceDecl>(DC);
463 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464 return NestedNameSpecifier::Create(Context, nullptr, ND);
465 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467 RD->getTypeForDecl());
468 else if (isa<TranslationUnitDecl>(DC))
469 return NestedNameSpecifier::GlobalSpecifier(Context);
471 llvm_unreachable("something isn't in TU scope?");
474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
475 SourceLocation NameLoc) {
476 // Accepting an undeclared identifier as a default argument for a template
477 // type parameter is a Microsoft extension.
478 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
480 // Build a fake DependentNameType that will perform lookup into CurContext at
481 // instantiation time. The name specifier isn't dependent, so template
482 // instantiation won't transform it. It will retry the lookup, however.
483 NestedNameSpecifier *NNS =
484 synthesizeCurrentNestedNameSpecifier(Context, CurContext);
485 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
487 // Build type location information. We synthesized the qualifier, so we have
488 // to build a fake NestedNameSpecifierLoc.
489 NestedNameSpecifierLocBuilder NNSLocBuilder;
490 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
493 TypeLocBuilder Builder;
494 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495 DepTL.setNameLoc(NameLoc);
496 DepTL.setElaboratedKeywordLoc(SourceLocation());
497 DepTL.setQualifierLoc(QualifierLoc);
498 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo"). If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
507 // Do a tag name lookup in this scope.
508 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509 LookupName(R, S, false);
510 R.suppressDiagnostics();
511 if (R.getResultKind() == LookupResult::Found)
512 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513 switch (TD->getTagKind()) {
514 case TTK_Struct: return DeclSpec::TST_struct;
515 case TTK_Interface: return DeclSpec::TST_interface;
516 case TTK_Union: return DeclSpec::TST_union;
517 case TTK_Class: return DeclSpec::TST_class;
518 case TTK_Enum: return DeclSpec::TST_enum;
522 return DeclSpec::TST_unspecified;
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
530 /// template<class T> class A {
532 /// typedef int TYPE;
534 /// template<class T> class B : public A<T> {
536 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
540 if (CurContext->isRecord()) {
541 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
544 const Type *Ty = SS->getScopeRep()->getAsType();
546 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547 for (const auto &Base : RD->bases())
548 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
550 return S->isFunctionPrototypeScope();
552 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
556 SourceLocation IILoc,
559 ParsedType &SuggestedType,
560 bool AllowClassTemplates) {
561 // We don't have anything to suggest (yet).
562 SuggestedType = ParsedType();
564 // There may have been a typo in the name of the type. Look up typo
565 // results, in case we have something that we can suggest.
566 if (TypoCorrection Corrected =
567 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568 llvm::make_unique<TypeNameValidatorCCC>(
569 false, false, AllowClassTemplates),
570 CTK_ErrorRecovery)) {
571 if (Corrected.isKeyword()) {
572 // We corrected to a keyword.
573 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574 II = Corrected.getCorrectionAsIdentifierInfo();
576 // We found a similarly-named type or interface; suggest that.
577 if (!SS || !SS->isSet()) {
578 diagnoseTypo(Corrected,
579 PDiag(diag::err_unknown_typename_suggest) << II);
580 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583 II->getName().equals(CorrectedStr);
584 diagnoseTypo(Corrected,
585 PDiag(diag::err_unknown_nested_typename_suggest)
586 << II << DC << DroppedSpecifier << SS->getRange());
588 llvm_unreachable("could not have corrected a typo here");
592 if (Corrected.getCorrectionSpecifier())
593 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
595 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
598 /*IsCtorOrDtorName=*/false,
599 /*NonTrivialTypeSourceInfo=*/true);
604 if (getLangOpts().CPlusPlus) {
605 // See if II is a class template that the user forgot to pass arguments to.
607 Name.setIdentifier(II, IILoc);
608 CXXScopeSpec EmptySS;
609 TemplateTy TemplateResult;
610 bool MemberOfUnknownSpecialization;
611 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612 Name, ParsedType(), true, TemplateResult,
613 MemberOfUnknownSpecialization) == TNK_Type_template) {
614 TemplateName TplName = TemplateResult.get();
615 Diag(IILoc, diag::err_template_missing_args) << TplName;
616 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618 << TplDecl->getTemplateParameters()->getSourceRange();
624 // FIXME: Should we move the logic that tries to recover from a missing tag
625 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
627 if (!SS || (!SS->isSet() && !SS->isInvalid()))
628 Diag(IILoc, diag::err_unknown_typename) << II;
629 else if (DeclContext *DC = computeDeclContext(*SS, false))
630 Diag(IILoc, diag::err_typename_nested_not_found)
631 << II << DC << SS->getRange();
632 else if (isDependentScopeSpecifier(*SS)) {
633 unsigned DiagID = diag::err_typename_missing;
634 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635 DiagID = diag::ext_typename_missing;
637 Diag(SS->getRange().getBegin(), DiagID)
638 << SS->getScopeRep() << II->getName()
639 << SourceRange(SS->getRange().getBegin(), IILoc)
640 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641 SuggestedType = ActOnTypenameType(S, SourceLocation(),
642 *SS, *II, IILoc).get();
644 assert(SS && SS->isInvalid() &&
645 "Invalid scope specifier has already been diagnosed");
649 /// \brief Determine whether the given result set contains either a type name
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653 NextToken.is(tok::less);
655 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
659 if (CheckTemplate && isa<TemplateDecl>(*I))
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667 Scope *S, CXXScopeSpec &SS,
668 IdentifierInfo *&Name,
669 SourceLocation NameLoc) {
670 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671 SemaRef.LookupParsedName(R, S, &SS);
672 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673 StringRef FixItTagName;
674 switch (Tag->getTagKind()) {
676 FixItTagName = "class ";
680 FixItTagName = "enum ";
684 FixItTagName = "struct ";
688 FixItTagName = "__interface ";
692 FixItTagName = "union ";
696 StringRef TagName = FixItTagName.drop_back();
697 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
701 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
703 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
706 // Replace lookup results with just the tag decl.
707 Result.clear(Sema::LookupTagName);
708 SemaRef.LookupParsedName(Result, S, &SS);
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
717 QualType T, SourceLocation NameLoc) {
718 ASTContext &Context = S.Context;
720 TypeLocBuilder Builder;
721 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
723 T = S.getElaboratedType(ETK_None, SS, T);
724 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
725 ElabTL.setElaboratedKeywordLoc(SourceLocation());
726 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
730 Sema::NameClassification
731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
732 SourceLocation NameLoc, const Token &NextToken,
733 bool IsAddressOfOperand,
734 std::unique_ptr<CorrectionCandidateCallback> CCC) {
735 DeclarationNameInfo NameInfo(Name, NameLoc);
736 ObjCMethodDecl *CurMethod = getCurMethodDecl();
738 if (NextToken.is(tok::coloncolon)) {
739 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740 QualType(), false, SS, nullptr, false);
743 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744 LookupParsedName(Result, S, &SS, !CurMethod);
746 // For unqualified lookup in a class template in MSVC mode, look into
747 // dependent base classes where the primary class template is known.
748 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749 if (ParsedType TypeInBase =
750 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
754 // Perform lookup for Objective-C instance variables (including automatically
755 // synthesized instance variables), if we're in an Objective-C method.
756 // FIXME: This lookup really, really needs to be folded in to the normal
757 // unqualified lookup mechanism.
758 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760 if (E.get() || E.isInvalid())
764 bool SecondTry = false;
765 bool IsFilteredTemplateName = false;
768 switch (Result.getResultKind()) {
769 case LookupResult::NotFound:
770 // If an unqualified-id is followed by a '(', then we have a function
772 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773 // In C++, this is an ADL-only call.
775 if (getLangOpts().CPlusPlus)
776 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
779 // If the expression that precedes the parenthesized argument list in a
780 // function call consists solely of an identifier, and if no
781 // declaration is visible for this identifier, the identifier is
782 // implicitly declared exactly as if, in the innermost block containing
783 // the function call, the declaration
785 // extern int identifier ();
789 // We also allow this in C99 as an extension.
790 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
792 Result.resolveKind();
793 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
797 // In C, we first see whether there is a tag type by the same name, in
798 // which case it's likely that the user just forget to write "enum",
799 // "struct", or "union".
800 if (!getLangOpts().CPlusPlus && !SecondTry &&
801 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
805 // Perform typo correction to determine if there is another name that is
806 // close to this name.
807 if (!SecondTry && CCC) {
809 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810 Result.getLookupKind(), S,
812 CTK_ErrorRecovery)) {
813 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814 unsigned QualifiedDiag = diag::err_no_member_suggest;
816 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
817 NamedDecl *UnderlyingFirstDecl
818 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
819 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821 UnqualifiedDiag = diag::err_no_template_suggest;
822 QualifiedDiag = diag::err_no_member_template_suggest;
823 } else if (UnderlyingFirstDecl &&
824 (isa<TypeDecl>(UnderlyingFirstDecl) ||
825 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827 UnqualifiedDiag = diag::err_unknown_typename_suggest;
828 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
832 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833 } else {// FIXME: is this even reachable? Test it.
834 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836 Name->getName().equals(CorrectedStr);
837 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838 << Name << computeDeclContext(SS, false)
839 << DroppedSpecifier << SS.getRange());
842 // Update the name, so that the caller has the new name.
843 Name = Corrected.getCorrectionAsIdentifierInfo();
845 // Typo correction corrected to a keyword.
846 if (Corrected.isKeyword())
849 // Also update the LookupResult...
850 // FIXME: This should probably go away at some point
852 Result.setLookupName(Corrected.getCorrection());
854 Result.addDecl(FirstDecl);
856 // If we found an Objective-C instance variable, let
857 // LookupInObjCMethod build the appropriate expression to
858 // reference the ivar.
859 // FIXME: This is a gross hack.
860 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
862 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
870 // We failed to correct; just fall through and let the parser deal with it.
871 Result.suppressDiagnostics();
872 return NameClassification::Unknown();
874 case LookupResult::NotFoundInCurrentInstantiation: {
875 // We performed name lookup into the current instantiation, and there were
876 // dependent bases, so we treat this result the same way as any other
877 // dependent nested-name-specifier.
880 // A name used in a template declaration or definition and that is
881 // dependent on a template-parameter is assumed not to name a type
882 // unless the applicable name lookup finds a type name or the name is
883 // qualified by the keyword typename.
885 // FIXME: If the next token is '<', we might want to ask the parser to
886 // perform some heroics to see if we actually have a
887 // template-argument-list, which would indicate a missing 'template'
889 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890 NameInfo, IsAddressOfOperand,
891 /*TemplateArgs=*/nullptr);
894 case LookupResult::Found:
895 case LookupResult::FoundOverloaded:
896 case LookupResult::FoundUnresolvedValue:
899 case LookupResult::Ambiguous:
900 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901 hasAnyAcceptableTemplateNames(Result)) {
902 // C++ [temp.local]p3:
903 // A lookup that finds an injected-class-name (10.2) can result in an
904 // ambiguity in certain cases (for example, if it is found in more than
905 // one base class). If all of the injected-class-names that are found
906 // refer to specializations of the same class template, and if the name
907 // is followed by a template-argument-list, the reference refers to the
908 // class template itself and not a specialization thereof, and is not
911 // This filtering can make an ambiguous result into an unambiguous one,
912 // so try again after filtering out template names.
913 FilterAcceptableTemplateNames(Result);
914 if (!Result.isAmbiguous()) {
915 IsFilteredTemplateName = true;
920 // Diagnose the ambiguity and return an error.
921 return NameClassification::Error();
924 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926 // C++ [temp.names]p3:
927 // After name lookup (3.4) finds that a name is a template-name or that
928 // an operator-function-id or a literal- operator-id refers to a set of
929 // overloaded functions any member of which is a function template if
930 // this is followed by a <, the < is always taken as the delimiter of a
931 // template-argument-list and never as the less-than operator.
932 if (!IsFilteredTemplateName)
933 FilterAcceptableTemplateNames(Result);
935 if (!Result.empty()) {
936 bool IsFunctionTemplate;
938 TemplateName Template;
939 if (Result.end() - Result.begin() > 1) {
940 IsFunctionTemplate = true;
941 Template = Context.getOverloadedTemplateName(Result.begin(),
945 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947 IsVarTemplate = isa<VarTemplateDecl>(TD);
949 if (SS.isSet() && !SS.isInvalid())
950 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
951 /*TemplateKeyword=*/false,
954 Template = TemplateName(TD);
957 if (IsFunctionTemplate) {
958 // Function templates always go through overload resolution, at which
959 // point we'll perform the various checks (e.g., accessibility) we need
960 // to based on which function we selected.
961 Result.suppressDiagnostics();
963 return NameClassification::FunctionTemplate(Template);
966 return IsVarTemplate ? NameClassification::VarTemplate(Template)
967 : NameClassification::TypeTemplate(Template);
971 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973 DiagnoseUseOfDecl(Type, NameLoc);
974 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
975 QualType T = Context.getTypeDeclType(Type);
977 return buildNestedType(*this, SS, T, NameLoc);
978 return ParsedType::make(T);
981 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
983 // FIXME: It's unfortunate that we don't have a Type node for handling this.
984 if (ObjCCompatibleAliasDecl *Alias =
985 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986 Class = Alias->getClassInterface();
990 DiagnoseUseOfDecl(Class, NameLoc);
992 if (NextToken.is(tok::period)) {
993 // Interface. <something> is parsed as a property reference expression.
994 // Just return "unknown" as a fall-through for now.
995 Result.suppressDiagnostics();
996 return NameClassification::Unknown();
999 QualType T = Context.getObjCInterfaceType(Class);
1000 return ParsedType::make(T);
1003 // We can have a type template here if we're classifying a template argument.
1004 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005 return NameClassification::TypeTemplate(
1006 TemplateName(cast<TemplateDecl>(FirstDecl)));
1008 // Check for a tag type hidden by a non-type decl in a few cases where it
1009 // seems likely a type is wanted instead of the non-type that was found.
1010 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011 if ((NextToken.is(tok::identifier) ||
1013 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016 DiagnoseUseOfDecl(Type, NameLoc);
1017 QualType T = Context.getTypeDeclType(Type);
1018 if (SS.isNotEmpty())
1019 return buildNestedType(*this, SS, T, NameLoc);
1020 return ParsedType::make(T);
1023 if (FirstDecl->isCXXClassMember())
1024 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1027 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028 return BuildDeclarationNameExpr(SS, Result, ADL);
1031 // Determines the context to return to after temporarily entering a
1032 // context. This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1036 // Functions defined inline within classes aren't parsed until we've
1037 // finished parsing the top-level class, so the top-level class is
1038 // the context we'll need to return to.
1039 // A Lambda call operator whose parent is a class must not be treated
1040 // as an inline member function. A Lambda can be used legally
1041 // either as an in-class member initializer or a default argument. These
1042 // are parsed once the class has been marked complete and so the containing
1043 // context would be the nested class (when the lambda is defined in one);
1044 // If the class is not complete, then the lambda is being used in an
1045 // ill-formed fashion (such as to specify the width of a bit-field, or
1046 // in an array-bound) - in which case we still want to return the
1047 // lexically containing DC (which could be a nested class).
1048 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049 DC = DC->getLexicalParent();
1051 // A function not defined within a class will always return to its
1053 if (!isa<CXXRecordDecl>(DC))
1056 // A C++ inline method/friend is parsed *after* the topmost class
1057 // it was declared in is fully parsed ("complete"); the topmost
1058 // class is the context we need to return to.
1059 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1062 // Return the declaration context of the topmost class the inline method is
1067 return DC->getLexicalParent();
1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1071 assert(getContainingDC(DC) == CurContext &&
1072 "The next DeclContext should be lexically contained in the current one.");
1077 void Sema::PopDeclContext() {
1078 assert(CurContext && "DeclContext imbalance!");
1080 CurContext = getContainingDC(CurContext);
1081 assert(CurContext && "Popped translation unit!");
1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1086 // Unlike PushDeclContext, the context to which we return is not necessarily
1087 // the containing DC of TD, because the new context will be some pre-existing
1088 // TagDecl definition instead of a fresh one.
1089 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090 CurContext = cast<TagDecl>(D)->getDefinition();
1091 assert(CurContext && "skipping definition of undefined tag");
1092 S->setEntity(CurContext);
1096 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1097 CurContext = static_cast<decltype(CurContext)>(Context);
1100 /// EnterDeclaratorContext - Used when we must lookup names in the context
1101 /// of a declarator's nested name specifier.
1103 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1104 // C++0x [basic.lookup.unqual]p13:
1105 // A name used in the definition of a static data member of class
1106 // X (after the qualified-id of the static member) is looked up as
1107 // if the name was used in a member function of X.
1108 // C++0x [basic.lookup.unqual]p14:
1109 // If a variable member of a namespace is defined outside of the
1110 // scope of its namespace then any name used in the definition of
1111 // the variable member (after the declarator-id) is looked up as
1112 // if the definition of the variable member occurred in its
1114 // Both of these imply that we should push a scope whose context
1115 // is the semantic context of the declaration. We can't use
1116 // PushDeclContext here because that context is not necessarily
1117 // lexically contained in the current context. Fortunately,
1118 // the containing scope should have the appropriate information.
1120 assert(!S->getEntity() && "scope already has entity");
1123 Scope *Ancestor = S->getParent();
1124 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1125 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1132 void Sema::ExitDeclaratorContext(Scope *S) {
1133 assert(S->getEntity() == CurContext && "Context imbalance!");
1135 // Switch back to the lexical context. The safety of this is
1136 // enforced by an assert in EnterDeclaratorContext.
1137 Scope *Ancestor = S->getParent();
1138 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1139 CurContext = Ancestor->getEntity();
1141 // We don't need to do anything with the scope, which is going to
1146 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1147 // We assume that the caller has already called
1148 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1149 FunctionDecl *FD = D->getAsFunction();
1153 // Same implementation as PushDeclContext, but enters the context
1154 // from the lexical parent, rather than the top-level class.
1155 assert(CurContext == FD->getLexicalParent() &&
1156 "The next DeclContext should be lexically contained in the current one.");
1158 S->setEntity(CurContext);
1160 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1161 ParmVarDecl *Param = FD->getParamDecl(P);
1162 // If the parameter has an identifier, then add it to the scope
1163 if (Param->getIdentifier()) {
1165 IdResolver.AddDecl(Param);
1171 void Sema::ActOnExitFunctionContext() {
1172 // Same implementation as PopDeclContext, but returns to the lexical parent,
1173 // rather than the top-level class.
1174 assert(CurContext && "DeclContext imbalance!");
1175 CurContext = CurContext->getLexicalParent();
1176 assert(CurContext && "Popped translation unit!");
1180 /// \brief Determine whether we allow overloading of the function
1181 /// PrevDecl with another declaration.
1183 /// This routine determines whether overloading is possible, not
1184 /// whether some new function is actually an overload. It will return
1185 /// true in C++ (where we can always provide overloads) or, as an
1186 /// extension, in C when the previous function is already an
1187 /// overloaded function declaration or has the "overloadable"
1189 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1190 ASTContext &Context) {
1191 if (Context.getLangOpts().CPlusPlus)
1194 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1197 return (Previous.getResultKind() == LookupResult::Found
1198 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1201 /// Add this decl to the scope shadowed decl chains.
1202 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1203 // Move up the scope chain until we find the nearest enclosing
1204 // non-transparent context. The declaration will be introduced into this
1206 while (S->getEntity() && S->getEntity()->isTransparentContext())
1209 // Add scoped declarations into their context, so that they can be
1210 // found later. Declarations without a context won't be inserted
1211 // into any context.
1213 CurContext->addDecl(D);
1215 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1216 // are function-local declarations.
1217 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1218 !D->getDeclContext()->getRedeclContext()->Equals(
1219 D->getLexicalDeclContext()->getRedeclContext()) &&
1220 !D->getLexicalDeclContext()->isFunctionOrMethod())
1223 // Template instantiations should also not be pushed into scope.
1224 if (isa<FunctionDecl>(D) &&
1225 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1228 // If this replaces anything in the current scope,
1229 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1230 IEnd = IdResolver.end();
1231 for (; I != IEnd; ++I) {
1232 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1234 IdResolver.RemoveDecl(*I);
1236 // Should only need to replace one decl.
1243 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1244 // Implicitly-generated labels may end up getting generated in an order that
1245 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1246 // the label at the appropriate place in the identifier chain.
1247 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1248 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1249 if (IDC == CurContext) {
1250 if (!S->isDeclScope(*I))
1252 } else if (IDC->Encloses(CurContext))
1256 IdResolver.InsertDeclAfter(I, D);
1258 IdResolver.AddDecl(D);
1262 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1263 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1264 TUScope->AddDecl(D);
1267 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1268 bool AllowInlineNamespace) {
1269 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1272 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1273 DeclContext *TargetDC = DC->getPrimaryContext();
1275 if (DeclContext *ScopeDC = S->getEntity())
1276 if (ScopeDC->getPrimaryContext() == TargetDC)
1278 } while ((S = S->getParent()));
1283 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1287 /// Filters out lookup results that don't fall within the given scope
1288 /// as determined by isDeclInScope.
1289 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1290 bool ConsiderLinkage,
1291 bool AllowInlineNamespace) {
1292 LookupResult::Filter F = R.makeFilter();
1293 while (F.hasNext()) {
1294 NamedDecl *D = F.next();
1296 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1299 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1308 static bool isUsingDecl(NamedDecl *D) {
1309 return isa<UsingShadowDecl>(D) ||
1310 isa<UnresolvedUsingTypenameDecl>(D) ||
1311 isa<UnresolvedUsingValueDecl>(D);
1314 /// Removes using shadow declarations from the lookup results.
1315 static void RemoveUsingDecls(LookupResult &R) {
1316 LookupResult::Filter F = R.makeFilter();
1318 if (isUsingDecl(F.next()))
1324 /// \brief Check for this common pattern:
1327 /// S(const S&); // DO NOT IMPLEMENT
1328 /// void operator=(const S&); // DO NOT IMPLEMENT
1331 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1332 // FIXME: Should check for private access too but access is set after we get
1334 if (D->doesThisDeclarationHaveABody())
1337 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1338 return CD->isCopyConstructor();
1339 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1340 return Method->isCopyAssignmentOperator();
1344 // We need this to handle
1347 // void *foo() { return 0; }
1350 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1351 // for example. If 'A', foo will have external linkage. If we have '*A',
1352 // foo will have no linkage. Since we can't know until we get to the end
1353 // of the typedef, this function finds out if D might have non-external linkage.
1354 // Callers should verify at the end of the TU if it D has external linkage or
1356 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1357 const DeclContext *DC = D->getDeclContext();
1358 while (!DC->isTranslationUnit()) {
1359 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1360 if (!RD->hasNameForLinkage())
1363 DC = DC->getParent();
1366 return !D->isExternallyVisible();
1369 // FIXME: This needs to be refactored; some other isInMainFile users want
1371 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1372 if (S.TUKind != TU_Complete)
1374 return S.SourceMgr.isInMainFile(Loc);
1377 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1380 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1383 // Ignore all entities declared within templates, and out-of-line definitions
1384 // of members of class templates.
1385 if (D->getDeclContext()->isDependentContext() ||
1386 D->getLexicalDeclContext()->isDependentContext())
1389 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1390 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1393 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1394 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1397 // 'static inline' functions are defined in headers; don't warn.
1398 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1402 if (FD->doesThisDeclarationHaveABody() &&
1403 Context.DeclMustBeEmitted(FD))
1405 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1406 // Constants and utility variables are defined in headers with internal
1407 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1409 if (!isMainFileLoc(*this, VD->getLocation()))
1412 if (Context.DeclMustBeEmitted(VD))
1415 if (VD->isStaticDataMember() &&
1416 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1422 // Only warn for unused decls internal to the translation unit.
1423 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1424 // for inline functions defined in the main source file, for instance.
1425 return mightHaveNonExternalLinkage(D);
1428 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1432 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1433 const FunctionDecl *First = FD->getFirstDecl();
1434 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1435 return; // First should already be in the vector.
1438 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1439 const VarDecl *First = VD->getFirstDecl();
1440 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1441 return; // First should already be in the vector.
1444 if (ShouldWarnIfUnusedFileScopedDecl(D))
1445 UnusedFileScopedDecls.push_back(D);
1448 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1449 if (D->isInvalidDecl())
1452 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1453 D->hasAttr<ObjCPreciseLifetimeAttr>())
1456 if (isa<LabelDecl>(D))
1459 // Except for labels, we only care about unused decls that are local to
1461 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1462 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1463 // For dependent types, the diagnostic is deferred.
1465 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1466 if (!WithinFunction)
1469 if (isa<TypedefNameDecl>(D))
1472 // White-list anything that isn't a local variable.
1473 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1476 // Types of valid local variables should be complete, so this should succeed.
1477 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1479 // White-list anything with an __attribute__((unused)) type.
1480 QualType Ty = VD->getType();
1482 // Only look at the outermost level of typedef.
1483 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1484 if (TT->getDecl()->hasAttr<UnusedAttr>())
1488 // If we failed to complete the type for some reason, or if the type is
1489 // dependent, don't diagnose the variable.
1490 if (Ty->isIncompleteType() || Ty->isDependentType())
1493 if (const TagType *TT = Ty->getAs<TagType>()) {
1494 const TagDecl *Tag = TT->getDecl();
1495 if (Tag->hasAttr<UnusedAttr>())
1498 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1499 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1502 if (const Expr *Init = VD->getInit()) {
1503 if (const ExprWithCleanups *Cleanups =
1504 dyn_cast<ExprWithCleanups>(Init))
1505 Init = Cleanups->getSubExpr();
1506 const CXXConstructExpr *Construct =
1507 dyn_cast<CXXConstructExpr>(Init);
1508 if (Construct && !Construct->isElidable()) {
1509 CXXConstructorDecl *CD = Construct->getConstructor();
1510 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1517 // TODO: __attribute__((unused)) templates?
1523 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1525 if (isa<LabelDecl>(D)) {
1526 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1527 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1528 if (AfterColon.isInvalid())
1530 Hint = FixItHint::CreateRemoval(CharSourceRange::
1531 getCharRange(D->getLocStart(), AfterColon));
1536 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1537 if (D->getTypeForDecl()->isDependentType())
1540 for (auto *TmpD : D->decls()) {
1541 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1542 DiagnoseUnusedDecl(T);
1543 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1544 DiagnoseUnusedNestedTypedefs(R);
1548 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1549 /// unless they are marked attr(unused).
1550 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1551 if (!ShouldDiagnoseUnusedDecl(D))
1554 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1555 // typedefs can be referenced later on, so the diagnostics are emitted
1556 // at end-of-translation-unit.
1557 UnusedLocalTypedefNameCandidates.insert(TD);
1562 GenerateFixForUnusedDecl(D, Context, Hint);
1565 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1566 DiagID = diag::warn_unused_exception_param;
1567 else if (isa<LabelDecl>(D))
1568 DiagID = diag::warn_unused_label;
1570 DiagID = diag::warn_unused_variable;
1572 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1575 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1576 // Verify that we have no forward references left. If so, there was a goto
1577 // or address of a label taken, but no definition of it. Label fwd
1578 // definitions are indicated with a null substmt which is also not a resolved
1579 // MS inline assembly label name.
1580 bool Diagnose = false;
1581 if (L->isMSAsmLabel())
1582 Diagnose = !L->isResolvedMSAsmLabel();
1584 Diagnose = L->getStmt() == nullptr;
1586 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1589 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1590 S->mergeNRVOIntoParent();
1592 if (S->decl_empty()) return;
1593 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1594 "Scope shouldn't contain decls!");
1596 for (auto *TmpD : S->decls()) {
1597 assert(TmpD && "This decl didn't get pushed??");
1599 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1600 NamedDecl *D = cast<NamedDecl>(TmpD);
1602 if (!D->getDeclName()) continue;
1604 // Diagnose unused variables in this scope.
1605 if (!S->hasUnrecoverableErrorOccurred()) {
1606 DiagnoseUnusedDecl(D);
1607 if (const auto *RD = dyn_cast<RecordDecl>(D))
1608 DiagnoseUnusedNestedTypedefs(RD);
1611 // If this was a forward reference to a label, verify it was defined.
1612 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1613 CheckPoppedLabel(LD, *this);
1615 // Remove this name from our lexical scope.
1616 IdResolver.RemoveDecl(D);
1620 /// \brief Look for an Objective-C class in the translation unit.
1622 /// \param Id The name of the Objective-C class we're looking for. If
1623 /// typo-correction fixes this name, the Id will be updated
1624 /// to the fixed name.
1626 /// \param IdLoc The location of the name in the translation unit.
1628 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1629 /// if there is no class with the given name.
1631 /// \returns The declaration of the named Objective-C class, or NULL if the
1632 /// class could not be found.
1633 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1634 SourceLocation IdLoc,
1635 bool DoTypoCorrection) {
1636 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1637 // creation from this context.
1638 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1640 if (!IDecl && DoTypoCorrection) {
1641 // Perform typo correction at the given location, but only if we
1642 // find an Objective-C class name.
1643 if (TypoCorrection C = CorrectTypo(
1644 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1645 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1646 CTK_ErrorRecovery)) {
1647 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1648 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1649 Id = IDecl->getIdentifier();
1652 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1653 // This routine must always return a class definition, if any.
1654 if (Def && Def->getDefinition())
1655 Def = Def->getDefinition();
1659 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1660 /// from S, where a non-field would be declared. This routine copes
1661 /// with the difference between C and C++ scoping rules in structs and
1662 /// unions. For example, the following code is well-formed in C but
1663 /// ill-formed in C++:
1669 /// void test_S6() {
1674 /// For the declaration of BAR, this routine will return a different
1675 /// scope. The scope S will be the scope of the unnamed enumeration
1676 /// within S6. In C++, this routine will return the scope associated
1677 /// with S6, because the enumeration's scope is a transparent
1678 /// context but structures can contain non-field names. In C, this
1679 /// routine will return the translation unit scope, since the
1680 /// enumeration's scope is a transparent context and structures cannot
1681 /// contain non-field names.
1682 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1683 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1684 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1685 (S->isClassScope() && !getLangOpts().CPlusPlus))
1690 /// \brief Looks up the declaration of "struct objc_super" and
1691 /// saves it for later use in building builtin declaration of
1692 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1693 /// pre-existing declaration exists no action takes place.
1694 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1695 IdentifierInfo *II) {
1696 if (!II->isStr("objc_msgSendSuper"))
1698 ASTContext &Context = ThisSema.Context;
1700 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1701 SourceLocation(), Sema::LookupTagName);
1702 ThisSema.LookupName(Result, S);
1703 if (Result.getResultKind() == LookupResult::Found)
1704 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1705 Context.setObjCSuperType(Context.getTagDeclType(TD));
1708 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1710 case ASTContext::GE_None:
1712 case ASTContext::GE_Missing_stdio:
1714 case ASTContext::GE_Missing_setjmp:
1716 case ASTContext::GE_Missing_ucontext:
1717 return "ucontext.h";
1719 llvm_unreachable("unhandled error kind");
1722 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1723 /// file scope. lazily create a decl for it. ForRedeclaration is true
1724 /// if we're creating this built-in in anticipation of redeclaring the
1726 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1727 Scope *S, bool ForRedeclaration,
1728 SourceLocation Loc) {
1729 LookupPredefedObjCSuperType(*this, S, II);
1731 ASTContext::GetBuiltinTypeError Error;
1732 QualType R = Context.GetBuiltinType(ID, Error);
1734 if (ForRedeclaration)
1735 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1736 << getHeaderName(Error)
1737 << Context.BuiltinInfo.GetName(ID);
1741 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1742 Diag(Loc, diag::ext_implicit_lib_function_decl)
1743 << Context.BuiltinInfo.GetName(ID)
1745 if (Context.BuiltinInfo.getHeaderName(ID) &&
1746 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1747 Diag(Loc, diag::note_include_header_or_declare)
1748 << Context.BuiltinInfo.getHeaderName(ID)
1749 << Context.BuiltinInfo.GetName(ID);
1752 DeclContext *Parent = Context.getTranslationUnitDecl();
1753 if (getLangOpts().CPlusPlus) {
1754 LinkageSpecDecl *CLinkageDecl =
1755 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1756 LinkageSpecDecl::lang_c, false);
1757 CLinkageDecl->setImplicit();
1758 Parent->addDecl(CLinkageDecl);
1759 Parent = CLinkageDecl;
1762 FunctionDecl *New = FunctionDecl::Create(Context,
1764 Loc, Loc, II, R, /*TInfo=*/nullptr,
1767 R->isFunctionProtoType());
1770 // Create Decl objects for each parameter, adding them to the
1772 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1773 SmallVector<ParmVarDecl*, 16> Params;
1774 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1776 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1777 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1779 parm->setScopeInfo(0, i);
1780 Params.push_back(parm);
1782 New->setParams(Params);
1785 AddKnownFunctionAttributes(New);
1786 RegisterLocallyScopedExternCDecl(New, S);
1788 // TUScope is the translation-unit scope to insert this function into.
1789 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1790 // relate Scopes to DeclContexts, and probably eliminate CurContext
1791 // entirely, but we're not there yet.
1792 DeclContext *SavedContext = CurContext;
1793 CurContext = Parent;
1794 PushOnScopeChains(New, TUScope);
1795 CurContext = SavedContext;
1799 /// \brief Filter out any previous declarations that the given declaration
1800 /// should not consider because they are not permitted to conflict, e.g.,
1801 /// because they come from hidden sub-modules and do not refer to the same
1803 static void filterNonConflictingPreviousDecls(Sema &S,
1805 LookupResult &previous){
1806 // This is only interesting when modules are enabled.
1807 if ((!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) ||
1808 !S.getLangOpts().ModulesHideInternalLinkage)
1811 // Empty sets are uninteresting.
1812 if (previous.empty())
1815 LookupResult::Filter filter = previous.makeFilter();
1816 while (filter.hasNext()) {
1817 NamedDecl *old = filter.next();
1819 // Non-hidden declarations are never ignored.
1820 if (S.isVisible(old))
1823 if (!old->isExternallyVisible())
1830 /// Typedef declarations don't have linkage, but they still denote the same
1831 /// entity if their types are the same.
1832 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1834 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1835 TypedefNameDecl *Decl,
1836 LookupResult &Previous) {
1837 // This is only interesting when modules are enabled.
1838 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1841 // Empty sets are uninteresting.
1842 if (Previous.empty())
1845 LookupResult::Filter Filter = Previous.makeFilter();
1846 while (Filter.hasNext()) {
1847 NamedDecl *Old = Filter.next();
1849 // Non-hidden declarations are never ignored.
1850 if (S.isVisible(Old))
1853 // Declarations of the same entity are not ignored, even if they have
1854 // different linkages.
1855 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1856 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1857 Decl->getUnderlyingType()))
1860 // If both declarations give a tag declaration a typedef name for linkage
1861 // purposes, then they declare the same entity.
1862 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1863 Decl->getAnonDeclWithTypedefName())
1867 if (!Old->isExternallyVisible())
1874 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1876 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1877 OldType = OldTypedef->getUnderlyingType();
1879 OldType = Context.getTypeDeclType(Old);
1880 QualType NewType = New->getUnderlyingType();
1882 if (NewType->isVariablyModifiedType()) {
1883 // Must not redefine a typedef with a variably-modified type.
1884 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1885 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1887 if (Old->getLocation().isValid())
1888 Diag(Old->getLocation(), diag::note_previous_definition);
1889 New->setInvalidDecl();
1893 if (OldType != NewType &&
1894 !OldType->isDependentType() &&
1895 !NewType->isDependentType() &&
1896 !Context.hasSameType(OldType, NewType)) {
1897 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1898 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1899 << Kind << NewType << OldType;
1900 if (Old->getLocation().isValid())
1901 Diag(Old->getLocation(), diag::note_previous_definition);
1902 New->setInvalidDecl();
1908 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1909 /// same name and scope as a previous declaration 'Old'. Figure out
1910 /// how to resolve this situation, merging decls or emitting
1911 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1913 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1914 // If the new decl is known invalid already, don't bother doing any
1916 if (New->isInvalidDecl()) return;
1918 // Allow multiple definitions for ObjC built-in typedefs.
1919 // FIXME: Verify the underlying types are equivalent!
1920 if (getLangOpts().ObjC1) {
1921 const IdentifierInfo *TypeID = New->getIdentifier();
1922 switch (TypeID->getLength()) {
1926 if (!TypeID->isStr("id"))
1928 QualType T = New->getUnderlyingType();
1929 if (!T->isPointerType())
1931 if (!T->isVoidPointerType()) {
1932 QualType PT = T->getAs<PointerType>()->getPointeeType();
1933 if (!PT->isStructureType())
1936 Context.setObjCIdRedefinitionType(T);
1937 // Install the built-in type for 'id', ignoring the current definition.
1938 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1942 if (!TypeID->isStr("Class"))
1944 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1945 // Install the built-in type for 'Class', ignoring the current definition.
1946 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1949 if (!TypeID->isStr("SEL"))
1951 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1952 // Install the built-in type for 'SEL', ignoring the current definition.
1953 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1956 // Fall through - the typedef name was not a builtin type.
1959 // Verify the old decl was also a type.
1960 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1962 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1963 << New->getDeclName();
1965 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1966 if (OldD->getLocation().isValid())
1967 Diag(OldD->getLocation(), diag::note_previous_definition);
1969 return New->setInvalidDecl();
1972 // If the old declaration is invalid, just give up here.
1973 if (Old->isInvalidDecl())
1974 return New->setInvalidDecl();
1976 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1977 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1978 auto *NewTag = New->getAnonDeclWithTypedefName();
1979 NamedDecl *Hidden = nullptr;
1980 if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1981 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1982 !hasVisibleDefinition(OldTag, &Hidden)) {
1983 // There is a definition of this tag, but it is not visible. Use it
1984 // instead of our tag.
1985 New->setTypeForDecl(OldTD->getTypeForDecl());
1986 if (OldTD->isModed())
1987 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1988 OldTD->getUnderlyingType());
1990 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1992 // Make the old tag definition visible.
1993 makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1997 // If the typedef types are not identical, reject them in all languages and
1998 // with any extensions enabled.
1999 if (isIncompatibleTypedef(Old, New))
2002 // The types match. Link up the redeclaration chain and merge attributes if
2003 // the old declaration was a typedef.
2004 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2005 New->setPreviousDecl(Typedef);
2006 mergeDeclAttributes(New, Old);
2009 if (getLangOpts().MicrosoftExt)
2012 if (getLangOpts().CPlusPlus) {
2013 // C++ [dcl.typedef]p2:
2014 // In a given non-class scope, a typedef specifier can be used to
2015 // redefine the name of any type declared in that scope to refer
2016 // to the type to which it already refers.
2017 if (!isa<CXXRecordDecl>(CurContext))
2020 // C++0x [dcl.typedef]p4:
2021 // In a given class scope, a typedef specifier can be used to redefine
2022 // any class-name declared in that scope that is not also a typedef-name
2023 // to refer to the type to which it already refers.
2025 // This wording came in via DR424, which was a correction to the
2026 // wording in DR56, which accidentally banned code like:
2029 // typedef struct A { } A;
2032 // in the C++03 standard. We implement the C++0x semantics, which
2033 // allow the above but disallow
2040 // since that was the intent of DR56.
2041 if (!isa<TypedefNameDecl>(Old))
2044 Diag(New->getLocation(), diag::err_redefinition)
2045 << New->getDeclName();
2046 Diag(Old->getLocation(), diag::note_previous_definition);
2047 return New->setInvalidDecl();
2050 // Modules always permit redefinition of typedefs, as does C11.
2051 if (getLangOpts().Modules || getLangOpts().C11)
2054 // If we have a redefinition of a typedef in C, emit a warning. This warning
2055 // is normally mapped to an error, but can be controlled with
2056 // -Wtypedef-redefinition. If either the original or the redefinition is
2057 // in a system header, don't emit this for compatibility with GCC.
2058 if (getDiagnostics().getSuppressSystemWarnings() &&
2059 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2060 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2063 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2064 << New->getDeclName();
2065 Diag(Old->getLocation(), diag::note_previous_definition);
2068 /// DeclhasAttr - returns true if decl Declaration already has the target
2070 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2071 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2072 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2073 for (const auto *i : D->attrs())
2074 if (i->getKind() == A->getKind()) {
2076 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2080 // FIXME: Don't hardcode this check
2081 if (OA && isa<OwnershipAttr>(i))
2082 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2089 static bool isAttributeTargetADefinition(Decl *D) {
2090 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2091 return VD->isThisDeclarationADefinition();
2092 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2093 return TD->isCompleteDefinition() || TD->isBeingDefined();
2097 /// Merge alignment attributes from \p Old to \p New, taking into account the
2098 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2100 /// \return \c true if any attributes were added to \p New.
2101 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2102 // Look for alignas attributes on Old, and pick out whichever attribute
2103 // specifies the strictest alignment requirement.
2104 AlignedAttr *OldAlignasAttr = nullptr;
2105 AlignedAttr *OldStrictestAlignAttr = nullptr;
2106 unsigned OldAlign = 0;
2107 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2108 // FIXME: We have no way of representing inherited dependent alignments
2110 // template<int A, int B> struct alignas(A) X;
2111 // template<int A, int B> struct alignas(B) X {};
2112 // For now, we just ignore any alignas attributes which are not on the
2113 // definition in such a case.
2114 if (I->isAlignmentDependent())
2120 unsigned Align = I->getAlignment(S.Context);
2121 if (Align > OldAlign) {
2123 OldStrictestAlignAttr = I;
2127 // Look for alignas attributes on New.
2128 AlignedAttr *NewAlignasAttr = nullptr;
2129 unsigned NewAlign = 0;
2130 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2131 if (I->isAlignmentDependent())
2137 unsigned Align = I->getAlignment(S.Context);
2138 if (Align > NewAlign)
2142 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2143 // Both declarations have 'alignas' attributes. We require them to match.
2144 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2145 // fall short. (If two declarations both have alignas, they must both match
2146 // every definition, and so must match each other if there is a definition.)
2148 // If either declaration only contains 'alignas(0)' specifiers, then it
2149 // specifies the natural alignment for the type.
2150 if (OldAlign == 0 || NewAlign == 0) {
2152 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2155 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2158 OldAlign = S.Context.getTypeAlign(Ty);
2160 NewAlign = S.Context.getTypeAlign(Ty);
2163 if (OldAlign != NewAlign) {
2164 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2165 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2166 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2167 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2171 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2172 // C++11 [dcl.align]p6:
2173 // if any declaration of an entity has an alignment-specifier,
2174 // every defining declaration of that entity shall specify an
2175 // equivalent alignment.
2177 // If the definition of an object does not have an alignment
2178 // specifier, any other declaration of that object shall also
2179 // have no alignment specifier.
2180 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2182 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2186 bool AnyAdded = false;
2188 // Ensure we have an attribute representing the strictest alignment.
2189 if (OldAlign > NewAlign) {
2190 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2191 Clone->setInherited(true);
2192 New->addAttr(Clone);
2196 // Ensure we have an alignas attribute if the old declaration had one.
2197 if (OldAlignasAttr && !NewAlignasAttr &&
2198 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2199 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2200 Clone->setInherited(true);
2201 New->addAttr(Clone);
2208 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2209 const InheritableAttr *Attr, bool Override) {
2210 InheritableAttr *NewAttr = nullptr;
2211 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2212 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2213 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2214 AA->getIntroduced(), AA->getDeprecated(),
2215 AA->getObsoleted(), AA->getUnavailable(),
2216 AA->getMessage(), Override,
2217 AttrSpellingListIndex);
2218 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2219 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2220 AttrSpellingListIndex);
2221 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2222 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2223 AttrSpellingListIndex);
2224 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2225 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2226 AttrSpellingListIndex);
2227 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2228 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2229 AttrSpellingListIndex);
2230 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2231 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2232 FA->getFormatIdx(), FA->getFirstArg(),
2233 AttrSpellingListIndex);
2234 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2235 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2236 AttrSpellingListIndex);
2237 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2238 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2239 AttrSpellingListIndex,
2240 IA->getSemanticSpelling());
2241 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2242 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2243 &S.Context.Idents.get(AA->getSpelling()),
2244 AttrSpellingListIndex);
2245 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2246 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2247 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2248 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2249 else if (isa<AlignedAttr>(Attr))
2250 // AlignedAttrs are handled separately, because we need to handle all
2251 // such attributes on a declaration at the same time.
2253 else if (isa<DeprecatedAttr>(Attr) && Override)
2255 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2256 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2259 NewAttr->setInherited(true);
2260 D->addAttr(NewAttr);
2267 static const Decl *getDefinition(const Decl *D) {
2268 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2269 return TD->getDefinition();
2270 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2271 const VarDecl *Def = VD->getDefinition();
2274 return VD->getActingDefinition();
2276 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2277 const FunctionDecl* Def;
2278 if (FD->isDefined(Def))
2284 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2285 for (const auto *Attribute : D->attrs())
2286 if (Attribute->getKind() == Kind)
2291 /// checkNewAttributesAfterDef - If we already have a definition, check that
2292 /// there are no new attributes in this declaration.
2293 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2294 if (!New->hasAttrs())
2297 const Decl *Def = getDefinition(Old);
2298 if (!Def || Def == New)
2301 AttrVec &NewAttributes = New->getAttrs();
2302 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2303 const Attr *NewAttribute = NewAttributes[I];
2305 if (isa<AliasAttr>(NewAttribute)) {
2306 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2307 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2309 VarDecl *VD = cast<VarDecl>(New);
2310 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2311 VarDecl::TentativeDefinition
2312 ? diag::err_alias_after_tentative
2313 : diag::err_redefinition;
2314 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2315 S.Diag(Def->getLocation(), diag::note_previous_definition);
2316 VD->setInvalidDecl();
2322 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2323 // Tentative definitions are only interesting for the alias check above.
2324 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2330 if (hasAttribute(Def, NewAttribute->getKind())) {
2332 continue; // regular attr merging will take care of validating this.
2335 if (isa<C11NoReturnAttr>(NewAttribute)) {
2336 // C's _Noreturn is allowed to be added to a function after it is defined.
2339 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2340 if (AA->isAlignas()) {
2341 // C++11 [dcl.align]p6:
2342 // if any declaration of an entity has an alignment-specifier,
2343 // every defining declaration of that entity shall specify an
2344 // equivalent alignment.
2346 // If the definition of an object does not have an alignment
2347 // specifier, any other declaration of that object shall also
2348 // have no alignment specifier.
2349 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2351 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2353 NewAttributes.erase(NewAttributes.begin() + I);
2359 S.Diag(NewAttribute->getLocation(),
2360 diag::warn_attribute_precede_definition);
2361 S.Diag(Def->getLocation(), diag::note_previous_definition);
2362 NewAttributes.erase(NewAttributes.begin() + I);
2367 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2368 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2369 AvailabilityMergeKind AMK) {
2370 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2371 UsedAttr *NewAttr = OldAttr->clone(Context);
2372 NewAttr->setInherited(true);
2373 New->addAttr(NewAttr);
2376 if (!Old->hasAttrs() && !New->hasAttrs())
2379 // attributes declared post-definition are currently ignored
2380 checkNewAttributesAfterDef(*this, New, Old);
2382 if (!Old->hasAttrs())
2385 bool foundAny = New->hasAttrs();
2387 // Ensure that any moving of objects within the allocated map is done before
2389 if (!foundAny) New->setAttrs(AttrVec());
2391 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2392 bool Override = false;
2393 // Ignore deprecated/unavailable/availability attributes if requested.
2394 if (isa<DeprecatedAttr>(I) ||
2395 isa<UnavailableAttr>(I) ||
2396 isa<AvailabilityAttr>(I)) {
2401 case AMK_Redeclaration:
2411 if (isa<UsedAttr>(I))
2414 if (mergeDeclAttribute(*this, New, I, Override))
2418 if (mergeAlignedAttrs(*this, New, Old))
2421 if (!foundAny) New->dropAttrs();
2424 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2426 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2427 const ParmVarDecl *oldDecl,
2429 // C++11 [dcl.attr.depend]p2:
2430 // The first declaration of a function shall specify the
2431 // carries_dependency attribute for its declarator-id if any declaration
2432 // of the function specifies the carries_dependency attribute.
2433 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2434 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2435 S.Diag(CDA->getLocation(),
2436 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2437 // Find the first declaration of the parameter.
2438 // FIXME: Should we build redeclaration chains for function parameters?
2439 const FunctionDecl *FirstFD =
2440 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2441 const ParmVarDecl *FirstVD =
2442 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2443 S.Diag(FirstVD->getLocation(),
2444 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2447 if (!oldDecl->hasAttrs())
2450 bool foundAny = newDecl->hasAttrs();
2452 // Ensure that any moving of objects within the allocated map is
2453 // done before we process them.
2454 if (!foundAny) newDecl->setAttrs(AttrVec());
2456 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2457 if (!DeclHasAttr(newDecl, I)) {
2458 InheritableAttr *newAttr =
2459 cast<InheritableParamAttr>(I->clone(S.Context));
2460 newAttr->setInherited(true);
2461 newDecl->addAttr(newAttr);
2466 if (!foundAny) newDecl->dropAttrs();
2469 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2470 const ParmVarDecl *OldParam,
2472 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2473 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2474 if (*Oldnullability != *Newnullability) {
2475 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2476 << DiagNullabilityKind(
2478 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2480 << DiagNullabilityKind(
2482 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2484 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2487 QualType NewT = NewParam->getType();
2488 NewT = S.Context.getAttributedType(
2489 AttributedType::getNullabilityAttrKind(*Oldnullability),
2491 NewParam->setType(NewT);
2498 /// Used in MergeFunctionDecl to keep track of function parameters in
2500 struct GNUCompatibleParamWarning {
2501 ParmVarDecl *OldParm;
2502 ParmVarDecl *NewParm;
2503 QualType PromotedType;
2508 /// getSpecialMember - get the special member enum for a method.
2509 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2510 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2511 if (Ctor->isDefaultConstructor())
2512 return Sema::CXXDefaultConstructor;
2514 if (Ctor->isCopyConstructor())
2515 return Sema::CXXCopyConstructor;
2517 if (Ctor->isMoveConstructor())
2518 return Sema::CXXMoveConstructor;
2519 } else if (isa<CXXDestructorDecl>(MD)) {
2520 return Sema::CXXDestructor;
2521 } else if (MD->isCopyAssignmentOperator()) {
2522 return Sema::CXXCopyAssignment;
2523 } else if (MD->isMoveAssignmentOperator()) {
2524 return Sema::CXXMoveAssignment;
2527 return Sema::CXXInvalid;
2530 // Determine whether the previous declaration was a definition, implicit
2531 // declaration, or a declaration.
2532 template <typename T>
2533 static std::pair<diag::kind, SourceLocation>
2534 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2535 diag::kind PrevDiag;
2536 SourceLocation OldLocation = Old->getLocation();
2537 if (Old->isThisDeclarationADefinition())
2538 PrevDiag = diag::note_previous_definition;
2539 else if (Old->isImplicit()) {
2540 PrevDiag = diag::note_previous_implicit_declaration;
2541 if (OldLocation.isInvalid())
2542 OldLocation = New->getLocation();
2544 PrevDiag = diag::note_previous_declaration;
2545 return std::make_pair(PrevDiag, OldLocation);
2548 /// canRedefineFunction - checks if a function can be redefined. Currently,
2549 /// only extern inline functions can be redefined, and even then only in
2551 static bool canRedefineFunction(const FunctionDecl *FD,
2552 const LangOptions& LangOpts) {
2553 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2554 !LangOpts.CPlusPlus &&
2555 FD->isInlineSpecified() &&
2556 FD->getStorageClass() == SC_Extern);
2559 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2560 const AttributedType *AT = T->getAs<AttributedType>();
2561 while (AT && !AT->isCallingConv())
2562 AT = AT->getModifiedType()->getAs<AttributedType>();
2566 template <typename T>
2567 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2568 const DeclContext *DC = Old->getDeclContext();
2572 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2573 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2575 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2580 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2581 static bool isExternC(VarTemplateDecl *) { return false; }
2583 /// \brief Check whether a redeclaration of an entity introduced by a
2584 /// using-declaration is valid, given that we know it's not an overload
2585 /// (nor a hidden tag declaration).
2586 template<typename ExpectedDecl>
2587 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2588 ExpectedDecl *New) {
2589 // C++11 [basic.scope.declarative]p4:
2590 // Given a set of declarations in a single declarative region, each of
2591 // which specifies the same unqualified name,
2592 // -- they shall all refer to the same entity, or all refer to functions
2593 // and function templates; or
2594 // -- exactly one declaration shall declare a class name or enumeration
2595 // name that is not a typedef name and the other declarations shall all
2596 // refer to the same variable or enumerator, or all refer to functions
2597 // and function templates; in this case the class name or enumeration
2598 // name is hidden (3.3.10).
2600 // C++11 [namespace.udecl]p14:
2601 // If a function declaration in namespace scope or block scope has the
2602 // same name and the same parameter-type-list as a function introduced
2603 // by a using-declaration, and the declarations do not declare the same
2604 // function, the program is ill-formed.
2606 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2608 !Old->getDeclContext()->getRedeclContext()->Equals(
2609 New->getDeclContext()->getRedeclContext()) &&
2610 !(isExternC(Old) && isExternC(New)))
2614 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2615 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2616 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2622 /// MergeFunctionDecl - We just parsed a function 'New' from
2623 /// declarator D which has the same name and scope as a previous
2624 /// declaration 'Old'. Figure out how to resolve this situation,
2625 /// merging decls or emitting diagnostics as appropriate.
2627 /// In C++, New and Old must be declarations that are not
2628 /// overloaded. Use IsOverload to determine whether New and Old are
2629 /// overloaded, and to select the Old declaration that New should be
2632 /// Returns true if there was an error, false otherwise.
2633 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2634 Scope *S, bool MergeTypeWithOld) {
2635 // Verify the old decl was also a function.
2636 FunctionDecl *Old = OldD->getAsFunction();
2638 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2639 if (New->getFriendObjectKind()) {
2640 Diag(New->getLocation(), diag::err_using_decl_friend);
2641 Diag(Shadow->getTargetDecl()->getLocation(),
2642 diag::note_using_decl_target);
2643 Diag(Shadow->getUsingDecl()->getLocation(),
2644 diag::note_using_decl) << 0;
2648 // Check whether the two declarations might declare the same function.
2649 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2651 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2653 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2654 << New->getDeclName();
2655 Diag(OldD->getLocation(), diag::note_previous_definition);
2660 // If the old declaration is invalid, just give up here.
2661 if (Old->isInvalidDecl())
2664 diag::kind PrevDiag;
2665 SourceLocation OldLocation;
2666 std::tie(PrevDiag, OldLocation) =
2667 getNoteDiagForInvalidRedeclaration(Old, New);
2669 // Don't complain about this if we're in GNU89 mode and the old function
2670 // is an extern inline function.
2671 // Don't complain about specializations. They are not supposed to have
2673 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2674 New->getStorageClass() == SC_Static &&
2675 Old->hasExternalFormalLinkage() &&
2676 !New->getTemplateSpecializationInfo() &&
2677 !canRedefineFunction(Old, getLangOpts())) {
2678 if (getLangOpts().MicrosoftExt) {
2679 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2680 Diag(OldLocation, PrevDiag);
2682 Diag(New->getLocation(), diag::err_static_non_static) << New;
2683 Diag(OldLocation, PrevDiag);
2689 // If a function is first declared with a calling convention, but is later
2690 // declared or defined without one, all following decls assume the calling
2691 // convention of the first.
2693 // It's OK if a function is first declared without a calling convention,
2694 // but is later declared or defined with the default calling convention.
2696 // To test if either decl has an explicit calling convention, we look for
2697 // AttributedType sugar nodes on the type as written. If they are missing or
2698 // were canonicalized away, we assume the calling convention was implicit.
2700 // Note also that we DO NOT return at this point, because we still have
2701 // other tests to run.
2702 QualType OldQType = Context.getCanonicalType(Old->getType());
2703 QualType NewQType = Context.getCanonicalType(New->getType());
2704 const FunctionType *OldType = cast<FunctionType>(OldQType);
2705 const FunctionType *NewType = cast<FunctionType>(NewQType);
2706 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2707 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2708 bool RequiresAdjustment = false;
2710 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2711 FunctionDecl *First = Old->getFirstDecl();
2712 const FunctionType *FT =
2713 First->getType().getCanonicalType()->castAs<FunctionType>();
2714 FunctionType::ExtInfo FI = FT->getExtInfo();
2715 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2716 if (!NewCCExplicit) {
2717 // Inherit the CC from the previous declaration if it was specified
2718 // there but not here.
2719 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2720 RequiresAdjustment = true;
2722 // Calling conventions aren't compatible, so complain.
2723 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2724 Diag(New->getLocation(), diag::err_cconv_change)
2725 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2727 << (!FirstCCExplicit ? "" :
2728 FunctionType::getNameForCallConv(FI.getCC()));
2730 // Put the note on the first decl, since it is the one that matters.
2731 Diag(First->getLocation(), diag::note_previous_declaration);
2736 // FIXME: diagnose the other way around?
2737 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2738 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2739 RequiresAdjustment = true;
2742 // Merge regparm attribute.
2743 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2744 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2745 if (NewTypeInfo.getHasRegParm()) {
2746 Diag(New->getLocation(), diag::err_regparm_mismatch)
2747 << NewType->getRegParmType()
2748 << OldType->getRegParmType();
2749 Diag(OldLocation, diag::note_previous_declaration);
2753 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2754 RequiresAdjustment = true;
2757 // Merge ns_returns_retained attribute.
2758 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2759 if (NewTypeInfo.getProducesResult()) {
2760 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2761 Diag(OldLocation, diag::note_previous_declaration);
2765 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2766 RequiresAdjustment = true;
2769 if (RequiresAdjustment) {
2770 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2771 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2772 New->setType(QualType(AdjustedType, 0));
2773 NewQType = Context.getCanonicalType(New->getType());
2774 NewType = cast<FunctionType>(NewQType);
2777 // If this redeclaration makes the function inline, we may need to add it to
2778 // UndefinedButUsed.
2779 if (!Old->isInlined() && New->isInlined() &&
2780 !New->hasAttr<GNUInlineAttr>() &&
2781 !getLangOpts().GNUInline &&
2782 Old->isUsed(false) &&
2783 !Old->isDefined() && !New->isThisDeclarationADefinition())
2784 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2787 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2789 if (New->hasAttr<GNUInlineAttr>() &&
2790 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2791 UndefinedButUsed.erase(Old->getCanonicalDecl());
2794 if (getLangOpts().CPlusPlus) {
2796 // Certain function declarations cannot be overloaded:
2797 // -- Function declarations that differ only in the return type
2798 // cannot be overloaded.
2800 // Go back to the type source info to compare the declared return types,
2801 // per C++1y [dcl.type.auto]p13:
2802 // Redeclarations or specializations of a function or function template
2803 // with a declared return type that uses a placeholder type shall also
2804 // use that placeholder, not a deduced type.
2805 QualType OldDeclaredReturnType =
2806 (Old->getTypeSourceInfo()
2807 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2808 : OldType)->getReturnType();
2809 QualType NewDeclaredReturnType =
2810 (New->getTypeSourceInfo()
2811 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2812 : NewType)->getReturnType();
2814 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2815 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2816 New->isLocalExternDecl())) {
2817 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2818 OldDeclaredReturnType->isObjCObjectPointerType())
2819 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2820 if (ResQT.isNull()) {
2821 if (New->isCXXClassMember() && New->isOutOfLine())
2822 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2823 << New << New->getReturnTypeSourceRange();
2825 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2826 << New->getReturnTypeSourceRange();
2827 Diag(OldLocation, PrevDiag) << Old << Old->getType()
2828 << Old->getReturnTypeSourceRange();
2835 QualType OldReturnType = OldType->getReturnType();
2836 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2837 if (OldReturnType != NewReturnType) {
2838 // If this function has a deduced return type and has already been
2839 // defined, copy the deduced value from the old declaration.
2840 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2841 if (OldAT && OldAT->isDeduced()) {
2843 SubstAutoType(New->getType(),
2844 OldAT->isDependentType() ? Context.DependentTy
2845 : OldAT->getDeducedType()));
2846 NewQType = Context.getCanonicalType(
2847 SubstAutoType(NewQType,
2848 OldAT->isDependentType() ? Context.DependentTy
2849 : OldAT->getDeducedType()));
2853 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2854 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2855 if (OldMethod && NewMethod) {
2856 // Preserve triviality.
2857 NewMethod->setTrivial(OldMethod->isTrivial());
2859 // MSVC allows explicit template specialization at class scope:
2860 // 2 CXXMethodDecls referring to the same function will be injected.
2861 // We don't want a redeclaration error.
2862 bool IsClassScopeExplicitSpecialization =
2863 OldMethod->isFunctionTemplateSpecialization() &&
2864 NewMethod->isFunctionTemplateSpecialization();
2865 bool isFriend = NewMethod->getFriendObjectKind();
2867 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2868 !IsClassScopeExplicitSpecialization) {
2869 // -- Member function declarations with the same name and the
2870 // same parameter types cannot be overloaded if any of them
2871 // is a static member function declaration.
2872 if (OldMethod->isStatic() != NewMethod->isStatic()) {
2873 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2874 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2878 // C++ [class.mem]p1:
2879 // [...] A member shall not be declared twice in the
2880 // member-specification, except that a nested class or member
2881 // class template can be declared and then later defined.
2882 if (ActiveTemplateInstantiations.empty()) {
2884 if (isa<CXXConstructorDecl>(OldMethod))
2885 NewDiag = diag::err_constructor_redeclared;
2886 else if (isa<CXXDestructorDecl>(NewMethod))
2887 NewDiag = diag::err_destructor_redeclared;
2888 else if (isa<CXXConversionDecl>(NewMethod))
2889 NewDiag = diag::err_conv_function_redeclared;
2891 NewDiag = diag::err_member_redeclared;
2893 Diag(New->getLocation(), NewDiag);
2895 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2896 << New << New->getType();
2898 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2901 // Complain if this is an explicit declaration of a special
2902 // member that was initially declared implicitly.
2904 // As an exception, it's okay to befriend such methods in order
2905 // to permit the implicit constructor/destructor/operator calls.
2906 } else if (OldMethod->isImplicit()) {
2908 NewMethod->setImplicit();
2910 Diag(NewMethod->getLocation(),
2911 diag::err_definition_of_implicitly_declared_member)
2912 << New << getSpecialMember(OldMethod);
2915 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2916 Diag(NewMethod->getLocation(),
2917 diag::err_definition_of_explicitly_defaulted_member)
2918 << getSpecialMember(OldMethod);
2923 // C++11 [dcl.attr.noreturn]p1:
2924 // The first declaration of a function shall specify the noreturn
2925 // attribute if any declaration of that function specifies the noreturn
2927 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2928 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2929 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2930 Diag(Old->getFirstDecl()->getLocation(),
2931 diag::note_noreturn_missing_first_decl);
2934 // C++11 [dcl.attr.depend]p2:
2935 // The first declaration of a function shall specify the
2936 // carries_dependency attribute for its declarator-id if any declaration
2937 // of the function specifies the carries_dependency attribute.
2938 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2939 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2940 Diag(CDA->getLocation(),
2941 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2942 Diag(Old->getFirstDecl()->getLocation(),
2943 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2947 // All declarations for a function shall agree exactly in both the
2948 // return type and the parameter-type-list.
2949 // We also want to respect all the extended bits except noreturn.
2951 // noreturn should now match unless the old type info didn't have it.
2952 QualType OldQTypeForComparison = OldQType;
2953 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2954 assert(OldQType == QualType(OldType, 0));
2955 const FunctionType *OldTypeForComparison
2956 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2957 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2958 assert(OldQTypeForComparison.isCanonical());
2961 if (haveIncompatibleLanguageLinkages(Old, New)) {
2962 // As a special case, retain the language linkage from previous
2963 // declarations of a friend function as an extension.
2965 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2966 // and is useful because there's otherwise no way to specify language
2967 // linkage within class scope.
2969 // Check cautiously as the friend object kind isn't yet complete.
2970 if (New->getFriendObjectKind() != Decl::FOK_None) {
2971 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2972 Diag(OldLocation, PrevDiag);
2974 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2975 Diag(OldLocation, PrevDiag);
2980 if (OldQTypeForComparison == NewQType)
2981 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2983 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2984 New->isLocalExternDecl()) {
2985 // It's OK if we couldn't merge types for a local function declaraton
2986 // if either the old or new type is dependent. We'll merge the types
2987 // when we instantiate the function.
2991 // Fall through for conflicting redeclarations and redefinitions.
2994 // C: Function types need to be compatible, not identical. This handles
2995 // duplicate function decls like "void f(int); void f(enum X);" properly.
2996 if (!getLangOpts().CPlusPlus &&
2997 Context.typesAreCompatible(OldQType, NewQType)) {
2998 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2999 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3000 const FunctionProtoType *OldProto = nullptr;
3001 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3002 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3003 // The old declaration provided a function prototype, but the
3004 // new declaration does not. Merge in the prototype.
3005 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3006 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3008 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3009 OldProto->getExtProtoInfo());
3010 New->setType(NewQType);
3011 New->setHasInheritedPrototype();
3013 // Synthesize parameters with the same types.
3014 SmallVector<ParmVarDecl*, 16> Params;
3015 for (const auto &ParamType : OldProto->param_types()) {
3016 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3017 SourceLocation(), nullptr,
3018 ParamType, /*TInfo=*/nullptr,
3020 Param->setScopeInfo(0, Params.size());
3021 Param->setImplicit();
3022 Params.push_back(Param);
3025 New->setParams(Params);
3028 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3031 // GNU C permits a K&R definition to follow a prototype declaration
3032 // if the declared types of the parameters in the K&R definition
3033 // match the types in the prototype declaration, even when the
3034 // promoted types of the parameters from the K&R definition differ
3035 // from the types in the prototype. GCC then keeps the types from
3038 // If a variadic prototype is followed by a non-variadic K&R definition,
3039 // the K&R definition becomes variadic. This is sort of an edge case, but
3040 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3042 if (!getLangOpts().CPlusPlus &&
3043 Old->hasPrototype() && !New->hasPrototype() &&
3044 New->getType()->getAs<FunctionProtoType>() &&
3045 Old->getNumParams() == New->getNumParams()) {
3046 SmallVector<QualType, 16> ArgTypes;
3047 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3048 const FunctionProtoType *OldProto
3049 = Old->getType()->getAs<FunctionProtoType>();
3050 const FunctionProtoType *NewProto
3051 = New->getType()->getAs<FunctionProtoType>();
3053 // Determine whether this is the GNU C extension.
3054 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3055 NewProto->getReturnType());
3056 bool LooseCompatible = !MergedReturn.isNull();
3057 for (unsigned Idx = 0, End = Old->getNumParams();
3058 LooseCompatible && Idx != End; ++Idx) {
3059 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3060 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3061 if (Context.typesAreCompatible(OldParm->getType(),
3062 NewProto->getParamType(Idx))) {
3063 ArgTypes.push_back(NewParm->getType());
3064 } else if (Context.typesAreCompatible(OldParm->getType(),
3066 /*CompareUnqualified=*/true)) {
3067 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3068 NewProto->getParamType(Idx) };
3069 Warnings.push_back(Warn);
3070 ArgTypes.push_back(NewParm->getType());
3072 LooseCompatible = false;
3075 if (LooseCompatible) {
3076 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3077 Diag(Warnings[Warn].NewParm->getLocation(),
3078 diag::ext_param_promoted_not_compatible_with_prototype)
3079 << Warnings[Warn].PromotedType
3080 << Warnings[Warn].OldParm->getType();
3081 if (Warnings[Warn].OldParm->getLocation().isValid())
3082 Diag(Warnings[Warn].OldParm->getLocation(),
3083 diag::note_previous_declaration);
3086 if (MergeTypeWithOld)
3087 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3088 OldProto->getExtProtoInfo()));
3089 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3092 // Fall through to diagnose conflicting types.
3095 // A function that has already been declared has been redeclared or
3096 // defined with a different type; show an appropriate diagnostic.
3098 // If the previous declaration was an implicitly-generated builtin
3099 // declaration, then at the very least we should use a specialized note.
3101 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3102 // If it's actually a library-defined builtin function like 'malloc'
3103 // or 'printf', just warn about the incompatible redeclaration.
3104 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3105 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3106 Diag(OldLocation, diag::note_previous_builtin_declaration)
3107 << Old << Old->getType();
3109 // If this is a global redeclaration, just forget hereafter
3110 // about the "builtin-ness" of the function.
3112 // Doing this for local extern declarations is problematic. If
3113 // the builtin declaration remains visible, a second invalid
3114 // local declaration will produce a hard error; if it doesn't
3115 // remain visible, a single bogus local redeclaration (which is
3116 // actually only a warning) could break all the downstream code.
3117 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3118 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
3123 PrevDiag = diag::note_previous_builtin_declaration;
3126 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3127 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3131 /// \brief Completes the merge of two function declarations that are
3132 /// known to be compatible.
3134 /// This routine handles the merging of attributes and other
3135 /// properties of function declarations from the old declaration to
3136 /// the new declaration, once we know that New is in fact a
3137 /// redeclaration of Old.
3140 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3141 Scope *S, bool MergeTypeWithOld) {
3142 // Merge the attributes
3143 mergeDeclAttributes(New, Old);
3145 // Merge "pure" flag.
3149 // Merge "used" flag.
3150 if (Old->getMostRecentDecl()->isUsed(false))
3153 // Merge attributes from the parameters. These can mismatch with K&R
3155 if (New->getNumParams() == Old->getNumParams())
3156 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3157 ParmVarDecl *NewParam = New->getParamDecl(i);
3158 ParmVarDecl *OldParam = Old->getParamDecl(i);
3159 mergeParamDeclAttributes(NewParam, OldParam, *this);
3160 mergeParamDeclTypes(NewParam, OldParam, *this);
3163 if (getLangOpts().CPlusPlus)
3164 return MergeCXXFunctionDecl(New, Old, S);
3166 // Merge the function types so the we get the composite types for the return
3167 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3169 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3170 if (!Merged.isNull() && MergeTypeWithOld)
3171 New->setType(Merged);
3177 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3178 ObjCMethodDecl *oldMethod) {
3180 // Merge the attributes, including deprecated/unavailable
3181 AvailabilityMergeKind MergeKind =
3182 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3184 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3186 // Merge attributes from the parameters.
3187 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3188 oe = oldMethod->param_end();
3189 for (ObjCMethodDecl::param_iterator
3190 ni = newMethod->param_begin(), ne = newMethod->param_end();
3191 ni != ne && oi != oe; ++ni, ++oi)
3192 mergeParamDeclAttributes(*ni, *oi, *this);
3194 CheckObjCMethodOverride(newMethod, oldMethod);
3197 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3198 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3199 /// emitting diagnostics as appropriate.
3201 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3202 /// to here in AddInitializerToDecl. We can't check them before the initializer
3204 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3205 bool MergeTypeWithOld) {
3206 if (New->isInvalidDecl() || Old->isInvalidDecl())
3210 if (getLangOpts().CPlusPlus) {
3211 if (New->getType()->isUndeducedType()) {
3212 // We don't know what the new type is until the initializer is attached.
3214 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3215 // These could still be something that needs exception specs checked.
3216 return MergeVarDeclExceptionSpecs(New, Old);
3218 // C++ [basic.link]p10:
3219 // [...] the types specified by all declarations referring to a given
3220 // object or function shall be identical, except that declarations for an
3221 // array object can specify array types that differ by the presence or
3222 // absence of a major array bound (8.3.4).
3223 else if (Old->getType()->isIncompleteArrayType() &&
3224 New->getType()->isArrayType()) {
3225 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3226 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3227 if (Context.hasSameType(OldArray->getElementType(),
3228 NewArray->getElementType()))
3229 MergedT = New->getType();
3230 } else if (Old->getType()->isArrayType() &&
3231 New->getType()->isIncompleteArrayType()) {
3232 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3233 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3234 if (Context.hasSameType(OldArray->getElementType(),
3235 NewArray->getElementType()))
3236 MergedT = Old->getType();
3237 } else if (New->getType()->isObjCObjectPointerType() &&
3238 Old->getType()->isObjCObjectPointerType()) {
3239 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3244 // All declarations that refer to the same object or function shall have
3246 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3248 if (MergedT.isNull()) {
3249 // It's OK if we couldn't merge types if either type is dependent, for a
3250 // block-scope variable. In other cases (static data members of class
3251 // templates, variable templates, ...), we require the types to be
3253 // FIXME: The C++ standard doesn't say anything about this.
3254 if ((New->getType()->isDependentType() ||
3255 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3256 // If the old type was dependent, we can't merge with it, so the new type
3257 // becomes dependent for now. We'll reproduce the original type when we
3258 // instantiate the TypeSourceInfo for the variable.
3259 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3260 New->setType(Context.DependentTy);
3264 // FIXME: Even if this merging succeeds, some other non-visible declaration
3265 // of this variable might have an incompatible type. For instance:
3267 // extern int arr[];
3268 // void f() { extern int arr[2]; }
3269 // void g() { extern int arr[3]; }
3271 // Neither C nor C++ requires a diagnostic for this, but we should still try
3273 Diag(New->getLocation(), New->isThisDeclarationADefinition()
3274 ? diag::err_redefinition_different_type
3275 : diag::err_redeclaration_different_type)
3276 << New->getDeclName() << New->getType() << Old->getType();
3278 diag::kind PrevDiag;
3279 SourceLocation OldLocation;
3280 std::tie(PrevDiag, OldLocation) =
3281 getNoteDiagForInvalidRedeclaration(Old, New);
3282 Diag(OldLocation, PrevDiag);
3283 return New->setInvalidDecl();
3286 // Don't actually update the type on the new declaration if the old
3287 // declaration was an extern declaration in a different scope.
3288 if (MergeTypeWithOld)
3289 New->setType(MergedT);
3292 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3293 LookupResult &Previous) {
3295 // For an identifier with internal or external linkage declared
3296 // in a scope in which a prior declaration of that identifier is
3297 // visible, if the prior declaration specifies internal or
3298 // external linkage, the type of the identifier at the later
3299 // declaration becomes the composite type.
3301 // If the variable isn't visible, we do not merge with its type.
3302 if (Previous.isShadowed())
3305 if (S.getLangOpts().CPlusPlus) {
3306 // C++11 [dcl.array]p3:
3307 // If there is a preceding declaration of the entity in the same
3308 // scope in which the bound was specified, an omitted array bound
3309 // is taken to be the same as in that earlier declaration.
3310 return NewVD->isPreviousDeclInSameBlockScope() ||
3311 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3312 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3314 // If the old declaration was function-local, don't merge with its
3315 // type unless we're in the same function.
3316 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3317 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3321 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3322 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3323 /// situation, merging decls or emitting diagnostics as appropriate.
3325 /// Tentative definition rules (C99 6.9.2p2) are checked by
3326 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3327 /// definitions here, since the initializer hasn't been attached.
3329 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3330 // If the new decl is already invalid, don't do any other checking.
3331 if (New->isInvalidDecl())
3334 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3336 // Verify the old decl was also a variable or variable template.
3337 VarDecl *Old = nullptr;
3338 VarTemplateDecl *OldTemplate = nullptr;
3339 if (Previous.isSingleResult()) {
3341 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3342 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3345 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3346 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3347 return New->setInvalidDecl();
3349 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3352 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3353 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3354 return New->setInvalidDecl();
3358 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3359 << New->getDeclName();
3360 Diag(Previous.getRepresentativeDecl()->getLocation(),
3361 diag::note_previous_definition);
3362 return New->setInvalidDecl();
3365 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3368 // Ensure the template parameters are compatible.
3370 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3371 OldTemplate->getTemplateParameters(),
3372 /*Complain=*/true, TPL_TemplateMatch))
3375 // C++ [class.mem]p1:
3376 // A member shall not be declared twice in the member-specification [...]
3378 // Here, we need only consider static data members.
3379 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3380 Diag(New->getLocation(), diag::err_duplicate_member)
3381 << New->getIdentifier();
3382 Diag(Old->getLocation(), diag::note_previous_declaration);
3383 New->setInvalidDecl();
3386 mergeDeclAttributes(New, Old);
3387 // Warn if an already-declared variable is made a weak_import in a subsequent
3389 if (New->hasAttr<WeakImportAttr>() &&
3390 Old->getStorageClass() == SC_None &&
3391 !Old->hasAttr<WeakImportAttr>()) {
3392 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3393 Diag(Old->getLocation(), diag::note_previous_definition);
3394 // Remove weak_import attribute on new declaration.
3395 New->dropAttr<WeakImportAttr>();
3399 VarDecl *MostRecent = Old->getMostRecentDecl();
3400 if (MostRecent != Old) {
3401 MergeVarDeclTypes(New, MostRecent,
3402 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3403 if (New->isInvalidDecl())
3407 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3408 if (New->isInvalidDecl())
3411 diag::kind PrevDiag;
3412 SourceLocation OldLocation;
3413 std::tie(PrevDiag, OldLocation) =
3414 getNoteDiagForInvalidRedeclaration(Old, New);
3416 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3417 if (New->getStorageClass() == SC_Static &&
3418 !New->isStaticDataMember() &&
3419 Old->hasExternalFormalLinkage()) {
3420 if (getLangOpts().MicrosoftExt) {
3421 Diag(New->getLocation(), diag::ext_static_non_static)
3422 << New->getDeclName();
3423 Diag(OldLocation, PrevDiag);
3425 Diag(New->getLocation(), diag::err_static_non_static)
3426 << New->getDeclName();
3427 Diag(OldLocation, PrevDiag);
3428 return New->setInvalidDecl();
3432 // For an identifier declared with the storage-class specifier
3433 // extern in a scope in which a prior declaration of that
3434 // identifier is visible,23) if the prior declaration specifies
3435 // internal or external linkage, the linkage of the identifier at
3436 // the later declaration is the same as the linkage specified at
3437 // the prior declaration. If no prior declaration is visible, or
3438 // if the prior declaration specifies no linkage, then the
3439 // identifier has external linkage.
3440 if (New->hasExternalStorage() && Old->hasLinkage())
3442 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3443 !New->isStaticDataMember() &&
3444 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3445 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3446 Diag(OldLocation, PrevDiag);
3447 return New->setInvalidDecl();
3450 // Check if extern is followed by non-extern and vice-versa.
3451 if (New->hasExternalStorage() &&
3452 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3453 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3454 Diag(OldLocation, PrevDiag);
3455 return New->setInvalidDecl();
3457 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3458 !New->hasExternalStorage()) {
3459 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3460 Diag(OldLocation, PrevDiag);
3461 return New->setInvalidDecl();
3464 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3466 // FIXME: The test for external storage here seems wrong? We still
3467 // need to check for mismatches.
3468 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3469 // Don't complain about out-of-line definitions of static members.
3470 !(Old->getLexicalDeclContext()->isRecord() &&
3471 !New->getLexicalDeclContext()->isRecord())) {
3472 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3473 Diag(OldLocation, PrevDiag);
3474 return New->setInvalidDecl();
3477 if (New->getTLSKind() != Old->getTLSKind()) {
3478 if (!Old->getTLSKind()) {
3479 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3480 Diag(OldLocation, PrevDiag);
3481 } else if (!New->getTLSKind()) {
3482 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3483 Diag(OldLocation, PrevDiag);
3485 // Do not allow redeclaration to change the variable between requiring
3486 // static and dynamic initialization.
3487 // FIXME: GCC allows this, but uses the TLS keyword on the first
3488 // declaration to determine the kind. Do we need to be compatible here?
3489 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3490 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3491 Diag(OldLocation, PrevDiag);
3495 // C++ doesn't have tentative definitions, so go right ahead and check here.
3497 if (getLangOpts().CPlusPlus &&
3498 New->isThisDeclarationADefinition() == VarDecl::Definition &&
3499 (Def = Old->getDefinition())) {
3500 NamedDecl *Hidden = nullptr;
3501 if (!hasVisibleDefinition(Def, &Hidden) &&
3502 (New->getFormalLinkage() == InternalLinkage ||
3503 New->getDescribedVarTemplate() ||
3504 New->getNumTemplateParameterLists() ||
3505 New->getDeclContext()->isDependentContext())) {
3506 // The previous definition is hidden, and multiple definitions are
3507 // permitted (in separate TUs). Form another definition of it.
3509 Diag(New->getLocation(), diag::err_redefinition) << New;
3510 Diag(Def->getLocation(), diag::note_previous_definition);
3511 New->setInvalidDecl();
3516 if (haveIncompatibleLanguageLinkages(Old, New)) {
3517 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3518 Diag(OldLocation, PrevDiag);
3519 New->setInvalidDecl();
3523 // Merge "used" flag.
3524 if (Old->getMostRecentDecl()->isUsed(false))
3527 // Keep a chain of previous declarations.
3528 New->setPreviousDecl(Old);
3530 NewTemplate->setPreviousDecl(OldTemplate);
3532 // Inherit access appropriately.
3533 New->setAccess(Old->getAccess());
3535 NewTemplate->setAccess(New->getAccess());
3538 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3539 /// no declarator (e.g. "struct foo;") is parsed.
3540 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3542 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3545 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3546 // disambiguate entities defined in different scopes.
3547 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3549 // We will pick our mangling number depending on which version of MSVC is being
3551 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3552 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3553 ? S->getMSCurManglingNumber()
3554 : S->getMSLastManglingNumber();
3557 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3558 if (!Context.getLangOpts().CPlusPlus)
3561 if (isa<CXXRecordDecl>(Tag->getParent())) {
3562 // If this tag is the direct child of a class, number it if
3564 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3566 MangleNumberingContext &MCtx =
3567 Context.getManglingNumberContext(Tag->getParent());
3568 Context.setManglingNumber(
3569 Tag, MCtx.getManglingNumber(
3570 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3574 // If this tag isn't a direct child of a class, number it if it is local.
3575 Decl *ManglingContextDecl;
3576 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3577 Tag->getDeclContext(), ManglingContextDecl)) {
3578 Context.setManglingNumber(
3579 Tag, MCtx->getManglingNumber(
3580 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3584 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3585 TypedefNameDecl *NewTD) {
3586 // Do nothing if the tag is not anonymous or already has an
3587 // associated typedef (from an earlier typedef in this decl group).
3588 if (TagFromDeclSpec->getIdentifier())
3590 if (TagFromDeclSpec->getTypedefNameForAnonDecl())
3593 // A well-formed anonymous tag must always be a TUK_Definition.
3594 assert(TagFromDeclSpec->isThisDeclarationADefinition());
3596 // The type must match the tag exactly; no qualifiers allowed.
3597 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3598 Context.getTagDeclType(TagFromDeclSpec)))
3601 // If we've already computed linkage for the anonymous tag, then
3602 // adding a typedef name for the anonymous decl can change that
3603 // linkage, which might be a serious problem. Diagnose this as
3604 // unsupported and ignore the typedef name. TODO: we should
3605 // pursue this as a language defect and establish a formal rule
3606 // for how to handle it.
3607 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3608 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3610 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3611 tagLoc = getLocForEndOfToken(tagLoc);
3613 llvm::SmallString<40> textToInsert;
3614 textToInsert += ' ';
3615 textToInsert += NewTD->getIdentifier()->getName();
3616 Diag(tagLoc, diag::note_typedef_changes_linkage)
3617 << FixItHint::CreateInsertion(tagLoc, textToInsert);
3621 // Otherwise, set this is the anon-decl typedef for the tag.
3622 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3625 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3627 case DeclSpec::TST_class:
3629 case DeclSpec::TST_struct:
3631 case DeclSpec::TST_interface:
3633 case DeclSpec::TST_union:
3635 case DeclSpec::TST_enum:
3638 llvm_unreachable("unexpected type specifier");
3642 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3643 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3644 /// parameters to cope with template friend declarations.
3645 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3647 MultiTemplateParamsArg TemplateParams,
3648 bool IsExplicitInstantiation) {
3649 Decl *TagD = nullptr;
3650 TagDecl *Tag = nullptr;
3651 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3652 DS.getTypeSpecType() == DeclSpec::TST_struct ||
3653 DS.getTypeSpecType() == DeclSpec::TST_interface ||
3654 DS.getTypeSpecType() == DeclSpec::TST_union ||
3655 DS.getTypeSpecType() == DeclSpec::TST_enum) {
3656 TagD = DS.getRepAsDecl();
3658 if (!TagD) // We probably had an error
3661 // Note that the above type specs guarantee that the
3662 // type rep is a Decl, whereas in many of the others
3664 if (isa<TagDecl>(TagD))
3665 Tag = cast<TagDecl>(TagD);
3666 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3667 Tag = CTD->getTemplatedDecl();
3671 handleTagNumbering(Tag, S);
3672 Tag->setFreeStanding();
3673 if (Tag->isInvalidDecl())
3677 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3678 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3679 // or incomplete types shall not be restrict-qualified."
3680 if (TypeQuals & DeclSpec::TQ_restrict)
3681 Diag(DS.getRestrictSpecLoc(),
3682 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3683 << DS.getSourceRange();
3686 if (DS.isConstexprSpecified()) {
3687 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3688 // and definitions of functions and variables.
3690 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3691 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3693 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3694 // Don't emit warnings after this error.
3698 DiagnoseFunctionSpecifiers(DS);
3700 if (DS.isFriendSpecified()) {
3701 // If we're dealing with a decl but not a TagDecl, assume that
3702 // whatever routines created it handled the friendship aspect.
3705 return ActOnFriendTypeDecl(S, DS, TemplateParams);
3708 const CXXScopeSpec &SS = DS.getTypeSpecScope();
3709 bool IsExplicitSpecialization =
3710 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3711 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3712 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3713 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3714 // nested-name-specifier unless it is an explicit instantiation
3715 // or an explicit specialization.
3716 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3717 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3718 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3722 // Track whether this decl-specifier declares anything.
3723 bool DeclaresAnything = true;
3725 // Handle anonymous struct definitions.
3726 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3727 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3728 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3729 if (getLangOpts().CPlusPlus ||
3730 Record->getDeclContext()->isRecord())
3731 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3732 Context.getPrintingPolicy());
3734 DeclaresAnything = false;
3739 // A struct-declaration that does not declare an anonymous structure or
3740 // anonymous union shall contain a struct-declarator-list.
3742 // This rule also existed in C89 and C99; the grammar for struct-declaration
3743 // did not permit a struct-declaration without a struct-declarator-list.
3744 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3745 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3746 // Check for Microsoft C extension: anonymous struct/union member.
3747 // Handle 2 kinds of anonymous struct/union:
3751 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3752 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3753 if ((Tag && Tag->getDeclName()) ||
3754 DS.getTypeSpecType() == DeclSpec::TST_typename) {
3755 RecordDecl *Record = nullptr;
3757 Record = dyn_cast<RecordDecl>(Tag);
3758 else if (const RecordType *RT =
3759 DS.getRepAsType().get()->getAsStructureType())
3760 Record = RT->getDecl();
3761 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3762 Record = UT->getDecl();
3764 if (Record && getLangOpts().MicrosoftExt) {
3765 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3766 << Record->isUnion() << DS.getSourceRange();
3767 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3770 DeclaresAnything = false;
3774 // Skip all the checks below if we have a type error.
3775 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3776 (TagD && TagD->isInvalidDecl()))
3779 if (getLangOpts().CPlusPlus &&
3780 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3781 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3782 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3783 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3784 DeclaresAnything = false;
3786 if (!DS.isMissingDeclaratorOk()) {
3787 // Customize diagnostic for a typedef missing a name.
3788 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3789 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3790 << DS.getSourceRange();
3792 DeclaresAnything = false;
3795 if (DS.isModulePrivateSpecified() &&
3796 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3797 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3798 << Tag->getTagKind()
3799 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3801 ActOnDocumentableDecl(TagD);
3804 // A declaration [...] shall declare at least a declarator [...], a tag,
3805 // or the members of an enumeration.
3807 // [If there are no declarators], and except for the declaration of an
3808 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3809 // names into the program, or shall redeclare a name introduced by a
3810 // previous declaration.
3811 if (!DeclaresAnything) {
3812 // In C, we allow this as a (popular) extension / bug. Don't bother
3813 // producing further diagnostics for redundant qualifiers after this.
3814 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3819 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3820 // init-declarator-list of the declaration shall not be empty.
3821 // C++ [dcl.fct.spec]p1:
3822 // If a cv-qualifier appears in a decl-specifier-seq, the
3823 // init-declarator-list of the declaration shall not be empty.
3825 // Spurious qualifiers here appear to be valid in C.
3826 unsigned DiagID = diag::warn_standalone_specifier;
3827 if (getLangOpts().CPlusPlus)
3828 DiagID = diag::ext_standalone_specifier;
3830 // Note that a linkage-specification sets a storage class, but
3831 // 'extern "C" struct foo;' is actually valid and not theoretically
3833 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3834 if (SCS == DeclSpec::SCS_mutable)
3835 // Since mutable is not a viable storage class specifier in C, there is
3836 // no reason to treat it as an extension. Instead, diagnose as an error.
3837 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3838 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3839 Diag(DS.getStorageClassSpecLoc(), DiagID)
3840 << DeclSpec::getSpecifierName(SCS);
3843 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3844 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3845 << DeclSpec::getSpecifierName(TSCS);
3846 if (DS.getTypeQualifiers()) {
3847 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3848 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3849 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3850 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3851 // Restrict is covered above.
3852 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3853 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3856 // Warn about ignored type attributes, for example:
3857 // __attribute__((aligned)) struct A;
3858 // Attributes should be placed after tag to apply to type declaration.
3859 if (!DS.getAttributes().empty()) {
3860 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3861 if (TypeSpecType == DeclSpec::TST_class ||
3862 TypeSpecType == DeclSpec::TST_struct ||
3863 TypeSpecType == DeclSpec::TST_interface ||
3864 TypeSpecType == DeclSpec::TST_union ||
3865 TypeSpecType == DeclSpec::TST_enum) {
3866 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3867 attrs = attrs->getNext())
3868 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3869 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3876 /// We are trying to inject an anonymous member into the given scope;
3877 /// check if there's an existing declaration that can't be overloaded.
3879 /// \return true if this is a forbidden redeclaration
3880 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3883 DeclarationName Name,
3884 SourceLocation NameLoc,
3885 unsigned diagnostic) {
3886 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3887 Sema::ForRedeclaration);
3888 if (!SemaRef.LookupName(R, S)) return false;
3890 if (R.getAsSingle<TagDecl>())
3893 // Pick a representative declaration.
3894 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3895 assert(PrevDecl && "Expected a non-null Decl");
3897 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3900 SemaRef.Diag(NameLoc, diagnostic) << Name;
3901 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3906 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3907 /// anonymous struct or union AnonRecord into the owning context Owner
3908 /// and scope S. This routine will be invoked just after we realize
3909 /// that an unnamed union or struct is actually an anonymous union or
3916 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3917 /// // f into the surrounding scope.x
3920 /// This routine is recursive, injecting the names of nested anonymous
3921 /// structs/unions into the owning context and scope as well.
3922 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3924 RecordDecl *AnonRecord,
3926 SmallVectorImpl<NamedDecl *> &Chaining,
3927 bool MSAnonStruct) {
3929 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3930 : diag::err_anonymous_struct_member_redecl;
3932 bool Invalid = false;
3934 // Look every FieldDecl and IndirectFieldDecl with a name.
3935 for (auto *D : AnonRecord->decls()) {
3936 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3937 cast<NamedDecl>(D)->getDeclName()) {
3938 ValueDecl *VD = cast<ValueDecl>(D);
3939 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3940 VD->getLocation(), diagKind)) {
3941 // C++ [class.union]p2:
3942 // The names of the members of an anonymous union shall be
3943 // distinct from the names of any other entity in the
3944 // scope in which the anonymous union is declared.
3947 // C++ [class.union]p2:
3948 // For the purpose of name lookup, after the anonymous union
3949 // definition, the members of the anonymous union are
3950 // considered to have been defined in the scope in which the
3951 // anonymous union is declared.
3952 unsigned OldChainingSize = Chaining.size();
3953 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3954 Chaining.append(IF->chain_begin(), IF->chain_end());
3956 Chaining.push_back(VD);
3958 assert(Chaining.size() >= 2);
3959 NamedDecl **NamedChain =
3960 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3961 for (unsigned i = 0; i < Chaining.size(); i++)
3962 NamedChain[i] = Chaining[i];
3964 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
3965 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3966 VD->getType(), NamedChain, Chaining.size());
3968 for (const auto *Attr : VD->attrs())
3969 IndirectField->addAttr(Attr->clone(SemaRef.Context));
3971 IndirectField->setAccess(AS);
3972 IndirectField->setImplicit();
3973 SemaRef.PushOnScopeChains(IndirectField, S);
3975 // That includes picking up the appropriate access specifier.
3976 if (AS != AS_none) IndirectField->setAccess(AS);
3978 Chaining.resize(OldChainingSize);
3986 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3987 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3988 /// illegal input values are mapped to SC_None.
3990 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3991 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3992 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3993 "Parser allowed 'typedef' as storage class VarDecl.");
3994 switch (StorageClassSpec) {
3995 case DeclSpec::SCS_unspecified: return SC_None;
3996 case DeclSpec::SCS_extern:
3997 if (DS.isExternInLinkageSpec())
4000 case DeclSpec::SCS_static: return SC_Static;
4001 case DeclSpec::SCS_auto: return SC_Auto;
4002 case DeclSpec::SCS_register: return SC_Register;
4003 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4004 // Illegal SCSs map to None: error reporting is up to the caller.
4005 case DeclSpec::SCS_mutable: // Fall through.
4006 case DeclSpec::SCS_typedef: return SC_None;
4008 llvm_unreachable("unknown storage class specifier");
4011 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4012 assert(Record->hasInClassInitializer());
4014 for (const auto *I : Record->decls()) {
4015 const auto *FD = dyn_cast<FieldDecl>(I);
4016 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4017 FD = IFD->getAnonField();
4018 if (FD && FD->hasInClassInitializer())
4019 return FD->getLocation();
4022 llvm_unreachable("couldn't find in-class initializer");
4025 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4026 SourceLocation DefaultInitLoc) {
4027 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4030 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4031 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4034 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4035 CXXRecordDecl *AnonUnion) {
4036 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4039 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4042 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4043 /// anonymous structure or union. Anonymous unions are a C++ feature
4044 /// (C++ [class.union]) and a C11 feature; anonymous structures
4045 /// are a C11 feature and GNU C++ extension.
4046 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4049 const PrintingPolicy &Policy) {
4050 DeclContext *Owner = Record->getDeclContext();
4052 // Diagnose whether this anonymous struct/union is an extension.
4053 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4054 Diag(Record->getLocation(), diag::ext_anonymous_union);
4055 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4056 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4057 else if (!Record->isUnion() && !getLangOpts().C11)
4058 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4060 // C and C++ require different kinds of checks for anonymous
4062 bool Invalid = false;
4063 if (getLangOpts().CPlusPlus) {
4064 const char *PrevSpec = nullptr;
4066 if (Record->isUnion()) {
4067 // C++ [class.union]p6:
4068 // Anonymous unions declared in a named namespace or in the
4069 // global namespace shall be declared static.
4070 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4071 (isa<TranslationUnitDecl>(Owner) ||
4072 (isa<NamespaceDecl>(Owner) &&
4073 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4074 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4075 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4077 // Recover by adding 'static'.
4078 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4079 PrevSpec, DiagID, Policy);
4081 // C++ [class.union]p6:
4082 // A storage class is not allowed in a declaration of an
4083 // anonymous union in a class scope.
4084 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4085 isa<RecordDecl>(Owner)) {
4086 Diag(DS.getStorageClassSpecLoc(),
4087 diag::err_anonymous_union_with_storage_spec)
4088 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4090 // Recover by removing the storage specifier.
4091 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4093 PrevSpec, DiagID, Context.getPrintingPolicy());
4097 // Ignore const/volatile/restrict qualifiers.
4098 if (DS.getTypeQualifiers()) {
4099 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4100 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4101 << Record->isUnion() << "const"
4102 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4103 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4104 Diag(DS.getVolatileSpecLoc(),
4105 diag::ext_anonymous_struct_union_qualified)
4106 << Record->isUnion() << "volatile"
4107 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4108 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4109 Diag(DS.getRestrictSpecLoc(),
4110 diag::ext_anonymous_struct_union_qualified)
4111 << Record->isUnion() << "restrict"
4112 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4113 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4114 Diag(DS.getAtomicSpecLoc(),
4115 diag::ext_anonymous_struct_union_qualified)
4116 << Record->isUnion() << "_Atomic"
4117 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4119 DS.ClearTypeQualifiers();
4122 // C++ [class.union]p2:
4123 // The member-specification of an anonymous union shall only
4124 // define non-static data members. [Note: nested types and
4125 // functions cannot be declared within an anonymous union. ]
4126 for (auto *Mem : Record->decls()) {
4127 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4128 // C++ [class.union]p3:
4129 // An anonymous union shall not have private or protected
4130 // members (clause 11).
4131 assert(FD->getAccess() != AS_none);
4132 if (FD->getAccess() != AS_public) {
4133 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4134 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
4138 // C++ [class.union]p1
4139 // An object of a class with a non-trivial constructor, a non-trivial
4140 // copy constructor, a non-trivial destructor, or a non-trivial copy
4141 // assignment operator cannot be a member of a union, nor can an
4142 // array of such objects.
4143 if (CheckNontrivialField(FD))
4145 } else if (Mem->isImplicit()) {
4146 // Any implicit members are fine.
4147 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4148 // This is a type that showed up in an
4149 // elaborated-type-specifier inside the anonymous struct or
4150 // union, but which actually declares a type outside of the
4151 // anonymous struct or union. It's okay.
4152 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4153 if (!MemRecord->isAnonymousStructOrUnion() &&
4154 MemRecord->getDeclName()) {
4155 // Visual C++ allows type definition in anonymous struct or union.
4156 if (getLangOpts().MicrosoftExt)
4157 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4158 << (int)Record->isUnion();
4160 // This is a nested type declaration.
4161 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4162 << (int)Record->isUnion();
4166 // This is an anonymous type definition within another anonymous type.
4167 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4168 // not part of standard C++.
4169 Diag(MemRecord->getLocation(),
4170 diag::ext_anonymous_record_with_anonymous_type)
4171 << (int)Record->isUnion();
4173 } else if (isa<AccessSpecDecl>(Mem)) {
4174 // Any access specifier is fine.
4175 } else if (isa<StaticAssertDecl>(Mem)) {
4176 // In C++1z, static_assert declarations are also fine.
4178 // We have something that isn't a non-static data
4179 // member. Complain about it.
4180 unsigned DK = diag::err_anonymous_record_bad_member;
4181 if (isa<TypeDecl>(Mem))
4182 DK = diag::err_anonymous_record_with_type;
4183 else if (isa<FunctionDecl>(Mem))
4184 DK = diag::err_anonymous_record_with_function;
4185 else if (isa<VarDecl>(Mem))
4186 DK = diag::err_anonymous_record_with_static;
4188 // Visual C++ allows type definition in anonymous struct or union.
4189 if (getLangOpts().MicrosoftExt &&
4190 DK == diag::err_anonymous_record_with_type)
4191 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4192 << (int)Record->isUnion();
4194 Diag(Mem->getLocation(), DK)
4195 << (int)Record->isUnion();
4201 // C++11 [class.union]p8 (DR1460):
4202 // At most one variant member of a union may have a
4203 // brace-or-equal-initializer.
4204 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4206 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4207 cast<CXXRecordDecl>(Record));
4210 if (!Record->isUnion() && !Owner->isRecord()) {
4211 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4212 << (int)getLangOpts().CPlusPlus;
4216 // Mock up a declarator.
4217 Declarator Dc(DS, Declarator::MemberContext);
4218 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4219 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4221 // Create a declaration for this anonymous struct/union.
4222 NamedDecl *Anon = nullptr;
4223 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4224 Anon = FieldDecl::Create(Context, OwningClass,
4226 Record->getLocation(),
4227 /*IdentifierInfo=*/nullptr,
4228 Context.getTypeDeclType(Record),
4230 /*BitWidth=*/nullptr, /*Mutable=*/false,
4231 /*InitStyle=*/ICIS_NoInit);
4232 Anon->setAccess(AS);
4233 if (getLangOpts().CPlusPlus)
4234 FieldCollector->Add(cast<FieldDecl>(Anon));
4236 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4237 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4238 if (SCSpec == DeclSpec::SCS_mutable) {
4239 // mutable can only appear on non-static class members, so it's always
4241 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4246 Anon = VarDecl::Create(Context, Owner,
4248 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4249 Context.getTypeDeclType(Record),
4252 // Default-initialize the implicit variable. This initialization will be
4253 // trivial in almost all cases, except if a union member has an in-class
4255 // union { int n = 0; };
4256 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4258 Anon->setImplicit();
4260 // Mark this as an anonymous struct/union type.
4261 Record->setAnonymousStructOrUnion(true);
4263 // Add the anonymous struct/union object to the current
4264 // context. We'll be referencing this object when we refer to one of
4266 Owner->addDecl(Anon);
4268 // Inject the members of the anonymous struct/union into the owning
4269 // context and into the identifier resolver chain for name lookup
4271 SmallVector<NamedDecl*, 2> Chain;
4272 Chain.push_back(Anon);
4274 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4278 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4279 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4280 Decl *ManglingContextDecl;
4281 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4282 NewVD->getDeclContext(), ManglingContextDecl)) {
4283 Context.setManglingNumber(
4284 NewVD, MCtx->getManglingNumber(
4285 NewVD, getMSManglingNumber(getLangOpts(), S)));
4286 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4292 Anon->setInvalidDecl();
4297 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4298 /// Microsoft C anonymous structure.
4299 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4302 /// struct A { int a; };
4303 /// struct B { struct A; int b; };
4310 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4311 RecordDecl *Record) {
4312 assert(Record && "expected a record!");
4314 // Mock up a declarator.
4315 Declarator Dc(DS, Declarator::TypeNameContext);
4316 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4317 assert(TInfo && "couldn't build declarator info for anonymous struct");
4319 auto *ParentDecl = cast<RecordDecl>(CurContext);
4320 QualType RecTy = Context.getTypeDeclType(Record);
4322 // Create a declaration for this anonymous struct.
4323 NamedDecl *Anon = FieldDecl::Create(Context,
4327 /*IdentifierInfo=*/nullptr,
4330 /*BitWidth=*/nullptr, /*Mutable=*/false,
4331 /*InitStyle=*/ICIS_NoInit);
4332 Anon->setImplicit();
4334 // Add the anonymous struct object to the current context.
4335 CurContext->addDecl(Anon);
4337 // Inject the members of the anonymous struct into the current
4338 // context and into the identifier resolver chain for name lookup
4340 SmallVector<NamedDecl*, 2> Chain;
4341 Chain.push_back(Anon);
4343 RecordDecl *RecordDef = Record->getDefinition();
4344 if (RequireCompleteType(Anon->getLocation(), RecTy,
4345 diag::err_field_incomplete) ||
4346 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4347 AS_none, Chain, true)) {
4348 Anon->setInvalidDecl();
4349 ParentDecl->setInvalidDecl();
4355 /// GetNameForDeclarator - Determine the full declaration name for the
4356 /// given Declarator.
4357 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4358 return GetNameFromUnqualifiedId(D.getName());
4361 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4363 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4364 DeclarationNameInfo NameInfo;
4365 NameInfo.setLoc(Name.StartLocation);
4367 switch (Name.getKind()) {
4369 case UnqualifiedId::IK_ImplicitSelfParam:
4370 case UnqualifiedId::IK_Identifier:
4371 NameInfo.setName(Name.Identifier);
4372 NameInfo.setLoc(Name.StartLocation);
4375 case UnqualifiedId::IK_OperatorFunctionId:
4376 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4377 Name.OperatorFunctionId.Operator));
4378 NameInfo.setLoc(Name.StartLocation);
4379 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4380 = Name.OperatorFunctionId.SymbolLocations[0];
4381 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4382 = Name.EndLocation.getRawEncoding();
4385 case UnqualifiedId::IK_LiteralOperatorId:
4386 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4388 NameInfo.setLoc(Name.StartLocation);
4389 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4392 case UnqualifiedId::IK_ConversionFunctionId: {
4393 TypeSourceInfo *TInfo;
4394 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4396 return DeclarationNameInfo();
4397 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4398 Context.getCanonicalType(Ty)));
4399 NameInfo.setLoc(Name.StartLocation);
4400 NameInfo.setNamedTypeInfo(TInfo);
4404 case UnqualifiedId::IK_ConstructorName: {
4405 TypeSourceInfo *TInfo;
4406 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4408 return DeclarationNameInfo();
4409 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4410 Context.getCanonicalType(Ty)));
4411 NameInfo.setLoc(Name.StartLocation);
4412 NameInfo.setNamedTypeInfo(TInfo);
4416 case UnqualifiedId::IK_ConstructorTemplateId: {
4417 // In well-formed code, we can only have a constructor
4418 // template-id that refers to the current context, so go there
4419 // to find the actual type being constructed.
4420 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4421 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4422 return DeclarationNameInfo();
4424 // Determine the type of the class being constructed.
4425 QualType CurClassType = Context.getTypeDeclType(CurClass);
4427 // FIXME: Check two things: that the template-id names the same type as
4428 // CurClassType, and that the template-id does not occur when the name
4431 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4432 Context.getCanonicalType(CurClassType)));
4433 NameInfo.setLoc(Name.StartLocation);
4434 // FIXME: should we retrieve TypeSourceInfo?
4435 NameInfo.setNamedTypeInfo(nullptr);
4439 case UnqualifiedId::IK_DestructorName: {
4440 TypeSourceInfo *TInfo;
4441 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4443 return DeclarationNameInfo();
4444 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4445 Context.getCanonicalType(Ty)));
4446 NameInfo.setLoc(Name.StartLocation);
4447 NameInfo.setNamedTypeInfo(TInfo);
4451 case UnqualifiedId::IK_TemplateId: {
4452 TemplateName TName = Name.TemplateId->Template.get();
4453 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4454 return Context.getNameForTemplate(TName, TNameLoc);
4457 } // switch (Name.getKind())
4459 llvm_unreachable("Unknown name kind");
4462 static QualType getCoreType(QualType Ty) {
4464 if (Ty->isPointerType() || Ty->isReferenceType())
4465 Ty = Ty->getPointeeType();
4466 else if (Ty->isArrayType())
4467 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4469 return Ty.withoutLocalFastQualifiers();
4473 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4474 /// and Definition have "nearly" matching parameters. This heuristic is
4475 /// used to improve diagnostics in the case where an out-of-line function
4476 /// definition doesn't match any declaration within the class or namespace.
4477 /// Also sets Params to the list of indices to the parameters that differ
4478 /// between the declaration and the definition. If hasSimilarParameters
4479 /// returns true and Params is empty, then all of the parameters match.
4480 static bool hasSimilarParameters(ASTContext &Context,
4481 FunctionDecl *Declaration,
4482 FunctionDecl *Definition,
4483 SmallVectorImpl<unsigned> &Params) {
4485 if (Declaration->param_size() != Definition->param_size())
4487 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4488 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4489 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4491 // The parameter types are identical
4492 if (Context.hasSameType(DefParamTy, DeclParamTy))
4495 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4496 QualType DefParamBaseTy = getCoreType(DefParamTy);
4497 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4498 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4500 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4501 (DeclTyName && DeclTyName == DefTyName))
4502 Params.push_back(Idx);
4503 else // The two parameters aren't even close
4510 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4511 /// declarator needs to be rebuilt in the current instantiation.
4512 /// Any bits of declarator which appear before the name are valid for
4513 /// consideration here. That's specifically the type in the decl spec
4514 /// and the base type in any member-pointer chunks.
4515 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4516 DeclarationName Name) {
4517 // The types we specifically need to rebuild are:
4518 // - typenames, typeofs, and decltypes
4519 // - types which will become injected class names
4520 // Of course, we also need to rebuild any type referencing such a
4521 // type. It's safest to just say "dependent", but we call out a
4524 DeclSpec &DS = D.getMutableDeclSpec();
4525 switch (DS.getTypeSpecType()) {
4526 case DeclSpec::TST_typename:
4527 case DeclSpec::TST_typeofType:
4528 case DeclSpec::TST_underlyingType:
4529 case DeclSpec::TST_atomic: {
4530 // Grab the type from the parser.
4531 TypeSourceInfo *TSI = nullptr;
4532 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4533 if (T.isNull() || !T->isDependentType()) break;
4535 // Make sure there's a type source info. This isn't really much
4536 // of a waste; most dependent types should have type source info
4537 // attached already.
4539 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4541 // Rebuild the type in the current instantiation.
4542 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4543 if (!TSI) return true;
4545 // Store the new type back in the decl spec.
4546 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4547 DS.UpdateTypeRep(LocType);
4551 case DeclSpec::TST_decltype:
4552 case DeclSpec::TST_typeofExpr: {
4553 Expr *E = DS.getRepAsExpr();
4554 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4555 if (Result.isInvalid()) return true;
4556 DS.UpdateExprRep(Result.get());
4561 // Nothing to do for these decl specs.
4565 // It doesn't matter what order we do this in.
4566 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4567 DeclaratorChunk &Chunk = D.getTypeObject(I);
4569 // The only type information in the declarator which can come
4570 // before the declaration name is the base type of a member
4572 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4575 // Rebuild the scope specifier in-place.
4576 CXXScopeSpec &SS = Chunk.Mem.Scope();
4577 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4584 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4585 D.setFunctionDefinitionKind(FDK_Declaration);
4586 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4588 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4589 Dcl && Dcl->getDeclContext()->isFileContext())
4590 Dcl->setTopLevelDeclInObjCContainer();
4595 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4596 /// If T is the name of a class, then each of the following shall have a
4597 /// name different from T:
4598 /// - every static data member of class T;
4599 /// - every member function of class T
4600 /// - every member of class T that is itself a type;
4601 /// \returns true if the declaration name violates these rules.
4602 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4603 DeclarationNameInfo NameInfo) {
4604 DeclarationName Name = NameInfo.getName();
4606 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4607 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4608 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4615 /// \brief Diagnose a declaration whose declarator-id has the given
4616 /// nested-name-specifier.
4618 /// \param SS The nested-name-specifier of the declarator-id.
4620 /// \param DC The declaration context to which the nested-name-specifier
4623 /// \param Name The name of the entity being declared.
4625 /// \param Loc The location of the name of the entity being declared.
4627 /// \returns true if we cannot safely recover from this error, false otherwise.
4628 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4629 DeclarationName Name,
4630 SourceLocation Loc) {
4631 DeclContext *Cur = CurContext;
4632 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4633 Cur = Cur->getParent();
4635 // If the user provided a superfluous scope specifier that refers back to the
4636 // class in which the entity is already declared, diagnose and ignore it.
4642 // Note, it was once ill-formed to give redundant qualification in all
4643 // contexts, but that rule was removed by DR482.
4644 if (Cur->Equals(DC)) {
4645 if (Cur->isRecord()) {
4646 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4647 : diag::err_member_extra_qualification)
4648 << Name << FixItHint::CreateRemoval(SS.getRange());
4651 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4656 // Check whether the qualifying scope encloses the scope of the original
4658 if (!Cur->Encloses(DC)) {
4659 if (Cur->isRecord())
4660 Diag(Loc, diag::err_member_qualification)
4661 << Name << SS.getRange();
4662 else if (isa<TranslationUnitDecl>(DC))
4663 Diag(Loc, diag::err_invalid_declarator_global_scope)
4664 << Name << SS.getRange();
4665 else if (isa<FunctionDecl>(Cur))
4666 Diag(Loc, diag::err_invalid_declarator_in_function)
4667 << Name << SS.getRange();
4668 else if (isa<BlockDecl>(Cur))
4669 Diag(Loc, diag::err_invalid_declarator_in_block)
4670 << Name << SS.getRange();
4672 Diag(Loc, diag::err_invalid_declarator_scope)
4673 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4678 if (Cur->isRecord()) {
4679 // Cannot qualify members within a class.
4680 Diag(Loc, diag::err_member_qualification)
4681 << Name << SS.getRange();
4684 // C++ constructors and destructors with incorrect scopes can break
4685 // our AST invariants by having the wrong underlying types. If
4686 // that's the case, then drop this declaration entirely.
4687 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4688 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4689 !Context.hasSameType(Name.getCXXNameType(),
4690 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4696 // C++11 [dcl.meaning]p1:
4697 // [...] "The nested-name-specifier of the qualified declarator-id shall
4698 // not begin with a decltype-specifer"
4699 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4700 while (SpecLoc.getPrefix())
4701 SpecLoc = SpecLoc.getPrefix();
4702 if (dyn_cast_or_null<DecltypeType>(
4703 SpecLoc.getNestedNameSpecifier()->getAsType()))
4704 Diag(Loc, diag::err_decltype_in_declarator)
4705 << SpecLoc.getTypeLoc().getSourceRange();
4710 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4711 MultiTemplateParamsArg TemplateParamLists) {
4712 // TODO: consider using NameInfo for diagnostic.
4713 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4714 DeclarationName Name = NameInfo.getName();
4716 // All of these full declarators require an identifier. If it doesn't have
4717 // one, the ParsedFreeStandingDeclSpec action should be used.
4719 if (!D.isInvalidType()) // Reject this if we think it is valid.
4720 Diag(D.getDeclSpec().getLocStart(),
4721 diag::err_declarator_need_ident)
4722 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4724 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4727 // The scope passed in may not be a decl scope. Zip up the scope tree until
4728 // we find one that is.
4729 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4730 (S->getFlags() & Scope::TemplateParamScope) != 0)
4733 DeclContext *DC = CurContext;
4734 if (D.getCXXScopeSpec().isInvalid())
4736 else if (D.getCXXScopeSpec().isSet()) {
4737 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4738 UPPC_DeclarationQualifier))
4741 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4742 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4743 if (!DC || isa<EnumDecl>(DC)) {
4744 // If we could not compute the declaration context, it's because the
4745 // declaration context is dependent but does not refer to a class,
4746 // class template, or class template partial specialization. Complain
4747 // and return early, to avoid the coming semantic disaster.
4748 Diag(D.getIdentifierLoc(),
4749 diag::err_template_qualified_declarator_no_match)
4750 << D.getCXXScopeSpec().getScopeRep()
4751 << D.getCXXScopeSpec().getRange();
4754 bool IsDependentContext = DC->isDependentContext();
4756 if (!IsDependentContext &&
4757 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4760 // If a class is incomplete, do not parse entities inside it.
4761 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4762 Diag(D.getIdentifierLoc(),
4763 diag::err_member_def_undefined_record)
4764 << Name << DC << D.getCXXScopeSpec().getRange();
4767 if (!D.getDeclSpec().isFriendSpecified()) {
4768 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4769 Name, D.getIdentifierLoc())) {
4777 // Check whether we need to rebuild the type of the given
4778 // declaration in the current instantiation.
4779 if (EnteringContext && IsDependentContext &&
4780 TemplateParamLists.size() != 0) {
4781 ContextRAII SavedContext(*this, DC);
4782 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4787 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4788 QualType R = TInfo->getType();
4790 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4791 // If this is a typedef, we'll end up spewing multiple diagnostics.
4792 // Just return early; it's safer. If this is a function, let the
4793 // "constructor cannot have a return type" diagnostic handle it.
4794 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4797 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4798 UPPC_DeclarationType))
4801 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4804 // See if this is a redefinition of a variable in the same scope.
4805 if (!D.getCXXScopeSpec().isSet()) {
4806 bool IsLinkageLookup = false;
4807 bool CreateBuiltins = false;
4809 // If the declaration we're planning to build will be a function
4810 // or object with linkage, then look for another declaration with
4811 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4813 // If the declaration we're planning to build will be declared with
4814 // external linkage in the translation unit, create any builtin with
4816 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4818 else if (CurContext->isFunctionOrMethod() &&
4819 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4820 R->isFunctionType())) {
4821 IsLinkageLookup = true;
4823 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4824 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4825 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4826 CreateBuiltins = true;
4828 if (IsLinkageLookup)
4829 Previous.clear(LookupRedeclarationWithLinkage);
4831 LookupName(Previous, S, CreateBuiltins);
4832 } else { // Something like "int foo::x;"
4833 LookupQualifiedName(Previous, DC);
4835 // C++ [dcl.meaning]p1:
4836 // When the declarator-id is qualified, the declaration shall refer to a
4837 // previously declared member of the class or namespace to which the
4838 // qualifier refers (or, in the case of a namespace, of an element of the
4839 // inline namespace set of that namespace (7.3.1)) or to a specialization
4842 // Note that we already checked the context above, and that we do not have
4843 // enough information to make sure that Previous contains the declaration
4844 // we want to match. For example, given:
4851 // void X::f(int) { } // ill-formed
4853 // In this case, Previous will point to the overload set
4854 // containing the two f's declared in X, but neither of them
4857 // C++ [dcl.meaning]p1:
4858 // [...] the member shall not merely have been introduced by a
4859 // using-declaration in the scope of the class or namespace nominated by
4860 // the nested-name-specifier of the declarator-id.
4861 RemoveUsingDecls(Previous);
4864 if (Previous.isSingleResult() &&
4865 Previous.getFoundDecl()->isTemplateParameter()) {
4866 // Maybe we will complain about the shadowed template parameter.
4867 if (!D.isInvalidType())
4868 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4869 Previous.getFoundDecl());
4871 // Just pretend that we didn't see the previous declaration.
4875 // In C++, the previous declaration we find might be a tag type
4876 // (class or enum). In this case, the new declaration will hide the
4877 // tag type. Note that this does does not apply if we're declaring a
4878 // typedef (C++ [dcl.typedef]p4).
4879 if (Previous.isSingleTagDecl() &&
4880 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4883 // Check that there are no default arguments other than in the parameters
4884 // of a function declaration (C++ only).
4885 if (getLangOpts().CPlusPlus)
4886 CheckExtraCXXDefaultArguments(D);
4890 bool AddToScope = true;
4891 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4892 if (TemplateParamLists.size()) {
4893 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4897 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4898 } else if (R->isFunctionType()) {
4899 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4903 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4910 // If this has an identifier and is not an invalid redeclaration or
4911 // function template specialization, add it to the scope stack.
4912 if (New->getDeclName() && AddToScope &&
4913 !(D.isRedeclaration() && New->isInvalidDecl())) {
4914 // Only make a locally-scoped extern declaration visible if it is the first
4915 // declaration of this entity. Qualified lookup for such an entity should
4916 // only find this declaration if there is no visible declaration of it.
4917 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4918 PushOnScopeChains(New, S, AddToContext);
4920 CurContext->addHiddenDecl(New);
4926 /// Helper method to turn variable array types into constant array
4927 /// types in certain situations which would otherwise be errors (for
4928 /// GCC compatibility).
4929 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4930 ASTContext &Context,
4931 bool &SizeIsNegative,
4932 llvm::APSInt &Oversized) {
4933 // This method tries to turn a variable array into a constant
4934 // array even when the size isn't an ICE. This is necessary
4935 // for compatibility with code that depends on gcc's buggy
4936 // constant expression folding, like struct {char x[(int)(char*)2];}
4937 SizeIsNegative = false;
4940 if (T->isDependentType())
4943 QualifierCollector Qs;
4944 const Type *Ty = Qs.strip(T);
4946 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4947 QualType Pointee = PTy->getPointeeType();
4948 QualType FixedType =
4949 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4951 if (FixedType.isNull()) return FixedType;
4952 FixedType = Context.getPointerType(FixedType);
4953 return Qs.apply(Context, FixedType);
4955 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4956 QualType Inner = PTy->getInnerType();
4957 QualType FixedType =
4958 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4960 if (FixedType.isNull()) return FixedType;
4961 FixedType = Context.getParenType(FixedType);
4962 return Qs.apply(Context, FixedType);
4965 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4968 // FIXME: We should probably handle this case
4969 if (VLATy->getElementType()->isVariablyModifiedType())
4973 if (!VLATy->getSizeExpr() ||
4974 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4977 // Check whether the array size is negative.
4978 if (Res.isSigned() && Res.isNegative()) {
4979 SizeIsNegative = true;
4983 // Check whether the array is too large to be addressed.
4984 unsigned ActiveSizeBits
4985 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4987 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4992 return Context.getConstantArrayType(VLATy->getElementType(),
4993 Res, ArrayType::Normal, 0);
4997 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4998 SrcTL = SrcTL.getUnqualifiedLoc();
4999 DstTL = DstTL.getUnqualifiedLoc();
5000 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5001 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5002 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5003 DstPTL.getPointeeLoc());
5004 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5007 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5008 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5009 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5010 DstPTL.getInnerLoc());
5011 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5012 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5015 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5016 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5017 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5018 TypeLoc DstElemTL = DstATL.getElementLoc();
5019 DstElemTL.initializeFullCopy(SrcElemTL);
5020 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5021 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5022 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5025 /// Helper method to turn variable array types into constant array
5026 /// types in certain situations which would otherwise be errors (for
5027 /// GCC compatibility).
5028 static TypeSourceInfo*
5029 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5030 ASTContext &Context,
5031 bool &SizeIsNegative,
5032 llvm::APSInt &Oversized) {
5034 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5035 SizeIsNegative, Oversized);
5036 if (FixedTy.isNull())
5038 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5039 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5040 FixedTInfo->getTypeLoc());
5044 /// \brief Register the given locally-scoped extern "C" declaration so
5045 /// that it can be found later for redeclarations. We include any extern "C"
5046 /// declaration that is not visible in the translation unit here, not just
5047 /// function-scope declarations.
5049 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5050 if (!getLangOpts().CPlusPlus &&
5051 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5052 // Don't need to track declarations in the TU in C.
5055 // Note that we have a locally-scoped external with this name.
5056 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5059 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5060 // FIXME: We can have multiple results via __attribute__((overloadable)).
5061 auto Result = Context.getExternCContextDecl()->lookup(Name);
5062 return Result.empty() ? nullptr : *Result.begin();
5065 /// \brief Diagnose function specifiers on a declaration of an identifier that
5066 /// does not identify a function.
5067 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5068 // FIXME: We should probably indicate the identifier in question to avoid
5069 // confusion for constructs like "inline int a(), b;"
5070 if (DS.isInlineSpecified())
5071 Diag(DS.getInlineSpecLoc(),
5072 diag::err_inline_non_function);
5074 if (DS.isVirtualSpecified())
5075 Diag(DS.getVirtualSpecLoc(),
5076 diag::err_virtual_non_function);
5078 if (DS.isExplicitSpecified())
5079 Diag(DS.getExplicitSpecLoc(),
5080 diag::err_explicit_non_function);
5082 if (DS.isNoreturnSpecified())
5083 Diag(DS.getNoreturnSpecLoc(),
5084 diag::err_noreturn_non_function);
5088 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5089 TypeSourceInfo *TInfo, LookupResult &Previous) {
5090 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5091 if (D.getCXXScopeSpec().isSet()) {
5092 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5093 << D.getCXXScopeSpec().getRange();
5095 // Pretend we didn't see the scope specifier.
5100 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5102 if (D.getDeclSpec().isConstexprSpecified())
5103 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5106 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5107 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5108 << D.getName().getSourceRange();
5112 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5113 if (!NewTD) return nullptr;
5115 // Handle attributes prior to checking for duplicates in MergeVarDecl
5116 ProcessDeclAttributes(S, NewTD, D);
5118 CheckTypedefForVariablyModifiedType(S, NewTD);
5120 bool Redeclaration = D.isRedeclaration();
5121 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5122 D.setRedeclaration(Redeclaration);
5127 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5128 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5129 // then it shall have block scope.
5130 // Note that variably modified types must be fixed before merging the decl so
5131 // that redeclarations will match.
5132 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5133 QualType T = TInfo->getType();
5134 if (T->isVariablyModifiedType()) {
5135 getCurFunction()->setHasBranchProtectedScope();
5137 if (S->getFnParent() == nullptr) {
5138 bool SizeIsNegative;
5139 llvm::APSInt Oversized;
5140 TypeSourceInfo *FixedTInfo =
5141 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5145 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5146 NewTD->setTypeSourceInfo(FixedTInfo);
5149 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5150 else if (T->isVariableArrayType())
5151 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5152 else if (Oversized.getBoolValue())
5153 Diag(NewTD->getLocation(), diag::err_array_too_large)
5154 << Oversized.toString(10);
5156 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5157 NewTD->setInvalidDecl();
5164 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5165 /// declares a typedef-name, either using the 'typedef' type specifier or via
5166 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5168 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5169 LookupResult &Previous, bool &Redeclaration) {
5170 // Merge the decl with the existing one if appropriate. If the decl is
5171 // in an outer scope, it isn't the same thing.
5172 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5173 /*AllowInlineNamespace*/false);
5174 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5175 if (!Previous.empty()) {
5176 Redeclaration = true;
5177 MergeTypedefNameDecl(NewTD, Previous);
5180 // If this is the C FILE type, notify the AST context.
5181 if (IdentifierInfo *II = NewTD->getIdentifier())
5182 if (!NewTD->isInvalidDecl() &&
5183 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5184 if (II->isStr("FILE"))
5185 Context.setFILEDecl(NewTD);
5186 else if (II->isStr("jmp_buf"))
5187 Context.setjmp_bufDecl(NewTD);
5188 else if (II->isStr("sigjmp_buf"))
5189 Context.setsigjmp_bufDecl(NewTD);
5190 else if (II->isStr("ucontext_t"))
5191 Context.setucontext_tDecl(NewTD);
5197 /// \brief Determines whether the given declaration is an out-of-scope
5198 /// previous declaration.
5200 /// This routine should be invoked when name lookup has found a
5201 /// previous declaration (PrevDecl) that is not in the scope where a
5202 /// new declaration by the same name is being introduced. If the new
5203 /// declaration occurs in a local scope, previous declarations with
5204 /// linkage may still be considered previous declarations (C99
5205 /// 6.2.2p4-5, C++ [basic.link]p6).
5207 /// \param PrevDecl the previous declaration found by name
5210 /// \param DC the context in which the new declaration is being
5213 /// \returns true if PrevDecl is an out-of-scope previous declaration
5214 /// for a new delcaration with the same name.
5216 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5217 ASTContext &Context) {
5221 if (!PrevDecl->hasLinkage())
5224 if (Context.getLangOpts().CPlusPlus) {
5225 // C++ [basic.link]p6:
5226 // If there is a visible declaration of an entity with linkage
5227 // having the same name and type, ignoring entities declared
5228 // outside the innermost enclosing namespace scope, the block
5229 // scope declaration declares that same entity and receives the
5230 // linkage of the previous declaration.
5231 DeclContext *OuterContext = DC->getRedeclContext();
5232 if (!OuterContext->isFunctionOrMethod())
5233 // This rule only applies to block-scope declarations.
5236 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5237 if (PrevOuterContext->isRecord())
5238 // We found a member function: ignore it.
5241 // Find the innermost enclosing namespace for the new and
5242 // previous declarations.
5243 OuterContext = OuterContext->getEnclosingNamespaceContext();
5244 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5246 // The previous declaration is in a different namespace, so it
5247 // isn't the same function.
5248 if (!OuterContext->Equals(PrevOuterContext))
5255 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5256 CXXScopeSpec &SS = D.getCXXScopeSpec();
5257 if (!SS.isSet()) return;
5258 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5261 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5262 QualType type = decl->getType();
5263 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5264 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5265 // Various kinds of declaration aren't allowed to be __autoreleasing.
5266 unsigned kind = -1U;
5267 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5268 if (var->hasAttr<BlocksAttr>())
5269 kind = 0; // __block
5270 else if (!var->hasLocalStorage())
5272 } else if (isa<ObjCIvarDecl>(decl)) {
5274 } else if (isa<FieldDecl>(decl)) {
5279 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5282 } else if (lifetime == Qualifiers::OCL_None) {
5283 // Try to infer lifetime.
5284 if (!type->isObjCLifetimeType())
5287 lifetime = type->getObjCARCImplicitLifetime();
5288 type = Context.getLifetimeQualifiedType(type, lifetime);
5289 decl->setType(type);
5292 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5293 // Thread-local variables cannot have lifetime.
5294 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5295 var->getTLSKind()) {
5296 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5305 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5306 // Ensure that an auto decl is deduced otherwise the checks below might cache
5307 // the wrong linkage.
5308 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5310 // 'weak' only applies to declarations with external linkage.
5311 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5312 if (!ND.isExternallyVisible()) {
5313 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5314 ND.dropAttr<WeakAttr>();
5317 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5318 if (ND.isExternallyVisible()) {
5319 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5320 ND.dropAttr<WeakRefAttr>();
5321 ND.dropAttr<AliasAttr>();
5325 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5326 if (VD->hasInit()) {
5327 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5328 assert(VD->isThisDeclarationADefinition() &&
5329 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5330 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5331 VD->dropAttr<AliasAttr>();
5336 // 'selectany' only applies to externally visible variable declarations.
5337 // It does not apply to functions.
5338 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5339 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5340 S.Diag(Attr->getLocation(),
5341 diag::err_attribute_selectany_non_extern_data);
5342 ND.dropAttr<SelectAnyAttr>();
5346 // dll attributes require external linkage.
5347 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5348 if (!ND.isExternallyVisible()) {
5349 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5351 ND.setInvalidDecl();
5356 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5358 bool IsSpecialization) {
5359 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5360 OldDecl = OldTD->getTemplatedDecl();
5361 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5362 NewDecl = NewTD->getTemplatedDecl();
5364 if (!OldDecl || !NewDecl)
5367 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5368 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5369 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5370 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5372 // dllimport and dllexport are inheritable attributes so we have to exclude
5373 // inherited attribute instances.
5374 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5375 (NewExportAttr && !NewExportAttr->isInherited());
5377 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5378 // the only exception being explicit specializations.
5379 // Implicitly generated declarations are also excluded for now because there
5380 // is no other way to switch these to use dllimport or dllexport.
5381 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5383 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5384 // Allow with a warning for free functions and global variables.
5385 bool JustWarn = false;
5386 if (!OldDecl->isCXXClassMember()) {
5387 auto *VD = dyn_cast<VarDecl>(OldDecl);
5388 if (VD && !VD->getDescribedVarTemplate())
5390 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5391 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5395 // We cannot change a declaration that's been used because IR has already
5396 // been emitted. Dllimported functions will still work though (modulo
5397 // address equality) as they can use the thunk.
5398 if (OldDecl->isUsed())
5399 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5402 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5403 : diag::err_attribute_dll_redeclaration;
5404 S.Diag(NewDecl->getLocation(), DiagID)
5406 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5407 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5409 NewDecl->setInvalidDecl();
5414 // A redeclaration is not allowed to drop a dllimport attribute, the only
5415 // exceptions being inline function definitions, local extern declarations,
5416 // and qualified friend declarations.
5417 // NB: MSVC converts such a declaration to dllexport.
5418 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5419 if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5420 // Ignore static data because out-of-line definitions are diagnosed
5422 IsStaticDataMember = VD->isStaticDataMember();
5423 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5424 IsInline = FD->isInlined();
5425 IsQualifiedFriend = FD->getQualifier() &&
5426 FD->getFriendObjectKind() == Decl::FOK_Declared;
5429 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5430 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5431 S.Diag(NewDecl->getLocation(),
5432 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5433 << NewDecl << OldImportAttr;
5434 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5435 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5436 OldDecl->dropAttr<DLLImportAttr>();
5437 NewDecl->dropAttr<DLLImportAttr>();
5438 } else if (IsInline && OldImportAttr &&
5439 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5440 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5441 OldDecl->dropAttr<DLLImportAttr>();
5442 NewDecl->dropAttr<DLLImportAttr>();
5443 S.Diag(NewDecl->getLocation(),
5444 diag::warn_dllimport_dropped_from_inline_function)
5445 << NewDecl << OldImportAttr;
5449 /// Given that we are within the definition of the given function,
5450 /// will that definition behave like C99's 'inline', where the
5451 /// definition is discarded except for optimization purposes?
5452 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5453 // Try to avoid calling GetGVALinkageForFunction.
5455 // All cases of this require the 'inline' keyword.
5456 if (!FD->isInlined()) return false;
5458 // This is only possible in C++ with the gnu_inline attribute.
5459 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5462 // Okay, go ahead and call the relatively-more-expensive function.
5465 // AST quite reasonably asserts that it's working on a function
5466 // definition. We don't really have a way to tell it that we're
5467 // currently defining the function, so just lie to it in +Asserts
5468 // builds. This is an awful hack.
5473 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5482 /// Determine whether a variable is extern "C" prior to attaching
5483 /// an initializer. We can't just call isExternC() here, because that
5484 /// will also compute and cache whether the declaration is externally
5485 /// visible, which might change when we attach the initializer.
5487 /// This can only be used if the declaration is known to not be a
5488 /// redeclaration of an internal linkage declaration.
5494 /// Attaching the initializer here makes this declaration not externally
5495 /// visible, because its type has internal linkage.
5497 /// FIXME: This is a hack.
5498 template<typename T>
5499 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5500 if (S.getLangOpts().CPlusPlus) {
5501 // In C++, the overloadable attribute negates the effects of extern "C".
5502 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5505 return D->isExternC();
5508 static bool shouldConsiderLinkage(const VarDecl *VD) {
5509 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5510 if (DC->isFunctionOrMethod())
5511 return VD->hasExternalStorage();
5512 if (DC->isFileContext())
5516 llvm_unreachable("Unexpected context");
5519 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5520 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5521 if (DC->isFileContext() || DC->isFunctionOrMethod())
5525 llvm_unreachable("Unexpected context");
5528 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5529 AttributeList::Kind Kind) {
5530 for (const AttributeList *L = AttrList; L; L = L->getNext())
5531 if (L->getKind() == Kind)
5536 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5537 AttributeList::Kind Kind) {
5538 // Check decl attributes on the DeclSpec.
5539 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5542 // Walk the declarator structure, checking decl attributes that were in a type
5543 // position to the decl itself.
5544 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5545 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5549 // Finally, check attributes on the decl itself.
5550 return hasParsedAttr(S, PD.getAttributes(), Kind);
5553 /// Adjust the \c DeclContext for a function or variable that might be a
5554 /// function-local external declaration.
5555 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5556 if (!DC->isFunctionOrMethod())
5559 // If this is a local extern function or variable declared within a function
5560 // template, don't add it into the enclosing namespace scope until it is
5561 // instantiated; it might have a dependent type right now.
5562 if (DC->isDependentContext())
5565 // C++11 [basic.link]p7:
5566 // When a block scope declaration of an entity with linkage is not found to
5567 // refer to some other declaration, then that entity is a member of the
5568 // innermost enclosing namespace.
5570 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5571 // semantically-enclosing namespace, not a lexically-enclosing one.
5572 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5573 DC = DC->getParent();
5577 /// \brief Returns true if given declaration is TU-scoped and externally
5579 static bool isDeclTUScopedExternallyVisible(const Decl *D) {
5580 if (auto *FD = dyn_cast<FunctionDecl>(D))
5581 return (FD->getDeclContext()->isTranslationUnit() || FD->isExternC()) &&
5582 FD->hasExternalFormalLinkage();
5583 else if (auto *VD = dyn_cast<VarDecl>(D))
5584 return (VD->getDeclContext()->isTranslationUnit() || VD->isExternC()) &&
5585 VD->hasExternalFormalLinkage();
5587 llvm_unreachable("Unknown type of decl!");
5591 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5592 TypeSourceInfo *TInfo, LookupResult &Previous,
5593 MultiTemplateParamsArg TemplateParamLists,
5595 QualType R = TInfo->getType();
5596 DeclarationName Name = GetNameForDeclarator(D).getName();
5598 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5599 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5601 // dllimport globals without explicit storage class are treated as extern. We
5602 // have to change the storage class this early to get the right DeclContext.
5603 if (SC == SC_None && !DC->isRecord() &&
5604 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5605 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5608 DeclContext *OriginalDC = DC;
5609 bool IsLocalExternDecl = SC == SC_Extern &&
5610 adjustContextForLocalExternDecl(DC);
5612 if (getLangOpts().OpenCL) {
5613 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5615 while (NR->isPointerType()) {
5616 if (NR->isFunctionPointerType()) {
5617 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5621 NR = NR->getPointeeType();
5624 if (!getOpenCLOptions().cl_khr_fp16) {
5625 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5626 // half array type (unless the cl_khr_fp16 extension is enabled).
5627 if (Context.getBaseElementType(R)->isHalfType()) {
5628 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5634 if (SCSpec == DeclSpec::SCS_mutable) {
5635 // mutable can only appear on non-static class members, so it's always
5637 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5642 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5643 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5644 D.getDeclSpec().getStorageClassSpecLoc())) {
5645 // In C++11, the 'register' storage class specifier is deprecated.
5646 // Suppress the warning in system macros, it's used in macros in some
5647 // popular C system headers, such as in glibc's htonl() macro.
5648 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5649 diag::warn_deprecated_register)
5650 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5653 IdentifierInfo *II = Name.getAsIdentifierInfo();
5655 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5660 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5662 if (!DC->isRecord() && S->getFnParent() == nullptr) {
5663 // C99 6.9p2: The storage-class specifiers auto and register shall not
5664 // appear in the declaration specifiers in an external declaration.
5665 // Global Register+Asm is a GNU extension we support.
5666 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5667 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5672 if (getLangOpts().OpenCL) {
5673 // Set up the special work-group-local storage class for variables in the
5674 // OpenCL __local address space.
5675 if (R.getAddressSpace() == LangAS::opencl_local) {
5676 SC = SC_OpenCLWorkGroupLocal;
5679 // OpenCL v1.2 s6.9.b p4:
5680 // The sampler type cannot be used with the __local and __global address
5681 // space qualifiers.
5682 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5683 R.getAddressSpace() == LangAS::opencl_global)) {
5684 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5687 // OpenCL 1.2 spec, p6.9 r:
5688 // The event type cannot be used to declare a program scope variable.
5689 // The event type cannot be used with the __local, __constant and __global
5690 // address space qualifiers.
5691 if (R->isEventT()) {
5692 if (S->getParent() == nullptr) {
5693 Diag(D.getLocStart(), diag::err_event_t_global_var);
5697 if (R.getAddressSpace()) {
5698 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5704 bool IsExplicitSpecialization = false;
5705 bool IsVariableTemplateSpecialization = false;
5706 bool IsPartialSpecialization = false;
5707 bool IsVariableTemplate = false;
5708 VarDecl *NewVD = nullptr;
5709 VarTemplateDecl *NewTemplate = nullptr;
5710 TemplateParameterList *TemplateParams = nullptr;
5711 if (!getLangOpts().CPlusPlus) {
5712 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5713 D.getIdentifierLoc(), II,
5716 if (D.isInvalidType())
5717 NewVD->setInvalidDecl();
5719 bool Invalid = false;
5721 if (DC->isRecord() && !CurContext->isRecord()) {
5722 // This is an out-of-line definition of a static data member.
5727 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5728 diag::err_static_out_of_line)
5729 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5734 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5735 // to names of variables declared in a block or to function parameters.
5736 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5739 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5740 diag::err_storage_class_for_static_member)
5741 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5743 case SC_PrivateExtern:
5744 llvm_unreachable("C storage class in c++!");
5745 case SC_OpenCLWorkGroupLocal:
5746 llvm_unreachable("OpenCL storage class in c++!");
5750 if (SC == SC_Static && CurContext->isRecord()) {
5751 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5752 if (RD->isLocalClass())
5753 Diag(D.getIdentifierLoc(),
5754 diag::err_static_data_member_not_allowed_in_local_class)
5755 << Name << RD->getDeclName();
5757 // C++98 [class.union]p1: If a union contains a static data member,
5758 // the program is ill-formed. C++11 drops this restriction.
5760 Diag(D.getIdentifierLoc(),
5761 getLangOpts().CPlusPlus11
5762 ? diag::warn_cxx98_compat_static_data_member_in_union
5763 : diag::ext_static_data_member_in_union) << Name;
5764 // We conservatively disallow static data members in anonymous structs.
5765 else if (!RD->getDeclName())
5766 Diag(D.getIdentifierLoc(),
5767 diag::err_static_data_member_not_allowed_in_anon_struct)
5768 << Name << RD->isUnion();
5772 // Match up the template parameter lists with the scope specifier, then
5773 // determine whether we have a template or a template specialization.
5774 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5775 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5776 D.getCXXScopeSpec(),
5777 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5778 ? D.getName().TemplateId
5781 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5783 if (TemplateParams) {
5784 if (!TemplateParams->size() &&
5785 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5786 // There is an extraneous 'template<>' for this variable. Complain
5787 // about it, but allow the declaration of the variable.
5788 Diag(TemplateParams->getTemplateLoc(),
5789 diag::err_template_variable_noparams)
5791 << SourceRange(TemplateParams->getTemplateLoc(),
5792 TemplateParams->getRAngleLoc());
5793 TemplateParams = nullptr;
5795 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5796 // This is an explicit specialization or a partial specialization.
5797 // FIXME: Check that we can declare a specialization here.
5798 IsVariableTemplateSpecialization = true;
5799 IsPartialSpecialization = TemplateParams->size() > 0;
5800 } else { // if (TemplateParams->size() > 0)
5801 // This is a template declaration.
5802 IsVariableTemplate = true;
5804 // Check that we can declare a template here.
5805 if (CheckTemplateDeclScope(S, TemplateParams))
5808 // Only C++1y supports variable templates (N3651).
5809 Diag(D.getIdentifierLoc(),
5810 getLangOpts().CPlusPlus14
5811 ? diag::warn_cxx11_compat_variable_template
5812 : diag::ext_variable_template);
5817 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5818 "should have a 'template<>' for this decl");
5821 if (IsVariableTemplateSpecialization) {
5822 SourceLocation TemplateKWLoc =
5823 TemplateParamLists.size() > 0
5824 ? TemplateParamLists[0]->getTemplateLoc()
5826 DeclResult Res = ActOnVarTemplateSpecialization(
5827 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5828 IsPartialSpecialization);
5829 if (Res.isInvalid())
5831 NewVD = cast<VarDecl>(Res.get());
5834 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5835 D.getIdentifierLoc(), II, R, TInfo, SC);
5837 // If this is supposed to be a variable template, create it as such.
5838 if (IsVariableTemplate) {
5840 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5841 TemplateParams, NewVD);
5842 NewVD->setDescribedVarTemplate(NewTemplate);
5845 // If this decl has an auto type in need of deduction, make a note of the
5846 // Decl so we can diagnose uses of it in its own initializer.
5847 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5848 ParsingInitForAutoVars.insert(NewVD);
5850 if (D.isInvalidType() || Invalid) {
5851 NewVD->setInvalidDecl();
5853 NewTemplate->setInvalidDecl();
5856 SetNestedNameSpecifier(NewVD, D);
5858 // If we have any template parameter lists that don't directly belong to
5859 // the variable (matching the scope specifier), store them.
5860 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5861 if (TemplateParamLists.size() > VDTemplateParamLists)
5862 NewVD->setTemplateParameterListsInfo(
5863 Context, TemplateParamLists.size() - VDTemplateParamLists,
5864 TemplateParamLists.data());
5866 if (D.getDeclSpec().isConstexprSpecified())
5867 NewVD->setConstexpr(true);
5870 // Set the lexical context. If the declarator has a C++ scope specifier, the
5871 // lexical context will be different from the semantic context.
5872 NewVD->setLexicalDeclContext(CurContext);
5874 NewTemplate->setLexicalDeclContext(CurContext);
5876 if (IsLocalExternDecl)
5877 NewVD->setLocalExternDecl();
5879 bool EmitTLSUnsupportedError = false;
5880 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5881 // C++11 [dcl.stc]p4:
5882 // When thread_local is applied to a variable of block scope the
5883 // storage-class-specifier static is implied if it does not appear
5885 // Core issue: 'static' is not implied if the variable is declared
5887 if (NewVD->hasLocalStorage() &&
5888 (SCSpec != DeclSpec::SCS_unspecified ||
5889 TSCS != DeclSpec::TSCS_thread_local ||
5890 !DC->isFunctionOrMethod()))
5891 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5892 diag::err_thread_non_global)
5893 << DeclSpec::getSpecifierName(TSCS);
5894 else if (!Context.getTargetInfo().isTLSSupported()) {
5895 if (getLangOpts().CUDA) {
5896 // Postpone error emission until we've collected attributes required to
5897 // figure out whether it's a host or device variable and whether the
5898 // error should be ignored.
5899 EmitTLSUnsupportedError = true;
5900 // We still need to mark the variable as TLS so it shows up in AST with
5901 // proper storage class for other tools to use even if we're not going
5902 // to emit any code for it.
5903 NewVD->setTSCSpec(TSCS);
5905 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5906 diag::err_thread_unsupported);
5908 NewVD->setTSCSpec(TSCS);
5912 // An inline definition of a function with external linkage shall
5913 // not contain a definition of a modifiable object with static or
5914 // thread storage duration...
5915 // We only apply this when the function is required to be defined
5916 // elsewhere, i.e. when the function is not 'extern inline'. Note
5917 // that a local variable with thread storage duration still has to
5918 // be marked 'static'. Also note that it's possible to get these
5919 // semantics in C++ using __attribute__((gnu_inline)).
5920 if (SC == SC_Static && S->getFnParent() != nullptr &&
5921 !NewVD->getType().isConstQualified()) {
5922 FunctionDecl *CurFD = getCurFunctionDecl();
5923 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5924 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5925 diag::warn_static_local_in_extern_inline);
5926 MaybeSuggestAddingStaticToDecl(CurFD);
5930 if (D.getDeclSpec().isModulePrivateSpecified()) {
5931 if (IsVariableTemplateSpecialization)
5932 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5933 << (IsPartialSpecialization ? 1 : 0)
5934 << FixItHint::CreateRemoval(
5935 D.getDeclSpec().getModulePrivateSpecLoc());
5936 else if (IsExplicitSpecialization)
5937 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5939 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5940 else if (NewVD->hasLocalStorage())
5941 Diag(NewVD->getLocation(), diag::err_module_private_local)
5942 << 0 << NewVD->getDeclName()
5943 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5944 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5946 NewVD->setModulePrivate();
5948 NewTemplate->setModulePrivate();
5952 // Handle attributes prior to checking for duplicates in MergeVarDecl
5953 ProcessDeclAttributes(S, NewVD, D);
5955 if (getLangOpts().CUDA) {
5956 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
5957 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5958 diag::err_thread_unsupported);
5959 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5960 // storage [duration]."
5961 if (SC == SC_None && S->getFnParent() != nullptr &&
5962 (NewVD->hasAttr<CUDASharedAttr>() ||
5963 NewVD->hasAttr<CUDAConstantAttr>())) {
5964 NewVD->setStorageClass(SC_Static);
5968 // Ensure that dllimport globals without explicit storage class are treated as
5969 // extern. The storage class is set above using parsed attributes. Now we can
5970 // check the VarDecl itself.
5971 assert(!NewVD->hasAttr<DLLImportAttr>() ||
5972 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5973 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5975 // In auto-retain/release, infer strong retension for variables of
5977 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5978 NewVD->setInvalidDecl();
5980 // Handle GNU asm-label extension (encoded as an attribute).
5981 if (Expr *E = (Expr*)D.getAsmLabel()) {
5982 // The parser guarantees this is a string.
5983 StringLiteral *SE = cast<StringLiteral>(E);
5984 StringRef Label = SE->getString();
5985 if (S->getFnParent() != nullptr) {
5989 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5992 // Local Named register
5993 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5994 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5998 case SC_PrivateExtern:
5999 case SC_OpenCLWorkGroupLocal:
6002 } else if (SC == SC_Register) {
6003 // Global Named register
6004 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
6005 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6006 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6007 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6008 NewVD->setInvalidDecl(true);
6012 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6013 Context, Label, 0));
6014 } else if (!ExtnameUndeclaredIdentifiers.empty() &&
6015 isDeclTUScopedExternallyVisible(NewVD)) {
6016 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6017 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6018 if (I != ExtnameUndeclaredIdentifiers.end()) {
6019 NewVD->addAttr(I->second);
6020 ExtnameUndeclaredIdentifiers.erase(I);
6024 // Diagnose shadowed variables before filtering for scope.
6025 if (D.getCXXScopeSpec().isEmpty())
6026 CheckShadow(S, NewVD, Previous);
6028 // Don't consider existing declarations that are in a different
6029 // scope and are out-of-semantic-context declarations (if the new
6030 // declaration has linkage).
6031 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6032 D.getCXXScopeSpec().isNotEmpty() ||
6033 IsExplicitSpecialization ||
6034 IsVariableTemplateSpecialization);
6036 // Check whether the previous declaration is in the same block scope. This
6037 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6038 if (getLangOpts().CPlusPlus &&
6039 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6040 NewVD->setPreviousDeclInSameBlockScope(
6041 Previous.isSingleResult() && !Previous.isShadowed() &&
6042 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6044 if (!getLangOpts().CPlusPlus) {
6045 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6047 // If this is an explicit specialization of a static data member, check it.
6048 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6049 CheckMemberSpecialization(NewVD, Previous))
6050 NewVD->setInvalidDecl();
6052 // Merge the decl with the existing one if appropriate.
6053 if (!Previous.empty()) {
6054 if (Previous.isSingleResult() &&
6055 isa<FieldDecl>(Previous.getFoundDecl()) &&
6056 D.getCXXScopeSpec().isSet()) {
6057 // The user tried to define a non-static data member
6058 // out-of-line (C++ [dcl.meaning]p1).
6059 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6060 << D.getCXXScopeSpec().getRange();
6062 NewVD->setInvalidDecl();
6064 } else if (D.getCXXScopeSpec().isSet()) {
6065 // No previous declaration in the qualifying scope.
6066 Diag(D.getIdentifierLoc(), diag::err_no_member)
6067 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6068 << D.getCXXScopeSpec().getRange();
6069 NewVD->setInvalidDecl();
6072 if (!IsVariableTemplateSpecialization)
6073 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6076 VarTemplateDecl *PrevVarTemplate =
6077 NewVD->getPreviousDecl()
6078 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6081 // Check the template parameter list of this declaration, possibly
6082 // merging in the template parameter list from the previous variable
6083 // template declaration.
6084 if (CheckTemplateParameterList(
6086 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6088 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6089 DC->isDependentContext())
6090 ? TPC_ClassTemplateMember
6092 NewVD->setInvalidDecl();
6094 // If we are providing an explicit specialization of a static variable
6095 // template, make a note of that.
6096 if (PrevVarTemplate &&
6097 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6098 PrevVarTemplate->setMemberSpecialization();
6102 ProcessPragmaWeak(S, NewVD);
6104 // If this is the first declaration of an extern C variable, update
6105 // the map of such variables.
6106 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6107 isIncompleteDeclExternC(*this, NewVD))
6108 RegisterLocallyScopedExternCDecl(NewVD, S);
6110 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6111 Decl *ManglingContextDecl;
6112 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6113 NewVD->getDeclContext(), ManglingContextDecl)) {
6114 Context.setManglingNumber(
6115 NewVD, MCtx->getManglingNumber(
6116 NewVD, getMSManglingNumber(getLangOpts(), S)));
6117 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6121 if (D.isRedeclaration() && !Previous.empty()) {
6122 checkDLLAttributeRedeclaration(
6123 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6124 IsExplicitSpecialization);
6128 if (NewVD->isInvalidDecl())
6129 NewTemplate->setInvalidDecl();
6130 ActOnDocumentableDecl(NewTemplate);
6137 /// \brief Diagnose variable or built-in function shadowing. Implements
6140 /// This method is called whenever a VarDecl is added to a "useful"
6143 /// \param S the scope in which the shadowing name is being declared
6144 /// \param R the lookup of the name
6146 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6147 // Return if warning is ignored.
6148 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6151 // Don't diagnose declarations at file scope.
6152 if (D->hasGlobalStorage())
6155 DeclContext *NewDC = D->getDeclContext();
6157 // Only diagnose if we're shadowing an unambiguous field or variable.
6158 if (R.getResultKind() != LookupResult::Found)
6161 NamedDecl* ShadowedDecl = R.getFoundDecl();
6162 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6165 // Fields are not shadowed by variables in C++ static methods.
6166 if (isa<FieldDecl>(ShadowedDecl))
6167 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6171 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6172 if (shadowedVar->isExternC()) {
6173 // For shadowing external vars, make sure that we point to the global
6174 // declaration, not a locally scoped extern declaration.
6175 for (auto I : shadowedVar->redecls())
6176 if (I->isFileVarDecl()) {
6182 DeclContext *OldDC = ShadowedDecl->getDeclContext();
6184 // Only warn about certain kinds of shadowing for class members.
6185 if (NewDC && NewDC->isRecord()) {
6186 // In particular, don't warn about shadowing non-class members.
6187 if (!OldDC->isRecord())
6190 // TODO: should we warn about static data members shadowing
6191 // static data members from base classes?
6193 // TODO: don't diagnose for inaccessible shadowed members.
6194 // This is hard to do perfectly because we might friend the
6195 // shadowing context, but that's just a false negative.
6198 // Determine what kind of declaration we're shadowing.
6200 if (isa<RecordDecl>(OldDC)) {
6201 if (isa<FieldDecl>(ShadowedDecl))
6204 Kind = 2; // static data member
6205 } else if (OldDC->isFileContext())
6210 DeclarationName Name = R.getLookupName();
6212 // Emit warning and note.
6213 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6215 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6216 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6219 /// \brief Check -Wshadow without the advantage of a previous lookup.
6220 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6221 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6224 LookupResult R(*this, D->getDeclName(), D->getLocation(),
6225 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6227 CheckShadow(S, D, R);
6230 /// Check for conflict between this global or extern "C" declaration and
6231 /// previous global or extern "C" declarations. This is only used in C++.
6232 template<typename T>
6233 static bool checkGlobalOrExternCConflict(
6234 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6235 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6236 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6238 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6239 // The common case: this global doesn't conflict with any extern "C"
6245 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6246 // Both the old and new declarations have C language linkage. This is a
6249 Previous.addDecl(Prev);
6253 // This is a global, non-extern "C" declaration, and there is a previous
6254 // non-global extern "C" declaration. Diagnose if this is a variable
6256 if (!isa<VarDecl>(ND))
6259 // The declaration is extern "C". Check for any declaration in the
6260 // translation unit which might conflict.
6262 // We have already performed the lookup into the translation unit.
6264 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6266 if (isa<VarDecl>(*I)) {
6272 DeclContext::lookup_result R =
6273 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6274 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6276 if (isa<VarDecl>(*I)) {
6280 // FIXME: If we have any other entity with this name in global scope,
6281 // the declaration is ill-formed, but that is a defect: it breaks the
6282 // 'stat' hack, for instance. Only variables can have mangled name
6283 // clashes with extern "C" declarations, so only they deserve a
6292 // Use the first declaration's location to ensure we point at something which
6293 // is lexically inside an extern "C" linkage-spec.
6294 assert(Prev && "should have found a previous declaration to diagnose");
6295 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6296 Prev = FD->getFirstDecl();
6298 Prev = cast<VarDecl>(Prev)->getFirstDecl();
6300 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6302 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6307 /// Apply special rules for handling extern "C" declarations. Returns \c true
6308 /// if we have found that this is a redeclaration of some prior entity.
6310 /// Per C++ [dcl.link]p6:
6311 /// Two declarations [for a function or variable] with C language linkage
6312 /// with the same name that appear in different scopes refer to the same
6313 /// [entity]. An entity with C language linkage shall not be declared with
6314 /// the same name as an entity in global scope.
6315 template<typename T>
6316 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6317 LookupResult &Previous) {
6318 if (!S.getLangOpts().CPlusPlus) {
6319 // In C, when declaring a global variable, look for a corresponding 'extern'
6320 // variable declared in function scope. We don't need this in C++, because
6321 // we find local extern decls in the surrounding file-scope DeclContext.
6322 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6323 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6325 Previous.addDecl(Prev);
6332 // A declaration in the translation unit can conflict with an extern "C"
6334 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6335 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6337 // An extern "C" declaration can conflict with a declaration in the
6338 // translation unit or can be a redeclaration of an extern "C" declaration
6339 // in another scope.
6340 if (isIncompleteDeclExternC(S,ND))
6341 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6343 // Neither global nor extern "C": nothing to do.
6347 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6348 // If the decl is already known invalid, don't check it.
6349 if (NewVD->isInvalidDecl())
6352 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6353 QualType T = TInfo->getType();
6355 // Defer checking an 'auto' type until its initializer is attached.
6356 if (T->isUndeducedType())
6359 if (NewVD->hasAttrs())
6360 CheckAlignasUnderalignment(NewVD);
6362 if (T->isObjCObjectType()) {
6363 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6364 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6365 T = Context.getObjCObjectPointerType(T);
6369 // Emit an error if an address space was applied to decl with local storage.
6370 // This includes arrays of objects with address space qualifiers, but not
6371 // automatic variables that point to other address spaces.
6372 // ISO/IEC TR 18037 S5.1.2
6373 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6374 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6375 NewVD->setInvalidDecl();
6379 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6380 // __constant address space.
6381 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6382 && T.getAddressSpace() != LangAS::opencl_constant
6383 && !T->isSamplerT()){
6384 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6385 NewVD->setInvalidDecl();
6389 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6391 if ((getLangOpts().OpenCLVersion >= 120)
6392 && NewVD->isStaticLocal()) {
6393 Diag(NewVD->getLocation(), diag::err_static_function_scope);
6394 NewVD->setInvalidDecl();
6398 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6399 && !NewVD->hasAttr<BlocksAttr>()) {
6400 if (getLangOpts().getGC() != LangOptions::NonGC)
6401 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6403 assert(!getLangOpts().ObjCAutoRefCount);
6404 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6408 bool isVM = T->isVariablyModifiedType();
6409 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6410 NewVD->hasAttr<BlocksAttr>())
6411 getCurFunction()->setHasBranchProtectedScope();
6413 if ((isVM && NewVD->hasLinkage()) ||
6414 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6415 bool SizeIsNegative;
6416 llvm::APSInt Oversized;
6417 TypeSourceInfo *FixedTInfo =
6418 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6419 SizeIsNegative, Oversized);
6420 if (!FixedTInfo && T->isVariableArrayType()) {
6421 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6422 // FIXME: This won't give the correct result for
6424 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6426 if (NewVD->isFileVarDecl())
6427 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6429 else if (NewVD->isStaticLocal())
6430 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6433 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6435 NewVD->setInvalidDecl();
6440 if (NewVD->isFileVarDecl())
6441 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6443 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6444 NewVD->setInvalidDecl();
6448 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6449 NewVD->setType(FixedTInfo->getType());
6450 NewVD->setTypeSourceInfo(FixedTInfo);
6453 if (T->isVoidType()) {
6454 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6455 // of objects and functions.
6456 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6457 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6459 NewVD->setInvalidDecl();
6464 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6465 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6466 NewVD->setInvalidDecl();
6470 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6471 Diag(NewVD->getLocation(), diag::err_block_on_vm);
6472 NewVD->setInvalidDecl();
6476 if (NewVD->isConstexpr() && !T->isDependentType() &&
6477 RequireLiteralType(NewVD->getLocation(), T,
6478 diag::err_constexpr_var_non_literal)) {
6479 NewVD->setInvalidDecl();
6484 /// \brief Perform semantic checking on a newly-created variable
6487 /// This routine performs all of the type-checking required for a
6488 /// variable declaration once it has been built. It is used both to
6489 /// check variables after they have been parsed and their declarators
6490 /// have been translated into a declaration, and to check variables
6491 /// that have been instantiated from a template.
6493 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6495 /// Returns true if the variable declaration is a redeclaration.
6496 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6497 CheckVariableDeclarationType(NewVD);
6499 // If the decl is already known invalid, don't check it.
6500 if (NewVD->isInvalidDecl())
6503 // If we did not find anything by this name, look for a non-visible
6504 // extern "C" declaration with the same name.
6505 if (Previous.empty() &&
6506 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6507 Previous.setShadowed();
6509 // Filter out any non-conflicting previous declarations.
6510 filterNonConflictingPreviousDecls(*this, NewVD, Previous);
6512 if (!Previous.empty()) {
6513 MergeVarDecl(NewVD, Previous);
6519 /// \brief Data used with FindOverriddenMethod
6520 struct FindOverriddenMethodData {
6522 CXXMethodDecl *Method;
6525 /// \brief Member lookup function that determines whether a given C++
6526 /// method overrides a method in a base class, to be used with
6527 /// CXXRecordDecl::lookupInBases().
6528 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6531 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6533 FindOverriddenMethodData *Data
6534 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6536 DeclarationName Name = Data->Method->getDeclName();
6538 // FIXME: Do we care about other names here too?
6539 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6540 // We really want to find the base class destructor here.
6541 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6542 CanQualType CT = Data->S->Context.getCanonicalType(T);
6544 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6547 for (Path.Decls = BaseRecord->lookup(Name);
6548 !Path.Decls.empty();
6549 Path.Decls = Path.Decls.slice(1)) {
6550 NamedDecl *D = Path.Decls.front();
6551 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6552 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6561 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6563 /// \brief Report an error regarding overriding, along with any relevant
6564 /// overriden methods.
6566 /// \param DiagID the primary error to report.
6567 /// \param MD the overriding method.
6568 /// \param OEK which overrides to include as notes.
6569 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6570 OverrideErrorKind OEK = OEK_All) {
6571 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6572 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6573 E = MD->end_overridden_methods();
6575 // This check (& the OEK parameter) could be replaced by a predicate, but
6576 // without lambdas that would be overkill. This is still nicer than writing
6577 // out the diag loop 3 times.
6578 if ((OEK == OEK_All) ||
6579 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6580 (OEK == OEK_Deleted && (*I)->isDeleted()))
6581 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6585 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6586 /// and if so, check that it's a valid override and remember it.
6587 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6588 // Look for methods in base classes that this method might override.
6590 FindOverriddenMethodData Data;
6593 bool hasDeletedOverridenMethods = false;
6594 bool hasNonDeletedOverridenMethods = false;
6595 bool AddedAny = false;
6596 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6597 for (auto *I : Paths.found_decls()) {
6598 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6599 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6600 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6601 !CheckOverridingFunctionAttributes(MD, OldMD) &&
6602 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6603 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6604 hasDeletedOverridenMethods |= OldMD->isDeleted();
6605 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6612 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6613 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6615 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6616 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6623 // Struct for holding all of the extra arguments needed by
6624 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6625 struct ActOnFDArgs {
6628 MultiTemplateParamsArg TemplateParamLists;
6635 // Callback to only accept typo corrections that have a non-zero edit distance.
6636 // Also only accept corrections that have the same parent decl.
6637 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6639 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6640 CXXRecordDecl *Parent)
6641 : Context(Context), OriginalFD(TypoFD),
6642 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6644 bool ValidateCandidate(const TypoCorrection &candidate) override {
6645 if (candidate.getEditDistance() == 0)
6648 SmallVector<unsigned, 1> MismatchedParams;
6649 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6650 CDeclEnd = candidate.end();
6651 CDecl != CDeclEnd; ++CDecl) {
6652 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6654 if (FD && !FD->hasBody() &&
6655 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6656 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6657 CXXRecordDecl *Parent = MD->getParent();
6658 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6660 } else if (!ExpectedParent) {
6670 ASTContext &Context;
6671 FunctionDecl *OriginalFD;
6672 CXXRecordDecl *ExpectedParent;
6677 /// \brief Generate diagnostics for an invalid function redeclaration.
6679 /// This routine handles generating the diagnostic messages for an invalid
6680 /// function redeclaration, including finding possible similar declarations
6681 /// or performing typo correction if there are no previous declarations with
6684 /// Returns a NamedDecl iff typo correction was performed and substituting in
6685 /// the new declaration name does not cause new errors.
6686 static NamedDecl *DiagnoseInvalidRedeclaration(
6687 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6688 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6689 DeclarationName Name = NewFD->getDeclName();
6690 DeclContext *NewDC = NewFD->getDeclContext();
6691 SmallVector<unsigned, 1> MismatchedParams;
6692 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6693 TypoCorrection Correction;
6694 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6695 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6696 : diag::err_member_decl_does_not_match;
6697 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6698 IsLocalFriend ? Sema::LookupLocalFriendName
6699 : Sema::LookupOrdinaryName,
6700 Sema::ForRedeclaration);
6702 NewFD->setInvalidDecl();
6704 SemaRef.LookupName(Prev, S);
6706 SemaRef.LookupQualifiedName(Prev, NewDC);
6707 assert(!Prev.isAmbiguous() &&
6708 "Cannot have an ambiguity in previous-declaration lookup");
6709 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6710 if (!Prev.empty()) {
6711 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6712 Func != FuncEnd; ++Func) {
6713 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6715 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6716 // Add 1 to the index so that 0 can mean the mismatch didn't
6717 // involve a parameter
6719 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6720 NearMatches.push_back(std::make_pair(FD, ParamNum));
6723 // If the qualified name lookup yielded nothing, try typo correction
6724 } else if ((Correction = SemaRef.CorrectTypo(
6725 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6726 &ExtraArgs.D.getCXXScopeSpec(),
6727 llvm::make_unique<DifferentNameValidatorCCC>(
6728 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6729 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6730 // Set up everything for the call to ActOnFunctionDeclarator
6731 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6732 ExtraArgs.D.getIdentifierLoc());
6734 Previous.setLookupName(Correction.getCorrection());
6735 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6736 CDeclEnd = Correction.end();
6737 CDecl != CDeclEnd; ++CDecl) {
6738 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6739 if (FD && !FD->hasBody() &&
6740 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6741 Previous.addDecl(FD);
6744 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6747 // Retry building the function declaration with the new previous
6748 // declarations, and with errors suppressed.
6751 Sema::SFINAETrap Trap(SemaRef);
6753 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6754 // pieces need to verify the typo-corrected C++ declaration and hopefully
6755 // eliminate the need for the parameter pack ExtraArgs.
6756 Result = SemaRef.ActOnFunctionDeclarator(
6757 ExtraArgs.S, ExtraArgs.D,
6758 Correction.getCorrectionDecl()->getDeclContext(),
6759 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6760 ExtraArgs.AddToScope);
6762 if (Trap.hasErrorOccurred())
6767 // Determine which correction we picked.
6768 Decl *Canonical = Result->getCanonicalDecl();
6769 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6771 if ((*I)->getCanonicalDecl() == Canonical)
6772 Correction.setCorrectionDecl(*I);
6774 SemaRef.diagnoseTypo(
6776 SemaRef.PDiag(IsLocalFriend
6777 ? diag::err_no_matching_local_friend_suggest
6778 : diag::err_member_decl_does_not_match_suggest)
6779 << Name << NewDC << IsDefinition);
6783 // Pretend the typo correction never occurred
6784 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6785 ExtraArgs.D.getIdentifierLoc());
6786 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6788 Previous.setLookupName(Name);
6791 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6792 << Name << NewDC << IsDefinition << NewFD->getLocation();
6794 bool NewFDisConst = false;
6795 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6796 NewFDisConst = NewMD->isConst();
6798 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6799 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6800 NearMatch != NearMatchEnd; ++NearMatch) {
6801 FunctionDecl *FD = NearMatch->first;
6802 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6803 bool FDisConst = MD && MD->isConst();
6804 bool IsMember = MD || !IsLocalFriend;
6806 // FIXME: These notes are poorly worded for the local friend case.
6807 if (unsigned Idx = NearMatch->second) {
6808 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6809 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6810 if (Loc.isInvalid()) Loc = FD->getLocation();
6811 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6812 : diag::note_local_decl_close_param_match)
6813 << Idx << FDParam->getType()
6814 << NewFD->getParamDecl(Idx - 1)->getType();
6815 } else if (FDisConst != NewFDisConst) {
6816 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6817 << NewFDisConst << FD->getSourceRange().getEnd();
6819 SemaRef.Diag(FD->getLocation(),
6820 IsMember ? diag::note_member_def_close_match
6821 : diag::note_local_decl_close_match);
6826 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6827 switch (D.getDeclSpec().getStorageClassSpec()) {
6828 default: llvm_unreachable("Unknown storage class!");
6829 case DeclSpec::SCS_auto:
6830 case DeclSpec::SCS_register:
6831 case DeclSpec::SCS_mutable:
6832 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6833 diag::err_typecheck_sclass_func);
6836 case DeclSpec::SCS_unspecified: break;
6837 case DeclSpec::SCS_extern:
6838 if (D.getDeclSpec().isExternInLinkageSpec())
6841 case DeclSpec::SCS_static: {
6842 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6844 // The declaration of an identifier for a function that has
6845 // block scope shall have no explicit storage-class specifier
6846 // other than extern
6847 // See also (C++ [dcl.stc]p4).
6848 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6849 diag::err_static_block_func);
6854 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6857 // No explicit storage class has already been returned
6861 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6862 DeclContext *DC, QualType &R,
6863 TypeSourceInfo *TInfo,
6865 bool &IsVirtualOkay) {
6866 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6867 DeclarationName Name = NameInfo.getName();
6869 FunctionDecl *NewFD = nullptr;
6870 bool isInline = D.getDeclSpec().isInlineSpecified();
6872 if (!SemaRef.getLangOpts().CPlusPlus) {
6873 // Determine whether the function was written with a
6874 // prototype. This true when:
6875 // - there is a prototype in the declarator, or
6876 // - the type R of the function is some kind of typedef or other reference
6877 // to a type name (which eventually refers to a function type).
6879 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6880 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6882 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6883 D.getLocStart(), NameInfo, R,
6884 TInfo, SC, isInline,
6885 HasPrototype, false);
6886 if (D.isInvalidType())
6887 NewFD->setInvalidDecl();
6892 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6893 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6895 // Check that the return type is not an abstract class type.
6896 // For record types, this is done by the AbstractClassUsageDiagnoser once
6897 // the class has been completely parsed.
6898 if (!DC->isRecord() &&
6899 SemaRef.RequireNonAbstractType(
6900 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6901 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6904 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6905 // This is a C++ constructor declaration.
6906 assert(DC->isRecord() &&
6907 "Constructors can only be declared in a member context");
6909 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6910 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6911 D.getLocStart(), NameInfo,
6912 R, TInfo, isExplicit, isInline,
6913 /*isImplicitlyDeclared=*/false,
6916 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6917 // This is a C++ destructor declaration.
6918 if (DC->isRecord()) {
6919 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6920 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6921 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6922 SemaRef.Context, Record,
6924 NameInfo, R, TInfo, isInline,
6925 /*isImplicitlyDeclared=*/false);
6927 // If the class is complete, then we now create the implicit exception
6928 // specification. If the class is incomplete or dependent, we can't do
6930 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6931 Record->getDefinition() && !Record->isBeingDefined() &&
6932 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6933 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6936 IsVirtualOkay = true;
6940 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6943 // Create a FunctionDecl to satisfy the function definition parsing
6945 return FunctionDecl::Create(SemaRef.Context, DC,
6947 D.getIdentifierLoc(), Name, R, TInfo,
6949 /*hasPrototype=*/true, isConstexpr);
6952 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6953 if (!DC->isRecord()) {
6954 SemaRef.Diag(D.getIdentifierLoc(),
6955 diag::err_conv_function_not_member);
6959 SemaRef.CheckConversionDeclarator(D, R, SC);
6960 IsVirtualOkay = true;
6961 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6962 D.getLocStart(), NameInfo,
6963 R, TInfo, isInline, isExplicit,
6964 isConstexpr, SourceLocation());
6966 } else if (DC->isRecord()) {
6967 // If the name of the function is the same as the name of the record,
6968 // then this must be an invalid constructor that has a return type.
6969 // (The parser checks for a return type and makes the declarator a
6970 // constructor if it has no return type).
6971 if (Name.getAsIdentifierInfo() &&
6972 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6973 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6974 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6975 << SourceRange(D.getIdentifierLoc());
6979 // This is a C++ method declaration.
6980 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6981 cast<CXXRecordDecl>(DC),
6982 D.getLocStart(), NameInfo, R,
6983 TInfo, SC, isInline,
6984 isConstexpr, SourceLocation());
6985 IsVirtualOkay = !Ret->isStatic();
6989 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
6990 if (!isFriend && SemaRef.CurContext->isRecord())
6993 // Determine whether the function was written with a
6994 // prototype. This true when:
6995 // - we're in C++ (where every function has a prototype),
6996 return FunctionDecl::Create(SemaRef.Context, DC,
6998 NameInfo, R, TInfo, SC, isInline,
6999 true/*HasPrototype*/, isConstexpr);
7003 enum OpenCLParamType {
7007 PrivatePtrKernelParam,
7012 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7013 if (PT->isPointerType()) {
7014 QualType PointeeType = PT->getPointeeType();
7015 if (PointeeType->isPointerType())
7016 return PtrPtrKernelParam;
7017 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7021 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7022 // be used as builtin types.
7024 if (PT->isImageType())
7025 return PtrKernelParam;
7027 if (PT->isBooleanType())
7028 return InvalidKernelParam;
7031 return InvalidKernelParam;
7033 if (PT->isHalfType())
7034 return InvalidKernelParam;
7036 if (PT->isRecordType())
7037 return RecordKernelParam;
7039 return ValidKernelParam;
7042 static void checkIsValidOpenCLKernelParameter(
7046 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7047 QualType PT = Param->getType();
7049 // Cache the valid types we encounter to avoid rechecking structs that are
7051 if (ValidTypes.count(PT.getTypePtr()))
7054 switch (getOpenCLKernelParameterType(PT)) {
7055 case PtrPtrKernelParam:
7056 // OpenCL v1.2 s6.9.a:
7057 // A kernel function argument cannot be declared as a
7058 // pointer to a pointer type.
7059 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7063 case PrivatePtrKernelParam:
7064 // OpenCL v1.2 s6.9.a:
7065 // A kernel function argument cannot be declared as a
7066 // pointer to the private address space.
7067 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7071 // OpenCL v1.2 s6.9.k:
7072 // Arguments to kernel functions in a program cannot be declared with the
7073 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7074 // uintptr_t or a struct and/or union that contain fields declared to be
7075 // one of these built-in scalar types.
7077 case InvalidKernelParam:
7078 // OpenCL v1.2 s6.8 n:
7079 // A kernel function argument cannot be declared
7081 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7085 case PtrKernelParam:
7086 case ValidKernelParam:
7087 ValidTypes.insert(PT.getTypePtr());
7090 case RecordKernelParam:
7094 // Track nested structs we will inspect
7095 SmallVector<const Decl *, 4> VisitStack;
7097 // Track where we are in the nested structs. Items will migrate from
7098 // VisitStack to HistoryStack as we do the DFS for bad field.
7099 SmallVector<const FieldDecl *, 4> HistoryStack;
7100 HistoryStack.push_back(nullptr);
7102 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7103 VisitStack.push_back(PD);
7105 assert(VisitStack.back() && "First decl null?");
7108 const Decl *Next = VisitStack.pop_back_val();
7110 assert(!HistoryStack.empty());
7111 // Found a marker, we have gone up a level
7112 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7113 ValidTypes.insert(Hist->getType().getTypePtr());
7118 // Adds everything except the original parameter declaration (which is not a
7119 // field itself) to the history stack.
7120 const RecordDecl *RD;
7121 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7122 HistoryStack.push_back(Field);
7123 RD = Field->getType()->castAs<RecordType>()->getDecl();
7125 RD = cast<RecordDecl>(Next);
7128 // Add a null marker so we know when we've gone back up a level
7129 VisitStack.push_back(nullptr);
7131 for (const auto *FD : RD->fields()) {
7132 QualType QT = FD->getType();
7134 if (ValidTypes.count(QT.getTypePtr()))
7137 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7138 if (ParamType == ValidKernelParam)
7141 if (ParamType == RecordKernelParam) {
7142 VisitStack.push_back(FD);
7146 // OpenCL v1.2 s6.9.p:
7147 // Arguments to kernel functions that are declared to be a struct or union
7148 // do not allow OpenCL objects to be passed as elements of the struct or
7150 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7151 ParamType == PrivatePtrKernelParam) {
7152 S.Diag(Param->getLocation(),
7153 diag::err_record_with_pointers_kernel_param)
7154 << PT->isUnionType()
7157 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7160 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7161 << PD->getDeclName();
7163 // We have an error, now let's go back up through history and show where
7164 // the offending field came from
7165 for (ArrayRef<const FieldDecl *>::const_iterator
7166 I = HistoryStack.begin() + 1,
7167 E = HistoryStack.end();
7169 const FieldDecl *OuterField = *I;
7170 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7171 << OuterField->getType();
7174 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7175 << QT->isPointerType()
7180 } while (!VisitStack.empty());
7184 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7185 TypeSourceInfo *TInfo, LookupResult &Previous,
7186 MultiTemplateParamsArg TemplateParamLists,
7188 QualType R = TInfo->getType();
7190 assert(R.getTypePtr()->isFunctionType());
7192 // TODO: consider using NameInfo for diagnostic.
7193 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7194 DeclarationName Name = NameInfo.getName();
7195 StorageClass SC = getFunctionStorageClass(*this, D);
7197 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7198 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7199 diag::err_invalid_thread)
7200 << DeclSpec::getSpecifierName(TSCS);
7202 if (D.isFirstDeclarationOfMember())
7203 adjustMemberFunctionCC(R, D.isStaticMember());
7205 bool isFriend = false;
7206 FunctionTemplateDecl *FunctionTemplate = nullptr;
7207 bool isExplicitSpecialization = false;
7208 bool isFunctionTemplateSpecialization = false;
7210 bool isDependentClassScopeExplicitSpecialization = false;
7211 bool HasExplicitTemplateArgs = false;
7212 TemplateArgumentListInfo TemplateArgs;
7214 bool isVirtualOkay = false;
7216 DeclContext *OriginalDC = DC;
7217 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7219 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7221 if (!NewFD) return nullptr;
7223 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7224 NewFD->setTopLevelDeclInObjCContainer();
7226 // Set the lexical context. If this is a function-scope declaration, or has a
7227 // C++ scope specifier, or is the object of a friend declaration, the lexical
7228 // context will be different from the semantic context.
7229 NewFD->setLexicalDeclContext(CurContext);
7231 if (IsLocalExternDecl)
7232 NewFD->setLocalExternDecl();
7234 if (getLangOpts().CPlusPlus) {
7235 bool isInline = D.getDeclSpec().isInlineSpecified();
7236 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7237 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7238 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7239 isFriend = D.getDeclSpec().isFriendSpecified();
7240 if (isFriend && !isInline && D.isFunctionDefinition()) {
7241 // C++ [class.friend]p5
7242 // A function can be defined in a friend declaration of a
7243 // class . . . . Such a function is implicitly inline.
7244 NewFD->setImplicitlyInline();
7247 // If this is a method defined in an __interface, and is not a constructor
7248 // or an overloaded operator, then set the pure flag (isVirtual will already
7250 if (const CXXRecordDecl *Parent =
7251 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7252 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7253 NewFD->setPure(true);
7255 // C++ [class.union]p2
7256 // A union can have member functions, but not virtual functions.
7257 if (isVirtual && Parent->isUnion())
7258 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7261 SetNestedNameSpecifier(NewFD, D);
7262 isExplicitSpecialization = false;
7263 isFunctionTemplateSpecialization = false;
7264 if (D.isInvalidType())
7265 NewFD->setInvalidDecl();
7267 // Match up the template parameter lists with the scope specifier, then
7268 // determine whether we have a template or a template specialization.
7269 bool Invalid = false;
7270 if (TemplateParameterList *TemplateParams =
7271 MatchTemplateParametersToScopeSpecifier(
7272 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7273 D.getCXXScopeSpec(),
7274 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7275 ? D.getName().TemplateId
7277 TemplateParamLists, isFriend, isExplicitSpecialization,
7279 if (TemplateParams->size() > 0) {
7280 // This is a function template
7282 // Check that we can declare a template here.
7283 if (CheckTemplateDeclScope(S, TemplateParams))
7284 NewFD->setInvalidDecl();
7286 // A destructor cannot be a template.
7287 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7288 Diag(NewFD->getLocation(), diag::err_destructor_template);
7289 NewFD->setInvalidDecl();
7292 // If we're adding a template to a dependent context, we may need to
7293 // rebuilding some of the types used within the template parameter list,
7294 // now that we know what the current instantiation is.
7295 if (DC->isDependentContext()) {
7296 ContextRAII SavedContext(*this, DC);
7297 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7302 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7303 NewFD->getLocation(),
7304 Name, TemplateParams,
7306 FunctionTemplate->setLexicalDeclContext(CurContext);
7307 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7309 // For source fidelity, store the other template param lists.
7310 if (TemplateParamLists.size() > 1) {
7311 NewFD->setTemplateParameterListsInfo(Context,
7312 TemplateParamLists.size() - 1,
7313 TemplateParamLists.data());
7316 // This is a function template specialization.
7317 isFunctionTemplateSpecialization = true;
7318 // For source fidelity, store all the template param lists.
7319 if (TemplateParamLists.size() > 0)
7320 NewFD->setTemplateParameterListsInfo(Context,
7321 TemplateParamLists.size(),
7322 TemplateParamLists.data());
7324 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7326 // We want to remove the "template<>", found here.
7327 SourceRange RemoveRange = TemplateParams->getSourceRange();
7329 // If we remove the template<> and the name is not a
7330 // template-id, we're actually silently creating a problem:
7331 // the friend declaration will refer to an untemplated decl,
7332 // and clearly the user wants a template specialization. So
7333 // we need to insert '<>' after the name.
7334 SourceLocation InsertLoc;
7335 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7336 InsertLoc = D.getName().getSourceRange().getEnd();
7337 InsertLoc = getLocForEndOfToken(InsertLoc);
7340 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7341 << Name << RemoveRange
7342 << FixItHint::CreateRemoval(RemoveRange)
7343 << FixItHint::CreateInsertion(InsertLoc, "<>");
7348 // All template param lists were matched against the scope specifier:
7349 // this is NOT (an explicit specialization of) a template.
7350 if (TemplateParamLists.size() > 0)
7351 // For source fidelity, store all the template param lists.
7352 NewFD->setTemplateParameterListsInfo(Context,
7353 TemplateParamLists.size(),
7354 TemplateParamLists.data());
7358 NewFD->setInvalidDecl();
7359 if (FunctionTemplate)
7360 FunctionTemplate->setInvalidDecl();
7363 // C++ [dcl.fct.spec]p5:
7364 // The virtual specifier shall only be used in declarations of
7365 // nonstatic class member functions that appear within a
7366 // member-specification of a class declaration; see 10.3.
7368 if (isVirtual && !NewFD->isInvalidDecl()) {
7369 if (!isVirtualOkay) {
7370 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7371 diag::err_virtual_non_function);
7372 } else if (!CurContext->isRecord()) {
7373 // 'virtual' was specified outside of the class.
7374 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7375 diag::err_virtual_out_of_class)
7376 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7377 } else if (NewFD->getDescribedFunctionTemplate()) {
7378 // C++ [temp.mem]p3:
7379 // A member function template shall not be virtual.
7380 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7381 diag::err_virtual_member_function_template)
7382 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7384 // Okay: Add virtual to the method.
7385 NewFD->setVirtualAsWritten(true);
7388 if (getLangOpts().CPlusPlus14 &&
7389 NewFD->getReturnType()->isUndeducedType())
7390 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7393 if (getLangOpts().CPlusPlus14 &&
7394 (NewFD->isDependentContext() ||
7395 (isFriend && CurContext->isDependentContext())) &&
7396 NewFD->getReturnType()->isUndeducedType()) {
7397 // If the function template is referenced directly (for instance, as a
7398 // member of the current instantiation), pretend it has a dependent type.
7399 // This is not really justified by the standard, but is the only sane
7401 // FIXME: For a friend function, we have not marked the function as being
7402 // a friend yet, so 'isDependentContext' on the FD doesn't work.
7403 const FunctionProtoType *FPT =
7404 NewFD->getType()->castAs<FunctionProtoType>();
7406 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7407 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7408 FPT->getExtProtoInfo()));
7411 // C++ [dcl.fct.spec]p3:
7412 // The inline specifier shall not appear on a block scope function
7414 if (isInline && !NewFD->isInvalidDecl()) {
7415 if (CurContext->isFunctionOrMethod()) {
7416 // 'inline' is not allowed on block scope function declaration.
7417 Diag(D.getDeclSpec().getInlineSpecLoc(),
7418 diag::err_inline_declaration_block_scope) << Name
7419 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7423 // C++ [dcl.fct.spec]p6:
7424 // The explicit specifier shall be used only in the declaration of a
7425 // constructor or conversion function within its class definition;
7426 // see 12.3.1 and 12.3.2.
7427 if (isExplicit && !NewFD->isInvalidDecl()) {
7428 if (!CurContext->isRecord()) {
7429 // 'explicit' was specified outside of the class.
7430 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7431 diag::err_explicit_out_of_class)
7432 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7433 } else if (!isa<CXXConstructorDecl>(NewFD) &&
7434 !isa<CXXConversionDecl>(NewFD)) {
7435 // 'explicit' was specified on a function that wasn't a constructor
7436 // or conversion function.
7437 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7438 diag::err_explicit_non_ctor_or_conv_function)
7439 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7444 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7445 // are implicitly inline.
7446 NewFD->setImplicitlyInline();
7448 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7449 // be either constructors or to return a literal type. Therefore,
7450 // destructors cannot be declared constexpr.
7451 if (isa<CXXDestructorDecl>(NewFD))
7452 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7455 // If __module_private__ was specified, mark the function accordingly.
7456 if (D.getDeclSpec().isModulePrivateSpecified()) {
7457 if (isFunctionTemplateSpecialization) {
7458 SourceLocation ModulePrivateLoc
7459 = D.getDeclSpec().getModulePrivateSpecLoc();
7460 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7462 << FixItHint::CreateRemoval(ModulePrivateLoc);
7464 NewFD->setModulePrivate();
7465 if (FunctionTemplate)
7466 FunctionTemplate->setModulePrivate();
7471 if (FunctionTemplate) {
7472 FunctionTemplate->setObjectOfFriendDecl();
7473 FunctionTemplate->setAccess(AS_public);
7475 NewFD->setObjectOfFriendDecl();
7476 NewFD->setAccess(AS_public);
7479 // If a function is defined as defaulted or deleted, mark it as such now.
7480 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7481 // definition kind to FDK_Definition.
7482 switch (D.getFunctionDefinitionKind()) {
7483 case FDK_Declaration:
7484 case FDK_Definition:
7488 NewFD->setDefaulted();
7492 NewFD->setDeletedAsWritten();
7496 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7497 D.isFunctionDefinition()) {
7498 // C++ [class.mfct]p2:
7499 // A member function may be defined (8.4) in its class definition, in
7500 // which case it is an inline member function (7.1.2)
7501 NewFD->setImplicitlyInline();
7504 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7505 !CurContext->isRecord()) {
7506 // C++ [class.static]p1:
7507 // A data or function member of a class may be declared static
7508 // in a class definition, in which case it is a static member of
7511 // Complain about the 'static' specifier if it's on an out-of-line
7512 // member function definition.
7513 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7514 diag::err_static_out_of_line)
7515 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7518 // C++11 [except.spec]p15:
7519 // A deallocation function with no exception-specification is treated
7520 // as if it were specified with noexcept(true).
7521 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7522 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7523 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7524 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7525 NewFD->setType(Context.getFunctionType(
7526 FPT->getReturnType(), FPT->getParamTypes(),
7527 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7530 // Filter out previous declarations that don't match the scope.
7531 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7532 D.getCXXScopeSpec().isNotEmpty() ||
7533 isExplicitSpecialization ||
7534 isFunctionTemplateSpecialization);
7536 // Handle GNU asm-label extension (encoded as an attribute).
7537 if (Expr *E = (Expr*) D.getAsmLabel()) {
7538 // The parser guarantees this is a string.
7539 StringLiteral *SE = cast<StringLiteral>(E);
7540 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7541 SE->getString(), 0));
7542 } else if (!ExtnameUndeclaredIdentifiers.empty() &&
7543 isDeclTUScopedExternallyVisible(NewFD)) {
7544 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7545 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7546 if (I != ExtnameUndeclaredIdentifiers.end()) {
7547 NewFD->addAttr(I->second);
7548 ExtnameUndeclaredIdentifiers.erase(I);
7552 // Copy the parameter declarations from the declarator D to the function
7553 // declaration NewFD, if they are available. First scavenge them into Params.
7554 SmallVector<ParmVarDecl*, 16> Params;
7555 if (D.isFunctionDeclarator()) {
7556 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7558 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7559 // function that takes no arguments, not a function that takes a
7560 // single void argument.
7561 // We let through "const void" here because Sema::GetTypeForDeclarator
7562 // already checks for that case.
7563 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7564 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7565 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7566 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7567 Param->setDeclContext(NewFD);
7568 Params.push_back(Param);
7570 if (Param->isInvalidDecl())
7571 NewFD->setInvalidDecl();
7575 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7576 // When we're declaring a function with a typedef, typeof, etc as in the
7577 // following example, we'll need to synthesize (unnamed)
7578 // parameters for use in the declaration.
7581 // typedef void fn(int);
7585 // Synthesize a parameter for each argument type.
7586 for (const auto &AI : FT->param_types()) {
7587 ParmVarDecl *Param =
7588 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7589 Param->setScopeInfo(0, Params.size());
7590 Params.push_back(Param);
7593 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7594 "Should not need args for typedef of non-prototype fn");
7597 // Finally, we know we have the right number of parameters, install them.
7598 NewFD->setParams(Params);
7600 // Find all anonymous symbols defined during the declaration of this function
7601 // and add to NewFD. This lets us track decls such 'enum Y' in:
7603 // void f(enum Y {AA} x) {}
7605 // which would otherwise incorrectly end up in the translation unit scope.
7606 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7607 DeclsInPrototypeScope.clear();
7609 if (D.getDeclSpec().isNoreturnSpecified())
7611 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7614 // Functions returning a variably modified type violate C99 6.7.5.2p2
7615 // because all functions have linkage.
7616 if (!NewFD->isInvalidDecl() &&
7617 NewFD->getReturnType()->isVariablyModifiedType()) {
7618 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7619 NewFD->setInvalidDecl();
7622 // Apply an implicit SectionAttr if #pragma code_seg is active.
7623 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7624 !NewFD->hasAttr<SectionAttr>()) {
7626 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7627 CodeSegStack.CurrentValue->getString(),
7628 CodeSegStack.CurrentPragmaLocation));
7629 if (UnifySection(CodeSegStack.CurrentValue->getString(),
7630 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7631 ASTContext::PSF_Read,
7633 NewFD->dropAttr<SectionAttr>();
7636 // Handle attributes.
7637 ProcessDeclAttributes(S, NewFD, D);
7639 if (getLangOpts().OpenCL) {
7640 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7641 // type declaration will generate a compilation error.
7642 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7643 if (AddressSpace == LangAS::opencl_local ||
7644 AddressSpace == LangAS::opencl_global ||
7645 AddressSpace == LangAS::opencl_constant) {
7646 Diag(NewFD->getLocation(),
7647 diag::err_opencl_return_value_with_address_space);
7648 NewFD->setInvalidDecl();
7652 if (!getLangOpts().CPlusPlus) {
7653 // Perform semantic checking on the function declaration.
7654 bool isExplicitSpecialization=false;
7655 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7656 CheckMain(NewFD, D.getDeclSpec());
7658 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7659 CheckMSVCRTEntryPoint(NewFD);
7661 if (!NewFD->isInvalidDecl())
7662 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7663 isExplicitSpecialization));
7664 else if (!Previous.empty())
7665 // Recover gracefully from an invalid redeclaration.
7666 D.setRedeclaration(true);
7667 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7668 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7669 "previous declaration set still overloaded");
7671 // Diagnose no-prototype function declarations with calling conventions that
7672 // don't support variadic calls. Only do this in C and do it after merging
7673 // possibly prototyped redeclarations.
7674 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7675 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7676 CallingConv CC = FT->getExtInfo().getCC();
7677 if (!supportsVariadicCall(CC)) {
7678 // Windows system headers sometimes accidentally use stdcall without
7679 // (void) parameters, so we relax this to a warning.
7681 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7682 Diag(NewFD->getLocation(), DiagID)
7683 << FunctionType::getNameForCallConv(CC);
7687 // C++11 [replacement.functions]p3:
7688 // The program's definitions shall not be specified as inline.
7690 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7692 // Suppress the diagnostic if the function is __attribute__((used)), since
7693 // that forces an external definition to be emitted.
7694 if (D.getDeclSpec().isInlineSpecified() &&
7695 NewFD->isReplaceableGlobalAllocationFunction() &&
7696 !NewFD->hasAttr<UsedAttr>())
7697 Diag(D.getDeclSpec().getInlineSpecLoc(),
7698 diag::ext_operator_new_delete_declared_inline)
7699 << NewFD->getDeclName();
7701 // If the declarator is a template-id, translate the parser's template
7702 // argument list into our AST format.
7703 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7704 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7705 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7706 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7707 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7708 TemplateId->NumArgs);
7709 translateTemplateArguments(TemplateArgsPtr,
7712 HasExplicitTemplateArgs = true;
7714 if (NewFD->isInvalidDecl()) {
7715 HasExplicitTemplateArgs = false;
7716 } else if (FunctionTemplate) {
7717 // Function template with explicit template arguments.
7718 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7719 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7721 HasExplicitTemplateArgs = false;
7723 assert((isFunctionTemplateSpecialization ||
7724 D.getDeclSpec().isFriendSpecified()) &&
7725 "should have a 'template<>' for this decl");
7726 // "friend void foo<>(int);" is an implicit specialization decl.
7727 isFunctionTemplateSpecialization = true;
7729 } else if (isFriend && isFunctionTemplateSpecialization) {
7730 // This combination is only possible in a recovery case; the user
7731 // wrote something like:
7732 // template <> friend void foo(int);
7733 // which we're recovering from as if the user had written:
7734 // friend void foo<>(int);
7735 // Go ahead and fake up a template id.
7736 HasExplicitTemplateArgs = true;
7737 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7738 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7741 // If it's a friend (and only if it's a friend), it's possible
7742 // that either the specialized function type or the specialized
7743 // template is dependent, and therefore matching will fail. In
7744 // this case, don't check the specialization yet.
7745 bool InstantiationDependent = false;
7746 if (isFunctionTemplateSpecialization && isFriend &&
7747 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7748 TemplateSpecializationType::anyDependentTemplateArguments(
7749 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7750 InstantiationDependent))) {
7751 assert(HasExplicitTemplateArgs &&
7752 "friend function specialization without template args");
7753 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7755 NewFD->setInvalidDecl();
7756 } else if (isFunctionTemplateSpecialization) {
7757 if (CurContext->isDependentContext() && CurContext->isRecord()
7759 isDependentClassScopeExplicitSpecialization = true;
7760 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7761 diag::ext_function_specialization_in_class :
7762 diag::err_function_specialization_in_class)
7763 << NewFD->getDeclName();
7764 } else if (CheckFunctionTemplateSpecialization(NewFD,
7765 (HasExplicitTemplateArgs ? &TemplateArgs
7768 NewFD->setInvalidDecl();
7771 // A storage-class-specifier shall not be specified in an explicit
7772 // specialization (14.7.3)
7773 FunctionTemplateSpecializationInfo *Info =
7774 NewFD->getTemplateSpecializationInfo();
7775 if (Info && SC != SC_None) {
7776 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7777 Diag(NewFD->getLocation(),
7778 diag::err_explicit_specialization_inconsistent_storage_class)
7780 << FixItHint::CreateRemoval(
7781 D.getDeclSpec().getStorageClassSpecLoc());
7784 Diag(NewFD->getLocation(),
7785 diag::ext_explicit_specialization_storage_class)
7786 << FixItHint::CreateRemoval(
7787 D.getDeclSpec().getStorageClassSpecLoc());
7790 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7791 if (CheckMemberSpecialization(NewFD, Previous))
7792 NewFD->setInvalidDecl();
7795 // Perform semantic checking on the function declaration.
7796 if (!isDependentClassScopeExplicitSpecialization) {
7797 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7798 CheckMain(NewFD, D.getDeclSpec());
7800 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7801 CheckMSVCRTEntryPoint(NewFD);
7803 if (!NewFD->isInvalidDecl())
7804 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7805 isExplicitSpecialization));
7806 else if (!Previous.empty())
7807 // Recover gracefully from an invalid redeclaration.
7808 D.setRedeclaration(true);
7811 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7812 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7813 "previous declaration set still overloaded");
7815 NamedDecl *PrincipalDecl = (FunctionTemplate
7816 ? cast<NamedDecl>(FunctionTemplate)
7819 if (isFriend && D.isRedeclaration()) {
7820 AccessSpecifier Access = AS_public;
7821 if (!NewFD->isInvalidDecl())
7822 Access = NewFD->getPreviousDecl()->getAccess();
7824 NewFD->setAccess(Access);
7825 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7828 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7829 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7830 PrincipalDecl->setNonMemberOperator();
7832 // If we have a function template, check the template parameter
7833 // list. This will check and merge default template arguments.
7834 if (FunctionTemplate) {
7835 FunctionTemplateDecl *PrevTemplate =
7836 FunctionTemplate->getPreviousDecl();
7837 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7838 PrevTemplate ? PrevTemplate->getTemplateParameters()
7840 D.getDeclSpec().isFriendSpecified()
7841 ? (D.isFunctionDefinition()
7842 ? TPC_FriendFunctionTemplateDefinition
7843 : TPC_FriendFunctionTemplate)
7844 : (D.getCXXScopeSpec().isSet() &&
7845 DC && DC->isRecord() &&
7846 DC->isDependentContext())
7847 ? TPC_ClassTemplateMember
7848 : TPC_FunctionTemplate);
7851 if (NewFD->isInvalidDecl()) {
7852 // Ignore all the rest of this.
7853 } else if (!D.isRedeclaration()) {
7854 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7856 // Fake up an access specifier if it's supposed to be a class member.
7857 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7858 NewFD->setAccess(AS_public);
7860 // Qualified decls generally require a previous declaration.
7861 if (D.getCXXScopeSpec().isSet()) {
7862 // ...with the major exception of templated-scope or
7863 // dependent-scope friend declarations.
7865 // TODO: we currently also suppress this check in dependent
7866 // contexts because (1) the parameter depth will be off when
7867 // matching friend templates and (2) we might actually be
7868 // selecting a friend based on a dependent factor. But there
7869 // are situations where these conditions don't apply and we
7870 // can actually do this check immediately.
7872 (TemplateParamLists.size() ||
7873 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7874 CurContext->isDependentContext())) {
7877 // The user tried to provide an out-of-line definition for a
7878 // function that is a member of a class or namespace, but there
7879 // was no such member function declared (C++ [class.mfct]p2,
7880 // C++ [namespace.memdef]p2). For example:
7886 // void X::f() { } // ill-formed
7888 // Complain about this problem, and attempt to suggest close
7889 // matches (e.g., those that differ only in cv-qualifiers and
7890 // whether the parameter types are references).
7892 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7893 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7894 AddToScope = ExtraArgs.AddToScope;
7899 // Unqualified local friend declarations are required to resolve
7901 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7902 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7903 *this, Previous, NewFD, ExtraArgs, true, S)) {
7904 AddToScope = ExtraArgs.AddToScope;
7909 } else if (!D.isFunctionDefinition() &&
7910 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7911 !isFriend && !isFunctionTemplateSpecialization &&
7912 !isExplicitSpecialization) {
7913 // An out-of-line member function declaration must also be a
7914 // definition (C++ [class.mfct]p2).
7915 // Note that this is not the case for explicit specializations of
7916 // function templates or member functions of class templates, per
7917 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7918 // extension for compatibility with old SWIG code which likes to
7920 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7921 << D.getCXXScopeSpec().getRange();
7925 ProcessPragmaWeak(S, NewFD);
7926 checkAttributesAfterMerging(*this, *NewFD);
7928 AddKnownFunctionAttributes(NewFD);
7930 if (NewFD->hasAttr<OverloadableAttr>() &&
7931 !NewFD->getType()->getAs<FunctionProtoType>()) {
7932 Diag(NewFD->getLocation(),
7933 diag::err_attribute_overloadable_no_prototype)
7936 // Turn this into a variadic function with no parameters.
7937 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7938 FunctionProtoType::ExtProtoInfo EPI(
7939 Context.getDefaultCallingConvention(true, false));
7940 EPI.Variadic = true;
7941 EPI.ExtInfo = FT->getExtInfo();
7943 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7947 // If there's a #pragma GCC visibility in scope, and this isn't a class
7948 // member, set the visibility of this function.
7949 if (!DC->isRecord() && NewFD->isExternallyVisible())
7950 AddPushedVisibilityAttribute(NewFD);
7952 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7953 // marking the function.
7954 AddCFAuditedAttribute(NewFD);
7956 // If this is a function definition, check if we have to apply optnone due to
7958 if(D.isFunctionDefinition())
7959 AddRangeBasedOptnone(NewFD);
7961 // If this is the first declaration of an extern C variable, update
7962 // the map of such variables.
7963 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7964 isIncompleteDeclExternC(*this, NewFD))
7965 RegisterLocallyScopedExternCDecl(NewFD, S);
7967 // Set this FunctionDecl's range up to the right paren.
7968 NewFD->setRangeEnd(D.getSourceRange().getEnd());
7970 if (D.isRedeclaration() && !Previous.empty()) {
7971 checkDLLAttributeRedeclaration(
7972 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7973 isExplicitSpecialization || isFunctionTemplateSpecialization);
7976 if (getLangOpts().CPlusPlus) {
7977 if (FunctionTemplate) {
7978 if (NewFD->isInvalidDecl())
7979 FunctionTemplate->setInvalidDecl();
7980 return FunctionTemplate;
7984 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7985 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7986 if ((getLangOpts().OpenCLVersion >= 120)
7987 && (SC == SC_Static)) {
7988 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7992 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7993 if (!NewFD->getReturnType()->isVoidType()) {
7994 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7995 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7996 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8001 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8002 for (auto Param : NewFD->params())
8003 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8006 MarkUnusedFileScopedDecl(NewFD);
8008 if (getLangOpts().CUDA)
8009 if (IdentifierInfo *II = NewFD->getIdentifier())
8010 if (!NewFD->isInvalidDecl() &&
8011 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8012 if (II->isStr("cudaConfigureCall")) {
8013 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8014 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8016 Context.setcudaConfigureCallDecl(NewFD);
8020 // Here we have an function template explicit specialization at class scope.
8021 // The actually specialization will be postponed to template instatiation
8022 // time via the ClassScopeFunctionSpecializationDecl node.
8023 if (isDependentClassScopeExplicitSpecialization) {
8024 ClassScopeFunctionSpecializationDecl *NewSpec =
8025 ClassScopeFunctionSpecializationDecl::Create(
8026 Context, CurContext, SourceLocation(),
8027 cast<CXXMethodDecl>(NewFD),
8028 HasExplicitTemplateArgs, TemplateArgs);
8029 CurContext->addDecl(NewSpec);
8036 /// \brief Perform semantic checking of a new function declaration.
8038 /// Performs semantic analysis of the new function declaration
8039 /// NewFD. This routine performs all semantic checking that does not
8040 /// require the actual declarator involved in the declaration, and is
8041 /// used both for the declaration of functions as they are parsed
8042 /// (called via ActOnDeclarator) and for the declaration of functions
8043 /// that have been instantiated via C++ template instantiation (called
8044 /// via InstantiateDecl).
8046 /// \param IsExplicitSpecialization whether this new function declaration is
8047 /// an explicit specialization of the previous declaration.
8049 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8051 /// \returns true if the function declaration is a redeclaration.
8052 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8053 LookupResult &Previous,
8054 bool IsExplicitSpecialization) {
8055 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8056 "Variably modified return types are not handled here");
8058 // Determine whether the type of this function should be merged with
8059 // a previous visible declaration. This never happens for functions in C++,
8060 // and always happens in C if the previous declaration was visible.
8061 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8062 !Previous.isShadowed();
8064 // Filter out any non-conflicting previous declarations.
8065 filterNonConflictingPreviousDecls(*this, NewFD, Previous);
8067 bool Redeclaration = false;
8068 NamedDecl *OldDecl = nullptr;
8070 // Merge or overload the declaration with an existing declaration of
8071 // the same name, if appropriate.
8072 if (!Previous.empty()) {
8073 // Determine whether NewFD is an overload of PrevDecl or
8074 // a declaration that requires merging. If it's an overload,
8075 // there's no more work to do here; we'll just add the new
8076 // function to the scope.
8077 if (!AllowOverloadingOfFunction(Previous, Context)) {
8078 NamedDecl *Candidate = Previous.getFoundDecl();
8079 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8080 Redeclaration = true;
8081 OldDecl = Candidate;
8084 switch (CheckOverload(S, NewFD, Previous, OldDecl,
8085 /*NewIsUsingDecl*/ false)) {
8087 Redeclaration = true;
8090 case Ovl_NonFunction:
8091 Redeclaration = true;
8095 Redeclaration = false;
8099 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8100 // If a function name is overloadable in C, then every function
8101 // with that name must be marked "overloadable".
8102 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8103 << Redeclaration << NewFD;
8104 NamedDecl *OverloadedDecl = nullptr;
8106 OverloadedDecl = OldDecl;
8107 else if (!Previous.empty())
8108 OverloadedDecl = Previous.getRepresentativeDecl();
8110 Diag(OverloadedDecl->getLocation(),
8111 diag::note_attribute_overloadable_prev_overload);
8112 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8117 // Check for a previous extern "C" declaration with this name.
8118 if (!Redeclaration &&
8119 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8120 filterNonConflictingPreviousDecls(*this, NewFD, Previous);
8121 if (!Previous.empty()) {
8122 // This is an extern "C" declaration with the same name as a previous
8123 // declaration, and thus redeclares that entity...
8124 Redeclaration = true;
8125 OldDecl = Previous.getFoundDecl();
8126 MergeTypeWithPrevious = false;
8128 // ... except in the presence of __attribute__((overloadable)).
8129 if (OldDecl->hasAttr<OverloadableAttr>()) {
8130 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8131 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8132 << Redeclaration << NewFD;
8133 Diag(Previous.getFoundDecl()->getLocation(),
8134 diag::note_attribute_overloadable_prev_overload);
8135 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8137 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8138 Redeclaration = false;
8145 // C++11 [dcl.constexpr]p8:
8146 // A constexpr specifier for a non-static member function that is not
8147 // a constructor declares that member function to be const.
8149 // This needs to be delayed until we know whether this is an out-of-line
8150 // definition of a static member function.
8152 // This rule is not present in C++1y, so we produce a backwards
8153 // compatibility warning whenever it happens in C++11.
8154 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8155 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8156 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8157 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8158 CXXMethodDecl *OldMD = nullptr;
8160 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8161 if (!OldMD || !OldMD->isStatic()) {
8162 const FunctionProtoType *FPT =
8163 MD->getType()->castAs<FunctionProtoType>();
8164 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8165 EPI.TypeQuals |= Qualifiers::Const;
8166 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8167 FPT->getParamTypes(), EPI));
8169 // Warn that we did this, if we're not performing template instantiation.
8170 // In that case, we'll have warned already when the template was defined.
8171 if (ActiveTemplateInstantiations.empty()) {
8172 SourceLocation AddConstLoc;
8173 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8174 .IgnoreParens().getAs<FunctionTypeLoc>())
8175 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8177 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8178 << FixItHint::CreateInsertion(AddConstLoc, " const");
8183 if (Redeclaration) {
8184 // NewFD and OldDecl represent declarations that need to be
8186 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8187 NewFD->setInvalidDecl();
8188 return Redeclaration;
8192 Previous.addDecl(OldDecl);
8194 if (FunctionTemplateDecl *OldTemplateDecl
8195 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8196 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8197 FunctionTemplateDecl *NewTemplateDecl
8198 = NewFD->getDescribedFunctionTemplate();
8199 assert(NewTemplateDecl && "Template/non-template mismatch");
8200 if (CXXMethodDecl *Method
8201 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8202 Method->setAccess(OldTemplateDecl->getAccess());
8203 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8206 // If this is an explicit specialization of a member that is a function
8207 // template, mark it as a member specialization.
8208 if (IsExplicitSpecialization &&
8209 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8210 NewTemplateDecl->setMemberSpecialization();
8211 assert(OldTemplateDecl->isMemberSpecialization());
8215 // This needs to happen first so that 'inline' propagates.
8216 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8218 if (isa<CXXMethodDecl>(NewFD))
8219 NewFD->setAccess(OldDecl->getAccess());
8223 // Semantic checking for this function declaration (in isolation).
8225 if (getLangOpts().CPlusPlus) {
8226 // C++-specific checks.
8227 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8228 CheckConstructor(Constructor);
8229 } else if (CXXDestructorDecl *Destructor =
8230 dyn_cast<CXXDestructorDecl>(NewFD)) {
8231 CXXRecordDecl *Record = Destructor->getParent();
8232 QualType ClassType = Context.getTypeDeclType(Record);
8234 // FIXME: Shouldn't we be able to perform this check even when the class
8235 // type is dependent? Both gcc and edg can handle that.
8236 if (!ClassType->isDependentType()) {
8237 DeclarationName Name
8238 = Context.DeclarationNames.getCXXDestructorName(
8239 Context.getCanonicalType(ClassType));
8240 if (NewFD->getDeclName() != Name) {
8241 Diag(NewFD->getLocation(), diag::err_destructor_name);
8242 NewFD->setInvalidDecl();
8243 return Redeclaration;
8246 } else if (CXXConversionDecl *Conversion
8247 = dyn_cast<CXXConversionDecl>(NewFD)) {
8248 ActOnConversionDeclarator(Conversion);
8251 // Find any virtual functions that this function overrides.
8252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8253 if (!Method->isFunctionTemplateSpecialization() &&
8254 !Method->getDescribedFunctionTemplate() &&
8255 Method->isCanonicalDecl()) {
8256 if (AddOverriddenMethods(Method->getParent(), Method)) {
8257 // If the function was marked as "static", we have a problem.
8258 if (NewFD->getStorageClass() == SC_Static) {
8259 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8264 if (Method->isStatic())
8265 checkThisInStaticMemberFunctionType(Method);
8268 // Extra checking for C++ overloaded operators (C++ [over.oper]).
8269 if (NewFD->isOverloadedOperator() &&
8270 CheckOverloadedOperatorDeclaration(NewFD)) {
8271 NewFD->setInvalidDecl();
8272 return Redeclaration;
8275 // Extra checking for C++0x literal operators (C++0x [over.literal]).
8276 if (NewFD->getLiteralIdentifier() &&
8277 CheckLiteralOperatorDeclaration(NewFD)) {
8278 NewFD->setInvalidDecl();
8279 return Redeclaration;
8282 // In C++, check default arguments now that we have merged decls. Unless
8283 // the lexical context is the class, because in this case this is done
8284 // during delayed parsing anyway.
8285 if (!CurContext->isRecord())
8286 CheckCXXDefaultArguments(NewFD);
8288 // If this function declares a builtin function, check the type of this
8289 // declaration against the expected type for the builtin.
8290 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8291 ASTContext::GetBuiltinTypeError Error;
8292 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8293 QualType T = Context.GetBuiltinType(BuiltinID, Error);
8294 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8295 // The type of this function differs from the type of the builtin,
8296 // so forget about the builtin entirely.
8297 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8301 // If this function is declared as being extern "C", then check to see if
8302 // the function returns a UDT (class, struct, or union type) that is not C
8303 // compatible, and if it does, warn the user.
8304 // But, issue any diagnostic on the first declaration only.
8305 if (Previous.empty() && NewFD->isExternC()) {
8306 QualType R = NewFD->getReturnType();
8307 if (R->isIncompleteType() && !R->isVoidType())
8308 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8310 else if (!R.isPODType(Context) && !R->isVoidType() &&
8311 !R->isObjCObjectPointerType())
8312 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8315 return Redeclaration;
8318 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8319 // C++11 [basic.start.main]p3:
8320 // A program that [...] declares main to be inline, static or
8321 // constexpr is ill-formed.
8322 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8323 // appear in a declaration of main.
8324 // static main is not an error under C99, but we should warn about it.
8325 // We accept _Noreturn main as an extension.
8326 if (FD->getStorageClass() == SC_Static)
8327 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8328 ? diag::err_static_main : diag::warn_static_main)
8329 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8330 if (FD->isInlineSpecified())
8331 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8332 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8333 if (DS.isNoreturnSpecified()) {
8334 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8335 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8336 Diag(NoreturnLoc, diag::ext_noreturn_main);
8337 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8338 << FixItHint::CreateRemoval(NoreturnRange);
8340 if (FD->isConstexpr()) {
8341 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8342 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8343 FD->setConstexpr(false);
8346 if (getLangOpts().OpenCL) {
8347 Diag(FD->getLocation(), diag::err_opencl_no_main)
8348 << FD->hasAttr<OpenCLKernelAttr>();
8349 FD->setInvalidDecl();
8353 QualType T = FD->getType();
8354 assert(T->isFunctionType() && "function decl is not of function type");
8355 const FunctionType* FT = T->castAs<FunctionType>();
8357 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8358 // In C with GNU extensions we allow main() to have non-integer return
8359 // type, but we should warn about the extension, and we disable the
8360 // implicit-return-zero rule.
8362 // GCC in C mode accepts qualified 'int'.
8363 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8364 FD->setHasImplicitReturnZero(true);
8366 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8367 SourceRange RTRange = FD->getReturnTypeSourceRange();
8368 if (RTRange.isValid())
8369 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8370 << FixItHint::CreateReplacement(RTRange, "int");
8373 // In C and C++, main magically returns 0 if you fall off the end;
8374 // set the flag which tells us that.
8375 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8377 // All the standards say that main() should return 'int'.
8378 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8379 FD->setHasImplicitReturnZero(true);
8381 // Otherwise, this is just a flat-out error.
8382 SourceRange RTRange = FD->getReturnTypeSourceRange();
8383 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8384 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8386 FD->setInvalidDecl(true);
8390 // Treat protoless main() as nullary.
8391 if (isa<FunctionNoProtoType>(FT)) return;
8393 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8394 unsigned nparams = FTP->getNumParams();
8395 assert(FD->getNumParams() == nparams);
8397 bool HasExtraParameters = (nparams > 3);
8399 if (FTP->isVariadic()) {
8400 Diag(FD->getLocation(), diag::ext_variadic_main);
8401 // FIXME: if we had information about the location of the ellipsis, we
8402 // could add a FixIt hint to remove it as a parameter.
8405 // Darwin passes an undocumented fourth argument of type char**. If
8406 // other platforms start sprouting these, the logic below will start
8408 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8409 HasExtraParameters = false;
8411 if (HasExtraParameters) {
8412 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8413 FD->setInvalidDecl(true);
8417 // FIXME: a lot of the following diagnostics would be improved
8418 // if we had some location information about types.
8421 Context.getPointerType(Context.getPointerType(Context.CharTy));
8422 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8424 for (unsigned i = 0; i < nparams; ++i) {
8425 QualType AT = FTP->getParamType(i);
8427 bool mismatch = true;
8429 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8431 else if (Expected[i] == CharPP) {
8432 // As an extension, the following forms are okay:
8434 // char const * const *
8437 QualifierCollector qs;
8438 const PointerType* PT;
8439 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8440 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8441 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8444 mismatch = !qs.empty();
8449 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8450 // TODO: suggest replacing given type with expected type
8451 FD->setInvalidDecl(true);
8455 if (nparams == 1 && !FD->isInvalidDecl()) {
8456 Diag(FD->getLocation(), diag::warn_main_one_arg);
8459 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8460 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8461 FD->setInvalidDecl();
8465 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8466 QualType T = FD->getType();
8467 assert(T->isFunctionType() && "function decl is not of function type");
8468 const FunctionType *FT = T->castAs<FunctionType>();
8470 // Set an implicit return of 'zero' if the function can return some integral,
8471 // enumeration, pointer or nullptr type.
8472 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8473 FT->getReturnType()->isAnyPointerType() ||
8474 FT->getReturnType()->isNullPtrType())
8475 // DllMain is exempt because a return value of zero means it failed.
8476 if (FD->getName() != "DllMain")
8477 FD->setHasImplicitReturnZero(true);
8479 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8480 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8481 FD->setInvalidDecl();
8485 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8486 // FIXME: Need strict checking. In C89, we need to check for
8487 // any assignment, increment, decrement, function-calls, or
8488 // commas outside of a sizeof. In C99, it's the same list,
8489 // except that the aforementioned are allowed in unevaluated
8490 // expressions. Everything else falls under the
8491 // "may accept other forms of constant expressions" exception.
8492 // (We never end up here for C++, so the constant expression
8493 // rules there don't matter.)
8494 const Expr *Culprit;
8495 if (Init->isConstantInitializer(Context, false, &Culprit))
8497 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8498 << Culprit->getSourceRange();
8503 // Visits an initialization expression to see if OrigDecl is evaluated in
8504 // its own initialization and throws a warning if it does.
8505 class SelfReferenceChecker
8506 : public EvaluatedExprVisitor<SelfReferenceChecker> {
8511 bool isReferenceType;
8514 llvm::SmallVector<unsigned, 4> InitFieldIndex;
8516 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8518 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8519 S(S), OrigDecl(OrigDecl) {
8521 isRecordType = false;
8522 isReferenceType = false;
8524 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8525 isPODType = VD->getType().isPODType(S.Context);
8526 isRecordType = VD->getType()->isRecordType();
8527 isReferenceType = VD->getType()->isReferenceType();
8531 // For most expressions, just call the visitor. For initializer lists,
8532 // track the index of the field being initialized since fields are
8533 // initialized in order allowing use of previously initialized fields.
8534 void CheckExpr(Expr *E) {
8535 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8541 // Track and increment the index here.
8543 InitFieldIndex.push_back(0);
8544 for (auto Child : InitList->children()) {
8545 CheckExpr(cast<Expr>(Child));
8546 ++InitFieldIndex.back();
8548 InitFieldIndex.pop_back();
8551 // Returns true if MemberExpr is checked and no futher checking is needed.
8552 // Returns false if additional checking is required.
8553 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8554 llvm::SmallVector<FieldDecl*, 4> Fields;
8556 bool ReferenceField = false;
8558 // Get the field memebers used.
8559 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8560 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8563 Fields.push_back(FD);
8564 if (FD->getType()->isReferenceType())
8565 ReferenceField = true;
8566 Base = ME->getBase()->IgnoreParenImpCasts();
8569 // Keep checking only if the base Decl is the same.
8570 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8571 if (!DRE || DRE->getDecl() != OrigDecl)
8574 // A reference field can be bound to an unininitialized field.
8575 if (CheckReference && !ReferenceField)
8578 // Convert FieldDecls to their index number.
8579 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8580 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8581 UsedFieldIndex.push_back((*I)->getFieldIndex());
8584 // See if a warning is needed by checking the first difference in index
8585 // numbers. If field being used has index less than the field being
8586 // initialized, then the use is safe.
8587 for (auto UsedIter = UsedFieldIndex.begin(),
8588 UsedEnd = UsedFieldIndex.end(),
8589 OrigIter = InitFieldIndex.begin(),
8590 OrigEnd = InitFieldIndex.end();
8591 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8592 if (*UsedIter < *OrigIter)
8594 if (*UsedIter > *OrigIter)
8598 // TODO: Add a different warning which will print the field names.
8599 HandleDeclRefExpr(DRE);
8603 // For most expressions, the cast is directly above the DeclRefExpr.
8604 // For conditional operators, the cast can be outside the conditional
8605 // operator if both expressions are DeclRefExpr's.
8606 void HandleValue(Expr *E) {
8607 E = E->IgnoreParens();
8608 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8609 HandleDeclRefExpr(DRE);
8613 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8614 Visit(CO->getCond());
8615 HandleValue(CO->getTrueExpr());
8616 HandleValue(CO->getFalseExpr());
8620 if (BinaryConditionalOperator *BCO =
8621 dyn_cast<BinaryConditionalOperator>(E)) {
8622 Visit(BCO->getCond());
8623 HandleValue(BCO->getFalseExpr());
8627 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8628 HandleValue(OVE->getSourceExpr());
8632 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8633 if (BO->getOpcode() == BO_Comma) {
8634 Visit(BO->getLHS());
8635 HandleValue(BO->getRHS());
8640 if (isa<MemberExpr>(E)) {
8642 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8643 false /*CheckReference*/))
8647 Expr *Base = E->IgnoreParenImpCasts();
8648 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8649 // Check for static member variables and don't warn on them.
8650 if (!isa<FieldDecl>(ME->getMemberDecl()))
8652 Base = ME->getBase()->IgnoreParenImpCasts();
8654 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8655 HandleDeclRefExpr(DRE);
8662 // Reference types not handled in HandleValue are handled here since all
8663 // uses of references are bad, not just r-value uses.
8664 void VisitDeclRefExpr(DeclRefExpr *E) {
8665 if (isReferenceType)
8666 HandleDeclRefExpr(E);
8669 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8670 if (E->getCastKind() == CK_LValueToRValue) {
8671 HandleValue(E->getSubExpr());
8675 Inherited::VisitImplicitCastExpr(E);
8678 void VisitMemberExpr(MemberExpr *E) {
8680 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8684 // Don't warn on arrays since they can be treated as pointers.
8685 if (E->getType()->canDecayToPointerType()) return;
8687 // Warn when a non-static method call is followed by non-static member
8688 // field accesses, which is followed by a DeclRefExpr.
8689 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8690 bool Warn = (MD && !MD->isStatic());
8691 Expr *Base = E->getBase()->IgnoreParenImpCasts();
8692 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8693 if (!isa<FieldDecl>(ME->getMemberDecl()))
8695 Base = ME->getBase()->IgnoreParenImpCasts();
8698 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8700 HandleDeclRefExpr(DRE);
8704 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8705 // Visit that expression.
8709 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8710 Expr *Callee = E->getCallee();
8712 if (isa<UnresolvedLookupExpr>(Callee))
8713 return Inherited::VisitCXXOperatorCallExpr(E);
8716 for (auto Arg: E->arguments())
8717 HandleValue(Arg->IgnoreParenImpCasts());
8720 void VisitUnaryOperator(UnaryOperator *E) {
8721 // For POD record types, addresses of its own members are well-defined.
8722 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8723 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8725 HandleValue(E->getSubExpr());
8729 if (E->isIncrementDecrementOp()) {
8730 HandleValue(E->getSubExpr());
8734 Inherited::VisitUnaryOperator(E);
8737 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8739 void VisitCXXConstructExpr(CXXConstructExpr *E) {
8740 if (E->getConstructor()->isCopyConstructor()) {
8741 Expr *ArgExpr = E->getArg(0);
8742 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8743 if (ILE->getNumInits() == 1)
8744 ArgExpr = ILE->getInit(0);
8745 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8746 if (ICE->getCastKind() == CK_NoOp)
8747 ArgExpr = ICE->getSubExpr();
8748 HandleValue(ArgExpr);
8751 Inherited::VisitCXXConstructExpr(E);
8754 void VisitCallExpr(CallExpr *E) {
8755 // Treat std::move as a use.
8756 if (E->getNumArgs() == 1) {
8757 if (FunctionDecl *FD = E->getDirectCallee()) {
8758 if (FD->isInStdNamespace() && FD->getIdentifier() &&
8759 FD->getIdentifier()->isStr("move")) {
8760 HandleValue(E->getArg(0));
8766 Inherited::VisitCallExpr(E);
8769 void VisitBinaryOperator(BinaryOperator *E) {
8770 if (E->isCompoundAssignmentOp()) {
8771 HandleValue(E->getLHS());
8776 Inherited::VisitBinaryOperator(E);
8779 // A custom visitor for BinaryConditionalOperator is needed because the
8780 // regular visitor would check the condition and true expression separately
8781 // but both point to the same place giving duplicate diagnostics.
8782 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8783 Visit(E->getCond());
8784 Visit(E->getFalseExpr());
8787 void HandleDeclRefExpr(DeclRefExpr *DRE) {
8788 Decl* ReferenceDecl = DRE->getDecl();
8789 if (OrigDecl != ReferenceDecl) return;
8791 if (isReferenceType) {
8792 diag = diag::warn_uninit_self_reference_in_reference_init;
8793 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8794 diag = diag::warn_static_self_reference_in_init;
8795 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
8796 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
8797 DRE->getDecl()->getType()->isRecordType()) {
8798 diag = diag::warn_uninit_self_reference_in_init;
8800 // Local variables will be handled by the CFG analysis.
8804 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8806 << DRE->getNameInfo().getName()
8807 << OrigDecl->getLocation()
8808 << DRE->getSourceRange());
8812 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8813 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8815 // Parameters arguments are occassionially constructed with itself,
8816 // for instance, in recursive functions. Skip them.
8817 if (isa<ParmVarDecl>(OrigDecl))
8820 E = E->IgnoreParens();
8822 // Skip checking T a = a where T is not a record or reference type.
8823 // Doing so is a way to silence uninitialized warnings.
8824 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8825 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8826 if (ICE->getCastKind() == CK_LValueToRValue)
8827 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8828 if (DRE->getDecl() == OrigDecl)
8831 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8835 /// AddInitializerToDecl - Adds the initializer Init to the
8836 /// declaration dcl. If DirectInit is true, this is C++ direct
8837 /// initialization rather than copy initialization.
8838 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8839 bool DirectInit, bool TypeMayContainAuto) {
8840 // If there is no declaration, there was an error parsing it. Just ignore
8842 if (!RealDecl || RealDecl->isInvalidDecl()) {
8843 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
8847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8848 // Pure-specifiers are handled in ActOnPureSpecifier.
8849 Diag(Method->getLocation(), diag::err_member_function_initialization)
8850 << Method->getDeclName() << Init->getSourceRange();
8851 Method->setInvalidDecl();
8855 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8857 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8858 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8859 RealDecl->setInvalidDecl();
8862 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8864 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8865 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8866 // Attempt typo correction early so that the type of the init expression can
8867 // be deduced based on the chosen correction:if the original init contains a
8869 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
8870 if (!Res.isUsable()) {
8871 RealDecl->setInvalidDecl();
8875 if (Res.get() != Init) {
8878 CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8881 Expr *DeduceInit = Init;
8882 // Initializer could be a C++ direct-initializer. Deduction only works if it
8883 // contains exactly one expression.
8884 if (CXXDirectInit) {
8885 if (CXXDirectInit->getNumExprs() == 0) {
8886 // It isn't possible to write this directly, but it is possible to
8887 // end up in this situation with "auto x(some_pack...);"
8888 Diag(CXXDirectInit->getLocStart(),
8889 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8890 : diag::err_auto_var_init_no_expression)
8891 << VDecl->getDeclName() << VDecl->getType()
8892 << VDecl->getSourceRange();
8893 RealDecl->setInvalidDecl();
8895 } else if (CXXDirectInit->getNumExprs() > 1) {
8896 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8897 VDecl->isInitCapture()
8898 ? diag::err_init_capture_multiple_expressions
8899 : diag::err_auto_var_init_multiple_expressions)
8900 << VDecl->getDeclName() << VDecl->getType()
8901 << VDecl->getSourceRange();
8902 RealDecl->setInvalidDecl();
8905 DeduceInit = CXXDirectInit->getExpr(0);
8906 if (isa<InitListExpr>(DeduceInit))
8907 Diag(CXXDirectInit->getLocStart(),
8908 diag::err_auto_var_init_paren_braces)
8909 << VDecl->getDeclName() << VDecl->getType()
8910 << VDecl->getSourceRange();
8914 // Expressions default to 'id' when we're in a debugger.
8915 bool DefaultedToAuto = false;
8916 if (getLangOpts().DebuggerCastResultToId &&
8917 Init->getType() == Context.UnknownAnyTy) {
8918 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8919 if (Result.isInvalid()) {
8920 VDecl->setInvalidDecl();
8923 Init = Result.get();
8924 DefaultedToAuto = true;
8927 QualType DeducedType;
8928 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8930 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8931 if (DeducedType.isNull()) {
8932 RealDecl->setInvalidDecl();
8935 VDecl->setType(DeducedType);
8936 assert(VDecl->isLinkageValid());
8938 // In ARC, infer lifetime.
8939 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8940 VDecl->setInvalidDecl();
8942 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8943 // 'id' instead of a specific object type prevents most of our usual checks.
8944 // We only want to warn outside of template instantiations, though:
8945 // inside a template, the 'id' could have come from a parameter.
8946 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8947 DeducedType->isObjCIdType()) {
8948 SourceLocation Loc =
8949 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8950 Diag(Loc, diag::warn_auto_var_is_id)
8951 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8954 // If this is a redeclaration, check that the type we just deduced matches
8955 // the previously declared type.
8956 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8957 // We never need to merge the type, because we cannot form an incomplete
8958 // array of auto, nor deduce such a type.
8959 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8962 // Check the deduced type is valid for a variable declaration.
8963 CheckVariableDeclarationType(VDecl);
8964 if (VDecl->isInvalidDecl())
8967 // If all looks well, warn if this is a case that will change meaning when
8968 // we implement N3922.
8969 if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
8970 Diag(Init->getLocStart(),
8971 diag::warn_auto_var_direct_list_init)
8972 << FixItHint::CreateInsertion(Init->getLocStart(), "=");
8976 // dllimport cannot be used on variable definitions.
8977 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8978 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8979 VDecl->setInvalidDecl();
8983 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8984 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8985 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8986 VDecl->setInvalidDecl();
8990 if (!VDecl->getType()->isDependentType()) {
8991 // A definition must end up with a complete type, which means it must be
8992 // complete with the restriction that an array type might be completed by
8993 // the initializer; note that later code assumes this restriction.
8994 QualType BaseDeclType = VDecl->getType();
8995 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8996 BaseDeclType = Array->getElementType();
8997 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8998 diag::err_typecheck_decl_incomplete_type)) {
8999 RealDecl->setInvalidDecl();
9003 // The variable can not have an abstract class type.
9004 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9005 diag::err_abstract_type_in_decl,
9006 AbstractVariableType))
9007 VDecl->setInvalidDecl();
9011 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9012 NamedDecl *Hidden = nullptr;
9013 if (!hasVisibleDefinition(Def, &Hidden) &&
9014 (VDecl->getFormalLinkage() == InternalLinkage ||
9015 VDecl->getDescribedVarTemplate() ||
9016 VDecl->getNumTemplateParameterLists() ||
9017 VDecl->getDeclContext()->isDependentContext())) {
9018 // The previous definition is hidden, and multiple definitions are
9019 // permitted (in separate TUs). Form another definition of it.
9021 Diag(VDecl->getLocation(), diag::err_redefinition)
9022 << VDecl->getDeclName();
9023 Diag(Def->getLocation(), diag::note_previous_definition);
9024 VDecl->setInvalidDecl();
9029 if (getLangOpts().CPlusPlus) {
9030 // C++ [class.static.data]p4
9031 // If a static data member is of const integral or const
9032 // enumeration type, its declaration in the class definition can
9033 // specify a constant-initializer which shall be an integral
9034 // constant expression (5.19). In that case, the member can appear
9035 // in integral constant expressions. The member shall still be
9036 // defined in a namespace scope if it is used in the program and the
9037 // namespace scope definition shall not contain an initializer.
9039 // We already performed a redefinition check above, but for static
9040 // data members we also need to check whether there was an in-class
9041 // declaration with an initializer.
9042 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9043 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9044 << VDecl->getDeclName();
9045 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9046 diag::note_previous_initializer)
9051 if (VDecl->hasLocalStorage())
9052 getCurFunction()->setHasBranchProtectedScope();
9054 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9055 VDecl->setInvalidDecl();
9060 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9061 // a kernel function cannot be initialized."
9062 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
9063 Diag(VDecl->getLocation(), diag::err_local_cant_init);
9064 VDecl->setInvalidDecl();
9068 // Get the decls type and save a reference for later, since
9069 // CheckInitializerTypes may change it.
9070 QualType DclT = VDecl->getType(), SavT = DclT;
9072 // Expressions default to 'id' when we're in a debugger
9073 // and we are assigning it to a variable of Objective-C pointer type.
9074 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9075 Init->getType() == Context.UnknownAnyTy) {
9076 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9077 if (Result.isInvalid()) {
9078 VDecl->setInvalidDecl();
9081 Init = Result.get();
9084 // Perform the initialization.
9085 if (!VDecl->isInvalidDecl()) {
9086 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9087 InitializationKind Kind
9089 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
9090 Init->getLocStart(),
9092 : InitializationKind::CreateDirectList(
9093 VDecl->getLocation())
9094 : InitializationKind::CreateCopy(VDecl->getLocation(),
9095 Init->getLocStart());
9097 MultiExprArg Args = Init;
9099 Args = MultiExprArg(CXXDirectInit->getExprs(),
9100 CXXDirectInit->getNumExprs());
9102 // Try to correct any TypoExprs in the initialization arguments.
9103 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9104 ExprResult Res = CorrectDelayedTyposInExpr(
9105 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9106 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9107 return Init.Failed() ? ExprError() : E;
9109 if (Res.isInvalid()) {
9110 VDecl->setInvalidDecl();
9111 } else if (Res.get() != Args[Idx]) {
9112 Args[Idx] = Res.get();
9115 if (VDecl->isInvalidDecl())
9118 InitializationSequence InitSeq(*this, Entity, Kind, Args);
9119 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9120 if (Result.isInvalid()) {
9121 VDecl->setInvalidDecl();
9125 Init = Result.getAs<Expr>();
9128 // Check for self-references within variable initializers.
9129 // Variables declared within a function/method body (except for references)
9130 // are handled by a dataflow analysis.
9131 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9132 VDecl->getType()->isReferenceType()) {
9133 CheckSelfReference(*this, RealDecl, Init, DirectInit);
9136 // If the type changed, it means we had an incomplete type that was
9137 // completed by the initializer. For example:
9138 // int ary[] = { 1, 3, 5 };
9139 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9140 if (!VDecl->isInvalidDecl() && (DclT != SavT))
9141 VDecl->setType(DclT);
9143 if (!VDecl->isInvalidDecl()) {
9144 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9146 if (VDecl->hasAttr<BlocksAttr>())
9147 checkRetainCycles(VDecl, Init);
9149 // It is safe to assign a weak reference into a strong variable.
9150 // Although this code can still have problems:
9151 // id x = self.weakProp;
9152 // id y = self.weakProp;
9153 // we do not warn to warn spuriously when 'x' and 'y' are on separate
9154 // paths through the function. This should be revisited if
9155 // -Wrepeated-use-of-weak is made flow-sensitive.
9156 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9157 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9158 Init->getLocStart()))
9159 getCurFunction()->markSafeWeakUse(Init);
9162 // The initialization is usually a full-expression.
9164 // FIXME: If this is a braced initialization of an aggregate, it is not
9165 // an expression, and each individual field initializer is a separate
9166 // full-expression. For instance, in:
9168 // struct Temp { ~Temp(); };
9169 // struct S { S(Temp); };
9170 // struct T { S a, b; } t = { Temp(), Temp() }
9172 // we should destroy the first Temp before constructing the second.
9173 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9175 VDecl->isConstexpr());
9176 if (Result.isInvalid()) {
9177 VDecl->setInvalidDecl();
9180 Init = Result.get();
9182 // Attach the initializer to the decl.
9183 VDecl->setInit(Init);
9185 if (VDecl->isLocalVarDecl()) {
9186 // C99 6.7.8p4: All the expressions in an initializer for an object that has
9187 // static storage duration shall be constant expressions or string literals.
9188 // C++ does not have this restriction.
9189 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9190 const Expr *Culprit;
9191 if (VDecl->getStorageClass() == SC_Static)
9192 CheckForConstantInitializer(Init, DclT);
9193 // C89 is stricter than C99 for non-static aggregate types.
9194 // C89 6.5.7p3: All the expressions [...] in an initializer list
9195 // for an object that has aggregate or union type shall be
9196 // constant expressions.
9197 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9198 isa<InitListExpr>(Init) &&
9199 !Init->isConstantInitializer(Context, false, &Culprit))
9200 Diag(Culprit->getExprLoc(),
9201 diag::ext_aggregate_init_not_constant)
9202 << Culprit->getSourceRange();
9204 } else if (VDecl->isStaticDataMember() &&
9205 VDecl->getLexicalDeclContext()->isRecord()) {
9206 // This is an in-class initialization for a static data member, e.g.,
9209 // static const int value = 17;
9212 // C++ [class.mem]p4:
9213 // A member-declarator can contain a constant-initializer only
9214 // if it declares a static member (9.4) of const integral or
9215 // const enumeration type, see 9.4.2.
9217 // C++11 [class.static.data]p3:
9218 // If a non-volatile const static data member is of integral or
9219 // enumeration type, its declaration in the class definition can
9220 // specify a brace-or-equal-initializer in which every initalizer-clause
9221 // that is an assignment-expression is a constant expression. A static
9222 // data member of literal type can be declared in the class definition
9223 // with the constexpr specifier; if so, its declaration shall specify a
9224 // brace-or-equal-initializer in which every initializer-clause that is
9225 // an assignment-expression is a constant expression.
9227 // Do nothing on dependent types.
9228 if (DclT->isDependentType()) {
9230 // Allow any 'static constexpr' members, whether or not they are of literal
9231 // type. We separately check that every constexpr variable is of literal
9233 } else if (VDecl->isConstexpr()) {
9235 // Require constness.
9236 } else if (!DclT.isConstQualified()) {
9237 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9238 << Init->getSourceRange();
9239 VDecl->setInvalidDecl();
9241 // We allow integer constant expressions in all cases.
9242 } else if (DclT->isIntegralOrEnumerationType()) {
9243 // Check whether the expression is a constant expression.
9245 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9246 // In C++11, a non-constexpr const static data member with an
9247 // in-class initializer cannot be volatile.
9248 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9249 else if (Init->isValueDependent())
9250 ; // Nothing to check.
9251 else if (Init->isIntegerConstantExpr(Context, &Loc))
9252 ; // Ok, it's an ICE!
9253 else if (Init->isEvaluatable(Context)) {
9254 // If we can constant fold the initializer through heroics, accept it,
9255 // but report this as a use of an extension for -pedantic.
9256 Diag(Loc, diag::ext_in_class_initializer_non_constant)
9257 << Init->getSourceRange();
9259 // Otherwise, this is some crazy unknown case. Report the issue at the
9260 // location provided by the isIntegerConstantExpr failed check.
9261 Diag(Loc, diag::err_in_class_initializer_non_constant)
9262 << Init->getSourceRange();
9263 VDecl->setInvalidDecl();
9266 // We allow foldable floating-point constants as an extension.
9267 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9268 // In C++98, this is a GNU extension. In C++11, it is not, but we support
9269 // it anyway and provide a fixit to add the 'constexpr'.
9270 if (getLangOpts().CPlusPlus11) {
9271 Diag(VDecl->getLocation(),
9272 diag::ext_in_class_initializer_float_type_cxx11)
9273 << DclT << Init->getSourceRange();
9274 Diag(VDecl->getLocStart(),
9275 diag::note_in_class_initializer_float_type_cxx11)
9276 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9278 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9279 << DclT << Init->getSourceRange();
9281 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9282 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9283 << Init->getSourceRange();
9284 VDecl->setInvalidDecl();
9288 // Suggest adding 'constexpr' in C++11 for literal types.
9289 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9290 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9291 << DclT << Init->getSourceRange()
9292 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9293 VDecl->setConstexpr(true);
9296 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9297 << DclT << Init->getSourceRange();
9298 VDecl->setInvalidDecl();
9300 } else if (VDecl->isFileVarDecl()) {
9301 if (VDecl->getStorageClass() == SC_Extern &&
9302 (!getLangOpts().CPlusPlus ||
9303 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9304 VDecl->isExternC())) &&
9305 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9306 Diag(VDecl->getLocation(), diag::warn_extern_init);
9308 // C99 6.7.8p4. All file scoped initializers need to be constant.
9309 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9310 CheckForConstantInitializer(Init, DclT);
9313 // We will represent direct-initialization similarly to copy-initialization:
9314 // int x(1); -as-> int x = 1;
9315 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9317 // Clients that want to distinguish between the two forms, can check for
9318 // direct initializer using VarDecl::getInitStyle().
9319 // A major benefit is that clients that don't particularly care about which
9320 // exactly form was it (like the CodeGen) can handle both cases without
9321 // special case code.
9324 // The form of initialization (using parentheses or '=') is generally
9325 // insignificant, but does matter when the entity being initialized has a
9327 if (CXXDirectInit) {
9328 assert(DirectInit && "Call-style initializer must be direct init.");
9329 VDecl->setInitStyle(VarDecl::CallInit);
9330 } else if (DirectInit) {
9331 // This must be list-initialization. No other way is direct-initialization.
9332 VDecl->setInitStyle(VarDecl::ListInit);
9335 CheckCompleteVariableDeclaration(VDecl);
9338 /// ActOnInitializerError - Given that there was an error parsing an
9339 /// initializer for the given declaration, try to return to some form
9341 void Sema::ActOnInitializerError(Decl *D) {
9342 // Our main concern here is re-establishing invariants like "a
9343 // variable's type is either dependent or complete".
9344 if (!D || D->isInvalidDecl()) return;
9346 VarDecl *VD = dyn_cast<VarDecl>(D);
9349 // Auto types are meaningless if we can't make sense of the initializer.
9350 if (ParsingInitForAutoVars.count(D)) {
9351 D->setInvalidDecl();
9355 QualType Ty = VD->getType();
9356 if (Ty->isDependentType()) return;
9358 // Require a complete type.
9359 if (RequireCompleteType(VD->getLocation(),
9360 Context.getBaseElementType(Ty),
9361 diag::err_typecheck_decl_incomplete_type)) {
9362 VD->setInvalidDecl();
9366 // Require a non-abstract type.
9367 if (RequireNonAbstractType(VD->getLocation(), Ty,
9368 diag::err_abstract_type_in_decl,
9369 AbstractVariableType)) {
9370 VD->setInvalidDecl();
9374 // Don't bother complaining about constructors or destructors,
9378 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9379 bool TypeMayContainAuto) {
9380 // If there is no declaration, there was an error parsing it. Just ignore it.
9384 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9385 QualType Type = Var->getType();
9387 // C++11 [dcl.spec.auto]p3
9388 if (TypeMayContainAuto && Type->getContainedAutoType()) {
9389 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9390 << Var->getDeclName() << Type;
9391 Var->setInvalidDecl();
9395 // C++11 [class.static.data]p3: A static data member can be declared with
9396 // the constexpr specifier; if so, its declaration shall specify
9397 // a brace-or-equal-initializer.
9398 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9399 // the definition of a variable [...] or the declaration of a static data
9401 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9402 if (Var->isStaticDataMember())
9403 Diag(Var->getLocation(),
9404 diag::err_constexpr_static_mem_var_requires_init)
9405 << Var->getDeclName();
9407 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9408 Var->setInvalidDecl();
9412 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9414 if (!Var->isInvalidDecl() &&
9415 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9416 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9417 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9418 Var->setInvalidDecl();
9422 switch (Var->isThisDeclarationADefinition()) {
9423 case VarDecl::Definition:
9424 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9427 // We have an out-of-line definition of a static data member
9428 // that has an in-class initializer, so we type-check this like
9433 case VarDecl::DeclarationOnly:
9434 // It's only a declaration.
9436 // Block scope. C99 6.7p7: If an identifier for an object is
9437 // declared with no linkage (C99 6.2.2p6), the type for the
9438 // object shall be complete.
9439 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9440 !Var->hasLinkage() && !Var->isInvalidDecl() &&
9441 RequireCompleteType(Var->getLocation(), Type,
9442 diag::err_typecheck_decl_incomplete_type))
9443 Var->setInvalidDecl();
9445 // Make sure that the type is not abstract.
9446 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9447 RequireNonAbstractType(Var->getLocation(), Type,
9448 diag::err_abstract_type_in_decl,
9449 AbstractVariableType))
9450 Var->setInvalidDecl();
9451 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9452 Var->getStorageClass() == SC_PrivateExtern) {
9453 Diag(Var->getLocation(), diag::warn_private_extern);
9454 Diag(Var->getLocation(), diag::note_private_extern);
9459 case VarDecl::TentativeDefinition:
9460 // File scope. C99 6.9.2p2: A declaration of an identifier for an
9461 // object that has file scope without an initializer, and without a
9462 // storage-class specifier or with the storage-class specifier "static",
9463 // constitutes a tentative definition. Note: A tentative definition with
9464 // external linkage is valid (C99 6.2.2p5).
9465 if (!Var->isInvalidDecl()) {
9466 if (const IncompleteArrayType *ArrayT
9467 = Context.getAsIncompleteArrayType(Type)) {
9468 if (RequireCompleteType(Var->getLocation(),
9469 ArrayT->getElementType(),
9470 diag::err_illegal_decl_array_incomplete_type))
9471 Var->setInvalidDecl();
9472 } else if (Var->getStorageClass() == SC_Static) {
9473 // C99 6.9.2p3: If the declaration of an identifier for an object is
9474 // a tentative definition and has internal linkage (C99 6.2.2p3), the
9475 // declared type shall not be an incomplete type.
9476 // NOTE: code such as the following
9478 // struct s { int a; };
9479 // is accepted by gcc. Hence here we issue a warning instead of
9480 // an error and we do not invalidate the static declaration.
9481 // NOTE: to avoid multiple warnings, only check the first declaration.
9482 if (Var->isFirstDecl())
9483 RequireCompleteType(Var->getLocation(), Type,
9484 diag::ext_typecheck_decl_incomplete_type);
9488 // Record the tentative definition; we're done.
9489 if (!Var->isInvalidDecl())
9490 TentativeDefinitions.push_back(Var);
9494 // Provide a specific diagnostic for uninitialized variable
9495 // definitions with incomplete array type.
9496 if (Type->isIncompleteArrayType()) {
9497 Diag(Var->getLocation(),
9498 diag::err_typecheck_incomplete_array_needs_initializer);
9499 Var->setInvalidDecl();
9503 // Provide a specific diagnostic for uninitialized variable
9504 // definitions with reference type.
9505 if (Type->isReferenceType()) {
9506 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9507 << Var->getDeclName()
9508 << SourceRange(Var->getLocation(), Var->getLocation());
9509 Var->setInvalidDecl();
9513 // Do not attempt to type-check the default initializer for a
9514 // variable with dependent type.
9515 if (Type->isDependentType())
9518 if (Var->isInvalidDecl())
9521 if (!Var->hasAttr<AliasAttr>()) {
9522 if (RequireCompleteType(Var->getLocation(),
9523 Context.getBaseElementType(Type),
9524 diag::err_typecheck_decl_incomplete_type)) {
9525 Var->setInvalidDecl();
9532 // The variable can not have an abstract class type.
9533 if (RequireNonAbstractType(Var->getLocation(), Type,
9534 diag::err_abstract_type_in_decl,
9535 AbstractVariableType)) {
9536 Var->setInvalidDecl();
9540 // Check for jumps past the implicit initializer. C++0x
9541 // clarifies that this applies to a "variable with automatic
9542 // storage duration", not a "local variable".
9543 // C++11 [stmt.dcl]p3
9544 // A program that jumps from a point where a variable with automatic
9545 // storage duration is not in scope to a point where it is in scope is
9546 // ill-formed unless the variable has scalar type, class type with a
9547 // trivial default constructor and a trivial destructor, a cv-qualified
9548 // version of one of these types, or an array of one of the preceding
9549 // types and is declared without an initializer.
9550 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9551 if (const RecordType *Record
9552 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9553 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9554 // Mark the function for further checking even if the looser rules of
9555 // C++11 do not require such checks, so that we can diagnose
9556 // incompatibilities with C++98.
9557 if (!CXXRecord->isPOD())
9558 getCurFunction()->setHasBranchProtectedScope();
9562 // C++03 [dcl.init]p9:
9563 // If no initializer is specified for an object, and the
9564 // object is of (possibly cv-qualified) non-POD class type (or
9565 // array thereof), the object shall be default-initialized; if
9566 // the object is of const-qualified type, the underlying class
9567 // type shall have a user-declared default
9568 // constructor. Otherwise, if no initializer is specified for
9569 // a non- static object, the object and its subobjects, if
9570 // any, have an indeterminate initial value); if the object
9571 // or any of its subobjects are of const-qualified type, the
9572 // program is ill-formed.
9573 // C++0x [dcl.init]p11:
9574 // If no initializer is specified for an object, the object is
9575 // default-initialized; [...].
9576 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9577 InitializationKind Kind
9578 = InitializationKind::CreateDefault(Var->getLocation());
9580 InitializationSequence InitSeq(*this, Entity, Kind, None);
9581 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9582 if (Init.isInvalid())
9583 Var->setInvalidDecl();
9584 else if (Init.get()) {
9585 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9586 // This is important for template substitution.
9587 Var->setInitStyle(VarDecl::CallInit);
9590 CheckCompleteVariableDeclaration(Var);
9594 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9595 VarDecl *VD = dyn_cast<VarDecl>(D);
9597 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9598 D->setInvalidDecl();
9602 VD->setCXXForRangeDecl(true);
9604 // for-range-declaration cannot be given a storage class specifier.
9606 switch (VD->getStorageClass()) {
9615 case SC_PrivateExtern:
9624 case SC_OpenCLWorkGroupLocal:
9625 llvm_unreachable("Unexpected storage class");
9628 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9629 << VD->getDeclName() << Error;
9630 D->setInvalidDecl();
9635 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9636 IdentifierInfo *Ident,
9637 ParsedAttributes &Attrs,
9638 SourceLocation AttrEnd) {
9639 // C++1y [stmt.iter]p1:
9640 // A range-based for statement of the form
9641 // for ( for-range-identifier : for-range-initializer ) statement
9643 // for ( auto&& for-range-identifier : for-range-initializer ) statement
9644 DeclSpec DS(Attrs.getPool().getFactory());
9646 const char *PrevSpec;
9648 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9649 getPrintingPolicy());
9651 Declarator D(DS, Declarator::ForContext);
9652 D.SetIdentifier(Ident, IdentLoc);
9653 D.takeAttributes(Attrs, AttrEnd);
9655 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9656 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9657 EmptyAttrs, IdentLoc);
9658 Decl *Var = ActOnDeclarator(S, D);
9659 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9660 FinalizeDeclaration(Var);
9661 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9662 AttrEnd.isValid() ? AttrEnd : IdentLoc);
9665 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9666 if (var->isInvalidDecl()) return;
9668 // In ARC, don't allow jumps past the implicit initialization of a
9669 // local retaining variable.
9670 if (getLangOpts().ObjCAutoRefCount &&
9671 var->hasLocalStorage()) {
9672 switch (var->getType().getObjCLifetime()) {
9673 case Qualifiers::OCL_None:
9674 case Qualifiers::OCL_ExplicitNone:
9675 case Qualifiers::OCL_Autoreleasing:
9678 case Qualifiers::OCL_Weak:
9679 case Qualifiers::OCL_Strong:
9680 getCurFunction()->setHasBranchProtectedScope();
9685 // Warn about externally-visible variables being defined without a
9686 // prior declaration. We only want to do this for global
9687 // declarations, but we also specifically need to avoid doing it for
9688 // class members because the linkage of an anonymous class can
9689 // change if it's later given a typedef name.
9690 if (var->isThisDeclarationADefinition() &&
9691 var->getDeclContext()->getRedeclContext()->isFileContext() &&
9692 var->isExternallyVisible() && var->hasLinkage() &&
9693 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9694 var->getLocation())) {
9695 // Find a previous declaration that's not a definition.
9696 VarDecl *prev = var->getPreviousDecl();
9697 while (prev && prev->isThisDeclarationADefinition())
9698 prev = prev->getPreviousDecl();
9701 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9704 if (var->getTLSKind() == VarDecl::TLS_Static) {
9705 const Expr *Culprit;
9706 if (var->getType().isDestructedType()) {
9707 // GNU C++98 edits for __thread, [basic.start.term]p3:
9708 // The type of an object with thread storage duration shall not
9709 // have a non-trivial destructor.
9710 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9711 if (getLangOpts().CPlusPlus11)
9712 Diag(var->getLocation(), diag::note_use_thread_local);
9713 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9714 !var->getInit()->isConstantInitializer(
9715 Context, var->getType()->isReferenceType(), &Culprit)) {
9716 // GNU C++98 edits for __thread, [basic.start.init]p4:
9717 // An object of thread storage duration shall not require dynamic
9719 // FIXME: Need strict checking here.
9720 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9721 << Culprit->getSourceRange();
9722 if (getLangOpts().CPlusPlus11)
9723 Diag(var->getLocation(), diag::note_use_thread_local);
9728 // Apply section attributes and pragmas to global variables.
9729 bool GlobalStorage = var->hasGlobalStorage();
9730 if (GlobalStorage && var->isThisDeclarationADefinition() &&
9731 ActiveTemplateInstantiations.empty()) {
9732 PragmaStack<StringLiteral *> *Stack = nullptr;
9733 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9734 if (var->getType().isConstQualified())
9735 Stack = &ConstSegStack;
9736 else if (!var->getInit()) {
9737 Stack = &BSSSegStack;
9738 SectionFlags |= ASTContext::PSF_Write;
9740 Stack = &DataSegStack;
9741 SectionFlags |= ASTContext::PSF_Write;
9743 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
9744 var->addAttr(SectionAttr::CreateImplicit(
9745 Context, SectionAttr::Declspec_allocate,
9746 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
9748 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9749 if (UnifySection(SA->getName(), SectionFlags, var))
9750 var->dropAttr<SectionAttr>();
9752 // Apply the init_seg attribute if this has an initializer. If the
9753 // initializer turns out to not be dynamic, we'll end up ignoring this
9755 if (CurInitSeg && var->getInit())
9756 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9760 // All the following checks are C++ only.
9761 if (!getLangOpts().CPlusPlus) return;
9763 QualType type = var->getType();
9764 if (type->isDependentType()) return;
9766 // __block variables might require us to capture a copy-initializer.
9767 if (var->hasAttr<BlocksAttr>()) {
9768 // It's currently invalid to ever have a __block variable with an
9769 // array type; should we diagnose that here?
9771 // Regardless, we don't want to ignore array nesting when
9772 // constructing this copy.
9773 if (type->isStructureOrClassType()) {
9774 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9775 SourceLocation poi = var->getLocation();
9776 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9778 = PerformMoveOrCopyInitialization(
9779 InitializedEntity::InitializeBlock(poi, type, false),
9780 var, var->getType(), varRef, /*AllowNRVO=*/true);
9781 if (!result.isInvalid()) {
9782 result = MaybeCreateExprWithCleanups(result);
9783 Expr *init = result.getAs<Expr>();
9784 Context.setBlockVarCopyInits(var, init);
9789 Expr *Init = var->getInit();
9790 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
9791 QualType baseType = Context.getBaseElementType(type);
9793 if (!var->getDeclContext()->isDependentContext() &&
9794 Init && !Init->isValueDependent()) {
9795 if (IsGlobal && !var->isConstexpr() &&
9796 !getDiagnostics().isIgnored(diag::warn_global_constructor,
9797 var->getLocation())) {
9798 // Warn about globals which don't have a constant initializer. Don't
9799 // warn about globals with a non-trivial destructor because we already
9800 // warned about them.
9801 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9802 if (!(RD && !RD->hasTrivialDestructor()) &&
9803 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9804 Diag(var->getLocation(), diag::warn_global_constructor)
9805 << Init->getSourceRange();
9808 if (var->isConstexpr()) {
9809 SmallVector<PartialDiagnosticAt, 8> Notes;
9810 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9811 SourceLocation DiagLoc = var->getLocation();
9812 // If the note doesn't add any useful information other than a source
9813 // location, fold it into the primary diagnostic.
9814 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9815 diag::note_invalid_subexpr_in_const_expr) {
9816 DiagLoc = Notes[0].first;
9819 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9820 << var << Init->getSourceRange();
9821 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9822 Diag(Notes[I].first, Notes[I].second);
9824 } else if (var->isUsableInConstantExpressions(Context)) {
9825 // Check whether the initializer of a const variable of integral or
9826 // enumeration type is an ICE now, since we can't tell whether it was
9827 // initialized by a constant expression if we check later.
9828 var->checkInitIsICE();
9832 // Require the destructor.
9833 if (const RecordType *recordType = baseType->getAs<RecordType>())
9834 FinalizeVarWithDestructor(var, recordType);
9837 /// \brief Determines if a variable's alignment is dependent.
9838 static bool hasDependentAlignment(VarDecl *VD) {
9839 if (VD->getType()->isDependentType())
9841 for (auto *I : VD->specific_attrs<AlignedAttr>())
9842 if (I->isAlignmentDependent())
9847 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9848 /// any semantic actions necessary after any initializer has been attached.
9850 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9851 // Note that we are no longer parsing the initializer for this declaration.
9852 ParsingInitForAutoVars.erase(ThisDecl);
9854 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9858 checkAttributesAfterMerging(*this, *VD);
9860 // Perform TLS alignment check here after attributes attached to the variable
9861 // which may affect the alignment have been processed. Only perform the check
9862 // if the target has a maximum TLS alignment (zero means no constraints).
9863 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
9864 // Protect the check so that it's not performed on dependent types and
9865 // dependent alignments (we can't determine the alignment in that case).
9866 if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
9867 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
9868 if (Context.getDeclAlign(VD) > MaxAlignChars) {
9869 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
9870 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
9871 << (unsigned)MaxAlignChars.getQuantity();
9876 // Static locals inherit dll attributes from their function.
9877 if (VD->isStaticLocal()) {
9878 if (FunctionDecl *FD =
9879 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9880 if (Attr *A = getDLLAttr(FD)) {
9881 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9882 NewAttr->setInherited(true);
9883 VD->addAttr(NewAttr);
9888 // Grab the dllimport or dllexport attribute off of the VarDecl.
9889 const InheritableAttr *DLLAttr = getDLLAttr(VD);
9891 // Imported static data members cannot be defined out-of-line.
9892 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9893 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9894 VD->isThisDeclarationADefinition()) {
9895 // We allow definitions of dllimport class template static data members
9897 CXXRecordDecl *Context =
9898 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9899 bool IsClassTemplateMember =
9900 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9901 Context->getDescribedClassTemplate();
9903 Diag(VD->getLocation(),
9904 IsClassTemplateMember
9905 ? diag::warn_attribute_dllimport_static_field_definition
9906 : diag::err_attribute_dllimport_static_field_definition);
9907 Diag(IA->getLocation(), diag::note_attribute);
9908 if (!IsClassTemplateMember)
9909 VD->setInvalidDecl();
9913 // dllimport/dllexport variables cannot be thread local, their TLS index
9914 // isn't exported with the variable.
9915 if (DLLAttr && VD->getTLSKind()) {
9916 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9918 VD->setInvalidDecl();
9921 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9922 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9923 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9924 VD->dropAttr<UsedAttr>();
9928 const DeclContext *DC = VD->getDeclContext();
9929 // If there's a #pragma GCC visibility in scope, and this isn't a class
9930 // member, set the visibility of this variable.
9931 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9932 AddPushedVisibilityAttribute(VD);
9934 // FIXME: Warn on unused templates.
9935 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9936 !isa<VarTemplatePartialSpecializationDecl>(VD))
9937 MarkUnusedFileScopedDecl(VD);
9939 // Now we have parsed the initializer and can update the table of magic
9941 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9942 !VD->getType()->isIntegralOrEnumerationType())
9945 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9946 const Expr *MagicValueExpr = VD->getInit();
9947 if (!MagicValueExpr) {
9950 llvm::APSInt MagicValueInt;
9951 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9952 Diag(I->getRange().getBegin(),
9953 diag::err_type_tag_for_datatype_not_ice)
9954 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9957 if (MagicValueInt.getActiveBits() > 64) {
9958 Diag(I->getRange().getBegin(),
9959 diag::err_type_tag_for_datatype_too_large)
9960 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9963 uint64_t MagicValue = MagicValueInt.getZExtValue();
9964 RegisterTypeTagForDatatype(I->getArgumentKind(),
9966 I->getMatchingCType(),
9967 I->getLayoutCompatible(),
9968 I->getMustBeNull());
9972 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9973 ArrayRef<Decl *> Group) {
9974 SmallVector<Decl*, 8> Decls;
9976 if (DS.isTypeSpecOwned())
9977 Decls.push_back(DS.getRepAsDecl());
9979 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9980 for (unsigned i = 0, e = Group.size(); i != e; ++i)
9981 if (Decl *D = Group[i]) {
9982 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9983 if (!FirstDeclaratorInGroup)
9984 FirstDeclaratorInGroup = DD;
9988 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9989 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9990 handleTagNumbering(Tag, S);
9991 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9992 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9996 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9999 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10000 /// group, performing any necessary semantic checking.
10001 Sema::DeclGroupPtrTy
10002 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10003 bool TypeMayContainAuto) {
10004 // C++0x [dcl.spec.auto]p7:
10005 // If the type deduced for the template parameter U is not the same in each
10006 // deduction, the program is ill-formed.
10007 // FIXME: When initializer-list support is added, a distinction is needed
10008 // between the deduced type U and the deduced type which 'auto' stands for.
10009 // auto a = 0, b = { 1, 2, 3 };
10010 // is legal because the deduced type U is 'int' in both cases.
10011 if (TypeMayContainAuto && Group.size() > 1) {
10013 CanQualType DeducedCanon;
10014 VarDecl *DeducedDecl = nullptr;
10015 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10016 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10017 AutoType *AT = D->getType()->getContainedAutoType();
10018 // Don't reissue diagnostics when instantiating a template.
10019 if (AT && D->isInvalidDecl())
10021 QualType U = AT ? AT->getDeducedType() : QualType();
10023 CanQualType UCanon = Context.getCanonicalType(U);
10024 if (Deduced.isNull()) {
10026 DeducedCanon = UCanon;
10028 } else if (DeducedCanon != UCanon) {
10029 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10030 diag::err_auto_different_deductions)
10031 << (AT->isDecltypeAuto() ? 1 : 0)
10032 << Deduced << DeducedDecl->getDeclName()
10033 << U << D->getDeclName()
10034 << DeducedDecl->getInit()->getSourceRange()
10035 << D->getInit()->getSourceRange();
10036 D->setInvalidDecl();
10044 ActOnDocumentableDecls(Group);
10046 return DeclGroupPtrTy::make(
10047 DeclGroupRef::Create(Context, Group.data(), Group.size()));
10050 void Sema::ActOnDocumentableDecl(Decl *D) {
10051 ActOnDocumentableDecls(D);
10054 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10055 // Don't parse the comment if Doxygen diagnostics are ignored.
10056 if (Group.empty() || !Group[0])
10059 if (Diags.isIgnored(diag::warn_doc_param_not_found,
10060 Group[0]->getLocation()) &&
10061 Diags.isIgnored(diag::warn_unknown_comment_command_name,
10062 Group[0]->getLocation()))
10065 if (Group.size() >= 2) {
10066 // This is a decl group. Normally it will contain only declarations
10067 // produced from declarator list. But in case we have any definitions or
10068 // additional declaration references:
10069 // 'typedef struct S {} S;'
10070 // 'typedef struct S *S;'
10072 // FinalizeDeclaratorGroup adds these as separate declarations.
10073 Decl *MaybeTagDecl = Group[0];
10074 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10075 Group = Group.slice(1);
10079 // See if there are any new comments that are not attached to a decl.
10080 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10081 if (!Comments.empty() &&
10082 !Comments.back()->isAttached()) {
10083 // There is at least one comment that not attached to a decl.
10084 // Maybe it should be attached to one of these decls?
10086 // Note that this way we pick up not only comments that precede the
10087 // declaration, but also comments that *follow* the declaration -- thanks to
10088 // the lookahead in the lexer: we've consumed the semicolon and looked
10089 // ahead through comments.
10090 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10091 Context.getCommentForDecl(Group[i], &PP);
10095 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10096 /// to introduce parameters into function prototype scope.
10097 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10098 const DeclSpec &DS = D.getDeclSpec();
10100 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10102 // C++03 [dcl.stc]p2 also permits 'auto'.
10103 StorageClass SC = SC_None;
10104 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10106 } else if (getLangOpts().CPlusPlus &&
10107 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10109 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10110 Diag(DS.getStorageClassSpecLoc(),
10111 diag::err_invalid_storage_class_in_func_decl);
10112 D.getMutableDeclSpec().ClearStorageClassSpecs();
10115 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10116 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10117 << DeclSpec::getSpecifierName(TSCS);
10118 if (DS.isConstexprSpecified())
10119 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10122 DiagnoseFunctionSpecifiers(DS);
10124 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10125 QualType parmDeclType = TInfo->getType();
10127 if (getLangOpts().CPlusPlus) {
10128 // Check that there are no default arguments inside the type of this
10130 CheckExtraCXXDefaultArguments(D);
10132 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10133 if (D.getCXXScopeSpec().isSet()) {
10134 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10135 << D.getCXXScopeSpec().getRange();
10136 D.getCXXScopeSpec().clear();
10140 // Ensure we have a valid name
10141 IdentifierInfo *II = nullptr;
10143 II = D.getIdentifier();
10145 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10146 << GetNameForDeclarator(D).getName();
10147 D.setInvalidType(true);
10151 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10153 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10156 if (R.isSingleResult()) {
10157 NamedDecl *PrevDecl = R.getFoundDecl();
10158 if (PrevDecl->isTemplateParameter()) {
10159 // Maybe we will complain about the shadowed template parameter.
10160 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10161 // Just pretend that we didn't see the previous declaration.
10162 PrevDecl = nullptr;
10163 } else if (S->isDeclScope(PrevDecl)) {
10164 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10165 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10167 // Recover by removing the name
10169 D.SetIdentifier(nullptr, D.getIdentifierLoc());
10170 D.setInvalidType(true);
10175 // Temporarily put parameter variables in the translation unit, not
10176 // the enclosing context. This prevents them from accidentally
10177 // looking like class members in C++.
10178 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10180 D.getIdentifierLoc(), II,
10181 parmDeclType, TInfo,
10184 if (D.isInvalidType())
10185 New->setInvalidDecl();
10187 assert(S->isFunctionPrototypeScope());
10188 assert(S->getFunctionPrototypeDepth() >= 1);
10189 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10190 S->getNextFunctionPrototypeIndex());
10192 // Add the parameter declaration into this scope.
10195 IdResolver.AddDecl(New);
10197 ProcessDeclAttributes(S, New, D);
10199 if (D.getDeclSpec().isModulePrivateSpecified())
10200 Diag(New->getLocation(), diag::err_module_private_local)
10201 << 1 << New->getDeclName()
10202 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10203 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10205 if (New->hasAttr<BlocksAttr>()) {
10206 Diag(New->getLocation(), diag::err_block_on_nonlocal);
10211 /// \brief Synthesizes a variable for a parameter arising from a
10213 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10214 SourceLocation Loc,
10216 /* FIXME: setting StartLoc == Loc.
10217 Would it be worth to modify callers so as to provide proper source
10218 location for the unnamed parameters, embedding the parameter's type? */
10219 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10220 T, Context.getTrivialTypeSourceInfo(T, Loc),
10222 Param->setImplicit();
10226 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10227 ParmVarDecl * const *ParamEnd) {
10228 // Don't diagnose unused-parameter errors in template instantiations; we
10229 // will already have done so in the template itself.
10230 if (!ActiveTemplateInstantiations.empty())
10233 for (; Param != ParamEnd; ++Param) {
10234 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10235 !(*Param)->hasAttr<UnusedAttr>()) {
10236 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10237 << (*Param)->getDeclName();
10242 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10243 ParmVarDecl * const *ParamEnd,
10246 if (LangOpts.NumLargeByValueCopy == 0) // No check.
10249 // Warn if the return value is pass-by-value and larger than the specified
10251 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10252 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10253 if (Size > LangOpts.NumLargeByValueCopy)
10254 Diag(D->getLocation(), diag::warn_return_value_size)
10255 << D->getDeclName() << Size;
10258 // Warn if any parameter is pass-by-value and larger than the specified
10260 for (; Param != ParamEnd; ++Param) {
10261 QualType T = (*Param)->getType();
10262 if (T->isDependentType() || !T.isPODType(Context))
10264 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10265 if (Size > LangOpts.NumLargeByValueCopy)
10266 Diag((*Param)->getLocation(), diag::warn_parameter_size)
10267 << (*Param)->getDeclName() << Size;
10271 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10272 SourceLocation NameLoc, IdentifierInfo *Name,
10273 QualType T, TypeSourceInfo *TSInfo,
10275 // In ARC, infer a lifetime qualifier for appropriate parameter types.
10276 if (getLangOpts().ObjCAutoRefCount &&
10277 T.getObjCLifetime() == Qualifiers::OCL_None &&
10278 T->isObjCLifetimeType()) {
10280 Qualifiers::ObjCLifetime lifetime;
10282 // Special cases for arrays:
10283 // - if it's const, use __unsafe_unretained
10284 // - otherwise, it's an error
10285 if (T->isArrayType()) {
10286 if (!T.isConstQualified()) {
10287 DelayedDiagnostics.add(
10288 sema::DelayedDiagnostic::makeForbiddenType(
10289 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10291 lifetime = Qualifiers::OCL_ExplicitNone;
10293 lifetime = T->getObjCARCImplicitLifetime();
10295 T = Context.getLifetimeQualifiedType(T, lifetime);
10298 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10299 Context.getAdjustedParameterType(T),
10300 TSInfo, SC, nullptr);
10302 // Parameters can not be abstract class types.
10303 // For record types, this is done by the AbstractClassUsageDiagnoser once
10304 // the class has been completely parsed.
10305 if (!CurContext->isRecord() &&
10306 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10307 AbstractParamType))
10308 New->setInvalidDecl();
10310 // Parameter declarators cannot be interface types. All ObjC objects are
10311 // passed by reference.
10312 if (T->isObjCObjectType()) {
10313 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10315 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10316 << FixItHint::CreateInsertion(TypeEndLoc, "*");
10317 T = Context.getObjCObjectPointerType(T);
10321 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10322 // duration shall not be qualified by an address-space qualifier."
10323 // Since all parameters have automatic store duration, they can not have
10324 // an address space.
10325 if (T.getAddressSpace() != 0) {
10326 // OpenCL allows function arguments declared to be an array of a type
10327 // to be qualified with an address space.
10328 if (!(getLangOpts().OpenCL && T->isArrayType())) {
10329 Diag(NameLoc, diag::err_arg_with_address_space);
10330 New->setInvalidDecl();
10337 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10338 SourceLocation LocAfterDecls) {
10339 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10341 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10342 // for a K&R function.
10343 if (!FTI.hasPrototype) {
10344 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10346 if (FTI.Params[i].Param == nullptr) {
10347 SmallString<256> Code;
10348 llvm::raw_svector_ostream(Code)
10349 << " int " << FTI.Params[i].Ident->getName() << ";\n";
10350 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10351 << FTI.Params[i].Ident
10352 << FixItHint::CreateInsertion(LocAfterDecls, Code);
10354 // Implicitly declare the argument as type 'int' for lack of a better
10356 AttributeFactory attrs;
10357 DeclSpec DS(attrs);
10358 const char* PrevSpec; // unused
10359 unsigned DiagID; // unused
10360 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10361 DiagID, Context.getPrintingPolicy());
10362 // Use the identifier location for the type source range.
10363 DS.SetRangeStart(FTI.Params[i].IdentLoc);
10364 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10365 Declarator ParamD(DS, Declarator::KNRTypeListContext);
10366 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10367 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10373 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
10374 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10375 assert(D.isFunctionDeclarator() && "Not a function declarator!");
10376 Scope *ParentScope = FnBodyScope->getParent();
10378 D.setFunctionDefinitionKind(FDK_Definition);
10379 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10380 return ActOnStartOfFunctionDef(FnBodyScope, DP);
10383 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10384 Consumer.HandleInlineMethodDefinition(D);
10387 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10388 const FunctionDecl*& PossibleZeroParamPrototype) {
10389 // Don't warn about invalid declarations.
10390 if (FD->isInvalidDecl())
10393 // Or declarations that aren't global.
10394 if (!FD->isGlobal())
10397 // Don't warn about C++ member functions.
10398 if (isa<CXXMethodDecl>(FD))
10401 // Don't warn about 'main'.
10405 // Don't warn about inline functions.
10406 if (FD->isInlined())
10409 // Don't warn about function templates.
10410 if (FD->getDescribedFunctionTemplate())
10413 // Don't warn about function template specializations.
10414 if (FD->isFunctionTemplateSpecialization())
10417 // Don't warn for OpenCL kernels.
10418 if (FD->hasAttr<OpenCLKernelAttr>())
10421 // Don't warn on explicitly deleted functions.
10422 if (FD->isDeleted())
10425 bool MissingPrototype = true;
10426 for (const FunctionDecl *Prev = FD->getPreviousDecl();
10427 Prev; Prev = Prev->getPreviousDecl()) {
10428 // Ignore any declarations that occur in function or method
10429 // scope, because they aren't visible from the header.
10430 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10433 MissingPrototype = !Prev->getType()->isFunctionProtoType();
10434 if (FD->getNumParams() == 0)
10435 PossibleZeroParamPrototype = Prev;
10439 return MissingPrototype;
10443 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10444 const FunctionDecl *EffectiveDefinition) {
10445 // Don't complain if we're in GNU89 mode and the previous definition
10446 // was an extern inline function.
10447 const FunctionDecl *Definition = EffectiveDefinition;
10449 if (!FD->isDefined(Definition))
10452 if (canRedefineFunction(Definition, getLangOpts()))
10455 // If we don't have a visible definition of the function, and it's inline or
10456 // a template, it's OK to form another definition of it.
10458 // FIXME: Should we skip the body of the function and use the old definition
10459 // in this case? That may be necessary for functions that return local types
10460 // through a deduced return type, or instantiate templates with local types.
10461 if (!hasVisibleDefinition(Definition) &&
10462 (Definition->getFormalLinkage() == InternalLinkage ||
10463 Definition->isInlined() ||
10464 Definition->getDescribedFunctionTemplate() ||
10465 Definition->getNumTemplateParameterLists()))
10468 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10469 Definition->getStorageClass() == SC_Extern)
10470 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10471 << FD->getDeclName() << getLangOpts().CPlusPlus;
10473 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10475 Diag(Definition->getLocation(), diag::note_previous_definition);
10476 FD->setInvalidDecl();
10480 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10482 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10484 LambdaScopeInfo *LSI = S.PushLambdaScope();
10485 LSI->CallOperator = CallOperator;
10486 LSI->Lambda = LambdaClass;
10487 LSI->ReturnType = CallOperator->getReturnType();
10488 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10490 if (LCD == LCD_None)
10491 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10492 else if (LCD == LCD_ByCopy)
10493 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10494 else if (LCD == LCD_ByRef)
10495 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10496 DeclarationNameInfo DNI = CallOperator->getNameInfo();
10498 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10499 LSI->Mutable = !CallOperator->isConst();
10501 // Add the captures to the LSI so they can be noted as already
10502 // captured within tryCaptureVar.
10503 auto I = LambdaClass->field_begin();
10504 for (const auto &C : LambdaClass->captures()) {
10505 if (C.capturesVariable()) {
10506 VarDecl *VD = C.getCapturedVar();
10507 if (VD->isInitCapture())
10508 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10509 QualType CaptureType = VD->getType();
10510 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10511 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10512 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10513 /*EllipsisLoc*/C.isPackExpansion()
10514 ? C.getEllipsisLoc() : SourceLocation(),
10515 CaptureType, /*Expr*/ nullptr);
10517 } else if (C.capturesThis()) {
10518 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10519 S.getCurrentThisType(), /*Expr*/ nullptr);
10521 LSI->addVLATypeCapture(C.getLocation(), I->getType());
10527 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10528 // Clear the last template instantiation error context.
10529 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10533 FunctionDecl *FD = nullptr;
10535 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10536 FD = FunTmpl->getTemplatedDecl();
10538 FD = cast<FunctionDecl>(D);
10539 // If we are instantiating a generic lambda call operator, push
10540 // a LambdaScopeInfo onto the function stack. But use the information
10541 // that's already been calculated (ActOnLambdaExpr) to prime the current
10542 // LambdaScopeInfo.
10543 // When the template operator is being specialized, the LambdaScopeInfo,
10544 // has to be properly restored so that tryCaptureVariable doesn't try
10545 // and capture any new variables. In addition when calculating potential
10546 // captures during transformation of nested lambdas, it is necessary to
10547 // have the LSI properly restored.
10548 if (isGenericLambdaCallOperatorSpecialization(FD)) {
10549 assert(ActiveTemplateInstantiations.size() &&
10550 "There should be an active template instantiation on the stack "
10551 "when instantiating a generic lambda!");
10552 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10555 // Enter a new function scope
10556 PushFunctionScope();
10558 // See if this is a redefinition.
10559 if (!FD->isLateTemplateParsed())
10560 CheckForFunctionRedefinition(FD);
10562 // Builtin functions cannot be defined.
10563 if (unsigned BuiltinID = FD->getBuiltinID()) {
10564 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10565 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10566 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10567 FD->setInvalidDecl();
10571 // The return type of a function definition must be complete
10572 // (C99 6.9.1p3, C++ [dcl.fct]p6).
10573 QualType ResultType = FD->getReturnType();
10574 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10575 !FD->isInvalidDecl() &&
10576 RequireCompleteType(FD->getLocation(), ResultType,
10577 diag::err_func_def_incomplete_result))
10578 FD->setInvalidDecl();
10581 PushDeclContext(FnBodyScope, FD);
10583 // Check the validity of our function parameters
10584 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10585 /*CheckParameterNames=*/true);
10587 // Introduce our parameters into the function scope
10588 for (auto Param : FD->params()) {
10589 Param->setOwningFunction(FD);
10591 // If this has an identifier, add it to the scope stack.
10592 if (Param->getIdentifier() && FnBodyScope) {
10593 CheckShadow(FnBodyScope, Param);
10595 PushOnScopeChains(Param, FnBodyScope);
10599 // If we had any tags defined in the function prototype,
10600 // introduce them into the function scope.
10602 for (ArrayRef<NamedDecl *>::iterator
10603 I = FD->getDeclsInPrototypeScope().begin(),
10604 E = FD->getDeclsInPrototypeScope().end();
10608 // Some of these decls (like enums) may have been pinned to the
10609 // translation unit for lack of a real context earlier. If so, remove
10610 // from the translation unit and reattach to the current context.
10611 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10612 // Is the decl actually in the context?
10613 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10615 Context.getTranslationUnitDecl()->removeDecl(D);
10619 // Either way, reassign the lexical decl context to our FunctionDecl.
10620 D->setLexicalDeclContext(CurContext);
10623 // If the decl has a non-null name, make accessible in the current scope.
10624 if (!D->getName().empty())
10625 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10627 // Similarly, dive into enums and fish their constants out, making them
10628 // accessible in this scope.
10629 if (auto *ED = dyn_cast<EnumDecl>(D)) {
10630 for (auto *EI : ED->enumerators())
10631 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10636 // Ensure that the function's exception specification is instantiated.
10637 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10638 ResolveExceptionSpec(D->getLocation(), FPT);
10640 // dllimport cannot be applied to non-inline function definitions.
10641 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10642 !FD->isTemplateInstantiation()) {
10643 assert(!FD->hasAttr<DLLExportAttr>());
10644 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10645 FD->setInvalidDecl();
10648 // We want to attach documentation to original Decl (which might be
10649 // a function template).
10650 ActOnDocumentableDecl(D);
10651 if (getCurLexicalContext()->isObjCContainer() &&
10652 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10653 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10654 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10659 /// \brief Given the set of return statements within a function body,
10660 /// compute the variables that are subject to the named return value
10663 /// Each of the variables that is subject to the named return value
10664 /// optimization will be marked as NRVO variables in the AST, and any
10665 /// return statement that has a marked NRVO variable as its NRVO candidate can
10666 /// use the named return value optimization.
10668 /// This function applies a very simplistic algorithm for NRVO: if every return
10669 /// statement in the scope of a variable has the same NRVO candidate, that
10670 /// candidate is an NRVO variable.
10671 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10672 ReturnStmt **Returns = Scope->Returns.data();
10674 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10675 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10676 if (!NRVOCandidate->isNRVOVariable())
10677 Returns[I]->setNRVOCandidate(nullptr);
10682 bool Sema::canDelayFunctionBody(const Declarator &D) {
10683 // We can't delay parsing the body of a constexpr function template (yet).
10684 if (D.getDeclSpec().isConstexprSpecified())
10687 // We can't delay parsing the body of a function template with a deduced
10688 // return type (yet).
10689 if (D.getDeclSpec().containsPlaceholderType()) {
10690 // If the placeholder introduces a non-deduced trailing return type,
10691 // we can still delay parsing it.
10692 if (D.getNumTypeObjects()) {
10693 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10694 if (Outer.Kind == DeclaratorChunk::Function &&
10695 Outer.Fun.hasTrailingReturnType()) {
10696 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10697 return Ty.isNull() || !Ty->isUndeducedType();
10706 bool Sema::canSkipFunctionBody(Decl *D) {
10707 // We cannot skip the body of a function (or function template) which is
10708 // constexpr, since we may need to evaluate its body in order to parse the
10709 // rest of the file.
10710 // We cannot skip the body of a function with an undeduced return type,
10711 // because any callers of that function need to know the type.
10712 if (const FunctionDecl *FD = D->getAsFunction())
10713 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10715 return Consumer.shouldSkipFunctionBody(D);
10718 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10719 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10720 FD->setHasSkippedBody();
10721 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10722 MD->setHasSkippedBody();
10723 return ActOnFinishFunctionBody(Decl, nullptr);
10726 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10727 return ActOnFinishFunctionBody(D, BodyArg, false);
10730 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10731 bool IsInstantiation) {
10732 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10734 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10735 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10740 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10741 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10742 // If the function has a deduced result type but contains no 'return'
10743 // statements, the result type as written must be exactly 'auto', and
10744 // the deduced result type is 'void'.
10745 if (!FD->getReturnType()->getAs<AutoType>()) {
10746 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10747 << FD->getReturnType();
10748 FD->setInvalidDecl();
10750 // Substitute 'void' for the 'auto' in the type.
10751 TypeLoc ResultType = getReturnTypeLoc(FD);
10752 Context.adjustDeducedFunctionResultType(
10753 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10755 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
10756 auto *LSI = getCurLambda();
10757 if (LSI->HasImplicitReturnType) {
10758 deduceClosureReturnType(*LSI);
10760 // C++11 [expr.prim.lambda]p4:
10761 // [...] if there are no return statements in the compound-statement
10762 // [the deduced type is] the type void
10764 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
10766 // Update the return type to the deduced type.
10767 const FunctionProtoType *Proto =
10768 FD->getType()->getAs<FunctionProtoType>();
10769 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
10770 Proto->getExtProtoInfo()));
10774 // The only way to be included in UndefinedButUsed is if there is an
10775 // ODR use before the definition. Avoid the expensive map lookup if this
10776 // is the first declaration.
10777 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10778 if (!FD->isExternallyVisible())
10779 UndefinedButUsed.erase(FD);
10780 else if (FD->isInlined() &&
10781 !LangOpts.GNUInline &&
10782 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10783 UndefinedButUsed.erase(FD);
10786 // If the function implicitly returns zero (like 'main') or is naked,
10787 // don't complain about missing return statements.
10788 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10789 WP.disableCheckFallThrough();
10791 // MSVC permits the use of pure specifier (=0) on function definition,
10792 // defined at class scope, warn about this non-standard construct.
10793 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10794 Diag(FD->getLocation(), diag::ext_pure_function_definition);
10796 if (!FD->isInvalidDecl()) {
10797 // Don't diagnose unused parameters of defaulted or deleted functions.
10798 if (!FD->isDeleted() && !FD->isDefaulted())
10799 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10800 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10801 FD->getReturnType(), FD);
10803 // If this is a structor, we need a vtable.
10804 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10805 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10806 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
10807 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
10809 // Try to apply the named return value optimization. We have to check
10810 // if we can do this here because lambdas keep return statements around
10811 // to deduce an implicit return type.
10812 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10813 !FD->isDependentContext())
10814 computeNRVO(Body, getCurFunction());
10817 // GNU warning -Wmissing-prototypes:
10818 // Warn if a global function is defined without a previous
10819 // prototype declaration. This warning is issued even if the
10820 // definition itself provides a prototype. The aim is to detect
10821 // global functions that fail to be declared in header files.
10822 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10823 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10824 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10826 if (PossibleZeroParamPrototype) {
10827 // We found a declaration that is not a prototype,
10828 // but that could be a zero-parameter prototype
10829 if (TypeSourceInfo *TI =
10830 PossibleZeroParamPrototype->getTypeSourceInfo()) {
10831 TypeLoc TL = TI->getTypeLoc();
10832 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10833 Diag(PossibleZeroParamPrototype->getLocation(),
10834 diag::note_declaration_not_a_prototype)
10835 << PossibleZeroParamPrototype
10836 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10841 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10842 const CXXMethodDecl *KeyFunction;
10843 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
10845 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
10846 MD == KeyFunction->getCanonicalDecl()) {
10847 // Update the key-function state if necessary for this ABI.
10848 if (FD->isInlined() &&
10849 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10850 Context.setNonKeyFunction(MD);
10852 // If the newly-chosen key function is already defined, then we
10853 // need to mark the vtable as used retroactively.
10854 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
10855 const FunctionDecl *Definition;
10856 if (KeyFunction && KeyFunction->isDefined(Definition))
10857 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
10859 // We just defined they key function; mark the vtable as used.
10860 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
10865 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10866 "Function parsing confused");
10867 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10868 assert(MD == getCurMethodDecl() && "Method parsing confused");
10870 if (!MD->isInvalidDecl()) {
10871 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10872 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10873 MD->getReturnType(), MD);
10876 computeNRVO(Body, getCurFunction());
10878 if (getCurFunction()->ObjCShouldCallSuper) {
10879 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10880 << MD->getSelector().getAsString();
10881 getCurFunction()->ObjCShouldCallSuper = false;
10883 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10884 const ObjCMethodDecl *InitMethod = nullptr;
10885 bool isDesignated =
10886 MD->isDesignatedInitializerForTheInterface(&InitMethod);
10887 assert(isDesignated && InitMethod);
10888 (void)isDesignated;
10890 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10891 auto IFace = MD->getClassInterface();
10894 auto SuperD = IFace->getSuperClass();
10897 return SuperD->getIdentifier() ==
10898 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10900 // Don't issue this warning for unavailable inits or direct subclasses
10902 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10903 Diag(MD->getLocation(),
10904 diag::warn_objc_designated_init_missing_super_call);
10905 Diag(InitMethod->getLocation(),
10906 diag::note_objc_designated_init_marked_here);
10908 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10910 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10911 // Don't issue this warning for unavaialable inits.
10912 if (!MD->isUnavailable())
10913 Diag(MD->getLocation(),
10914 diag::warn_objc_secondary_init_missing_init_call);
10915 getCurFunction()->ObjCWarnForNoInitDelegation = false;
10921 assert(!getCurFunction()->ObjCShouldCallSuper &&
10922 "This should only be set for ObjC methods, which should have been "
10923 "handled in the block above.");
10925 // Verify and clean out per-function state.
10926 if (Body && (!FD || !FD->isDefaulted())) {
10927 // C++ constructors that have function-try-blocks can't have return
10928 // statements in the handlers of that block. (C++ [except.handle]p14)
10930 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10931 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10933 // Verify that gotos and switch cases don't jump into scopes illegally.
10934 if (getCurFunction()->NeedsScopeChecking() &&
10935 !PP.isCodeCompletionEnabled())
10936 DiagnoseInvalidJumps(Body);
10938 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10939 if (!Destructor->getParent()->isDependentType())
10940 CheckDestructor(Destructor);
10942 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10943 Destructor->getParent());
10946 // If any errors have occurred, clear out any temporaries that may have
10947 // been leftover. This ensures that these temporaries won't be picked up for
10948 // deletion in some later function.
10949 if (getDiagnostics().hasErrorOccurred() ||
10950 getDiagnostics().getSuppressAllDiagnostics()) {
10951 DiscardCleanupsInEvaluationContext();
10953 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10954 !isa<FunctionTemplateDecl>(dcl)) {
10955 // Since the body is valid, issue any analysis-based warnings that are
10957 ActivePolicy = &WP;
10960 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10961 (!CheckConstexprFunctionDecl(FD) ||
10962 !CheckConstexprFunctionBody(FD, Body)))
10963 FD->setInvalidDecl();
10965 if (FD && FD->hasAttr<NakedAttr>()) {
10966 for (const Stmt *S : Body->children()) {
10967 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10968 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10969 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10970 FD->setInvalidDecl();
10976 assert(ExprCleanupObjects.size() ==
10977 ExprEvalContexts.back().NumCleanupObjects &&
10978 "Leftover temporaries in function");
10979 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10980 assert(MaybeODRUseExprs.empty() &&
10981 "Leftover expressions for odr-use checking");
10984 if (!IsInstantiation)
10987 PopFunctionScopeInfo(ActivePolicy, dcl);
10988 // If any errors have occurred, clear out any temporaries that may have
10989 // been leftover. This ensures that these temporaries won't be picked up for
10990 // deletion in some later function.
10991 if (getDiagnostics().hasErrorOccurred()) {
10992 DiscardCleanupsInEvaluationContext();
10999 /// When we finish delayed parsing of an attribute, we must attach it to the
11001 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11002 ParsedAttributes &Attrs) {
11003 // Always attach attributes to the underlying decl.
11004 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11005 D = TD->getTemplatedDecl();
11006 ProcessDeclAttributeList(S, D, Attrs.getList());
11008 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11009 if (Method->isStatic())
11010 checkThisInStaticMemberFunctionAttributes(Method);
11014 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11015 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11016 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11017 IdentifierInfo &II, Scope *S) {
11018 // Before we produce a declaration for an implicitly defined
11019 // function, see whether there was a locally-scoped declaration of
11020 // this name as a function or variable. If so, use that
11021 // (non-visible) declaration, and complain about it.
11022 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11023 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11024 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11025 return ExternCPrev;
11028 // Extension in C99. Legal in C90, but warn about it.
11030 if (II.getName().startswith("__builtin_"))
11031 diag_id = diag::warn_builtin_unknown;
11032 else if (getLangOpts().C99)
11033 diag_id = diag::ext_implicit_function_decl;
11035 diag_id = diag::warn_implicit_function_decl;
11036 Diag(Loc, diag_id) << &II;
11038 // Because typo correction is expensive, only do it if the implicit
11039 // function declaration is going to be treated as an error.
11040 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11041 TypoCorrection Corrected;
11043 (Corrected = CorrectTypo(
11044 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11045 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11046 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11047 /*ErrorRecovery*/false);
11050 // Set a Declarator for the implicit definition: int foo();
11052 AttributeFactory attrFactory;
11053 DeclSpec DS(attrFactory);
11055 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11056 Context.getPrintingPolicy());
11057 (void)Error; // Silence warning.
11058 assert(!Error && "Error setting up implicit decl!");
11059 SourceLocation NoLoc;
11060 Declarator D(DS, Declarator::BlockContext);
11061 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11062 /*IsAmbiguous=*/false,
11063 /*LParenLoc=*/NoLoc,
11064 /*Params=*/nullptr,
11066 /*EllipsisLoc=*/NoLoc,
11067 /*RParenLoc=*/NoLoc,
11069 /*RefQualifierIsLvalueRef=*/true,
11070 /*RefQualifierLoc=*/NoLoc,
11071 /*ConstQualifierLoc=*/NoLoc,
11072 /*VolatileQualifierLoc=*/NoLoc,
11073 /*RestrictQualifierLoc=*/NoLoc,
11074 /*MutableLoc=*/NoLoc,
11076 /*ESpecLoc=*/NoLoc,
11077 /*Exceptions=*/nullptr,
11078 /*ExceptionRanges=*/nullptr,
11079 /*NumExceptions=*/0,
11080 /*NoexceptExpr=*/nullptr,
11081 /*ExceptionSpecTokens=*/nullptr,
11083 DS.getAttributes(),
11085 D.SetIdentifier(&II, Loc);
11087 // Insert this function into translation-unit scope.
11089 DeclContext *PrevDC = CurContext;
11090 CurContext = Context.getTranslationUnitDecl();
11092 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11095 CurContext = PrevDC;
11097 AddKnownFunctionAttributes(FD);
11102 /// \brief Adds any function attributes that we know a priori based on
11103 /// the declaration of this function.
11105 /// These attributes can apply both to implicitly-declared builtins
11106 /// (like __builtin___printf_chk) or to library-declared functions
11107 /// like NSLog or printf.
11109 /// We need to check for duplicate attributes both here and where user-written
11110 /// attributes are applied to declarations.
11111 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11112 if (FD->isInvalidDecl())
11115 // If this is a built-in function, map its builtin attributes to
11116 // actual attributes.
11117 if (unsigned BuiltinID = FD->getBuiltinID()) {
11118 // Handle printf-formatting attributes.
11119 unsigned FormatIdx;
11121 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11122 if (!FD->hasAttr<FormatAttr>()) {
11123 const char *fmt = "printf";
11124 unsigned int NumParams = FD->getNumParams();
11125 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11126 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11128 FD->addAttr(FormatAttr::CreateImplicit(Context,
11129 &Context.Idents.get(fmt),
11131 HasVAListArg ? 0 : FormatIdx+2,
11132 FD->getLocation()));
11135 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11137 if (!FD->hasAttr<FormatAttr>())
11138 FD->addAttr(FormatAttr::CreateImplicit(Context,
11139 &Context.Idents.get("scanf"),
11141 HasVAListArg ? 0 : FormatIdx+2,
11142 FD->getLocation()));
11145 // Mark const if we don't care about errno and that is the only
11146 // thing preventing the function from being const. This allows
11147 // IRgen to use LLVM intrinsics for such functions.
11148 if (!getLangOpts().MathErrno &&
11149 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11150 if (!FD->hasAttr<ConstAttr>())
11151 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11154 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11155 !FD->hasAttr<ReturnsTwiceAttr>())
11156 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11157 FD->getLocation()));
11158 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11159 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11160 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11161 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11164 IdentifierInfo *Name = FD->getIdentifier();
11167 if ((!getLangOpts().CPlusPlus &&
11168 FD->getDeclContext()->isTranslationUnit()) ||
11169 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11170 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11171 LinkageSpecDecl::lang_c)) {
11172 // Okay: this could be a libc/libm/Objective-C function we know
11177 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11178 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11179 // target-specific builtins, perhaps?
11180 if (!FD->hasAttr<FormatAttr>())
11181 FD->addAttr(FormatAttr::CreateImplicit(Context,
11182 &Context.Idents.get("printf"), 2,
11183 Name->isStr("vasprintf") ? 0 : 3,
11184 FD->getLocation()));
11187 if (Name->isStr("__CFStringMakeConstantString")) {
11188 // We already have a __builtin___CFStringMakeConstantString,
11189 // but builds that use -fno-constant-cfstrings don't go through that.
11190 if (!FD->hasAttr<FormatArgAttr>())
11191 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11192 FD->getLocation()));
11196 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11197 TypeSourceInfo *TInfo) {
11198 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11199 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11202 assert(D.isInvalidType() && "no declarator info for valid type");
11203 TInfo = Context.getTrivialTypeSourceInfo(T);
11206 // Scope manipulation handled by caller.
11207 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11209 D.getIdentifierLoc(),
11213 // Bail out immediately if we have an invalid declaration.
11214 if (D.isInvalidType()) {
11215 NewTD->setInvalidDecl();
11219 if (D.getDeclSpec().isModulePrivateSpecified()) {
11220 if (CurContext->isFunctionOrMethod())
11221 Diag(NewTD->getLocation(), diag::err_module_private_local)
11222 << 2 << NewTD->getDeclName()
11223 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11224 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11226 NewTD->setModulePrivate();
11229 // C++ [dcl.typedef]p8:
11230 // If the typedef declaration defines an unnamed class (or
11231 // enum), the first typedef-name declared by the declaration
11232 // to be that class type (or enum type) is used to denote the
11233 // class type (or enum type) for linkage purposes only.
11234 // We need to check whether the type was declared in the declaration.
11235 switch (D.getDeclSpec().getTypeSpecType()) {
11238 case TST_interface:
11241 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11242 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11254 /// \brief Check that this is a valid underlying type for an enum declaration.
11255 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11256 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11257 QualType T = TI->getType();
11259 if (T->isDependentType())
11262 if (const BuiltinType *BT = T->getAs<BuiltinType>())
11263 if (BT->isInteger())
11266 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11270 /// Check whether this is a valid redeclaration of a previous enumeration.
11271 /// \return true if the redeclaration was invalid.
11272 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
11273 QualType EnumUnderlyingTy,
11274 const EnumDecl *Prev) {
11275 bool IsFixed = !EnumUnderlyingTy.isNull();
11277 if (IsScoped != Prev->isScoped()) {
11278 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11279 << Prev->isScoped();
11280 Diag(Prev->getLocation(), diag::note_previous_declaration);
11284 if (IsFixed && Prev->isFixed()) {
11285 if (!EnumUnderlyingTy->isDependentType() &&
11286 !Prev->getIntegerType()->isDependentType() &&
11287 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11288 Prev->getIntegerType())) {
11289 // TODO: Highlight the underlying type of the redeclaration.
11290 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11291 << EnumUnderlyingTy << Prev->getIntegerType();
11292 Diag(Prev->getLocation(), diag::note_previous_declaration)
11293 << Prev->getIntegerTypeRange();
11296 } else if (IsFixed != Prev->isFixed()) {
11297 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11298 << Prev->isFixed();
11299 Diag(Prev->getLocation(), diag::note_previous_declaration);
11306 /// \brief Get diagnostic %select index for tag kind for
11307 /// redeclaration diagnostic message.
11308 /// WARNING: Indexes apply to particular diagnostics only!
11310 /// \returns diagnostic %select index.
11311 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11313 case TTK_Struct: return 0;
11314 case TTK_Interface: return 1;
11315 case TTK_Class: return 2;
11316 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11320 /// \brief Determine if tag kind is a class-key compatible with
11321 /// class for redeclaration (class, struct, or __interface).
11323 /// \returns true iff the tag kind is compatible.
11324 static bool isClassCompatTagKind(TagTypeKind Tag)
11326 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11329 /// \brief Determine whether a tag with a given kind is acceptable
11330 /// as a redeclaration of the given tag declaration.
11332 /// \returns true if the new tag kind is acceptable, false otherwise.
11333 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11334 TagTypeKind NewTag, bool isDefinition,
11335 SourceLocation NewTagLoc,
11336 const IdentifierInfo *Name) {
11337 // C++ [dcl.type.elab]p3:
11338 // The class-key or enum keyword present in the
11339 // elaborated-type-specifier shall agree in kind with the
11340 // declaration to which the name in the elaborated-type-specifier
11341 // refers. This rule also applies to the form of
11342 // elaborated-type-specifier that declares a class-name or
11343 // friend class since it can be construed as referring to the
11344 // definition of the class. Thus, in any
11345 // elaborated-type-specifier, the enum keyword shall be used to
11346 // refer to an enumeration (7.2), the union class-key shall be
11347 // used to refer to a union (clause 9), and either the class or
11348 // struct class-key shall be used to refer to a class (clause 9)
11349 // declared using the class or struct class-key.
11350 TagTypeKind OldTag = Previous->getTagKind();
11351 if (!isDefinition || !isClassCompatTagKind(NewTag))
11352 if (OldTag == NewTag)
11355 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11356 // Warn about the struct/class tag mismatch.
11357 bool isTemplate = false;
11358 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11359 isTemplate = Record->getDescribedClassTemplate();
11361 if (!ActiveTemplateInstantiations.empty()) {
11362 // In a template instantiation, do not offer fix-its for tag mismatches
11363 // since they usually mess up the template instead of fixing the problem.
11364 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11365 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11366 << getRedeclDiagFromTagKind(OldTag);
11370 if (isDefinition) {
11371 // On definitions, check previous tags and issue a fix-it for each
11372 // one that doesn't match the current tag.
11373 if (Previous->getDefinition()) {
11374 // Don't suggest fix-its for redefinitions.
11378 bool previousMismatch = false;
11379 for (auto I : Previous->redecls()) {
11380 if (I->getTagKind() != NewTag) {
11381 if (!previousMismatch) {
11382 previousMismatch = true;
11383 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11384 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11385 << getRedeclDiagFromTagKind(I->getTagKind());
11387 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11388 << getRedeclDiagFromTagKind(NewTag)
11389 << FixItHint::CreateReplacement(I->getInnerLocStart(),
11390 TypeWithKeyword::getTagTypeKindName(NewTag));
11396 // Check for a previous definition. If current tag and definition
11397 // are same type, do nothing. If no definition, but disagree with
11398 // with previous tag type, give a warning, but no fix-it.
11399 const TagDecl *Redecl = Previous->getDefinition() ?
11400 Previous->getDefinition() : Previous;
11401 if (Redecl->getTagKind() == NewTag) {
11405 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11406 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11407 << getRedeclDiagFromTagKind(OldTag);
11408 Diag(Redecl->getLocation(), diag::note_previous_use);
11410 // If there is a previous definition, suggest a fix-it.
11411 if (Previous->getDefinition()) {
11412 Diag(NewTagLoc, diag::note_struct_class_suggestion)
11413 << getRedeclDiagFromTagKind(Redecl->getTagKind())
11414 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11415 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11423 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11424 /// from an outer enclosing namespace or file scope inside a friend declaration.
11425 /// This should provide the commented out code in the following snippet:
11429 /// struct Y { friend struct /*N::*/ X; };
11432 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11433 SourceLocation NameLoc) {
11434 // While the decl is in a namespace, do repeated lookup of that name and see
11435 // if we get the same namespace back. If we do not, continue until
11436 // translation unit scope, at which point we have a fully qualified NNS.
11437 SmallVector<IdentifierInfo *, 4> Namespaces;
11438 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11439 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11440 // This tag should be declared in a namespace, which can only be enclosed by
11441 // other namespaces. Bail if there's an anonymous namespace in the chain.
11442 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11443 if (!Namespace || Namespace->isAnonymousNamespace())
11444 return FixItHint();
11445 IdentifierInfo *II = Namespace->getIdentifier();
11446 Namespaces.push_back(II);
11447 NamedDecl *Lookup = SemaRef.LookupSingleName(
11448 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11449 if (Lookup == Namespace)
11453 // Once we have all the namespaces, reverse them to go outermost first, and
11455 SmallString<64> Insertion;
11456 llvm::raw_svector_ostream OS(Insertion);
11457 if (DC->isTranslationUnit())
11459 std::reverse(Namespaces.begin(), Namespaces.end());
11460 for (auto *II : Namespaces)
11461 OS << II->getName() << "::";
11463 return FixItHint::CreateInsertion(NameLoc, Insertion);
11466 /// \brief Determine whether a tag originally declared in context \p OldDC can
11467 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11468 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11469 /// using-declaration).
11470 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11471 DeclContext *NewDC) {
11472 OldDC = OldDC->getRedeclContext();
11473 NewDC = NewDC->getRedeclContext();
11475 if (OldDC->Equals(NewDC))
11478 // In MSVC mode, we allow a redeclaration if the contexts are related (either
11479 // encloses the other).
11480 if (S.getLangOpts().MSVCCompat &&
11481 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11487 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
11488 /// former case, Name will be non-null. In the later case, Name will be null.
11489 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11490 /// reference/declaration/definition of a tag.
11492 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11493 /// trailing-type-specifier) other than one in an alias-declaration.
11495 /// \param SkipBody If non-null, will be set to indicate if the caller should
11496 /// skip the definition of this tag and treat it as if it were a declaration.
11497 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11498 SourceLocation KWLoc, CXXScopeSpec &SS,
11499 IdentifierInfo *Name, SourceLocation NameLoc,
11500 AttributeList *Attr, AccessSpecifier AS,
11501 SourceLocation ModulePrivateLoc,
11502 MultiTemplateParamsArg TemplateParameterLists,
11503 bool &OwnedDecl, bool &IsDependent,
11504 SourceLocation ScopedEnumKWLoc,
11505 bool ScopedEnumUsesClassTag,
11506 TypeResult UnderlyingType,
11507 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11508 // If this is not a definition, it must have a name.
11509 IdentifierInfo *OrigName = Name;
11510 assert((Name != nullptr || TUK == TUK_Definition) &&
11511 "Nameless record must be a definition!");
11512 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11515 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11516 bool ScopedEnum = ScopedEnumKWLoc.isValid();
11518 // FIXME: Check explicit specializations more carefully.
11519 bool isExplicitSpecialization = false;
11520 bool Invalid = false;
11522 // We only need to do this matching if we have template parameters
11523 // or a scope specifier, which also conveniently avoids this work
11524 // for non-C++ cases.
11525 if (TemplateParameterLists.size() > 0 ||
11526 (SS.isNotEmpty() && TUK != TUK_Reference)) {
11527 if (TemplateParameterList *TemplateParams =
11528 MatchTemplateParametersToScopeSpecifier(
11529 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11530 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11531 if (Kind == TTK_Enum) {
11532 Diag(KWLoc, diag::err_enum_template);
11536 if (TemplateParams->size() > 0) {
11537 // This is a declaration or definition of a class template (which may
11538 // be a member of another template).
11544 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11545 SS, Name, NameLoc, Attr,
11546 TemplateParams, AS,
11548 /*FriendLoc*/SourceLocation(),
11549 TemplateParameterLists.size()-1,
11550 TemplateParameterLists.data(),
11552 return Result.get();
11554 // The "template<>" header is extraneous.
11555 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11556 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11557 isExplicitSpecialization = true;
11562 // Figure out the underlying type if this a enum declaration. We need to do
11563 // this early, because it's needed to detect if this is an incompatible
11565 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11567 if (Kind == TTK_Enum) {
11568 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11569 // No underlying type explicitly specified, or we failed to parse the
11570 // type, default to int.
11571 EnumUnderlying = Context.IntTy.getTypePtr();
11572 else if (UnderlyingType.get()) {
11573 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11574 // integral type; any cv-qualification is ignored.
11575 TypeSourceInfo *TI = nullptr;
11576 GetTypeFromParser(UnderlyingType.get(), &TI);
11577 EnumUnderlying = TI;
11579 if (CheckEnumUnderlyingType(TI))
11580 // Recover by falling back to int.
11581 EnumUnderlying = Context.IntTy.getTypePtr();
11583 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11584 UPPC_FixedUnderlyingType))
11585 EnumUnderlying = Context.IntTy.getTypePtr();
11587 } else if (getLangOpts().MSVCCompat)
11588 // Microsoft enums are always of int type.
11589 EnumUnderlying = Context.IntTy.getTypePtr();
11592 DeclContext *SearchDC = CurContext;
11593 DeclContext *DC = CurContext;
11594 bool isStdBadAlloc = false;
11596 RedeclarationKind Redecl = ForRedeclaration;
11597 if (TUK == TUK_Friend || TUK == TUK_Reference)
11598 Redecl = NotForRedeclaration;
11600 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11601 if (Name && SS.isNotEmpty()) {
11602 // We have a nested-name tag ('struct foo::bar').
11604 // Check for invalid 'foo::'.
11605 if (SS.isInvalid()) {
11607 goto CreateNewDecl;
11610 // If this is a friend or a reference to a class in a dependent
11611 // context, don't try to make a decl for it.
11612 if (TUK == TUK_Friend || TUK == TUK_Reference) {
11613 DC = computeDeclContext(SS, false);
11615 IsDependent = true;
11619 DC = computeDeclContext(SS, true);
11621 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11627 if (RequireCompleteDeclContext(SS, DC))
11631 // Look-up name inside 'foo::'.
11632 LookupQualifiedName(Previous, DC);
11634 if (Previous.isAmbiguous())
11637 if (Previous.empty()) {
11638 // Name lookup did not find anything. However, if the
11639 // nested-name-specifier refers to the current instantiation,
11640 // and that current instantiation has any dependent base
11641 // classes, we might find something at instantiation time: treat
11642 // this as a dependent elaborated-type-specifier.
11643 // But this only makes any sense for reference-like lookups.
11644 if (Previous.wasNotFoundInCurrentInstantiation() &&
11645 (TUK == TUK_Reference || TUK == TUK_Friend)) {
11646 IsDependent = true;
11650 // A tag 'foo::bar' must already exist.
11651 Diag(NameLoc, diag::err_not_tag_in_scope)
11652 << Kind << Name << DC << SS.getRange();
11655 goto CreateNewDecl;
11658 // C++14 [class.mem]p14:
11659 // If T is the name of a class, then each of the following shall have a
11660 // name different from T:
11661 // -- every member of class T that is itself a type
11662 if (TUK != TUK_Reference && TUK != TUK_Friend &&
11663 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
11666 // If this is a named struct, check to see if there was a previous forward
11667 // declaration or definition.
11668 // FIXME: We're looking into outer scopes here, even when we
11669 // shouldn't be. Doing so can result in ambiguities that we
11670 // shouldn't be diagnosing.
11671 LookupName(Previous, S);
11673 // When declaring or defining a tag, ignore ambiguities introduced
11674 // by types using'ed into this scope.
11675 if (Previous.isAmbiguous() &&
11676 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11677 LookupResult::Filter F = Previous.makeFilter();
11678 while (F.hasNext()) {
11679 NamedDecl *ND = F.next();
11680 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11686 // C++11 [namespace.memdef]p3:
11687 // If the name in a friend declaration is neither qualified nor
11688 // a template-id and the declaration is a function or an
11689 // elaborated-type-specifier, the lookup to determine whether
11690 // the entity has been previously declared shall not consider
11691 // any scopes outside the innermost enclosing namespace.
11693 // MSVC doesn't implement the above rule for types, so a friend tag
11694 // declaration may be a redeclaration of a type declared in an enclosing
11695 // scope. They do implement this rule for friend functions.
11697 // Does it matter that this should be by scope instead of by
11698 // semantic context?
11699 if (!Previous.empty() && TUK == TUK_Friend) {
11700 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11701 LookupResult::Filter F = Previous.makeFilter();
11702 bool FriendSawTagOutsideEnclosingNamespace = false;
11703 while (F.hasNext()) {
11704 NamedDecl *ND = F.next();
11705 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11706 if (DC->isFileContext() &&
11707 !EnclosingNS->Encloses(ND->getDeclContext())) {
11708 if (getLangOpts().MSVCCompat)
11709 FriendSawTagOutsideEnclosingNamespace = true;
11716 // Diagnose this MSVC extension in the easy case where lookup would have
11717 // unambiguously found something outside the enclosing namespace.
11718 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11719 NamedDecl *ND = Previous.getFoundDecl();
11720 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11721 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11725 // Note: there used to be some attempt at recovery here.
11726 if (Previous.isAmbiguous())
11729 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11730 // FIXME: This makes sure that we ignore the contexts associated
11731 // with C structs, unions, and enums when looking for a matching
11732 // tag declaration or definition. See the similar lookup tweak
11733 // in Sema::LookupName; is there a better way to deal with this?
11734 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11735 SearchDC = SearchDC->getParent();
11739 if (Previous.isSingleResult() &&
11740 Previous.getFoundDecl()->isTemplateParameter()) {
11741 // Maybe we will complain about the shadowed template parameter.
11742 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11743 // Just pretend that we didn't see the previous declaration.
11747 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11748 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11749 // This is a declaration of or a reference to "std::bad_alloc".
11750 isStdBadAlloc = true;
11752 if (Previous.empty() && StdBadAlloc) {
11753 // std::bad_alloc has been implicitly declared (but made invisible to
11754 // name lookup). Fill in this implicit declaration as the previous
11755 // declaration, so that the declarations get chained appropriately.
11756 Previous.addDecl(getStdBadAlloc());
11760 // If we didn't find a previous declaration, and this is a reference
11761 // (or friend reference), move to the correct scope. In C++, we
11762 // also need to do a redeclaration lookup there, just in case
11763 // there's a shadow friend decl.
11764 if (Name && Previous.empty() &&
11765 (TUK == TUK_Reference || TUK == TUK_Friend)) {
11766 if (Invalid) goto CreateNewDecl;
11767 assert(SS.isEmpty());
11769 if (TUK == TUK_Reference) {
11770 // C++ [basic.scope.pdecl]p5:
11771 // -- for an elaborated-type-specifier of the form
11773 // class-key identifier
11775 // if the elaborated-type-specifier is used in the
11776 // decl-specifier-seq or parameter-declaration-clause of a
11777 // function defined in namespace scope, the identifier is
11778 // declared as a class-name in the namespace that contains
11779 // the declaration; otherwise, except as a friend
11780 // declaration, the identifier is declared in the smallest
11781 // non-class, non-function-prototype scope that contains the
11784 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11785 // C structs and unions.
11787 // It is an error in C++ to declare (rather than define) an enum
11788 // type, including via an elaborated type specifier. We'll
11789 // diagnose that later; for now, declare the enum in the same
11790 // scope as we would have picked for any other tag type.
11792 // GNU C also supports this behavior as part of its incomplete
11793 // enum types extension, while GNU C++ does not.
11795 // Find the context where we'll be declaring the tag.
11796 // FIXME: We would like to maintain the current DeclContext as the
11797 // lexical context,
11798 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11799 SearchDC = SearchDC->getParent();
11801 // Find the scope where we'll be declaring the tag.
11802 while (S->isClassScope() ||
11803 (getLangOpts().CPlusPlus &&
11804 S->isFunctionPrototypeScope()) ||
11805 ((S->getFlags() & Scope::DeclScope) == 0) ||
11806 (S->getEntity() && S->getEntity()->isTransparentContext()))
11807 S = S->getParent();
11809 assert(TUK == TUK_Friend);
11810 // C++ [namespace.memdef]p3:
11811 // If a friend declaration in a non-local class first declares a
11812 // class or function, the friend class or function is a member of
11813 // the innermost enclosing namespace.
11814 SearchDC = SearchDC->getEnclosingNamespaceContext();
11817 // In C++, we need to do a redeclaration lookup to properly
11818 // diagnose some problems.
11819 if (getLangOpts().CPlusPlus) {
11820 Previous.setRedeclarationKind(ForRedeclaration);
11821 LookupQualifiedName(Previous, SearchDC);
11825 // If we have a known previous declaration to use, then use it.
11826 if (Previous.empty() && SkipBody && SkipBody->Previous)
11827 Previous.addDecl(SkipBody->Previous);
11829 if (!Previous.empty()) {
11830 NamedDecl *PrevDecl = Previous.getFoundDecl();
11831 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
11833 // It's okay to have a tag decl in the same scope as a typedef
11834 // which hides a tag decl in the same scope. Finding this
11835 // insanity with a redeclaration lookup can only actually happen
11838 // This is also okay for elaborated-type-specifiers, which is
11839 // technically forbidden by the current standard but which is
11840 // okay according to the likely resolution of an open issue;
11841 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11842 if (getLangOpts().CPlusPlus) {
11843 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11844 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11845 TagDecl *Tag = TT->getDecl();
11846 if (Tag->getDeclName() == Name &&
11847 Tag->getDeclContext()->getRedeclContext()
11848 ->Equals(TD->getDeclContext()->getRedeclContext())) {
11851 Previous.addDecl(Tag);
11852 Previous.resolveKind();
11858 // If this is a redeclaration of a using shadow declaration, it must
11859 // declare a tag in the same context. In MSVC mode, we allow a
11860 // redefinition if either context is within the other.
11861 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
11862 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
11863 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
11864 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
11865 !(OldTag && isAcceptableTagRedeclContext(
11866 *this, OldTag->getDeclContext(), SearchDC))) {
11867 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
11868 Diag(Shadow->getTargetDecl()->getLocation(),
11869 diag::note_using_decl_target);
11870 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
11872 // Recover by ignoring the old declaration.
11874 goto CreateNewDecl;
11878 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11879 // If this is a use of a previous tag, or if the tag is already declared
11880 // in the same scope (so that the definition/declaration completes or
11881 // rementions the tag), reuse the decl.
11882 if (TUK == TUK_Reference || TUK == TUK_Friend ||
11883 isDeclInScope(DirectPrevDecl, SearchDC, S,
11884 SS.isNotEmpty() || isExplicitSpecialization)) {
11885 // Make sure that this wasn't declared as an enum and now used as a
11886 // struct or something similar.
11887 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11888 TUK == TUK_Definition, KWLoc,
11890 bool SafeToContinue
11891 = (PrevTagDecl->getTagKind() != TTK_Enum &&
11893 if (SafeToContinue)
11894 Diag(KWLoc, diag::err_use_with_wrong_tag)
11896 << FixItHint::CreateReplacement(SourceRange(KWLoc),
11897 PrevTagDecl->getKindName());
11899 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11900 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11902 if (SafeToContinue)
11903 Kind = PrevTagDecl->getTagKind();
11905 // Recover by making this an anonymous redefinition.
11912 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11913 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11915 // If this is an elaborated-type-specifier for a scoped enumeration,
11916 // the 'class' keyword is not necessary and not permitted.
11917 if (TUK == TUK_Reference || TUK == TUK_Friend) {
11919 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11920 << PrevEnum->isScoped()
11921 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11922 return PrevTagDecl;
11925 QualType EnumUnderlyingTy;
11926 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11927 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11928 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11929 EnumUnderlyingTy = QualType(T, 0);
11931 // All conflicts with previous declarations are recovered by
11932 // returning the previous declaration, unless this is a definition,
11933 // in which case we want the caller to bail out.
11934 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11935 ScopedEnum, EnumUnderlyingTy, PrevEnum))
11936 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11939 // C++11 [class.mem]p1:
11940 // A member shall not be declared twice in the member-specification,
11941 // except that a nested class or member class template can be declared
11942 // and then later defined.
11943 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11944 S->isDeclScope(PrevDecl)) {
11945 Diag(NameLoc, diag::ext_member_redeclared);
11946 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11950 // If this is a use, just return the declaration we found, unless
11951 // we have attributes.
11953 // FIXME: In the future, return a variant or some other clue
11954 // for the consumer of this Decl to know it doesn't own it.
11955 // For our current ASTs this shouldn't be a problem, but will
11956 // need to be changed with DeclGroups.
11958 ((TUK == TUK_Reference &&
11959 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11960 || TUK == TUK_Friend))
11961 return PrevTagDecl;
11963 // Diagnose attempts to redefine a tag.
11964 if (TUK == TUK_Definition) {
11965 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
11966 // If we're defining a specialization and the previous definition
11967 // is from an implicit instantiation, don't emit an error
11968 // here; we'll catch this in the general case below.
11969 bool IsExplicitSpecializationAfterInstantiation = false;
11970 if (isExplicitSpecialization) {
11971 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11972 IsExplicitSpecializationAfterInstantiation =
11973 RD->getTemplateSpecializationKind() !=
11974 TSK_ExplicitSpecialization;
11975 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11976 IsExplicitSpecializationAfterInstantiation =
11977 ED->getTemplateSpecializationKind() !=
11978 TSK_ExplicitSpecialization;
11981 NamedDecl *Hidden = nullptr;
11982 if (SkipBody && getLangOpts().CPlusPlus &&
11983 !hasVisibleDefinition(Def, &Hidden)) {
11984 // There is a definition of this tag, but it is not visible. We
11985 // explicitly make use of C++'s one definition rule here, and
11986 // assume that this definition is identical to the hidden one
11987 // we already have. Make the existing definition visible and
11988 // use it in place of this one.
11989 SkipBody->ShouldSkip = true;
11990 makeMergedDefinitionVisible(Hidden, KWLoc);
11992 } else if (!IsExplicitSpecializationAfterInstantiation) {
11993 // A redeclaration in function prototype scope in C isn't
11994 // visible elsewhere, so merely issue a warning.
11995 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11996 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11998 Diag(NameLoc, diag::err_redefinition) << Name;
11999 Diag(Def->getLocation(), diag::note_previous_definition);
12000 // If this is a redefinition, recover by making this
12001 // struct be anonymous, which will make any later
12002 // references get the previous definition.
12008 // If the type is currently being defined, complain
12009 // about a nested redefinition.
12010 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12011 if (TD->isBeingDefined()) {
12012 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12013 Diag(PrevTagDecl->getLocation(),
12014 diag::note_previous_definition);
12021 // Okay, this is definition of a previously declared or referenced
12022 // tag. We're going to create a new Decl for it.
12025 // Okay, we're going to make a redeclaration. If this is some kind
12026 // of reference, make sure we build the redeclaration in the same DC
12027 // as the original, and ignore the current access specifier.
12028 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12029 SearchDC = PrevTagDecl->getDeclContext();
12033 // If we get here we have (another) forward declaration or we
12034 // have a definition. Just create a new decl.
12037 // If we get here, this is a definition of a new tag type in a nested
12038 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12039 // new decl/type. We set PrevDecl to NULL so that the entities
12040 // have distinct types.
12043 // If we get here, we're going to create a new Decl. If PrevDecl
12044 // is non-NULL, it's a definition of the tag declared by
12045 // PrevDecl. If it's NULL, we have a new definition.
12048 // Otherwise, PrevDecl is not a tag, but was found with tag
12049 // lookup. This is only actually possible in C++, where a few
12050 // things like templates still live in the tag namespace.
12052 // Use a better diagnostic if an elaborated-type-specifier
12053 // found the wrong kind of type on the first
12054 // (non-redeclaration) lookup.
12055 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12056 !Previous.isForRedeclaration()) {
12058 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12059 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12060 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12061 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12062 Diag(PrevDecl->getLocation(), diag::note_declared_at);
12065 // Otherwise, only diagnose if the declaration is in scope.
12066 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12067 SS.isNotEmpty() || isExplicitSpecialization)) {
12070 // Diagnose implicit declarations introduced by elaborated types.
12071 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12073 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12074 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12075 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12076 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12077 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12080 // Otherwise it's a declaration. Call out a particularly common
12082 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12084 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12085 Diag(NameLoc, diag::err_tag_definition_of_typedef)
12086 << Name << Kind << TND->getUnderlyingType();
12087 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12090 // Otherwise, diagnose.
12092 // The tag name clashes with something else in the target scope,
12093 // issue an error and recover by making this tag be anonymous.
12094 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12095 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12100 // The existing declaration isn't relevant to us; we're in a
12101 // new scope, so clear out the previous declaration.
12108 TagDecl *PrevDecl = nullptr;
12109 if (Previous.isSingleResult())
12110 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12112 // If there is an identifier, use the location of the identifier as the
12113 // location of the decl, otherwise use the location of the struct/union
12115 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12117 // Otherwise, create a new declaration. If there is a previous
12118 // declaration of the same entity, the two will be linked via
12122 bool IsForwardReference = false;
12123 if (Kind == TTK_Enum) {
12124 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12125 // enum X { A, B, C } D; D should chain to X.
12126 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12127 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12128 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12129 // If this is an undefined enum, warn.
12130 if (TUK != TUK_Definition && !Invalid) {
12132 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12133 cast<EnumDecl>(New)->isFixed()) {
12134 // C++0x: 7.2p2: opaque-enum-declaration.
12135 // Conflicts are diagnosed above. Do nothing.
12137 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12138 Diag(Loc, diag::ext_forward_ref_enum_def)
12140 Diag(Def->getLocation(), diag::note_previous_definition);
12142 unsigned DiagID = diag::ext_forward_ref_enum;
12143 if (getLangOpts().MSVCCompat)
12144 DiagID = diag::ext_ms_forward_ref_enum;
12145 else if (getLangOpts().CPlusPlus)
12146 DiagID = diag::err_forward_ref_enum;
12149 // If this is a forward-declared reference to an enumeration, make a
12150 // note of it; we won't actually be introducing the declaration into
12151 // the declaration context.
12152 if (TUK == TUK_Reference)
12153 IsForwardReference = true;
12157 if (EnumUnderlying) {
12158 EnumDecl *ED = cast<EnumDecl>(New);
12159 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12160 ED->setIntegerTypeSourceInfo(TI);
12162 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12163 ED->setPromotionType(ED->getIntegerType());
12167 // struct/union/class
12169 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12170 // struct X { int A; } D; D should chain to X.
12171 if (getLangOpts().CPlusPlus) {
12172 // FIXME: Look for a way to use RecordDecl for simple structs.
12173 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12174 cast_or_null<CXXRecordDecl>(PrevDecl));
12176 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12177 StdBadAlloc = cast<CXXRecordDecl>(New);
12179 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12180 cast_or_null<RecordDecl>(PrevDecl));
12183 // C++11 [dcl.type]p3:
12184 // A type-specifier-seq shall not define a class or enumeration [...].
12185 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12186 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12187 << Context.getTagDeclType(New);
12191 // Maybe add qualifier info.
12192 if (SS.isNotEmpty()) {
12194 // If this is either a declaration or a definition, check the
12195 // nested-name-specifier against the current context. We don't do this
12196 // for explicit specializations, because they have similar checking
12197 // (with more specific diagnostics) in the call to
12198 // CheckMemberSpecialization, below.
12199 if (!isExplicitSpecialization &&
12200 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12201 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12204 New->setQualifierInfo(SS.getWithLocInContext(Context));
12205 if (TemplateParameterLists.size() > 0) {
12206 New->setTemplateParameterListsInfo(Context,
12207 TemplateParameterLists.size(),
12208 TemplateParameterLists.data());
12215 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12216 // Add alignment attributes if necessary; these attributes are checked when
12217 // the ASTContext lays out the structure.
12219 // It is important for implementing the correct semantics that this
12220 // happen here (in act on tag decl). The #pragma pack stack is
12221 // maintained as a result of parser callbacks which can occur at
12222 // many points during the parsing of a struct declaration (because
12223 // the #pragma tokens are effectively skipped over during the
12224 // parsing of the struct).
12225 if (TUK == TUK_Definition) {
12226 AddAlignmentAttributesForRecord(RD);
12227 AddMsStructLayoutForRecord(RD);
12231 if (ModulePrivateLoc.isValid()) {
12232 if (isExplicitSpecialization)
12233 Diag(New->getLocation(), diag::err_module_private_specialization)
12235 << FixItHint::CreateRemoval(ModulePrivateLoc);
12236 // __module_private__ does not apply to local classes. However, we only
12237 // diagnose this as an error when the declaration specifiers are
12238 // freestanding. Here, we just ignore the __module_private__.
12239 else if (!SearchDC->isFunctionOrMethod())
12240 New->setModulePrivate();
12243 // If this is a specialization of a member class (of a class template),
12244 // check the specialization.
12245 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12248 // If we're declaring or defining a tag in function prototype scope in C,
12249 // note that this type can only be used within the function and add it to
12250 // the list of decls to inject into the function definition scope.
12251 if ((Name || Kind == TTK_Enum) &&
12252 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12253 if (getLangOpts().CPlusPlus) {
12254 // C++ [dcl.fct]p6:
12255 // Types shall not be defined in return or parameter types.
12256 if (TUK == TUK_Definition && !IsTypeSpecifier) {
12257 Diag(Loc, diag::err_type_defined_in_param_type)
12262 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12264 DeclsInPrototypeScope.push_back(New);
12268 New->setInvalidDecl();
12271 ProcessDeclAttributeList(S, New, Attr);
12273 // Set the lexical context. If the tag has a C++ scope specifier, the
12274 // lexical context will be different from the semantic context.
12275 New->setLexicalDeclContext(CurContext);
12277 // Mark this as a friend decl if applicable.
12278 // In Microsoft mode, a friend declaration also acts as a forward
12279 // declaration so we always pass true to setObjectOfFriendDecl to make
12280 // the tag name visible.
12281 if (TUK == TUK_Friend)
12282 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12284 // Set the access specifier.
12285 if (!Invalid && SearchDC->isRecord())
12286 SetMemberAccessSpecifier(New, PrevDecl, AS);
12288 if (TUK == TUK_Definition)
12289 New->startDefinition();
12291 // If this has an identifier, add it to the scope stack.
12292 if (TUK == TUK_Friend) {
12293 // We might be replacing an existing declaration in the lookup tables;
12294 // if so, borrow its access specifier.
12296 New->setAccess(PrevDecl->getAccess());
12298 DeclContext *DC = New->getDeclContext()->getRedeclContext();
12299 DC->makeDeclVisibleInContext(New);
12300 if (Name) // can be null along some error paths
12301 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12302 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12304 S = getNonFieldDeclScope(S);
12305 PushOnScopeChains(New, S, !IsForwardReference);
12306 if (IsForwardReference)
12307 SearchDC->makeDeclVisibleInContext(New);
12310 CurContext->addDecl(New);
12313 // If this is the C FILE type, notify the AST context.
12314 if (IdentifierInfo *II = New->getIdentifier())
12315 if (!New->isInvalidDecl() &&
12316 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12318 Context.setFILEDecl(New);
12321 mergeDeclAttributes(New, PrevDecl);
12323 // If there's a #pragma GCC visibility in scope, set the visibility of this
12325 AddPushedVisibilityAttribute(New);
12328 // In C++, don't return an invalid declaration. We can't recover well from
12329 // the cases where we make the type anonymous.
12330 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12333 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12334 AdjustDeclIfTemplate(TagD);
12335 TagDecl *Tag = cast<TagDecl>(TagD);
12337 // Enter the tag context.
12338 PushDeclContext(S, Tag);
12340 ActOnDocumentableDecl(TagD);
12342 // If there's a #pragma GCC visibility in scope, set the visibility of this
12344 AddPushedVisibilityAttribute(Tag);
12347 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12348 assert(isa<ObjCContainerDecl>(IDecl) &&
12349 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12350 DeclContext *OCD = cast<DeclContext>(IDecl);
12351 assert(getContainingDC(OCD) == CurContext &&
12352 "The next DeclContext should be lexically contained in the current one.");
12357 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12358 SourceLocation FinalLoc,
12359 bool IsFinalSpelledSealed,
12360 SourceLocation LBraceLoc) {
12361 AdjustDeclIfTemplate(TagD);
12362 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12364 FieldCollector->StartClass();
12366 if (!Record->getIdentifier())
12369 if (FinalLoc.isValid())
12370 Record->addAttr(new (Context)
12371 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12374 // [...] The class-name is also inserted into the scope of the
12375 // class itself; this is known as the injected-class-name. For
12376 // purposes of access checking, the injected-class-name is treated
12377 // as if it were a public member name.
12378 CXXRecordDecl *InjectedClassName
12379 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12380 Record->getLocStart(), Record->getLocation(),
12381 Record->getIdentifier(),
12382 /*PrevDecl=*/nullptr,
12383 /*DelayTypeCreation=*/true);
12384 Context.getTypeDeclType(InjectedClassName, Record);
12385 InjectedClassName->setImplicit();
12386 InjectedClassName->setAccess(AS_public);
12387 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12388 InjectedClassName->setDescribedClassTemplate(Template);
12389 PushOnScopeChains(InjectedClassName, S);
12390 assert(InjectedClassName->isInjectedClassName() &&
12391 "Broken injected-class-name");
12394 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12395 SourceLocation RBraceLoc) {
12396 AdjustDeclIfTemplate(TagD);
12397 TagDecl *Tag = cast<TagDecl>(TagD);
12398 Tag->setRBraceLoc(RBraceLoc);
12400 // Make sure we "complete" the definition even it is invalid.
12401 if (Tag->isBeingDefined()) {
12402 assert(Tag->isInvalidDecl() && "We should already have completed it");
12403 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12404 RD->completeDefinition();
12407 if (isa<CXXRecordDecl>(Tag))
12408 FieldCollector->FinishClass();
12410 // Exit this scope of this tag's definition.
12413 if (getCurLexicalContext()->isObjCContainer() &&
12414 Tag->getDeclContext()->isFileContext())
12415 Tag->setTopLevelDeclInObjCContainer();
12417 // Notify the consumer that we've defined a tag.
12418 if (!Tag->isInvalidDecl())
12419 Consumer.HandleTagDeclDefinition(Tag);
12422 void Sema::ActOnObjCContainerFinishDefinition() {
12423 // Exit this scope of this interface definition.
12427 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12428 assert(DC == CurContext && "Mismatch of container contexts");
12429 OriginalLexicalContext = DC;
12430 ActOnObjCContainerFinishDefinition();
12433 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12434 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12435 OriginalLexicalContext = nullptr;
12438 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12439 AdjustDeclIfTemplate(TagD);
12440 TagDecl *Tag = cast<TagDecl>(TagD);
12441 Tag->setInvalidDecl();
12443 // Make sure we "complete" the definition even it is invalid.
12444 if (Tag->isBeingDefined()) {
12445 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12446 RD->completeDefinition();
12449 // We're undoing ActOnTagStartDefinition here, not
12450 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12451 // the FieldCollector.
12456 // Note that FieldName may be null for anonymous bitfields.
12457 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12458 IdentifierInfo *FieldName,
12459 QualType FieldTy, bool IsMsStruct,
12460 Expr *BitWidth, bool *ZeroWidth) {
12461 // Default to true; that shouldn't confuse checks for emptiness
12465 // C99 6.7.2.1p4 - verify the field type.
12466 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12467 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12468 // Handle incomplete types with specific error.
12469 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12470 return ExprError();
12472 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12473 << FieldName << FieldTy << BitWidth->getSourceRange();
12474 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12475 << FieldTy << BitWidth->getSourceRange();
12476 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12477 UPPC_BitFieldWidth))
12478 return ExprError();
12480 // If the bit-width is type- or value-dependent, don't try to check
12482 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12485 llvm::APSInt Value;
12486 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12487 if (ICE.isInvalid())
12489 BitWidth = ICE.get();
12491 if (Value != 0 && ZeroWidth)
12492 *ZeroWidth = false;
12494 // Zero-width bitfield is ok for anonymous field.
12495 if (Value == 0 && FieldName)
12496 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12498 if (Value.isSigned() && Value.isNegative()) {
12500 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12501 << FieldName << Value.toString(10);
12502 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12503 << Value.toString(10);
12506 if (!FieldTy->isDependentType()) {
12507 uint64_t TypeSize = Context.getTypeSize(FieldTy);
12508 if (Value.getZExtValue() > TypeSize) {
12509 if (!getLangOpts().CPlusPlus || IsMsStruct ||
12510 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12512 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12513 << FieldName << (unsigned)Value.getZExtValue()
12514 << (unsigned)TypeSize;
12516 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12517 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12521 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12522 << FieldName << (unsigned)Value.getZExtValue()
12523 << (unsigned)TypeSize;
12525 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12526 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12533 /// ActOnField - Each field of a C struct/union is passed into this in order
12534 /// to create a FieldDecl object for it.
12535 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12536 Declarator &D, Expr *BitfieldWidth) {
12537 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12538 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12539 /*InitStyle=*/ICIS_NoInit, AS_public);
12543 /// HandleField - Analyze a field of a C struct or a C++ data member.
12545 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12546 SourceLocation DeclStart,
12547 Declarator &D, Expr *BitWidth,
12548 InClassInitStyle InitStyle,
12549 AccessSpecifier AS) {
12550 IdentifierInfo *II = D.getIdentifier();
12551 SourceLocation Loc = DeclStart;
12552 if (II) Loc = D.getIdentifierLoc();
12554 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12555 QualType T = TInfo->getType();
12556 if (getLangOpts().CPlusPlus) {
12557 CheckExtraCXXDefaultArguments(D);
12559 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12560 UPPC_DataMemberType)) {
12561 D.setInvalidType();
12563 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12567 // TR 18037 does not allow fields to be declared with address spaces.
12568 if (T.getQualifiers().hasAddressSpace()) {
12569 Diag(Loc, diag::err_field_with_address_space);
12570 D.setInvalidType();
12573 // OpenCL 1.2 spec, s6.9 r:
12574 // The event type cannot be used to declare a structure or union field.
12575 if (LangOpts.OpenCL && T->isEventT()) {
12576 Diag(Loc, diag::err_event_t_struct_field);
12577 D.setInvalidType();
12580 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12582 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12583 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12584 diag::err_invalid_thread)
12585 << DeclSpec::getSpecifierName(TSCS);
12587 // Check to see if this name was declared as a member previously
12588 NamedDecl *PrevDecl = nullptr;
12589 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12590 LookupName(Previous, S);
12591 switch (Previous.getResultKind()) {
12592 case LookupResult::Found:
12593 case LookupResult::FoundUnresolvedValue:
12594 PrevDecl = Previous.getAsSingle<NamedDecl>();
12597 case LookupResult::FoundOverloaded:
12598 PrevDecl = Previous.getRepresentativeDecl();
12601 case LookupResult::NotFound:
12602 case LookupResult::NotFoundInCurrentInstantiation:
12603 case LookupResult::Ambiguous:
12606 Previous.suppressDiagnostics();
12608 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12609 // Maybe we will complain about the shadowed template parameter.
12610 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12611 // Just pretend that we didn't see the previous declaration.
12612 PrevDecl = nullptr;
12615 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12616 PrevDecl = nullptr;
12619 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12620 SourceLocation TSSL = D.getLocStart();
12622 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12623 TSSL, AS, PrevDecl, &D);
12625 if (NewFD->isInvalidDecl())
12626 Record->setInvalidDecl();
12628 if (D.getDeclSpec().isModulePrivateSpecified())
12629 NewFD->setModulePrivate();
12631 if (NewFD->isInvalidDecl() && PrevDecl) {
12632 // Don't introduce NewFD into scope; there's already something
12633 // with the same name in the same scope.
12635 PushOnScopeChains(NewFD, S);
12637 Record->addDecl(NewFD);
12642 /// \brief Build a new FieldDecl and check its well-formedness.
12644 /// This routine builds a new FieldDecl given the fields name, type,
12645 /// record, etc. \p PrevDecl should refer to any previous declaration
12646 /// with the same name and in the same scope as the field to be
12649 /// \returns a new FieldDecl.
12651 /// \todo The Declarator argument is a hack. It will be removed once
12652 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12653 TypeSourceInfo *TInfo,
12654 RecordDecl *Record, SourceLocation Loc,
12655 bool Mutable, Expr *BitWidth,
12656 InClassInitStyle InitStyle,
12657 SourceLocation TSSL,
12658 AccessSpecifier AS, NamedDecl *PrevDecl,
12660 IdentifierInfo *II = Name.getAsIdentifierInfo();
12661 bool InvalidDecl = false;
12662 if (D) InvalidDecl = D->isInvalidType();
12664 // If we receive a broken type, recover by assuming 'int' and
12665 // marking this declaration as invalid.
12667 InvalidDecl = true;
12671 QualType EltTy = Context.getBaseElementType(T);
12672 if (!EltTy->isDependentType()) {
12673 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12674 // Fields of incomplete type force their record to be invalid.
12675 Record->setInvalidDecl();
12676 InvalidDecl = true;
12679 EltTy->isIncompleteType(&Def);
12680 if (Def && Def->isInvalidDecl()) {
12681 Record->setInvalidDecl();
12682 InvalidDecl = true;
12687 // OpenCL v1.2 s6.9.c: bitfields are not supported.
12688 if (BitWidth && getLangOpts().OpenCL) {
12689 Diag(Loc, diag::err_opencl_bitfields);
12690 InvalidDecl = true;
12693 // C99 6.7.2.1p8: A member of a structure or union may have any type other
12694 // than a variably modified type.
12695 if (!InvalidDecl && T->isVariablyModifiedType()) {
12696 bool SizeIsNegative;
12697 llvm::APSInt Oversized;
12699 TypeSourceInfo *FixedTInfo =
12700 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12704 Diag(Loc, diag::warn_illegal_constant_array_size);
12705 TInfo = FixedTInfo;
12706 T = FixedTInfo->getType();
12708 if (SizeIsNegative)
12709 Diag(Loc, diag::err_typecheck_negative_array_size);
12710 else if (Oversized.getBoolValue())
12711 Diag(Loc, diag::err_array_too_large)
12712 << Oversized.toString(10);
12714 Diag(Loc, diag::err_typecheck_field_variable_size);
12715 InvalidDecl = true;
12719 // Fields can not have abstract class types
12720 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12721 diag::err_abstract_type_in_decl,
12722 AbstractFieldType))
12723 InvalidDecl = true;
12725 bool ZeroWidth = false;
12727 BitWidth = nullptr;
12728 // If this is declared as a bit-field, check the bit-field.
12730 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12733 InvalidDecl = true;
12734 BitWidth = nullptr;
12739 // Check that 'mutable' is consistent with the type of the declaration.
12740 if (!InvalidDecl && Mutable) {
12741 unsigned DiagID = 0;
12742 if (T->isReferenceType())
12743 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
12744 : diag::err_mutable_reference;
12745 else if (T.isConstQualified())
12746 DiagID = diag::err_mutable_const;
12749 SourceLocation ErrLoc = Loc;
12750 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12751 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12752 Diag(ErrLoc, DiagID);
12753 if (DiagID != diag::ext_mutable_reference) {
12755 InvalidDecl = true;
12760 // C++11 [class.union]p8 (DR1460):
12761 // At most one variant member of a union may have a
12762 // brace-or-equal-initializer.
12763 if (InitStyle != ICIS_NoInit)
12764 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12766 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12767 BitWidth, Mutable, InitStyle);
12769 NewFD->setInvalidDecl();
12771 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12772 Diag(Loc, diag::err_duplicate_member) << II;
12773 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12774 NewFD->setInvalidDecl();
12777 if (!InvalidDecl && getLangOpts().CPlusPlus) {
12778 if (Record->isUnion()) {
12779 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12780 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12781 if (RDecl->getDefinition()) {
12782 // C++ [class.union]p1: An object of a class with a non-trivial
12783 // constructor, a non-trivial copy constructor, a non-trivial
12784 // destructor, or a non-trivial copy assignment operator
12785 // cannot be a member of a union, nor can an array of such
12787 if (CheckNontrivialField(NewFD))
12788 NewFD->setInvalidDecl();
12792 // C++ [class.union]p1: If a union contains a member of reference type,
12793 // the program is ill-formed, except when compiling with MSVC extensions
12795 if (EltTy->isReferenceType()) {
12796 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12797 diag::ext_union_member_of_reference_type :
12798 diag::err_union_member_of_reference_type)
12799 << NewFD->getDeclName() << EltTy;
12800 if (!getLangOpts().MicrosoftExt)
12801 NewFD->setInvalidDecl();
12806 // FIXME: We need to pass in the attributes given an AST
12807 // representation, not a parser representation.
12809 // FIXME: The current scope is almost... but not entirely... correct here.
12810 ProcessDeclAttributes(getCurScope(), NewFD, *D);
12812 if (NewFD->hasAttrs())
12813 CheckAlignasUnderalignment(NewFD);
12816 // In auto-retain/release, infer strong retension for fields of
12817 // retainable type.
12818 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12819 NewFD->setInvalidDecl();
12821 if (T.isObjCGCWeak())
12822 Diag(Loc, diag::warn_attribute_weak_on_field);
12824 NewFD->setAccess(AS);
12828 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12830 assert(getLangOpts().CPlusPlus && "valid check only for C++");
12832 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12835 QualType EltTy = Context.getBaseElementType(FD->getType());
12836 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12837 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12838 if (RDecl->getDefinition()) {
12839 // We check for copy constructors before constructors
12840 // because otherwise we'll never get complaints about
12841 // copy constructors.
12843 CXXSpecialMember member = CXXInvalid;
12844 // We're required to check for any non-trivial constructors. Since the
12845 // implicit default constructor is suppressed if there are any
12846 // user-declared constructors, we just need to check that there is a
12847 // trivial default constructor and a trivial copy constructor. (We don't
12848 // worry about move constructors here, since this is a C++98 check.)
12849 if (RDecl->hasNonTrivialCopyConstructor())
12850 member = CXXCopyConstructor;
12851 else if (!RDecl->hasTrivialDefaultConstructor())
12852 member = CXXDefaultConstructor;
12853 else if (RDecl->hasNonTrivialCopyAssignment())
12854 member = CXXCopyAssignment;
12855 else if (RDecl->hasNonTrivialDestructor())
12856 member = CXXDestructor;
12858 if (member != CXXInvalid) {
12859 if (!getLangOpts().CPlusPlus11 &&
12860 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12861 // Objective-C++ ARC: it is an error to have a non-trivial field of
12862 // a union. However, system headers in Objective-C programs
12863 // occasionally have Objective-C lifetime objects within unions,
12864 // and rather than cause the program to fail, we make those
12865 // members unavailable.
12866 SourceLocation Loc = FD->getLocation();
12867 if (getSourceManager().isInSystemHeader(Loc)) {
12868 if (!FD->hasAttr<UnavailableAttr>())
12869 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12870 "this system field has retaining ownership",
12876 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12877 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12878 diag::err_illegal_union_or_anon_struct_member)
12879 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12880 DiagnoseNontrivial(RDecl, member);
12881 return !getLangOpts().CPlusPlus11;
12889 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12890 /// AST enum value.
12891 static ObjCIvarDecl::AccessControl
12892 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12893 switch (ivarVisibility) {
12894 default: llvm_unreachable("Unknown visitibility kind");
12895 case tok::objc_private: return ObjCIvarDecl::Private;
12896 case tok::objc_public: return ObjCIvarDecl::Public;
12897 case tok::objc_protected: return ObjCIvarDecl::Protected;
12898 case tok::objc_package: return ObjCIvarDecl::Package;
12902 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12903 /// in order to create an IvarDecl object for it.
12904 Decl *Sema::ActOnIvar(Scope *S,
12905 SourceLocation DeclStart,
12906 Declarator &D, Expr *BitfieldWidth,
12907 tok::ObjCKeywordKind Visibility) {
12909 IdentifierInfo *II = D.getIdentifier();
12910 Expr *BitWidth = (Expr*)BitfieldWidth;
12911 SourceLocation Loc = DeclStart;
12912 if (II) Loc = D.getIdentifierLoc();
12914 // FIXME: Unnamed fields can be handled in various different ways, for
12915 // example, unnamed unions inject all members into the struct namespace!
12917 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12918 QualType T = TInfo->getType();
12921 // 6.7.2.1p3, 6.7.2.1p4
12922 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12924 D.setInvalidType();
12931 if (T->isReferenceType()) {
12932 Diag(Loc, diag::err_ivar_reference_type);
12933 D.setInvalidType();
12935 // C99 6.7.2.1p8: A member of a structure or union may have any type other
12936 // than a variably modified type.
12937 else if (T->isVariablyModifiedType()) {
12938 Diag(Loc, diag::err_typecheck_ivar_variable_size);
12939 D.setInvalidType();
12942 // Get the visibility (access control) for this ivar.
12943 ObjCIvarDecl::AccessControl ac =
12944 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12945 : ObjCIvarDecl::None;
12946 // Must set ivar's DeclContext to its enclosing interface.
12947 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12948 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12950 ObjCContainerDecl *EnclosingContext;
12951 if (ObjCImplementationDecl *IMPDecl =
12952 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12953 if (LangOpts.ObjCRuntime.isFragile()) {
12954 // Case of ivar declared in an implementation. Context is that of its class.
12955 EnclosingContext = IMPDecl->getClassInterface();
12956 assert(EnclosingContext && "Implementation has no class interface!");
12959 EnclosingContext = EnclosingDecl;
12961 if (ObjCCategoryDecl *CDecl =
12962 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12963 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12964 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12968 EnclosingContext = EnclosingDecl;
12971 // Construct the decl.
12972 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12973 DeclStart, Loc, II, T,
12974 TInfo, ac, (Expr *)BitfieldWidth);
12977 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12979 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12980 && !isa<TagDecl>(PrevDecl)) {
12981 Diag(Loc, diag::err_duplicate_member) << II;
12982 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12983 NewID->setInvalidDecl();
12987 // Process attributes attached to the ivar.
12988 ProcessDeclAttributes(S, NewID, D);
12990 if (D.isInvalidType())
12991 NewID->setInvalidDecl();
12993 // In ARC, infer 'retaining' for ivars of retainable type.
12994 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12995 NewID->setInvalidDecl();
12997 if (D.getDeclSpec().isModulePrivateSpecified())
12998 NewID->setModulePrivate();
13001 // FIXME: When interfaces are DeclContexts, we'll need to add
13002 // these to the interface.
13004 IdResolver.AddDecl(NewID);
13007 if (LangOpts.ObjCRuntime.isNonFragile() &&
13008 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13009 Diag(Loc, diag::warn_ivars_in_interface);
13014 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13015 /// class and class extensions. For every class \@interface and class
13016 /// extension \@interface, if the last ivar is a bitfield of any type,
13017 /// then add an implicit `char :0` ivar to the end of that interface.
13018 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13019 SmallVectorImpl<Decl *> &AllIvarDecls) {
13020 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13023 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13024 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13026 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13028 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13030 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13031 if (!CD->IsClassExtension())
13034 // No need to add this to end of @implementation.
13038 // All conditions are met. Add a new bitfield to the tail end of ivars.
13039 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13040 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13042 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13043 DeclLoc, DeclLoc, nullptr,
13045 Context.getTrivialTypeSourceInfo(Context.CharTy,
13047 ObjCIvarDecl::Private, BW,
13049 AllIvarDecls.push_back(Ivar);
13052 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13053 ArrayRef<Decl *> Fields, SourceLocation LBrac,
13054 SourceLocation RBrac, AttributeList *Attr) {
13055 assert(EnclosingDecl && "missing record or interface decl");
13057 // If this is an Objective-C @implementation or category and we have
13058 // new fields here we should reset the layout of the interface since
13059 // it will now change.
13060 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13061 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13062 switch (DC->getKind()) {
13064 case Decl::ObjCCategory:
13065 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13067 case Decl::ObjCImplementation:
13069 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13074 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13076 // Start counting up the number of named members; make sure to include
13077 // members of anonymous structs and unions in the total.
13078 unsigned NumNamedMembers = 0;
13080 for (const auto *I : Record->decls()) {
13081 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13082 if (IFD->getDeclName())
13087 // Verify that all the fields are okay.
13088 SmallVector<FieldDecl*, 32> RecFields;
13090 bool ARCErrReported = false;
13091 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13093 FieldDecl *FD = cast<FieldDecl>(*i);
13095 // Get the type for the field.
13096 const Type *FDTy = FD->getType().getTypePtr();
13098 if (!FD->isAnonymousStructOrUnion()) {
13099 // Remember all fields written by the user.
13100 RecFields.push_back(FD);
13103 // If the field is already invalid for some reason, don't emit more
13104 // diagnostics about it.
13105 if (FD->isInvalidDecl()) {
13106 EnclosingDecl->setInvalidDecl();
13111 // A structure or union shall not contain a member with
13112 // incomplete or function type (hence, a structure shall not
13113 // contain an instance of itself, but may contain a pointer to
13114 // an instance of itself), except that the last member of a
13115 // structure with more than one named member may have incomplete
13116 // array type; such a structure (and any union containing,
13117 // possibly recursively, a member that is such a structure)
13118 // shall not be a member of a structure or an element of an
13120 if (FDTy->isFunctionType()) {
13121 // Field declared as a function.
13122 Diag(FD->getLocation(), diag::err_field_declared_as_function)
13123 << FD->getDeclName();
13124 FD->setInvalidDecl();
13125 EnclosingDecl->setInvalidDecl();
13127 } else if (FDTy->isIncompleteArrayType() && Record &&
13128 ((i + 1 == Fields.end() && !Record->isUnion()) ||
13129 ((getLangOpts().MicrosoftExt ||
13130 getLangOpts().CPlusPlus) &&
13131 (i + 1 == Fields.end() || Record->isUnion())))) {
13132 // Flexible array member.
13133 // Microsoft and g++ is more permissive regarding flexible array.
13134 // It will accept flexible array in union and also
13135 // as the sole element of a struct/class.
13136 unsigned DiagID = 0;
13137 if (Record->isUnion())
13138 DiagID = getLangOpts().MicrosoftExt
13139 ? diag::ext_flexible_array_union_ms
13140 : getLangOpts().CPlusPlus
13141 ? diag::ext_flexible_array_union_gnu
13142 : diag::err_flexible_array_union;
13143 else if (Fields.size() == 1)
13144 DiagID = getLangOpts().MicrosoftExt
13145 ? diag::ext_flexible_array_empty_aggregate_ms
13146 : getLangOpts().CPlusPlus
13147 ? diag::ext_flexible_array_empty_aggregate_gnu
13148 : NumNamedMembers < 1
13149 ? diag::err_flexible_array_empty_aggregate
13153 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13154 << Record->getTagKind();
13155 // While the layout of types that contain virtual bases is not specified
13156 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13157 // virtual bases after the derived members. This would make a flexible
13158 // array member declared at the end of an object not adjacent to the end
13160 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13161 if (RD->getNumVBases() != 0)
13162 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13163 << FD->getDeclName() << Record->getTagKind();
13164 if (!getLangOpts().C99)
13165 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13166 << FD->getDeclName() << Record->getTagKind();
13168 // If the element type has a non-trivial destructor, we would not
13169 // implicitly destroy the elements, so disallow it for now.
13171 // FIXME: GCC allows this. We should probably either implicitly delete
13172 // the destructor of the containing class, or just allow this.
13173 QualType BaseElem = Context.getBaseElementType(FD->getType());
13174 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13175 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13176 << FD->getDeclName() << FD->getType();
13177 FD->setInvalidDecl();
13178 EnclosingDecl->setInvalidDecl();
13181 // Okay, we have a legal flexible array member at the end of the struct.
13182 Record->setHasFlexibleArrayMember(true);
13183 } else if (!FDTy->isDependentType() &&
13184 RequireCompleteType(FD->getLocation(), FD->getType(),
13185 diag::err_field_incomplete)) {
13187 FD->setInvalidDecl();
13188 EnclosingDecl->setInvalidDecl();
13190 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13191 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13192 // A type which contains a flexible array member is considered to be a
13193 // flexible array member.
13194 Record->setHasFlexibleArrayMember(true);
13195 if (!Record->isUnion()) {
13196 // If this is a struct/class and this is not the last element, reject
13197 // it. Note that GCC supports variable sized arrays in the middle of
13199 if (i + 1 != Fields.end())
13200 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13201 << FD->getDeclName() << FD->getType();
13203 // We support flexible arrays at the end of structs in
13204 // other structs as an extension.
13205 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13206 << FD->getDeclName();
13210 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13211 RequireNonAbstractType(FD->getLocation(), FD->getType(),
13212 diag::err_abstract_type_in_decl,
13213 AbstractIvarType)) {
13214 // Ivars can not have abstract class types
13215 FD->setInvalidDecl();
13217 if (Record && FDTTy->getDecl()->hasObjectMember())
13218 Record->setHasObjectMember(true);
13219 if (Record && FDTTy->getDecl()->hasVolatileMember())
13220 Record->setHasVolatileMember(true);
13221 } else if (FDTy->isObjCObjectType()) {
13222 /// A field cannot be an Objective-c object
13223 Diag(FD->getLocation(), diag::err_statically_allocated_object)
13224 << FixItHint::CreateInsertion(FD->getLocation(), "*");
13225 QualType T = Context.getObjCObjectPointerType(FD->getType());
13227 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13228 (!getLangOpts().CPlusPlus || Record->isUnion())) {
13229 // It's an error in ARC if a field has lifetime.
13230 // We don't want to report this in a system header, though,
13231 // so we just make the field unavailable.
13232 // FIXME: that's really not sufficient; we need to make the type
13233 // itself invalid to, say, initialize or copy.
13234 QualType T = FD->getType();
13235 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13236 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13237 SourceLocation loc = FD->getLocation();
13238 if (getSourceManager().isInSystemHeader(loc)) {
13239 if (!FD->hasAttr<UnavailableAttr>()) {
13240 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
13241 "this system field has retaining ownership",
13245 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13246 << T->isBlockPointerType() << Record->getTagKind();
13248 ARCErrReported = true;
13250 } else if (getLangOpts().ObjC1 &&
13251 getLangOpts().getGC() != LangOptions::NonGC &&
13252 Record && !Record->hasObjectMember()) {
13253 if (FD->getType()->isObjCObjectPointerType() ||
13254 FD->getType().isObjCGCStrong())
13255 Record->setHasObjectMember(true);
13256 else if (Context.getAsArrayType(FD->getType())) {
13257 QualType BaseType = Context.getBaseElementType(FD->getType());
13258 if (BaseType->isRecordType() &&
13259 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13260 Record->setHasObjectMember(true);
13261 else if (BaseType->isObjCObjectPointerType() ||
13262 BaseType.isObjCGCStrong())
13263 Record->setHasObjectMember(true);
13266 if (Record && FD->getType().isVolatileQualified())
13267 Record->setHasVolatileMember(true);
13268 // Keep track of the number of named members.
13269 if (FD->getIdentifier())
13273 // Okay, we successfully defined 'Record'.
13275 bool Completed = false;
13276 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13277 if (!CXXRecord->isInvalidDecl()) {
13278 // Set access bits correctly on the directly-declared conversions.
13279 for (CXXRecordDecl::conversion_iterator
13280 I = CXXRecord->conversion_begin(),
13281 E = CXXRecord->conversion_end(); I != E; ++I)
13282 I.setAccess((*I)->getAccess());
13284 if (!CXXRecord->isDependentType()) {
13285 if (CXXRecord->hasUserDeclaredDestructor()) {
13286 // Adjust user-defined destructor exception spec.
13287 if (getLangOpts().CPlusPlus11)
13288 AdjustDestructorExceptionSpec(CXXRecord,
13289 CXXRecord->getDestructor());
13292 // Add any implicitly-declared members to this class.
13293 AddImplicitlyDeclaredMembersToClass(CXXRecord);
13295 // If we have virtual base classes, we may end up finding multiple
13296 // final overriders for a given virtual function. Check for this
13298 if (CXXRecord->getNumVBases()) {
13299 CXXFinalOverriderMap FinalOverriders;
13300 CXXRecord->getFinalOverriders(FinalOverriders);
13302 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13303 MEnd = FinalOverriders.end();
13305 for (OverridingMethods::iterator SO = M->second.begin(),
13306 SOEnd = M->second.end();
13307 SO != SOEnd; ++SO) {
13308 assert(SO->second.size() > 0 &&
13309 "Virtual function without overridding functions?");
13310 if (SO->second.size() == 1)
13313 // C++ [class.virtual]p2:
13314 // In a derived class, if a virtual member function of a base
13315 // class subobject has more than one final overrider the
13316 // program is ill-formed.
13317 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13318 << (const NamedDecl *)M->first << Record;
13319 Diag(M->first->getLocation(),
13320 diag::note_overridden_virtual_function);
13321 for (OverridingMethods::overriding_iterator
13322 OM = SO->second.begin(),
13323 OMEnd = SO->second.end();
13325 Diag(OM->Method->getLocation(), diag::note_final_overrider)
13326 << (const NamedDecl *)M->first << OM->Method->getParent();
13328 Record->setInvalidDecl();
13331 CXXRecord->completeDefinition(&FinalOverriders);
13339 Record->completeDefinition();
13341 if (Record->hasAttrs()) {
13342 CheckAlignasUnderalignment(Record);
13344 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13345 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13346 IA->getRange(), IA->getBestCase(),
13347 IA->getSemanticSpelling());
13350 // Check if the structure/union declaration is a type that can have zero
13351 // size in C. For C this is a language extension, for C++ it may cause
13352 // compatibility problems.
13353 bool CheckForZeroSize;
13354 if (!getLangOpts().CPlusPlus) {
13355 CheckForZeroSize = true;
13357 // For C++ filter out types that cannot be referenced in C code.
13358 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13360 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13361 !CXXRecord->isDependentType() &&
13362 CXXRecord->isCLike();
13364 if (CheckForZeroSize) {
13365 bool ZeroSize = true;
13366 bool IsEmpty = true;
13367 unsigned NonBitFields = 0;
13368 for (RecordDecl::field_iterator I = Record->field_begin(),
13369 E = Record->field_end();
13370 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13372 if (I->isUnnamedBitfield()) {
13373 if (I->getBitWidthValue(Context) > 0)
13377 QualType FieldType = I->getType();
13378 if (FieldType->isIncompleteType() ||
13379 !Context.getTypeSizeInChars(FieldType).isZero())
13384 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13385 // allowed in C++, but warn if its declaration is inside
13386 // extern "C" block.
13388 Diag(RecLoc, getLangOpts().CPlusPlus ?
13389 diag::warn_zero_size_struct_union_in_extern_c :
13390 diag::warn_zero_size_struct_union_compat)
13391 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13394 // Structs without named members are extension in C (C99 6.7.2.1p7),
13395 // but are accepted by GCC.
13396 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13397 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13398 diag::ext_no_named_members_in_struct_union)
13399 << Record->isUnion();
13403 ObjCIvarDecl **ClsFields =
13404 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13405 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13406 ID->setEndOfDefinitionLoc(RBrac);
13407 // Add ivar's to class's DeclContext.
13408 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13409 ClsFields[i]->setLexicalDeclContext(ID);
13410 ID->addDecl(ClsFields[i]);
13412 // Must enforce the rule that ivars in the base classes may not be
13414 if (ID->getSuperClass())
13415 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13416 } else if (ObjCImplementationDecl *IMPDecl =
13417 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13418 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13419 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13420 // Ivar declared in @implementation never belongs to the implementation.
13421 // Only it is in implementation's lexical context.
13422 ClsFields[I]->setLexicalDeclContext(IMPDecl);
13423 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13424 IMPDecl->setIvarLBraceLoc(LBrac);
13425 IMPDecl->setIvarRBraceLoc(RBrac);
13426 } else if (ObjCCategoryDecl *CDecl =
13427 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13428 // case of ivars in class extension; all other cases have been
13429 // reported as errors elsewhere.
13430 // FIXME. Class extension does not have a LocEnd field.
13431 // CDecl->setLocEnd(RBrac);
13432 // Add ivar's to class extension's DeclContext.
13433 // Diagnose redeclaration of private ivars.
13434 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13435 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13437 if (const ObjCIvarDecl *ClsIvar =
13438 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13439 Diag(ClsFields[i]->getLocation(),
13440 diag::err_duplicate_ivar_declaration);
13441 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13444 for (const auto *Ext : IDecl->known_extensions()) {
13445 if (const ObjCIvarDecl *ClsExtIvar
13446 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13447 Diag(ClsFields[i]->getLocation(),
13448 diag::err_duplicate_ivar_declaration);
13449 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13454 ClsFields[i]->setLexicalDeclContext(CDecl);
13455 CDecl->addDecl(ClsFields[i]);
13457 CDecl->setIvarLBraceLoc(LBrac);
13458 CDecl->setIvarRBraceLoc(RBrac);
13463 ProcessDeclAttributeList(S, Record, Attr);
13466 /// \brief Determine whether the given integral value is representable within
13467 /// the given type T.
13468 static bool isRepresentableIntegerValue(ASTContext &Context,
13469 llvm::APSInt &Value,
13471 assert(T->isIntegralType(Context) && "Integral type required!");
13472 unsigned BitWidth = Context.getIntWidth(T);
13474 if (Value.isUnsigned() || Value.isNonNegative()) {
13475 if (T->isSignedIntegerOrEnumerationType())
13477 return Value.getActiveBits() <= BitWidth;
13479 return Value.getMinSignedBits() <= BitWidth;
13482 // \brief Given an integral type, return the next larger integral type
13483 // (or a NULL type of no such type exists).
13484 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13485 // FIXME: Int128/UInt128 support, which also needs to be introduced into
13486 // enum checking below.
13487 assert(T->isIntegralType(Context) && "Integral type required!");
13488 const unsigned NumTypes = 4;
13489 QualType SignedIntegralTypes[NumTypes] = {
13490 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13492 QualType UnsignedIntegralTypes[NumTypes] = {
13493 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13494 Context.UnsignedLongLongTy
13497 unsigned BitWidth = Context.getTypeSize(T);
13498 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13499 : UnsignedIntegralTypes;
13500 for (unsigned I = 0; I != NumTypes; ++I)
13501 if (Context.getTypeSize(Types[I]) > BitWidth)
13507 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13508 EnumConstantDecl *LastEnumConst,
13509 SourceLocation IdLoc,
13510 IdentifierInfo *Id,
13512 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13513 llvm::APSInt EnumVal(IntWidth);
13516 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13520 Val = DefaultLvalueConversion(Val).get();
13523 if (Enum->isDependentType() || Val->isTypeDependent())
13524 EltTy = Context.DependentTy;
13526 SourceLocation ExpLoc;
13527 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13528 !getLangOpts().MSVCCompat) {
13529 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13530 // constant-expression in the enumerator-definition shall be a converted
13531 // constant expression of the underlying type.
13532 EltTy = Enum->getIntegerType();
13533 ExprResult Converted =
13534 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13536 if (Converted.isInvalid())
13539 Val = Converted.get();
13540 } else if (!Val->isValueDependent() &&
13541 !(Val = VerifyIntegerConstantExpression(Val,
13542 &EnumVal).get())) {
13543 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13545 if (Enum->isFixed()) {
13546 EltTy = Enum->getIntegerType();
13548 // In Obj-C and Microsoft mode, require the enumeration value to be
13549 // representable in the underlying type of the enumeration. In C++11,
13550 // we perform a non-narrowing conversion as part of converted constant
13551 // expression checking.
13552 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13553 if (getLangOpts().MSVCCompat) {
13554 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13555 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13557 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13559 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13560 } else if (getLangOpts().CPlusPlus) {
13561 // C++11 [dcl.enum]p5:
13562 // If the underlying type is not fixed, the type of each enumerator
13563 // is the type of its initializing value:
13564 // - If an initializer is specified for an enumerator, the
13565 // initializing value has the same type as the expression.
13566 EltTy = Val->getType();
13569 // The expression that defines the value of an enumeration constant
13570 // shall be an integer constant expression that has a value
13571 // representable as an int.
13573 // Complain if the value is not representable in an int.
13574 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13575 Diag(IdLoc, diag::ext_enum_value_not_int)
13576 << EnumVal.toString(10) << Val->getSourceRange()
13577 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13578 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13579 // Force the type of the expression to 'int'.
13580 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13582 EltTy = Val->getType();
13589 if (Enum->isDependentType())
13590 EltTy = Context.DependentTy;
13591 else if (!LastEnumConst) {
13592 // C++0x [dcl.enum]p5:
13593 // If the underlying type is not fixed, the type of each enumerator
13594 // is the type of its initializing value:
13595 // - If no initializer is specified for the first enumerator, the
13596 // initializing value has an unspecified integral type.
13598 // GCC uses 'int' for its unspecified integral type, as does
13600 if (Enum->isFixed()) {
13601 EltTy = Enum->getIntegerType();
13604 EltTy = Context.IntTy;
13607 // Assign the last value + 1.
13608 EnumVal = LastEnumConst->getInitVal();
13610 EltTy = LastEnumConst->getType();
13612 // Check for overflow on increment.
13613 if (EnumVal < LastEnumConst->getInitVal()) {
13614 // C++0x [dcl.enum]p5:
13615 // If the underlying type is not fixed, the type of each enumerator
13616 // is the type of its initializing value:
13618 // - Otherwise the type of the initializing value is the same as
13619 // the type of the initializing value of the preceding enumerator
13620 // unless the incremented value is not representable in that type,
13621 // in which case the type is an unspecified integral type
13622 // sufficient to contain the incremented value. If no such type
13623 // exists, the program is ill-formed.
13624 QualType T = getNextLargerIntegralType(Context, EltTy);
13625 if (T.isNull() || Enum->isFixed()) {
13626 // There is no integral type larger enough to represent this
13627 // value. Complain, then allow the value to wrap around.
13628 EnumVal = LastEnumConst->getInitVal();
13629 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13631 if (Enum->isFixed())
13632 // When the underlying type is fixed, this is ill-formed.
13633 Diag(IdLoc, diag::err_enumerator_wrapped)
13634 << EnumVal.toString(10)
13637 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13638 << EnumVal.toString(10);
13643 // Retrieve the last enumerator's value, extent that type to the
13644 // type that is supposed to be large enough to represent the incremented
13645 // value, then increment.
13646 EnumVal = LastEnumConst->getInitVal();
13647 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13648 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13651 // If we're not in C++, diagnose the overflow of enumerator values,
13652 // which in C99 means that the enumerator value is not representable in
13653 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13654 // permits enumerator values that are representable in some larger
13656 if (!getLangOpts().CPlusPlus && !T.isNull())
13657 Diag(IdLoc, diag::warn_enum_value_overflow);
13658 } else if (!getLangOpts().CPlusPlus &&
13659 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13660 // Enforce C99 6.7.2.2p2 even when we compute the next value.
13661 Diag(IdLoc, diag::ext_enum_value_not_int)
13662 << EnumVal.toString(10) << 1;
13667 if (!EltTy->isDependentType()) {
13668 // Make the enumerator value match the signedness and size of the
13669 // enumerator's type.
13670 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13671 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13674 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13678 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
13679 SourceLocation IILoc) {
13680 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
13681 !getLangOpts().CPlusPlus)
13682 return SkipBodyInfo();
13684 // We have an anonymous enum definition. Look up the first enumerator to
13685 // determine if we should merge the definition with an existing one and
13687 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
13689 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
13692 !hasVisibleDefinition(cast<NamedDecl>(PrevECD->getDeclContext()),
13695 Skip.Previous = Hidden;
13699 return SkipBodyInfo();
13702 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13703 SourceLocation IdLoc, IdentifierInfo *Id,
13704 AttributeList *Attr,
13705 SourceLocation EqualLoc, Expr *Val) {
13706 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13707 EnumConstantDecl *LastEnumConst =
13708 cast_or_null<EnumConstantDecl>(lastEnumConst);
13710 // The scope passed in may not be a decl scope. Zip up the scope tree until
13711 // we find one that is.
13712 S = getNonFieldDeclScope(S);
13714 // Verify that there isn't already something declared with this name in this
13716 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13718 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13719 // Maybe we will complain about the shadowed template parameter.
13720 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13721 // Just pretend that we didn't see the previous declaration.
13722 PrevDecl = nullptr;
13726 // When in C++, we may get a TagDecl with the same name; in this case the
13727 // enum constant will 'hide' the tag.
13728 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13729 "Received TagDecl when not in C++!");
13730 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13731 if (isa<EnumConstantDecl>(PrevDecl))
13732 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13734 Diag(IdLoc, diag::err_redefinition) << Id;
13735 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13740 // C++ [class.mem]p15:
13741 // If T is the name of a class, then each of the following shall have a name
13742 // different from T:
13743 // - every enumerator of every member of class T that is an unscoped
13745 if (!TheEnumDecl->isScoped())
13746 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
13747 DeclarationNameInfo(Id, IdLoc));
13749 EnumConstantDecl *New =
13750 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13753 // Process attributes.
13754 if (Attr) ProcessDeclAttributeList(S, New, Attr);
13756 // Register this decl in the current scope stack.
13757 New->setAccess(TheEnumDecl->getAccess());
13758 PushOnScopeChains(New, S);
13761 ActOnDocumentableDecl(New);
13766 // Returns true when the enum initial expression does not trigger the
13767 // duplicate enum warning. A few common cases are exempted as follows:
13768 // Element2 = Element1
13769 // Element2 = Element1 + 1
13770 // Element2 = Element1 - 1
13771 // Where Element2 and Element1 are from the same enum.
13772 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13773 Expr *InitExpr = ECD->getInitExpr();
13776 InitExpr = InitExpr->IgnoreImpCasts();
13778 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13779 if (!BO->isAdditiveOp())
13781 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13784 if (IL->getValue() != 1)
13787 InitExpr = BO->getLHS();
13790 // This checks if the elements are from the same enum.
13791 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13795 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13799 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13808 bool isTombstoneOrEmptyKey;
13809 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13810 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13813 static DupKey GetDupKey(const llvm::APSInt& Val) {
13814 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13818 struct DenseMapInfoDupKey {
13819 static DupKey getEmptyKey() { return DupKey(0, true); }
13820 static DupKey getTombstoneKey() { return DupKey(1, true); }
13821 static unsigned getHashValue(const DupKey Key) {
13822 return (unsigned)(Key.val * 37);
13824 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13825 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13826 LHS.val == RHS.val;
13830 // Emits a warning when an element is implicitly set a value that
13831 // a previous element has already been set to.
13832 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13834 QualType EnumType) {
13835 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13837 // Avoid anonymous enums
13838 if (!Enum->getIdentifier())
13841 // Only check for small enums.
13842 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13845 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13846 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13848 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13849 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13852 DuplicatesVector DupVector;
13853 ValueToVectorMap EnumMap;
13855 // Populate the EnumMap with all values represented by enum constants without
13857 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13858 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13860 // Null EnumConstantDecl means a previous diagnostic has been emitted for
13861 // this constant. Skip this enum since it may be ill-formed.
13866 if (ECD->getInitExpr())
13869 DupKey Key = GetDupKey(ECD->getInitVal());
13870 DeclOrVector &Entry = EnumMap[Key];
13872 // First time encountering this value.
13873 if (Entry.isNull())
13877 // Create vectors for any values that has duplicates.
13878 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13879 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13880 if (!ValidDuplicateEnum(ECD, Enum))
13883 DupKey Key = GetDupKey(ECD->getInitVal());
13885 DeclOrVector& Entry = EnumMap[Key];
13886 if (Entry.isNull())
13889 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13890 // Ensure constants are different.
13894 // Create new vector and push values onto it.
13895 ECDVector *Vec = new ECDVector();
13897 Vec->push_back(ECD);
13899 // Update entry to point to the duplicates vector.
13902 // Store the vector somewhere we can consult later for quick emission of
13904 DupVector.push_back(Vec);
13908 ECDVector *Vec = Entry.get<ECDVector*>();
13909 // Make sure constants are not added more than once.
13910 if (*Vec->begin() == ECD)
13913 Vec->push_back(ECD);
13916 // Emit diagnostics.
13917 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13918 DupVectorEnd = DupVector.end();
13919 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13920 ECDVector *Vec = *DupVectorIter;
13921 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13923 // Emit warning for one enum constant.
13924 ECDVector::iterator I = Vec->begin();
13925 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13926 << (*I)->getName() << (*I)->getInitVal().toString(10)
13927 << (*I)->getSourceRange();
13930 // Emit one note for each of the remaining enum constants with
13932 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13933 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13934 << (*I)->getName() << (*I)->getInitVal().toString(10)
13935 << (*I)->getSourceRange();
13941 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
13942 bool AllowMask) const {
13943 FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
13944 assert(FEAttr && "looking for value in non-flag enum");
13946 llvm::APInt FlagMask = ~FEAttr->getFlagBits();
13947 unsigned Width = FlagMask.getBitWidth();
13949 // We will try a zero-extended value for the regular check first.
13950 llvm::APInt ExtVal = Val.zextOrSelf(Width);
13952 // A value is in a flag enum if either its bits are a subset of the enum's
13953 // flag bits (the first condition) or we are allowing masks and the same is
13954 // true of its complement (the second condition). When masks are allowed, we
13955 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
13957 // While it's true that any value could be used as a mask, the assumption is
13958 // that a mask will have all of the insignificant bits set. Anything else is
13959 // likely a logic error.
13960 if (!(FlagMask & ExtVal))
13964 // Try a one-extended value instead. This can happen if the enum is wider
13965 // than the constant used, in C with extensions to allow for wider enums.
13966 // The mask will still have the correct behaviour, so we give the user the
13967 // benefit of the doubt.
13969 // FIXME: This heuristic can cause weird results if the enum was extended
13970 // to a larger type and is signed, because then bit-masks of smaller types
13971 // that get extended will fall out of range (e.g. ~0x1u). We currently don't
13972 // detect that case and will get a false positive for it. In most cases,
13973 // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
13974 // be fine just to accept this as a warning.
13975 ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
13976 if (!(FlagMask & ~ExtVal))
13983 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13984 SourceLocation RBraceLoc, Decl *EnumDeclX,
13985 ArrayRef<Decl *> Elements,
13986 Scope *S, AttributeList *Attr) {
13987 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13988 QualType EnumType = Context.getTypeDeclType(Enum);
13991 ProcessDeclAttributeList(S, Enum, Attr);
13993 if (Enum->isDependentType()) {
13994 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13995 EnumConstantDecl *ECD =
13996 cast_or_null<EnumConstantDecl>(Elements[i]);
13997 if (!ECD) continue;
13999 ECD->setType(EnumType);
14002 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14006 // TODO: If the result value doesn't fit in an int, it must be a long or long
14007 // long value. ISO C does not support this, but GCC does as an extension,
14009 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14010 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14011 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14013 // Verify that all the values are okay, compute the size of the values, and
14014 // reverse the list.
14015 unsigned NumNegativeBits = 0;
14016 unsigned NumPositiveBits = 0;
14018 // Keep track of whether all elements have type int.
14019 bool AllElementsInt = true;
14021 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14022 EnumConstantDecl *ECD =
14023 cast_or_null<EnumConstantDecl>(Elements[i]);
14024 if (!ECD) continue; // Already issued a diagnostic.
14026 const llvm::APSInt &InitVal = ECD->getInitVal();
14028 // Keep track of the size of positive and negative values.
14029 if (InitVal.isUnsigned() || InitVal.isNonNegative())
14030 NumPositiveBits = std::max(NumPositiveBits,
14031 (unsigned)InitVal.getActiveBits());
14033 NumNegativeBits = std::max(NumNegativeBits,
14034 (unsigned)InitVal.getMinSignedBits());
14036 // Keep track of whether every enum element has type int (very commmon).
14037 if (AllElementsInt)
14038 AllElementsInt = ECD->getType() == Context.IntTy;
14041 // Figure out the type that should be used for this enum.
14043 unsigned BestWidth;
14045 // C++0x N3000 [conv.prom]p3:
14046 // An rvalue of an unscoped enumeration type whose underlying
14047 // type is not fixed can be converted to an rvalue of the first
14048 // of the following types that can represent all the values of
14049 // the enumeration: int, unsigned int, long int, unsigned long
14050 // int, long long int, or unsigned long long int.
14052 // An identifier declared as an enumeration constant has type int.
14053 // The C99 rule is modified by a gcc extension
14054 QualType BestPromotionType;
14056 bool Packed = Enum->hasAttr<PackedAttr>();
14057 // -fshort-enums is the equivalent to specifying the packed attribute on all
14058 // enum definitions.
14059 if (LangOpts.ShortEnums)
14062 if (Enum->isFixed()) {
14063 BestType = Enum->getIntegerType();
14064 if (BestType->isPromotableIntegerType())
14065 BestPromotionType = Context.getPromotedIntegerType(BestType);
14067 BestPromotionType = BestType;
14069 BestWidth = Context.getIntWidth(BestType);
14071 else if (NumNegativeBits) {
14072 // If there is a negative value, figure out the smallest integer type (of
14073 // int/long/longlong) that fits.
14074 // If it's packed, check also if it fits a char or a short.
14075 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14076 BestType = Context.SignedCharTy;
14077 BestWidth = CharWidth;
14078 } else if (Packed && NumNegativeBits <= ShortWidth &&
14079 NumPositiveBits < ShortWidth) {
14080 BestType = Context.ShortTy;
14081 BestWidth = ShortWidth;
14082 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14083 BestType = Context.IntTy;
14084 BestWidth = IntWidth;
14086 BestWidth = Context.getTargetInfo().getLongWidth();
14088 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14089 BestType = Context.LongTy;
14091 BestWidth = Context.getTargetInfo().getLongLongWidth();
14093 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14094 Diag(Enum->getLocation(), diag::ext_enum_too_large);
14095 BestType = Context.LongLongTy;
14098 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14100 // If there is no negative value, figure out the smallest type that fits
14101 // all of the enumerator values.
14102 // If it's packed, check also if it fits a char or a short.
14103 if (Packed && NumPositiveBits <= CharWidth) {
14104 BestType = Context.UnsignedCharTy;
14105 BestPromotionType = Context.IntTy;
14106 BestWidth = CharWidth;
14107 } else if (Packed && NumPositiveBits <= ShortWidth) {
14108 BestType = Context.UnsignedShortTy;
14109 BestPromotionType = Context.IntTy;
14110 BestWidth = ShortWidth;
14111 } else if (NumPositiveBits <= IntWidth) {
14112 BestType = Context.UnsignedIntTy;
14113 BestWidth = IntWidth;
14115 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14116 ? Context.UnsignedIntTy : Context.IntTy;
14117 } else if (NumPositiveBits <=
14118 (BestWidth = Context.getTargetInfo().getLongWidth())) {
14119 BestType = Context.UnsignedLongTy;
14121 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14122 ? Context.UnsignedLongTy : Context.LongTy;
14124 BestWidth = Context.getTargetInfo().getLongLongWidth();
14125 assert(NumPositiveBits <= BestWidth &&
14126 "How could an initializer get larger than ULL?");
14127 BestType = Context.UnsignedLongLongTy;
14129 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14130 ? Context.UnsignedLongLongTy : Context.LongLongTy;
14134 FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
14136 FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
14138 // Loop over all of the enumerator constants, changing their types to match
14139 // the type of the enum if needed. If we have a flag type, we also prepare the
14141 for (auto *D : Elements) {
14142 auto *ECD = cast_or_null<EnumConstantDecl>(D);
14143 if (!ECD) continue; // Already issued a diagnostic.
14145 // Standard C says the enumerators have int type, but we allow, as an
14146 // extension, the enumerators to be larger than int size. If each
14147 // enumerator value fits in an int, type it as an int, otherwise type it the
14148 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
14149 // that X has type 'int', not 'unsigned'.
14151 // Determine whether the value fits into an int.
14152 llvm::APSInt InitVal = ECD->getInitVal();
14154 // If it fits into an integer type, force it. Otherwise force it to match
14155 // the enum decl type.
14159 if (!getLangOpts().CPlusPlus &&
14160 !Enum->isFixed() &&
14161 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14162 NewTy = Context.IntTy;
14163 NewWidth = IntWidth;
14165 } else if (ECD->getType() == BestType) {
14166 // Already the right type!
14167 if (getLangOpts().CPlusPlus)
14168 // C++ [dcl.enum]p4: Following the closing brace of an
14169 // enum-specifier, each enumerator has the type of its
14171 ECD->setType(EnumType);
14175 NewWidth = BestWidth;
14176 NewSign = BestType->isSignedIntegerOrEnumerationType();
14179 // Adjust the APSInt value.
14180 InitVal = InitVal.extOrTrunc(NewWidth);
14181 InitVal.setIsSigned(NewSign);
14182 ECD->setInitVal(InitVal);
14184 // Adjust the Expr initializer and type.
14185 if (ECD->getInitExpr() &&
14186 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14187 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14189 ECD->getInitExpr(),
14190 /*base paths*/ nullptr,
14192 if (getLangOpts().CPlusPlus)
14193 // C++ [dcl.enum]p4: Following the closing brace of an
14194 // enum-specifier, each enumerator has the type of its
14196 ECD->setType(EnumType);
14198 ECD->setType(NewTy);
14201 // Check to see if we have a constant with exactly one bit set. Note that x
14202 // & (x - 1) will be nonzero if and only if x has more than one bit set.
14204 llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
14205 if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
14206 FEAttr->getFlagBits() |= ExtVal;
14212 for (Decl *D : Elements) {
14213 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14214 if (!ECD) continue; // Already issued a diagnostic.
14216 llvm::APSInt InitVal = ECD->getInitVal();
14217 if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
14218 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14225 Enum->completeDefinition(BestType, BestPromotionType,
14226 NumPositiveBits, NumNegativeBits);
14228 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14230 // Now that the enum type is defined, ensure it's not been underaligned.
14231 if (Enum->hasAttrs())
14232 CheckAlignasUnderalignment(Enum);
14235 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14236 SourceLocation StartLoc,
14237 SourceLocation EndLoc) {
14238 StringLiteral *AsmString = cast<StringLiteral>(expr);
14240 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14241 AsmString, StartLoc,
14243 CurContext->addDecl(New);
14247 static void checkModuleImportContext(Sema &S, Module *M,
14248 SourceLocation ImportLoc,
14250 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14251 switch (LSD->getLanguage()) {
14252 case LinkageSpecDecl::lang_c:
14253 if (!M->IsExternC) {
14254 S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
14255 << M->getFullModuleName();
14256 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
14260 case LinkageSpecDecl::lang_cxx:
14263 DC = LSD->getParent();
14266 while (isa<LinkageSpecDecl>(DC))
14267 DC = DC->getParent();
14268 if (!isa<TranslationUnitDecl>(DC)) {
14269 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
14270 << M->getFullModuleName() << DC;
14271 S.Diag(cast<Decl>(DC)->getLocStart(),
14272 diag::note_module_import_not_at_top_level)
14277 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14278 SourceLocation ImportLoc,
14279 ModuleIdPath Path) {
14281 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14282 /*IsIncludeDirective=*/false);
14286 VisibleModules.setVisible(Mod, ImportLoc);
14288 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14290 // FIXME: we should support importing a submodule within a different submodule
14291 // of the same top-level module. Until we do, make it an error rather than
14292 // silently ignoring the import.
14293 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14294 Diag(ImportLoc, diag::err_module_self_import)
14295 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14296 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14297 Diag(ImportLoc, diag::err_module_import_in_implementation)
14298 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14300 SmallVector<SourceLocation, 2> IdentifierLocs;
14301 Module *ModCheck = Mod;
14302 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14303 // If we've run out of module parents, just drop the remaining identifiers.
14304 // We need the length to be consistent.
14307 ModCheck = ModCheck->Parent;
14309 IdentifierLocs.push_back(Path[I].second);
14312 ImportDecl *Import = ImportDecl::Create(Context,
14313 Context.getTranslationUnitDecl(),
14314 AtLoc.isValid()? AtLoc : ImportLoc,
14315 Mod, IdentifierLocs);
14316 Context.getTranslationUnitDecl()->addDecl(Import);
14320 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14321 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14323 // Determine whether we're in the #include buffer for a module. The #includes
14324 // in that buffer do not qualify as module imports; they're just an
14325 // implementation detail of us building the module.
14327 // FIXME: Should we even get ActOnModuleInclude calls for those?
14328 bool IsInModuleIncludes =
14329 TUKind == TU_Module &&
14330 getSourceManager().isWrittenInMainFile(DirectiveLoc);
14332 // If this module import was due to an inclusion directive, create an
14333 // implicit import declaration to capture it in the AST.
14334 if (!IsInModuleIncludes) {
14335 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14336 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14339 TU->addDecl(ImportD);
14340 Consumer.HandleImplicitImportDecl(ImportD);
14343 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14344 VisibleModules.setVisible(Mod, DirectiveLoc);
14347 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14348 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14350 if (getLangOpts().ModulesLocalVisibility)
14351 VisibleModulesStack.push_back(std::move(VisibleModules));
14352 VisibleModules.setVisible(Mod, DirectiveLoc);
14355 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14356 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14358 if (getLangOpts().ModulesLocalVisibility) {
14359 VisibleModules = std::move(VisibleModulesStack.back());
14360 VisibleModulesStack.pop_back();
14361 VisibleModules.setVisible(Mod, DirectiveLoc);
14365 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14367 // Bail if we're not allowed to implicitly import a module here.
14368 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14371 // Create the implicit import declaration.
14372 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14373 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14375 TU->addDecl(ImportD);
14376 Consumer.HandleImplicitImportDecl(ImportD);
14378 // Make the module visible.
14379 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14380 VisibleModules.setVisible(Mod, Loc);
14383 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14384 IdentifierInfo* AliasName,
14385 SourceLocation PragmaLoc,
14386 SourceLocation NameLoc,
14387 SourceLocation AliasNameLoc) {
14388 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14389 LookupOrdinaryName);
14390 AsmLabelAttr *Attr =
14391 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14393 // If a declaration that:
14394 // 1) declares a function or a variable
14395 // 2) has external linkage
14396 // already exists, add a label attribute to it.
14398 (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)) &&
14399 PrevDecl->hasExternalFormalLinkage())
14400 PrevDecl->addAttr(Attr);
14401 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14403 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14406 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14407 SourceLocation PragmaLoc,
14408 SourceLocation NameLoc) {
14409 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14412 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14414 (void)WeakUndeclaredIdentifiers.insert(
14415 std::pair<IdentifierInfo*,WeakInfo>
14416 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14420 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14421 IdentifierInfo* AliasName,
14422 SourceLocation PragmaLoc,
14423 SourceLocation NameLoc,
14424 SourceLocation AliasNameLoc) {
14425 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14426 LookupOrdinaryName);
14427 WeakInfo W = WeakInfo(Name, NameLoc);
14430 if (!PrevDecl->hasAttr<AliasAttr>())
14431 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14432 DeclApplyPragmaWeak(TUScope, ND, W);
14434 (void)WeakUndeclaredIdentifiers.insert(
14435 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14439 Decl *Sema::getObjCDeclContext() const {
14440 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14443 AvailabilityResult Sema::getCurContextAvailability() const {
14444 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14446 return AR_Available;
14448 // If we are within an Objective-C method, we should consult
14449 // both the availability of the method as well as the
14450 // enclosing class. If the class is (say) deprecated,
14451 // the entire method is considered deprecated from the
14452 // purpose of checking if the current context is deprecated.
14453 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14454 AvailabilityResult R = MD->getAvailability();
14455 if (R != AR_Available)
14457 D = MD->getClassInterface();
14459 // If we are within an Objective-c @implementation, it
14460 // gets the same availability context as the @interface.
14461 else if (const ObjCImplementationDecl *ID =
14462 dyn_cast<ObjCImplementationDecl>(D)) {
14463 D = ID->getClassInterface();
14465 // Recover from user error.
14466 return D ? D->getAvailability() : AR_Available;