1 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements name lookup for C, C++, Objective-C, and
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclLookups.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Lex/HeaderSearch.h"
26 #include "clang/Lex/ModuleLoader.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/Overload.h"
31 #include "clang/Sema/RISCVIntrinsicManager.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "clang/Sema/SemaRISCV.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "clang/Sema/TypoCorrection.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/STLForwardCompat.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/TinyPtrVector.h"
43 #include "llvm/ADT/edit_distance.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
54 #include "OpenCLBuiltins.inc"
56 using namespace clang
;
60 class UnqualUsingEntry
{
61 const DeclContext
*Nominated
;
62 const DeclContext
*CommonAncestor
;
65 UnqualUsingEntry(const DeclContext
*Nominated
,
66 const DeclContext
*CommonAncestor
)
67 : Nominated(Nominated
), CommonAncestor(CommonAncestor
) {
70 const DeclContext
*getCommonAncestor() const {
71 return CommonAncestor
;
74 const DeclContext
*getNominatedNamespace() const {
78 // Sort by the pointer value of the common ancestor.
80 bool operator()(const UnqualUsingEntry
&L
, const UnqualUsingEntry
&R
) {
81 return L
.getCommonAncestor() < R
.getCommonAncestor();
84 bool operator()(const UnqualUsingEntry
&E
, const DeclContext
*DC
) {
85 return E
.getCommonAncestor() < DC
;
88 bool operator()(const DeclContext
*DC
, const UnqualUsingEntry
&E
) {
89 return DC
< E
.getCommonAncestor();
94 /// A collection of using directives, as used by C++ unqualified
96 class UnqualUsingDirectiveSet
{
99 typedef SmallVector
<UnqualUsingEntry
, 8> ListTy
;
102 llvm::SmallPtrSet
<DeclContext
*, 8> visited
;
105 UnqualUsingDirectiveSet(Sema
&SemaRef
) : SemaRef(SemaRef
) {}
107 void visitScopeChain(Scope
*S
, Scope
*InnermostFileScope
) {
108 // C++ [namespace.udir]p1:
109 // During unqualified name lookup, the names appear as if they
110 // were declared in the nearest enclosing namespace which contains
111 // both the using-directive and the nominated namespace.
112 DeclContext
*InnermostFileDC
= InnermostFileScope
->getEntity();
113 assert(InnermostFileDC
&& InnermostFileDC
->isFileContext());
115 for (; S
; S
= S
->getParent()) {
116 // C++ [namespace.udir]p1:
117 // A using-directive shall not appear in class scope, but may
118 // appear in namespace scope or in block scope.
119 DeclContext
*Ctx
= S
->getEntity();
120 if (Ctx
&& Ctx
->isFileContext()) {
122 } else if (!Ctx
|| Ctx
->isFunctionOrMethod()) {
123 for (auto *I
: S
->using_directives())
124 if (SemaRef
.isVisible(I
))
125 visit(I
, InnermostFileDC
);
130 // Visits a context and collect all of its using directives
131 // recursively. Treats all using directives as if they were
132 // declared in the context.
134 // A given context is only every visited once, so it is important
135 // that contexts be visited from the inside out in order to get
136 // the effective DCs right.
137 void visit(DeclContext
*DC
, DeclContext
*EffectiveDC
) {
138 if (!visited
.insert(DC
).second
)
141 addUsingDirectives(DC
, EffectiveDC
);
144 // Visits a using directive and collects all of its using
145 // directives recursively. Treats all using directives as if they
146 // were declared in the effective DC.
147 void visit(UsingDirectiveDecl
*UD
, DeclContext
*EffectiveDC
) {
148 DeclContext
*NS
= UD
->getNominatedNamespace();
149 if (!visited
.insert(NS
).second
)
152 addUsingDirective(UD
, EffectiveDC
);
153 addUsingDirectives(NS
, EffectiveDC
);
156 // Adds all the using directives in a context (and those nominated
157 // by its using directives, transitively) as if they appeared in
158 // the given effective context.
159 void addUsingDirectives(DeclContext
*DC
, DeclContext
*EffectiveDC
) {
160 SmallVector
<DeclContext
*, 4> queue
;
162 for (auto *UD
: DC
->using_directives()) {
163 DeclContext
*NS
= UD
->getNominatedNamespace();
164 if (SemaRef
.isVisible(UD
) && visited
.insert(NS
).second
) {
165 addUsingDirective(UD
, EffectiveDC
);
173 DC
= queue
.pop_back_val();
177 // Add a using directive as if it had been declared in the given
178 // context. This helps implement C++ [namespace.udir]p3:
179 // The using-directive is transitive: if a scope contains a
180 // using-directive that nominates a second namespace that itself
181 // contains using-directives, the effect is as if the
182 // using-directives from the second namespace also appeared in
184 void addUsingDirective(UsingDirectiveDecl
*UD
, DeclContext
*EffectiveDC
) {
185 // Find the common ancestor between the effective context and
186 // the nominated namespace.
187 DeclContext
*Common
= UD
->getNominatedNamespace();
188 while (!Common
->Encloses(EffectiveDC
))
189 Common
= Common
->getParent();
190 Common
= Common
->getPrimaryContext();
192 list
.push_back(UnqualUsingEntry(UD
->getNominatedNamespace(), Common
));
195 void done() { llvm::sort(list
, UnqualUsingEntry::Comparator()); }
197 typedef ListTy::const_iterator const_iterator
;
199 const_iterator
begin() const { return list
.begin(); }
200 const_iterator
end() const { return list
.end(); }
202 llvm::iterator_range
<const_iterator
>
203 getNamespacesFor(const DeclContext
*DC
) const {
204 return llvm::make_range(std::equal_range(begin(), end(),
205 DC
->getPrimaryContext(),
206 UnqualUsingEntry::Comparator()));
209 } // end anonymous namespace
211 // Retrieve the set of identifier namespaces that correspond to a
212 // specific kind of name lookup.
213 static inline unsigned getIDNS(Sema::LookupNameKind NameKind
,
215 bool Redeclaration
) {
218 case Sema::LookupObjCImplicitSelfParam
:
219 case Sema::LookupOrdinaryName
:
220 case Sema::LookupRedeclarationWithLinkage
:
221 case Sema::LookupLocalFriendName
:
222 case Sema::LookupDestructorName
:
223 IDNS
= Decl::IDNS_Ordinary
;
225 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Member
| Decl::IDNS_Namespace
;
227 IDNS
|= Decl::IDNS_TagFriend
| Decl::IDNS_OrdinaryFriend
;
230 IDNS
|= Decl::IDNS_LocalExtern
;
233 case Sema::LookupOperatorName
:
234 // Operator lookup is its own crazy thing; it is not the same
235 // as (e.g.) looking up an operator name for redeclaration.
236 assert(!Redeclaration
&& "cannot do redeclaration operator lookup");
237 IDNS
= Decl::IDNS_NonMemberOperator
;
240 case Sema::LookupTagName
:
242 IDNS
= Decl::IDNS_Type
;
244 // When looking for a redeclaration of a tag name, we add:
245 // 1) TagFriend to find undeclared friend decls
246 // 2) Namespace because they can't "overload" with tag decls.
247 // 3) Tag because it includes class templates, which can't
248 // "overload" with tag decls.
250 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_TagFriend
| Decl::IDNS_Namespace
;
252 IDNS
= Decl::IDNS_Tag
;
256 case Sema::LookupLabel
:
257 IDNS
= Decl::IDNS_Label
;
260 case Sema::LookupMemberName
:
261 IDNS
= Decl::IDNS_Member
;
263 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Ordinary
;
266 case Sema::LookupNestedNameSpecifierName
:
267 IDNS
= Decl::IDNS_Type
| Decl::IDNS_Namespace
;
270 case Sema::LookupNamespaceName
:
271 IDNS
= Decl::IDNS_Namespace
;
274 case Sema::LookupUsingDeclName
:
275 assert(Redeclaration
&& "should only be used for redecl lookup");
276 IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_Tag
| Decl::IDNS_Member
|
277 Decl::IDNS_Using
| Decl::IDNS_TagFriend
| Decl::IDNS_OrdinaryFriend
|
278 Decl::IDNS_LocalExtern
;
281 case Sema::LookupObjCProtocolName
:
282 IDNS
= Decl::IDNS_ObjCProtocol
;
285 case Sema::LookupOMPReductionName
:
286 IDNS
= Decl::IDNS_OMPReduction
;
289 case Sema::LookupOMPMapperName
:
290 IDNS
= Decl::IDNS_OMPMapper
;
293 case Sema::LookupAnyName
:
294 IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_Tag
| Decl::IDNS_Member
295 | Decl::IDNS_Using
| Decl::IDNS_Namespace
| Decl::IDNS_ObjCProtocol
302 void LookupResult::configure() {
303 IDNS
= getIDNS(LookupKind
, getSema().getLangOpts().CPlusPlus
,
304 isForRedeclaration());
306 // If we're looking for one of the allocation or deallocation
307 // operators, make sure that the implicitly-declared new and delete
308 // operators can be found.
309 switch (NameInfo
.getName().getCXXOverloadedOperator()) {
313 case OO_Array_Delete
:
314 getSema().DeclareGlobalNewDelete();
321 // Compiler builtins are always visible, regardless of where they end
322 // up being declared.
323 if (IdentifierInfo
*Id
= NameInfo
.getName().getAsIdentifierInfo()) {
324 if (unsigned BuiltinID
= Id
->getBuiltinID()) {
325 if (!getSema().Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
))
331 bool LookupResult::checkDebugAssumptions() const {
332 // This function is never called by NDEBUG builds.
333 assert(ResultKind
!= NotFound
|| Decls
.size() == 0);
334 assert(ResultKind
!= Found
|| Decls
.size() == 1);
335 assert(ResultKind
!= FoundOverloaded
|| Decls
.size() > 1 ||
336 (Decls
.size() == 1 &&
337 isa
<FunctionTemplateDecl
>((*begin())->getUnderlyingDecl())));
338 assert(ResultKind
!= FoundUnresolvedValue
|| checkUnresolved());
339 assert(ResultKind
!= Ambiguous
|| Decls
.size() > 1 ||
340 (Decls
.size() == 1 && (Ambiguity
== AmbiguousBaseSubobjects
||
341 Ambiguity
== AmbiguousBaseSubobjectTypes
)));
342 assert((Paths
!= nullptr) == (ResultKind
== Ambiguous
&&
343 (Ambiguity
== AmbiguousBaseSubobjectTypes
||
344 Ambiguity
== AmbiguousBaseSubobjects
)));
348 // Necessary because CXXBasePaths is not complete in Sema.h
349 void LookupResult::deletePaths(CXXBasePaths
*Paths
) {
353 /// Get a representative context for a declaration such that two declarations
354 /// will have the same context if they were found within the same scope.
355 static const DeclContext
*getContextForScopeMatching(const Decl
*D
) {
356 // For function-local declarations, use that function as the context. This
357 // doesn't account for scopes within the function; the caller must deal with
359 if (const DeclContext
*DC
= D
->getLexicalDeclContext();
360 DC
->isFunctionOrMethod())
363 // Otherwise, look at the semantic context of the declaration. The
364 // declaration must have been found there.
365 return D
->getDeclContext()->getRedeclContext();
368 /// Determine whether \p D is a better lookup result than \p Existing,
369 /// given that they declare the same entity.
370 static bool isPreferredLookupResult(Sema
&S
, Sema::LookupNameKind Kind
,
372 const NamedDecl
*Existing
) {
373 // When looking up redeclarations of a using declaration, prefer a using
374 // shadow declaration over any other declaration of the same entity.
375 if (Kind
== Sema::LookupUsingDeclName
&& isa
<UsingShadowDecl
>(D
) &&
376 !isa
<UsingShadowDecl
>(Existing
))
379 const auto *DUnderlying
= D
->getUnderlyingDecl();
380 const auto *EUnderlying
= Existing
->getUnderlyingDecl();
382 // If they have different underlying declarations, prefer a typedef over the
383 // original type (this happens when two type declarations denote the same
384 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
385 // might carry additional semantic information, such as an alignment override.
386 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
387 // declaration over a typedef. Also prefer a tag over a typedef for
388 // destructor name lookup because in some contexts we only accept a
389 // class-name in a destructor declaration.
390 if (DUnderlying
->getCanonicalDecl() != EUnderlying
->getCanonicalDecl()) {
391 assert(isa
<TypeDecl
>(DUnderlying
) && isa
<TypeDecl
>(EUnderlying
));
392 bool HaveTag
= isa
<TagDecl
>(EUnderlying
);
394 Kind
== Sema::LookupTagName
|| Kind
== Sema::LookupDestructorName
;
395 return HaveTag
!= WantTag
;
398 // Pick the function with more default arguments.
399 // FIXME: In the presence of ambiguous default arguments, we should keep both,
400 // so we can diagnose the ambiguity if the default argument is needed.
401 // See C++ [over.match.best]p3.
402 if (const auto *DFD
= dyn_cast
<FunctionDecl
>(DUnderlying
)) {
403 const auto *EFD
= cast
<FunctionDecl
>(EUnderlying
);
404 unsigned DMin
= DFD
->getMinRequiredArguments();
405 unsigned EMin
= EFD
->getMinRequiredArguments();
406 // If D has more default arguments, it is preferred.
409 // FIXME: When we track visibility for default function arguments, check
410 // that we pick the declaration with more visible default arguments.
413 // Pick the template with more default template arguments.
414 if (const auto *DTD
= dyn_cast
<TemplateDecl
>(DUnderlying
)) {
415 const auto *ETD
= cast
<TemplateDecl
>(EUnderlying
);
416 unsigned DMin
= DTD
->getTemplateParameters()->getMinRequiredArguments();
417 unsigned EMin
= ETD
->getTemplateParameters()->getMinRequiredArguments();
418 // If D has more default arguments, it is preferred. Note that default
419 // arguments (and their visibility) is monotonically increasing across the
420 // redeclaration chain, so this is a quick proxy for "is more recent".
423 // If D has more *visible* default arguments, it is preferred. Note, an
424 // earlier default argument being visible does not imply that a later
425 // default argument is visible, so we can't just check the first one.
426 for (unsigned I
= DMin
, N
= DTD
->getTemplateParameters()->size();
428 if (!S
.hasVisibleDefaultArgument(
429 ETD
->getTemplateParameters()->getParam(I
)) &&
430 S
.hasVisibleDefaultArgument(
431 DTD
->getTemplateParameters()->getParam(I
)))
436 // VarDecl can have incomplete array types, prefer the one with more complete
438 if (const auto *DVD
= dyn_cast
<VarDecl
>(DUnderlying
)) {
439 const auto *EVD
= cast
<VarDecl
>(EUnderlying
);
440 if (EVD
->getType()->isIncompleteType() &&
441 !DVD
->getType()->isIncompleteType()) {
442 // Prefer the decl with a more complete type if visible.
443 return S
.isVisible(DVD
);
445 return false; // Avoid picking up a newer decl, just because it was newer.
448 // For most kinds of declaration, it doesn't really matter which one we pick.
449 if (!isa
<FunctionDecl
>(DUnderlying
) && !isa
<VarDecl
>(DUnderlying
)) {
450 // If the existing declaration is hidden, prefer the new one. Otherwise,
451 // keep what we've got.
452 return !S
.isVisible(Existing
);
455 // Pick the newer declaration; it might have a more precise type.
456 for (const Decl
*Prev
= DUnderlying
->getPreviousDecl(); Prev
;
457 Prev
= Prev
->getPreviousDecl())
458 if (Prev
== EUnderlying
)
463 /// Determine whether \p D can hide a tag declaration.
464 static bool canHideTag(const NamedDecl
*D
) {
465 // C++ [basic.scope.declarative]p4:
466 // Given a set of declarations in a single declarative region [...]
467 // exactly one declaration shall declare a class name or enumeration name
468 // that is not a typedef name and the other declarations shall all refer to
469 // the same variable, non-static data member, or enumerator, or all refer
470 // to functions and function templates; in this case the class name or
471 // enumeration name is hidden.
472 // C++ [basic.scope.hiding]p2:
473 // A class name or enumeration name can be hidden by the name of a
474 // variable, data member, function, or enumerator declared in the same
476 // An UnresolvedUsingValueDecl always instantiates to one of these.
477 D
= D
->getUnderlyingDecl();
478 return isa
<VarDecl
>(D
) || isa
<EnumConstantDecl
>(D
) || isa
<FunctionDecl
>(D
) ||
479 isa
<FunctionTemplateDecl
>(D
) || isa
<FieldDecl
>(D
) ||
480 isa
<UnresolvedUsingValueDecl
>(D
);
483 /// Resolves the result kind of this lookup.
484 void LookupResult::resolveKind() {
485 unsigned N
= Decls
.size();
487 // Fast case: no possible ambiguity.
489 assert(ResultKind
== NotFound
||
490 ResultKind
== NotFoundInCurrentInstantiation
);
494 // If there's a single decl, we need to examine it to decide what
495 // kind of lookup this is.
497 const NamedDecl
*D
= (*Decls
.begin())->getUnderlyingDecl();
498 if (isa
<FunctionTemplateDecl
>(D
))
499 ResultKind
= FoundOverloaded
;
500 else if (isa
<UnresolvedUsingValueDecl
>(D
))
501 ResultKind
= FoundUnresolvedValue
;
505 // Don't do any extra resolution if we've already resolved as ambiguous.
506 if (ResultKind
== Ambiguous
) return;
508 llvm::SmallDenseMap
<const NamedDecl
*, unsigned, 16> Unique
;
509 llvm::SmallDenseMap
<QualType
, unsigned, 16> UniqueTypes
;
511 bool Ambiguous
= false;
512 bool ReferenceToPlaceHolderVariable
= false;
513 bool HasTag
= false, HasFunction
= false;
514 bool HasFunctionTemplate
= false, HasUnresolved
= false;
515 const NamedDecl
*HasNonFunction
= nullptr;
517 llvm::SmallVector
<const NamedDecl
*, 4> EquivalentNonFunctions
;
518 llvm::BitVector
RemovedDecls(N
);
520 for (unsigned I
= 0; I
< N
; I
++) {
521 const NamedDecl
*D
= Decls
[I
]->getUnderlyingDecl();
522 D
= cast
<NamedDecl
>(D
->getCanonicalDecl());
524 // Ignore an invalid declaration unless it's the only one left.
525 // Also ignore HLSLBufferDecl which not have name conflict with other Decls.
526 if ((D
->isInvalidDecl() || isa
<HLSLBufferDecl
>(D
)) &&
527 N
- RemovedDecls
.count() > 1) {
532 // C++ [basic.scope.hiding]p2:
533 // A class name or enumeration name can be hidden by the name of
534 // an object, function, or enumerator declared in the same
535 // scope. If a class or enumeration name and an object, function,
536 // or enumerator are declared in the same scope (in any order)
537 // with the same name, the class or enumeration name is hidden
538 // wherever the object, function, or enumerator name is visible.
539 if (HideTags
&& isa
<TagDecl
>(D
)) {
541 for (auto *OtherDecl
: Decls
) {
542 if (canHideTag(OtherDecl
) && !OtherDecl
->isInvalidDecl() &&
543 getContextForScopeMatching(OtherDecl
)->Equals(
544 getContextForScopeMatching(Decls
[I
]))) {
554 std::optional
<unsigned> ExistingI
;
556 // Redeclarations of types via typedef can occur both within a scope
557 // and, through using declarations and directives, across scopes. There is
558 // no ambiguity if they all refer to the same type, so unique based on the
560 if (const auto *TD
= dyn_cast
<TypeDecl
>(D
)) {
561 QualType T
= getSema().Context
.getTypeDeclType(TD
);
562 auto UniqueResult
= UniqueTypes
.insert(
563 std::make_pair(getSema().Context
.getCanonicalType(T
), I
));
564 if (!UniqueResult
.second
) {
565 // The type is not unique.
566 ExistingI
= UniqueResult
.first
->second
;
570 // For non-type declarations, check for a prior lookup result naming this
571 // canonical declaration.
573 auto UniqueResult
= Unique
.insert(std::make_pair(D
, I
));
574 if (!UniqueResult
.second
) {
575 // We've seen this entity before.
576 ExistingI
= UniqueResult
.first
->second
;
581 // This is not a unique lookup result. Pick one of the results and
582 // discard the other.
583 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls
[I
],
585 Decls
[*ExistingI
] = Decls
[I
];
590 // Otherwise, do some decl type analysis and then continue.
592 if (isa
<UnresolvedUsingValueDecl
>(D
)) {
593 HasUnresolved
= true;
594 } else if (isa
<TagDecl
>(D
)) {
598 } else if (isa
<FunctionTemplateDecl
>(D
)) {
600 HasFunctionTemplate
= true;
601 } else if (isa
<FunctionDecl
>(D
)) {
604 if (HasNonFunction
) {
605 // If we're about to create an ambiguity between two declarations that
606 // are equivalent, but one is an internal linkage declaration from one
607 // module and the other is an internal linkage declaration from another
608 // module, just skip it.
609 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction
,
611 EquivalentNonFunctions
.push_back(D
);
615 if (D
->isPlaceholderVar(getSema().getLangOpts()) &&
616 getContextForScopeMatching(D
) ==
617 getContextForScopeMatching(Decls
[I
])) {
618 ReferenceToPlaceHolderVariable
= true;
626 // FIXME: This diagnostic should really be delayed until we're done with
627 // the lookup result, in case the ambiguity is resolved by the caller.
628 if (!EquivalentNonFunctions
.empty() && !Ambiguous
)
629 getSema().diagnoseEquivalentInternalLinkageDeclarations(
630 getNameLoc(), HasNonFunction
, EquivalentNonFunctions
);
632 // Remove decls by replacing them with decls from the end (which
633 // means that we need to iterate from the end) and then truncating
635 for (int I
= RemovedDecls
.find_last(); I
>= 0; I
= RemovedDecls
.find_prev(I
))
636 Decls
[I
] = Decls
[--N
];
639 if ((HasNonFunction
&& (HasFunction
|| HasUnresolved
)) ||
640 (HideTags
&& HasTag
&& (HasFunction
|| HasNonFunction
|| HasUnresolved
)))
643 if (Ambiguous
&& ReferenceToPlaceHolderVariable
)
644 setAmbiguous(LookupResult::AmbiguousReferenceToPlaceholderVariable
);
646 setAmbiguous(LookupResult::AmbiguousReference
);
647 else if (HasUnresolved
)
648 ResultKind
= LookupResult::FoundUnresolvedValue
;
649 else if (N
> 1 || HasFunctionTemplate
)
650 ResultKind
= LookupResult::FoundOverloaded
;
652 ResultKind
= LookupResult::Found
;
655 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths
&P
) {
656 CXXBasePaths::const_paths_iterator I
, E
;
657 for (I
= P
.begin(), E
= P
.end(); I
!= E
; ++I
)
658 for (DeclContext::lookup_iterator DI
= I
->Decls
, DE
= DI
.end(); DI
!= DE
;
663 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths
&P
) {
664 Paths
= new CXXBasePaths
;
666 addDeclsFromBasePaths(*Paths
);
668 setAmbiguous(AmbiguousBaseSubobjects
);
671 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths
&P
) {
672 Paths
= new CXXBasePaths
;
674 addDeclsFromBasePaths(*Paths
);
676 setAmbiguous(AmbiguousBaseSubobjectTypes
);
679 void LookupResult::print(raw_ostream
&Out
) {
680 Out
<< Decls
.size() << " result(s)";
681 if (isAmbiguous()) Out
<< ", ambiguous";
682 if (Paths
) Out
<< ", base paths present";
684 for (iterator I
= begin(), E
= end(); I
!= E
; ++I
) {
690 LLVM_DUMP_METHOD
void LookupResult::dump() {
691 llvm::errs() << "lookup results for " << getLookupName().getAsString()
693 for (NamedDecl
*D
: *this)
697 /// Diagnose a missing builtin type.
698 static QualType
diagOpenCLBuiltinTypeError(Sema
&S
, llvm::StringRef TypeClass
,
699 llvm::StringRef Name
) {
700 S
.Diag(SourceLocation(), diag::err_opencl_type_not_found
)
701 << TypeClass
<< Name
;
702 return S
.Context
.VoidTy
;
705 /// Lookup an OpenCL enum type.
706 static QualType
getOpenCLEnumType(Sema
&S
, llvm::StringRef Name
) {
707 LookupResult
Result(S
, &S
.Context
.Idents
.get(Name
), SourceLocation(),
708 Sema::LookupTagName
);
709 S
.LookupName(Result
, S
.TUScope
);
711 return diagOpenCLBuiltinTypeError(S
, "enum", Name
);
712 EnumDecl
*Decl
= Result
.getAsSingle
<EnumDecl
>();
714 return diagOpenCLBuiltinTypeError(S
, "enum", Name
);
715 return S
.Context
.getEnumType(Decl
);
718 /// Lookup an OpenCL typedef type.
719 static QualType
getOpenCLTypedefType(Sema
&S
, llvm::StringRef Name
) {
720 LookupResult
Result(S
, &S
.Context
.Idents
.get(Name
), SourceLocation(),
721 Sema::LookupOrdinaryName
);
722 S
.LookupName(Result
, S
.TUScope
);
724 return diagOpenCLBuiltinTypeError(S
, "typedef", Name
);
725 TypedefNameDecl
*Decl
= Result
.getAsSingle
<TypedefNameDecl
>();
727 return diagOpenCLBuiltinTypeError(S
, "typedef", Name
);
728 return S
.Context
.getTypedefType(Decl
);
731 /// Get the QualType instances of the return type and arguments for an OpenCL
732 /// builtin function signature.
733 /// \param S (in) The Sema instance.
734 /// \param OpenCLBuiltin (in) The signature currently handled.
735 /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
736 /// type used as return type or as argument.
737 /// Only meaningful for generic types, otherwise equals 1.
738 /// \param RetTypes (out) List of the possible return types.
739 /// \param ArgTypes (out) List of the possible argument types. For each
740 /// argument, ArgTypes contains QualTypes for the Cartesian product
741 /// of (vector sizes) x (types) .
742 static void GetQualTypesForOpenCLBuiltin(
743 Sema
&S
, const OpenCLBuiltinStruct
&OpenCLBuiltin
, unsigned &GenTypeMaxCnt
,
744 SmallVector
<QualType
, 1> &RetTypes
,
745 SmallVector
<SmallVector
<QualType
, 1>, 5> &ArgTypes
) {
746 // Get the QualType instances of the return types.
747 unsigned Sig
= SignatureTable
[OpenCLBuiltin
.SigTableIndex
];
748 OCL2Qual(S
, TypeTable
[Sig
], RetTypes
);
749 GenTypeMaxCnt
= RetTypes
.size();
751 // Get the QualType instances of the arguments.
752 // First type is the return type, skip it.
753 for (unsigned Index
= 1; Index
< OpenCLBuiltin
.NumTypes
; Index
++) {
754 SmallVector
<QualType
, 1> Ty
;
755 OCL2Qual(S
, TypeTable
[SignatureTable
[OpenCLBuiltin
.SigTableIndex
+ Index
]],
757 GenTypeMaxCnt
= (Ty
.size() > GenTypeMaxCnt
) ? Ty
.size() : GenTypeMaxCnt
;
758 ArgTypes
.push_back(std::move(Ty
));
762 /// Create a list of the candidate function overloads for an OpenCL builtin
764 /// \param Context (in) The ASTContext instance.
765 /// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic
766 /// type used as return type or as argument.
767 /// Only meaningful for generic types, otherwise equals 1.
768 /// \param FunctionList (out) List of FunctionTypes.
769 /// \param RetTypes (in) List of the possible return types.
770 /// \param ArgTypes (in) List of the possible types for the arguments.
771 static void GetOpenCLBuiltinFctOverloads(
772 ASTContext
&Context
, unsigned GenTypeMaxCnt
,
773 std::vector
<QualType
> &FunctionList
, SmallVector
<QualType
, 1> &RetTypes
,
774 SmallVector
<SmallVector
<QualType
, 1>, 5> &ArgTypes
) {
775 FunctionProtoType::ExtProtoInfo
PI(
776 Context
.getDefaultCallingConvention(false, false, true));
779 // Do not attempt to create any FunctionTypes if there are no return types,
780 // which happens when a type belongs to a disabled extension.
781 if (RetTypes
.size() == 0)
784 // Create FunctionTypes for each (gen)type.
785 for (unsigned IGenType
= 0; IGenType
< GenTypeMaxCnt
; IGenType
++) {
786 SmallVector
<QualType
, 5> ArgList
;
788 for (unsigned A
= 0; A
< ArgTypes
.size(); A
++) {
789 // Bail out if there is an argument that has no available types.
790 if (ArgTypes
[A
].size() == 0)
793 // Builtins such as "max" have an "sgentype" argument that represents
794 // the corresponding scalar type of a gentype. The number of gentypes
795 // must be a multiple of the number of sgentypes.
796 assert(GenTypeMaxCnt
% ArgTypes
[A
].size() == 0 &&
797 "argument type count not compatible with gentype type count");
798 unsigned Idx
= IGenType
% ArgTypes
[A
].size();
799 ArgList
.push_back(ArgTypes
[A
][Idx
]);
802 FunctionList
.push_back(Context
.getFunctionType(
803 RetTypes
[(RetTypes
.size() != 1) ? IGenType
: 0], ArgList
, PI
));
807 /// When trying to resolve a function name, if isOpenCLBuiltin() returns a
808 /// non-null <Index, Len> pair, then the name is referencing an OpenCL
809 /// builtin function. Add all candidate signatures to the LookUpResult.
811 /// \param S (in) The Sema instance.
812 /// \param LR (inout) The LookupResult instance.
813 /// \param II (in) The identifier being resolved.
814 /// \param FctIndex (in) Starting index in the BuiltinTable.
815 /// \param Len (in) The signature list has Len elements.
816 static void InsertOCLBuiltinDeclarationsFromTable(Sema
&S
, LookupResult
&LR
,
818 const unsigned FctIndex
,
819 const unsigned Len
) {
820 // The builtin function declaration uses generic types (gentype).
821 bool HasGenType
= false;
823 // Maximum number of types contained in a generic type used as return type or
824 // as argument. Only meaningful for generic types, otherwise equals 1.
825 unsigned GenTypeMaxCnt
;
827 ASTContext
&Context
= S
.Context
;
829 for (unsigned SignatureIndex
= 0; SignatureIndex
< Len
; SignatureIndex
++) {
830 const OpenCLBuiltinStruct
&OpenCLBuiltin
=
831 BuiltinTable
[FctIndex
+ SignatureIndex
];
833 // Ignore this builtin function if it is not available in the currently
834 // selected language version.
835 if (!isOpenCLVersionContainedInMask(Context
.getLangOpts(),
836 OpenCLBuiltin
.Versions
))
839 // Ignore this builtin function if it carries an extension macro that is
840 // not defined. This indicates that the extension is not supported by the
841 // target, so the builtin function should not be available.
842 StringRef Extensions
= FunctionExtensionTable
[OpenCLBuiltin
.Extension
];
843 if (!Extensions
.empty()) {
844 SmallVector
<StringRef
, 2> ExtVec
;
845 Extensions
.split(ExtVec
, " ");
846 bool AllExtensionsDefined
= true;
847 for (StringRef Ext
: ExtVec
) {
848 if (!S
.getPreprocessor().isMacroDefined(Ext
)) {
849 AllExtensionsDefined
= false;
853 if (!AllExtensionsDefined
)
857 SmallVector
<QualType
, 1> RetTypes
;
858 SmallVector
<SmallVector
<QualType
, 1>, 5> ArgTypes
;
860 // Obtain QualType lists for the function signature.
861 GetQualTypesForOpenCLBuiltin(S
, OpenCLBuiltin
, GenTypeMaxCnt
, RetTypes
,
863 if (GenTypeMaxCnt
> 1) {
867 // Create function overload for each type combination.
868 std::vector
<QualType
> FunctionList
;
869 GetOpenCLBuiltinFctOverloads(Context
, GenTypeMaxCnt
, FunctionList
, RetTypes
,
872 SourceLocation Loc
= LR
.getNameLoc();
873 DeclContext
*Parent
= Context
.getTranslationUnitDecl();
874 FunctionDecl
*NewOpenCLBuiltin
;
876 for (const auto &FTy
: FunctionList
) {
877 NewOpenCLBuiltin
= FunctionDecl::Create(
878 Context
, Parent
, Loc
, Loc
, II
, FTy
, /*TInfo=*/nullptr, SC_Extern
,
879 S
.getCurFPFeatures().isFPConstrained(), false,
880 FTy
->isFunctionProtoType());
881 NewOpenCLBuiltin
->setImplicit();
883 // Create Decl objects for each parameter, adding them to the
885 const auto *FP
= cast
<FunctionProtoType
>(FTy
);
886 SmallVector
<ParmVarDecl
*, 4> ParmList
;
887 for (unsigned IParm
= 0, e
= FP
->getNumParams(); IParm
!= e
; ++IParm
) {
888 ParmVarDecl
*Parm
= ParmVarDecl::Create(
889 Context
, NewOpenCLBuiltin
, SourceLocation(), SourceLocation(),
890 nullptr, FP
->getParamType(IParm
), nullptr, SC_None
, nullptr);
891 Parm
->setScopeInfo(0, IParm
);
892 ParmList
.push_back(Parm
);
894 NewOpenCLBuiltin
->setParams(ParmList
);
896 // Add function attributes.
897 if (OpenCLBuiltin
.IsPure
)
898 NewOpenCLBuiltin
->addAttr(PureAttr::CreateImplicit(Context
));
899 if (OpenCLBuiltin
.IsConst
)
900 NewOpenCLBuiltin
->addAttr(ConstAttr::CreateImplicit(Context
));
901 if (OpenCLBuiltin
.IsConv
)
902 NewOpenCLBuiltin
->addAttr(ConvergentAttr::CreateImplicit(Context
));
904 if (!S
.getLangOpts().OpenCLCPlusPlus
)
905 NewOpenCLBuiltin
->addAttr(OverloadableAttr::CreateImplicit(Context
));
907 LR
.addDecl(NewOpenCLBuiltin
);
911 // If we added overloads, need to resolve the lookup result.
912 if (Len
> 1 || HasGenType
)
916 bool Sema::LookupBuiltin(LookupResult
&R
) {
917 Sema::LookupNameKind NameKind
= R
.getLookupKind();
919 // If we didn't find a use of this identifier, and if the identifier
920 // corresponds to a compiler builtin, create the decl object for the builtin
921 // now, injecting it into translation unit scope, and return it.
922 if (NameKind
== Sema::LookupOrdinaryName
||
923 NameKind
== Sema::LookupRedeclarationWithLinkage
) {
924 IdentifierInfo
*II
= R
.getLookupName().getAsIdentifierInfo();
926 if (getLangOpts().CPlusPlus
&& NameKind
== Sema::LookupOrdinaryName
) {
927 if (II
== getASTContext().getMakeIntegerSeqName()) {
928 R
.addDecl(getASTContext().getMakeIntegerSeqDecl());
931 if (II
== getASTContext().getTypePackElementName()) {
932 R
.addDecl(getASTContext().getTypePackElementDecl());
935 if (II
== getASTContext().getBuiltinCommonTypeName()) {
936 R
.addDecl(getASTContext().getBuiltinCommonTypeDecl());
941 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
942 if (getLangOpts().OpenCL
&& getLangOpts().DeclareOpenCLBuiltins
) {
943 auto Index
= isOpenCLBuiltin(II
->getName());
945 InsertOCLBuiltinDeclarationsFromTable(*this, R
, II
, Index
.first
- 1,
951 if (RISCV().DeclareRVVBuiltins
|| RISCV().DeclareSiFiveVectorBuiltins
) {
952 if (!RISCV().IntrinsicManager
)
953 RISCV().IntrinsicManager
= CreateRISCVIntrinsicManager(*this);
955 RISCV().IntrinsicManager
->InitIntrinsicList();
957 if (RISCV().IntrinsicManager
->CreateIntrinsicIfFound(R
, II
, PP
))
961 // If this is a builtin on this (or all) targets, create the decl.
962 if (unsigned BuiltinID
= II
->getBuiltinID()) {
963 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
964 // library functions like 'malloc'. Instead, we'll just error.
965 if ((getLangOpts().CPlusPlus
|| getLangOpts().OpenCL
) &&
966 Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
))
970 LazilyCreateBuiltin(II
, BuiltinID
, TUScope
,
971 R
.isForRedeclaration(), R
.getNameLoc())) {
982 /// Looks up the declaration of "struct objc_super" and
983 /// saves it for later use in building builtin declaration of
984 /// objc_msgSendSuper and objc_msgSendSuper_stret.
985 static void LookupPredefedObjCSuperType(Sema
&Sema
, Scope
*S
) {
986 ASTContext
&Context
= Sema
.Context
;
987 LookupResult
Result(Sema
, &Context
.Idents
.get("objc_super"), SourceLocation(),
988 Sema::LookupTagName
);
989 Sema
.LookupName(Result
, S
);
990 if (Result
.getResultKind() == LookupResult::Found
)
991 if (const TagDecl
*TD
= Result
.getAsSingle
<TagDecl
>())
992 Context
.setObjCSuperType(Context
.getTagDeclType(TD
));
995 void Sema::LookupNecessaryTypesForBuiltin(Scope
*S
, unsigned ID
) {
996 if (ID
== Builtin::BIobjc_msgSendSuper
)
997 LookupPredefedObjCSuperType(*this, S
);
1000 /// Determine whether we can declare a special member function within
1001 /// the class at this point.
1002 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl
*Class
) {
1003 // We need to have a definition for the class.
1004 if (!Class
->getDefinition() || Class
->isDependentContext())
1007 // We can't be in the middle of defining the class.
1008 return !Class
->isBeingDefined();
1011 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl
*Class
) {
1012 if (!CanDeclareSpecialMemberFunction(Class
))
1015 // If the default constructor has not yet been declared, do so now.
1016 if (Class
->needsImplicitDefaultConstructor())
1017 DeclareImplicitDefaultConstructor(Class
);
1019 // If the copy constructor has not yet been declared, do so now.
1020 if (Class
->needsImplicitCopyConstructor())
1021 DeclareImplicitCopyConstructor(Class
);
1023 // If the copy assignment operator has not yet been declared, do so now.
1024 if (Class
->needsImplicitCopyAssignment())
1025 DeclareImplicitCopyAssignment(Class
);
1027 if (getLangOpts().CPlusPlus11
) {
1028 // If the move constructor has not yet been declared, do so now.
1029 if (Class
->needsImplicitMoveConstructor())
1030 DeclareImplicitMoveConstructor(Class
);
1032 // If the move assignment operator has not yet been declared, do so now.
1033 if (Class
->needsImplicitMoveAssignment())
1034 DeclareImplicitMoveAssignment(Class
);
1037 // If the destructor has not yet been declared, do so now.
1038 if (Class
->needsImplicitDestructor())
1039 DeclareImplicitDestructor(Class
);
1042 /// Determine whether this is the name of an implicitly-declared
1043 /// special member function.
1044 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name
) {
1045 switch (Name
.getNameKind()) {
1046 case DeclarationName::CXXConstructorName
:
1047 case DeclarationName::CXXDestructorName
:
1050 case DeclarationName::CXXOperatorName
:
1051 return Name
.getCXXOverloadedOperator() == OO_Equal
;
1060 /// If there are any implicit member functions with the given name
1061 /// that need to be declared in the given declaration context, do so.
1062 static void DeclareImplicitMemberFunctionsWithName(Sema
&S
,
1063 DeclarationName Name
,
1065 const DeclContext
*DC
) {
1069 switch (Name
.getNameKind()) {
1070 case DeclarationName::CXXConstructorName
:
1071 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
))
1072 if (Record
->getDefinition() && CanDeclareSpecialMemberFunction(Record
)) {
1073 CXXRecordDecl
*Class
= const_cast<CXXRecordDecl
*>(Record
);
1074 if (Record
->needsImplicitDefaultConstructor())
1075 S
.DeclareImplicitDefaultConstructor(Class
);
1076 if (Record
->needsImplicitCopyConstructor())
1077 S
.DeclareImplicitCopyConstructor(Class
);
1078 if (S
.getLangOpts().CPlusPlus11
&&
1079 Record
->needsImplicitMoveConstructor())
1080 S
.DeclareImplicitMoveConstructor(Class
);
1084 case DeclarationName::CXXDestructorName
:
1085 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
))
1086 if (Record
->getDefinition() && Record
->needsImplicitDestructor() &&
1087 CanDeclareSpecialMemberFunction(Record
))
1088 S
.DeclareImplicitDestructor(const_cast<CXXRecordDecl
*>(Record
));
1091 case DeclarationName::CXXOperatorName
:
1092 if (Name
.getCXXOverloadedOperator() != OO_Equal
)
1095 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
)) {
1096 if (Record
->getDefinition() && CanDeclareSpecialMemberFunction(Record
)) {
1097 CXXRecordDecl
*Class
= const_cast<CXXRecordDecl
*>(Record
);
1098 if (Record
->needsImplicitCopyAssignment())
1099 S
.DeclareImplicitCopyAssignment(Class
);
1100 if (S
.getLangOpts().CPlusPlus11
&&
1101 Record
->needsImplicitMoveAssignment())
1102 S
.DeclareImplicitMoveAssignment(Class
);
1107 case DeclarationName::CXXDeductionGuideName
:
1108 S
.DeclareImplicitDeductionGuides(Name
.getCXXDeductionGuideTemplate(), Loc
);
1116 // Adds all qualifying matches for a name within a decl context to the
1117 // given lookup result. Returns true if any matches were found.
1118 static bool LookupDirect(Sema
&S
, LookupResult
&R
, const DeclContext
*DC
) {
1121 // Lazily declare C++ special member functions.
1122 if (S
.getLangOpts().CPlusPlus
)
1123 DeclareImplicitMemberFunctionsWithName(S
, R
.getLookupName(), R
.getNameLoc(),
1126 // Perform lookup into this declaration context.
1127 DeclContext::lookup_result DR
= DC
->lookup(R
.getLookupName());
1128 for (NamedDecl
*D
: DR
) {
1129 if ((D
= R
.getAcceptableDecl(D
))) {
1135 if (!Found
&& DC
->isTranslationUnit() && S
.LookupBuiltin(R
))
1138 if (R
.getLookupName().getNameKind()
1139 != DeclarationName::CXXConversionFunctionName
||
1140 R
.getLookupName().getCXXNameType()->isDependentType() ||
1141 !isa
<CXXRecordDecl
>(DC
))
1144 // C++ [temp.mem]p6:
1145 // A specialization of a conversion function template is not found by
1146 // name lookup. Instead, any conversion function templates visible in the
1147 // context of the use are considered. [...]
1148 const CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DC
);
1149 if (!Record
->isCompleteDefinition())
1152 // For conversion operators, 'operator auto' should only match
1153 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
1154 // as a candidate for template substitution.
1155 auto *ContainedDeducedType
=
1156 R
.getLookupName().getCXXNameType()->getContainedDeducedType();
1157 if (R
.getLookupName().getNameKind() ==
1158 DeclarationName::CXXConversionFunctionName
&&
1159 ContainedDeducedType
&& ContainedDeducedType
->isUndeducedType())
1162 for (CXXRecordDecl::conversion_iterator U
= Record
->conversion_begin(),
1163 UEnd
= Record
->conversion_end(); U
!= UEnd
; ++U
) {
1164 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(*U
);
1168 // When we're performing lookup for the purposes of redeclaration, just
1169 // add the conversion function template. When we deduce template
1170 // arguments for specializations, we'll end up unifying the return
1171 // type of the new declaration with the type of the function template.
1172 if (R
.isForRedeclaration()) {
1173 R
.addDecl(ConvTemplate
);
1178 // C++ [temp.mem]p6:
1179 // [...] For each such operator, if argument deduction succeeds
1180 // (14.9.2.3), the resulting specialization is used as if found by
1183 // When referencing a conversion function for any purpose other than
1184 // a redeclaration (such that we'll be building an expression with the
1185 // result), perform template argument deduction and place the
1186 // specialization into the result set. We do this to avoid forcing all
1187 // callers to perform special deduction for conversion functions.
1188 TemplateDeductionInfo
Info(R
.getNameLoc());
1189 FunctionDecl
*Specialization
= nullptr;
1191 const FunctionProtoType
*ConvProto
1192 = ConvTemplate
->getTemplatedDecl()->getType()->getAs
<FunctionProtoType
>();
1193 assert(ConvProto
&& "Nonsensical conversion function template type");
1195 // Compute the type of the function that we would expect the conversion
1196 // function to have, if it were to match the name given.
1197 // FIXME: Calling convention!
1198 FunctionProtoType::ExtProtoInfo EPI
= ConvProto
->getExtProtoInfo();
1199 EPI
.ExtInfo
= EPI
.ExtInfo
.withCallingConv(CC_C
);
1200 EPI
.ExceptionSpec
= EST_None
;
1201 QualType ExpectedType
= R
.getSema().Context
.getFunctionType(
1202 R
.getLookupName().getCXXNameType(), {}, EPI
);
1204 // Perform template argument deduction against the type that we would
1205 // expect the function to have.
1206 if (R
.getSema().DeduceTemplateArguments(ConvTemplate
, nullptr, ExpectedType
,
1207 Specialization
, Info
) ==
1208 TemplateDeductionResult::Success
) {
1209 R
.addDecl(Specialization
);
1217 // Performs C++ unqualified lookup into the given file context.
1218 static bool CppNamespaceLookup(Sema
&S
, LookupResult
&R
, ASTContext
&Context
,
1219 const DeclContext
*NS
,
1220 UnqualUsingDirectiveSet
&UDirs
) {
1222 assert(NS
&& NS
->isFileContext() && "CppNamespaceLookup() requires namespace!");
1224 // Perform direct name lookup into the LookupCtx.
1225 bool Found
= LookupDirect(S
, R
, NS
);
1227 // Perform direct name lookup into the namespaces nominated by the
1228 // using directives whose common ancestor is this namespace.
1229 for (const UnqualUsingEntry
&UUE
: UDirs
.getNamespacesFor(NS
))
1230 if (LookupDirect(S
, R
, UUE
.getNominatedNamespace()))
1238 static bool isNamespaceOrTranslationUnitScope(Scope
*S
) {
1239 if (DeclContext
*Ctx
= S
->getEntity())
1240 return Ctx
->isFileContext();
1244 /// Find the outer declaration context from this scope. This indicates the
1245 /// context that we should search up to (exclusive) before considering the
1246 /// parent of the specified scope.
1247 static DeclContext
*findOuterContext(Scope
*S
) {
1248 for (Scope
*OuterS
= S
->getParent(); OuterS
; OuterS
= OuterS
->getParent())
1249 if (DeclContext
*DC
= OuterS
->getLookupEntity())
1255 /// An RAII object to specify that we want to find block scope extern
1257 struct FindLocalExternScope
{
1258 FindLocalExternScope(LookupResult
&R
)
1259 : R(R
), OldFindLocalExtern(R
.getIdentifierNamespace() &
1260 Decl::IDNS_LocalExtern
) {
1261 R
.setFindLocalExtern(R
.getIdentifierNamespace() &
1262 (Decl::IDNS_Ordinary
| Decl::IDNS_NonMemberOperator
));
1265 R
.setFindLocalExtern(OldFindLocalExtern
);
1267 ~FindLocalExternScope() {
1271 bool OldFindLocalExtern
;
1273 } // end anonymous namespace
1275 bool Sema::CppLookupName(LookupResult
&R
, Scope
*S
) {
1276 assert(getLangOpts().CPlusPlus
&& "Can perform only C++ lookup");
1278 DeclarationName Name
= R
.getLookupName();
1279 Sema::LookupNameKind NameKind
= R
.getLookupKind();
1281 // If this is the name of an implicitly-declared special member function,
1282 // go through the scope stack to implicitly declare
1283 if (isImplicitlyDeclaredMemberFunctionName(Name
)) {
1284 for (Scope
*PreS
= S
; PreS
; PreS
= PreS
->getParent())
1285 if (DeclContext
*DC
= PreS
->getEntity())
1286 DeclareImplicitMemberFunctionsWithName(*this, Name
, R
.getNameLoc(), DC
);
1289 // C++23 [temp.dep.general]p2:
1290 // The component name of an unqualified-id is dependent if
1291 // - it is a conversion-function-id whose conversion-type-id
1293 // - it is operator= and the current class is a templated entity, or
1294 // - the unqualified-id is the postfix-expression in a dependent call.
1295 if (Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
&&
1296 Name
.getCXXNameType()->isDependentType()) {
1297 R
.setNotFoundInCurrentInstantiation();
1301 // Implicitly declare member functions with the name we're looking for, if in
1302 // fact we are in a scope where it matters.
1305 IdentifierResolver::iterator
1306 I
= IdResolver
.begin(Name
),
1307 IEnd
= IdResolver
.end();
1309 // First we lookup local scope.
1310 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1311 // ...During unqualified name lookup (3.4.1), the names appear as if
1312 // they were declared in the nearest enclosing namespace which contains
1313 // both the using-directive and the nominated namespace.
1314 // [Note: in this context, "contains" means "contains directly or
1318 // namespace A { int i; }
1322 // using namespace A;
1323 // ++i; // finds local 'i', A::i appears at global scope
1327 UnqualUsingDirectiveSet
UDirs(*this);
1328 bool VisitedUsingDirectives
= false;
1329 bool LeftStartingScope
= false;
1331 // When performing a scope lookup, we want to find local extern decls.
1332 FindLocalExternScope
FindLocals(R
);
1334 for (; S
&& !isNamespaceOrTranslationUnitScope(S
); S
= S
->getParent()) {
1335 bool SearchNamespaceScope
= true;
1336 // Check whether the IdResolver has anything in this scope.
1337 for (; I
!= IEnd
&& S
->isDeclScope(*I
); ++I
) {
1338 if (NamedDecl
*ND
= R
.getAcceptableDecl(*I
)) {
1339 if (NameKind
== LookupRedeclarationWithLinkage
&&
1340 !(*I
)->isTemplateParameter()) {
1341 // If it's a template parameter, we still find it, so we can diagnose
1342 // the invalid redeclaration.
1344 // Determine whether this (or a previous) declaration is
1346 if (!LeftStartingScope
&& !Initial
->isDeclScope(*I
))
1347 LeftStartingScope
= true;
1349 // If we found something outside of our starting scope that
1350 // does not have linkage, skip it.
1351 if (LeftStartingScope
&& !((*I
)->hasLinkage())) {
1356 // We found something in this scope, we should not look at the
1358 SearchNamespaceScope
= false;
1363 if (!SearchNamespaceScope
) {
1365 if (S
->isClassScope())
1366 if (auto *Record
= dyn_cast_if_present
<CXXRecordDecl
>(S
->getEntity()))
1367 R
.setNamingClass(Record
);
1371 if (NameKind
== LookupLocalFriendName
&& !S
->isClassScope()) {
1372 // C++11 [class.friend]p11:
1373 // If a friend declaration appears in a local class and the name
1374 // specified is an unqualified name, a prior declaration is
1375 // looked up without considering scopes that are outside the
1376 // innermost enclosing non-class scope.
1380 if (DeclContext
*Ctx
= S
->getLookupEntity()) {
1381 DeclContext
*OuterCtx
= findOuterContext(S
);
1382 for (; Ctx
&& !Ctx
->Equals(OuterCtx
); Ctx
= Ctx
->getLookupParent()) {
1383 // We do not directly look into transparent contexts, since
1384 // those entities will be found in the nearest enclosing
1385 // non-transparent context.
1386 if (Ctx
->isTransparentContext())
1389 // We do not look directly into function or method contexts,
1390 // since all of the local variables and parameters of the
1391 // function/method are present within the Scope.
1392 if (Ctx
->isFunctionOrMethod()) {
1393 // If we have an Objective-C instance method, look for ivars
1394 // in the corresponding interface.
1395 if (ObjCMethodDecl
*Method
= dyn_cast
<ObjCMethodDecl
>(Ctx
)) {
1396 if (Method
->isInstanceMethod() && Name
.getAsIdentifierInfo())
1397 if (ObjCInterfaceDecl
*Class
= Method
->getClassInterface()) {
1398 ObjCInterfaceDecl
*ClassDeclared
;
1399 if (ObjCIvarDecl
*Ivar
= Class
->lookupInstanceVariable(
1400 Name
.getAsIdentifierInfo(),
1402 if (NamedDecl
*ND
= R
.getAcceptableDecl(Ivar
)) {
1414 // If this is a file context, we need to perform unqualified name
1415 // lookup considering using directives.
1416 if (Ctx
->isFileContext()) {
1417 // If we haven't handled using directives yet, do so now.
1418 if (!VisitedUsingDirectives
) {
1419 // Add using directives from this context up to the top level.
1420 for (DeclContext
*UCtx
= Ctx
; UCtx
; UCtx
= UCtx
->getParent()) {
1421 if (UCtx
->isTransparentContext())
1424 UDirs
.visit(UCtx
, UCtx
);
1427 // Find the innermost file scope, so we can add using directives
1428 // from local scopes.
1429 Scope
*InnermostFileScope
= S
;
1430 while (InnermostFileScope
&&
1431 !isNamespaceOrTranslationUnitScope(InnermostFileScope
))
1432 InnermostFileScope
= InnermostFileScope
->getParent();
1433 UDirs
.visitScopeChain(Initial
, InnermostFileScope
);
1437 VisitedUsingDirectives
= true;
1440 if (CppNamespaceLookup(*this, R
, Context
, Ctx
, UDirs
)) {
1448 // Perform qualified name lookup into this context.
1449 // FIXME: In some cases, we know that every name that could be found by
1450 // this qualified name lookup will also be on the identifier chain. For
1451 // example, inside a class without any base classes, we never need to
1452 // perform qualified lookup because all of the members are on top of the
1453 // identifier chain.
1454 if (LookupQualifiedName(R
, Ctx
, /*InUnqualifiedLookup=*/true))
1460 // Stop if we ran out of scopes.
1461 // FIXME: This really, really shouldn't be happening.
1462 if (!S
) return false;
1464 // If we are looking for members, no need to look into global/namespace scope.
1465 if (NameKind
== LookupMemberName
)
1468 // Collect UsingDirectiveDecls in all scopes, and recursively all
1469 // nominated namespaces by those using-directives.
1471 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1472 // don't build it for each lookup!
1473 if (!VisitedUsingDirectives
) {
1474 UDirs
.visitScopeChain(Initial
, S
);
1478 // If we're not performing redeclaration lookup, do not look for local
1479 // extern declarations outside of a function scope.
1480 if (!R
.isForRedeclaration())
1481 FindLocals
.restore();
1483 // Lookup namespace scope, and global scope.
1484 // Unqualified name lookup in C++ requires looking into scopes
1485 // that aren't strictly lexical, and therefore we walk through the
1486 // context as well as walking through the scopes.
1487 for (; S
; S
= S
->getParent()) {
1488 // Check whether the IdResolver has anything in this scope.
1490 for (; I
!= IEnd
&& S
->isDeclScope(*I
); ++I
) {
1491 if (NamedDecl
*ND
= R
.getAcceptableDecl(*I
)) {
1492 // We found something. Look for anything else in our scope
1493 // with this same name and in an acceptable identifier
1494 // namespace, so that we can construct an overload set if we
1501 if (Found
&& S
->isTemplateParamScope()) {
1506 DeclContext
*Ctx
= S
->getLookupEntity();
1508 DeclContext
*OuterCtx
= findOuterContext(S
);
1509 for (; Ctx
&& !Ctx
->Equals(OuterCtx
); Ctx
= Ctx
->getLookupParent()) {
1510 // We do not directly look into transparent contexts, since
1511 // those entities will be found in the nearest enclosing
1512 // non-transparent context.
1513 if (Ctx
->isTransparentContext())
1516 // If we have a context, and it's not a context stashed in the
1517 // template parameter scope for an out-of-line definition, also
1518 // look into that context.
1519 if (!(Found
&& S
->isTemplateParamScope())) {
1520 assert(Ctx
->isFileContext() &&
1521 "We should have been looking only at file context here already.");
1523 // Look into context considering using-directives.
1524 if (CppNamespaceLookup(*this, R
, Context
, Ctx
, UDirs
))
1533 if (R
.isForRedeclaration() && !Ctx
->isTransparentContext())
1538 if (R
.isForRedeclaration() && Ctx
&& !Ctx
->isTransparentContext())
1545 void Sema::makeMergedDefinitionVisible(NamedDecl
*ND
) {
1546 if (auto *M
= getCurrentModule())
1547 Context
.mergeDefinitionIntoModule(ND
, M
);
1549 // We're not building a module; just make the definition visible.
1550 ND
->setVisibleDespiteOwningModule();
1552 // If ND is a template declaration, make the template parameters
1553 // visible too. They're not (necessarily) within a mergeable DeclContext.
1554 if (auto *TD
= dyn_cast
<TemplateDecl
>(ND
))
1555 for (auto *Param
: *TD
->getTemplateParameters())
1556 makeMergedDefinitionVisible(Param
);
1559 /// Find the module in which the given declaration was defined.
1560 static Module
*getDefiningModule(Sema
&S
, Decl
*Entity
) {
1561 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(Entity
)) {
1562 // If this function was instantiated from a template, the defining module is
1563 // the module containing the pattern.
1564 if (FunctionDecl
*Pattern
= FD
->getTemplateInstantiationPattern())
1566 } else if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Entity
)) {
1567 if (CXXRecordDecl
*Pattern
= RD
->getTemplateInstantiationPattern())
1569 } else if (EnumDecl
*ED
= dyn_cast
<EnumDecl
>(Entity
)) {
1570 if (auto *Pattern
= ED
->getTemplateInstantiationPattern())
1572 } else if (VarDecl
*VD
= dyn_cast
<VarDecl
>(Entity
)) {
1573 if (VarDecl
*Pattern
= VD
->getTemplateInstantiationPattern())
1577 // Walk up to the containing context. That might also have been instantiated
1579 DeclContext
*Context
= Entity
->getLexicalDeclContext();
1580 if (Context
->isFileContext())
1581 return S
.getOwningModule(Entity
);
1582 return getDefiningModule(S
, cast
<Decl
>(Context
));
1585 llvm::DenseSet
<Module
*> &Sema::getLookupModules() {
1586 unsigned N
= CodeSynthesisContexts
.size();
1587 for (unsigned I
= CodeSynthesisContextLookupModules
.size();
1589 Module
*M
= CodeSynthesisContexts
[I
].Entity
?
1590 getDefiningModule(*this, CodeSynthesisContexts
[I
].Entity
) :
1592 if (M
&& !LookupModulesCache
.insert(M
).second
)
1594 CodeSynthesisContextLookupModules
.push_back(M
);
1596 return LookupModulesCache
;
1599 bool Sema::isUsableModule(const Module
*M
) {
1600 assert(M
&& "We shouldn't check nullness for module here");
1601 // Return quickly if we cached the result.
1602 if (UsableModuleUnitsCache
.count(M
))
1605 // If M is the global module fragment of the current translation unit. So it
1606 // should be usable.
1607 // [module.global.frag]p1:
1608 // The global module fragment can be used to provide declarations that are
1609 // attached to the global module and usable within the module unit.
1610 if (M
== TheGlobalModuleFragment
|| M
== TheImplicitGlobalModuleFragment
) {
1611 UsableModuleUnitsCache
.insert(M
);
1615 // Otherwise, the global module fragment from other translation unit is not
1617 if (M
->isGlobalModule())
1620 Module
*Current
= getCurrentModule();
1622 // If we're not parsing a module, we can't use all the declarations from
1623 // another module easily.
1627 // If M is the module we're parsing or M and the current module unit lives in
1628 // the same module, M should be usable.
1630 // Note: It should be fine to search the vector `ModuleScopes` linearly since
1631 // it should be generally small enough. There should be rare module fragments
1632 // in a named module unit.
1633 if (llvm::count_if(ModuleScopes
,
1634 [&M
](const ModuleScope
&MS
) { return MS
.Module
== M
; }) ||
1635 getASTContext().isInSameModule(M
, Current
)) {
1636 UsableModuleUnitsCache
.insert(M
);
1643 bool Sema::hasVisibleMergedDefinition(const NamedDecl
*Def
) {
1644 for (const Module
*Merged
: Context
.getModulesWithMergedDefinition(Def
))
1645 if (isModuleVisible(Merged
))
1650 bool Sema::hasMergedDefinitionInCurrentModule(const NamedDecl
*Def
) {
1651 for (const Module
*Merged
: Context
.getModulesWithMergedDefinition(Def
))
1652 if (isUsableModule(Merged
))
1657 template <typename ParmDecl
>
1659 hasAcceptableDefaultArgument(Sema
&S
, const ParmDecl
*D
,
1660 llvm::SmallVectorImpl
<Module
*> *Modules
,
1661 Sema::AcceptableKind Kind
) {
1662 if (!D
->hasDefaultArgument())
1665 llvm::SmallPtrSet
<const ParmDecl
*, 4> Visited
;
1666 while (D
&& Visited
.insert(D
).second
) {
1667 auto &DefaultArg
= D
->getDefaultArgStorage();
1668 if (!DefaultArg
.isInherited() && S
.isAcceptable(D
, Kind
))
1671 if (!DefaultArg
.isInherited() && Modules
) {
1672 auto *NonConstD
= const_cast<ParmDecl
*>(D
);
1673 Modules
->push_back(S
.getOwningModule(NonConstD
));
1676 // If there was a previous default argument, maybe its parameter is
1678 D
= DefaultArg
.getInheritedFrom();
1683 bool Sema::hasAcceptableDefaultArgument(
1684 const NamedDecl
*D
, llvm::SmallVectorImpl
<Module
*> *Modules
,
1685 Sema::AcceptableKind Kind
) {
1686 if (auto *P
= dyn_cast
<TemplateTypeParmDecl
>(D
))
1687 return ::hasAcceptableDefaultArgument(*this, P
, Modules
, Kind
);
1689 if (auto *P
= dyn_cast
<NonTypeTemplateParmDecl
>(D
))
1690 return ::hasAcceptableDefaultArgument(*this, P
, Modules
, Kind
);
1692 return ::hasAcceptableDefaultArgument(
1693 *this, cast
<TemplateTemplateParmDecl
>(D
), Modules
, Kind
);
1696 bool Sema::hasVisibleDefaultArgument(const NamedDecl
*D
,
1697 llvm::SmallVectorImpl
<Module
*> *Modules
) {
1698 return hasAcceptableDefaultArgument(D
, Modules
,
1699 Sema::AcceptableKind::Visible
);
1702 bool Sema::hasReachableDefaultArgument(
1703 const NamedDecl
*D
, llvm::SmallVectorImpl
<Module
*> *Modules
) {
1704 return hasAcceptableDefaultArgument(D
, Modules
,
1705 Sema::AcceptableKind::Reachable
);
1708 template <typename Filter
>
1710 hasAcceptableDeclarationImpl(Sema
&S
, const NamedDecl
*D
,
1711 llvm::SmallVectorImpl
<Module
*> *Modules
, Filter F
,
1712 Sema::AcceptableKind Kind
) {
1713 bool HasFilteredRedecls
= false;
1715 for (auto *Redecl
: D
->redecls()) {
1716 auto *R
= cast
<NamedDecl
>(Redecl
);
1720 if (S
.isAcceptable(R
, Kind
))
1723 HasFilteredRedecls
= true;
1726 Modules
->push_back(R
->getOwningModule());
1729 // Only return false if there is at least one redecl that is not filtered out.
1730 if (HasFilteredRedecls
)
1737 hasAcceptableExplicitSpecialization(Sema
&S
, const NamedDecl
*D
,
1738 llvm::SmallVectorImpl
<Module
*> *Modules
,
1739 Sema::AcceptableKind Kind
) {
1740 return hasAcceptableDeclarationImpl(
1742 [](const NamedDecl
*D
) {
1743 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(D
))
1744 return RD
->getTemplateSpecializationKind() ==
1745 TSK_ExplicitSpecialization
;
1746 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
))
1747 return FD
->getTemplateSpecializationKind() ==
1748 TSK_ExplicitSpecialization
;
1749 if (auto *VD
= dyn_cast
<VarDecl
>(D
))
1750 return VD
->getTemplateSpecializationKind() ==
1751 TSK_ExplicitSpecialization
;
1752 llvm_unreachable("unknown explicit specialization kind");
1757 bool Sema::hasVisibleExplicitSpecialization(
1758 const NamedDecl
*D
, llvm::SmallVectorImpl
<Module
*> *Modules
) {
1759 return ::hasAcceptableExplicitSpecialization(*this, D
, Modules
,
1760 Sema::AcceptableKind::Visible
);
1763 bool Sema::hasReachableExplicitSpecialization(
1764 const NamedDecl
*D
, llvm::SmallVectorImpl
<Module
*> *Modules
) {
1765 return ::hasAcceptableExplicitSpecialization(*this, D
, Modules
,
1766 Sema::AcceptableKind::Reachable
);
1770 hasAcceptableMemberSpecialization(Sema
&S
, const NamedDecl
*D
,
1771 llvm::SmallVectorImpl
<Module
*> *Modules
,
1772 Sema::AcceptableKind Kind
) {
1773 assert(isa
<CXXRecordDecl
>(D
->getDeclContext()) &&
1774 "not a member specialization");
1775 return hasAcceptableDeclarationImpl(
1777 [](const NamedDecl
*D
) {
1778 // If the specialization is declared at namespace scope, then it's a
1779 // member specialization declaration. If it's lexically inside the class
1780 // definition then it was instantiated.
1782 // FIXME: This is a hack. There should be a better way to determine
1784 // FIXME: What about MS-style explicit specializations declared within a
1785 // class definition?
1786 return D
->getLexicalDeclContext()->isFileContext();
1791 bool Sema::hasVisibleMemberSpecialization(
1792 const NamedDecl
*D
, llvm::SmallVectorImpl
<Module
*> *Modules
) {
1793 return hasAcceptableMemberSpecialization(*this, D
, Modules
,
1794 Sema::AcceptableKind::Visible
);
1797 bool Sema::hasReachableMemberSpecialization(
1798 const NamedDecl
*D
, llvm::SmallVectorImpl
<Module
*> *Modules
) {
1799 return hasAcceptableMemberSpecialization(*this, D
, Modules
,
1800 Sema::AcceptableKind::Reachable
);
1803 /// Determine whether a declaration is acceptable to name lookup.
1805 /// This routine determines whether the declaration D is acceptable in the
1806 /// current lookup context, taking into account the current template
1807 /// instantiation stack. During template instantiation, a declaration is
1808 /// acceptable if it is acceptable from a module containing any entity on the
1809 /// template instantiation path (by instantiating a template, you allow it to
1810 /// see the declarations that your module can see, including those later on in
1812 bool LookupResult::isAcceptableSlow(Sema
&SemaRef
, NamedDecl
*D
,
1813 Sema::AcceptableKind Kind
) {
1814 assert(!D
->isUnconditionallyVisible() &&
1815 "should not call this: not in slow case");
1817 Module
*DeclModule
= SemaRef
.getOwningModule(D
);
1818 assert(DeclModule
&& "hidden decl has no owning module");
1820 // If the owning module is visible, the decl is acceptable.
1821 if (SemaRef
.isModuleVisible(DeclModule
,
1822 D
->isInvisibleOutsideTheOwningModule()))
1825 // Determine whether a decl context is a file context for the purpose of
1826 // visibility/reachability. This looks through some (export and linkage spec)
1827 // transparent contexts, but not others (enums).
1828 auto IsEffectivelyFileContext
= [](const DeclContext
*DC
) {
1829 return DC
->isFileContext() || isa
<LinkageSpecDecl
>(DC
) ||
1830 isa
<ExportDecl
>(DC
);
1833 // If this declaration is not at namespace scope
1834 // then it is acceptable if its lexical parent has a acceptable definition.
1835 DeclContext
*DC
= D
->getLexicalDeclContext();
1836 if (DC
&& !IsEffectivelyFileContext(DC
)) {
1837 // For a parameter, check whether our current template declaration's
1838 // lexical context is acceptable, not whether there's some other acceptable
1839 // definition of it, because parameters aren't "within" the definition.
1841 // In C++ we need to check for a acceptable definition due to ODR merging,
1842 // and in C we must not because each declaration of a function gets its own
1843 // set of declarations for tags in prototype scope.
1844 bool AcceptableWithinParent
;
1845 if (D
->isTemplateParameter()) {
1846 bool SearchDefinitions
= true;
1847 if (const auto *DCD
= dyn_cast
<Decl
>(DC
)) {
1848 if (const auto *TD
= DCD
->getDescribedTemplate()) {
1849 TemplateParameterList
*TPL
= TD
->getTemplateParameters();
1850 auto Index
= getDepthAndIndex(D
).second
;
1851 SearchDefinitions
= Index
>= TPL
->size() || TPL
->getParam(Index
) != D
;
1854 if (SearchDefinitions
)
1855 AcceptableWithinParent
=
1856 SemaRef
.hasAcceptableDefinition(cast
<NamedDecl
>(DC
), Kind
);
1858 AcceptableWithinParent
=
1859 isAcceptable(SemaRef
, cast
<NamedDecl
>(DC
), Kind
);
1860 } else if (isa
<ParmVarDecl
>(D
) ||
1861 (isa
<FunctionDecl
>(DC
) && !SemaRef
.getLangOpts().CPlusPlus
))
1862 AcceptableWithinParent
= isAcceptable(SemaRef
, cast
<NamedDecl
>(DC
), Kind
);
1863 else if (D
->isModulePrivate()) {
1864 // A module-private declaration is only acceptable if an enclosing lexical
1865 // parent was merged with another definition in the current module.
1866 AcceptableWithinParent
= false;
1868 if (SemaRef
.hasMergedDefinitionInCurrentModule(cast
<NamedDecl
>(DC
))) {
1869 AcceptableWithinParent
= true;
1872 DC
= DC
->getLexicalParent();
1873 } while (!IsEffectivelyFileContext(DC
));
1875 AcceptableWithinParent
=
1876 SemaRef
.hasAcceptableDefinition(cast
<NamedDecl
>(DC
), Kind
);
1879 if (AcceptableWithinParent
&& SemaRef
.CodeSynthesisContexts
.empty() &&
1880 Kind
== Sema::AcceptableKind::Visible
&&
1881 // FIXME: Do something better in this case.
1882 !SemaRef
.getLangOpts().ModulesLocalVisibility
) {
1883 // Cache the fact that this declaration is implicitly visible because
1884 // its parent has a visible definition.
1885 D
->setVisibleDespiteOwningModule();
1887 return AcceptableWithinParent
;
1890 if (Kind
== Sema::AcceptableKind::Visible
)
1893 assert(Kind
== Sema::AcceptableKind::Reachable
&&
1894 "Additional Sema::AcceptableKind?");
1895 return isReachableSlow(SemaRef
, D
);
1898 bool Sema::isModuleVisible(const Module
*M
, bool ModulePrivate
) {
1899 // The module might be ordinarily visible. For a module-private query, that
1900 // means it is part of the current module.
1901 if (ModulePrivate
&& isUsableModule(M
))
1904 // For a query which is not module-private, that means it is in our visible
1906 if (!ModulePrivate
&& VisibleModules
.isVisible(M
))
1909 // Otherwise, it might be visible by virtue of the query being within a
1910 // template instantiation or similar that is permitted to look inside M.
1912 // Find the extra places where we need to look.
1913 const auto &LookupModules
= getLookupModules();
1914 if (LookupModules
.empty())
1917 // If our lookup set contains the module, it's visible.
1918 if (LookupModules
.count(M
))
1921 // The global module fragments are visible to its corresponding module unit.
1922 // So the global module fragment should be visible if the its corresponding
1923 // module unit is visible.
1924 if (M
->isGlobalModule() && LookupModules
.count(M
->getTopLevelModule()))
1927 // For a module-private query, that's everywhere we get to look.
1931 // Check whether M is transitively exported to an import of the lookup set.
1932 return llvm::any_of(LookupModules
, [&](const Module
*LookupM
) {
1933 return LookupM
->isModuleVisible(M
);
1937 // FIXME: Return false directly if we don't have an interface dependency on the
1938 // translation unit containing D.
1939 bool LookupResult::isReachableSlow(Sema
&SemaRef
, NamedDecl
*D
) {
1940 assert(!isVisible(SemaRef
, D
) && "Shouldn't call the slow case.\n");
1942 Module
*DeclModule
= SemaRef
.getOwningModule(D
);
1943 assert(DeclModule
&& "hidden decl has no owning module");
1945 // Entities in header like modules are reachable only if they're visible.
1946 if (DeclModule
->isHeaderLikeModule())
1949 if (!D
->isInAnotherModuleUnit())
1952 // [module.reach]/p3:
1953 // A declaration D is reachable from a point P if:
1955 // - D is not discarded ([module.global.frag]), appears in a translation unit
1956 // that is reachable from P, and does not appear within a private module
1959 // A declaration that's discarded in the GMF should be module-private.
1960 if (D
->isModulePrivate())
1963 // [module.reach]/p1
1964 // A translation unit U is necessarily reachable from a point P if U is a
1965 // module interface unit on which the translation unit containing P has an
1966 // interface dependency, or the translation unit containing P imports U, in
1967 // either case prior to P ([module.import]).
1969 // [module.import]/p10
1970 // A translation unit has an interface dependency on a translation unit U if
1971 // it contains a declaration (possibly a module-declaration) that imports U
1972 // or if it has an interface dependency on a translation unit that has an
1973 // interface dependency on U.
1975 // So we could conclude the module unit U is necessarily reachable if:
1976 // (1) The module unit U is module interface unit.
1977 // (2) The current unit has an interface dependency on the module unit U.
1979 // Here we only check for the first condition. Since we couldn't see
1980 // DeclModule if it isn't (transitively) imported.
1981 if (DeclModule
->getTopLevelModule()->isModuleInterfaceUnit())
1984 // [module.reach]/p2
1985 // Additional translation units on
1986 // which the point within the program has an interface dependency may be
1987 // considered reachable, but it is unspecified which are and under what
1990 // The decision here is to treat all additional tranditional units as
1995 bool Sema::isAcceptableSlow(const NamedDecl
*D
, Sema::AcceptableKind Kind
) {
1996 return LookupResult::isAcceptable(*this, const_cast<NamedDecl
*>(D
), Kind
);
1999 bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult
&R
, const NamedDecl
*New
) {
2000 // FIXME: If there are both visible and hidden declarations, we need to take
2001 // into account whether redeclaration is possible. Example:
2003 // Non-imported module:
2006 // static int f(U); // #2, not a redeclaration of #1
2007 // int f(T); // #3, finds both, should link with #1 if T != U, but
2008 // // with #2 if T == U; neither should be ambiguous.
2012 assert(D
->isExternallyDeclarable() &&
2013 "should not have hidden, non-externally-declarable result here");
2016 // This function is called once "New" is essentially complete, but before a
2017 // previous declaration is attached. We can't query the linkage of "New" in
2018 // general, because attaching the previous declaration can change the
2019 // linkage of New to match the previous declaration.
2021 // However, because we've just determined that there is no *visible* prior
2022 // declaration, we can compute the linkage here. There are two possibilities:
2024 // * This is not a redeclaration; it's safe to compute the linkage now.
2026 // * This is a redeclaration of a prior declaration that is externally
2027 // redeclarable. In that case, the linkage of the declaration is not
2028 // changed by attaching the prior declaration, because both are externally
2029 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
2031 // FIXME: This is subtle and fragile.
2032 return New
->isExternallyDeclarable();
2035 /// Retrieve the visible declaration corresponding to D, if any.
2037 /// This routine determines whether the declaration D is visible in the current
2038 /// module, with the current imports. If not, it checks whether any
2039 /// redeclaration of D is visible, and if so, returns that declaration.
2041 /// \returns D, or a visible previous declaration of D, whichever is more recent
2042 /// and visible. If no declaration of D is visible, returns null.
2043 static NamedDecl
*findAcceptableDecl(Sema
&SemaRef
, NamedDecl
*D
,
2045 assert(!LookupResult::isAvailableForLookup(SemaRef
, D
) && "not in slow case");
2047 for (auto *RD
: D
->redecls()) {
2048 // Don't bother with extra checks if we already know this one isn't visible.
2052 auto ND
= cast
<NamedDecl
>(RD
);
2053 // FIXME: This is wrong in the case where the previous declaration is not
2054 // visible in the same scope as D. This needs to be done much more
2056 if (ND
->isInIdentifierNamespace(IDNS
) &&
2057 LookupResult::isAvailableForLookup(SemaRef
, ND
))
2064 bool Sema::hasVisibleDeclarationSlow(const NamedDecl
*D
,
2065 llvm::SmallVectorImpl
<Module
*> *Modules
) {
2066 assert(!isVisible(D
) && "not in slow case");
2067 return hasAcceptableDeclarationImpl(
2068 *this, D
, Modules
, [](const NamedDecl
*) { return true; },
2069 Sema::AcceptableKind::Visible
);
2072 bool Sema::hasReachableDeclarationSlow(
2073 const NamedDecl
*D
, llvm::SmallVectorImpl
<Module
*> *Modules
) {
2074 assert(!isReachable(D
) && "not in slow case");
2075 return hasAcceptableDeclarationImpl(
2076 *this, D
, Modules
, [](const NamedDecl
*) { return true; },
2077 Sema::AcceptableKind::Reachable
);
2080 NamedDecl
*LookupResult::getAcceptableDeclSlow(NamedDecl
*D
) const {
2081 if (auto *ND
= dyn_cast
<NamespaceDecl
>(D
)) {
2082 // Namespaces are a bit of a special case: we expect there to be a lot of
2083 // redeclarations of some namespaces, all declarations of a namespace are
2084 // essentially interchangeable, all declarations are found by name lookup
2085 // if any is, and namespaces are never looked up during template
2086 // instantiation. So we benefit from caching the check in this case, and
2087 // it is correct to do so.
2088 auto *Key
= ND
->getCanonicalDecl();
2089 if (auto *Acceptable
= getSema().VisibleNamespaceCache
.lookup(Key
))
2091 auto *Acceptable
= isVisible(getSema(), Key
)
2093 : findAcceptableDecl(getSema(), Key
, IDNS
);
2095 getSema().VisibleNamespaceCache
.insert(std::make_pair(Key
, Acceptable
));
2099 return findAcceptableDecl(getSema(), D
, IDNS
);
2102 bool LookupResult::isVisible(Sema
&SemaRef
, NamedDecl
*D
) {
2103 // If this declaration is already visible, return it directly.
2104 if (D
->isUnconditionallyVisible())
2107 // During template instantiation, we can refer to hidden declarations, if
2108 // they were visible in any module along the path of instantiation.
2109 return isAcceptableSlow(SemaRef
, D
, Sema::AcceptableKind::Visible
);
2112 bool LookupResult::isReachable(Sema
&SemaRef
, NamedDecl
*D
) {
2113 if (D
->isUnconditionallyVisible())
2116 return isAcceptableSlow(SemaRef
, D
, Sema::AcceptableKind::Reachable
);
2119 bool LookupResult::isAvailableForLookup(Sema
&SemaRef
, NamedDecl
*ND
) {
2120 // We should check the visibility at the callsite already.
2121 if (isVisible(SemaRef
, ND
))
2124 // Deduction guide lives in namespace scope generally, but it is just a
2125 // hint to the compilers. What we actually lookup for is the generated member
2126 // of the corresponding template. So it is sufficient to check the
2127 // reachability of the template decl.
2128 if (auto *DeductionGuide
= ND
->getDeclName().getCXXDeductionGuideTemplate())
2129 return SemaRef
.hasReachableDefinition(DeductionGuide
);
2131 // FIXME: The lookup for allocation function is a standalone process.
2132 // (We can find the logics in Sema::FindAllocationFunctions)
2134 // Such structure makes it a problem when we instantiate a template
2135 // declaration using placement allocation function if the placement
2136 // allocation function is invisible.
2137 // (See https://github.com/llvm/llvm-project/issues/59601)
2139 // Here we workaround it by making the placement allocation functions
2140 // always acceptable. The downside is that we can't diagnose the direct
2141 // use of the invisible placement allocation functions. (Although such uses
2143 if (auto *FD
= dyn_cast
<FunctionDecl
>(ND
);
2144 FD
&& FD
->isReservedGlobalPlacementOperator())
2147 auto *DC
= ND
->getDeclContext();
2148 // If ND is not visible and it is at namespace scope, it shouldn't be found
2150 if (DC
->isFileContext())
2153 // [module.interface]p7
2154 // Class and enumeration member names can be found by name lookup in any
2155 // context in which a definition of the type is reachable.
2157 // FIXME: The current implementation didn't consider about scope. For example,
2165 // auto a = E1::e1; // Error as expected.
2166 // auto b = e1; // Should be error. namespace-scope name e1 is not visible
2169 // For the above example, the current implementation would emit error for `a`
2170 // correctly. However, the implementation wouldn't diagnose about `b` now.
2171 // Since we only check the reachability for the parent only.
2172 // See clang/test/CXX/module/module.interface/p7.cpp for example.
2173 if (auto *TD
= dyn_cast
<TagDecl
>(DC
))
2174 return SemaRef
.hasReachableDefinition(TD
);
2179 bool Sema::LookupName(LookupResult
&R
, Scope
*S
, bool AllowBuiltinCreation
,
2180 bool ForceNoCPlusPlus
) {
2181 DeclarationName Name
= R
.getLookupName();
2182 if (!Name
) return false;
2184 LookupNameKind NameKind
= R
.getLookupKind();
2186 if (!getLangOpts().CPlusPlus
|| ForceNoCPlusPlus
) {
2187 // Unqualified name lookup in C/Objective-C is purely lexical, so
2188 // search in the declarations attached to the name.
2189 if (NameKind
== Sema::LookupRedeclarationWithLinkage
) {
2190 // Find the nearest non-transparent declaration scope.
2191 while (!(S
->getFlags() & Scope::DeclScope
) ||
2192 (S
->getEntity() && S
->getEntity()->isTransparentContext()))
2196 // When performing a scope lookup, we want to find local extern decls.
2197 FindLocalExternScope
FindLocals(R
);
2199 // Scan up the scope chain looking for a decl that matches this
2200 // identifier that is in the appropriate namespace. This search
2201 // should not take long, as shadowing of names is uncommon, and
2202 // deep shadowing is extremely uncommon.
2203 bool LeftStartingScope
= false;
2205 for (IdentifierResolver::iterator I
= IdResolver
.begin(Name
),
2206 IEnd
= IdResolver
.end();
2208 if (NamedDecl
*D
= R
.getAcceptableDecl(*I
)) {
2209 if (NameKind
== LookupRedeclarationWithLinkage
) {
2210 // Determine whether this (or a previous) declaration is
2212 if (!LeftStartingScope
&& !S
->isDeclScope(*I
))
2213 LeftStartingScope
= true;
2215 // If we found something outside of our starting scope that
2216 // does not have linkage, skip it.
2217 if (LeftStartingScope
&& !((*I
)->hasLinkage())) {
2222 else if (NameKind
== LookupObjCImplicitSelfParam
&&
2223 !isa
<ImplicitParamDecl
>(*I
))
2228 // Check whether there are any other declarations with the same name
2229 // and in the same scope.
2231 // Find the scope in which this declaration was declared (if it
2232 // actually exists in a Scope).
2233 while (S
&& !S
->isDeclScope(D
))
2236 // If the scope containing the declaration is the translation unit,
2237 // then we'll need to perform our checks based on the matching
2238 // DeclContexts rather than matching scopes.
2239 if (S
&& isNamespaceOrTranslationUnitScope(S
))
2242 // Compute the DeclContext, if we need it.
2243 DeclContext
*DC
= nullptr;
2245 DC
= (*I
)->getDeclContext()->getRedeclContext();
2247 IdentifierResolver::iterator LastI
= I
;
2248 for (++LastI
; LastI
!= IEnd
; ++LastI
) {
2250 // Match based on scope.
2251 if (!S
->isDeclScope(*LastI
))
2254 // Match based on DeclContext.
2256 = (*LastI
)->getDeclContext()->getRedeclContext();
2257 if (!LastDC
->Equals(DC
))
2261 // If the declaration is in the right namespace and visible, add it.
2262 if (NamedDecl
*LastD
= R
.getAcceptableDecl(*LastI
))
2272 // Perform C++ unqualified name lookup.
2273 if (CppLookupName(R
, S
))
2277 // If we didn't find a use of this identifier, and if the identifier
2278 // corresponds to a compiler builtin, create the decl object for the builtin
2279 // now, injecting it into translation unit scope, and return it.
2280 if (AllowBuiltinCreation
&& LookupBuiltin(R
))
2283 // If we didn't find a use of this identifier, the ExternalSource
2284 // may be able to handle the situation.
2285 // Note: some lookup failures are expected!
2286 // See e.g. R.isForRedeclaration().
2287 return (ExternalSource
&& ExternalSource
->LookupUnqualified(R
, S
));
2290 /// Perform qualified name lookup in the namespaces nominated by
2291 /// using directives by the given context.
2293 /// C++98 [namespace.qual]p2:
2294 /// Given X::m (where X is a user-declared namespace), or given \::m
2295 /// (where X is the global namespace), let S be the set of all
2296 /// declarations of m in X and in the transitive closure of all
2297 /// namespaces nominated by using-directives in X and its used
2298 /// namespaces, except that using-directives are ignored in any
2299 /// namespace, including X, directly containing one or more
2300 /// declarations of m. No namespace is searched more than once in
2301 /// the lookup of a name. If S is the empty set, the program is
2302 /// ill-formed. Otherwise, if S has exactly one member, or if the
2303 /// context of the reference is a using-declaration
2304 /// (namespace.udecl), S is the required set of declarations of
2305 /// m. Otherwise if the use of m is not one that allows a unique
2306 /// declaration to be chosen from S, the program is ill-formed.
2308 /// C++98 [namespace.qual]p5:
2309 /// During the lookup of a qualified namespace member name, if the
2310 /// lookup finds more than one declaration of the member, and if one
2311 /// declaration introduces a class name or enumeration name and the
2312 /// other declarations either introduce the same object, the same
2313 /// enumerator or a set of functions, the non-type name hides the
2314 /// class or enumeration name if and only if the declarations are
2315 /// from the same namespace; otherwise (the declarations are from
2316 /// different namespaces), the program is ill-formed.
2317 static bool LookupQualifiedNameInUsingDirectives(Sema
&S
, LookupResult
&R
,
2318 DeclContext
*StartDC
) {
2319 assert(StartDC
->isFileContext() && "start context is not a file context");
2321 // We have not yet looked into these namespaces, much less added
2322 // their "using-children" to the queue.
2323 SmallVector
<NamespaceDecl
*, 8> Queue
;
2325 // We have at least added all these contexts to the queue.
2326 llvm::SmallPtrSet
<DeclContext
*, 8> Visited
;
2327 Visited
.insert(StartDC
);
2329 // We have already looked into the initial namespace; seed the queue
2330 // with its using-children.
2331 for (auto *I
: StartDC
->using_directives()) {
2332 NamespaceDecl
*ND
= I
->getNominatedNamespace()->getFirstDecl();
2333 if (S
.isVisible(I
) && Visited
.insert(ND
).second
)
2334 Queue
.push_back(ND
);
2337 // The easiest way to implement the restriction in [namespace.qual]p5
2338 // is to check whether any of the individual results found a tag
2339 // and, if so, to declare an ambiguity if the final result is not
2341 bool FoundTag
= false;
2342 bool FoundNonTag
= false;
2344 LookupResult
LocalR(LookupResult::Temporary
, R
);
2347 while (!Queue
.empty()) {
2348 NamespaceDecl
*ND
= Queue
.pop_back_val();
2350 // We go through some convolutions here to avoid copying results
2351 // between LookupResults.
2352 bool UseLocal
= !R
.empty();
2353 LookupResult
&DirectR
= UseLocal
? LocalR
: R
;
2354 bool FoundDirect
= LookupDirect(S
, DirectR
, ND
);
2357 // First do any local hiding.
2358 DirectR
.resolveKind();
2360 // If the local result is a tag, remember that.
2361 if (DirectR
.isSingleTagDecl())
2366 // Append the local results to the total results if necessary.
2368 R
.addAllDecls(LocalR
);
2373 // If we find names in this namespace, ignore its using directives.
2379 for (auto *I
: ND
->using_directives()) {
2380 NamespaceDecl
*Nom
= I
->getNominatedNamespace();
2381 if (S
.isVisible(I
) && Visited
.insert(Nom
).second
)
2382 Queue
.push_back(Nom
);
2387 if (FoundTag
&& FoundNonTag
)
2388 R
.setAmbiguousQualifiedTagHiding();
2396 bool Sema::LookupQualifiedName(LookupResult
&R
, DeclContext
*LookupCtx
,
2397 bool InUnqualifiedLookup
) {
2398 assert(LookupCtx
&& "Sema::LookupQualifiedName requires a lookup context");
2400 if (!R
.getLookupName())
2403 // Make sure that the declaration context is complete.
2404 assert((!isa
<TagDecl
>(LookupCtx
) ||
2405 LookupCtx
->isDependentContext() ||
2406 cast
<TagDecl
>(LookupCtx
)->isCompleteDefinition() ||
2407 cast
<TagDecl
>(LookupCtx
)->isBeingDefined()) &&
2408 "Declaration context must already be complete!");
2410 struct QualifiedLookupInScope
{
2412 DeclContext
*Context
;
2413 // Set flag in DeclContext informing debugger that we're looking for qualified name
2414 QualifiedLookupInScope(DeclContext
*ctx
)
2415 : oldVal(ctx
->shouldUseQualifiedLookup()), Context(ctx
) {
2416 ctx
->setUseQualifiedLookup();
2418 ~QualifiedLookupInScope() {
2419 Context
->setUseQualifiedLookup(oldVal
);
2423 CXXRecordDecl
*LookupRec
= dyn_cast
<CXXRecordDecl
>(LookupCtx
);
2424 // FIXME: Per [temp.dep.general]p2, an unqualified name is also dependent
2425 // if it's a dependent conversion-function-id or operator= where the current
2426 // class is a templated entity. This should be handled in LookupName.
2427 if (!InUnqualifiedLookup
&& !R
.isForRedeclaration()) {
2428 // C++23 [temp.dep.type]p5:
2429 // A qualified name is dependent if
2430 // - it is a conversion-function-id whose conversion-type-id
2433 // - its lookup context is the current instantiation and it
2436 if (DeclarationName Name
= R
.getLookupName();
2437 Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
&&
2438 Name
.getCXXNameType()->isDependentType()) {
2439 R
.setNotFoundInCurrentInstantiation();
2444 if (LookupDirect(*this, R
, LookupCtx
)) {
2447 R
.setNamingClass(LookupRec
);
2451 // Don't descend into implied contexts for redeclarations.
2452 // C++98 [namespace.qual]p6:
2453 // In a declaration for a namespace member in which the
2454 // declarator-id is a qualified-id, given that the qualified-id
2455 // for the namespace member has the form
2456 // nested-name-specifier unqualified-id
2457 // the unqualified-id shall name a member of the namespace
2458 // designated by the nested-name-specifier.
2459 // See also [class.mfct]p5 and [class.static.data]p2.
2460 if (R
.isForRedeclaration())
2463 // If this is a namespace, look it up in the implied namespaces.
2464 if (LookupCtx
->isFileContext())
2465 return LookupQualifiedNameInUsingDirectives(*this, R
, LookupCtx
);
2467 // If this isn't a C++ class, we aren't allowed to look into base
2468 // classes, we're done.
2469 if (!LookupRec
|| !LookupRec
->getDefinition())
2472 // We're done for lookups that can never succeed for C++ classes.
2473 if (R
.getLookupKind() == LookupOperatorName
||
2474 R
.getLookupKind() == LookupNamespaceName
||
2475 R
.getLookupKind() == LookupObjCProtocolName
||
2476 R
.getLookupKind() == LookupLabel
)
2479 // If we're performing qualified name lookup into a dependent class,
2480 // then we are actually looking into a current instantiation. If we have any
2481 // dependent base classes, then we either have to delay lookup until
2482 // template instantiation time (at which point all bases will be available)
2483 // or we have to fail.
2484 if (!InUnqualifiedLookup
&& LookupRec
->isDependentContext() &&
2485 LookupRec
->hasAnyDependentBases()) {
2486 R
.setNotFoundInCurrentInstantiation();
2490 // Perform lookup into our base classes.
2492 DeclarationName Name
= R
.getLookupName();
2493 unsigned IDNS
= R
.getIdentifierNamespace();
2495 // Look for this member in our base classes.
2496 auto BaseCallback
= [Name
, IDNS
](const CXXBaseSpecifier
*Specifier
,
2497 CXXBasePath
&Path
) -> bool {
2498 CXXRecordDecl
*BaseRecord
= Specifier
->getType()->getAsCXXRecordDecl();
2499 // Drop leading non-matching lookup results from the declaration list so
2500 // we don't need to consider them again below.
2501 for (Path
.Decls
= BaseRecord
->lookup(Name
).begin();
2502 Path
.Decls
!= Path
.Decls
.end(); ++Path
.Decls
) {
2503 if ((*Path
.Decls
)->isInIdentifierNamespace(IDNS
))
2510 Paths
.setOrigin(LookupRec
);
2511 if (!LookupRec
->lookupInBases(BaseCallback
, Paths
))
2514 R
.setNamingClass(LookupRec
);
2516 // C++ [class.member.lookup]p2:
2517 // [...] If the resulting set of declarations are not all from
2518 // sub-objects of the same type, or the set has a nonstatic member
2519 // and includes members from distinct sub-objects, there is an
2520 // ambiguity and the program is ill-formed. Otherwise that set is
2521 // the result of the lookup.
2522 QualType SubobjectType
;
2523 int SubobjectNumber
= 0;
2524 AccessSpecifier SubobjectAccess
= AS_none
;
2526 // Check whether the given lookup result contains only static members.
2527 auto HasOnlyStaticMembers
= [&](DeclContext::lookup_iterator Result
) {
2528 for (DeclContext::lookup_iterator I
= Result
, E
= I
.end(); I
!= E
; ++I
)
2529 if ((*I
)->isInIdentifierNamespace(IDNS
) && (*I
)->isCXXInstanceMember())
2534 bool TemplateNameLookup
= R
.isTemplateNameLookup();
2536 // Determine whether two sets of members contain the same members, as
2537 // required by C++ [class.member.lookup]p6.
2538 auto HasSameDeclarations
= [&](DeclContext::lookup_iterator A
,
2539 DeclContext::lookup_iterator B
) {
2540 using Iterator
= DeclContextLookupResult::iterator
;
2541 using Result
= const void *;
2543 auto Next
= [&](Iterator
&It
, Iterator End
) -> Result
{
2545 NamedDecl
*ND
= *It
++;
2546 if (!ND
->isInIdentifierNamespace(IDNS
))
2549 // C++ [temp.local]p3:
2550 // A lookup that finds an injected-class-name (10.2) can result in
2551 // an ambiguity in certain cases (for example, if it is found in
2552 // more than one base class). If all of the injected-class-names
2553 // that are found refer to specializations of the same class
2554 // template, and if the name is used as a template-name, the
2555 // reference refers to the class template itself and not a
2556 // specialization thereof, and is not ambiguous.
2557 if (TemplateNameLookup
)
2558 if (auto *TD
= getAsTemplateNameDecl(ND
))
2561 // C++ [class.member.lookup]p3:
2562 // type declarations (including injected-class-names) are replaced by
2563 // the types they designate
2564 if (const TypeDecl
*TD
= dyn_cast
<TypeDecl
>(ND
->getUnderlyingDecl())) {
2565 QualType T
= Context
.getTypeDeclType(TD
);
2566 return T
.getCanonicalType().getAsOpaquePtr();
2569 return ND
->getUnderlyingDecl()->getCanonicalDecl();
2574 // We'll often find the declarations are in the same order. Handle this
2575 // case (and the special case of only one declaration) efficiently.
2576 Iterator AIt
= A
, BIt
= B
, AEnd
, BEnd
;
2578 Result AResult
= Next(AIt
, AEnd
);
2579 Result BResult
= Next(BIt
, BEnd
);
2580 if (!AResult
&& !BResult
)
2582 if (!AResult
|| !BResult
)
2584 if (AResult
!= BResult
) {
2585 // Found a mismatch; carefully check both lists, accounting for the
2586 // possibility of declarations appearing more than once.
2587 llvm::SmallDenseMap
<Result
, bool, 32> AResults
;
2588 for (; AResult
; AResult
= Next(AIt
, AEnd
))
2589 AResults
.insert({AResult
, /*FoundInB*/false});
2591 for (; BResult
; BResult
= Next(BIt
, BEnd
)) {
2592 auto It
= AResults
.find(BResult
);
2593 if (It
== AResults
.end())
2600 return AResults
.size() == Found
;
2605 for (CXXBasePaths::paths_iterator Path
= Paths
.begin(), PathEnd
= Paths
.end();
2606 Path
!= PathEnd
; ++Path
) {
2607 const CXXBasePathElement
&PathElement
= Path
->back();
2609 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2610 // across all paths.
2611 SubobjectAccess
= std::min(SubobjectAccess
, Path
->Access
);
2613 // Determine whether we're looking at a distinct sub-object or not.
2614 if (SubobjectType
.isNull()) {
2615 // This is the first subobject we've looked at. Record its type.
2616 SubobjectType
= Context
.getCanonicalType(PathElement
.Base
->getType());
2617 SubobjectNumber
= PathElement
.SubobjectNumber
;
2621 if (SubobjectType
!=
2622 Context
.getCanonicalType(PathElement
.Base
->getType())) {
2623 // We found members of the given name in two subobjects of
2624 // different types. If the declaration sets aren't the same, this
2625 // lookup is ambiguous.
2627 // FIXME: The language rule says that this applies irrespective of
2628 // whether the sets contain only static members.
2629 if (HasOnlyStaticMembers(Path
->Decls
) &&
2630 HasSameDeclarations(Paths
.begin()->Decls
, Path
->Decls
))
2633 R
.setAmbiguousBaseSubobjectTypes(Paths
);
2637 // FIXME: This language rule no longer exists. Checking for ambiguous base
2638 // subobjects should be done as part of formation of a class member access
2639 // expression (when converting the object parameter to the member's type).
2640 if (SubobjectNumber
!= PathElement
.SubobjectNumber
) {
2641 // We have a different subobject of the same type.
2643 // C++ [class.member.lookup]p5:
2644 // A static member, a nested type or an enumerator defined in
2645 // a base class T can unambiguously be found even if an object
2646 // has more than one base class subobject of type T.
2647 if (HasOnlyStaticMembers(Path
->Decls
))
2650 // We have found a nonstatic member name in multiple, distinct
2651 // subobjects. Name lookup is ambiguous.
2652 R
.setAmbiguousBaseSubobjects(Paths
);
2657 // Lookup in a base class succeeded; return these results.
2659 for (DeclContext::lookup_iterator I
= Paths
.front().Decls
, E
= I
.end();
2661 AccessSpecifier AS
= CXXRecordDecl::MergeAccess(SubobjectAccess
,
2663 if (NamedDecl
*ND
= R
.getAcceptableDecl(*I
))
2670 bool Sema::LookupQualifiedName(LookupResult
&R
, DeclContext
*LookupCtx
,
2672 auto *NNS
= SS
.getScopeRep();
2673 if (NNS
&& NNS
->getKind() == NestedNameSpecifier::Super
)
2674 return LookupInSuper(R
, NNS
->getAsRecordDecl());
2677 return LookupQualifiedName(R
, LookupCtx
);
2680 bool Sema::LookupParsedName(LookupResult
&R
, Scope
*S
, CXXScopeSpec
*SS
,
2681 QualType ObjectType
, bool AllowBuiltinCreation
,
2682 bool EnteringContext
) {
2683 // When the scope specifier is invalid, don't even look for anything.
2684 if (SS
&& SS
->isInvalid())
2687 // Determine where to perform name lookup
2688 DeclContext
*DC
= nullptr;
2689 bool IsDependent
= false;
2690 if (!ObjectType
.isNull()) {
2691 // This nested-name-specifier occurs in a member access expression, e.g.,
2692 // x->B::f, and we are looking into the type of the object.
2693 assert((!SS
|| SS
->isEmpty()) &&
2694 "ObjectType and scope specifier cannot coexist");
2695 DC
= computeDeclContext(ObjectType
);
2696 IsDependent
= !DC
&& ObjectType
->isDependentType();
2697 assert(((!DC
&& ObjectType
->isDependentType()) ||
2698 !ObjectType
->isIncompleteType() || !ObjectType
->getAs
<TagType
>() ||
2699 ObjectType
->castAs
<TagType
>()->isBeingDefined()) &&
2700 "Caller should have completed object type");
2701 } else if (SS
&& SS
->isNotEmpty()) {
2702 // This nested-name-specifier occurs after another nested-name-specifier,
2703 // so long into the context associated with the prior nested-name-specifier.
2704 if ((DC
= computeDeclContext(*SS
, EnteringContext
))) {
2705 // The declaration context must be complete.
2706 if (!DC
->isDependentContext() && RequireCompleteDeclContext(*SS
, DC
))
2708 R
.setContextRange(SS
->getRange());
2709 // FIXME: '__super' lookup semantics could be implemented by a
2710 // LookupResult::isSuperLookup flag which skips the initial search of
2711 // the lookup context in LookupQualified.
2712 if (NestedNameSpecifier
*NNS
= SS
->getScopeRep();
2713 NNS
->getKind() == NestedNameSpecifier::Super
)
2714 return LookupInSuper(R
, NNS
->getAsRecordDecl());
2716 IsDependent
= !DC
&& isDependentScopeSpecifier(*SS
);
2718 // Perform unqualified name lookup starting in the given scope.
2719 return LookupName(R
, S
, AllowBuiltinCreation
);
2722 // If we were able to compute a declaration context, perform qualified name
2723 // lookup in that context.
2725 return LookupQualifiedName(R
, DC
);
2726 else if (IsDependent
)
2727 // We could not resolve the scope specified to a specific declaration
2728 // context, which means that SS refers to an unknown specialization.
2729 // Name lookup can't find anything in this case.
2730 R
.setNotFoundInCurrentInstantiation();
2734 bool Sema::LookupInSuper(LookupResult
&R
, CXXRecordDecl
*Class
) {
2735 // The access-control rules we use here are essentially the rules for
2736 // doing a lookup in Class that just magically skipped the direct
2737 // members of Class itself. That is, the naming class is Class, and the
2738 // access includes the access of the base.
2739 for (const auto &BaseSpec
: Class
->bases()) {
2740 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(
2741 BaseSpec
.getType()->castAs
<RecordType
>()->getDecl());
2742 LookupResult
Result(*this, R
.getLookupNameInfo(), R
.getLookupKind());
2743 Result
.setBaseObjectType(Context
.getRecordType(Class
));
2744 LookupQualifiedName(Result
, RD
);
2746 // Copy the lookup results into the target, merging the base's access into
2748 for (auto I
= Result
.begin(), E
= Result
.end(); I
!= E
; ++I
) {
2749 R
.addDecl(I
.getDecl(),
2750 CXXRecordDecl::MergeAccess(BaseSpec
.getAccessSpecifier(),
2754 Result
.suppressDiagnostics();
2758 R
.setNamingClass(Class
);
2763 void Sema::DiagnoseAmbiguousLookup(LookupResult
&Result
) {
2764 assert(Result
.isAmbiguous() && "Lookup result must be ambiguous");
2766 DeclarationName Name
= Result
.getLookupName();
2767 SourceLocation NameLoc
= Result
.getNameLoc();
2768 SourceRange LookupRange
= Result
.getContextRange();
2770 switch (Result
.getAmbiguityKind()) {
2771 case LookupResult::AmbiguousBaseSubobjects
: {
2772 CXXBasePaths
*Paths
= Result
.getBasePaths();
2773 QualType SubobjectType
= Paths
->front().back().Base
->getType();
2774 Diag(NameLoc
, diag::err_ambiguous_member_multiple_subobjects
)
2775 << Name
<< SubobjectType
<< getAmbiguousPathsDisplayString(*Paths
)
2778 DeclContext::lookup_iterator Found
= Paths
->front().Decls
;
2779 while (isa
<CXXMethodDecl
>(*Found
) &&
2780 cast
<CXXMethodDecl
>(*Found
)->isStatic())
2783 Diag((*Found
)->getLocation(), diag::note_ambiguous_member_found
);
2787 case LookupResult::AmbiguousBaseSubobjectTypes
: {
2788 Diag(NameLoc
, diag::err_ambiguous_member_multiple_subobject_types
)
2789 << Name
<< LookupRange
;
2791 CXXBasePaths
*Paths
= Result
.getBasePaths();
2792 std::set
<const NamedDecl
*> DeclsPrinted
;
2793 for (CXXBasePaths::paths_iterator Path
= Paths
->begin(),
2794 PathEnd
= Paths
->end();
2795 Path
!= PathEnd
; ++Path
) {
2796 const NamedDecl
*D
= *Path
->Decls
;
2797 if (!D
->isInIdentifierNamespace(Result
.getIdentifierNamespace()))
2799 if (DeclsPrinted
.insert(D
).second
) {
2800 if (const auto *TD
= dyn_cast
<TypedefNameDecl
>(D
->getUnderlyingDecl()))
2801 Diag(D
->getLocation(), diag::note_ambiguous_member_type_found
)
2802 << TD
->getUnderlyingType();
2803 else if (const auto *TD
= dyn_cast
<TypeDecl
>(D
->getUnderlyingDecl()))
2804 Diag(D
->getLocation(), diag::note_ambiguous_member_type_found
)
2805 << Context
.getTypeDeclType(TD
);
2807 Diag(D
->getLocation(), diag::note_ambiguous_member_found
);
2813 case LookupResult::AmbiguousTagHiding
: {
2814 Diag(NameLoc
, diag::err_ambiguous_tag_hiding
) << Name
<< LookupRange
;
2816 llvm::SmallPtrSet
<NamedDecl
*, 8> TagDecls
;
2818 for (auto *D
: Result
)
2819 if (TagDecl
*TD
= dyn_cast
<TagDecl
>(D
)) {
2820 TagDecls
.insert(TD
);
2821 Diag(TD
->getLocation(), diag::note_hidden_tag
);
2824 for (auto *D
: Result
)
2825 if (!isa
<TagDecl
>(D
))
2826 Diag(D
->getLocation(), diag::note_hiding_object
);
2828 // For recovery purposes, go ahead and implement the hiding.
2829 LookupResult::Filter F
= Result
.makeFilter();
2830 while (F
.hasNext()) {
2831 if (TagDecls
.count(F
.next()))
2838 case LookupResult::AmbiguousReferenceToPlaceholderVariable
: {
2839 Diag(NameLoc
, diag::err_using_placeholder_variable
) << Name
<< LookupRange
;
2840 DeclContext
*DC
= nullptr;
2841 for (auto *D
: Result
) {
2842 Diag(D
->getLocation(), diag::note_reference_placeholder
) << D
;
2843 if (DC
!= nullptr && DC
!= D
->getDeclContext())
2845 DC
= D
->getDeclContext();
2850 case LookupResult::AmbiguousReference
: {
2851 Diag(NameLoc
, diag::err_ambiguous_reference
) << Name
<< LookupRange
;
2853 for (auto *D
: Result
)
2854 Diag(D
->getLocation(), diag::note_ambiguous_candidate
) << D
;
2861 struct AssociatedLookup
{
2862 AssociatedLookup(Sema
&S
, SourceLocation InstantiationLoc
,
2863 Sema::AssociatedNamespaceSet
&Namespaces
,
2864 Sema::AssociatedClassSet
&Classes
)
2865 : S(S
), Namespaces(Namespaces
), Classes(Classes
),
2866 InstantiationLoc(InstantiationLoc
) {
2869 bool addClassTransitive(CXXRecordDecl
*RD
) {
2871 return ClassesTransitive
.insert(RD
);
2875 Sema::AssociatedNamespaceSet
&Namespaces
;
2876 Sema::AssociatedClassSet
&Classes
;
2877 SourceLocation InstantiationLoc
;
2880 Sema::AssociatedClassSet ClassesTransitive
;
2882 } // end anonymous namespace
2885 addAssociatedClassesAndNamespaces(AssociatedLookup
&Result
, QualType T
);
2887 // Given the declaration context \param Ctx of a class, class template or
2888 // enumeration, add the associated namespaces to \param Namespaces as described
2889 // in [basic.lookup.argdep]p2.
2890 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet
&Namespaces
,
2892 // The exact wording has been changed in C++14 as a result of
2893 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2894 // to all language versions since it is possible to return a local type
2895 // from a lambda in C++11.
2897 // C++14 [basic.lookup.argdep]p2:
2898 // If T is a class type [...]. Its associated namespaces are the innermost
2899 // enclosing namespaces of its associated classes. [...]
2901 // If T is an enumeration type, its associated namespace is the innermost
2902 // enclosing namespace of its declaration. [...]
2904 // We additionally skip inline namespaces. The innermost non-inline namespace
2905 // contains all names of all its nested inline namespaces anyway, so we can
2906 // replace the entire inline namespace tree with its root.
2907 while (!Ctx
->isFileContext() || Ctx
->isInlineNamespace())
2908 Ctx
= Ctx
->getParent();
2910 Namespaces
.insert(Ctx
->getPrimaryContext());
2913 // Add the associated classes and namespaces for argument-dependent
2914 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2916 addAssociatedClassesAndNamespaces(AssociatedLookup
&Result
,
2917 const TemplateArgument
&Arg
) {
2918 // C++ [basic.lookup.argdep]p2, last bullet:
2920 switch (Arg
.getKind()) {
2921 case TemplateArgument::Null
:
2924 case TemplateArgument::Type
:
2925 // [...] the namespaces and classes associated with the types of the
2926 // template arguments provided for template type parameters (excluding
2927 // template template parameters)
2928 addAssociatedClassesAndNamespaces(Result
, Arg
.getAsType());
2931 case TemplateArgument::Template
:
2932 case TemplateArgument::TemplateExpansion
: {
2933 // [...] the namespaces in which any template template arguments are
2934 // defined; and the classes in which any member templates used as
2935 // template template arguments are defined.
2936 TemplateName Template
= Arg
.getAsTemplateOrTemplatePattern();
2937 if (ClassTemplateDecl
*ClassTemplate
2938 = dyn_cast
<ClassTemplateDecl
>(Template
.getAsTemplateDecl())) {
2939 DeclContext
*Ctx
= ClassTemplate
->getDeclContext();
2940 if (CXXRecordDecl
*EnclosingClass
= dyn_cast
<CXXRecordDecl
>(Ctx
))
2941 Result
.Classes
.insert(EnclosingClass
);
2942 // Add the associated namespace for this class.
2943 CollectEnclosingNamespace(Result
.Namespaces
, Ctx
);
2948 case TemplateArgument::Declaration
:
2949 case TemplateArgument::Integral
:
2950 case TemplateArgument::Expression
:
2951 case TemplateArgument::NullPtr
:
2952 case TemplateArgument::StructuralValue
:
2953 // [Note: non-type template arguments do not contribute to the set of
2954 // associated namespaces. ]
2957 case TemplateArgument::Pack
:
2958 for (const auto &P
: Arg
.pack_elements())
2959 addAssociatedClassesAndNamespaces(Result
, P
);
2964 // Add the associated classes and namespaces for argument-dependent lookup
2965 // with an argument of class type (C++ [basic.lookup.argdep]p2).
2967 addAssociatedClassesAndNamespaces(AssociatedLookup
&Result
,
2968 CXXRecordDecl
*Class
) {
2970 // Just silently ignore anything whose name is __va_list_tag.
2971 if (Class
->getDeclName() == Result
.S
.VAListTagName
)
2974 // C++ [basic.lookup.argdep]p2:
2976 // -- If T is a class type (including unions), its associated
2977 // classes are: the class itself; the class of which it is a
2978 // member, if any; and its direct and indirect base classes.
2979 // Its associated namespaces are the innermost enclosing
2980 // namespaces of its associated classes.
2982 // Add the class of which it is a member, if any.
2983 DeclContext
*Ctx
= Class
->getDeclContext();
2984 if (CXXRecordDecl
*EnclosingClass
= dyn_cast
<CXXRecordDecl
>(Ctx
))
2985 Result
.Classes
.insert(EnclosingClass
);
2987 // Add the associated namespace for this class.
2988 CollectEnclosingNamespace(Result
.Namespaces
, Ctx
);
2990 // -- If T is a template-id, its associated namespaces and classes are
2991 // the namespace in which the template is defined; for member
2992 // templates, the member template's class; the namespaces and classes
2993 // associated with the types of the template arguments provided for
2994 // template type parameters (excluding template template parameters); the
2995 // namespaces in which any template template arguments are defined; and
2996 // the classes in which any member templates used as template template
2997 // arguments are defined. [Note: non-type template arguments do not
2998 // contribute to the set of associated namespaces. ]
2999 if (ClassTemplateSpecializationDecl
*Spec
3000 = dyn_cast
<ClassTemplateSpecializationDecl
>(Class
)) {
3001 DeclContext
*Ctx
= Spec
->getSpecializedTemplate()->getDeclContext();
3002 if (CXXRecordDecl
*EnclosingClass
= dyn_cast
<CXXRecordDecl
>(Ctx
))
3003 Result
.Classes
.insert(EnclosingClass
);
3004 // Add the associated namespace for this class.
3005 CollectEnclosingNamespace(Result
.Namespaces
, Ctx
);
3007 const TemplateArgumentList
&TemplateArgs
= Spec
->getTemplateArgs();
3008 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
3009 addAssociatedClassesAndNamespaces(Result
, TemplateArgs
[I
]);
3012 // Add the class itself. If we've already transitively visited this class,
3013 // we don't need to visit base classes.
3014 if (!Result
.addClassTransitive(Class
))
3017 // Only recurse into base classes for complete types.
3018 if (!Result
.S
.isCompleteType(Result
.InstantiationLoc
,
3019 Result
.S
.Context
.getRecordType(Class
)))
3022 // Add direct and indirect base classes along with their associated
3024 SmallVector
<CXXRecordDecl
*, 32> Bases
;
3025 Bases
.push_back(Class
);
3026 while (!Bases
.empty()) {
3027 // Pop this class off the stack.
3028 Class
= Bases
.pop_back_val();
3030 // Visit the base classes.
3031 for (const auto &Base
: Class
->bases()) {
3032 const RecordType
*BaseType
= Base
.getType()->getAs
<RecordType
>();
3033 // In dependent contexts, we do ADL twice, and the first time around,
3034 // the base type might be a dependent TemplateSpecializationType, or a
3035 // TemplateTypeParmType. If that happens, simply ignore it.
3036 // FIXME: If we want to support export, we probably need to add the
3037 // namespace of the template in a TemplateSpecializationType, or even
3038 // the classes and namespaces of known non-dependent arguments.
3041 CXXRecordDecl
*BaseDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
3042 if (Result
.addClassTransitive(BaseDecl
)) {
3043 // Find the associated namespace for this base class.
3044 DeclContext
*BaseCtx
= BaseDecl
->getDeclContext();
3045 CollectEnclosingNamespace(Result
.Namespaces
, BaseCtx
);
3047 // Make sure we visit the bases of this base class.
3048 if (BaseDecl
->bases_begin() != BaseDecl
->bases_end())
3049 Bases
.push_back(BaseDecl
);
3055 // Add the associated classes and namespaces for
3056 // argument-dependent lookup with an argument of type T
3057 // (C++ [basic.lookup.koenig]p2).
3059 addAssociatedClassesAndNamespaces(AssociatedLookup
&Result
, QualType Ty
) {
3060 // C++ [basic.lookup.koenig]p2:
3062 // For each argument type T in the function call, there is a set
3063 // of zero or more associated namespaces and a set of zero or more
3064 // associated classes to be considered. The sets of namespaces and
3065 // classes is determined entirely by the types of the function
3066 // arguments (and the namespace of any template template
3067 // argument). Typedef names and using-declarations used to specify
3068 // the types do not contribute to this set. The sets of namespaces
3069 // and classes are determined in the following way:
3071 SmallVector
<const Type
*, 16> Queue
;
3072 const Type
*T
= Ty
->getCanonicalTypeInternal().getTypePtr();
3075 switch (T
->getTypeClass()) {
3077 #define TYPE(Class, Base)
3078 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3079 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3080 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3081 #define ABSTRACT_TYPE(Class, Base)
3082 #include "clang/AST/TypeNodes.inc"
3083 // T is canonical. We can also ignore dependent types because
3084 // we don't need to do ADL at the definition point, but if we
3085 // wanted to implement template export (or if we find some other
3086 // use for associated classes and namespaces...) this would be
3090 // -- If T is a pointer to U or an array of U, its associated
3091 // namespaces and classes are those associated with U.
3093 T
= cast
<PointerType
>(T
)->getPointeeType().getTypePtr();
3095 case Type::ConstantArray
:
3096 case Type::IncompleteArray
:
3097 case Type::VariableArray
:
3098 T
= cast
<ArrayType
>(T
)->getElementType().getTypePtr();
3101 // -- If T is a fundamental type, its associated sets of
3102 // namespaces and classes are both empty.
3106 // -- If T is a class type (including unions), its associated
3107 // classes are: the class itself; the class of which it is
3108 // a member, if any; and its direct and indirect base classes.
3109 // Its associated namespaces are the innermost enclosing
3110 // namespaces of its associated classes.
3111 case Type::Record
: {
3112 CXXRecordDecl
*Class
=
3113 cast
<CXXRecordDecl
>(cast
<RecordType
>(T
)->getDecl());
3114 addAssociatedClassesAndNamespaces(Result
, Class
);
3118 // -- If T is an enumeration type, its associated namespace
3119 // is the innermost enclosing namespace of its declaration.
3120 // If it is a class member, its associated class is the
3121 // member’s class; else it has no associated class.
3123 EnumDecl
*Enum
= cast
<EnumType
>(T
)->getDecl();
3125 DeclContext
*Ctx
= Enum
->getDeclContext();
3126 if (CXXRecordDecl
*EnclosingClass
= dyn_cast
<CXXRecordDecl
>(Ctx
))
3127 Result
.Classes
.insert(EnclosingClass
);
3129 // Add the associated namespace for this enumeration.
3130 CollectEnclosingNamespace(Result
.Namespaces
, Ctx
);
3135 // -- If T is a function type, its associated namespaces and
3136 // classes are those associated with the function parameter
3137 // types and those associated with the return type.
3138 case Type::FunctionProto
: {
3139 const FunctionProtoType
*Proto
= cast
<FunctionProtoType
>(T
);
3140 for (const auto &Arg
: Proto
->param_types())
3141 Queue
.push_back(Arg
.getTypePtr());
3145 case Type::FunctionNoProto
: {
3146 const FunctionType
*FnType
= cast
<FunctionType
>(T
);
3147 T
= FnType
->getReturnType().getTypePtr();
3151 // -- If T is a pointer to a member function of a class X, its
3152 // associated namespaces and classes are those associated
3153 // with the function parameter types and return type,
3154 // together with those associated with X.
3156 // -- If T is a pointer to a data member of class X, its
3157 // associated namespaces and classes are those associated
3158 // with the member type together with those associated with
3160 case Type::MemberPointer
: {
3161 const MemberPointerType
*MemberPtr
= cast
<MemberPointerType
>(T
);
3163 // Queue up the class type into which this points.
3164 Queue
.push_back(MemberPtr
->getClass());
3166 // And directly continue with the pointee type.
3167 T
= MemberPtr
->getPointeeType().getTypePtr();
3171 // As an extension, treat this like a normal pointer.
3172 case Type::BlockPointer
:
3173 T
= cast
<BlockPointerType
>(T
)->getPointeeType().getTypePtr();
3176 // References aren't covered by the standard, but that's such an
3177 // obvious defect that we cover them anyway.
3178 case Type::LValueReference
:
3179 case Type::RValueReference
:
3180 T
= cast
<ReferenceType
>(T
)->getPointeeType().getTypePtr();
3183 // These are fundamental types.
3185 case Type::ExtVector
:
3186 case Type::ConstantMatrix
:
3191 // Non-deduced auto types only get here for error cases.
3193 case Type::DeducedTemplateSpecialization
:
3196 // If T is an Objective-C object or interface type, or a pointer to an
3197 // object or interface type, the associated namespace is the global
3199 case Type::ObjCObject
:
3200 case Type::ObjCInterface
:
3201 case Type::ObjCObjectPointer
:
3202 Result
.Namespaces
.insert(Result
.S
.Context
.getTranslationUnitDecl());
3205 // Atomic types are just wrappers; use the associations of the
3208 T
= cast
<AtomicType
>(T
)->getValueType().getTypePtr();
3211 T
= cast
<PipeType
>(T
)->getElementType().getTypePtr();
3214 // Array parameter types are treated as fundamental types.
3215 case Type::ArrayParameter
:
3218 case Type::HLSLAttributedResource
:
3219 T
= cast
<HLSLAttributedResourceType
>(T
)->getWrappedType().getTypePtr();
3224 T
= Queue
.pop_back_val();
3228 void Sema::FindAssociatedClassesAndNamespaces(
3229 SourceLocation InstantiationLoc
, ArrayRef
<Expr
*> Args
,
3230 AssociatedNamespaceSet
&AssociatedNamespaces
,
3231 AssociatedClassSet
&AssociatedClasses
) {
3232 AssociatedNamespaces
.clear();
3233 AssociatedClasses
.clear();
3235 AssociatedLookup
Result(*this, InstantiationLoc
,
3236 AssociatedNamespaces
, AssociatedClasses
);
3238 // C++ [basic.lookup.koenig]p2:
3239 // For each argument type T in the function call, there is a set
3240 // of zero or more associated namespaces and a set of zero or more
3241 // associated classes to be considered. The sets of namespaces and
3242 // classes is determined entirely by the types of the function
3243 // arguments (and the namespace of any template template
3245 for (unsigned ArgIdx
= 0; ArgIdx
!= Args
.size(); ++ArgIdx
) {
3246 Expr
*Arg
= Args
[ArgIdx
];
3248 if (Arg
->getType() != Context
.OverloadTy
) {
3249 addAssociatedClassesAndNamespaces(Result
, Arg
->getType());
3253 // [...] In addition, if the argument is the name or address of a
3254 // set of overloaded functions and/or function templates, its
3255 // associated classes and namespaces are the union of those
3256 // associated with each of the members of the set: the namespace
3257 // in which the function or function template is defined and the
3258 // classes and namespaces associated with its (non-dependent)
3259 // parameter types and return type.
3260 OverloadExpr
*OE
= OverloadExpr::find(Arg
).Expression
;
3262 for (const NamedDecl
*D
: OE
->decls()) {
3263 // Look through any using declarations to find the underlying function.
3264 const FunctionDecl
*FDecl
= D
->getUnderlyingDecl()->getAsFunction();
3266 // Add the classes and namespaces associated with the parameter
3267 // types and return type of this function.
3268 addAssociatedClassesAndNamespaces(Result
, FDecl
->getType());
3273 NamedDecl
*Sema::LookupSingleName(Scope
*S
, DeclarationName Name
,
3275 LookupNameKind NameKind
,
3276 RedeclarationKind Redecl
) {
3277 LookupResult
R(*this, Name
, Loc
, NameKind
, Redecl
);
3279 return R
.getAsSingle
<NamedDecl
>();
3282 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op
, Scope
*S
,
3283 UnresolvedSetImpl
&Functions
) {
3284 // C++ [over.match.oper]p3:
3285 // -- The set of non-member candidates is the result of the
3286 // unqualified lookup of operator@ in the context of the
3287 // expression according to the usual rules for name lookup in
3288 // unqualified function calls (3.4.2) except that all member
3289 // functions are ignored.
3290 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
3291 LookupResult
Operators(*this, OpName
, SourceLocation(), LookupOperatorName
);
3292 LookupName(Operators
, S
);
3294 assert(!Operators
.isAmbiguous() && "Operator lookup cannot be ambiguous");
3295 Functions
.append(Operators
.begin(), Operators
.end());
3298 Sema::SpecialMemberOverloadResult
3299 Sema::LookupSpecialMember(CXXRecordDecl
*RD
, CXXSpecialMemberKind SM
,
3300 bool ConstArg
, bool VolatileArg
, bool RValueThis
,
3301 bool ConstThis
, bool VolatileThis
) {
3302 assert(CanDeclareSpecialMemberFunction(RD
) &&
3303 "doing special member lookup into record that isn't fully complete");
3304 RD
= RD
->getDefinition();
3305 if (RValueThis
|| ConstThis
|| VolatileThis
)
3306 assert((SM
== CXXSpecialMemberKind::CopyAssignment
||
3307 SM
== CXXSpecialMemberKind::MoveAssignment
) &&
3308 "constructors and destructors always have unqualified lvalue this");
3309 if (ConstArg
|| VolatileArg
)
3310 assert((SM
!= CXXSpecialMemberKind::DefaultConstructor
&&
3311 SM
!= CXXSpecialMemberKind::Destructor
) &&
3312 "parameter-less special members can't have qualified arguments");
3314 // FIXME: Get the caller to pass in a location for the lookup.
3315 SourceLocation LookupLoc
= RD
->getLocation();
3317 llvm::FoldingSetNodeID ID
;
3319 ID
.AddInteger(llvm::to_underlying(SM
));
3320 ID
.AddInteger(ConstArg
);
3321 ID
.AddInteger(VolatileArg
);
3322 ID
.AddInteger(RValueThis
);
3323 ID
.AddInteger(ConstThis
);
3324 ID
.AddInteger(VolatileThis
);
3327 SpecialMemberOverloadResultEntry
*Result
=
3328 SpecialMemberCache
.FindNodeOrInsertPos(ID
, InsertPoint
);
3330 // This was already cached
3334 Result
= BumpAlloc
.Allocate
<SpecialMemberOverloadResultEntry
>();
3335 Result
= new (Result
) SpecialMemberOverloadResultEntry(ID
);
3336 SpecialMemberCache
.InsertNode(Result
, InsertPoint
);
3338 if (SM
== CXXSpecialMemberKind::Destructor
) {
3339 if (RD
->needsImplicitDestructor()) {
3340 runWithSufficientStackSpace(RD
->getLocation(), [&] {
3341 DeclareImplicitDestructor(RD
);
3344 CXXDestructorDecl
*DD
= RD
->getDestructor();
3345 Result
->setMethod(DD
);
3346 Result
->setKind(DD
&& !DD
->isDeleted()
3347 ? SpecialMemberOverloadResult::Success
3348 : SpecialMemberOverloadResult::NoMemberOrDeleted
);
3352 // Prepare for overload resolution. Here we construct a synthetic argument
3353 // if necessary and make sure that implicit functions are declared.
3354 CanQualType CanTy
= Context
.getCanonicalType(Context
.getTagDeclType(RD
));
3355 DeclarationName Name
;
3356 Expr
*Arg
= nullptr;
3359 QualType ArgType
= CanTy
;
3360 ExprValueKind VK
= VK_LValue
;
3362 if (SM
== CXXSpecialMemberKind::DefaultConstructor
) {
3363 Name
= Context
.DeclarationNames
.getCXXConstructorName(CanTy
);
3365 if (RD
->needsImplicitDefaultConstructor()) {
3366 runWithSufficientStackSpace(RD
->getLocation(), [&] {
3367 DeclareImplicitDefaultConstructor(RD
);
3371 if (SM
== CXXSpecialMemberKind::CopyConstructor
||
3372 SM
== CXXSpecialMemberKind::MoveConstructor
) {
3373 Name
= Context
.DeclarationNames
.getCXXConstructorName(CanTy
);
3374 if (RD
->needsImplicitCopyConstructor()) {
3375 runWithSufficientStackSpace(RD
->getLocation(), [&] {
3376 DeclareImplicitCopyConstructor(RD
);
3379 if (getLangOpts().CPlusPlus11
&& RD
->needsImplicitMoveConstructor()) {
3380 runWithSufficientStackSpace(RD
->getLocation(), [&] {
3381 DeclareImplicitMoveConstructor(RD
);
3385 Name
= Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
3386 if (RD
->needsImplicitCopyAssignment()) {
3387 runWithSufficientStackSpace(RD
->getLocation(), [&] {
3388 DeclareImplicitCopyAssignment(RD
);
3391 if (getLangOpts().CPlusPlus11
&& RD
->needsImplicitMoveAssignment()) {
3392 runWithSufficientStackSpace(RD
->getLocation(), [&] {
3393 DeclareImplicitMoveAssignment(RD
);
3401 ArgType
.addVolatile();
3403 // This isn't /really/ specified by the standard, but it's implied
3404 // we should be working from a PRValue in the case of move to ensure
3405 // that we prefer to bind to rvalue references, and an LValue in the
3406 // case of copy to ensure we don't bind to rvalue references.
3407 // Possibly an XValue is actually correct in the case of move, but
3408 // there is no semantic difference for class types in this restricted
3410 if (SM
== CXXSpecialMemberKind::CopyConstructor
||
3411 SM
== CXXSpecialMemberKind::CopyAssignment
)
3417 OpaqueValueExpr
FakeArg(LookupLoc
, ArgType
, VK
);
3419 if (SM
!= CXXSpecialMemberKind::DefaultConstructor
) {
3424 // Create the object argument
3425 QualType ThisTy
= CanTy
;
3429 ThisTy
.addVolatile();
3430 Expr::Classification Classification
=
3431 OpaqueValueExpr(LookupLoc
, ThisTy
, RValueThis
? VK_PRValue
: VK_LValue
)
3434 // Now we perform lookup on the name we computed earlier and do overload
3435 // resolution. Lookup is only performed directly into the class since there
3436 // will always be a (possibly implicit) declaration to shadow any others.
3437 OverloadCandidateSet
OCS(LookupLoc
, OverloadCandidateSet::CSK_Normal
);
3438 DeclContext::lookup_result R
= RD
->lookup(Name
);
3441 // We might have no default constructor because we have a lambda's closure
3442 // type, rather than because there's some other declared constructor.
3443 // Every class has a copy/move constructor, copy/move assignment, and
3445 assert(SM
== CXXSpecialMemberKind::DefaultConstructor
&&
3446 "lookup for a constructor or assignment operator was empty");
3447 Result
->setMethod(nullptr);
3448 Result
->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted
);
3452 // Copy the candidates as our processing of them may load new declarations
3453 // from an external source and invalidate lookup_result.
3454 SmallVector
<NamedDecl
*, 8> Candidates(R
.begin(), R
.end());
3456 for (NamedDecl
*CandDecl
: Candidates
) {
3457 if (CandDecl
->isInvalidDecl())
3460 DeclAccessPair Cand
= DeclAccessPair::make(CandDecl
, AS_public
);
3461 auto CtorInfo
= getConstructorInfo(Cand
);
3462 if (CXXMethodDecl
*M
= dyn_cast
<CXXMethodDecl
>(Cand
->getUnderlyingDecl())) {
3463 if (SM
== CXXSpecialMemberKind::CopyAssignment
||
3464 SM
== CXXSpecialMemberKind::MoveAssignment
)
3465 AddMethodCandidate(M
, Cand
, RD
, ThisTy
, Classification
,
3466 llvm::ArrayRef(&Arg
, NumArgs
), OCS
, true);
3468 AddOverloadCandidate(CtorInfo
.Constructor
, CtorInfo
.FoundDecl
,
3469 llvm::ArrayRef(&Arg
, NumArgs
), OCS
,
3470 /*SuppressUserConversions*/ true);
3472 AddOverloadCandidate(M
, Cand
, llvm::ArrayRef(&Arg
, NumArgs
), OCS
,
3473 /*SuppressUserConversions*/ true);
3474 } else if (FunctionTemplateDecl
*Tmpl
=
3475 dyn_cast
<FunctionTemplateDecl
>(Cand
->getUnderlyingDecl())) {
3476 if (SM
== CXXSpecialMemberKind::CopyAssignment
||
3477 SM
== CXXSpecialMemberKind::MoveAssignment
)
3478 AddMethodTemplateCandidate(Tmpl
, Cand
, RD
, nullptr, ThisTy
,
3480 llvm::ArrayRef(&Arg
, NumArgs
), OCS
, true);
3482 AddTemplateOverloadCandidate(CtorInfo
.ConstructorTmpl
,
3483 CtorInfo
.FoundDecl
, nullptr,
3484 llvm::ArrayRef(&Arg
, NumArgs
), OCS
, true);
3486 AddTemplateOverloadCandidate(Tmpl
, Cand
, nullptr,
3487 llvm::ArrayRef(&Arg
, NumArgs
), OCS
, true);
3489 assert(isa
<UsingDecl
>(Cand
.getDecl()) &&
3490 "illegal Kind of operator = Decl");
3494 OverloadCandidateSet::iterator Best
;
3495 switch (OCS
.BestViableFunction(*this, LookupLoc
, Best
)) {
3497 Result
->setMethod(cast
<CXXMethodDecl
>(Best
->Function
));
3498 Result
->setKind(SpecialMemberOverloadResult::Success
);
3502 Result
->setMethod(cast
<CXXMethodDecl
>(Best
->Function
));
3503 Result
->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted
);
3507 Result
->setMethod(nullptr);
3508 Result
->setKind(SpecialMemberOverloadResult::Ambiguous
);
3511 case OR_No_Viable_Function
:
3512 Result
->setMethod(nullptr);
3513 Result
->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted
);
3520 CXXConstructorDecl
*Sema::LookupDefaultConstructor(CXXRecordDecl
*Class
) {
3521 SpecialMemberOverloadResult Result
=
3522 LookupSpecialMember(Class
, CXXSpecialMemberKind::DefaultConstructor
,
3523 false, false, false, false, false);
3525 return cast_or_null
<CXXConstructorDecl
>(Result
.getMethod());
3528 CXXConstructorDecl
*Sema::LookupCopyingConstructor(CXXRecordDecl
*Class
,
3530 assert(!(Quals
& ~(Qualifiers::Const
| Qualifiers::Volatile
)) &&
3531 "non-const, non-volatile qualifiers for copy ctor arg");
3532 SpecialMemberOverloadResult Result
= LookupSpecialMember(
3533 Class
, CXXSpecialMemberKind::CopyConstructor
, Quals
& Qualifiers::Const
,
3534 Quals
& Qualifiers::Volatile
, false, false, false);
3536 return cast_or_null
<CXXConstructorDecl
>(Result
.getMethod());
3539 CXXConstructorDecl
*Sema::LookupMovingConstructor(CXXRecordDecl
*Class
,
3541 SpecialMemberOverloadResult Result
= LookupSpecialMember(
3542 Class
, CXXSpecialMemberKind::MoveConstructor
, Quals
& Qualifiers::Const
,
3543 Quals
& Qualifiers::Volatile
, false, false, false);
3545 return cast_or_null
<CXXConstructorDecl
>(Result
.getMethod());
3548 DeclContext::lookup_result
Sema::LookupConstructors(CXXRecordDecl
*Class
) {
3549 // If the implicit constructors have not yet been declared, do so now.
3550 if (CanDeclareSpecialMemberFunction(Class
)) {
3551 runWithSufficientStackSpace(Class
->getLocation(), [&] {
3552 if (Class
->needsImplicitDefaultConstructor())
3553 DeclareImplicitDefaultConstructor(Class
);
3554 if (Class
->needsImplicitCopyConstructor())
3555 DeclareImplicitCopyConstructor(Class
);
3556 if (getLangOpts().CPlusPlus11
&& Class
->needsImplicitMoveConstructor())
3557 DeclareImplicitMoveConstructor(Class
);
3561 CanQualType T
= Context
.getCanonicalType(Context
.getTypeDeclType(Class
));
3562 DeclarationName Name
= Context
.DeclarationNames
.getCXXConstructorName(T
);
3563 return Class
->lookup(Name
);
3566 CXXMethodDecl
*Sema::LookupCopyingAssignment(CXXRecordDecl
*Class
,
3567 unsigned Quals
, bool RValueThis
,
3568 unsigned ThisQuals
) {
3569 assert(!(Quals
& ~(Qualifiers::Const
| Qualifiers::Volatile
)) &&
3570 "non-const, non-volatile qualifiers for copy assignment arg");
3571 assert(!(ThisQuals
& ~(Qualifiers::Const
| Qualifiers::Volatile
)) &&
3572 "non-const, non-volatile qualifiers for copy assignment this");
3573 SpecialMemberOverloadResult Result
= LookupSpecialMember(
3574 Class
, CXXSpecialMemberKind::CopyAssignment
, Quals
& Qualifiers::Const
,
3575 Quals
& Qualifiers::Volatile
, RValueThis
, ThisQuals
& Qualifiers::Const
,
3576 ThisQuals
& Qualifiers::Volatile
);
3578 return Result
.getMethod();
3581 CXXMethodDecl
*Sema::LookupMovingAssignment(CXXRecordDecl
*Class
,
3584 unsigned ThisQuals
) {
3585 assert(!(ThisQuals
& ~(Qualifiers::Const
| Qualifiers::Volatile
)) &&
3586 "non-const, non-volatile qualifiers for copy assignment this");
3587 SpecialMemberOverloadResult Result
= LookupSpecialMember(
3588 Class
, CXXSpecialMemberKind::MoveAssignment
, Quals
& Qualifiers::Const
,
3589 Quals
& Qualifiers::Volatile
, RValueThis
, ThisQuals
& Qualifiers::Const
,
3590 ThisQuals
& Qualifiers::Volatile
);
3592 return Result
.getMethod();
3595 CXXDestructorDecl
*Sema::LookupDestructor(CXXRecordDecl
*Class
) {
3596 return cast_or_null
<CXXDestructorDecl
>(
3597 LookupSpecialMember(Class
, CXXSpecialMemberKind::Destructor
, false, false,
3598 false, false, false)
3602 Sema::LiteralOperatorLookupResult
3603 Sema::LookupLiteralOperator(Scope
*S
, LookupResult
&R
,
3604 ArrayRef
<QualType
> ArgTys
, bool AllowRaw
,
3605 bool AllowTemplate
, bool AllowStringTemplatePack
,
3606 bool DiagnoseMissing
, StringLiteral
*StringLit
) {
3608 assert(R
.getResultKind() != LookupResult::Ambiguous
&&
3609 "literal operator lookup can't be ambiguous");
3611 // Filter the lookup results appropriately.
3612 LookupResult::Filter F
= R
.makeFilter();
3614 bool AllowCooked
= true;
3615 bool FoundRaw
= false;
3616 bool FoundTemplate
= false;
3617 bool FoundStringTemplatePack
= false;
3618 bool FoundCooked
= false;
3620 while (F
.hasNext()) {
3622 if (UsingShadowDecl
*USD
= dyn_cast
<UsingShadowDecl
>(D
))
3623 D
= USD
->getTargetDecl();
3625 // If the declaration we found is invalid, skip it.
3626 if (D
->isInvalidDecl()) {
3632 bool IsTemplate
= false;
3633 bool IsStringTemplatePack
= false;
3634 bool IsCooked
= false;
3636 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
3637 if (FD
->getNumParams() == 1 &&
3638 FD
->getParamDecl(0)->getType()->getAs
<PointerType
>())
3640 else if (FD
->getNumParams() == ArgTys
.size()) {
3642 for (unsigned ArgIdx
= 0; ArgIdx
!= ArgTys
.size(); ++ArgIdx
) {
3643 QualType ParamTy
= FD
->getParamDecl(ArgIdx
)->getType();
3644 if (!Context
.hasSameUnqualifiedType(ArgTys
[ArgIdx
], ParamTy
)) {
3651 if (FunctionTemplateDecl
*FD
= dyn_cast
<FunctionTemplateDecl
>(D
)) {
3652 TemplateParameterList
*Params
= FD
->getTemplateParameters();
3653 if (Params
->size() == 1) {
3655 if (!Params
->getParam(0)->isTemplateParameterPack() && !StringLit
) {
3656 // Implied but not stated: user-defined integer and floating literals
3657 // only ever use numeric literal operator templates, not templates
3658 // taking a parameter of class type.
3663 // A string literal template is only considered if the string literal
3664 // is a well-formed template argument for the template parameter.
3666 SFINAETrap
Trap(*this);
3667 SmallVector
<TemplateArgument
, 1> SugaredChecked
, CanonicalChecked
;
3668 TemplateArgumentLoc
Arg(TemplateArgument(StringLit
), StringLit
);
3669 if (CheckTemplateArgument(
3670 Params
->getParam(0), Arg
, FD
, R
.getNameLoc(), R
.getNameLoc(),
3671 0, SugaredChecked
, CanonicalChecked
, CTAK_Specified
) ||
3672 Trap
.hasErrorOccurred())
3676 IsStringTemplatePack
= true;
3680 if (AllowTemplate
&& StringLit
&& IsTemplate
) {
3681 FoundTemplate
= true;
3683 AllowCooked
= false;
3684 AllowStringTemplatePack
= false;
3685 if (FoundRaw
|| FoundCooked
|| FoundStringTemplatePack
) {
3687 FoundRaw
= FoundCooked
= FoundStringTemplatePack
= false;
3689 } else if (AllowCooked
&& IsCooked
) {
3692 AllowTemplate
= StringLit
;
3693 AllowStringTemplatePack
= false;
3694 if (FoundRaw
|| FoundTemplate
|| FoundStringTemplatePack
) {
3695 // Go through again and remove the raw and template decls we've
3698 FoundRaw
= FoundTemplate
= FoundStringTemplatePack
= false;
3700 } else if (AllowRaw
&& IsRaw
) {
3702 } else if (AllowTemplate
&& IsTemplate
) {
3703 FoundTemplate
= true;
3704 } else if (AllowStringTemplatePack
&& IsStringTemplatePack
) {
3705 FoundStringTemplatePack
= true;
3713 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3714 // form for string literal operator templates.
3715 if (StringLit
&& FoundTemplate
)
3716 return LOLR_Template
;
3718 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3719 // parameter type, that is used in preference to a raw literal operator
3720 // or literal operator template.
3724 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3725 // operator template, but not both.
3726 if (FoundRaw
&& FoundTemplate
) {
3727 Diag(R
.getNameLoc(), diag::err_ovl_ambiguous_call
) << R
.getLookupName();
3728 for (const NamedDecl
*D
: R
)
3729 NoteOverloadCandidate(D
, D
->getUnderlyingDecl()->getAsFunction());
3737 return LOLR_Template
;
3739 if (FoundStringTemplatePack
)
3740 return LOLR_StringTemplatePack
;
3742 // Didn't find anything we could use.
3743 if (DiagnoseMissing
) {
3744 Diag(R
.getNameLoc(), diag::err_ovl_no_viable_literal_operator
)
3745 << R
.getLookupName() << (int)ArgTys
.size() << ArgTys
[0]
3746 << (ArgTys
.size() == 2 ? ArgTys
[1] : QualType()) << AllowRaw
3747 << (AllowTemplate
|| AllowStringTemplatePack
);
3751 return LOLR_ErrorNoDiagnostic
;
3754 void ADLResult::insert(NamedDecl
*New
) {
3755 NamedDecl
*&Old
= Decls
[cast
<NamedDecl
>(New
->getCanonicalDecl())];
3757 // If we haven't yet seen a decl for this key, or the last decl
3758 // was exactly this one, we're done.
3759 if (Old
== nullptr || Old
== New
) {
3764 // Otherwise, decide which is a more recent redeclaration.
3765 FunctionDecl
*OldFD
= Old
->getAsFunction();
3766 FunctionDecl
*NewFD
= New
->getAsFunction();
3768 FunctionDecl
*Cursor
= NewFD
;
3770 Cursor
= Cursor
->getPreviousDecl();
3772 // If we got to the end without finding OldFD, OldFD is the newer
3773 // declaration; leave things as they are.
3774 if (!Cursor
) return;
3776 // If we do find OldFD, then NewFD is newer.
3777 if (Cursor
== OldFD
) break;
3779 // Otherwise, keep looking.
3785 void Sema::ArgumentDependentLookup(DeclarationName Name
, SourceLocation Loc
,
3786 ArrayRef
<Expr
*> Args
, ADLResult
&Result
) {
3787 // Find all of the associated namespaces and classes based on the
3788 // arguments we have.
3789 AssociatedNamespaceSet AssociatedNamespaces
;
3790 AssociatedClassSet AssociatedClasses
;
3791 FindAssociatedClassesAndNamespaces(Loc
, Args
,
3792 AssociatedNamespaces
,
3795 // C++ [basic.lookup.argdep]p3:
3796 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3797 // and let Y be the lookup set produced by argument dependent
3798 // lookup (defined as follows). If X contains [...] then Y is
3799 // empty. Otherwise Y is the set of declarations found in the
3800 // namespaces associated with the argument types as described
3801 // below. The set of declarations found by the lookup of the name
3802 // is the union of X and Y.
3804 // Here, we compute Y and add its members to the overloaded
3806 for (auto *NS
: AssociatedNamespaces
) {
3807 // When considering an associated namespace, the lookup is the
3808 // same as the lookup performed when the associated namespace is
3809 // used as a qualifier (3.4.3.2) except that:
3811 // -- Any using-directives in the associated namespace are
3814 // -- Any namespace-scope friend functions declared in
3815 // associated classes are visible within their respective
3816 // namespaces even if they are not visible during an ordinary
3819 // C++20 [basic.lookup.argdep] p4.3
3820 // -- are exported, are attached to a named module M, do not appear
3821 // in the translation unit containing the point of the lookup, and
3822 // have the same innermost enclosing non-inline namespace scope as
3823 // a declaration of an associated entity attached to M.
3824 DeclContext::lookup_result R
= NS
->lookup(Name
);
3826 auto *Underlying
= D
;
3827 if (auto *USD
= dyn_cast
<UsingShadowDecl
>(D
))
3828 Underlying
= USD
->getTargetDecl();
3830 if (!isa
<FunctionDecl
>(Underlying
) &&
3831 !isa
<FunctionTemplateDecl
>(Underlying
))
3834 // The declaration is visible to argument-dependent lookup if either
3835 // it's ordinarily visible or declared as a friend in an associated
3837 bool Visible
= false;
3838 for (D
= D
->getMostRecentDecl(); D
;
3839 D
= cast_or_null
<NamedDecl
>(D
->getPreviousDecl())) {
3840 if (D
->getIdentifierNamespace() & Decl::IDNS_Ordinary
) {
3846 if (!getLangOpts().CPlusPlusModules
)
3849 if (D
->isInExportDeclContext()) {
3850 Module
*FM
= D
->getOwningModule();
3851 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
3852 // exports are only valid in module purview and outside of any
3853 // PMF (although a PMF should not even be present in a module
3856 (FM
->isNamedModule() || FM
->isImplicitGlobalModule()) &&
3857 !FM
->isPrivateModule() && "bad export context");
3858 // .. are attached to a named module M, do not appear in the
3859 // translation unit containing the point of the lookup..
3860 if (D
->isInAnotherModuleUnit() &&
3861 llvm::any_of(AssociatedClasses
, [&](auto *E
) {
3862 // ... and have the same innermost enclosing non-inline
3863 // namespace scope as a declaration of an associated entity
3865 if (E
->getOwningModule() != FM
)
3867 // TODO: maybe this could be cached when generating the
3868 // associated namespaces / entities.
3869 DeclContext
*Ctx
= E
->getDeclContext();
3870 while (!Ctx
->isFileContext() || Ctx
->isInlineNamespace())
3871 Ctx
= Ctx
->getParent();
3878 } else if (D
->getFriendObjectKind()) {
3879 auto *RD
= cast
<CXXRecordDecl
>(D
->getLexicalDeclContext());
3880 // [basic.lookup.argdep]p4:
3881 // Argument-dependent lookup finds all declarations of functions and
3882 // function templates that
3884 // - are declared as a friend ([class.friend]) of any class with a
3885 // reachable definition in the set of associated entities,
3887 // FIXME: If there's a merged definition of D that is reachable, then
3888 // the friend declaration should be considered.
3889 if (AssociatedClasses
.count(RD
) && isReachable(D
)) {
3896 // FIXME: Preserve D as the FoundDecl.
3898 Result
.insert(Underlying
);
3903 //----------------------------------------------------------------------------
3904 // Search for all visible declarations.
3905 //----------------------------------------------------------------------------
3906 VisibleDeclConsumer::~VisibleDeclConsumer() { }
3908 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3912 class ShadowContextRAII
;
3914 class VisibleDeclsRecord
{
3916 /// An entry in the shadow map, which is optimized to store a
3917 /// single declaration (the common case) but can also store a list
3918 /// of declarations.
3919 typedef llvm::TinyPtrVector
<NamedDecl
*> ShadowMapEntry
;
3922 /// A mapping from declaration names to the declarations that have
3923 /// this name within a particular scope.
3924 typedef llvm::DenseMap
<DeclarationName
, ShadowMapEntry
> ShadowMap
;
3926 /// A list of shadow maps, which is used to model name hiding.
3927 std::list
<ShadowMap
> ShadowMaps
;
3929 /// The declaration contexts we have already visited.
3930 llvm::SmallPtrSet
<DeclContext
*, 8> VisitedContexts
;
3932 friend class ShadowContextRAII
;
3935 /// Determine whether we have already visited this context
3936 /// (and, if not, note that we are going to visit that context now).
3937 bool visitedContext(DeclContext
*Ctx
) {
3938 return !VisitedContexts
.insert(Ctx
).second
;
3941 bool alreadyVisitedContext(DeclContext
*Ctx
) {
3942 return VisitedContexts
.count(Ctx
);
3945 /// Determine whether the given declaration is hidden in the
3948 /// \returns the declaration that hides the given declaration, or
3949 /// NULL if no such declaration exists.
3950 NamedDecl
*checkHidden(NamedDecl
*ND
);
3952 /// Add a declaration to the current shadow map.
3953 void add(NamedDecl
*ND
) {
3954 ShadowMaps
.back()[ND
->getDeclName()].push_back(ND
);
3958 /// RAII object that records when we've entered a shadow context.
3959 class ShadowContextRAII
{
3960 VisibleDeclsRecord
&Visible
;
3962 typedef VisibleDeclsRecord::ShadowMap ShadowMap
;
3965 ShadowContextRAII(VisibleDeclsRecord
&Visible
) : Visible(Visible
) {
3966 Visible
.ShadowMaps
.emplace_back();
3969 ~ShadowContextRAII() {
3970 Visible
.ShadowMaps
.pop_back();
3974 } // end anonymous namespace
3976 NamedDecl
*VisibleDeclsRecord::checkHidden(NamedDecl
*ND
) {
3977 unsigned IDNS
= ND
->getIdentifierNamespace();
3978 std::list
<ShadowMap
>::reverse_iterator SM
= ShadowMaps
.rbegin();
3979 for (std::list
<ShadowMap
>::reverse_iterator SMEnd
= ShadowMaps
.rend();
3980 SM
!= SMEnd
; ++SM
) {
3981 ShadowMap::iterator Pos
= SM
->find(ND
->getDeclName());
3982 if (Pos
== SM
->end())
3985 for (auto *D
: Pos
->second
) {
3986 // A tag declaration does not hide a non-tag declaration.
3987 if (D
->hasTagIdentifierNamespace() &&
3988 (IDNS
& (Decl::IDNS_Member
| Decl::IDNS_Ordinary
|
3989 Decl::IDNS_ObjCProtocol
)))
3992 // Protocols are in distinct namespaces from everything else.
3993 if (((D
->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol
)
3994 || (IDNS
& Decl::IDNS_ObjCProtocol
)) &&
3995 D
->getIdentifierNamespace() != IDNS
)
3998 // Functions and function templates in the same scope overload
3999 // rather than hide. FIXME: Look for hiding based on function
4001 if (D
->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4002 ND
->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4003 SM
== ShadowMaps
.rbegin())
4006 // A shadow declaration that's created by a resolved using declaration
4007 // is not hidden by the same using declaration.
4008 if (isa
<UsingShadowDecl
>(ND
) && isa
<UsingDecl
>(D
) &&
4009 cast
<UsingShadowDecl
>(ND
)->getIntroducer() == D
)
4012 // We've found a declaration that hides this one.
4021 class LookupVisibleHelper
{
4023 LookupVisibleHelper(VisibleDeclConsumer
&Consumer
, bool IncludeDependentBases
,
4025 : Consumer(Consumer
), IncludeDependentBases(IncludeDependentBases
),
4026 LoadExternal(LoadExternal
) {}
4028 void lookupVisibleDecls(Sema
&SemaRef
, Scope
*S
, Sema::LookupNameKind Kind
,
4029 bool IncludeGlobalScope
) {
4030 // Determine the set of using directives available during
4031 // unqualified name lookup.
4033 UnqualUsingDirectiveSet
UDirs(SemaRef
);
4034 if (SemaRef
.getLangOpts().CPlusPlus
) {
4035 // Find the first namespace or translation-unit scope.
4036 while (S
&& !isNamespaceOrTranslationUnitScope(S
))
4039 UDirs
.visitScopeChain(Initial
, S
);
4043 // Look for visible declarations.
4044 LookupResult
Result(SemaRef
, DeclarationName(), SourceLocation(), Kind
);
4045 Result
.setAllowHidden(Consumer
.includeHiddenDecls());
4046 if (!IncludeGlobalScope
)
4047 Visited
.visitedContext(SemaRef
.getASTContext().getTranslationUnitDecl());
4048 ShadowContextRAII
Shadow(Visited
);
4049 lookupInScope(Initial
, Result
, UDirs
);
4052 void lookupVisibleDecls(Sema
&SemaRef
, DeclContext
*Ctx
,
4053 Sema::LookupNameKind Kind
, bool IncludeGlobalScope
) {
4054 LookupResult
Result(SemaRef
, DeclarationName(), SourceLocation(), Kind
);
4055 Result
.setAllowHidden(Consumer
.includeHiddenDecls());
4056 if (!IncludeGlobalScope
)
4057 Visited
.visitedContext(SemaRef
.getASTContext().getTranslationUnitDecl());
4059 ShadowContextRAII
Shadow(Visited
);
4060 lookupInDeclContext(Ctx
, Result
, /*QualifiedNameLookup=*/true,
4061 /*InBaseClass=*/false);
4065 void lookupInDeclContext(DeclContext
*Ctx
, LookupResult
&Result
,
4066 bool QualifiedNameLookup
, bool InBaseClass
) {
4070 // Make sure we don't visit the same context twice.
4071 if (Visited
.visitedContext(Ctx
->getPrimaryContext()))
4074 Consumer
.EnteredContext(Ctx
);
4076 // Outside C++, lookup results for the TU live on identifiers.
4077 if (isa
<TranslationUnitDecl
>(Ctx
) &&
4078 !Result
.getSema().getLangOpts().CPlusPlus
) {
4079 auto &S
= Result
.getSema();
4080 auto &Idents
= S
.Context
.Idents
;
4082 // Ensure all external identifiers are in the identifier table.
4084 if (IdentifierInfoLookup
*External
=
4085 Idents
.getExternalIdentifierLookup()) {
4086 std::unique_ptr
<IdentifierIterator
> Iter(External
->getIdentifiers());
4087 for (StringRef Name
= Iter
->Next(); !Name
.empty();
4088 Name
= Iter
->Next())
4092 // Walk all lookup results in the TU for each identifier.
4093 for (const auto &Ident
: Idents
) {
4094 for (auto I
= S
.IdResolver
.begin(Ident
.getValue()),
4095 E
= S
.IdResolver
.end();
4097 if (S
.IdResolver
.isDeclInScope(*I
, Ctx
)) {
4098 if (NamedDecl
*ND
= Result
.getAcceptableDecl(*I
)) {
4099 Consumer
.FoundDecl(ND
, Visited
.checkHidden(ND
), Ctx
, InBaseClass
);
4109 if (CXXRecordDecl
*Class
= dyn_cast
<CXXRecordDecl
>(Ctx
))
4110 Result
.getSema().ForceDeclarationOfImplicitMembers(Class
);
4112 llvm::SmallVector
<NamedDecl
*, 4> DeclsToVisit
;
4113 // We sometimes skip loading namespace-level results (they tend to be huge).
4114 bool Load
= LoadExternal
||
4115 !(isa
<TranslationUnitDecl
>(Ctx
) || isa
<NamespaceDecl
>(Ctx
));
4116 // Enumerate all of the results in this context.
4117 for (DeclContextLookupResult R
:
4118 Load
? Ctx
->lookups()
4119 : Ctx
->noload_lookups(/*PreserveInternalState=*/false))
4121 // Rather than visit immediately, we put ND into a vector and visit
4122 // all decls, in order, outside of this loop. The reason is that
4123 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)
4124 // may invalidate the iterators used in the two
4126 DeclsToVisit
.push_back(D
);
4128 for (auto *D
: DeclsToVisit
)
4129 if (auto *ND
= Result
.getAcceptableDecl(D
)) {
4130 Consumer
.FoundDecl(ND
, Visited
.checkHidden(ND
), Ctx
, InBaseClass
);
4134 DeclsToVisit
.clear();
4136 // Traverse using directives for qualified name lookup.
4137 if (QualifiedNameLookup
) {
4138 ShadowContextRAII
Shadow(Visited
);
4139 for (auto *I
: Ctx
->using_directives()) {
4140 if (!Result
.getSema().isVisible(I
))
4142 lookupInDeclContext(I
->getNominatedNamespace(), Result
,
4143 QualifiedNameLookup
, InBaseClass
);
4147 // Traverse the contexts of inherited C++ classes.
4148 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Ctx
)) {
4149 if (!Record
->hasDefinition())
4152 for (const auto &B
: Record
->bases()) {
4153 QualType BaseType
= B
.getType();
4156 if (BaseType
->isDependentType()) {
4157 if (!IncludeDependentBases
) {
4158 // Don't look into dependent bases, because name lookup can't look
4162 const auto *TST
= BaseType
->getAs
<TemplateSpecializationType
>();
4165 TemplateName TN
= TST
->getTemplateName();
4167 dyn_cast_or_null
<ClassTemplateDecl
>(TN
.getAsTemplateDecl());
4170 RD
= TD
->getTemplatedDecl();
4172 const auto *Record
= BaseType
->getAs
<RecordType
>();
4175 RD
= Record
->getDecl();
4178 // FIXME: It would be nice to be able to determine whether referencing
4179 // a particular member would be ambiguous. For example, given
4181 // struct A { int member; };
4182 // struct B { int member; };
4183 // struct C : A, B { };
4185 // void f(C *c) { c->### }
4187 // accessing 'member' would result in an ambiguity. However, we
4188 // could be smart enough to qualify the member with the base
4197 // Find results in this base class (and its bases).
4198 ShadowContextRAII
Shadow(Visited
);
4199 lookupInDeclContext(RD
, Result
, QualifiedNameLookup
,
4200 /*InBaseClass=*/true);
4204 // Traverse the contexts of Objective-C classes.
4205 if (ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(Ctx
)) {
4206 // Traverse categories.
4207 for (auto *Cat
: IFace
->visible_categories()) {
4208 ShadowContextRAII
Shadow(Visited
);
4209 lookupInDeclContext(Cat
, Result
, QualifiedNameLookup
,
4210 /*InBaseClass=*/false);
4213 // Traverse protocols.
4214 for (auto *I
: IFace
->all_referenced_protocols()) {
4215 ShadowContextRAII
Shadow(Visited
);
4216 lookupInDeclContext(I
, Result
, QualifiedNameLookup
,
4217 /*InBaseClass=*/false);
4220 // Traverse the superclass.
4221 if (IFace
->getSuperClass()) {
4222 ShadowContextRAII
Shadow(Visited
);
4223 lookupInDeclContext(IFace
->getSuperClass(), Result
, QualifiedNameLookup
,
4224 /*InBaseClass=*/true);
4227 // If there is an implementation, traverse it. We do this to find
4228 // synthesized ivars.
4229 if (IFace
->getImplementation()) {
4230 ShadowContextRAII
Shadow(Visited
);
4231 lookupInDeclContext(IFace
->getImplementation(), Result
,
4232 QualifiedNameLookup
, InBaseClass
);
4234 } else if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Ctx
)) {
4235 for (auto *I
: Protocol
->protocols()) {
4236 ShadowContextRAII
Shadow(Visited
);
4237 lookupInDeclContext(I
, Result
, QualifiedNameLookup
,
4238 /*InBaseClass=*/false);
4240 } else if (ObjCCategoryDecl
*Category
= dyn_cast
<ObjCCategoryDecl
>(Ctx
)) {
4241 for (auto *I
: Category
->protocols()) {
4242 ShadowContextRAII
Shadow(Visited
);
4243 lookupInDeclContext(I
, Result
, QualifiedNameLookup
,
4244 /*InBaseClass=*/false);
4247 // If there is an implementation, traverse it.
4248 if (Category
->getImplementation()) {
4249 ShadowContextRAII
Shadow(Visited
);
4250 lookupInDeclContext(Category
->getImplementation(), Result
,
4251 QualifiedNameLookup
, /*InBaseClass=*/true);
4256 void lookupInScope(Scope
*S
, LookupResult
&Result
,
4257 UnqualUsingDirectiveSet
&UDirs
) {
4258 // No clients run in this mode and it's not supported. Please add tests and
4259 // remove the assertion if you start relying on it.
4260 assert(!IncludeDependentBases
&& "Unsupported flag for lookupInScope");
4265 if (!S
->getEntity() ||
4266 (!S
->getParent() && !Visited
.alreadyVisitedContext(S
->getEntity())) ||
4267 (S
->getEntity())->isFunctionOrMethod()) {
4268 FindLocalExternScope
FindLocals(Result
);
4269 // Walk through the declarations in this Scope. The consumer might add new
4270 // decls to the scope as part of deserialization, so make a copy first.
4271 SmallVector
<Decl
*, 8> ScopeDecls(S
->decls().begin(), S
->decls().end());
4272 for (Decl
*D
: ScopeDecls
) {
4273 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(D
))
4274 if ((ND
= Result
.getAcceptableDecl(ND
))) {
4275 Consumer
.FoundDecl(ND
, Visited
.checkHidden(ND
), nullptr, false);
4281 DeclContext
*Entity
= S
->getLookupEntity();
4283 // Look into this scope's declaration context, along with any of its
4284 // parent lookup contexts (e.g., enclosing classes), up to the point
4285 // where we hit the context stored in the next outer scope.
4286 DeclContext
*OuterCtx
= findOuterContext(S
);
4288 for (DeclContext
*Ctx
= Entity
; Ctx
&& !Ctx
->Equals(OuterCtx
);
4289 Ctx
= Ctx
->getLookupParent()) {
4290 if (ObjCMethodDecl
*Method
= dyn_cast
<ObjCMethodDecl
>(Ctx
)) {
4291 if (Method
->isInstanceMethod()) {
4292 // For instance methods, look for ivars in the method's interface.
4293 LookupResult
IvarResult(Result
.getSema(), Result
.getLookupName(),
4294 Result
.getNameLoc(),
4295 Sema::LookupMemberName
);
4296 if (ObjCInterfaceDecl
*IFace
= Method
->getClassInterface()) {
4297 lookupInDeclContext(IFace
, IvarResult
,
4298 /*QualifiedNameLookup=*/false,
4299 /*InBaseClass=*/false);
4303 // We've already performed all of the name lookup that we need
4304 // to for Objective-C methods; the next context will be the
4309 if (Ctx
->isFunctionOrMethod())
4312 lookupInDeclContext(Ctx
, Result
, /*QualifiedNameLookup=*/false,
4313 /*InBaseClass=*/false);
4315 } else if (!S
->getParent()) {
4316 // Look into the translation unit scope. We walk through the translation
4317 // unit's declaration context, because the Scope itself won't have all of
4318 // the declarations if we loaded a precompiled header.
4319 // FIXME: We would like the translation unit's Scope object to point to
4320 // the translation unit, so we don't need this special "if" branch.
4321 // However, doing so would force the normal C++ name-lookup code to look
4322 // into the translation unit decl when the IdentifierInfo chains would
4323 // suffice. Once we fix that problem (which is part of a more general
4324 // "don't look in DeclContexts unless we have to" optimization), we can
4326 Entity
= Result
.getSema().Context
.getTranslationUnitDecl();
4327 lookupInDeclContext(Entity
, Result
, /*QualifiedNameLookup=*/false,
4328 /*InBaseClass=*/false);
4332 // Lookup visible declarations in any namespaces found by using
4334 for (const UnqualUsingEntry
&UUE
: UDirs
.getNamespacesFor(Entity
))
4335 lookupInDeclContext(
4336 const_cast<DeclContext
*>(UUE
.getNominatedNamespace()), Result
,
4337 /*QualifiedNameLookup=*/false,
4338 /*InBaseClass=*/false);
4341 // Lookup names in the parent scope.
4342 ShadowContextRAII
Shadow(Visited
);
4343 lookupInScope(S
->getParent(), Result
, UDirs
);
4347 VisibleDeclsRecord Visited
;
4348 VisibleDeclConsumer
&Consumer
;
4349 bool IncludeDependentBases
;
4354 void Sema::LookupVisibleDecls(Scope
*S
, LookupNameKind Kind
,
4355 VisibleDeclConsumer
&Consumer
,
4356 bool IncludeGlobalScope
, bool LoadExternal
) {
4357 LookupVisibleHelper
H(Consumer
, /*IncludeDependentBases=*/false,
4359 H
.lookupVisibleDecls(*this, S
, Kind
, IncludeGlobalScope
);
4362 void Sema::LookupVisibleDecls(DeclContext
*Ctx
, LookupNameKind Kind
,
4363 VisibleDeclConsumer
&Consumer
,
4364 bool IncludeGlobalScope
,
4365 bool IncludeDependentBases
, bool LoadExternal
) {
4366 LookupVisibleHelper
H(Consumer
, IncludeDependentBases
, LoadExternal
);
4367 H
.lookupVisibleDecls(*this, Ctx
, Kind
, IncludeGlobalScope
);
4370 LabelDecl
*Sema::LookupOrCreateLabel(IdentifierInfo
*II
, SourceLocation Loc
,
4371 SourceLocation GnuLabelLoc
) {
4372 // Do a lookup to see if we have a label with this name already.
4373 NamedDecl
*Res
= nullptr;
4375 if (GnuLabelLoc
.isValid()) {
4376 // Local label definitions always shadow existing labels.
4377 Res
= LabelDecl::Create(Context
, CurContext
, Loc
, II
, GnuLabelLoc
);
4378 Scope
*S
= CurScope
;
4379 PushOnScopeChains(Res
, S
, true);
4380 return cast
<LabelDecl
>(Res
);
4383 // Not a GNU local label.
4384 Res
= LookupSingleName(CurScope
, II
, Loc
, LookupLabel
,
4385 RedeclarationKind::NotForRedeclaration
);
4386 // If we found a label, check to see if it is in the same context as us.
4387 // When in a Block, we don't want to reuse a label in an enclosing function.
4388 if (Res
&& Res
->getDeclContext() != CurContext
)
4391 // If not forward referenced or defined already, create the backing decl.
4392 Res
= LabelDecl::Create(Context
, CurContext
, Loc
, II
);
4393 Scope
*S
= CurScope
->getFnParent();
4394 assert(S
&& "Not in a function?");
4395 PushOnScopeChains(Res
, S
, true);
4397 return cast
<LabelDecl
>(Res
);
4400 //===----------------------------------------------------------------------===//
4402 //===----------------------------------------------------------------------===//
4404 static bool isCandidateViable(CorrectionCandidateCallback
&CCC
,
4405 TypoCorrection
&Candidate
) {
4406 Candidate
.setCallbackDistance(CCC
.RankCandidate(Candidate
));
4407 return Candidate
.getEditDistance(false) != TypoCorrection::InvalidDistance
;
4410 static void LookupPotentialTypoResult(Sema
&SemaRef
,
4412 IdentifierInfo
*Name
,
4413 Scope
*S
, CXXScopeSpec
*SS
,
4414 DeclContext
*MemberContext
,
4415 bool EnteringContext
,
4416 bool isObjCIvarLookup
,
4419 /// Check whether the declarations found for a typo correction are
4420 /// visible. Set the correction's RequiresImport flag to true if none of the
4421 /// declarations are visible, false otherwise.
4422 static void checkCorrectionVisibility(Sema
&SemaRef
, TypoCorrection
&TC
) {
4423 TypoCorrection::decl_iterator DI
= TC
.begin(), DE
= TC
.end();
4425 for (/**/; DI
!= DE
; ++DI
)
4426 if (!LookupResult::isVisible(SemaRef
, *DI
))
4428 // No filtering needed if all decls are visible.
4430 TC
.setRequiresImport(false);
4434 llvm::SmallVector
<NamedDecl
*, 4> NewDecls(TC
.begin(), DI
);
4435 bool AnyVisibleDecls
= !NewDecls
.empty();
4437 for (/**/; DI
!= DE
; ++DI
) {
4438 if (LookupResult::isVisible(SemaRef
, *DI
)) {
4439 if (!AnyVisibleDecls
) {
4440 // Found a visible decl, discard all hidden ones.
4441 AnyVisibleDecls
= true;
4444 NewDecls
.push_back(*DI
);
4445 } else if (!AnyVisibleDecls
&& !(*DI
)->isModulePrivate())
4446 NewDecls
.push_back(*DI
);
4449 if (NewDecls
.empty())
4450 TC
= TypoCorrection();
4452 TC
.setCorrectionDecls(NewDecls
);
4453 TC
.setRequiresImport(!AnyVisibleDecls
);
4457 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
4458 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4459 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4460 static void getNestedNameSpecifierIdentifiers(
4461 NestedNameSpecifier
*NNS
,
4462 SmallVectorImpl
<const IdentifierInfo
*> &Identifiers
) {
4463 if (NestedNameSpecifier
*Prefix
= NNS
->getPrefix())
4464 getNestedNameSpecifierIdentifiers(Prefix
, Identifiers
);
4466 Identifiers
.clear();
4468 const IdentifierInfo
*II
= nullptr;
4470 switch (NNS
->getKind()) {
4471 case NestedNameSpecifier::Identifier
:
4472 II
= NNS
->getAsIdentifier();
4475 case NestedNameSpecifier::Namespace
:
4476 if (NNS
->getAsNamespace()->isAnonymousNamespace())
4478 II
= NNS
->getAsNamespace()->getIdentifier();
4481 case NestedNameSpecifier::NamespaceAlias
:
4482 II
= NNS
->getAsNamespaceAlias()->getIdentifier();
4485 case NestedNameSpecifier::TypeSpecWithTemplate
:
4486 case NestedNameSpecifier::TypeSpec
:
4487 II
= QualType(NNS
->getAsType(), 0).getBaseTypeIdentifier();
4490 case NestedNameSpecifier::Global
:
4491 case NestedNameSpecifier::Super
:
4496 Identifiers
.push_back(II
);
4499 void TypoCorrectionConsumer::FoundDecl(NamedDecl
*ND
, NamedDecl
*Hiding
,
4500 DeclContext
*Ctx
, bool InBaseClass
) {
4501 // Don't consider hidden names for typo correction.
4505 // Only consider entities with identifiers for names, ignoring
4506 // special names (constructors, overloaded operators, selectors,
4508 IdentifierInfo
*Name
= ND
->getIdentifier();
4512 // Only consider visible declarations and declarations from modules with
4513 // names that exactly match.
4514 if (!LookupResult::isVisible(SemaRef
, ND
) && Name
!= Typo
)
4517 FoundName(Name
->getName());
4520 void TypoCorrectionConsumer::FoundName(StringRef Name
) {
4521 // Compute the edit distance between the typo and the name of this
4522 // entity, and add the identifier to the list of results.
4523 addName(Name
, nullptr);
4526 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword
) {
4527 // Compute the edit distance between the typo and this keyword,
4528 // and add the keyword to the list of results.
4529 addName(Keyword
, nullptr, nullptr, true);
4532 void TypoCorrectionConsumer::addName(StringRef Name
, NamedDecl
*ND
,
4533 NestedNameSpecifier
*NNS
, bool isKeyword
) {
4534 // Use a simple length-based heuristic to determine the minimum possible
4535 // edit distance. If the minimum isn't good enough, bail out early.
4536 StringRef TypoStr
= Typo
->getName();
4537 unsigned MinED
= abs((int)Name
.size() - (int)TypoStr
.size());
4538 if (MinED
&& TypoStr
.size() / MinED
< 3)
4541 // Compute an upper bound on the allowable edit distance, so that the
4542 // edit-distance algorithm can short-circuit.
4543 unsigned UpperBound
= (TypoStr
.size() + 2) / 3;
4544 unsigned ED
= TypoStr
.edit_distance(Name
, true, UpperBound
);
4545 if (ED
> UpperBound
) return;
4547 TypoCorrection
TC(&SemaRef
.Context
.Idents
.get(Name
), ND
, NNS
, ED
);
4548 if (isKeyword
) TC
.makeKeyword();
4549 TC
.setCorrectionRange(nullptr, Result
.getLookupNameInfo());
4553 static const unsigned MaxTypoDistanceResultSets
= 5;
4555 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction
) {
4556 StringRef TypoStr
= Typo
->getName();
4557 StringRef Name
= Correction
.getCorrectionAsIdentifierInfo()->getName();
4559 // For very short typos, ignore potential corrections that have a different
4560 // base identifier from the typo or which have a normalized edit distance
4561 // longer than the typo itself.
4562 if (TypoStr
.size() < 3 &&
4563 (Name
!= TypoStr
|| Correction
.getEditDistance(true) > TypoStr
.size()))
4566 // If the correction is resolved but is not viable, ignore it.
4567 if (Correction
.isResolved()) {
4568 checkCorrectionVisibility(SemaRef
, Correction
);
4569 if (!Correction
|| !isCandidateViable(*CorrectionValidator
, Correction
))
4573 TypoResultList
&CList
=
4574 CorrectionResults
[Correction
.getEditDistance(false)][Name
];
4576 if (!CList
.empty() && !CList
.back().isResolved())
4578 if (NamedDecl
*NewND
= Correction
.getCorrectionDecl()) {
4579 auto RI
= llvm::find_if(CList
, [NewND
](const TypoCorrection
&TypoCorr
) {
4580 return TypoCorr
.getCorrectionDecl() == NewND
;
4582 if (RI
!= CList
.end()) {
4583 // The Correction refers to a decl already in the list. No insertion is
4584 // necessary and all further cases will return.
4586 auto IsDeprecated
= [](Decl
*D
) {
4588 if (D
->isDeprecated())
4590 D
= llvm::dyn_cast_or_null
<NamespaceDecl
>(D
->getDeclContext());
4595 // Prefer non deprecated Corrections over deprecated and only then
4596 // sort using an alphabetical order.
4597 std::pair
<bool, std::string
> NewKey
= {
4598 IsDeprecated(Correction
.getFoundDecl()),
4599 Correction
.getAsString(SemaRef
.getLangOpts())};
4601 std::pair
<bool, std::string
> PrevKey
= {
4602 IsDeprecated(RI
->getFoundDecl()),
4603 RI
->getAsString(SemaRef
.getLangOpts())};
4605 if (NewKey
< PrevKey
)
4610 if (CList
.empty() || Correction
.isResolved())
4611 CList
.push_back(Correction
);
4613 while (CorrectionResults
.size() > MaxTypoDistanceResultSets
)
4614 CorrectionResults
.erase(std::prev(CorrectionResults
.end()));
4617 void TypoCorrectionConsumer::addNamespaces(
4618 const llvm::MapVector
<NamespaceDecl
*, bool> &KnownNamespaces
) {
4619 SearchNamespaces
= true;
4621 for (auto KNPair
: KnownNamespaces
)
4622 Namespaces
.addNameSpecifier(KNPair
.first
);
4624 bool SSIsTemplate
= false;
4625 if (NestedNameSpecifier
*NNS
=
4626 (SS
&& SS
->isValid()) ? SS
->getScopeRep() : nullptr) {
4627 if (const Type
*T
= NNS
->getAsType())
4628 SSIsTemplate
= T
->getTypeClass() == Type::TemplateSpecialization
;
4630 // Do not transform this into an iterator-based loop. The loop body can
4631 // trigger the creation of further types (through lazy deserialization) and
4632 // invalid iterators into this list.
4633 auto &Types
= SemaRef
.getASTContext().getTypes();
4634 for (unsigned I
= 0; I
!= Types
.size(); ++I
) {
4635 const auto *TI
= Types
[I
];
4636 if (CXXRecordDecl
*CD
= TI
->getAsCXXRecordDecl()) {
4637 CD
= CD
->getCanonicalDecl();
4638 if (!CD
->isDependentType() && !CD
->isAnonymousStructOrUnion() &&
4639 !CD
->isUnion() && CD
->getIdentifier() &&
4640 (SSIsTemplate
|| !isa
<ClassTemplateSpecializationDecl
>(CD
)) &&
4641 (CD
->isBeingDefined() || CD
->isCompleteDefinition()))
4642 Namespaces
.addNameSpecifier(CD
);
4647 const TypoCorrection
&TypoCorrectionConsumer::getNextCorrection() {
4648 if (++CurrentTCIndex
< ValidatedCorrections
.size())
4649 return ValidatedCorrections
[CurrentTCIndex
];
4651 CurrentTCIndex
= ValidatedCorrections
.size();
4652 while (!CorrectionResults
.empty()) {
4653 auto DI
= CorrectionResults
.begin();
4654 if (DI
->second
.empty()) {
4655 CorrectionResults
.erase(DI
);
4659 auto RI
= DI
->second
.begin();
4660 if (RI
->second
.empty()) {
4661 DI
->second
.erase(RI
);
4662 performQualifiedLookups();
4666 TypoCorrection TC
= RI
->second
.pop_back_val();
4667 if (TC
.isResolved() || TC
.requiresImport() || resolveCorrection(TC
)) {
4668 ValidatedCorrections
.push_back(TC
);
4669 return ValidatedCorrections
[CurrentTCIndex
];
4672 return ValidatedCorrections
[0]; // The empty correction.
4675 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection
&Candidate
) {
4676 IdentifierInfo
*Name
= Candidate
.getCorrectionAsIdentifierInfo();
4677 DeclContext
*TempMemberContext
= MemberContext
;
4678 CXXScopeSpec
*TempSS
= SS
.get();
4680 LookupPotentialTypoResult(SemaRef
, Result
, Name
, S
, TempSS
, TempMemberContext
,
4682 CorrectionValidator
->IsObjCIvarLookup
,
4683 Name
== Typo
&& !Candidate
.WillReplaceSpecifier());
4684 switch (Result
.getResultKind()) {
4685 case LookupResult::NotFound
:
4686 case LookupResult::NotFoundInCurrentInstantiation
:
4687 case LookupResult::FoundUnresolvedValue
:
4689 // Immediately retry the lookup without the given CXXScopeSpec
4691 Candidate
.WillReplaceSpecifier(true);
4694 if (TempMemberContext
) {
4697 TempMemberContext
= nullptr;
4700 if (SearchNamespaces
)
4701 QualifiedResults
.push_back(Candidate
);
4704 case LookupResult::Ambiguous
:
4705 // We don't deal with ambiguities.
4708 case LookupResult::Found
:
4709 case LookupResult::FoundOverloaded
:
4710 // Store all of the Decls for overloaded symbols
4711 for (auto *TRD
: Result
)
4712 Candidate
.addCorrectionDecl(TRD
);
4713 checkCorrectionVisibility(SemaRef
, Candidate
);
4714 if (!isCandidateViable(*CorrectionValidator
, Candidate
)) {
4715 if (SearchNamespaces
)
4716 QualifiedResults
.push_back(Candidate
);
4719 Candidate
.setCorrectionRange(SS
.get(), Result
.getLookupNameInfo());
4725 void TypoCorrectionConsumer::performQualifiedLookups() {
4726 unsigned TypoLen
= Typo
->getName().size();
4727 for (const TypoCorrection
&QR
: QualifiedResults
) {
4728 for (const auto &NSI
: Namespaces
) {
4729 DeclContext
*Ctx
= NSI
.DeclCtx
;
4730 const Type
*NSType
= NSI
.NameSpecifier
->getAsType();
4732 // If the current NestedNameSpecifier refers to a class and the
4733 // current correction candidate is the name of that class, then skip
4734 // it as it is unlikely a qualified version of the class' constructor
4735 // is an appropriate correction.
4736 if (CXXRecordDecl
*NSDecl
= NSType
? NSType
->getAsCXXRecordDecl() :
4738 if (NSDecl
->getIdentifier() == QR
.getCorrectionAsIdentifierInfo())
4742 TypoCorrection
TC(QR
);
4743 TC
.ClearCorrectionDecls();
4744 TC
.setCorrectionSpecifier(NSI
.NameSpecifier
);
4745 TC
.setQualifierDistance(NSI
.EditDistance
);
4746 TC
.setCallbackDistance(0); // Reset the callback distance
4748 // If the current correction candidate and namespace combination are
4749 // too far away from the original typo based on the normalized edit
4750 // distance, then skip performing a qualified name lookup.
4751 unsigned TmpED
= TC
.getEditDistance(true);
4752 if (QR
.getCorrectionAsIdentifierInfo() != Typo
&& TmpED
&&
4753 TypoLen
/ TmpED
< 3)
4757 Result
.setLookupName(QR
.getCorrectionAsIdentifierInfo());
4758 if (!SemaRef
.LookupQualifiedName(Result
, Ctx
))
4761 // Any corrections added below will be validated in subsequent
4762 // iterations of the main while() loop over the Consumer's contents.
4763 switch (Result
.getResultKind()) {
4764 case LookupResult::Found
:
4765 case LookupResult::FoundOverloaded
: {
4766 if (SS
&& SS
->isValid()) {
4767 std::string NewQualified
= TC
.getAsString(SemaRef
.getLangOpts());
4768 std::string OldQualified
;
4769 llvm::raw_string_ostream
OldOStream(OldQualified
);
4770 SS
->getScopeRep()->print(OldOStream
, SemaRef
.getPrintingPolicy());
4771 OldOStream
<< Typo
->getName();
4772 // If correction candidate would be an identical written qualified
4773 // identifier, then the existing CXXScopeSpec probably included a
4774 // typedef that didn't get accounted for properly.
4775 if (OldOStream
.str() == NewQualified
)
4778 for (LookupResult::iterator TRD
= Result
.begin(), TRDEnd
= Result
.end();
4779 TRD
!= TRDEnd
; ++TRD
) {
4780 if (SemaRef
.CheckMemberAccess(TC
.getCorrectionRange().getBegin(),
4781 NSType
? NSType
->getAsCXXRecordDecl()
4783 TRD
.getPair()) == Sema::AR_accessible
)
4784 TC
.addCorrectionDecl(*TRD
);
4786 if (TC
.isResolved()) {
4787 TC
.setCorrectionRange(SS
.get(), Result
.getLookupNameInfo());
4792 case LookupResult::NotFound
:
4793 case LookupResult::NotFoundInCurrentInstantiation
:
4794 case LookupResult::Ambiguous
:
4795 case LookupResult::FoundUnresolvedValue
:
4800 QualifiedResults
.clear();
4803 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4804 ASTContext
&Context
, DeclContext
*CurContext
, CXXScopeSpec
*CurScopeSpec
)
4805 : Context(Context
), CurContextChain(buildContextChain(CurContext
)) {
4806 if (NestedNameSpecifier
*NNS
=
4807 CurScopeSpec
? CurScopeSpec
->getScopeRep() : nullptr) {
4808 llvm::raw_string_ostream
SpecifierOStream(CurNameSpecifier
);
4809 NNS
->print(SpecifierOStream
, Context
.getPrintingPolicy());
4811 getNestedNameSpecifierIdentifiers(NNS
, CurNameSpecifierIdentifiers
);
4813 // Build the list of identifiers that would be used for an absolute
4814 // (from the global context) NestedNameSpecifier referring to the current
4816 for (DeclContext
*C
: llvm::reverse(CurContextChain
)) {
4817 if (auto *ND
= dyn_cast_or_null
<NamespaceDecl
>(C
))
4818 CurContextIdentifiers
.push_back(ND
->getIdentifier());
4821 // Add the global context as a NestedNameSpecifier
4822 SpecifierInfo SI
= {cast
<DeclContext
>(Context
.getTranslationUnitDecl()),
4823 NestedNameSpecifier::GlobalSpecifier(Context
), 1};
4824 DistanceMap
[1].push_back(SI
);
4827 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4828 DeclContext
*Start
) -> DeclContextList
{
4829 assert(Start
&& "Building a context chain from a null context");
4830 DeclContextList Chain
;
4831 for (DeclContext
*DC
= Start
->getPrimaryContext(); DC
!= nullptr;
4832 DC
= DC
->getLookupParent()) {
4833 NamespaceDecl
*ND
= dyn_cast_or_null
<NamespaceDecl
>(DC
);
4834 if (!DC
->isInlineNamespace() && !DC
->isTransparentContext() &&
4835 !(ND
&& ND
->isAnonymousNamespace()))
4836 Chain
.push_back(DC
->getPrimaryContext());
4842 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4843 DeclContextList
&DeclChain
, NestedNameSpecifier
*&NNS
) {
4844 unsigned NumSpecifiers
= 0;
4845 for (DeclContext
*C
: llvm::reverse(DeclChain
)) {
4846 if (auto *ND
= dyn_cast_or_null
<NamespaceDecl
>(C
)) {
4847 NNS
= NestedNameSpecifier::Create(Context
, NNS
, ND
);
4849 } else if (auto *RD
= dyn_cast_or_null
<RecordDecl
>(C
)) {
4850 NNS
= NestedNameSpecifier::Create(Context
, NNS
, RD
->isTemplateDecl(),
4851 RD
->getTypeForDecl());
4855 return NumSpecifiers
;
4858 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4860 NestedNameSpecifier
*NNS
= nullptr;
4861 unsigned NumSpecifiers
= 0;
4862 DeclContextList
NamespaceDeclChain(buildContextChain(Ctx
));
4863 DeclContextList
FullNamespaceDeclChain(NamespaceDeclChain
);
4865 // Eliminate common elements from the two DeclContext chains.
4866 for (DeclContext
*C
: llvm::reverse(CurContextChain
)) {
4867 if (NamespaceDeclChain
.empty() || NamespaceDeclChain
.back() != C
)
4869 NamespaceDeclChain
.pop_back();
4872 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4873 NumSpecifiers
= buildNestedNameSpecifier(NamespaceDeclChain
, NNS
);
4875 // Add an explicit leading '::' specifier if needed.
4876 if (NamespaceDeclChain
.empty()) {
4877 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4878 NNS
= NestedNameSpecifier::GlobalSpecifier(Context
);
4880 buildNestedNameSpecifier(FullNamespaceDeclChain
, NNS
);
4881 } else if (NamedDecl
*ND
=
4882 dyn_cast_or_null
<NamedDecl
>(NamespaceDeclChain
.back())) {
4883 IdentifierInfo
*Name
= ND
->getIdentifier();
4884 bool SameNameSpecifier
= false;
4885 if (llvm::is_contained(CurNameSpecifierIdentifiers
, Name
)) {
4886 std::string NewNameSpecifier
;
4887 llvm::raw_string_ostream
SpecifierOStream(NewNameSpecifier
);
4888 SmallVector
<const IdentifierInfo
*, 4> NewNameSpecifierIdentifiers
;
4889 getNestedNameSpecifierIdentifiers(NNS
, NewNameSpecifierIdentifiers
);
4890 NNS
->print(SpecifierOStream
, Context
.getPrintingPolicy());
4891 SameNameSpecifier
= NewNameSpecifier
== CurNameSpecifier
;
4893 if (SameNameSpecifier
|| llvm::is_contained(CurContextIdentifiers
, Name
)) {
4894 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4895 NNS
= NestedNameSpecifier::GlobalSpecifier(Context
);
4897 buildNestedNameSpecifier(FullNamespaceDeclChain
, NNS
);
4901 // If the built NestedNameSpecifier would be replacing an existing
4902 // NestedNameSpecifier, use the number of component identifiers that
4903 // would need to be changed as the edit distance instead of the number
4904 // of components in the built NestedNameSpecifier.
4905 if (NNS
&& !CurNameSpecifierIdentifiers
.empty()) {
4906 SmallVector
<const IdentifierInfo
*, 4> NewNameSpecifierIdentifiers
;
4907 getNestedNameSpecifierIdentifiers(NNS
, NewNameSpecifierIdentifiers
);
4909 llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers
),
4910 llvm::ArrayRef(NewNameSpecifierIdentifiers
));
4913 SpecifierInfo SI
= {Ctx
, NNS
, NumSpecifiers
};
4914 DistanceMap
[NumSpecifiers
].push_back(SI
);
4917 /// Perform name lookup for a possible result for typo correction.
4918 static void LookupPotentialTypoResult(Sema
&SemaRef
,
4920 IdentifierInfo
*Name
,
4921 Scope
*S
, CXXScopeSpec
*SS
,
4922 DeclContext
*MemberContext
,
4923 bool EnteringContext
,
4924 bool isObjCIvarLookup
,
4926 Res
.suppressDiagnostics();
4928 Res
.setLookupName(Name
);
4929 Res
.setAllowHidden(FindHidden
);
4930 if (MemberContext
) {
4931 if (ObjCInterfaceDecl
*Class
= dyn_cast
<ObjCInterfaceDecl
>(MemberContext
)) {
4932 if (isObjCIvarLookup
) {
4933 if (ObjCIvarDecl
*Ivar
= Class
->lookupInstanceVariable(Name
)) {
4940 if (ObjCPropertyDecl
*Prop
= Class
->FindPropertyDeclaration(
4941 Name
, ObjCPropertyQueryKind::OBJC_PR_query_instance
)) {
4948 SemaRef
.LookupQualifiedName(Res
, MemberContext
);
4952 SemaRef
.LookupParsedName(Res
, S
, SS
,
4953 /*ObjectType=*/QualType(),
4954 /*AllowBuiltinCreation=*/false, EnteringContext
);
4956 // Fake ivar lookup; this should really be part of
4957 // LookupParsedName.
4958 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl()) {
4959 if (Method
->isInstanceMethod() && Method
->getClassInterface() &&
4961 (Res
.isSingleResult() &&
4962 Res
.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4963 if (ObjCIvarDecl
*IV
4964 = Method
->getClassInterface()->lookupInstanceVariable(Name
)) {
4972 /// Add keywords to the consumer as possible typo corrections.
4973 static void AddKeywordsToConsumer(Sema
&SemaRef
,
4974 TypoCorrectionConsumer
&Consumer
,
4975 Scope
*S
, CorrectionCandidateCallback
&CCC
,
4976 bool AfterNestedNameSpecifier
) {
4977 if (AfterNestedNameSpecifier
) {
4978 // For 'X::', we know exactly which keywords can appear next.
4979 Consumer
.addKeywordResult("template");
4980 if (CCC
.WantExpressionKeywords
)
4981 Consumer
.addKeywordResult("operator");
4985 if (CCC
.WantObjCSuper
)
4986 Consumer
.addKeywordResult("super");
4988 if (CCC
.WantTypeSpecifiers
) {
4989 // Add type-specifier keywords to the set of results.
4990 static const char *const CTypeSpecs
[] = {
4991 "char", "const", "double", "enum", "float", "int", "long", "short",
4992 "signed", "struct", "union", "unsigned", "void", "volatile",
4994 // storage-specifiers as well
4995 "extern", "inline", "static", "typedef"
4998 for (const auto *CTS
: CTypeSpecs
)
4999 Consumer
.addKeywordResult(CTS
);
5001 if (SemaRef
.getLangOpts().C99
&& !SemaRef
.getLangOpts().C2y
)
5002 Consumer
.addKeywordResult("_Imaginary");
5004 if (SemaRef
.getLangOpts().C99
)
5005 Consumer
.addKeywordResult("restrict");
5006 if (SemaRef
.getLangOpts().Bool
|| SemaRef
.getLangOpts().CPlusPlus
)
5007 Consumer
.addKeywordResult("bool");
5008 else if (SemaRef
.getLangOpts().C99
)
5009 Consumer
.addKeywordResult("_Bool");
5011 if (SemaRef
.getLangOpts().CPlusPlus
) {
5012 Consumer
.addKeywordResult("class");
5013 Consumer
.addKeywordResult("typename");
5014 Consumer
.addKeywordResult("wchar_t");
5016 if (SemaRef
.getLangOpts().CPlusPlus11
) {
5017 Consumer
.addKeywordResult("char16_t");
5018 Consumer
.addKeywordResult("char32_t");
5019 Consumer
.addKeywordResult("constexpr");
5020 Consumer
.addKeywordResult("decltype");
5021 Consumer
.addKeywordResult("thread_local");
5025 if (SemaRef
.getLangOpts().GNUKeywords
)
5026 Consumer
.addKeywordResult("typeof");
5027 } else if (CCC
.WantFunctionLikeCasts
) {
5028 static const char *const CastableTypeSpecs
[] = {
5029 "char", "double", "float", "int", "long", "short",
5030 "signed", "unsigned", "void"
5032 for (auto *kw
: CastableTypeSpecs
)
5033 Consumer
.addKeywordResult(kw
);
5036 if (CCC
.WantCXXNamedCasts
&& SemaRef
.getLangOpts().CPlusPlus
) {
5037 Consumer
.addKeywordResult("const_cast");
5038 Consumer
.addKeywordResult("dynamic_cast");
5039 Consumer
.addKeywordResult("reinterpret_cast");
5040 Consumer
.addKeywordResult("static_cast");
5043 if (CCC
.WantExpressionKeywords
) {
5044 Consumer
.addKeywordResult("sizeof");
5045 if (SemaRef
.getLangOpts().Bool
|| SemaRef
.getLangOpts().CPlusPlus
) {
5046 Consumer
.addKeywordResult("false");
5047 Consumer
.addKeywordResult("true");
5050 if (SemaRef
.getLangOpts().CPlusPlus
) {
5051 static const char *const CXXExprs
[] = {
5052 "delete", "new", "operator", "throw", "typeid"
5054 for (const auto *CE
: CXXExprs
)
5055 Consumer
.addKeywordResult(CE
);
5057 if (isa
<CXXMethodDecl
>(SemaRef
.CurContext
) &&
5058 cast
<CXXMethodDecl
>(SemaRef
.CurContext
)->isInstance())
5059 Consumer
.addKeywordResult("this");
5061 if (SemaRef
.getLangOpts().CPlusPlus11
) {
5062 Consumer
.addKeywordResult("alignof");
5063 Consumer
.addKeywordResult("nullptr");
5067 if (SemaRef
.getLangOpts().C11
) {
5068 // FIXME: We should not suggest _Alignof if the alignof macro
5070 Consumer
.addKeywordResult("_Alignof");
5074 if (CCC
.WantRemainingKeywords
) {
5075 if (SemaRef
.getCurFunctionOrMethodDecl() || SemaRef
.getCurBlock()) {
5077 static const char *const CStmts
[] = {
5078 "do", "else", "for", "goto", "if", "return", "switch", "while" };
5079 for (const auto *CS
: CStmts
)
5080 Consumer
.addKeywordResult(CS
);
5082 if (SemaRef
.getLangOpts().CPlusPlus
) {
5083 Consumer
.addKeywordResult("catch");
5084 Consumer
.addKeywordResult("try");
5087 if (S
&& S
->getBreakParent())
5088 Consumer
.addKeywordResult("break");
5090 if (S
&& S
->getContinueParent())
5091 Consumer
.addKeywordResult("continue");
5093 if (SemaRef
.getCurFunction() &&
5094 !SemaRef
.getCurFunction()->SwitchStack
.empty()) {
5095 Consumer
.addKeywordResult("case");
5096 Consumer
.addKeywordResult("default");
5099 if (SemaRef
.getLangOpts().CPlusPlus
) {
5100 Consumer
.addKeywordResult("namespace");
5101 Consumer
.addKeywordResult("template");
5104 if (S
&& S
->isClassScope()) {
5105 Consumer
.addKeywordResult("explicit");
5106 Consumer
.addKeywordResult("friend");
5107 Consumer
.addKeywordResult("mutable");
5108 Consumer
.addKeywordResult("private");
5109 Consumer
.addKeywordResult("protected");
5110 Consumer
.addKeywordResult("public");
5111 Consumer
.addKeywordResult("virtual");
5115 if (SemaRef
.getLangOpts().CPlusPlus
) {
5116 Consumer
.addKeywordResult("using");
5118 if (SemaRef
.getLangOpts().CPlusPlus11
)
5119 Consumer
.addKeywordResult("static_assert");
5124 std::unique_ptr
<TypoCorrectionConsumer
> Sema::makeTypoCorrectionConsumer(
5125 const DeclarationNameInfo
&TypoName
, Sema::LookupNameKind LookupKind
,
5126 Scope
*S
, CXXScopeSpec
*SS
, CorrectionCandidateCallback
&CCC
,
5127 DeclContext
*MemberContext
, bool EnteringContext
,
5128 const ObjCObjectPointerType
*OPT
, bool ErrorRecovery
) {
5130 if (Diags
.hasFatalErrorOccurred() || !getLangOpts().SpellChecking
||
5131 DisableTypoCorrection
)
5134 // In Microsoft mode, don't perform typo correction in a template member
5135 // function dependent context because it interferes with the "lookup into
5136 // dependent bases of class templates" feature.
5137 if (getLangOpts().MSVCCompat
&& CurContext
->isDependentContext() &&
5138 isa
<CXXMethodDecl
>(CurContext
))
5141 // We only attempt to correct typos for identifiers.
5142 IdentifierInfo
*Typo
= TypoName
.getName().getAsIdentifierInfo();
5146 // If the scope specifier itself was invalid, don't try to correct
5148 if (SS
&& SS
->isInvalid())
5151 // Never try to correct typos during any kind of code synthesis.
5152 if (!CodeSynthesisContexts
.empty())
5155 // Don't try to correct 'super'.
5156 if (S
&& S
->isInObjcMethodScope() && Typo
== getSuperIdentifier())
5159 // Abort if typo correction already failed for this specific typo.
5160 IdentifierSourceLocations::iterator locs
= TypoCorrectionFailures
.find(Typo
);
5161 if (locs
!= TypoCorrectionFailures
.end() &&
5162 locs
->second
.count(TypoName
.getLoc()))
5165 // Don't try to correct the identifier "vector" when in AltiVec mode.
5166 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5167 // remove this workaround.
5168 if ((getLangOpts().AltiVec
|| getLangOpts().ZVector
) && Typo
->isStr("vector"))
5171 // Provide a stop gap for files that are just seriously broken. Trying
5172 // to correct all typos can turn into a HUGE performance penalty, causing
5173 // some files to take minutes to get rejected by the parser.
5174 unsigned Limit
= getDiagnostics().getDiagnosticOptions().SpellCheckingLimit
;
5175 if (Limit
&& TyposCorrected
>= Limit
)
5179 // If we're handling a missing symbol error, using modules, and the
5180 // special search all modules option is used, look for a missing import.
5181 if (ErrorRecovery
&& getLangOpts().Modules
&&
5182 getLangOpts().ModulesSearchAll
) {
5183 // The following has the side effect of loading the missing module.
5184 getModuleLoader().lookupMissingImports(Typo
->getName(),
5185 TypoName
.getBeginLoc());
5188 // Extend the lifetime of the callback. We delayed this until here
5189 // to avoid allocations in the hot path (which is where no typo correction
5190 // occurs). Note that CorrectionCandidateCallback is polymorphic and
5191 // initially stack-allocated.
5192 std::unique_ptr
<CorrectionCandidateCallback
> ClonedCCC
= CCC
.clone();
5193 auto Consumer
= std::make_unique
<TypoCorrectionConsumer
>(
5194 *this, TypoName
, LookupKind
, S
, SS
, std::move(ClonedCCC
), MemberContext
,
5197 // Perform name lookup to find visible, similarly-named entities.
5198 bool IsUnqualifiedLookup
= false;
5199 DeclContext
*QualifiedDC
= MemberContext
;
5200 if (MemberContext
) {
5201 LookupVisibleDecls(MemberContext
, LookupKind
, *Consumer
);
5203 // Look in qualified interfaces.
5205 for (auto *I
: OPT
->quals())
5206 LookupVisibleDecls(I
, LookupKind
, *Consumer
);
5208 } else if (SS
&& SS
->isSet()) {
5209 QualifiedDC
= computeDeclContext(*SS
, EnteringContext
);
5213 LookupVisibleDecls(QualifiedDC
, LookupKind
, *Consumer
);
5215 IsUnqualifiedLookup
= true;
5218 // Determine whether we are going to search in the various namespaces for
5220 bool SearchNamespaces
5221 = getLangOpts().CPlusPlus
&&
5222 (IsUnqualifiedLookup
|| (SS
&& SS
->isSet()));
5224 if (IsUnqualifiedLookup
|| SearchNamespaces
) {
5225 // For unqualified lookup, look through all of the names that we have
5226 // seen in this translation unit.
5227 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5228 for (const auto &I
: Context
.Idents
)
5229 Consumer
->FoundName(I
.getKey());
5231 // Walk through identifiers in external identifier sources.
5232 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5233 if (IdentifierInfoLookup
*External
5234 = Context
.Idents
.getExternalIdentifierLookup()) {
5235 std::unique_ptr
<IdentifierIterator
> Iter(External
->getIdentifiers());
5237 StringRef Name
= Iter
->Next();
5241 Consumer
->FoundName(Name
);
5246 AddKeywordsToConsumer(*this, *Consumer
, S
,
5247 *Consumer
->getCorrectionValidator(),
5248 SS
&& SS
->isNotEmpty());
5250 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5251 // to search those namespaces.
5252 if (SearchNamespaces
) {
5253 // Load any externally-known namespaces.
5254 if (ExternalSource
&& !LoadedExternalKnownNamespaces
) {
5255 SmallVector
<NamespaceDecl
*, 4> ExternalKnownNamespaces
;
5256 LoadedExternalKnownNamespaces
= true;
5257 ExternalSource
->ReadKnownNamespaces(ExternalKnownNamespaces
);
5258 for (auto *N
: ExternalKnownNamespaces
)
5259 KnownNamespaces
[N
] = true;
5262 Consumer
->addNamespaces(KnownNamespaces
);
5268 TypoCorrection
Sema::CorrectTypo(const DeclarationNameInfo
&TypoName
,
5269 Sema::LookupNameKind LookupKind
,
5270 Scope
*S
, CXXScopeSpec
*SS
,
5271 CorrectionCandidateCallback
&CCC
,
5272 CorrectTypoKind Mode
,
5273 DeclContext
*MemberContext
,
5274 bool EnteringContext
,
5275 const ObjCObjectPointerType
*OPT
,
5276 bool RecordFailure
) {
5277 // Always let the ExternalSource have the first chance at correction, even
5278 // if we would otherwise have given up.
5279 if (ExternalSource
) {
5280 if (TypoCorrection Correction
=
5281 ExternalSource
->CorrectTypo(TypoName
, LookupKind
, S
, SS
, CCC
,
5282 MemberContext
, EnteringContext
, OPT
))
5286 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5287 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5288 // some instances of CTC_Unknown, while WantRemainingKeywords is true
5289 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5290 bool ObjCMessageReceiver
= CCC
.WantObjCSuper
&& !CCC
.WantRemainingKeywords
;
5292 IdentifierInfo
*Typo
= TypoName
.getName().getAsIdentifierInfo();
5293 auto Consumer
= makeTypoCorrectionConsumer(TypoName
, LookupKind
, S
, SS
, CCC
,
5294 MemberContext
, EnteringContext
,
5295 OPT
, Mode
== CTK_ErrorRecovery
);
5298 return TypoCorrection();
5300 // If we haven't found anything, we're done.
5301 if (Consumer
->empty())
5302 return FailedCorrection(Typo
, TypoName
.getLoc(), RecordFailure
);
5304 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5305 // is not more that about a third of the length of the typo's identifier.
5306 unsigned ED
= Consumer
->getBestEditDistance(true);
5307 unsigned TypoLen
= Typo
->getName().size();
5308 if (ED
> 0 && TypoLen
/ ED
< 3)
5309 return FailedCorrection(Typo
, TypoName
.getLoc(), RecordFailure
);
5311 TypoCorrection BestTC
= Consumer
->getNextCorrection();
5312 TypoCorrection SecondBestTC
= Consumer
->getNextCorrection();
5314 return FailedCorrection(Typo
, TypoName
.getLoc(), RecordFailure
);
5316 ED
= BestTC
.getEditDistance();
5318 if (TypoLen
>= 3 && ED
> 0 && TypoLen
/ ED
< 3) {
5319 // If this was an unqualified lookup and we believe the callback
5320 // object wouldn't have filtered out possible corrections, note
5321 // that no correction was found.
5322 return FailedCorrection(Typo
, TypoName
.getLoc(), RecordFailure
);
5325 // If only a single name remains, return that result.
5326 if (!SecondBestTC
||
5327 SecondBestTC
.getEditDistance(false) > BestTC
.getEditDistance(false)) {
5328 const TypoCorrection
&Result
= BestTC
;
5330 // Don't correct to a keyword that's the same as the typo; the keyword
5331 // wasn't actually in scope.
5332 if (ED
== 0 && Result
.isKeyword())
5333 return FailedCorrection(Typo
, TypoName
.getLoc(), RecordFailure
);
5335 TypoCorrection TC
= Result
;
5336 TC
.setCorrectionRange(SS
, TypoName
);
5337 checkCorrectionVisibility(*this, TC
);
5339 } else if (SecondBestTC
&& ObjCMessageReceiver
) {
5340 // Prefer 'super' when we're completing in a message-receiver
5343 if (BestTC
.getCorrection().getAsString() != "super") {
5344 if (SecondBestTC
.getCorrection().getAsString() == "super")
5345 BestTC
= SecondBestTC
;
5346 else if ((*Consumer
)["super"].front().isKeyword())
5347 BestTC
= (*Consumer
)["super"].front();
5349 // Don't correct to a keyword that's the same as the typo; the keyword
5350 // wasn't actually in scope.
5351 if (BestTC
.getEditDistance() == 0 ||
5352 BestTC
.getCorrection().getAsString() != "super")
5353 return FailedCorrection(Typo
, TypoName
.getLoc(), RecordFailure
);
5355 BestTC
.setCorrectionRange(SS
, TypoName
);
5359 // Record the failure's location if needed and return an empty correction. If
5360 // this was an unqualified lookup and we believe the callback object did not
5361 // filter out possible corrections, also cache the failure for the typo.
5362 return FailedCorrection(Typo
, TypoName
.getLoc(), RecordFailure
&& !SecondBestTC
);
5365 TypoExpr
*Sema::CorrectTypoDelayed(
5366 const DeclarationNameInfo
&TypoName
, Sema::LookupNameKind LookupKind
,
5367 Scope
*S
, CXXScopeSpec
*SS
, CorrectionCandidateCallback
&CCC
,
5368 TypoDiagnosticGenerator TDG
, TypoRecoveryCallback TRC
, CorrectTypoKind Mode
,
5369 DeclContext
*MemberContext
, bool EnteringContext
,
5370 const ObjCObjectPointerType
*OPT
) {
5371 auto Consumer
= makeTypoCorrectionConsumer(TypoName
, LookupKind
, S
, SS
, CCC
,
5372 MemberContext
, EnteringContext
,
5373 OPT
, Mode
== CTK_ErrorRecovery
);
5375 // Give the external sema source a chance to correct the typo.
5376 TypoCorrection ExternalTypo
;
5377 if (ExternalSource
&& Consumer
) {
5378 ExternalTypo
= ExternalSource
->CorrectTypo(
5379 TypoName
, LookupKind
, S
, SS
, *Consumer
->getCorrectionValidator(),
5380 MemberContext
, EnteringContext
, OPT
);
5382 Consumer
->addCorrection(ExternalTypo
);
5385 if (!Consumer
|| Consumer
->empty())
5388 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5389 // is not more that about a third of the length of the typo's identifier.
5390 unsigned ED
= Consumer
->getBestEditDistance(true);
5391 IdentifierInfo
*Typo
= TypoName
.getName().getAsIdentifierInfo();
5392 if (!ExternalTypo
&& ED
> 0 && Typo
->getName().size() / ED
< 3)
5394 ExprEvalContexts
.back().NumTypos
++;
5395 return createDelayedTypo(std::move(Consumer
), std::move(TDG
), std::move(TRC
),
5399 void TypoCorrection::addCorrectionDecl(NamedDecl
*CDecl
) {
5403 CorrectionDecls
.clear();
5405 CorrectionDecls
.push_back(CDecl
);
5407 if (!CorrectionName
)
5408 CorrectionName
= CDecl
->getDeclName();
5411 std::string
TypoCorrection::getAsString(const LangOptions
&LO
) const {
5412 if (CorrectionNameSpec
) {
5413 std::string tmpBuffer
;
5414 llvm::raw_string_ostream
PrefixOStream(tmpBuffer
);
5415 CorrectionNameSpec
->print(PrefixOStream
, PrintingPolicy(LO
));
5416 PrefixOStream
<< CorrectionName
;
5417 return PrefixOStream
.str();
5420 return CorrectionName
.getAsString();
5423 bool CorrectionCandidateCallback::ValidateCandidate(
5424 const TypoCorrection
&candidate
) {
5425 if (!candidate
.isResolved())
5428 if (candidate
.isKeyword())
5429 return WantTypeSpecifiers
|| WantExpressionKeywords
|| WantCXXNamedCasts
||
5430 WantRemainingKeywords
|| WantObjCSuper
;
5432 bool HasNonType
= false;
5433 bool HasStaticMethod
= false;
5434 bool HasNonStaticMethod
= false;
5435 for (Decl
*D
: candidate
) {
5436 if (FunctionTemplateDecl
*FTD
= dyn_cast
<FunctionTemplateDecl
>(D
))
5437 D
= FTD
->getTemplatedDecl();
5438 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
5439 if (Method
->isStatic())
5440 HasStaticMethod
= true;
5442 HasNonStaticMethod
= true;
5444 if (!isa
<TypeDecl
>(D
))
5448 if (IsAddressOfOperand
&& HasNonStaticMethod
&& !HasStaticMethod
&&
5449 !candidate
.getCorrectionSpecifier())
5452 return WantTypeSpecifiers
|| HasNonType
;
5455 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema
&SemaRef
, unsigned NumArgs
,
5456 bool HasExplicitTemplateArgs
,
5458 : NumArgs(NumArgs
), HasExplicitTemplateArgs(HasExplicitTemplateArgs
),
5459 CurContext(SemaRef
.CurContext
), MemberFn(ME
) {
5460 WantTypeSpecifiers
= false;
5461 WantFunctionLikeCasts
= SemaRef
.getLangOpts().CPlusPlus
&&
5462 !HasExplicitTemplateArgs
&& NumArgs
== 1;
5463 WantCXXNamedCasts
= HasExplicitTemplateArgs
&& NumArgs
== 1;
5464 WantRemainingKeywords
= false;
5467 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection
&candidate
) {
5468 if (!candidate
.getCorrectionDecl())
5469 return candidate
.isKeyword();
5471 for (auto *C
: candidate
) {
5472 FunctionDecl
*FD
= nullptr;
5473 NamedDecl
*ND
= C
->getUnderlyingDecl();
5474 if (FunctionTemplateDecl
*FTD
= dyn_cast
<FunctionTemplateDecl
>(ND
))
5475 FD
= FTD
->getTemplatedDecl();
5476 if (!HasExplicitTemplateArgs
&& !FD
) {
5477 if (!(FD
= dyn_cast
<FunctionDecl
>(ND
)) && isa
<ValueDecl
>(ND
)) {
5478 // If the Decl is neither a function nor a template function,
5479 // determine if it is a pointer or reference to a function. If so,
5480 // check against the number of arguments expected for the pointee.
5481 QualType ValType
= cast
<ValueDecl
>(ND
)->getType();
5482 if (ValType
.isNull())
5484 if (ValType
->isAnyPointerType() || ValType
->isReferenceType())
5485 ValType
= ValType
->getPointeeType();
5486 if (const FunctionProtoType
*FPT
= ValType
->getAs
<FunctionProtoType
>())
5487 if (FPT
->getNumParams() == NumArgs
)
5492 // A typo for a function-style cast can look like a function call in C++.
5493 if ((HasExplicitTemplateArgs
? getAsTypeTemplateDecl(ND
) != nullptr
5494 : isa
<TypeDecl
>(ND
)) &&
5495 CurContext
->getParentASTContext().getLangOpts().CPlusPlus
)
5496 // Only a class or class template can take two or more arguments.
5497 return NumArgs
<= 1 || HasExplicitTemplateArgs
|| isa
<CXXRecordDecl
>(ND
);
5499 // Skip the current candidate if it is not a FunctionDecl or does not accept
5500 // the current number of arguments.
5501 if (!FD
|| !(FD
->getNumParams() >= NumArgs
&&
5502 FD
->getMinRequiredArguments() <= NumArgs
))
5505 // If the current candidate is a non-static C++ method, skip the candidate
5506 // unless the method being corrected--or the current DeclContext, if the
5507 // function being corrected is not a method--is a method in the same class
5508 // or a descendent class of the candidate's parent class.
5509 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
5510 if (MemberFn
|| !MD
->isStatic()) {
5513 ? dyn_cast_if_present
<CXXMethodDecl
>(MemberFn
->getMemberDecl())
5514 : dyn_cast_if_present
<CXXMethodDecl
>(CurContext
);
5515 const CXXRecordDecl
*CurRD
=
5516 CurMD
? CurMD
->getParent()->getCanonicalDecl() : nullptr;
5517 const CXXRecordDecl
*RD
= MD
->getParent()->getCanonicalDecl();
5518 if (!CurRD
|| (CurRD
!= RD
&& !CurRD
->isDerivedFrom(RD
)))
5527 void Sema::diagnoseTypo(const TypoCorrection
&Correction
,
5528 const PartialDiagnostic
&TypoDiag
,
5529 bool ErrorRecovery
) {
5530 diagnoseTypo(Correction
, TypoDiag
, PDiag(diag::note_previous_decl
),
5534 /// Find which declaration we should import to provide the definition of
5535 /// the given declaration.
5536 static const NamedDecl
*getDefinitionToImport(const NamedDecl
*D
) {
5537 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
5538 return VD
->getDefinition();
5539 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
5540 return FD
->getDefinition();
5541 if (const auto *TD
= dyn_cast
<TagDecl
>(D
))
5542 return TD
->getDefinition();
5543 if (const auto *ID
= dyn_cast
<ObjCInterfaceDecl
>(D
))
5544 return ID
->getDefinition();
5545 if (const auto *PD
= dyn_cast
<ObjCProtocolDecl
>(D
))
5546 return PD
->getDefinition();
5547 if (const auto *TD
= dyn_cast
<TemplateDecl
>(D
))
5548 if (const NamedDecl
*TTD
= TD
->getTemplatedDecl())
5549 return getDefinitionToImport(TTD
);
5553 void Sema::diagnoseMissingImport(SourceLocation Loc
, const NamedDecl
*Decl
,
5554 MissingImportKind MIK
, bool Recover
) {
5555 // Suggest importing a module providing the definition of this entity, if
5557 const NamedDecl
*Def
= getDefinitionToImport(Decl
);
5561 Module
*Owner
= getOwningModule(Def
);
5562 assert(Owner
&& "definition of hidden declaration is not in a module");
5564 llvm::SmallVector
<Module
*, 8> OwningModules
;
5565 OwningModules
.push_back(Owner
);
5566 auto Merged
= Context
.getModulesWithMergedDefinition(Def
);
5567 OwningModules
.insert(OwningModules
.end(), Merged
.begin(), Merged
.end());
5569 diagnoseMissingImport(Loc
, Def
, Def
->getLocation(), OwningModules
, MIK
,
5573 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5574 /// suggesting the addition of a #include of the specified file.
5575 static std::string
getHeaderNameForHeader(Preprocessor
&PP
, FileEntryRef E
,
5576 llvm::StringRef IncludingFile
) {
5577 bool IsAngled
= false;
5578 auto Path
= PP
.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5579 E
, IncludingFile
, &IsAngled
);
5580 return (IsAngled
? '<' : '"') + Path
+ (IsAngled
? '>' : '"');
5583 void Sema::diagnoseMissingImport(SourceLocation UseLoc
, const NamedDecl
*Decl
,
5584 SourceLocation DeclLoc
,
5585 ArrayRef
<Module
*> Modules
,
5586 MissingImportKind MIK
, bool Recover
) {
5587 assert(!Modules
.empty());
5589 // See https://github.com/llvm/llvm-project/issues/73893. It is generally
5590 // confusing than helpful to show the namespace is not visible.
5591 if (isa
<NamespaceDecl
>(Decl
))
5594 auto NotePrevious
= [&] {
5595 // FIXME: Suppress the note backtrace even under
5596 // -fdiagnostics-show-note-include-stack. We don't care how this
5597 // declaration was previously reached.
5598 Diag(DeclLoc
, diag::note_unreachable_entity
) << (int)MIK
;
5601 // Weed out duplicates from module list.
5602 llvm::SmallVector
<Module
*, 8> UniqueModules
;
5603 llvm::SmallDenseSet
<Module
*, 8> UniqueModuleSet
;
5604 for (auto *M
: Modules
) {
5605 if (M
->isExplicitGlobalModule() || M
->isPrivateModule())
5607 if (UniqueModuleSet
.insert(M
).second
)
5608 UniqueModules
.push_back(M
);
5611 // Try to find a suitable header-name to #include.
5612 std::string HeaderName
;
5613 if (OptionalFileEntryRef Header
=
5614 PP
.getHeaderToIncludeForDiagnostics(UseLoc
, DeclLoc
)) {
5615 if (const FileEntry
*FE
=
5616 SourceMgr
.getFileEntryForID(SourceMgr
.getFileID(UseLoc
)))
5618 getHeaderNameForHeader(PP
, *Header
, FE
->tryGetRealPathName());
5621 // If we have a #include we should suggest, or if all definition locations
5622 // were in global module fragments, don't suggest an import.
5623 if (!HeaderName
.empty() || UniqueModules
.empty()) {
5624 // FIXME: Find a smart place to suggest inserting a #include, and add
5625 // a FixItHint there.
5626 Diag(UseLoc
, diag::err_module_unimported_use_header
)
5627 << (int)MIK
<< Decl
<< !HeaderName
.empty() << HeaderName
;
5628 // Produce a note showing where the entity was declared.
5631 createImplicitModuleImportForErrorRecovery(UseLoc
, Modules
[0]);
5635 Modules
= UniqueModules
;
5637 auto GetModuleNameForDiagnostic
= [this](const Module
*M
) -> std::string
{
5638 if (M
->isModuleMapModule())
5639 return M
->getFullModuleName();
5641 if (M
->isImplicitGlobalModule())
5642 M
= M
->getTopLevelModule();
5644 // If the current module unit is in the same module with M, it is OK to show
5645 // the partition name. Otherwise, it'll be sufficient to show the primary
5647 if (getASTContext().isInSameModule(M
, getCurrentModule()))
5648 return M
->getTopLevelModuleName().str();
5650 return M
->getPrimaryModuleInterfaceName().str();
5653 if (Modules
.size() > 1) {
5654 std::string ModuleList
;
5656 for (const auto *M
: Modules
) {
5657 ModuleList
+= "\n ";
5658 if (++N
== 5 && N
!= Modules
.size()) {
5659 ModuleList
+= "[...]";
5662 ModuleList
+= GetModuleNameForDiagnostic(M
);
5665 Diag(UseLoc
, diag::err_module_unimported_use_multiple
)
5666 << (int)MIK
<< Decl
<< ModuleList
;
5668 // FIXME: Add a FixItHint that imports the corresponding module.
5669 Diag(UseLoc
, diag::err_module_unimported_use
)
5670 << (int)MIK
<< Decl
<< GetModuleNameForDiagnostic(Modules
[0]);
5675 // Try to recover by implicitly importing this module.
5677 createImplicitModuleImportForErrorRecovery(UseLoc
, Modules
[0]);
5680 void Sema::diagnoseTypo(const TypoCorrection
&Correction
,
5681 const PartialDiagnostic
&TypoDiag
,
5682 const PartialDiagnostic
&PrevNote
,
5683 bool ErrorRecovery
) {
5684 std::string CorrectedStr
= Correction
.getAsString(getLangOpts());
5685 std::string CorrectedQuotedStr
= Correction
.getQuoted(getLangOpts());
5686 FixItHint FixTypo
= FixItHint::CreateReplacement(
5687 Correction
.getCorrectionRange(), CorrectedStr
);
5689 // Maybe we're just missing a module import.
5690 if (Correction
.requiresImport()) {
5691 NamedDecl
*Decl
= Correction
.getFoundDecl();
5692 assert(Decl
&& "import required but no declaration to import");
5694 diagnoseMissingImport(Correction
.getCorrectionRange().getBegin(), Decl
,
5695 MissingImportKind::Declaration
, ErrorRecovery
);
5699 Diag(Correction
.getCorrectionRange().getBegin(), TypoDiag
)
5700 << CorrectedQuotedStr
<< (ErrorRecovery
? FixTypo
: FixItHint());
5702 NamedDecl
*ChosenDecl
=
5703 Correction
.isKeyword() ? nullptr : Correction
.getFoundDecl();
5705 // For builtin functions which aren't declared anywhere in source,
5706 // don't emit the "declared here" note.
5707 if (const auto *FD
= dyn_cast_if_present
<FunctionDecl
>(ChosenDecl
);
5708 FD
&& FD
->getBuiltinID() &&
5709 PrevNote
.getDiagID() == diag::note_previous_decl
&&
5710 Correction
.getCorrectionRange().getBegin() == FD
->getBeginLoc()) {
5711 ChosenDecl
= nullptr;
5714 if (PrevNote
.getDiagID() && ChosenDecl
)
5715 Diag(ChosenDecl
->getLocation(), PrevNote
)
5716 << CorrectedQuotedStr
<< (ErrorRecovery
? FixItHint() : FixTypo
);
5718 // Add any extra diagnostics.
5719 for (const PartialDiagnostic
&PD
: Correction
.getExtraDiagnostics())
5720 Diag(Correction
.getCorrectionRange().getBegin(), PD
);
5723 TypoExpr
*Sema::createDelayedTypo(std::unique_ptr
<TypoCorrectionConsumer
> TCC
,
5724 TypoDiagnosticGenerator TDG
,
5725 TypoRecoveryCallback TRC
,
5726 SourceLocation TypoLoc
) {
5727 assert(TCC
&& "createDelayedTypo requires a valid TypoCorrectionConsumer");
5728 auto TE
= new (Context
) TypoExpr(Context
.DependentTy
, TypoLoc
);
5729 auto &State
= DelayedTypos
[TE
];
5730 State
.Consumer
= std::move(TCC
);
5731 State
.DiagHandler
= std::move(TDG
);
5732 State
.RecoveryHandler
= std::move(TRC
);
5734 TypoExprs
.push_back(TE
);
5738 const Sema::TypoExprState
&Sema::getTypoExprState(TypoExpr
*TE
) const {
5739 auto Entry
= DelayedTypos
.find(TE
);
5740 assert(Entry
!= DelayedTypos
.end() &&
5741 "Failed to get the state for a TypoExpr!");
5742 return Entry
->second
;
5745 void Sema::clearDelayedTypo(TypoExpr
*TE
) {
5746 DelayedTypos
.erase(TE
);
5749 void Sema::ActOnPragmaDump(Scope
*S
, SourceLocation IILoc
, IdentifierInfo
*II
) {
5750 DeclarationNameInfo
Name(II
, IILoc
);
5751 LookupResult
R(*this, Name
, LookupAnyName
,
5752 RedeclarationKind::NotForRedeclaration
);
5753 R
.suppressDiagnostics();
5754 R
.setHideTags(false);
5759 void Sema::ActOnPragmaDump(Expr
*E
) {
5763 RedeclarationKind
Sema::forRedeclarationInCurContext() const {
5764 // A declaration with an owning module for linkage can never link against
5765 // anything that is not visible. We don't need to check linkage here; if
5766 // the context has internal linkage, redeclaration lookup won't find things
5767 // from other TUs, and we can't safely compute linkage yet in general.
5768 if (cast
<Decl
>(CurContext
)->getOwningModuleForLinkage())
5769 return RedeclarationKind::ForVisibleRedeclaration
;
5770 return RedeclarationKind::ForExternalRedeclaration
;