clang 19.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaCUDA.h"
49#include "clang/Sema/SemaHLSL.h"
51#include "clang/Sema/Template.h"
52#include "llvm/ADT/STLForwardCompat.h"
53#include "llvm/ADT/SmallString.h"
54#include "llvm/ADT/StringExtras.h"
55#include "llvm/TargetParser/Triple.h"
56#include <algorithm>
57#include <cstring>
58#include <functional>
59#include <optional>
60#include <unordered_map>
61
62using namespace clang;
63using namespace sema;
64
66 if (OwnedType) {
67 Decl *Group[2] = { OwnedType, Ptr };
69 }
70
72}
73
74namespace {
75
76class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
77 public:
78 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
79 bool AllowTemplates = false,
80 bool AllowNonTemplates = true)
81 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
82 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
83 WantExpressionKeywords = false;
84 WantCXXNamedCasts = false;
85 WantRemainingKeywords = false;
86 }
87
88 bool ValidateCandidate(const TypoCorrection &candidate) override {
89 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
90 if (!AllowInvalidDecl && ND->isInvalidDecl())
91 return false;
92
94 return AllowTemplates;
95
96 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
97 if (!IsType)
98 return false;
99
100 if (AllowNonTemplates)
101 return true;
102
103 // An injected-class-name of a class template (specialization) is valid
104 // as a template or as a non-template.
105 if (AllowTemplates) {
106 auto *RD = dyn_cast<CXXRecordDecl>(ND);
107 if (!RD || !RD->isInjectedClassName())
108 return false;
109 RD = cast<CXXRecordDecl>(RD->getDeclContext());
110 return RD->getDescribedClassTemplate() ||
111 isa<ClassTemplateSpecializationDecl>(RD);
112 }
113
114 return false;
115 }
116
117 return !WantClassName && candidate.isKeyword();
118 }
119
120 std::unique_ptr<CorrectionCandidateCallback> clone() override {
121 return std::make_unique<TypeNameValidatorCCC>(*this);
122 }
123
124 private:
125 bool AllowInvalidDecl;
126 bool WantClassName;
127 bool AllowTemplates;
128 bool AllowNonTemplates;
129};
130
131} // end anonymous namespace
132
133namespace {
134enum class UnqualifiedTypeNameLookupResult {
135 NotFound,
136 FoundNonType,
137 FoundType
138};
139} // end anonymous namespace
140
141/// Tries to perform unqualified lookup of the type decls in bases for
142/// dependent class.
143/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144/// type decl, \a FoundType if only type decls are found.
145static UnqualifiedTypeNameLookupResult
147 SourceLocation NameLoc,
148 const CXXRecordDecl *RD) {
149 if (!RD->hasDefinition())
150 return UnqualifiedTypeNameLookupResult::NotFound;
151 // Look for type decls in base classes.
152 UnqualifiedTypeNameLookupResult FoundTypeDecl =
153 UnqualifiedTypeNameLookupResult::NotFound;
154 for (const auto &Base : RD->bases()) {
155 const CXXRecordDecl *BaseRD = nullptr;
156 if (auto *BaseTT = Base.getType()->getAs<TagType>())
157 BaseRD = BaseTT->getAsCXXRecordDecl();
158 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159 // Look for type decls in dependent base classes that have known primary
160 // templates.
161 if (!TST || !TST->isDependentType())
162 continue;
163 auto *TD = TST->getTemplateName().getAsTemplateDecl();
164 if (!TD)
165 continue;
166 if (auto *BasePrimaryTemplate =
167 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169 BaseRD = BasePrimaryTemplate;
170 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
172 CTD->findPartialSpecialization(Base.getType()))
173 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174 BaseRD = PS;
175 }
176 }
177 }
178 if (BaseRD) {
179 for (NamedDecl *ND : BaseRD->lookup(&II)) {
180 if (!isa<TypeDecl>(ND))
181 return UnqualifiedTypeNameLookupResult::FoundNonType;
182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183 }
184 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186 case UnqualifiedTypeNameLookupResult::FoundNonType:
187 return UnqualifiedTypeNameLookupResult::FoundNonType;
188 case UnqualifiedTypeNameLookupResult::FoundType:
189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190 break;
191 case UnqualifiedTypeNameLookupResult::NotFound:
192 break;
193 }
194 }
195 }
196 }
197
198 return FoundTypeDecl;
199}
200
202 const IdentifierInfo &II,
203 SourceLocation NameLoc) {
204 // Lookup in the parent class template context, if any.
205 const CXXRecordDecl *RD = nullptr;
206 UnqualifiedTypeNameLookupResult FoundTypeDecl =
207 UnqualifiedTypeNameLookupResult::NotFound;
208 for (DeclContext *DC = S.CurContext;
209 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210 DC = DC->getParent()) {
211 // Look for type decls in dependent base classes that have known primary
212 // templates.
213 RD = dyn_cast<CXXRecordDecl>(DC);
214 if (RD && RD->getDescribedClassTemplate())
215 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216 }
217 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218 return nullptr;
219
220 // We found some types in dependent base classes. Recover as if the user
221 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
222 // lookup during template instantiation.
223 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
224
225 ASTContext &Context = S.Context;
226 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227 cast<Type>(Context.getRecordType(RD)));
228 QualType T =
230
231 CXXScopeSpec SS;
232 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
233
234 TypeLocBuilder Builder;
235 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
236 DepTL.setNameLoc(NameLoc);
238 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
239 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
240}
241
242/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
244 SourceLocation NameLoc,
245 bool WantNontrivialTypeSourceInfo = true) {
246 switch (T->getTypeClass()) {
247 case Type::DeducedTemplateSpecialization:
248 case Type::Enum:
249 case Type::InjectedClassName:
250 case Type::Record:
251 case Type::Typedef:
252 case Type::UnresolvedUsing:
253 case Type::Using:
254 break;
255 // These can never be qualified so an ElaboratedType node
256 // would carry no additional meaning.
257 case Type::ObjCInterface:
258 case Type::ObjCTypeParam:
259 case Type::TemplateTypeParm:
260 return ParsedType::make(T);
261 default:
262 llvm_unreachable("Unexpected Type Class");
263 }
264
265 if (!SS || SS->isEmpty())
267 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
268
270 if (!WantNontrivialTypeSourceInfo)
271 return ParsedType::make(ElTy);
272
273 TypeLocBuilder Builder;
274 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
275 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
278 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
279}
280
281/// If the identifier refers to a type name within this scope,
282/// return the declaration of that type.
283///
284/// This routine performs ordinary name lookup of the identifier II
285/// within the given scope, with optional C++ scope specifier SS, to
286/// determine whether the name refers to a type. If so, returns an
287/// opaque pointer (actually a QualType) corresponding to that
288/// type. Otherwise, returns NULL.
290 Scope *S, CXXScopeSpec *SS, bool isClassName,
291 bool HasTrailingDot, ParsedType ObjectTypePtr,
292 bool IsCtorOrDtorName,
293 bool WantNontrivialTypeSourceInfo,
294 bool IsClassTemplateDeductionContext,
295 ImplicitTypenameContext AllowImplicitTypename,
296 IdentifierInfo **CorrectedII) {
297 // FIXME: Consider allowing this outside C++1z mode as an extension.
298 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
299 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
300 !isClassName && !HasTrailingDot;
301
302 // Determine where we will perform name lookup.
303 DeclContext *LookupCtx = nullptr;
304 if (ObjectTypePtr) {
305 QualType ObjectType = ObjectTypePtr.get();
306 if (ObjectType->isRecordType())
307 LookupCtx = computeDeclContext(ObjectType);
308 } else if (SS && SS->isNotEmpty()) {
309 LookupCtx = computeDeclContext(*SS, false);
310
311 if (!LookupCtx) {
312 if (isDependentScopeSpecifier(*SS)) {
313 // C++ [temp.res]p3:
314 // A qualified-id that refers to a type and in which the
315 // nested-name-specifier depends on a template-parameter (14.6.2)
316 // shall be prefixed by the keyword typename to indicate that the
317 // qualified-id denotes a type, forming an
318 // elaborated-type-specifier (7.1.5.3).
319 //
320 // We therefore do not perform any name lookup if the result would
321 // refer to a member of an unknown specialization.
322 // In C++2a, in several contexts a 'typename' is not required. Also
323 // allow this as an extension.
324 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
325 !isClassName && !IsCtorOrDtorName)
326 return nullptr;
327 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
328 if (IsImplicitTypename) {
329 SourceLocation QualifiedLoc = SS->getRange().getBegin();
331 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
332 else
333 Diag(QualifiedLoc, diag::ext_implicit_typename)
334 << SS->getScopeRep() << II.getName()
335 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
336 }
337
338 // We know from the grammar that this name refers to a type,
339 // so build a dependent node to describe the type.
340 if (WantNontrivialTypeSourceInfo)
341 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
342 (ImplicitTypenameContext)IsImplicitTypename)
343 .get();
344
347 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
349 SourceLocation(), QualifierLoc, II, NameLoc);
350 return ParsedType::make(T);
351 }
352
353 return nullptr;
354 }
355
356 if (!LookupCtx->isDependentContext() &&
357 RequireCompleteDeclContext(*SS, LookupCtx))
358 return nullptr;
359 }
360
361 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
362 // lookup for class-names.
363 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
365 LookupResult Result(*this, &II, NameLoc, Kind);
366 if (LookupCtx) {
367 // Perform "qualified" name lookup into the declaration context we
368 // computed, which is either the type of the base of a member access
369 // expression or the declaration context associated with a prior
370 // nested-name-specifier.
371 LookupQualifiedName(Result, LookupCtx);
372
373 if (ObjectTypePtr && Result.empty()) {
374 // C++ [basic.lookup.classref]p3:
375 // If the unqualified-id is ~type-name, the type-name is looked up
376 // in the context of the entire postfix-expression. If the type T of
377 // the object expression is of a class type C, the type-name is also
378 // looked up in the scope of class C. At least one of the lookups shall
379 // find a name that refers to (possibly cv-qualified) T.
380 LookupName(Result, S);
381 }
382 } else {
383 // Perform unqualified name lookup.
384 LookupName(Result, S);
385
386 // For unqualified lookup in a class template in MSVC mode, look into
387 // dependent base classes where the primary class template is known.
388 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
389 if (ParsedType TypeInBase =
390 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
391 return TypeInBase;
392 }
393 }
394
395 NamedDecl *IIDecl = nullptr;
396 UsingShadowDecl *FoundUsingShadow = nullptr;
397 switch (Result.getResultKind()) {
399 if (CorrectedII) {
400 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
401 AllowDeducedTemplate);
402 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
403 S, SS, CCC, CTK_ErrorRecovery);
404 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
405 TemplateTy Template;
406 bool MemberOfUnknownSpecialization;
408 TemplateName.setIdentifier(NewII, NameLoc);
410 CXXScopeSpec NewSS, *NewSSPtr = SS;
411 if (SS && NNS) {
412 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
413 NewSSPtr = &NewSS;
414 }
415 if (Correction && (NNS || NewII != &II) &&
416 // Ignore a correction to a template type as the to-be-corrected
417 // identifier is not a template (typo correction for template names
418 // is handled elsewhere).
419 !(getLangOpts().CPlusPlus && NewSSPtr &&
420 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
421 Template, MemberOfUnknownSpecialization))) {
422 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
423 isClassName, HasTrailingDot, ObjectTypePtr,
424 IsCtorOrDtorName,
425 WantNontrivialTypeSourceInfo,
426 IsClassTemplateDeductionContext);
427 if (Ty) {
428 diagnoseTypo(Correction,
429 PDiag(diag::err_unknown_type_or_class_name_suggest)
430 << Result.getLookupName() << isClassName);
431 if (SS && NNS)
432 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
433 *CorrectedII = NewII;
434 return Ty;
435 }
436 }
437 }
438 Result.suppressDiagnostics();
439 return nullptr;
441 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
443 SS->getScopeRep(), &II);
444 TypeLocBuilder TLB;
448 TL.setNameLoc(NameLoc);
450 }
451 [[fallthrough]];
454 Result.suppressDiagnostics();
455 return nullptr;
456
458 // Recover from type-hiding ambiguities by hiding the type. We'll
459 // do the lookup again when looking for an object, and we can
460 // diagnose the error then. If we don't do this, then the error
461 // about hiding the type will be immediately followed by an error
462 // that only makes sense if the identifier was treated like a type.
463 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
464 Result.suppressDiagnostics();
465 return nullptr;
466 }
467
468 // Look to see if we have a type anywhere in the list of results.
469 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
470 Res != ResEnd; ++Res) {
471 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
472 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
473 RealRes) ||
474 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
475 if (!IIDecl ||
476 // Make the selection of the recovery decl deterministic.
477 RealRes->getLocation() < IIDecl->getLocation()) {
478 IIDecl = RealRes;
479 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
480 }
481 }
482 }
483
484 if (!IIDecl) {
485 // None of the entities we found is a type, so there is no way
486 // to even assume that the result is a type. In this case, don't
487 // complain about the ambiguity. The parser will either try to
488 // perform this lookup again (e.g., as an object name), which
489 // will produce the ambiguity, or will complain that it expected
490 // a type name.
491 Result.suppressDiagnostics();
492 return nullptr;
493 }
494
495 // We found a type within the ambiguous lookup; diagnose the
496 // ambiguity and then return that type. This might be the right
497 // answer, or it might not be, but it suppresses any attempt to
498 // perform the name lookup again.
499 break;
500
502 IIDecl = Result.getFoundDecl();
503 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
504 break;
505 }
506
507 assert(IIDecl && "Didn't find decl");
508
509 QualType T;
510 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
511 // C++ [class.qual]p2: A lookup that would find the injected-class-name
512 // instead names the constructors of the class, except when naming a class.
513 // This is ill-formed when we're not actually forming a ctor or dtor name.
514 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
515 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
516 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
517 FoundRD->isInjectedClassName() &&
518 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
519 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
520 << &II << /*Type*/1;
521
522 DiagnoseUseOfDecl(IIDecl, NameLoc);
523
525 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
526 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
527 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
528 if (!HasTrailingDot)
530 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
531 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
532 (void)DiagnoseUseOfDecl(UD, NameLoc);
533 // Recover with 'int'
535 } else if (AllowDeducedTemplate) {
536 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
537 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
538 TemplateName Template =
539 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
541 false);
542 // Don't wrap in a further UsingType.
543 FoundUsingShadow = nullptr;
544 }
545 }
546
547 if (T.isNull()) {
548 // If it's not plausibly a type, suppress diagnostics.
549 Result.suppressDiagnostics();
550 return nullptr;
551 }
552
553 if (FoundUsingShadow)
554 T = Context.getUsingType(FoundUsingShadow, T);
555
556 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
557}
558
559// Builds a fake NNS for the given decl context.
560static NestedNameSpecifier *
562 for (;; DC = DC->getLookupParent()) {
563 DC = DC->getPrimaryContext();
564 auto *ND = dyn_cast<NamespaceDecl>(DC);
565 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
566 return NestedNameSpecifier::Create(Context, nullptr, ND);
567 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
568 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569 RD->getTypeForDecl());
570 else if (isa<TranslationUnitDecl>(DC))
572 }
573 llvm_unreachable("something isn't in TU scope?");
574}
575
576/// Find the parent class with dependent bases of the innermost enclosing method
577/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
578/// up allowing unqualified dependent type names at class-level, which MSVC
579/// correctly rejects.
580static const CXXRecordDecl *
582 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
583 DC = DC->getPrimaryContext();
584 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
585 if (MD->getParent()->hasAnyDependentBases())
586 return MD->getParent();
587 }
588 return nullptr;
589}
590
592 SourceLocation NameLoc,
593 bool IsTemplateTypeArg) {
594 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
595
596 NestedNameSpecifier *NNS = nullptr;
597 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
598 // If we weren't able to parse a default template argument, delay lookup
599 // until instantiation time by making a non-dependent DependentTypeName. We
600 // pretend we saw a NestedNameSpecifier referring to the current scope, and
601 // lookup is retried.
602 // FIXME: This hurts our diagnostic quality, since we get errors like "no
603 // type named 'Foo' in 'current_namespace'" when the user didn't write any
604 // name specifiers.
606 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
607 } else if (const CXXRecordDecl *RD =
609 // Build a DependentNameType that will perform lookup into RD at
610 // instantiation time.
611 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
612 RD->getTypeForDecl());
613
614 // Diagnose that this identifier was undeclared, and retry the lookup during
615 // template instantiation.
616 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
617 << RD;
618 } else {
619 // This is not a situation that we should recover from.
620 return ParsedType();
621 }
622
623 QualType T =
625
626 // Build type location information. We synthesized the qualifier, so we have
627 // to build a fake NestedNameSpecifierLoc.
628 NestedNameSpecifierLocBuilder NNSLocBuilder;
629 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
630 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
631
632 TypeLocBuilder Builder;
633 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
634 DepTL.setNameLoc(NameLoc);
636 DepTL.setQualifierLoc(QualifierLoc);
637 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
638}
639
640/// isTagName() - This method is called *for error recovery purposes only*
641/// to determine if the specified name is a valid tag name ("struct foo"). If
642/// so, this returns the TST for the tag corresponding to it (TST_enum,
643/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
644/// cases in C where the user forgot to specify the tag.
646 // Do a tag name lookup in this scope.
647 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
648 LookupName(R, S, false);
651 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
652 switch (TD->getTagKind()) {
658 return DeclSpec::TST_union;
660 return DeclSpec::TST_class;
662 return DeclSpec::TST_enum;
663 }
664 }
665
667}
668
669/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
670/// if a CXXScopeSpec's type is equal to the type of one of the base classes
671/// then downgrade the missing typename error to a warning.
672/// This is needed for MSVC compatibility; Example:
673/// @code
674/// template<class T> class A {
675/// public:
676/// typedef int TYPE;
677/// };
678/// template<class T> class B : public A<T> {
679/// public:
680/// A<T>::TYPE a; // no typename required because A<T> is a base class.
681/// };
682/// @endcode
684 if (CurContext->isRecord()) {
686 return true;
687
688 const Type *Ty = SS->getScopeRep()->getAsType();
689
690 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
691 for (const auto &Base : RD->bases())
692 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
693 return true;
694 return S->isFunctionPrototypeScope();
695 }
696 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
697}
698
700 SourceLocation IILoc,
701 Scope *S,
702 CXXScopeSpec *SS,
703 ParsedType &SuggestedType,
704 bool IsTemplateName) {
705 // Don't report typename errors for editor placeholders.
706 if (II->isEditorPlaceholder())
707 return;
708 // We don't have anything to suggest (yet).
709 SuggestedType = nullptr;
710
711 // There may have been a typo in the name of the type. Look up typo
712 // results, in case we have something that we can suggest.
713 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
714 /*AllowTemplates=*/IsTemplateName,
715 /*AllowNonTemplates=*/!IsTemplateName);
716 if (TypoCorrection Corrected =
718 CCC, CTK_ErrorRecovery)) {
719 // FIXME: Support error recovery for the template-name case.
720 bool CanRecover = !IsTemplateName;
721 if (Corrected.isKeyword()) {
722 // We corrected to a keyword.
723 diagnoseTypo(Corrected,
724 PDiag(IsTemplateName ? diag::err_no_template_suggest
725 : diag::err_unknown_typename_suggest)
726 << II);
727 II = Corrected.getCorrectionAsIdentifierInfo();
728 } else {
729 // We found a similarly-named type or interface; suggest that.
730 if (!SS || !SS->isSet()) {
731 diagnoseTypo(Corrected,
732 PDiag(IsTemplateName ? diag::err_no_template_suggest
733 : diag::err_unknown_typename_suggest)
734 << II, CanRecover);
735 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
736 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
737 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
738 II->getName().equals(CorrectedStr);
739 diagnoseTypo(Corrected,
740 PDiag(IsTemplateName
741 ? diag::err_no_member_template_suggest
742 : diag::err_unknown_nested_typename_suggest)
743 << II << DC << DroppedSpecifier << SS->getRange(),
744 CanRecover);
745 } else {
746 llvm_unreachable("could not have corrected a typo here");
747 }
748
749 if (!CanRecover)
750 return;
751
752 CXXScopeSpec tmpSS;
753 if (Corrected.getCorrectionSpecifier())
754 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
755 SourceRange(IILoc));
756 // FIXME: Support class template argument deduction here.
757 SuggestedType =
758 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
759 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
760 /*IsCtorOrDtorName=*/false,
761 /*WantNontrivialTypeSourceInfo=*/true);
762 }
763 return;
764 }
765
766 if (getLangOpts().CPlusPlus && !IsTemplateName) {
767 // See if II is a class template that the user forgot to pass arguments to.
768 UnqualifiedId Name;
769 Name.setIdentifier(II, IILoc);
770 CXXScopeSpec EmptySS;
771 TemplateTy TemplateResult;
772 bool MemberOfUnknownSpecialization;
773 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
774 Name, nullptr, true, TemplateResult,
775 MemberOfUnknownSpecialization) == TNK_Type_template) {
776 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
777 return;
778 }
779 }
780
781 // FIXME: Should we move the logic that tries to recover from a missing tag
782 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
783
784 if (!SS || (!SS->isSet() && !SS->isInvalid()))
785 Diag(IILoc, IsTemplateName ? diag::err_no_template
786 : diag::err_unknown_typename)
787 << II;
788 else if (DeclContext *DC = computeDeclContext(*SS, false))
789 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
790 : diag::err_typename_nested_not_found)
791 << II << DC << SS->getRange();
792 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
793 SuggestedType =
794 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
795 } else if (isDependentScopeSpecifier(*SS)) {
796 unsigned DiagID = diag::err_typename_missing;
797 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
798 DiagID = diag::ext_typename_missing;
799
800 Diag(SS->getRange().getBegin(), DiagID)
801 << SS->getScopeRep() << II->getName()
802 << SourceRange(SS->getRange().getBegin(), IILoc)
803 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
804 SuggestedType = ActOnTypenameType(S, SourceLocation(),
805 *SS, *II, IILoc).get();
806 } else {
807 assert(SS && SS->isInvalid() &&
808 "Invalid scope specifier has already been diagnosed");
809 }
810}
811
812/// Determine whether the given result set contains either a type name
813/// or
814static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
815 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
816 NextToken.is(tok::less);
817
818 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
819 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
820 return true;
821
822 if (CheckTemplate && isa<TemplateDecl>(*I))
823 return true;
824 }
825
826 return false;
827}
828
830 Scope *S, CXXScopeSpec &SS,
831 IdentifierInfo *&Name,
832 SourceLocation NameLoc) {
833 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
834 SemaRef.LookupParsedName(R, S, &SS);
835 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
836 StringRef FixItTagName;
837 switch (Tag->getTagKind()) {
839 FixItTagName = "class ";
840 break;
841
843 FixItTagName = "enum ";
844 break;
845
847 FixItTagName = "struct ";
848 break;
849
851 FixItTagName = "__interface ";
852 break;
853
855 FixItTagName = "union ";
856 break;
857 }
858
859 StringRef TagName = FixItTagName.drop_back();
860 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
861 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
862 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
863
864 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
865 I != IEnd; ++I)
866 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
867 << Name << TagName;
868
869 // Replace lookup results with just the tag decl.
871 SemaRef.LookupParsedName(Result, S, &SS);
872 return true;
873 }
874
875 return false;
876}
877
879 IdentifierInfo *&Name,
880 SourceLocation NameLoc,
881 const Token &NextToken,
883 DeclarationNameInfo NameInfo(Name, NameLoc);
884 ObjCMethodDecl *CurMethod = getCurMethodDecl();
885
886 assert(NextToken.isNot(tok::coloncolon) &&
887 "parse nested name specifiers before calling ClassifyName");
888 if (getLangOpts().CPlusPlus && SS.isSet() &&
889 isCurrentClassName(*Name, S, &SS)) {
890 // Per [class.qual]p2, this names the constructors of SS, not the
891 // injected-class-name. We don't have a classification for that.
892 // There's not much point caching this result, since the parser
893 // will reject it later.
895 }
896
897 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
898 LookupParsedName(Result, S, &SS, !CurMethod);
899
900 if (SS.isInvalid())
902
903 // For unqualified lookup in a class template in MSVC mode, look into
904 // dependent base classes where the primary class template is known.
905 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
906 if (ParsedType TypeInBase =
907 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
908 return TypeInBase;
909 }
910
911 // Perform lookup for Objective-C instance variables (including automatically
912 // synthesized instance variables), if we're in an Objective-C method.
913 // FIXME: This lookup really, really needs to be folded in to the normal
914 // unqualified lookup mechanism.
915 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
917 if (Ivar.isInvalid())
919 if (Ivar.isUsable())
920 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
921
922 // We defer builtin creation until after ivar lookup inside ObjC methods.
923 if (Result.empty())
925 }
926
927 bool SecondTry = false;
928 bool IsFilteredTemplateName = false;
929
930Corrected:
931 switch (Result.getResultKind()) {
933 // If an unqualified-id is followed by a '(', then we have a function
934 // call.
935 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
936 // In C++, this is an ADL-only call.
937 // FIXME: Reference?
940
941 // C90 6.3.2.2:
942 // If the expression that precedes the parenthesized argument list in a
943 // function call consists solely of an identifier, and if no
944 // declaration is visible for this identifier, the identifier is
945 // implicitly declared exactly as if, in the innermost block containing
946 // the function call, the declaration
947 //
948 // extern int identifier ();
949 //
950 // appeared.
951 //
952 // We also allow this in C99 as an extension. However, this is not
953 // allowed in all language modes as functions without prototypes may not
954 // be supported.
955 if (getLangOpts().implicitFunctionsAllowed()) {
956 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
958 }
959 }
960
961 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
962 // In C++20 onwards, this could be an ADL-only call to a function
963 // template, and we're required to assume that this is a template name.
964 //
965 // FIXME: Find a way to still do typo correction in this case.
966 TemplateName Template =
969 }
970
971 // In C, we first see whether there is a tag type by the same name, in
972 // which case it's likely that the user just forgot to write "enum",
973 // "struct", or "union".
974 if (!getLangOpts().CPlusPlus && !SecondTry &&
975 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
976 break;
977 }
978
979 // Perform typo correction to determine if there is another name that is
980 // close to this name.
981 if (!SecondTry && CCC) {
982 SecondTry = true;
983 if (TypoCorrection Corrected =
984 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
985 &SS, *CCC, CTK_ErrorRecovery)) {
986 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
987 unsigned QualifiedDiag = diag::err_no_member_suggest;
988
989 NamedDecl *FirstDecl = Corrected.getFoundDecl();
990 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
991 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
992 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
993 UnqualifiedDiag = diag::err_no_template_suggest;
994 QualifiedDiag = diag::err_no_member_template_suggest;
995 } else if (UnderlyingFirstDecl &&
996 (isa<TypeDecl>(UnderlyingFirstDecl) ||
997 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
998 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
999 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1000 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1001 }
1002
1003 if (SS.isEmpty()) {
1004 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1005 } else {// FIXME: is this even reachable? Test it.
1006 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1007 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1008 Name->getName().equals(CorrectedStr);
1009 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1010 << Name << computeDeclContext(SS, false)
1011 << DroppedSpecifier << SS.getRange());
1012 }
1013
1014 // Update the name, so that the caller has the new name.
1015 Name = Corrected.getCorrectionAsIdentifierInfo();
1016
1017 // Typo correction corrected to a keyword.
1018 if (Corrected.isKeyword())
1019 return Name;
1020
1021 // Also update the LookupResult...
1022 // FIXME: This should probably go away at some point
1023 Result.clear();
1024 Result.setLookupName(Corrected.getCorrection());
1025 if (FirstDecl)
1026 Result.addDecl(FirstDecl);
1027
1028 // If we found an Objective-C instance variable, let
1029 // LookupInObjCMethod build the appropriate expression to
1030 // reference the ivar.
1031 // FIXME: This is a gross hack.
1032 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1033 DeclResult R =
1034 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1035 if (R.isInvalid())
1037 if (R.isUsable())
1038 return NameClassification::NonType(Ivar);
1039 }
1040
1041 goto Corrected;
1042 }
1043 }
1044
1045 // We failed to correct; just fall through and let the parser deal with it.
1046 Result.suppressDiagnostics();
1048
1050 // We performed name lookup into the current instantiation, and there were
1051 // dependent bases, so we treat this result the same way as any other
1052 // dependent nested-name-specifier.
1053
1054 // C++ [temp.res]p2:
1055 // A name used in a template declaration or definition and that is
1056 // dependent on a template-parameter is assumed not to name a type
1057 // unless the applicable name lookup finds a type name or the name is
1058 // qualified by the keyword typename.
1059 //
1060 // FIXME: If the next token is '<', we might want to ask the parser to
1061 // perform some heroics to see if we actually have a
1062 // template-argument-list, which would indicate a missing 'template'
1063 // keyword here.
1065 }
1066
1070 break;
1071
1073 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1074 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1075 /*AllowDependent=*/false)) {
1076 // C++ [temp.local]p3:
1077 // A lookup that finds an injected-class-name (10.2) can result in an
1078 // ambiguity in certain cases (for example, if it is found in more than
1079 // one base class). If all of the injected-class-names that are found
1080 // refer to specializations of the same class template, and if the name
1081 // is followed by a template-argument-list, the reference refers to the
1082 // class template itself and not a specialization thereof, and is not
1083 // ambiguous.
1084 //
1085 // This filtering can make an ambiguous result into an unambiguous one,
1086 // so try again after filtering out template names.
1088 if (!Result.isAmbiguous()) {
1089 IsFilteredTemplateName = true;
1090 break;
1091 }
1092 }
1093
1094 // Diagnose the ambiguity and return an error.
1096 }
1097
1098 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1099 (IsFilteredTemplateName ||
1101 Result, /*AllowFunctionTemplates=*/true,
1102 /*AllowDependent=*/false,
1103 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1105 // C++ [temp.names]p3:
1106 // After name lookup (3.4) finds that a name is a template-name or that
1107 // an operator-function-id or a literal- operator-id refers to a set of
1108 // overloaded functions any member of which is a function template if
1109 // this is followed by a <, the < is always taken as the delimiter of a
1110 // template-argument-list and never as the less-than operator.
1111 // C++2a [temp.names]p2:
1112 // A name is also considered to refer to a template if it is an
1113 // unqualified-id followed by a < and name lookup finds either one
1114 // or more functions or finds nothing.
1115 if (!IsFilteredTemplateName)
1117
1118 bool IsFunctionTemplate;
1119 bool IsVarTemplate;
1120 TemplateName Template;
1121 if (Result.end() - Result.begin() > 1) {
1122 IsFunctionTemplate = true;
1123 Template = Context.getOverloadedTemplateName(Result.begin(),
1124 Result.end());
1125 } else if (!Result.empty()) {
1126 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1127 *Result.begin(), /*AllowFunctionTemplates=*/true,
1128 /*AllowDependent=*/false));
1129 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1130 IsVarTemplate = isa<VarTemplateDecl>(TD);
1131
1132 UsingShadowDecl *FoundUsingShadow =
1133 dyn_cast<UsingShadowDecl>(*Result.begin());
1134 assert(!FoundUsingShadow ||
1135 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1136 Template =
1137 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1138 if (SS.isNotEmpty())
1140 /*TemplateKeyword=*/false,
1141 Template);
1142 } else {
1143 // All results were non-template functions. This is a function template
1144 // name.
1145 IsFunctionTemplate = true;
1146 Template = Context.getAssumedTemplateName(NameInfo.getName());
1147 }
1148
1149 if (IsFunctionTemplate) {
1150 // Function templates always go through overload resolution, at which
1151 // point we'll perform the various checks (e.g., accessibility) we need
1152 // to based on which function we selected.
1153 Result.suppressDiagnostics();
1154
1155 return NameClassification::FunctionTemplate(Template);
1156 }
1157
1158 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1160 }
1161
1162 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1164 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1165 T = Context.getUsingType(USD, T);
1166 return buildNamedType(*this, &SS, T, NameLoc);
1167 };
1168
1169 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1170 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1171 DiagnoseUseOfDecl(Type, NameLoc);
1172 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1173 return BuildTypeFor(Type, *Result.begin());
1174 }
1175
1176 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1177 if (!Class) {
1178 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1179 if (ObjCCompatibleAliasDecl *Alias =
1180 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1181 Class = Alias->getClassInterface();
1182 }
1183
1184 if (Class) {
1185 DiagnoseUseOfDecl(Class, NameLoc);
1186
1187 if (NextToken.is(tok::period)) {
1188 // Interface. <something> is parsed as a property reference expression.
1189 // Just return "unknown" as a fall-through for now.
1190 Result.suppressDiagnostics();
1192 }
1193
1195 return ParsedType::make(T);
1196 }
1197
1198 if (isa<ConceptDecl>(FirstDecl)) {
1199 // We want to preserve the UsingShadowDecl for concepts.
1200 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1203 TemplateName(cast<TemplateDecl>(FirstDecl)));
1204 }
1205
1206 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1207 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1209 }
1210
1211 // We can have a type template here if we're classifying a template argument.
1212 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1213 !isa<VarTemplateDecl>(FirstDecl))
1215 TemplateName(cast<TemplateDecl>(FirstDecl)));
1216
1217 // Check for a tag type hidden by a non-type decl in a few cases where it
1218 // seems likely a type is wanted instead of the non-type that was found.
1219 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1220 if ((NextToken.is(tok::identifier) ||
1221 (NextIsOp &&
1222 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1223 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1224 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1225 DiagnoseUseOfDecl(Type, NameLoc);
1226 return BuildTypeFor(Type, *Result.begin());
1227 }
1228
1229 // If we already know which single declaration is referenced, just annotate
1230 // that declaration directly. Defer resolving even non-overloaded class
1231 // member accesses, as we need to defer certain access checks until we know
1232 // the context.
1233 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1234 if (Result.isSingleResult() && !ADL &&
1235 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1236 return NameClassification::NonType(Result.getRepresentativeDecl());
1237
1238 // Otherwise, this is an overload set that we will need to resolve later.
1239 Result.suppressDiagnostics();
1241 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1242 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1243 Result.begin(), Result.end()));
1244}
1245
1248 SourceLocation NameLoc) {
1249 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1250 CXXScopeSpec SS;
1251 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1252 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1253}
1254
1257 IdentifierInfo *Name,
1258 SourceLocation NameLoc,
1259 bool IsAddressOfOperand) {
1260 DeclarationNameInfo NameInfo(Name, NameLoc);
1261 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1262 NameInfo, IsAddressOfOperand,
1263 /*TemplateArgs=*/nullptr);
1264}
1265
1267 NamedDecl *Found,
1268 SourceLocation NameLoc,
1269 const Token &NextToken) {
1270 if (getCurMethodDecl() && SS.isEmpty())
1271 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1272 return BuildIvarRefExpr(S, NameLoc, Ivar);
1273
1274 // Reconstruct the lookup result.
1275 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1276 Result.addDecl(Found);
1277 Result.resolveKind();
1278
1279 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1280 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1281}
1282
1284 // For an implicit class member access, transform the result into a member
1285 // access expression if necessary.
1286 auto *ULE = cast<UnresolvedLookupExpr>(E);
1287 if ((*ULE->decls_begin())->isCXXClassMember()) {
1288 CXXScopeSpec SS;
1289 SS.Adopt(ULE->getQualifierLoc());
1290
1291 // Reconstruct the lookup result.
1292 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1294 Result.setNamingClass(ULE->getNamingClass());
1295 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1296 Result.addDecl(*I, I.getAccess());
1297 Result.resolveKind();
1299 nullptr, S);
1300 }
1301
1302 // Otherwise, this is already in the form we needed, and no further checks
1303 // are necessary.
1304 return ULE;
1305}
1306
1309 auto *TD = Name.getAsTemplateDecl();
1310 if (!TD)
1312 if (isa<ClassTemplateDecl>(TD))
1314 if (isa<FunctionTemplateDecl>(TD))
1316 if (isa<VarTemplateDecl>(TD))
1318 if (isa<TypeAliasTemplateDecl>(TD))
1320 if (isa<TemplateTemplateParmDecl>(TD))
1322 if (isa<ConceptDecl>(TD))
1325}
1326
1328 assert(DC->getLexicalParent() == CurContext &&
1329 "The next DeclContext should be lexically contained in the current one.");
1330 CurContext = DC;
1331 S->setEntity(DC);
1332}
1333
1335 assert(CurContext && "DeclContext imbalance!");
1336
1338 assert(CurContext && "Popped translation unit!");
1339}
1340
1342 Decl *D) {
1343 // Unlike PushDeclContext, the context to which we return is not necessarily
1344 // the containing DC of TD, because the new context will be some pre-existing
1345 // TagDecl definition instead of a fresh one.
1346 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1347 CurContext = cast<TagDecl>(D)->getDefinition();
1348 assert(CurContext && "skipping definition of undefined tag");
1349 // Start lookups from the parent of the current context; we don't want to look
1350 // into the pre-existing complete definition.
1351 S->setEntity(CurContext->getLookupParent());
1352 return Result;
1353}
1354
1356 CurContext = static_cast<decltype(CurContext)>(Context);
1357}
1358
1359/// EnterDeclaratorContext - Used when we must lookup names in the context
1360/// of a declarator's nested name specifier.
1361///
1363 // C++0x [basic.lookup.unqual]p13:
1364 // A name used in the definition of a static data member of class
1365 // X (after the qualified-id of the static member) is looked up as
1366 // if the name was used in a member function of X.
1367 // C++0x [basic.lookup.unqual]p14:
1368 // If a variable member of a namespace is defined outside of the
1369 // scope of its namespace then any name used in the definition of
1370 // the variable member (after the declarator-id) is looked up as
1371 // if the definition of the variable member occurred in its
1372 // namespace.
1373 // Both of these imply that we should push a scope whose context
1374 // is the semantic context of the declaration. We can't use
1375 // PushDeclContext here because that context is not necessarily
1376 // lexically contained in the current context. Fortunately,
1377 // the containing scope should have the appropriate information.
1378
1379 assert(!S->getEntity() && "scope already has entity");
1380
1381#ifndef NDEBUG
1382 Scope *Ancestor = S->getParent();
1383 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1384 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1385#endif
1386
1387 CurContext = DC;
1388 S->setEntity(DC);
1389
1390 if (S->getParent()->isTemplateParamScope()) {
1391 // Also set the corresponding entities for all immediately-enclosing
1392 // template parameter scopes.
1393 EnterTemplatedContext(S->getParent(), DC);
1394 }
1395}
1396
1398 assert(S->getEntity() == CurContext && "Context imbalance!");
1399
1400 // Switch back to the lexical context. The safety of this is
1401 // enforced by an assert in EnterDeclaratorContext.
1402 Scope *Ancestor = S->getParent();
1403 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1404 CurContext = Ancestor->getEntity();
1405
1406 // We don't need to do anything with the scope, which is going to
1407 // disappear.
1408}
1409
1411 assert(S->isTemplateParamScope() &&
1412 "expected to be initializing a template parameter scope");
1413
1414 // C++20 [temp.local]p7:
1415 // In the definition of a member of a class template that appears outside
1416 // of the class template definition, the name of a member of the class
1417 // template hides the name of a template-parameter of any enclosing class
1418 // templates (but not a template-parameter of the member if the member is a
1419 // class or function template).
1420 // C++20 [temp.local]p9:
1421 // In the definition of a class template or in the definition of a member
1422 // of such a template that appears outside of the template definition, for
1423 // each non-dependent base class (13.8.2.1), if the name of the base class
1424 // or the name of a member of the base class is the same as the name of a
1425 // template-parameter, the base class name or member name hides the
1426 // template-parameter name (6.4.10).
1427 //
1428 // This means that a template parameter scope should be searched immediately
1429 // after searching the DeclContext for which it is a template parameter
1430 // scope. For example, for
1431 // template<typename T> template<typename U> template<typename V>
1432 // void N::A<T>::B<U>::f(...)
1433 // we search V then B<U> (and base classes) then U then A<T> (and base
1434 // classes) then T then N then ::.
1435 unsigned ScopeDepth = getTemplateDepth(S);
1436 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1437 DeclContext *SearchDCAfterScope = DC;
1438 for (; DC; DC = DC->getLookupParent()) {
1439 if (const TemplateParameterList *TPL =
1440 cast<Decl>(DC)->getDescribedTemplateParams()) {
1441 unsigned DCDepth = TPL->getDepth() + 1;
1442 if (DCDepth > ScopeDepth)
1443 continue;
1444 if (ScopeDepth == DCDepth)
1445 SearchDCAfterScope = DC = DC->getLookupParent();
1446 break;
1447 }
1448 }
1449 S->setLookupEntity(SearchDCAfterScope);
1450 }
1451}
1452
1454 // We assume that the caller has already called
1455 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1456 FunctionDecl *FD = D->getAsFunction();
1457 if (!FD)
1458 return;
1459
1460 // Same implementation as PushDeclContext, but enters the context
1461 // from the lexical parent, rather than the top-level class.
1462 assert(CurContext == FD->getLexicalParent() &&
1463 "The next DeclContext should be lexically contained in the current one.");
1464 CurContext = FD;
1465 S->setEntity(CurContext);
1466
1467 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1468 ParmVarDecl *Param = FD->getParamDecl(P);
1469 // If the parameter has an identifier, then add it to the scope
1470 if (Param->getIdentifier()) {
1471 S->AddDecl(Param);
1472 IdResolver.AddDecl(Param);
1473 }
1474 }
1475}
1476
1478 // Same implementation as PopDeclContext, but returns to the lexical parent,
1479 // rather than the top-level class.
1480 assert(CurContext && "DeclContext imbalance!");
1482 assert(CurContext && "Popped translation unit!");
1483}
1484
1485/// Determine whether overloading is allowed for a new function
1486/// declaration considering prior declarations of the same name.
1487///
1488/// This routine determines whether overloading is possible, not
1489/// whether a new declaration actually overloads a previous one.
1490/// It will return true in C++ (where overloads are alway permitted)
1491/// or, as a C extension, when either the new declaration or a
1492/// previous one is declared with the 'overloadable' attribute.
1494 ASTContext &Context,
1495 const FunctionDecl *New) {
1496 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1497 return true;
1498
1499 // Multiversion function declarations are not overloads in the
1500 // usual sense of that term, but lookup will report that an
1501 // overload set was found if more than one multiversion function
1502 // declaration is present for the same name. It is therefore
1503 // inadequate to assume that some prior declaration(s) had
1504 // the overloadable attribute; checking is required. Since one
1505 // declaration is permitted to omit the attribute, it is necessary
1506 // to check at least two; hence the 'any_of' check below. Note that
1507 // the overloadable attribute is implicitly added to declarations
1508 // that were required to have it but did not.
1509 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1510 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1511 return ND->hasAttr<OverloadableAttr>();
1512 });
1513 } else if (Previous.getResultKind() == LookupResult::Found)
1514 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1515
1516 return false;
1517}
1518
1519/// Add this decl to the scope shadowed decl chains.
1520void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1521 // Move up the scope chain until we find the nearest enclosing
1522 // non-transparent context. The declaration will be introduced into this
1523 // scope.
1524 while (S->getEntity() && S->getEntity()->isTransparentContext())
1525 S = S->getParent();
1526
1527 // Add scoped declarations into their context, so that they can be
1528 // found later. Declarations without a context won't be inserted
1529 // into any context.
1530 if (AddToContext)
1531 CurContext->addDecl(D);
1532
1533 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1534 // are function-local declarations.
1535 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1536 return;
1537
1538 // Template instantiations should also not be pushed into scope.
1539 if (isa<FunctionDecl>(D) &&
1540 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1541 return;
1542
1543 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1544 S->AddDecl(D);
1545 return;
1546 }
1547 // If this replaces anything in the current scope,
1549 IEnd = IdResolver.end();
1550 for (; I != IEnd; ++I) {
1551 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1552 S->RemoveDecl(*I);
1554
1555 // Should only need to replace one decl.
1556 break;
1557 }
1558 }
1559
1560 S->AddDecl(D);
1561
1562 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1563 // Implicitly-generated labels may end up getting generated in an order that
1564 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1565 // the label at the appropriate place in the identifier chain.
1566 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1567 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1568 if (IDC == CurContext) {
1569 if (!S->isDeclScope(*I))
1570 continue;
1571 } else if (IDC->Encloses(CurContext))
1572 break;
1573 }
1574
1576 } else {
1578 }
1580}
1581
1583 bool AllowInlineNamespace) const {
1584 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1585}
1586
1588 DeclContext *TargetDC = DC->getPrimaryContext();
1589 do {
1590 if (DeclContext *ScopeDC = S->getEntity())
1591 if (ScopeDC->getPrimaryContext() == TargetDC)
1592 return S;
1593 } while ((S = S->getParent()));
1594
1595 return nullptr;
1596}
1597
1599 DeclContext*,
1600 ASTContext&);
1601
1602/// Filters out lookup results that don't fall within the given scope
1603/// as determined by isDeclInScope.
1605 bool ConsiderLinkage,
1606 bool AllowInlineNamespace) {
1608 while (F.hasNext()) {
1609 NamedDecl *D = F.next();
1610
1611 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1612 continue;
1613
1614 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1615 continue;
1616
1617 F.erase();
1618 }
1619
1620 F.done();
1621}
1622
1623/// We've determined that \p New is a redeclaration of \p Old. Check that they
1624/// have compatible owning modules.
1626 // [module.interface]p7:
1627 // A declaration is attached to a module as follows:
1628 // - If the declaration is a non-dependent friend declaration that nominates a
1629 // function with a declarator-id that is a qualified-id or template-id or that
1630 // nominates a class other than with an elaborated-type-specifier with neither
1631 // a nested-name-specifier nor a simple-template-id, it is attached to the
1632 // module to which the friend is attached ([basic.link]).
1633 if (New->getFriendObjectKind() &&
1637 return false;
1638 }
1639
1640 Module *NewM = New->getOwningModule();
1641 Module *OldM = Old->getOwningModule();
1642
1643 if (NewM && NewM->isPrivateModule())
1644 NewM = NewM->Parent;
1645 if (OldM && OldM->isPrivateModule())
1646 OldM = OldM->Parent;
1647
1648 if (NewM == OldM)
1649 return false;
1650
1651 if (NewM && OldM) {
1652 // A module implementation unit has visibility of the decls in its
1653 // implicitly imported interface.
1654 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1655 return false;
1656
1657 // Partitions are part of the module, but a partition could import another
1658 // module, so verify that the PMIs agree.
1659 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1662 return false;
1663 }
1664
1665 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1666 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1667 if (NewIsModuleInterface || OldIsModuleInterface) {
1668 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1669 // if a declaration of D [...] appears in the purview of a module, all
1670 // other such declarations shall appear in the purview of the same module
1671 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1672 << New
1673 << NewIsModuleInterface
1674 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1675 << OldIsModuleInterface
1676 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1677 Diag(Old->getLocation(), diag::note_previous_declaration);
1678 New->setInvalidDecl();
1679 return true;
1680 }
1681
1682 return false;
1683}
1684
1685// [module.interface]p6:
1686// A redeclaration of an entity X is implicitly exported if X was introduced by
1687// an exported declaration; otherwise it shall not be exported.
1689 // [module.interface]p1:
1690 // An export-declaration shall inhabit a namespace scope.
1691 //
1692 // So it is meaningless to talk about redeclaration which is not at namespace
1693 // scope.
1694 if (!New->getLexicalDeclContext()
1696 ->isFileContext() ||
1697 !Old->getLexicalDeclContext()
1699 ->isFileContext())
1700 return false;
1701
1702 bool IsNewExported = New->isInExportDeclContext();
1703 bool IsOldExported = Old->isInExportDeclContext();
1704
1705 // It should be irrevelant if both of them are not exported.
1706 if (!IsNewExported && !IsOldExported)
1707 return false;
1708
1709 if (IsOldExported)
1710 return false;
1711
1712 assert(IsNewExported);
1713
1714 auto Lk = Old->getFormalLinkage();
1715 int S = 0;
1716 if (Lk == Linkage::Internal)
1717 S = 1;
1718 else if (Lk == Linkage::Module)
1719 S = 2;
1720 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1721 Diag(Old->getLocation(), diag::note_previous_declaration);
1722 return true;
1723}
1724
1725// A wrapper function for checking the semantic restrictions of
1726// a redeclaration within a module.
1729 return true;
1730
1731 if (CheckRedeclarationExported(New, Old))
1732 return true;
1733
1734 return false;
1735}
1736
1737// Check the redefinition in C++20 Modules.
1738//
1739// [basic.def.odr]p14:
1740// For any definable item D with definitions in multiple translation units,
1741// - if D is a non-inline non-templated function or variable, or
1742// - if the definitions in different translation units do not satisfy the
1743// following requirements,
1744// the program is ill-formed; a diagnostic is required only if the definable
1745// item is attached to a named module and a prior definition is reachable at
1746// the point where a later definition occurs.
1747// - Each such definition shall not be attached to a named module
1748// ([module.unit]).
1749// - Each such definition shall consist of the same sequence of tokens, ...
1750// ...
1751//
1752// Return true if the redefinition is not allowed. Return false otherwise.
1754 const NamedDecl *Old) const {
1755 assert(getASTContext().isSameEntity(New, Old) &&
1756 "New and Old are not the same definition, we should diagnostic it "
1757 "immediately instead of checking it.");
1758 assert(const_cast<Sema *>(this)->isReachable(New) &&
1759 const_cast<Sema *>(this)->isReachable(Old) &&
1760 "We shouldn't see unreachable definitions here.");
1761
1762 Module *NewM = New->getOwningModule();
1763 Module *OldM = Old->getOwningModule();
1764
1765 // We only checks for named modules here. The header like modules is skipped.
1766 // FIXME: This is not right if we import the header like modules in the module
1767 // purview.
1768 //
1769 // For example, assuming "header.h" provides definition for `D`.
1770 // ```C++
1771 // //--- M.cppm
1772 // export module M;
1773 // import "header.h"; // or #include "header.h" but import it by clang modules
1774 // actually.
1775 //
1776 // //--- Use.cpp
1777 // import M;
1778 // import "header.h"; // or uses clang modules.
1779 // ```
1780 //
1781 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1782 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1783 // reject it. But the current implementation couldn't detect the case since we
1784 // don't record the information about the importee modules.
1785 //
1786 // But this might not be painful in practice. Since the design of C++20 Named
1787 // Modules suggests us to use headers in global module fragment instead of
1788 // module purview.
1789 if (NewM && NewM->isHeaderLikeModule())
1790 NewM = nullptr;
1791 if (OldM && OldM->isHeaderLikeModule())
1792 OldM = nullptr;
1793
1794 if (!NewM && !OldM)
1795 return true;
1796
1797 // [basic.def.odr]p14.3
1798 // Each such definition shall not be attached to a named module
1799 // ([module.unit]).
1800 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1801 return true;
1802
1803 // Then New and Old lives in the same TU if their share one same module unit.
1804 if (NewM)
1805 NewM = NewM->getTopLevelModule();
1806 if (OldM)
1807 OldM = OldM->getTopLevelModule();
1808 return OldM == NewM;
1809}
1810
1812 if (D->getDeclContext()->isFileContext())
1813 return false;
1814
1815 return isa<UsingShadowDecl>(D) ||
1816 isa<UnresolvedUsingTypenameDecl>(D) ||
1817 isa<UnresolvedUsingValueDecl>(D);
1818}
1819
1820/// Removes using shadow declarations not at class scope from the lookup
1821/// results.
1824 while (F.hasNext())
1826 F.erase();
1827
1828 F.done();
1829}
1830
1831/// Check for this common pattern:
1832/// @code
1833/// class S {
1834/// S(const S&); // DO NOT IMPLEMENT
1835/// void operator=(const S&); // DO NOT IMPLEMENT
1836/// };
1837/// @endcode
1839 // FIXME: Should check for private access too but access is set after we get
1840 // the decl here.
1842 return false;
1843
1844 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1845 return CD->isCopyConstructor();
1846 return D->isCopyAssignmentOperator();
1847}
1848
1849// We need this to handle
1850//
1851// typedef struct {
1852// void *foo() { return 0; }
1853// } A;
1854//
1855// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1856// for example. If 'A', foo will have external linkage. If we have '*A',
1857// foo will have no linkage. Since we can't know until we get to the end
1858// of the typedef, this function finds out if D might have non-external linkage.
1859// Callers should verify at the end of the TU if it D has external linkage or
1860// not.
1861bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1862 const DeclContext *DC = D->getDeclContext();
1863 while (!DC->isTranslationUnit()) {
1864 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1865 if (!RD->hasNameForLinkage())
1866 return true;
1867 }
1868 DC = DC->getParent();
1869 }
1870
1871 return !D->isExternallyVisible();
1872}
1873
1874// FIXME: This needs to be refactored; some other isInMainFile users want
1875// these semantics.
1876static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1878 return false;
1879 return S.SourceMgr.isInMainFile(Loc);
1880}
1881
1883 assert(D);
1884
1885 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1886 return false;
1887
1888 // Ignore all entities declared within templates, and out-of-line definitions
1889 // of members of class templates.
1890 if (D->getDeclContext()->isDependentContext() ||
1892 return false;
1893
1894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1895 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1896 return false;
1897 // A non-out-of-line declaration of a member specialization was implicitly
1898 // instantiated; it's the out-of-line declaration that we're interested in.
1899 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1900 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1901 return false;
1902
1903 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1904 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1905 return false;
1906 } else {
1907 // 'static inline' functions are defined in headers; don't warn.
1908 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1909 return false;
1910 }
1911
1912 if (FD->doesThisDeclarationHaveABody() &&
1914 return false;
1915 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1916 // Constants and utility variables are defined in headers with internal
1917 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1918 // like "inline".)
1919 if (!isMainFileLoc(*this, VD->getLocation()))
1920 return false;
1921
1922 if (Context.DeclMustBeEmitted(VD))
1923 return false;
1924
1925 if (VD->isStaticDataMember() &&
1926 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1927 return false;
1928 if (VD->isStaticDataMember() &&
1929 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1930 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1931 return false;
1932
1933 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1934 return false;
1935 } else {
1936 return false;
1937 }
1938
1939 // Only warn for unused decls internal to the translation unit.
1940 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1941 // for inline functions defined in the main source file, for instance.
1942 return mightHaveNonExternalLinkage(D);
1943}
1944
1946 if (!D)
1947 return;
1948
1949 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1950 const FunctionDecl *First = FD->getFirstDecl();
1952 return; // First should already be in the vector.
1953 }
1954
1955 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1956 const VarDecl *First = VD->getFirstDecl();
1958 return; // First should already be in the vector.
1959 }
1960
1963}
1964
1965static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1966 const NamedDecl *D) {
1967 if (D->isInvalidDecl())
1968 return false;
1969
1970 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1971 // For a decomposition declaration, warn if none of the bindings are
1972 // referenced, instead of if the variable itself is referenced (which
1973 // it is, by the bindings' expressions).
1974 bool IsAllPlaceholders = true;
1975 for (const auto *BD : DD->bindings()) {
1976 if (BD->isReferenced())
1977 return false;
1978 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1979 }
1980 if (IsAllPlaceholders)
1981 return false;
1982 } else if (!D->getDeclName()) {
1983 return false;
1984 } else if (D->isReferenced() || D->isUsed()) {
1985 return false;
1986 }
1987
1988 if (D->isPlaceholderVar(LangOpts))
1989 return false;
1990
1991 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1992 D->hasAttr<CleanupAttr>())
1993 return false;
1994
1995 if (isa<LabelDecl>(D))
1996 return true;
1997
1998 // Except for labels, we only care about unused decls that are local to
1999 // functions.
2000 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2001 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2002 // For dependent types, the diagnostic is deferred.
2003 WithinFunction =
2004 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2005 if (!WithinFunction)
2006 return false;
2007
2008 if (isa<TypedefNameDecl>(D))
2009 return true;
2010
2011 // White-list anything that isn't a local variable.
2012 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2013 return false;
2014
2015 // Types of valid local variables should be complete, so this should succeed.
2016 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2017
2018 const Expr *Init = VD->getInit();
2019 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2020 Init = Cleanups->getSubExpr();
2021
2022 const auto *Ty = VD->getType().getTypePtr();
2023
2024 // Only look at the outermost level of typedef.
2025 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2026 // Allow anything marked with __attribute__((unused)).
2027 if (TT->getDecl()->hasAttr<UnusedAttr>())
2028 return false;
2029 }
2030
2031 // Warn for reference variables whose initializtion performs lifetime
2032 // extension.
2033 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2034 MTE && MTE->getExtendingDecl()) {
2035 Ty = VD->getType().getNonReferenceType().getTypePtr();
2036 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2037 }
2038
2039 // If we failed to complete the type for some reason, or if the type is
2040 // dependent, don't diagnose the variable.
2041 if (Ty->isIncompleteType() || Ty->isDependentType())
2042 return false;
2043
2044 // Look at the element type to ensure that the warning behaviour is
2045 // consistent for both scalars and arrays.
2046 Ty = Ty->getBaseElementTypeUnsafe();
2047
2048 if (const TagType *TT = Ty->getAs<TagType>()) {
2049 const TagDecl *Tag = TT->getDecl();
2050 if (Tag->hasAttr<UnusedAttr>())
2051 return false;
2052
2053 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2054 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2055 return false;
2056
2057 if (Init) {
2058 const auto *Construct =
2059 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2060 if (Construct && !Construct->isElidable()) {
2061 const CXXConstructorDecl *CD = Construct->getConstructor();
2062 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2063 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2064 return false;
2065 }
2066
2067 // Suppress the warning if we don't know how this is constructed, and
2068 // it could possibly be non-trivial constructor.
2069 if (Init->isTypeDependent()) {
2070 for (const CXXConstructorDecl *Ctor : RD->ctors())
2071 if (!Ctor->isTrivial())
2072 return false;
2073 }
2074
2075 // Suppress the warning if the constructor is unresolved because
2076 // its arguments are dependent.
2077 if (isa<CXXUnresolvedConstructExpr>(Init))
2078 return false;
2079 }
2080 }
2081 }
2082
2083 // TODO: __attribute__((unused)) templates?
2084 }
2085
2086 return true;
2087}
2088
2090 FixItHint &Hint) {
2091 if (isa<LabelDecl>(D)) {
2093 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2094 /*SkipTrailingWhitespaceAndNewline=*/false);
2095 if (AfterColon.isInvalid())
2096 return;
2098 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2099 }
2100}
2101
2104 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2105}
2106
2108 DiagReceiverTy DiagReceiver) {
2109 if (D->getTypeForDecl()->isDependentType())
2110 return;
2111
2112 for (auto *TmpD : D->decls()) {
2113 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2114 DiagnoseUnusedDecl(T, DiagReceiver);
2115 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2116 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2117 }
2118}
2119
2122 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2123}
2124
2125/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2126/// unless they are marked attr(unused).
2129 return;
2130
2131 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2132 // typedefs can be referenced later on, so the diagnostics are emitted
2133 // at end-of-translation-unit.
2135 return;
2136 }
2137
2138 FixItHint Hint;
2140
2141 unsigned DiagID;
2142 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2143 DiagID = diag::warn_unused_exception_param;
2144 else if (isa<LabelDecl>(D))
2145 DiagID = diag::warn_unused_label;
2146 else
2147 DiagID = diag::warn_unused_variable;
2148
2149 SourceLocation DiagLoc = D->getLocation();
2150 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2151}
2152
2154 DiagReceiverTy DiagReceiver) {
2155 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2156 // it's not really unused.
2157 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2158 return;
2159
2160 // In C++, `_` variables behave as if they were maybe_unused
2161 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2162 return;
2163
2164 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2165
2166 if (Ty->isReferenceType() || Ty->isDependentType())
2167 return;
2168
2169 if (const TagType *TT = Ty->getAs<TagType>()) {
2170 const TagDecl *Tag = TT->getDecl();
2171 if (Tag->hasAttr<UnusedAttr>())
2172 return;
2173 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2174 // mimic gcc's behavior.
2175 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2176 RD && !RD->hasAttr<WarnUnusedAttr>())
2177 return;
2178 }
2179
2180 // Don't warn about __block Objective-C pointer variables, as they might
2181 // be assigned in the block but not used elsewhere for the purpose of lifetime
2182 // extension.
2183 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2184 return;
2185
2186 // Don't warn about Objective-C pointer variables with precise lifetime
2187 // semantics; they can be used to ensure ARC releases the object at a known
2188 // time, which may mean assignment but no other references.
2189 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2190 return;
2191
2192 auto iter = RefsMinusAssignments.find(VD);
2193 if (iter == RefsMinusAssignments.end())
2194 return;
2195
2196 assert(iter->getSecond() >= 0 &&
2197 "Found a negative number of references to a VarDecl");
2198 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2199 // Assume the given VarDecl is "used" if its ref count stored in
2200 // `RefMinusAssignments` is positive, with one exception.
2201 //
2202 // For a C++ variable whose decl (with initializer) entirely consist the
2203 // condition expression of a if/while/for construct,
2204 // Clang creates a DeclRefExpr for the condition expression rather than a
2205 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2206 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2207 // used in the body of the if/while/for construct.
2208 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2209 if (!UnusedCXXCondDecl)
2210 return;
2211 }
2212
2213 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2214 : diag::warn_unused_but_set_variable;
2215 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2216}
2217
2219 Sema::DiagReceiverTy DiagReceiver) {
2220 // Verify that we have no forward references left. If so, there was a goto
2221 // or address of a label taken, but no definition of it. Label fwd
2222 // definitions are indicated with a null substmt which is also not a resolved
2223 // MS inline assembly label name.
2224 bool Diagnose = false;
2225 if (L->isMSAsmLabel())
2226 Diagnose = !L->isResolvedMSAsmLabel();
2227 else
2228 Diagnose = L->getStmt() == nullptr;
2229 if (Diagnose)
2230 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2231 << L);
2232}
2233
2235 S->applyNRVO();
2236
2237 if (S->decl_empty()) return;
2238 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2239 "Scope shouldn't contain decls!");
2240
2241 /// We visit the decls in non-deterministic order, but we want diagnostics
2242 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2243 /// and sort the diagnostics before emitting them, after we visited all decls.
2244 struct LocAndDiag {
2245 SourceLocation Loc;
2246 std::optional<SourceLocation> PreviousDeclLoc;
2248 };
2250 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2251 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2252 };
2253 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2254 SourceLocation PreviousDeclLoc,
2255 PartialDiagnostic PD) {
2256 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2257 };
2258
2259 for (auto *TmpD : S->decls()) {
2260 assert(TmpD && "This decl didn't get pushed??");
2261
2262 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2263 NamedDecl *D = cast<NamedDecl>(TmpD);
2264
2265 // Diagnose unused variables in this scope.
2266 if (!S->hasUnrecoverableErrorOccurred()) {
2267 DiagnoseUnusedDecl(D, addDiag);
2268 if (const auto *RD = dyn_cast<RecordDecl>(D))
2269 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2270 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2271 DiagnoseUnusedButSetDecl(VD, addDiag);
2272 RefsMinusAssignments.erase(VD);
2273 }
2274 }
2275
2276 if (!D->getDeclName()) continue;
2277
2278 // If this was a forward reference to a label, verify it was defined.
2279 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2280 CheckPoppedLabel(LD, *this, addDiag);
2281
2282 // Remove this name from our lexical scope, and warn on it if we haven't
2283 // already.
2285 auto ShadowI = ShadowingDecls.find(D);
2286 if (ShadowI != ShadowingDecls.end()) {
2287 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2288 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2289 PDiag(diag::warn_ctor_parm_shadows_field)
2290 << D << FD << FD->getParent());
2291 }
2292 ShadowingDecls.erase(ShadowI);
2293 }
2294 }
2295
2296 llvm::sort(DeclDiags,
2297 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2298 // The particular order for diagnostics is not important, as long
2299 // as the order is deterministic. Using the raw location is going
2300 // to generally be in source order unless there are macro
2301 // expansions involved.
2302 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2303 });
2304 for (const LocAndDiag &D : DeclDiags) {
2305 Diag(D.Loc, D.PD);
2306 if (D.PreviousDeclLoc)
2307 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2308 }
2309}
2310
2311/// Look for an Objective-C class in the translation unit.
2312///
2313/// \param Id The name of the Objective-C class we're looking for. If
2314/// typo-correction fixes this name, the Id will be updated
2315/// to the fixed name.
2316///
2317/// \param IdLoc The location of the name in the translation unit.
2318///
2319/// \param DoTypoCorrection If true, this routine will attempt typo correction
2320/// if there is no class with the given name.
2321///
2322/// \returns The declaration of the named Objective-C class, or NULL if the
2323/// class could not be found.
2325 SourceLocation IdLoc,
2326 bool DoTypoCorrection) {
2327 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2328 // creation from this context.
2330
2331 if (!IDecl && DoTypoCorrection) {
2332 // Perform typo correction at the given location, but only if we
2333 // find an Objective-C class name.
2335 if (TypoCorrection C =
2337 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2338 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2339 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2340 Id = IDecl->getIdentifier();
2341 }
2342 }
2343 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2344 // This routine must always return a class definition, if any.
2345 if (Def && Def->getDefinition())
2346 Def = Def->getDefinition();
2347 return Def;
2348}
2349
2350/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2351/// from S, where a non-field would be declared. This routine copes
2352/// with the difference between C and C++ scoping rules in structs and
2353/// unions. For example, the following code is well-formed in C but
2354/// ill-formed in C++:
2355/// @code
2356/// struct S6 {
2357/// enum { BAR } e;
2358/// };
2359///
2360/// void test_S6() {
2361/// struct S6 a;
2362/// a.e = BAR;
2363/// }
2364/// @endcode
2365/// For the declaration of BAR, this routine will return a different
2366/// scope. The scope S will be the scope of the unnamed enumeration
2367/// within S6. In C++, this routine will return the scope associated
2368/// with S6, because the enumeration's scope is a transparent
2369/// context but structures can contain non-field names. In C, this
2370/// routine will return the translation unit scope, since the
2371/// enumeration's scope is a transparent context and structures cannot
2372/// contain non-field names.
2374 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2375 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2376 (S->isClassScope() && !getLangOpts().CPlusPlus))
2377 S = S->getParent();
2378 return S;
2379}
2380
2381static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2383 switch (Error) {
2385 return "";
2387 return BuiltinInfo.getHeaderName(ID);
2389 return "stdio.h";
2391 return "setjmp.h";
2393 return "ucontext.h";
2394 }
2395 llvm_unreachable("unhandled error kind");
2396}
2397
2399 unsigned ID, SourceLocation Loc) {
2401
2402 if (getLangOpts().CPlusPlus) {
2404 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2405 CLinkageDecl->setImplicit();
2406 Parent->addDecl(CLinkageDecl);
2407 Parent = CLinkageDecl;
2408 }
2409
2410 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2411 /*TInfo=*/nullptr, SC_Extern,
2412 getCurFPFeatures().isFPConstrained(),
2413 false, Type->isFunctionProtoType());
2414 New->setImplicit();
2415 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2416
2417 // Create Decl objects for each parameter, adding them to the
2418 // FunctionDecl.
2419 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2421 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2423 Context, New, SourceLocation(), SourceLocation(), nullptr,
2424 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2425 parm->setScopeInfo(0, i);
2426 Params.push_back(parm);
2427 }
2428 New->setParams(Params);
2429 }
2430
2432 return New;
2433}
2434
2435/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2436/// file scope. lazily create a decl for it. ForRedeclaration is true
2437/// if we're creating this built-in in anticipation of redeclaring the
2438/// built-in.
2440 Scope *S, bool ForRedeclaration,
2441 SourceLocation Loc) {
2443
2445 QualType R = Context.GetBuiltinType(ID, Error);
2446 if (Error) {
2447 if (!ForRedeclaration)
2448 return nullptr;
2449
2450 // If we have a builtin without an associated type we should not emit a
2451 // warning when we were not able to find a type for it.
2452 if (Error == ASTContext::GE_Missing_type ||
2454 return nullptr;
2455
2456 // If we could not find a type for setjmp it is because the jmp_buf type was
2457 // not defined prior to the setjmp declaration.
2458 if (Error == ASTContext::GE_Missing_setjmp) {
2459 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2461 return nullptr;
2462 }
2463
2464 // Generally, we emit a warning that the declaration requires the
2465 // appropriate header.
2466 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2467 << getHeaderName(Context.BuiltinInfo, ID, Error)
2469 return nullptr;
2470 }
2471
2472 if (!ForRedeclaration &&
2475 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2476 : diag::ext_implicit_lib_function_decl)
2477 << Context.BuiltinInfo.getName(ID) << R;
2478 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2479 Diag(Loc, diag::note_include_header_or_declare)
2480 << Header << Context.BuiltinInfo.getName(ID);
2481 }
2482
2483 if (R.isNull())
2484 return nullptr;
2485
2486 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2488
2489 // TUScope is the translation-unit scope to insert this function into.
2490 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2491 // relate Scopes to DeclContexts, and probably eliminate CurContext
2492 // entirely, but we're not there yet.
2493 DeclContext *SavedContext = CurContext;
2494 CurContext = New->getDeclContext();
2496 CurContext = SavedContext;
2497 return New;
2498}
2499
2500/// Typedef declarations don't have linkage, but they still denote the same
2501/// entity if their types are the same.
2502/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2503/// isSameEntity.
2507 // This is only interesting when modules are enabled.
2508 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2509 return;
2510
2511 // Empty sets are uninteresting.
2512 if (Previous.empty())
2513 return;
2514
2515 LookupResult::Filter Filter = Previous.makeFilter();
2516 while (Filter.hasNext()) {
2517 NamedDecl *Old = Filter.next();
2518
2519 // Non-hidden declarations are never ignored.
2520 if (S.isVisible(Old))
2521 continue;
2522
2523 // Declarations of the same entity are not ignored, even if they have
2524 // different linkages.
2525 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2526 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2527 Decl->getUnderlyingType()))
2528 continue;
2529
2530 // If both declarations give a tag declaration a typedef name for linkage
2531 // purposes, then they declare the same entity.
2532 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2533 Decl->getAnonDeclWithTypedefName())
2534 continue;
2535 }
2536
2537 Filter.erase();
2538 }
2539
2540 Filter.done();
2541}
2542
2544 QualType OldType;
2545 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2546 OldType = OldTypedef->getUnderlyingType();
2547 else
2548 OldType = Context.getTypeDeclType(Old);
2549 QualType NewType = New->getUnderlyingType();
2550
2551 if (NewType->isVariablyModifiedType()) {
2552 // Must not redefine a typedef with a variably-modified type.
2553 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2554 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2555 << Kind << NewType;
2556 if (Old->getLocation().isValid())
2558 New->setInvalidDecl();
2559 return true;
2560 }
2561
2562 if (OldType != NewType &&
2563 !OldType->isDependentType() &&
2564 !NewType->isDependentType() &&
2565 !Context.hasSameType(OldType, NewType)) {
2566 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2567 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2568 << Kind << NewType << OldType;
2569 if (Old->getLocation().isValid())
2571 New->setInvalidDecl();
2572 return true;
2573 }
2574 return false;
2575}
2576
2577/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2578/// same name and scope as a previous declaration 'Old'. Figure out
2579/// how to resolve this situation, merging decls or emitting
2580/// diagnostics as appropriate. If there was an error, set New to be invalid.
2581///
2583 LookupResult &OldDecls) {
2584 // If the new decl is known invalid already, don't bother doing any
2585 // merging checks.
2586 if (New->isInvalidDecl()) return;
2587
2588 // Allow multiple definitions for ObjC built-in typedefs.
2589 // FIXME: Verify the underlying types are equivalent!
2590 if (getLangOpts().ObjC) {
2591 const IdentifierInfo *TypeID = New->getIdentifier();
2592 switch (TypeID->getLength()) {
2593 default: break;
2594 case 2:
2595 {
2596 if (!TypeID->isStr("id"))
2597 break;
2598 QualType T = New->getUnderlyingType();
2599 if (!T->isPointerType())
2600 break;
2601 if (!T->isVoidPointerType()) {
2602 QualType PT = T->castAs<PointerType>()->getPointeeType();
2603 if (!PT->isStructureType())
2604 break;
2605 }
2607 // Install the built-in type for 'id', ignoring the current definition.
2609 return;
2610 }
2611 case 5:
2612 if (!TypeID->isStr("Class"))
2613 break;
2615 // Install the built-in type for 'Class', ignoring the current definition.
2617 return;
2618 case 3:
2619 if (!TypeID->isStr("SEL"))
2620 break;
2622 // Install the built-in type for 'SEL', ignoring the current definition.
2624 return;
2625 }
2626 // Fall through - the typedef name was not a builtin type.
2627 }
2628
2629 // Verify the old decl was also a type.
2630 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2631 if (!Old) {
2632 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2633 << New->getDeclName();
2634
2635 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2636 if (OldD->getLocation().isValid())
2637 notePreviousDefinition(OldD, New->getLocation());
2638
2639 return New->setInvalidDecl();
2640 }
2641
2642 // If the old declaration is invalid, just give up here.
2643 if (Old->isInvalidDecl())
2644 return New->setInvalidDecl();
2645
2646 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2647 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2648 auto *NewTag = New->getAnonDeclWithTypedefName();
2649 NamedDecl *Hidden = nullptr;
2650 if (OldTag && NewTag &&
2651 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2652 !hasVisibleDefinition(OldTag, &Hidden)) {
2653 // There is a definition of this tag, but it is not visible. Use it
2654 // instead of our tag.
2655 New->setTypeForDecl(OldTD->getTypeForDecl());
2656 if (OldTD->isModed())
2657 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2658 OldTD->getUnderlyingType());
2659 else
2660 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2661
2662 // Make the old tag definition visible.
2664
2665 // If this was an unscoped enumeration, yank all of its enumerators
2666 // out of the scope.
2667 if (isa<EnumDecl>(NewTag)) {
2668 Scope *EnumScope = getNonFieldDeclScope(S);
2669 for (auto *D : NewTag->decls()) {
2670 auto *ED = cast<EnumConstantDecl>(D);
2671 assert(EnumScope->isDeclScope(ED));
2672 EnumScope->RemoveDecl(ED);
2674 ED->getLexicalDeclContext()->removeDecl(ED);
2675 }
2676 }
2677 }
2678 }
2679
2680 // If the typedef types are not identical, reject them in all languages and
2681 // with any extensions enabled.
2682 if (isIncompatibleTypedef(Old, New))
2683 return;
2684
2685 // The types match. Link up the redeclaration chain and merge attributes if
2686 // the old declaration was a typedef.
2687 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2688 New->setPreviousDecl(Typedef);
2689 mergeDeclAttributes(New, Old);
2690 }
2691
2692 if (getLangOpts().MicrosoftExt)
2693 return;
2694
2695 if (getLangOpts().CPlusPlus) {
2696 // C++ [dcl.typedef]p2:
2697 // In a given non-class scope, a typedef specifier can be used to
2698 // redefine the name of any type declared in that scope to refer
2699 // to the type to which it already refers.
2700 if (!isa<CXXRecordDecl>(CurContext))
2701 return;
2702
2703 // C++0x [dcl.typedef]p4:
2704 // In a given class scope, a typedef specifier can be used to redefine
2705 // any class-name declared in that scope that is not also a typedef-name
2706 // to refer to the type to which it already refers.
2707 //
2708 // This wording came in via DR424, which was a correction to the
2709 // wording in DR56, which accidentally banned code like:
2710 //
2711 // struct S {
2712 // typedef struct A { } A;
2713 // };
2714 //
2715 // in the C++03 standard. We implement the C++0x semantics, which
2716 // allow the above but disallow
2717 //
2718 // struct S {
2719 // typedef int I;
2720 // typedef int I;
2721 // };
2722 //
2723 // since that was the intent of DR56.
2724 if (!isa<TypedefNameDecl>(Old))
2725 return;
2726
2727 Diag(New->getLocation(), diag::err_redefinition)
2728 << New->getDeclName();
2730 return New->setInvalidDecl();
2731 }
2732
2733 // Modules always permit redefinition of typedefs, as does C11.
2734 if (getLangOpts().Modules || getLangOpts().C11)
2735 return;
2736
2737 // If we have a redefinition of a typedef in C, emit a warning. This warning
2738 // is normally mapped to an error, but can be controlled with
2739 // -Wtypedef-redefinition. If either the original or the redefinition is
2740 // in a system header, don't emit this for compatibility with GCC.
2741 if (getDiagnostics().getSuppressSystemWarnings() &&
2742 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2743 (Old->isImplicit() ||
2746 return;
2747
2748 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2749 << New->getDeclName();
2751}
2752
2753/// DeclhasAttr - returns true if decl Declaration already has the target
2754/// attribute.
2755static bool DeclHasAttr(const Decl *D, const Attr *A) {
2756 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2757 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2758 for (const auto *i : D->attrs())
2759 if (i->getKind() == A->getKind()) {
2760 if (Ann) {
2761 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2762 return true;
2763 continue;
2764 }
2765 // FIXME: Don't hardcode this check
2766 if (OA && isa<OwnershipAttr>(i))
2767 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2768 return true;
2769 }
2770
2771 return false;
2772}
2773
2775 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2776 return VD->isThisDeclarationADefinition();
2777 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2778 return TD->isCompleteDefinition() || TD->isBeingDefined();
2779 return true;
2780}
2781
2782/// Merge alignment attributes from \p Old to \p New, taking into account the
2783/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2784///
2785/// \return \c true if any attributes were added to \p New.
2786static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2787 // Look for alignas attributes on Old, and pick out whichever attribute
2788 // specifies the strictest alignment requirement.
2789 AlignedAttr *OldAlignasAttr = nullptr;
2790 AlignedAttr *OldStrictestAlignAttr = nullptr;
2791 unsigned OldAlign = 0;
2792 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2793 // FIXME: We have no way of representing inherited dependent alignments
2794 // in a case like:
2795 // template<int A, int B> struct alignas(A) X;
2796 // template<int A, int B> struct alignas(B) X {};
2797 // For now, we just ignore any alignas attributes which are not on the
2798 // definition in such a case.
2799 if (I->isAlignmentDependent())
2800 return false;
2801
2802 if (I->isAlignas())
2803 OldAlignasAttr = I;
2804
2805 unsigned Align = I->getAlignment(S.Context);
2806 if (Align > OldAlign) {
2807 OldAlign = Align;
2808 OldStrictestAlignAttr = I;
2809 }
2810 }
2811
2812 // Look for alignas attributes on New.
2813 AlignedAttr *NewAlignasAttr = nullptr;
2814 unsigned NewAlign = 0;
2815 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2816 if (I->isAlignmentDependent())
2817 return false;
2818
2819 if (I->isAlignas())
2820 NewAlignasAttr = I;
2821
2822 unsigned Align = I->getAlignment(S.Context);
2823 if (Align > NewAlign)
2824 NewAlign = Align;
2825 }
2826
2827 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2828 // Both declarations have 'alignas' attributes. We require them to match.
2829 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2830 // fall short. (If two declarations both have alignas, they must both match
2831 // every definition, and so must match each other if there is a definition.)
2832
2833 // If either declaration only contains 'alignas(0)' specifiers, then it
2834 // specifies the natural alignment for the type.
2835 if (OldAlign == 0 || NewAlign == 0) {
2836 QualType Ty;
2837 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2838 Ty = VD->getType();
2839 else
2840 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2841
2842 if (OldAlign == 0)
2843 OldAlign = S.Context.getTypeAlign(Ty);
2844 if (NewAlign == 0)
2845 NewAlign = S.Context.getTypeAlign(Ty);
2846 }
2847
2848 if (OldAlign != NewAlign) {
2849 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2852 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2853 }
2854 }
2855
2856 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2857 // C++11 [dcl.align]p6:
2858 // if any declaration of an entity has an alignment-specifier,
2859 // every defining declaration of that entity shall specify an
2860 // equivalent alignment.
2861 // C11 6.7.5/7:
2862 // If the definition of an object does not have an alignment
2863 // specifier, any other declaration of that object shall also
2864 // have no alignment specifier.
2865 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2866 << OldAlignasAttr;
2867 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2868 << OldAlignasAttr;
2869 }
2870
2871 bool AnyAdded = false;
2872
2873 // Ensure we have an attribute representing the strictest alignment.
2874 if (OldAlign > NewAlign) {
2875 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2876 Clone->setInherited(true);
2877 New->addAttr(Clone);
2878 AnyAdded = true;
2879 }
2880
2881 // Ensure we have an alignas attribute if the old declaration had one.
2882 if (OldAlignasAttr && !NewAlignasAttr &&
2883 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2884 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2885 Clone->setInherited(true);
2886 New->addAttr(Clone);
2887 AnyAdded = true;
2888 }
2889
2890 return AnyAdded;
2891}
2892
2893#define WANT_DECL_MERGE_LOGIC
2894#include "clang/Sema/AttrParsedAttrImpl.inc"
2895#undef WANT_DECL_MERGE_LOGIC
2896
2898 const InheritableAttr *Attr,
2900 // Diagnose any mutual exclusions between the attribute that we want to add
2901 // and attributes that already exist on the declaration.
2902 if (!DiagnoseMutualExclusions(S, D, Attr))
2903 return false;
2904
2905 // This function copies an attribute Attr from a previous declaration to the
2906 // new declaration D if the new declaration doesn't itself have that attribute
2907 // yet or if that attribute allows duplicates.
2908 // If you're adding a new attribute that requires logic different from
2909 // "use explicit attribute on decl if present, else use attribute from
2910 // previous decl", for example if the attribute needs to be consistent
2911 // between redeclarations, you need to call a custom merge function here.
2912 InheritableAttr *NewAttr = nullptr;
2913 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2914 NewAttr = S.mergeAvailabilityAttr(
2915 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2916 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2917 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2918 AA->getPriority());
2919 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2920 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2921 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2922 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2923 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2924 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2925 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2926 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2927 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2928 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2929 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2930 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2931 FA->getFirstArg());
2932 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2933 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2934 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2935 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2936 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2937 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2938 IA->getInheritanceModel());
2939 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2940 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2941 &S.Context.Idents.get(AA->getSpelling()));
2942 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2943 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2944 isa<CUDAGlobalAttr>(Attr))) {
2945 // CUDA target attributes are part of function signature for
2946 // overloading purposes and must not be merged.
2947 return false;
2948 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2949 NewAttr = S.mergeMinSizeAttr(D, *MA);
2950 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2951 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2952 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2953 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2954 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2955 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2956 else if (isa<AlignedAttr>(Attr))
2957 // AlignedAttrs are handled separately, because we need to handle all
2958 // such attributes on a declaration at the same time.
2959 NewAttr = nullptr;
2960 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2961 (AMK == Sema::AMK_Override ||
2964 NewAttr = nullptr;
2965 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2966 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2967 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2968 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2969 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2970 NewAttr = S.mergeImportNameAttr(D, *INA);
2971 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2972 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2973 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2974 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2975 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2976 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2977 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2978 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2979 NT->getZ());
2980 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2981 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2982 else if (isa<SuppressAttr>(Attr))
2983 // Do nothing. Each redeclaration should be suppressed separately.
2984 NewAttr = nullptr;
2985 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2986 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2987
2988 if (NewAttr) {
2989 NewAttr->setInherited(true);
2990 D->addAttr(NewAttr);
2991 if (isa<MSInheritanceAttr>(NewAttr))
2992 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2993 return true;
2994 }
2995
2996 return false;
2997}
2998
2999static const NamedDecl *getDefinition(const Decl *D) {
3000 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
3001 return TD->getDefinition();
3002 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3003 const VarDecl *Def = VD->getDefinition();
3004 if (Def)
3005 return Def;
3006 return VD->getActingDefinition();
3007 }
3008 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3009 const FunctionDecl *Def = nullptr;
3010 if (FD->isDefined(Def, true))
3011 return Def;
3012 }
3013 return nullptr;
3014}
3015
3016static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3017 for (const auto *Attribute : D->attrs())
3018 if (Attribute->getKind() == Kind)
3019 return true;
3020 return false;
3021}
3022
3023/// checkNewAttributesAfterDef - If we already have a definition, check that
3024/// there are no new attributes in this declaration.
3025static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3026 if (!New->hasAttrs())
3027 return;
3028
3029 const NamedDecl *Def = getDefinition(Old);
3030 if (!Def || Def == New)
3031 return;
3032
3033 AttrVec &NewAttributes = New->getAttrs();
3034 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3035 const Attr *NewAttribute = NewAttributes[I];
3036
3037 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3038 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3039 Sema::SkipBodyInfo SkipBody;
3040 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3041
3042 // If we're skipping this definition, drop the "alias" attribute.
3043 if (SkipBody.ShouldSkip) {
3044 NewAttributes.erase(NewAttributes.begin() + I);
3045 --E;
3046 continue;
3047 }
3048 } else {
3049 VarDecl *VD = cast<VarDecl>(New);
3050 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3052 ? diag::err_alias_after_tentative
3053 : diag::err_redefinition;
3054 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3055 if (Diag == diag::err_redefinition)
3056 S.notePreviousDefinition(Def, VD->getLocation());
3057 else
3058 S.Diag(Def->getLocation(), diag::note_previous_definition);
3059 VD->setInvalidDecl();
3060 }
3061 ++I;
3062 continue;
3063 }
3064
3065 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3066 // Tentative definitions are only interesting for the alias check above.
3067 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3068 ++I;
3069 continue;
3070 }
3071 }
3072
3073 if (hasAttribute(Def, NewAttribute->getKind())) {
3074 ++I;
3075 continue; // regular attr merging will take care of validating this.
3076 }
3077
3078 if (isa<C11NoReturnAttr>(NewAttribute)) {
3079 // C's _Noreturn is allowed to be added to a function after it is defined.
3080 ++I;
3081 continue;
3082 } else if (isa<UuidAttr>(NewAttribute)) {
3083 // msvc will allow a subsequent definition to add an uuid to a class
3084 ++I;
3085 continue;
3086 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3087 if (AA->isAlignas()) {
3088 // C++11 [dcl.align]p6:
3089 // if any declaration of an entity has an alignment-specifier,
3090 // every defining declaration of that entity shall specify an
3091 // equivalent alignment.
3092 // C11 6.7.5/7:
3093 // If the definition of an object does not have an alignment
3094 // specifier, any other declaration of that object shall also
3095 // have no alignment specifier.
3096 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3097 << AA;
3098 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3099 << AA;
3100 NewAttributes.erase(NewAttributes.begin() + I);
3101 --E;
3102 continue;
3103 }
3104 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3105 // If there is a C definition followed by a redeclaration with this
3106 // attribute then there are two different definitions. In C++, prefer the
3107 // standard diagnostics.
3108 if (!S.getLangOpts().CPlusPlus) {
3109 S.Diag(NewAttribute->getLocation(),
3110 diag::err_loader_uninitialized_redeclaration);
3111 S.Diag(Def->getLocation(), diag::note_previous_definition);
3112 NewAttributes.erase(NewAttributes.begin() + I);
3113 --E;
3114 continue;
3115 }
3116 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3117 cast<VarDecl>(New)->isInline() &&
3118 !cast<VarDecl>(New)->isInlineSpecified()) {
3119 // Don't warn about applying selectany to implicitly inline variables.
3120 // Older compilers and language modes would require the use of selectany
3121 // to make such variables inline, and it would have no effect if we
3122 // honored it.
3123 ++I;
3124 continue;
3125 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3126 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3127 // declarations after definitions.
3128 ++I;
3129 continue;
3130 }
3131
3132 S.Diag(NewAttribute->getLocation(),
3133 diag::warn_attribute_precede_definition);
3134 S.Diag(Def->getLocation(), diag::note_previous_definition);
3135 NewAttributes.erase(NewAttributes.begin() + I);
3136 --E;
3137 }
3138}
3139
3140static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3141 const ConstInitAttr *CIAttr,
3142 bool AttrBeforeInit) {
3143 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3144
3145 // Figure out a good way to write this specifier on the old declaration.
3146 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3147 // enough of the attribute list spelling information to extract that without
3148 // heroics.
3149 std::string SuitableSpelling;
3150 if (S.getLangOpts().CPlusPlus20)
3151 SuitableSpelling = std::string(
3152 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3153 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3154 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3155 InsertLoc, {tok::l_square, tok::l_square,
3156 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3157 S.PP.getIdentifierInfo("require_constant_initialization"),
3158 tok::r_square, tok::r_square}));
3159 if (SuitableSpelling.empty())
3160 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3161 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3162 S.PP.getIdentifierInfo("require_constant_initialization"),
3163 tok::r_paren, tok::r_paren}));
3164 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3165 SuitableSpelling = "constinit";
3166 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3167 SuitableSpelling = "[[clang::require_constant_initialization]]";
3168 if (SuitableSpelling.empty())
3169 SuitableSpelling = "__attribute__((require_constant_initialization))";
3170 SuitableSpelling += " ";
3171
3172 if (AttrBeforeInit) {
3173 // extern constinit int a;
3174 // int a = 0; // error (missing 'constinit'), accepted as extension
3175 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3176 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3177 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3178 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3179 } else {
3180 // int a = 0;
3181 // constinit extern int a; // error (missing 'constinit')
3182 S.Diag(CIAttr->getLocation(),
3183 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3184 : diag::warn_require_const_init_added_too_late)
3185 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3186 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3187 << CIAttr->isConstinit()
3188 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3189 }
3190}
3191
3192/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3195 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3196 UsedAttr *NewAttr = OldAttr->clone(Context);
3197 NewAttr->setInherited(true);
3198 New->addAttr(NewAttr);
3199 }
3200 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3201 RetainAttr *NewAttr = OldAttr->clone(Context);
3202 NewAttr->setInherited(true);
3203 New->addAttr(NewAttr);
3204 }
3205
3206 if (!Old->hasAttrs() && !New->hasAttrs())
3207 return;
3208
3209 // [dcl.constinit]p1:
3210 // If the [constinit] specifier is applied to any declaration of a
3211 // variable, it shall be applied to the initializing declaration.
3212 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3213 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3214 if (bool(OldConstInit) != bool(NewConstInit)) {
3215 const auto *OldVD = cast<VarDecl>(Old);
3216 auto *NewVD = cast<VarDecl>(New);
3217
3218 // Find the initializing declaration. Note that we might not have linked
3219 // the new declaration into the redeclaration chain yet.
3220 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3221 if (!InitDecl &&
3222 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3223 InitDecl = NewVD;
3224
3225 if (InitDecl == NewVD) {
3226 // This is the initializing declaration. If it would inherit 'constinit',
3227 // that's ill-formed. (Note that we do not apply this to the attribute
3228 // form).
3229 if (OldConstInit && OldConstInit->isConstinit())
3230 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3231 /*AttrBeforeInit=*/true);
3232 } else if (NewConstInit) {
3233 // This is the first time we've been told that this declaration should
3234 // have a constant initializer. If we already saw the initializing
3235 // declaration, this is too late.
3236 if (InitDecl && InitDecl != NewVD) {
3237 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3238 /*AttrBeforeInit=*/false);
3239 NewVD->dropAttr<ConstInitAttr>();
3240 }
3241 }
3242 }
3243
3244 // Attributes declared post-definition are currently ignored.
3245 checkNewAttributesAfterDef(*this, New, Old);
3246
3247 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3248 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3249 if (!OldA->isEquivalent(NewA)) {
3250 // This redeclaration changes __asm__ label.
3251 Diag(New->getLocation(), diag::err_different_asm_label);
3252 Diag(OldA->getLocation(), diag::note_previous_declaration);
3253 }
3254 } else if (Old->isUsed()) {
3255 // This redeclaration adds an __asm__ label to a declaration that has
3256 // already been ODR-used.
3257 Diag(New->getLocation(), diag::err_late_asm_label_name)
3258 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3259 }
3260 }
3261
3262 // Re-declaration cannot add abi_tag's.
3263 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3264 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3265 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3266 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3267 Diag(NewAbiTagAttr->getLocation(),
3268 diag::err_new_abi_tag_on_redeclaration)
3269 << NewTag;
3270 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3271 }
3272 }
3273 } else {
3274 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3275 Diag(Old->getLocation(), diag::note_previous_declaration);
3276 }
3277 }
3278
3279 // This redeclaration adds a section attribute.
3280 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3281 if (auto *VD = dyn_cast<VarDecl>(New)) {
3282 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3283 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3284 Diag(Old->getLocation(), diag::note_previous_declaration);
3285 }
3286 }
3287 }
3288
3289 // Redeclaration adds code-seg attribute.
3290 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3291 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3292 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3293 Diag(New->getLocation(), diag::warn_mismatched_section)
3294 << 0 /*codeseg*/;
3295 Diag(Old->getLocation(), diag::note_previous_declaration);
3296 }
3297
3298 if (!Old->hasAttrs())
3299 return;
3300
3301 bool foundAny = New->hasAttrs();
3302
3303 // Ensure that any moving of objects within the allocated map is done before
3304 // we process them.
3305 if (!foundAny) New->setAttrs(AttrVec());
3306
3307 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3308 // Ignore deprecated/unavailable/availability attributes if requested.
3310 if (isa<DeprecatedAttr>(I) ||
3311 isa<UnavailableAttr>(I) ||
3312 isa<AvailabilityAttr>(I)) {
3313 switch (AMK) {
3314 case AMK_None:
3315 continue;
3316
3317 case AMK_Redeclaration:
3318 case AMK_Override:
3321 LocalAMK = AMK;
3322 break;
3323 }
3324 }
3325
3326 // Already handled.
3327 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3328 continue;
3329
3330 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3331 foundAny = true;
3332 }
3333
3334 if (mergeAlignedAttrs(*this, New, Old))
3335 foundAny = true;
3336
3337 if (!foundAny) New->dropAttrs();
3338}
3339
3340/// mergeParamDeclAttributes - Copy attributes from the old parameter
3341/// to the new one.
3343 const ParmVarDecl *oldDecl,
3344 Sema &S) {
3345 // C++11 [dcl.attr.depend]p2:
3346 // The first declaration of a function shall specify the
3347 // carries_dependency attribute for its declarator-id if any declaration
3348 // of the function specifies the carries_dependency attribute.
3349 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3350 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3351 S.Diag(CDA->getLocation(),
3352 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3353 // Find the first declaration of the parameter.
3354 // FIXME: Should we build redeclaration chains for function parameters?
3355 const FunctionDecl *FirstFD =
3356 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3357 const ParmVarDecl *FirstVD =
3358 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3359 S.Diag(FirstVD->getLocation(),
3360 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3361 }
3362
3363 // HLSL parameter declarations for inout and out must match between
3364 // declarations. In HLSL inout and out are ambiguous at the call site, but
3365 // have different calling behavior, so you cannot overload a method based on a
3366 // difference between inout and out annotations.
3367 if (S.getLangOpts().HLSL) {
3368 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3369 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3370 // We don't need to cover the case where one declaration doesn't have an
3371 // attribute. The only possible case there is if one declaration has an `in`
3372 // attribute and the other declaration has no attribute. This case is
3373 // allowed since parameters are `in` by default.
3374 if (NDAttr && ODAttr &&
3375 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3376 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3377 << NDAttr << newDecl;
3378 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3379 << ODAttr;
3380 }
3381 }
3382
3383 if (!oldDecl->hasAttrs())
3384 return;
3385
3386 bool foundAny = newDecl->hasAttrs();
3387
3388 // Ensure that any moving of objects within the allocated map is
3389 // done before we process them.
3390 if (!foundAny) newDecl->setAttrs(AttrVec());
3391
3392 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3393 if (!DeclHasAttr(newDecl, I)) {
3394 InheritableAttr *newAttr =
3395 cast<InheritableParamAttr>(I->clone(S.Context));
3396 newAttr->setInherited(true);
3397 newDecl->addAttr(newAttr);
3398 foundAny = true;
3399 }
3400 }
3401
3402 if (!foundAny) newDecl->dropAttrs();
3403}
3404
3406 const ASTContext &Ctx) {
3407
3408 auto NoSizeInfo = [&Ctx](QualType Ty) {
3409 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3410 return true;
3411 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3412 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3413 return false;
3414 };
3415
3416 // `type[]` is equivalent to `type *` and `type[*]`.
3417 if (NoSizeInfo(Old) && NoSizeInfo(New))
3418 return true;
3419
3420 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3421 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3422 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3423 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3424 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3425 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3426 return false;
3427 return true;
3428 }
3429
3430 // Only compare size, ignore Size modifiers and CVR.
3431 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3432 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3433 Ctx.getAsConstantArrayType(New)->getSize();
3434 }
3435
3436 // Don't try to compare dependent sized array
3438 return true;
3439 }
3440
3441 return Old == New;
3442}
3443
3444static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3445 const ParmVarDecl *OldParam,
3446 Sema &S) {
3447 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3448 if (auto Newnullability = NewParam->getType()->getNullability()) {
3449 if (*Oldnullability != *Newnullability) {
3450 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3452 *Newnullability,
3454 != 0))
3456 *Oldnullability,
3458 != 0));
3459 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3460 }
3461 } else {
3462 QualType NewT = NewParam->getType();
3463 NewT = S.Context.getAttributedType(
3465 NewT, NewT);
3466 NewParam->setType(NewT);
3467 }
3468 }
3469 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3470 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3471 if (OldParamDT && NewParamDT &&
3472 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3473 QualType OldParamOT = OldParamDT->getOriginalType();
3474 QualType NewParamOT = NewParamDT->getOriginalType();
3475 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3476 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3477 << NewParam << NewParamOT;
3478 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3479 << OldParamOT;
3480 }
3481 }
3482}
3483
3484namespace {
3485
3486/// Used in MergeFunctionDecl to keep track of function parameters in
3487/// C.
3488struct GNUCompatibleParamWarning {
3489 ParmVarDecl *OldParm;
3490 ParmVarDecl *NewParm;
3491 QualType PromotedType;
3492};
3493
3494} // end anonymous namespace
3495
3496// Determine whether the previous declaration was a definition, implicit
3497// declaration, or a declaration.
3498template <typename T>
3499static std::pair<diag::kind, SourceLocation>
3500getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3501 diag::kind PrevDiag;
3502 SourceLocation OldLocation = Old->getLocation();
3503 if (Old->isThisDeclarationADefinition())
3504 PrevDiag = diag::note_previous_definition;
3505 else if (Old->isImplicit()) {
3506 PrevDiag = diag::note_previous_implicit_declaration;
3507 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3508 if (FD->getBuiltinID())
3509 PrevDiag = diag::note_previous_builtin_declaration;
3510 }
3511 if (OldLocation.isInvalid())
3512 OldLocation = New->getLocation();
3513 } else
3514 PrevDiag = diag::note_previous_declaration;
3515 return std::make_pair(PrevDiag, OldLocation);
3516}
3517
3518/// canRedefineFunction - checks if a function can be redefined. Currently,
3519/// only extern inline functions can be redefined, and even then only in
3520/// GNU89 mode.
3521static bool canRedefineFunction(const FunctionDecl *FD,
3522 const LangOptions& LangOpts) {
3523 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3524 !LangOpts.CPlusPlus &&
3525 FD->isInlineSpecified() &&
3526 FD->getStorageClass() == SC_Extern);
3527}
3528
3530 const AttributedType *AT = T->getAs<AttributedType>();
3531 while (AT && !AT->isCallingConv())
3532 AT = AT->getModifiedType()->getAs<AttributedType>();
3533 return AT;
3534}
3535
3536template <typename T>
3537static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3538 const DeclContext *DC = Old->getDeclContext();
3539 if (DC->isRecord())
3540 return false;
3541
3542 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3543 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3544 return true;
3545 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3546 return true;
3547 return false;
3548}
3549
3550template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3551static bool isExternC(VarTemplateDecl *) { return false; }
3552static bool isExternC(FunctionTemplateDecl *) { return false; }
3553
3554/// Check whether a redeclaration of an entity introduced by a
3555/// using-declaration is valid, given that we know it's not an overload
3556/// (nor a hidden tag declaration).
3557template<typename ExpectedDecl>
3559 ExpectedDecl *New) {
3560 // C++11 [basic.scope.declarative]p4:
3561 // Given a set of declarations in a single declarative region, each of
3562 // which specifies the same unqualified name,
3563 // -- they shall all refer to the same entity, or all refer to functions
3564 // and function templates; or
3565 // -- exactly one declaration shall declare a class name or enumeration
3566 // name that is not a typedef name and the other declarations shall all
3567 // refer to the same variable or enumerator, or all refer to functions
3568 // and function templates; in this case the class name or enumeration
3569 // name is hidden (3.3.10).
3570
3571 // C++11 [namespace.udecl]p14:
3572 // If a function declaration in namespace scope or block scope has the
3573 // same name and the same parameter-type-list as a function introduced
3574 // by a using-declaration, and the declarations do not declare the same
3575 // function, the program is ill-formed.
3576
3577 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3578 if (Old &&
3579 !Old->getDeclContext()->getRedeclContext()->Equals(
3580 New->getDeclContext()->getRedeclContext()) &&
3581 !(isExternC(Old) && isExternC(New)))
3582 Old = nullptr;
3583
3584 if (!Old) {
3585 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3586 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3587 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3588 return true;
3589 }
3590 return false;
3591}
3592
3594 const FunctionDecl *B) {
3595 assert(A->getNumParams() == B->getNumParams());
3596
3597 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3598 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3599 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3600 if (AttrA == AttrB)
3601 return true;
3602 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3603 AttrA->isDynamic() == AttrB->isDynamic();
3604 };
3605
3606 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3607}
3608
3609/// If necessary, adjust the semantic declaration context for a qualified
3610/// declaration to name the correct inline namespace within the qualifier.
3612 DeclaratorDecl *OldD) {
3613 // The only case where we need to update the DeclContext is when
3614 // redeclaration lookup for a qualified name finds a declaration
3615 // in an inline namespace within the context named by the qualifier:
3616 //
3617 // inline namespace N { int f(); }
3618 // int ::f(); // Sema DC needs adjusting from :: to N::.
3619 //
3620 // For unqualified declarations, the semantic context *can* change
3621 // along the redeclaration chain (for local extern declarations,
3622 // extern "C" declarations, and friend declarations in particular).
3623 if (!NewD->getQualifier())
3624 return;
3625
3626 // NewD is probably already in the right context.
3627 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3628 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3629 if (NamedDC->Equals(SemaDC))
3630 return;
3631
3632 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3633 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3634 "unexpected context for redeclaration");
3635
3636 auto *LexDC = NewD->getLexicalDeclContext();
3637 auto FixSemaDC = [=](NamedDecl *D) {
3638 if (!D)
3639 return;
3640 D->setDeclContext(SemaDC);
3641 D->setLexicalDeclContext(LexDC);
3642 };
3643
3644 FixSemaDC(NewD);
3645 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3646 FixSemaDC(FD->getDescribedFunctionTemplate());
3647 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3648 FixSemaDC(VD->getDescribedVarTemplate());
3649}
3650
3651/// MergeFunctionDecl - We just parsed a function 'New' from
3652/// declarator D which has the same name and scope as a previous
3653/// declaration 'Old'. Figure out how to resolve this situation,
3654/// merging decls or emitting diagnostics as appropriate.
3655///
3656/// In C++, New and Old must be declarations that are not
3657/// overloaded. Use IsOverload to determine whether New and Old are
3658/// overloaded, and to select the Old declaration that New should be
3659/// merged with.
3660///
3661/// Returns true if there was an error, false otherwise.
3663 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3664 // Verify the old decl was also a function.
3665 FunctionDecl *Old = OldD->getAsFunction();
3666 if (!Old) {
3667 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3668 if (New->getFriendObjectKind()) {
3669 Diag(New->getLocation(), diag::err_using_decl_friend);
3670 Diag(Shadow->getTargetDecl()->getLocation(),
3671 diag::note_using_decl_target);
3672 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3673 << 0;
3674 return true;
3675 }
3676
3677 // Check whether the two declarations might declare the same function or
3678 // function template.
3679 if (FunctionTemplateDecl *NewTemplate =
3681 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3682 NewTemplate))
3683 return true;
3684 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3685 ->getAsFunction();
3686 } else {
3687 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3688 return true;
3689 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3690 }
3691 } else {
3692 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3693 << New->getDeclName();
3694 notePreviousDefinition(OldD, New->getLocation());
3695 return true;
3696 }
3697 }
3698
3699 // If the old declaration was found in an inline namespace and the new
3700 // declaration was qualified, update the DeclContext to match.
3702
3703 // If the old declaration is invalid, just give up here.
3704 if (Old->isInvalidDecl())
3705 return true;
3706
3707 // Disallow redeclaration of some builtins.
3708 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3709 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3710 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3711 << Old << Old->getType();
3712 return true;
3713 }
3714
3715 diag::kind PrevDiag;
3716 SourceLocation OldLocation;
3717 std::tie(PrevDiag, OldLocation) =
3719
3720 // Don't complain about this if we're in GNU89 mode and the old function
3721 // is an extern inline function.
3722 // Don't complain about specializations. They are not supposed to have
3723 // storage classes.
3724 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3725 New->getStorageClass() == SC_Static &&
3726 Old->hasExternalFormalLinkage() &&
3729 if (getLangOpts().MicrosoftExt) {
3730 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3731 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3732 } else {
3733 Diag(New->getLocation(), diag::err_static_non_static) << New;
3734 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3735 return true;
3736 }
3737 }
3738
3739 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3740 if (!Old->hasAttr<InternalLinkageAttr>()) {
3741 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3742 << ILA;
3743 Diag(Old->getLocation(), diag::note_previous_declaration);
3744 New->dropAttr<InternalLinkageAttr>();
3745 }
3746
3747 if (auto *EA = New->getAttr<ErrorAttr>()) {
3748 if (!Old->hasAttr<ErrorAttr>()) {
3749 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3750 Diag(Old->getLocation(), diag::note_previous_declaration);
3751 New->dropAttr<ErrorAttr>();
3752 }
3753 }
3754
3755 if (CheckRedeclarationInModule(New, Old))
3756 return true;
3757
3758 if (!getLangOpts().CPlusPlus) {
3759 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3760 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3761 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3762 << New << OldOvl;
3763
3764 // Try our best to find a decl that actually has the overloadable
3765 // attribute for the note. In most cases (e.g. programs with only one
3766 // broken declaration/definition), this won't matter.
3767 //
3768 // FIXME: We could do this if we juggled some extra state in
3769 // OverloadableAttr, rather than just removing it.
3770 const Decl *DiagOld = Old;
3771 if (OldOvl) {
3772 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3773 const auto *A = D->getAttr<OverloadableAttr>();
3774 return A && !A->isImplicit();
3775 });
3776 // If we've implicitly added *all* of the overloadable attrs to this
3777 // chain, emitting a "previous redecl" note is pointless.
3778 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3779 }
3780
3781 if (DiagOld)
3782 Diag(DiagOld->getLocation(),
3783 diag::note_attribute_overloadable_prev_overload)
3784 << OldOvl;
3785
3786 if (OldOvl)
3787 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3788 else
3789 New->dropAttr<OverloadableAttr>();
3790 }
3791 }
3792
3793 // It is not permitted to redeclare an SME function with different SME
3794 // attributes.
3795 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3796 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3797 << New->getType() << Old->getType();
3798 Diag(OldLocation, diag::note_previous_declaration);
3799 return true;
3800 }
3801
3802 // If a function is first declared with a calling convention, but is later
3803 // declared or defined without one, all following decls assume the calling
3804 // convention of the first.
3805 //
3806 // It's OK if a function is first declared without a calling convention,
3807 // but is later declared or defined with the default calling convention.
3808 //
3809 // To test if either decl has an explicit calling convention, we look for
3810 // AttributedType sugar nodes on the type as written. If they are missing or
3811 // were canonicalized away, we assume the calling convention was implicit.
3812 //
3813 // Note also that we DO NOT return at this point, because we still have
3814 // other tests to run.
3815 QualType OldQType = Context.getCanonicalType(Old->getType());
3816 QualType NewQType = Context.getCanonicalType(New->getType());
3817 const FunctionType *OldType = cast<FunctionType>(OldQType);
3818 const FunctionType *NewType = cast<FunctionType>(NewQType);
3819 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3820 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3821 bool RequiresAdjustment = false;
3822
3823 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3825 const FunctionType *FT =
3826 First->getType().getCanonicalType()->castAs<FunctionType>();
3828 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3829 if (!NewCCExplicit) {
3830 // Inherit the CC from the previous declaration if it was specified
3831 // there but not here.
3832 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3833 RequiresAdjustment = true;
3834 } else if (Old->getBuiltinID()) {
3835 // Builtin attribute isn't propagated to the new one yet at this point,
3836 // so we check if the old one is a builtin.
3837
3838 // Calling Conventions on a Builtin aren't really useful and setting a
3839 // default calling convention and cdecl'ing some builtin redeclarations is
3840 // common, so warn and ignore the calling convention on the redeclaration.
3841 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3842 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3844 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3845 RequiresAdjustment = true;
3846 } else {
3847 // Calling conventions aren't compatible, so complain.
3848 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3849 Diag(New->getLocation(), diag::err_cconv_change)
3850 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3851 << !FirstCCExplicit
3852 << (!FirstCCExplicit ? "" :
3854
3855 // Put the note on the first decl, since it is the one that matters.
3856 Diag(First->getLocation(), diag::note_previous_declaration);
3857 return true;
3858 }
3859 }
3860
3861 // FIXME: diagnose the other way around?
3862 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3863 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3864 RequiresAdjustment = true;
3865 }
3866
3867 // Merge regparm attribute.
3868 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3869 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3870 if (NewTypeInfo.getHasRegParm()) {
3871 Diag(New->getLocation(), diag::err_regparm_mismatch)
3872 << NewType->getRegParmType()
3873 << OldType->getRegParmType();
3874 Diag(OldLocation, diag::note_previous_declaration);
3875 return true;
3876 }
3877
3878 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3879 RequiresAdjustment = true;
3880 }
3881
3882 // Merge ns_returns_retained attribute.
3883 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3884 if (NewTypeInfo.getProducesResult()) {
3885 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3886 << "'ns_returns_retained'";
3887 Diag(OldLocation, diag::note_previous_declaration);
3888 return true;
3889 }
3890
3891 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3892 RequiresAdjustment = true;
3893 }
3894
3895 if (OldTypeInfo.getNoCallerSavedRegs() !=
3896 NewTypeInfo.getNoCallerSavedRegs()) {
3897 if (NewTypeInfo.getNoCallerSavedRegs()) {
3898 AnyX86NoCallerSavedRegistersAttr *Attr =
3899 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3900 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3901 Diag(OldLocation, diag::note_previous_declaration);
3902 return true;
3903 }
3904
3905 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3906 RequiresAdjustment = true;
3907 }
3908
3909 if (RequiresAdjustment) {
3912 New->setType(QualType(AdjustedType, 0));
3913 NewQType = Context.getCanonicalType(New->getType());
3914 }
3915
3916 // If this redeclaration makes the function inline, we may need to add it to
3917 // UndefinedButUsed.
3918 if (!Old->isInlined() && New->isInlined() &&
3919 !New->hasAttr<GNUInlineAttr>() &&
3920 !getLangOpts().GNUInline &&
3921 Old->isUsed(false) &&
3922 !Old->isDefined() && !New->isThisDeclarationADefinition())
3923 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3924 SourceLocation()));
3925
3926 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3927 // about it.
3928 if (New->hasAttr<GNUInlineAttr>() &&
3929 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3930 UndefinedButUsed.erase(Old->getCanonicalDecl());
3931 }
3932
3933 // If pass_object_size params don't match up perfectly, this isn't a valid
3934 // redeclaration.
3935 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3937 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3938 << New->getDeclName();
3939 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3940 return true;
3941 }
3942
3943 if (getLangOpts().CPlusPlus) {
3944 OldQType = Context.getCanonicalType(Old->getType());
3945 NewQType = Context.getCanonicalType(New->getType());
3946
3947 // Go back to the type source info to compare the declared return types,
3948 // per C++1y [dcl.type.auto]p13:
3949 // Redeclarations or specializations of a function or function template
3950 // with a declared return type that uses a placeholder type shall also
3951 // use that placeholder, not a deduced type.
3952 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3953 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3954 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3955 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3956 OldDeclaredReturnType)) {
3957 QualType ResQT;
3958 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3959 OldDeclaredReturnType->isObjCObjectPointerType())
3960 // FIXME: This does the wrong thing for a deduced return type.
3961 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3962 if (ResQT.isNull()) {
3963 if (New->isCXXClassMember() && New->isOutOfLine())
3964 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3965 << New << New->getReturnTypeSourceRange();
3966 else
3967 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3968 << New->getReturnTypeSourceRange();
3969 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3970 << Old->getReturnTypeSourceRange();
3971 return true;
3972 }
3973 else
3974 NewQType = ResQT;
3975 }
3976
3977 QualType OldReturnType = OldType->getReturnType();
3978 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3979 if (OldReturnType != NewReturnType) {
3980 // If this function has a deduced return type and has already been
3981 // defined, copy the deduced value from the old declaration.
3982 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3983 if (OldAT && OldAT->isDeduced()) {
3984 QualType DT = OldAT->getDeducedType();
3985 if (DT.isNull()) {
3987 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3988 } else {
3989 New->setType(SubstAutoType(New->getType(), DT));
3990 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3991 }
3992 }
3993 }
3994
3995 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3996 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3997 if (OldMethod && NewMethod) {
3998 // Preserve triviality.
3999 NewMethod->setTrivial(OldMethod->isTrivial());
4000
4001 // MSVC allows explicit template specialization at class scope:
4002 // 2 CXXMethodDecls referring to the same function will be injected.
4003 // We don't want a redeclaration error.
4004 bool IsClassScopeExplicitSpecialization =
4005 OldMethod->isFunctionTemplateSpecialization() &&
4007 bool isFriend = NewMethod->getFriendObjectKind();
4008
4009 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4010 !IsClassScopeExplicitSpecialization) {
4011 // -- Member function declarations with the same name and the
4012 // same parameter types cannot be overloaded if any of them
4013 // is a static member function declaration.
4014 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4015 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4016 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4017 return true;
4018 }
4019
4020 // C++ [class.mem]p1:
4021 // [...] A member shall not be declared twice in the
4022 // member-specification, except that a nested class or member
4023 // class template can be declared and then later defined.
4024 if (!inTemplateInstantiation()) {
4025 unsigned NewDiag;
4026 if (isa<CXXConstructorDecl>(OldMethod))
4027 NewDiag = diag::err_constructor_redeclared;
4028 else if (isa<CXXDestructorDecl>(NewMethod))
4029 NewDiag = diag::err_destructor_redeclared;
4030 else if (isa<CXXConversionDecl>(NewMethod))
4031 NewDiag = diag::err_conv_function_redeclared;
4032 else
4033 NewDiag = diag::err_member_redeclared;
4034
4035 Diag(New->getLocation(), NewDiag);
4036 } else {
4037 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4038 << New << New->getType();
4039 }
4040 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4041 return true;
4042
4043 // Complain if this is an explicit declaration of a special
4044 // member that was initially declared implicitly.
4045 //
4046 // As an exception, it's okay to befriend such methods in order
4047 // to permit the implicit constructor/destructor/operator calls.
4048 } else if (OldMethod->isImplicit()) {
4049 if (isFriend) {
4050 NewMethod->setImplicit();
4051 } else {
4052 Diag(NewMethod->getLocation(),
4053 diag::err_definition_of_implicitly_declared_member)
4054 << New << llvm::to_underlying(getSpecialMember(OldMethod));
4055 return true;
4056 }
4057 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4058 Diag(NewMethod->getLocation(),
4059 diag::err_definition_of_explicitly_defaulted_member)
4060 << llvm::to_underlying(getSpecialMember(OldMethod));
4061 return true;
4062 }
4063 }
4064
4065 // C++1z [over.load]p2
4066 // Certain function declarations cannot be overloaded:
4067 // -- Function declarations that differ only in the return type,
4068 // the exception specification, or both cannot be overloaded.
4069
4070 // Check the exception specifications match. This may recompute the type of
4071 // both Old and New if it resolved exception specifications, so grab the
4072 // types again after this. Because this updates the type, we do this before
4073 // any of the other checks below, which may update the "de facto" NewQType
4074 // but do not necessarily update the type of New.
4075 if (CheckEquivalentExceptionSpec(Old, New))
4076 return true;
4077
4078 // C++11 [dcl.attr.noreturn]p1:
4079 // The first declaration of a function shall specify the noreturn
4080 // attribute if any declaration of that function specifies the noreturn
4081 // attribute.
4082 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4083 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4084 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4085 << NRA;
4086 Diag(Old->getLocation(), diag::note_previous_declaration);
4087 }
4088
4089 // C++11 [dcl.attr.depend]p2:
4090 // The first declaration of a function shall specify the
4091 // carries_dependency attribute for its declarator-id if any declaration
4092 // of the function specifies the carries_dependency attribute.
4093 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4094 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4095 Diag(CDA->getLocation(),
4096 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4097 Diag(Old->getFirstDecl()->getLocation(),
4098 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4099 }
4100
4101 // (C++98 8.3.5p3):
4102 // All declarations for a function shall agree exactly in both the
4103 // return type and the parameter-type-list.
4104 // We also want to respect all the extended bits except noreturn.
4105
4106 // noreturn should now match unless the old type info didn't have it.
4107 QualType OldQTypeForComparison = OldQType;
4108 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4109 auto *OldType = OldQType->castAs<FunctionProtoType>();
4110 const FunctionType *OldTypeForComparison
4111 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4112 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4113 assert(OldQTypeForComparison.isCanonical());
4114 }
4115
4116 if (haveIncompatibleLanguageLinkages(Old, New)) {
4117 // As a special case, retain the language linkage from previous
4118 // declarations of a friend function as an extension.
4119 //
4120 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4121 // and is useful because there's otherwise no way to specify language
4122 // linkage within class scope.
4123 //
4124 // Check cautiously as the friend object kind isn't yet complete.
4125 if (New->getFriendObjectKind() != Decl::FOK_None) {
4126 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4127 Diag(OldLocation, PrevDiag);
4128 } else {
4129 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4130 Diag(OldLocation, PrevDiag);
4131 return true;
4132 }
4133 }
4134
4135 // If the function types are compatible, merge the declarations. Ignore the
4136 // exception specifier because it was already checked above in
4137 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4138 // about incompatible types under -fms-compatibility.
4139 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4140 NewQType))
4141 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4142
4143 // If the types are imprecise (due to dependent constructs in friends or
4144 // local extern declarations), it's OK if they differ. We'll check again
4145 // during instantiation.
4146 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4147 return false;
4148
4149 // Fall through for conflicting redeclarations and redefinitions.
4150 }
4151
4152 // C: Function types need to be compatible, not identical. This handles
4153 // duplicate function decls like "void f(int); void f(enum X);" properly.
4154 if (!getLangOpts().CPlusPlus) {
4155 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4156 // type is specified by a function definition that contains a (possibly
4157 // empty) identifier list, both shall agree in the number of parameters
4158 // and the type of each parameter shall be compatible with the type that
4159 // results from the application of default argument promotions to the
4160 // type of the corresponding identifier. ...
4161 // This cannot be handled by ASTContext::typesAreCompatible() because that
4162 // doesn't know whether the function type is for a definition or not when
4163 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4164 // we need to cover here is that the number of arguments agree as the
4165 // default argument promotion rules were already checked by
4166 // ASTContext::typesAreCompatible().
4167 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4168 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4169 if (Old->hasInheritedPrototype())
4170 Old = Old->getCanonicalDecl();
4171 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4172 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4173 return true;
4174 }
4175
4176 // If we are merging two functions where only one of them has a prototype,
4177 // we may have enough information to decide to issue a diagnostic that the
4178 // function without a protoype will change behavior in C23. This handles
4179 // cases like:
4180 // void i(); void i(int j);
4181 // void i(int j); void i();
4182 // void i(); void i(int j) {}
4183 // See ActOnFinishFunctionBody() for other cases of the behavior change
4184 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4185 // type without a prototype.
4186 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4187 !New->isImplicit() && !Old->isImplicit()) {
4188 const FunctionDecl *WithProto, *WithoutProto;
4189 if (New->hasWrittenPrototype()) {
4190 WithProto = New;
4191 WithoutProto = Old;
4192 } else {
4193 WithProto = Old;
4194 WithoutProto = New;
4195 }
4196
4197 if (WithProto->getNumParams() != 0) {
4198 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4199 // The one without the prototype will be changing behavior in C23, so
4200 // warn about that one so long as it's a user-visible declaration.
4201 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4202 if (WithoutProto == New)
4203 IsWithoutProtoADef = NewDeclIsDefn;
4204 else
4205 IsWithProtoADef = NewDeclIsDefn;
4206 Diag(WithoutProto->getLocation(),
4207 diag::warn_non_prototype_changes_behavior)
4208 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4209 << (WithoutProto == Old) << IsWithProtoADef;
4210
4211 // The reason the one without the prototype will be changing behavior
4212 // is because of the one with the prototype, so note that so long as
4213 // it's a user-visible declaration. There is one exception to this:
4214 // when the new declaration is a definition without a prototype, the
4215 // old declaration with a prototype is not the cause of the issue,
4216 // and that does not need to be noted because the one with a
4217 // prototype will not change behavior in C23.
4218 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4219 !IsWithoutProtoADef)
4220 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4221 }
4222 }
4223 }
4224
4225 if (Context.typesAreCompatible(OldQType, NewQType)) {
4226 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4227 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4228 const FunctionProtoType *OldProto = nullptr;
4229 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4230 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4231 // The old declaration provided a function prototype, but the
4232 // new declaration does not. Merge in the prototype.
4233 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4234 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4235 OldProto->getParamTypes(),
4236 OldProto->getExtProtoInfo());
4237 New->setType(NewQType);
4239
4240 // Synthesize parameters with the same types.
4242 for (const auto &ParamType : OldProto->param_types()) {
4244 Context, New, SourceLocation(), SourceLocation(), nullptr,
4245 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4246 Param->setScopeInfo(0, Params.size());
4247 Param->setImplicit();
4248 Params.push_back(Param);
4249 }
4250
4251 New->setParams(Params);
4252 }
4253
4254 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4255 }
4256 }
4257
4258 // Check if the function types are compatible when pointer size address
4259 // spaces are ignored.
4260 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4261 return false;
4262
4263 // GNU C permits a K&R definition to follow a prototype declaration
4264 // if the declared types of the parameters in the K&R definition
4265 // match the types in the prototype declaration, even when the
4266 // promoted types of the parameters from the K&R definition differ
4267 // from the types in the prototype. GCC then keeps the types from
4268 // the prototype.
4269 //
4270 // If a variadic prototype is followed by a non-variadic K&R definition,
4271 // the K&R definition becomes variadic. This is sort of an edge case, but
4272 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4273 // C99 6.9.1p8.
4274 if (!getLangOpts().CPlusPlus &&
4275 Old->hasPrototype() && !New->hasPrototype() &&
4276 New->getType()->getAs<FunctionProtoType>() &&
4277 Old->getNumParams() == New->getNumParams()) {
4280 const FunctionProtoType *OldProto
4281 = Old->getType()->getAs<FunctionProtoType>();
4282 const FunctionProtoType *NewProto
4283 = New->getType()->getAs<FunctionProtoType>();
4284
4285 // Determine whether this is the GNU C extension.
4286 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4287 NewProto->getReturnType());
4288 bool LooseCompatible = !MergedReturn.isNull();
4289 for (unsigned Idx = 0, End = Old->getNumParams();
4290 LooseCompatible && Idx != End; ++Idx) {
4291 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4292 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4293 if (Context.typesAreCompatible(OldParm->getType(),
4294 NewProto->getParamType(Idx))) {
4295 ArgTypes.push_back(NewParm->getType());
4296 } else if (Context.typesAreCompatible(OldParm->getType(),
4297 NewParm->getType(),
4298 /*CompareUnqualified=*/true)) {
4299 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4300 NewProto->getParamType(Idx) };
4301 Warnings.push_back(Warn);
4302 ArgTypes.push_back(NewParm->getType());
4303 } else
4304 LooseCompatible = false;
4305 }
4306
4307 if (LooseCompatible) {
4308 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4309 Diag(Warnings[Warn].NewParm->getLocation(),
4310 diag::ext_param_promoted_not_compatible_with_prototype)
4311 << Warnings[Warn].PromotedType
4312 << Warnings[Warn].OldParm->getType();
4313 if (Warnings[Warn].OldParm->getLocation().isValid())
4314 Diag(Warnings[Warn].OldParm->getLocation(),
4315 diag::note_previous_declaration);
4316 }
4317
4318 if (MergeTypeWithOld)
4319 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4320 OldProto->getExtProtoInfo()));
4321 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4322 }
4323
4324 // Fall through to diagnose conflicting types.
4325 }
4326
4327 // A function that has already been declared has been redeclared or
4328 // defined with a different type; show an appropriate diagnostic.
4329
4330 // If the previous declaration was an implicitly-generated builtin
4331 // declaration, then at the very least we should use a specialized note.
4332 unsigned BuiltinID;
4333 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4334 // If it's actually a library-defined builtin function like 'malloc'
4335 // or 'printf', just warn about the incompatible redeclaration.
4337 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4338 Diag(OldLocation, diag::note_previous_builtin_declaration)
4339 << Old << Old->getType();
4340 return false;
4341 }
4342
4343 PrevDiag = diag::note_previous_builtin_declaration;
4344 }
4345
4346 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4347 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4348 return true;
4349}
4350
4351/// Completes the merge of two function declarations that are
4352/// known to be compatible.
4353///
4354/// This routine handles the merging of attributes and other
4355/// properties of function declarations from the old declaration to
4356/// the new declaration, once we know that New is in fact a
4357/// redeclaration of Old.
4358///
4359/// \returns false
4361 Scope *S, bool MergeTypeWithOld) {
4362 // Merge the attributes
4363 mergeDeclAttributes(New, Old);
4364
4365 // Merge "pure" flag.
4366 if (Old->isPureVirtual())
4367 New->setIsPureVirtual();
4368
4369 // Merge "used" flag.
4370 if (Old->getMostRecentDecl()->isUsed(false))
4371 New->setIsUsed();
4372
4373 // Merge attributes from the parameters. These can mismatch with K&R
4374 // declarations.
4375 if (New->getNumParams() == Old->getNumParams())
4376 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4377 ParmVarDecl *NewParam = New->getParamDecl(i);
4378 ParmVarDecl *OldParam = Old->getParamDecl(i);
4379 mergeParamDeclAttributes(NewParam, OldParam, *this);
4380 mergeParamDeclTypes(NewParam, OldParam, *this);
4381 }
4382
4383 if (getLangOpts().CPlusPlus)
4384 return MergeCXXFunctionDecl(New, Old, S);
4385
4386 // Merge the function types so the we get the composite types for the return
4387 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4388 // was visible.
4389 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4390 if (!Merged.isNull() && MergeTypeWithOld)
4391 New->setType(Merged);
4392
4393 return false;
4394}
4395
4397 ObjCMethodDecl *oldMethod) {
4398 // Merge the attributes, including deprecated/unavailable
4399 AvailabilityMergeKind MergeKind =
4400 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4403 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4404 : AMK_Override;
4405
4406 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4407
4408 // Merge attributes from the parameters.
4410 oe = oldMethod->param_end();
4412 ni = newMethod->param_begin(), ne = newMethod->param_end();
4413 ni != ne && oi != oe; ++ni, ++oi)
4414 mergeParamDeclAttributes(*ni, *oi, *this);
4415
4416 CheckObjCMethodOverride(newMethod, oldMethod);
4417}
4418
4420 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4421
4423 ? diag::err_redefinition_different_type
4424 : diag::err_redeclaration_different_type)
4425 << New->getDeclName() << New->getType() << Old->getType();
4426
4427 diag::kind PrevDiag;
4428 SourceLocation OldLocation;
4429 std::tie(PrevDiag, OldLocation)
4431 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4432 New->setInvalidDecl();
4433}
4434
4435/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4436/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4437/// emitting diagnostics as appropriate.
4438///
4439/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4440/// to here in AddInitializerToDecl. We can't check them before the initializer
4441/// is attached.
4443 bool MergeTypeWithOld) {
4444 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4445 return;
4446
4447 QualType MergedT;
4448 if (getLangOpts().CPlusPlus) {
4449 if (New->getType()->isUndeducedType()) {
4450 // We don't know what the new type is until the initializer is attached.
4451 return;
4452 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4453 // These could still be something that needs exception specs checked.
4454 return MergeVarDeclExceptionSpecs(New, Old);
4455 }
4456 // C++ [basic.link]p10:
4457 // [...] the types specified by all declarations referring to a given
4458 // object or function shall be identical, except that declarations for an
4459 // array object can specify array types that differ by the presence or
4460 // absence of a major array bound (8.3.4).
4461 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4462 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4463 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4464
4465 // We are merging a variable declaration New into Old. If it has an array
4466 // bound, and that bound differs from Old's bound, we should diagnose the
4467 // mismatch.
4468 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4469 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4470 PrevVD = PrevVD->getPreviousDecl()) {
4471 QualType PrevVDTy = PrevVD->getType();
4472 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4473 continue;
4474
4475 if (!Context.hasSameType(New->getType(), PrevVDTy))
4476 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4477 }
4478 }
4479
4480 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4481 if (Context.hasSameType(OldArray->getElementType(),
4482 NewArray->getElementType()))
4483 MergedT = New->getType();
4484 }
4485 // FIXME: Check visibility. New is hidden but has a complete type. If New
4486 // has no array bound, it should not inherit one from Old, if Old is not
4487 // visible.
4488 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4489 if (Context.hasSameType(OldArray->getElementType(),
4490 NewArray->getElementType()))
4491 MergedT = Old->getType();
4492 }
4493 }
4494 else if (New->getType()->isObjCObjectPointerType() &&
4495 Old->getType()->isObjCObjectPointerType()) {
4496 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4497 Old->getType());
4498 }
4499 } else {
4500 // C 6.2.7p2:
4501 // All declarations that refer to the same object or function shall have
4502 // compatible type.
4503 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4504 }
4505 if (MergedT.isNull()) {
4506 // It's OK if we couldn't merge types if either type is dependent, for a
4507 // block-scope variable. In other cases (static data members of class
4508 // templates, variable templates, ...), we require the types to be
4509 // equivalent.
4510 // FIXME: The C++ standard doesn't say anything about this.
4511 if ((New->getType()->isDependentType() ||
4512 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4513 // If the old type was dependent, we can't merge with it, so the new type
4514 // becomes dependent for now. We'll reproduce the original type when we
4515 // instantiate the TypeSourceInfo for the variable.
4516 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4518 return;
4519 }
4520 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4521 }
4522
4523 // Don't actually update the type on the new declaration if the old
4524 // declaration was an extern declaration in a different scope.
4525 if (MergeTypeWithOld)
4526 New->setType(MergedT);
4527}
4528
4529static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4531 // C11 6.2.7p4:
4532 // For an identifier with internal or external linkage declared
4533 // in a scope in which a prior declaration of that identifier is
4534 // visible, if the prior declaration specifies internal or
4535 // external linkage, the type of the identifier at the later
4536 // declaration becomes the composite type.
4537 //
4538 // If the variable isn't visible, we do not merge with its type.
4539 if (Previous.isShadowed())
4540 return false;
4541
4542 if (S.getLangOpts().CPlusPlus) {
4543 // C++11 [dcl.array]p3:
4544 // If there is a preceding declaration of the entity in the same
4545 // scope in which the bound was specified, an omitted array bound
4546 // is taken to be the same as in that earlier declaration.
4547 return NewVD->isPreviousDeclInSameBlockScope() ||
4550 } else {
4551 // If the old declaration was function-local, don't merge with its
4552 // type unless we're in the same function.
4553 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4554 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4555 }
4556}
4557
4558/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4559/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4560/// situation, merging decls or emitting diagnostics as appropriate.
4561///
4562/// Tentative definition rules (C99 6.9.2p2) are checked by
4563/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4564/// definitions here, since the initializer hasn't been attached.
4565///
4567 // If the new decl is already invalid, don't do any other checking.
4568 if (New->isInvalidDecl())
4569 return;
4570
4571 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4572 return;
4573
4574 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4575
4576 // Verify the old decl was also a variable or variable template.
4577 VarDecl *Old = nullptr;
4578 VarTemplateDecl *OldTemplate = nullptr;
4579 if (Previous.isSingleResult()) {
4580 if (NewTemplate) {
4581 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4582 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4583
4584 if (auto *Shadow =
4585 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4586 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4587 return New->setInvalidDecl();
4588 } else {
4589 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4590
4591 if (auto *Shadow =
4592 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4593 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4594 return New->setInvalidDecl();
4595 }
4596 }
4597 if (!Old) {
4598 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4599 << New->getDeclName();
4600 notePreviousDefinition(Previous.getRepresentativeDecl(),
4601 New->getLocation());
4602 return New->setInvalidDecl();
4603 }
4604
4605 // If the old declaration was found in an inline namespace and the new
4606 // declaration was qualified, update the DeclContext to match.
4608
4609 // Ensure the template parameters are compatible.
4610 if (NewTemplate &&
4612 OldTemplate->getTemplateParameters(),
4613 /*Complain=*/true, TPL_TemplateMatch))
4614 return New->setInvalidDecl();
4615
4616 // C++ [class.mem]p1:
4617 // A member shall not be declared twice in the member-specification [...]
4618 //
4619 // Here, we need only consider static data members.
4620 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4621 Diag(New->getLocation(), diag::err_duplicate_member)
4622 << New->getIdentifier();
4623 Diag(Old->getLocation(), diag::note_previous_declaration);
4624 New->setInvalidDecl();
4625 }
4626
4627 mergeDeclAttributes(New, Old);
4628 // Warn if an already-declared variable is made a weak_import in a subsequent
4629 // declaration
4630 if (New->hasAttr<WeakImportAttr>() &&
4631 Old->getStorageClass() == SC_None &&
4632 !Old->hasAttr<WeakImportAttr>()) {
4633 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4634 Diag(Old->getLocation(), diag::note_previous_declaration);
4635 // Remove weak_import attribute on new declaration.
4636 New->dropAttr<WeakImportAttr>();
4637 }
4638
4639 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4640 if (!Old->hasAttr<InternalLinkageAttr>()) {
4641 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4642 << ILA;
4643 Diag(Old->getLocation(), diag::note_previous_declaration);
4644 New->dropAttr<InternalLinkageAttr>();
4645 }
4646
4647 // Merge the types.
4648 VarDecl *MostRecent = Old->getMostRecentDecl();
4649 if (MostRecent != Old) {
4650 MergeVarDeclTypes(New, MostRecent,
4651 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4652 if (New->isInvalidDecl())
4653 return;
4654 }
4655
4656 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4657 if (New->isInvalidDecl())
4658 return;
4659
4660 diag::kind PrevDiag;
4661 SourceLocation OldLocation;
4662 std::tie(PrevDiag, OldLocation) =
4664
4665 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4666 if (New->getStorageClass() == SC_Static &&
4667 !New->isStaticDataMember() &&
4668 Old->hasExternalFormalLinkage()) {
4669 if (getLangOpts().MicrosoftExt) {
4670 Diag(New->getLocation(), diag::ext_static_non_static)
4671 << New->getDeclName();
4672 Diag(OldLocation, PrevDiag);
4673 } else {
4674 Diag(New->getLocation(), diag::err_static_non_static)
4675 << New->getDeclName();
4676 Diag(OldLocation, PrevDiag);
4677 return New->setInvalidDecl();
4678 }
4679 }
4680 // C99 6.2.2p4:
4681 // For an identifier declared with the storage-class specifier
4682 // extern in a scope in which a prior declaration of that
4683 // identifier is visible,23) if the prior declaration specifies
4684 // internal or external linkage, the linkage of the identifier at
4685 // the later declaration is the same as the linkage specified at
4686 // the prior declaration. If no prior declaration is visible, or
4687 // if the prior declaration specifies no linkage, then the
4688 // identifier has external linkage.
4689 if (New->hasExternalStorage() && Old->hasLinkage())
4690 /* Okay */;
4691 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4692 !New->isStaticDataMember() &&
4694 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4695 Diag(OldLocation, PrevDiag);
4696 return New->setInvalidDecl();
4697 }
4698
4699 // Check if extern is followed by non-extern and vice-versa.
4700 if (New->hasExternalStorage() &&
4701 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4702 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4703 Diag(OldLocation, PrevDiag);
4704 return New->setInvalidDecl();
4705 }
4706 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4707 !New->hasExternalStorage()) {
4708 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4709 Diag(OldLocation, PrevDiag);
4710 return New->setInvalidDecl();
4711 }
4712
4713 if (CheckRedeclarationInModule(New, Old))
4714 return;
4715
4716 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4717
4718 // FIXME: The test for external storage here seems wrong? We still
4719 // need to check for mismatches.
4720 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4721 // Don't complain about out-of-line definitions of static members.
4722 !(Old->getLexicalDeclContext()->isRecord() &&
4723 !New->getLexicalDeclContext()->isRecord())) {
4724 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4725 Diag(OldLocation, PrevDiag);
4726 return New->setInvalidDecl();
4727 }
4728
4729 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4730 if (VarDecl *Def = Old->getDefinition()) {
4731 // C++1z [dcl.fcn.spec]p4:
4732 // If the definition of a variable appears in a translation unit before
4733 // its first declaration as inline, the program is ill-formed.
4734 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4735 Diag(Def->getLocation(), diag::note_previous_definition);
4736 }
4737 }
4738
4739 // If this redeclaration makes the variable inline, we may need to add it to
4740 // UndefinedButUsed.
4741 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4743 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4744 SourceLocation()));
4745
4746 if (New->getTLSKind() != Old->getTLSKind()) {
4747 if (!Old->getTLSKind()) {
4748 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4749 Diag(OldLocation, PrevDiag);
4750 } else if (!New->getTLSKind()) {
4751 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4752 Diag(OldLocation, PrevDiag);
4753 } else {
4754 // Do not allow redeclaration to change the variable between requiring
4755 // static and dynamic initialization.
4756 // FIXME: GCC allows this, but uses the TLS keyword on the first
4757 // declaration to determine the kind. Do we need to be compatible here?
4758 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4759 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4760 Diag(OldLocation, PrevDiag);
4761 }
4762 }
4763
4764 // C++ doesn't have tentative definitions, so go right ahead and check here.
4765 if (getLangOpts().CPlusPlus) {
4766 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4767 Old->getCanonicalDecl()->isConstexpr()) {
4768 // This definition won't be a definition any more once it's been merged.
4769 Diag(New->getLocation(),
4770 diag::warn_deprecated_redundant_constexpr_static_def);
4772 VarDecl *Def = Old->getDefinition();
4773 if (Def && checkVarDeclRedefinition(Def, New))
4774 return;
4775 }
4776 }
4777
4778 if (haveIncompatibleLanguageLinkages(Old, New)) {
4779 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4780 Diag(OldLocation, PrevDiag);
4781 New->setInvalidDecl();
4782 return;
4783 }
4784
4785 // Merge "used" flag.
4786 if (Old->getMostRecentDecl()->isUsed(false))
4787 New->setIsUsed();
4788
4789 // Keep a chain of previous declarations.
4790 New->setPreviousDecl(Old);
4791 if (NewTemplate)
4792 NewTemplate->setPreviousDecl(OldTemplate);
4793
4794 // Inherit access appropriately.
4795 New->setAccess(Old->getAccess());
4796 if (NewTemplate)
4797 NewTemplate->setAccess(New->getAccess());
4798
4799 if (Old->isInline())
4800 New->setImplicitlyInline();
4801}
4802
4804 SourceManager &SrcMgr = getSourceManager();
4805 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4806 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4807 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4808 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4809 auto &HSI = PP.getHeaderSearchInfo();
4810 StringRef HdrFilename =
4811 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4812
4813 auto noteFromModuleOrInclude = [&](Module *Mod,
4814 SourceLocation IncLoc) -> bool {
4815 // Redefinition errors with modules are common with non modular mapped
4816 // headers, example: a non-modular header H in module A that also gets
4817 // included directly in a TU. Pointing twice to the same header/definition
4818 // is confusing, try to get better diagnostics when modules is on.
4819 if (IncLoc.isValid()) {
4820 if (Mod) {
4821 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4822 << HdrFilename.str() << Mod->getFullModuleName();
4823 if (!Mod->DefinitionLoc.isInvalid())
4824 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4825 << Mod->getFullModuleName();
4826 } else {
4827 Diag(IncLoc, diag::note_redefinition_include_same_file)
4828 << HdrFilename.str();
4829 }
4830 return true;
4831 }
4832
4833 return false;
4834 };
4835
4836 // Is it the same file and same offset? Provide more information on why
4837 // this leads to a redefinition error.
4838 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4839 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4840 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4841 bool EmittedDiag =
4842 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4843 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4844
4845 // If the header has no guards, emit a note suggesting one.
4846 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4847 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4848
4849 if (EmittedDiag)
4850 return;
4851 }
4852
4853 // Redefinition coming from different files or couldn't do better above.
4854 if (Old->getLocation().isValid())
4855 Diag(Old->getLocation(), diag::note_previous_definition);
4856}
4857
4858/// We've just determined that \p Old and \p New both appear to be definitions
4859/// of the same variable. Either diagnose or fix the problem.
4861 if (!hasVisibleDefinition(Old) &&
4862 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4863 isa<VarTemplateSpecializationDecl>(New) ||
4866 // The previous definition is hidden, and multiple definitions are
4867 // permitted (in separate TUs). Demote this to a declaration.
4869
4870 // Make the canonical definition visible.
4871 if (auto *OldTD = Old->getDescribedVarTemplate())
4874 return false;
4875 } else {
4876 Diag(New->getLocation(), diag::err_redefinition) << New;
4878 New->setInvalidDecl();
4879 return true;
4880 }
4881}
4882
4883/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4884/// no declarator (e.g. "struct foo;") is parsed.
4886 DeclSpec &DS,
4887 const ParsedAttributesView &DeclAttrs,
4888 RecordDecl *&AnonRecord) {
4890 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4891}
4892
4893// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4894// disambiguate entities defined in different scopes.
4895// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4896// compatibility.
4897// We will pick our mangling number depending on which version of MSVC is being
4898// targeted.
4899static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4901 ? S->getMSCurManglingNumber()
4902 : S->getMSLastManglingNumber();
4903}
4904
4905void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4906 if (!Context.getLangOpts().CPlusPlus)
4907 return;
4908
4909 if (isa<CXXRecordDecl>(Tag->getParent())) {
4910 // If this tag is the direct child of a class, number it if
4911 // it is anonymous.
4912 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4913 return;
4917 Tag, MCtx.getManglingNumber(
4918 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4919 return;
4920 }
4921
4922 // If this tag isn't a direct child of a class, number it if it is local.
4924 Decl *ManglingContextDecl;
4925 std::tie(MCtx, ManglingContextDecl) =
4927 if (MCtx) {
4929 Tag, MCtx->getManglingNumber(
4930 Tag, getMSManglingNumber(getLangOpts(), TagScope)));