clang 19.0.0git
SemaLookup.cpp
Go to the documentation of this file.
1//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements name lookup for C, C++, Objective-C, and
10// Objective-C++.
11//
12//===----------------------------------------------------------------------===//
13
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Overload.h"
33#include "clang/Sema/Scope.h"
35#include "clang/Sema/Sema.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"
46#include <algorithm>
47#include <iterator>
48#include <list>
49#include <optional>
50#include <set>
51#include <utility>
52#include <vector>
53
54#include "OpenCLBuiltins.inc"
55
56using namespace clang;
57using namespace sema;
58
59namespace {
60 class UnqualUsingEntry {
61 const DeclContext *Nominated;
62 const DeclContext *CommonAncestor;
63
64 public:
65 UnqualUsingEntry(const DeclContext *Nominated,
66 const DeclContext *CommonAncestor)
67 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
68 }
69
70 const DeclContext *getCommonAncestor() const {
71 return CommonAncestor;
72 }
73
74 const DeclContext *getNominatedNamespace() const {
75 return Nominated;
76 }
77
78 // Sort by the pointer value of the common ancestor.
79 struct Comparator {
80 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
81 return L.getCommonAncestor() < R.getCommonAncestor();
82 }
83
84 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
85 return E.getCommonAncestor() < DC;
86 }
87
88 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
89 return DC < E.getCommonAncestor();
90 }
91 };
92 };
93
94 /// A collection of using directives, as used by C++ unqualified
95 /// lookup.
96 class UnqualUsingDirectiveSet {
97 Sema &SemaRef;
98
100
101 ListTy list;
103
104 public:
105 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
106
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());
114
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()) {
121 visit(Ctx, Ctx);
122 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
123 for (auto *I : S->using_directives())
124 if (SemaRef.isVisible(I))
125 visit(I, InnermostFileDC);
126 }
127 }
128 }
129
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.
133 //
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)
139 return;
140
141 addUsingDirectives(DC, EffectiveDC);
142 }
143
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) {
149 if (!visited.insert(NS).second)
150 return;
151
152 addUsingDirective(UD, EffectiveDC);
153 addUsingDirectives(NS, EffectiveDC);
154 }
155
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) {
161 while (true) {
162 for (auto *UD : DC->using_directives()) {
164 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
165 addUsingDirective(UD, EffectiveDC);
166 queue.push_back(NS);
167 }
168 }
169
170 if (queue.empty())
171 return;
172
173 DC = queue.pop_back_val();
174 }
175 }
176
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
183 // the first.
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();
191
192 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
193 }
194
195 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
196
197 typedef ListTy::const_iterator const_iterator;
198
199 const_iterator begin() const { return list.begin(); }
200 const_iterator end() const { return list.end(); }
201
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()));
207 }
208 };
209} // end anonymous namespace
210
211// Retrieve the set of identifier namespaces that correspond to a
212// specific kind of name lookup.
213static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
214 bool CPlusPlus,
215 bool Redeclaration) {
216 unsigned IDNS = 0;
217 switch (NameKind) {
223 IDNS = Decl::IDNS_Ordinary;
224 if (CPlusPlus) {
226 if (Redeclaration)
228 }
229 if (Redeclaration)
231 break;
232
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");
238 break;
239
241 if (CPlusPlus) {
242 IDNS = Decl::IDNS_Type;
243
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.
249 if (Redeclaration)
251 } else {
252 IDNS = Decl::IDNS_Tag;
253 }
254 break;
255
257 IDNS = Decl::IDNS_Label;
258 break;
259
261 IDNS = Decl::IDNS_Member;
262 if (CPlusPlus)
264 break;
265
268 break;
269
272 break;
273
275 assert(Redeclaration && "should only be used for redecl lookup");
279 break;
280
283 break;
284
287 break;
288
291 break;
292
297 break;
298 }
299 return IDNS;
300}
301
302void LookupResult::configure() {
303 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
305
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()) {
310 case OO_New:
311 case OO_Delete:
312 case OO_Array_New:
313 case OO_Array_Delete:
315 break;
316
317 default:
318 break;
319 }
320
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))
326 AllowHidden = true;
327 }
328 }
329}
330
331bool 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)));
345 return true;
346}
347
348// Necessary because CXXBasePaths is not complete in Sema.h
349void LookupResult::deletePaths(CXXBasePaths *Paths) {
350 delete Paths;
351}
352
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.
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
358 // those.
359 if (const DeclContext *DC = D->getLexicalDeclContext();
360 DC->isFunctionOrMethod())
361 return DC;
362
363 // Otherwise, look at the semantic context of the declaration. The
364 // declaration must have been found there.
365 return D->getDeclContext()->getRedeclContext();
366}
367
368/// Determine whether \p D is a better lookup result than \p Existing,
369/// given that they declare the same entity.
371 const NamedDecl *D,
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))
377 return true;
378
379 const auto *DUnderlying = D->getUnderlyingDecl();
380 const auto *EUnderlying = Existing->getUnderlyingDecl();
381
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);
393 bool WantTag =
395 return HaveTag != WantTag;
396 }
397
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.
407 if (DMin != EMin)
408 return DMin < EMin;
409 // FIXME: When we track visibility for default function arguments, check
410 // that we pick the declaration with more visible default arguments.
411 }
412
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".
421 if (DMin != EMin)
422 return DMin < EMin;
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();
427 I != N; ++I) {
429 ETD->getTemplateParameters()->getParam(I)) &&
431 DTD->getTemplateParameters()->getParam(I)))
432 return true;
433 }
434 }
435
436 // VarDecl can have incomplete array types, prefer the one with more complete
437 // array type.
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);
444 }
445 return false; // Avoid picking up a newer decl, just because it was newer.
446 }
447
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);
453 }
454
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)
459 return true;
460 return false;
461}
462
463/// Determine whether \p D can hide a tag declaration.
464static 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
475 // scope.
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);
481}
482
483/// Resolves the result kind of this lookup.
485 unsigned N = Decls.size();
486
487 // Fast case: no possible ambiguity.
488 if (N == 0) {
489 assert(ResultKind == NotFound ||
490 ResultKind == NotFoundInCurrentInstantiation);
491 return;
492 }
493
494 // If there's a single decl, we need to examine it to decide what
495 // kind of lookup this is.
496 if (N == 1) {
497 const NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
498 if (isa<FunctionTemplateDecl>(D))
499 ResultKind = FoundOverloaded;
500 else if (isa<UnresolvedUsingValueDecl>(D))
501 ResultKind = FoundUnresolvedValue;
502 return;
503 }
504
505 // Don't do any extra resolution if we've already resolved as ambiguous.
506 if (ResultKind == Ambiguous) return;
507
508 llvm::SmallDenseMap<const NamedDecl *, unsigned, 16> Unique;
509 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
510
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;
516
517 llvm::SmallVector<const NamedDecl *, 4> EquivalentNonFunctions;
518 llvm::BitVector RemovedDecls(N);
519
520 for (unsigned I = 0; I < N; I++) {
521 const NamedDecl *D = Decls[I]->getUnderlyingDecl();
522 D = cast<NamedDecl>(D->getCanonicalDecl());
523
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) {
528 RemovedDecls.set(I);
529 continue;
530 }
531
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)) {
540 bool Hidden = false;
541 for (auto *OtherDecl : Decls) {
542 if (canHideTag(OtherDecl) && !OtherDecl->isInvalidDecl() &&
543 getContextForScopeMatching(OtherDecl)->Equals(
544 getContextForScopeMatching(Decls[I]))) {
545 RemovedDecls.set(I);
546 Hidden = true;
547 break;
548 }
549 }
550 if (Hidden)
551 continue;
552 }
553
554 std::optional<unsigned> ExistingI;
555
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
559 // canonical type.
560 if (const auto *TD = dyn_cast<TypeDecl>(D)) {
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;
567 }
568 }
569
570 // For non-type declarations, check for a prior lookup result naming this
571 // canonical declaration.
572 if (!D->isPlaceholderVar(getSema().getLangOpts()) && !ExistingI) {
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;
577 }
578 }
579
580 if (ExistingI) {
581 // This is not a unique lookup result. Pick one of the results and
582 // discard the other.
584 Decls[*ExistingI]))
585 Decls[*ExistingI] = Decls[I];
586 RemovedDecls.set(I);
587 continue;
588 }
589
590 // Otherwise, do some decl type analysis and then continue.
591
592 if (isa<UnresolvedUsingValueDecl>(D)) {
593 HasUnresolved = true;
594 } else if (isa<TagDecl>(D)) {
595 if (HasTag)
596 Ambiguous = true;
597 HasTag = true;
598 } else if (isa<FunctionTemplateDecl>(D)) {
599 HasFunction = true;
600 HasFunctionTemplate = true;
601 } else if (isa<FunctionDecl>(D)) {
602 HasFunction = true;
603 } else {
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,
610 D)) {
611 EquivalentNonFunctions.push_back(D);
612 RemovedDecls.set(I);
613 continue;
614 }
615 if (D->isPlaceholderVar(getSema().getLangOpts()) &&
617 getContextForScopeMatching(Decls[I])) {
618 ReferenceToPlaceHolderVariable = true;
619 }
620 Ambiguous = true;
621 }
622 HasNonFunction = D;
623 }
624 }
625
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)
630 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
631
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
634 // to the new size.
635 for (int I = RemovedDecls.find_last(); I >= 0; I = RemovedDecls.find_prev(I))
636 Decls[I] = Decls[--N];
637 Decls.truncate(N);
638
639 if ((HasNonFunction && (HasFunction || HasUnresolved)) ||
640 (HideTags && HasTag && (HasFunction || HasNonFunction || HasUnresolved)))
641 Ambiguous = true;
642
643 if (Ambiguous && ReferenceToPlaceHolderVariable)
645 else if (Ambiguous)
647 else if (HasUnresolved)
649 else if (N > 1 || HasFunctionTemplate)
651 else
652 ResultKind = LookupResult::Found;
653}
654
655void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
657 for (I = P.begin(), E = P.end(); I != E; ++I)
658 for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;
659 ++DI)
660 addDecl(*DI);
661}
662
664 Paths = new CXXBasePaths;
665 Paths->swap(P);
666 addDeclsFromBasePaths(*Paths);
667 resolveKind();
668 setAmbiguous(AmbiguousBaseSubobjects);
669}
670
672 Paths = new CXXBasePaths;
673 Paths->swap(P);
674 addDeclsFromBasePaths(*Paths);
675 resolveKind();
676 setAmbiguous(AmbiguousBaseSubobjectTypes);
677}
678
679void LookupResult::print(raw_ostream &Out) {
680 Out << Decls.size() << " result(s)";
681 if (isAmbiguous()) Out << ", ambiguous";
682 if (Paths) Out << ", base paths present";
683
684 for (iterator I = begin(), E = end(); I != E; ++I) {
685 Out << "\n";
686 (*I)->print(Out, 2);
687 }
688}
689
690LLVM_DUMP_METHOD void LookupResult::dump() {
691 llvm::errs() << "lookup results for " << getLookupName().getAsString()
692 << ":\n";
693 for (NamedDecl *D : *this)
694 D->dump();
695}
696
697/// Diagnose a missing builtin type.
698static 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;
703}
704
705/// Lookup an OpenCL enum type.
706static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
710 if (Result.empty())
711 return diagOpenCLBuiltinTypeError(S, "enum", Name);
712 EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
713 if (!Decl)
714 return diagOpenCLBuiltinTypeError(S, "enum", Name);
715 return S.Context.getEnumType(Decl);
716}
717
718/// Lookup an OpenCL typedef type.
719static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
723 if (Result.empty())
724 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
725 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
726 if (!Decl)
727 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
728 return S.Context.getTypedefType(Decl);
729}
730
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) .
743 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
744 SmallVector<QualType, 1> &RetTypes,
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();
750
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++) {
755 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
756 Ty);
757 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
758 ArgTypes.push_back(std::move(Ty));
759 }
760}
761
762/// Create a list of the candidate function overloads for an OpenCL builtin
763/// function.
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.
772 ASTContext &Context, unsigned GenTypeMaxCnt,
773 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
776 Context.getDefaultCallingConvention(false, false, true));
777 PI.Variadic = false;
778
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)
782 return;
783
784 // Create FunctionTypes for each (gen)type.
785 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
787
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)
791 return;
792
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]);
800 }
801
802 FunctionList.push_back(Context.getFunctionType(
803 RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));
804 }
805}
806
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.
810///
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.
817 IdentifierInfo *II,
818 const unsigned FctIndex,
819 const unsigned Len) {
820 // The builtin function declaration uses generic types (gentype).
821 bool HasGenType = false;
822
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;
826
827 ASTContext &Context = S.Context;
828
829 for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
830 const OpenCLBuiltinStruct &OpenCLBuiltin =
831 BuiltinTable[FctIndex + SignatureIndex];
832
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))
837 continue;
838
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()) {
845 Extensions.split(ExtVec, " ");
846 bool AllExtensionsDefined = true;
847 for (StringRef Ext : ExtVec) {
848 if (!S.getPreprocessor().isMacroDefined(Ext)) {
849 AllExtensionsDefined = false;
850 break;
851 }
852 }
853 if (!AllExtensionsDefined)
854 continue;
855 }
856
859
860 // Obtain QualType lists for the function signature.
861 GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,
862 ArgTypes);
863 if (GenTypeMaxCnt > 1) {
864 HasGenType = true;
865 }
866
867 // Create function overload for each type combination.
868 std::vector<QualType> FunctionList;
869 GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,
870 ArgTypes);
871
872 SourceLocation Loc = LR.getNameLoc();
874 FunctionDecl *NewOpenCLBuiltin;
875
876 for (const auto &FTy : FunctionList) {
877 NewOpenCLBuiltin = FunctionDecl::Create(
878 Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,
880 FTy->isFunctionProtoType());
881 NewOpenCLBuiltin->setImplicit();
882
883 // Create Decl objects for each parameter, adding them to the
884 // FunctionDecl.
885 const auto *FP = cast<FunctionProtoType>(FTy);
887 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
889 Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),
890 nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);
891 Parm->setScopeInfo(0, IParm);
892 ParmList.push_back(Parm);
893 }
894 NewOpenCLBuiltin->setParams(ParmList);
895
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));
903
904 if (!S.getLangOpts().OpenCLCPlusPlus)
905 NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));
906
907 LR.addDecl(NewOpenCLBuiltin);
908 }
909 }
910
911 // If we added overloads, need to resolve the lookup result.
912 if (Len > 1 || HasGenType)
913 LR.resolveKind();
914}
915
916/// Lookup a builtin function, when name lookup would otherwise
917/// fail.
919 Sema::LookupNameKind NameKind = R.getLookupKind();
920
921 // If we didn't find a use of this identifier, and if the identifier
922 // corresponds to a compiler builtin, create the decl object for the builtin
923 // now, injecting it into translation unit scope, and return it.
924 if (NameKind == Sema::LookupOrdinaryName ||
927 if (II) {
928 if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
929 if (II == getASTContext().getMakeIntegerSeqName()) {
930 R.addDecl(getASTContext().getMakeIntegerSeqDecl());
931 return true;
932 } else if (II == getASTContext().getTypePackElementName()) {
933 R.addDecl(getASTContext().getTypePackElementDecl());
934 return true;
935 }
936 }
937
938 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
939 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
940 auto Index = isOpenCLBuiltin(II->getName());
941 if (Index.first) {
942 InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,
943 Index.second);
944 return true;
945 }
946 }
947
949 if (!RVIntrinsicManager)
950 RVIntrinsicManager = CreateRISCVIntrinsicManager(*this);
951
952 RVIntrinsicManager->InitIntrinsicList();
953
954 if (RVIntrinsicManager->CreateIntrinsicIfFound(R, II, PP))
955 return true;
956 }
957
958 // If this is a builtin on this (or all) targets, create the decl.
959 if (unsigned BuiltinID = II->getBuiltinID()) {
960 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
961 // library functions like 'malloc'. Instead, we'll just error.
964 return false;
965
966 if (NamedDecl *D =
967 LazilyCreateBuiltin(II, BuiltinID, TUScope,
968 R.isForRedeclaration(), R.getNameLoc())) {
969 R.addDecl(D);
970 return true;
971 }
972 }
973 }
974 }
975
976 return false;
977}
978
979/// Looks up the declaration of "struct objc_super" and
980/// saves it for later use in building builtin declaration of
981/// objc_msgSendSuper and objc_msgSendSuper_stret.
983 ASTContext &Context = Sema.Context;
984 LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),
987 if (Result.getResultKind() == LookupResult::Found)
988 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
989 Context.setObjCSuperType(Context.getTagDeclType(TD));
990}
991
993 if (ID == Builtin::BIobjc_msgSendSuper)
995}
996
997/// Determine whether we can declare a special member function within
998/// the class at this point.
1000 // We need to have a definition for the class.
1001 if (!Class->getDefinition() || Class->isDependentContext())
1002 return false;
1003
1004 // We can't be in the middle of defining the class.
1005 return !Class->isBeingDefined();
1006}
1007
1010 return;
1011
1012 // If the default constructor has not yet been declared, do so now.
1013 if (Class->needsImplicitDefaultConstructor())
1015
1016 // If the copy constructor has not yet been declared, do so now.
1017 if (Class->needsImplicitCopyConstructor())
1019
1020 // If the copy assignment operator has not yet been declared, do so now.
1021 if (Class->needsImplicitCopyAssignment())
1023
1024 if (getLangOpts().CPlusPlus11) {
1025 // If the move constructor has not yet been declared, do so now.
1026 if (Class->needsImplicitMoveConstructor())
1028
1029 // If the move assignment operator has not yet been declared, do so now.
1030 if (Class->needsImplicitMoveAssignment())
1032 }
1033
1034 // If the destructor has not yet been declared, do so now.
1035 if (Class->needsImplicitDestructor())
1037}
1038
1039/// Determine whether this is the name of an implicitly-declared
1040/// special member function.
1042 switch (Name.getNameKind()) {
1045 return true;
1046
1048 return Name.getCXXOverloadedOperator() == OO_Equal;
1049
1050 default:
1051 break;
1052 }
1053
1054 return false;
1055}
1056
1057/// If there are any implicit member functions with the given name
1058/// that need to be declared in the given declaration context, do so.
1060 DeclarationName Name,
1061 SourceLocation Loc,
1062 const DeclContext *DC) {
1063 if (!DC)
1064 return;
1065
1066 switch (Name.getNameKind()) {
1068 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1069 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1070 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1071 if (Record->needsImplicitDefaultConstructor())
1073 if (Record->needsImplicitCopyConstructor())
1075 if (S.getLangOpts().CPlusPlus11 &&
1076 Record->needsImplicitMoveConstructor())
1078 }
1079 break;
1080
1082 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1083 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
1086 break;
1087
1089 if (Name.getCXXOverloadedOperator() != OO_Equal)
1090 break;
1091
1092 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
1093 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1094 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1095 if (Record->needsImplicitCopyAssignment())
1097 if (S.getLangOpts().CPlusPlus11 &&
1098 Record->needsImplicitMoveAssignment())
1100 }
1101 }
1102 break;
1103
1105 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
1106 break;
1107
1108 default:
1109 break;
1110 }
1111}
1112
1113// Adds all qualifying matches for a name within a decl context to the
1114// given lookup result. Returns true if any matches were found.
1115static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
1116 bool Found = false;
1117
1118 // Lazily declare C++ special member functions.
1119 if (S.getLangOpts().CPlusPlus)
1121 DC);
1122
1123 // Perform lookup into this declaration context.
1125 for (NamedDecl *D : DR) {
1126 if ((D = R.getAcceptableDecl(D))) {
1127 R.addDecl(D);
1128 Found = true;
1129 }
1130 }
1131
1132 if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
1133 return true;
1134
1135 if (R.getLookupName().getNameKind()
1138 !isa<CXXRecordDecl>(DC))
1139 return Found;
1140
1141 // C++ [temp.mem]p6:
1142 // A specialization of a conversion function template is not found by
1143 // name lookup. Instead, any conversion function templates visible in the
1144 // context of the use are considered. [...]
1145 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1146 if (!Record->isCompleteDefinition())
1147 return Found;
1148
1149 // For conversion operators, 'operator auto' should only match
1150 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
1151 // as a candidate for template substitution.
1152 auto *ContainedDeducedType =
1154 if (R.getLookupName().getNameKind() ==
1156 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
1157 return Found;
1158
1159 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
1160 UEnd = Record->conversion_end(); U != UEnd; ++U) {
1161 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
1162 if (!ConvTemplate)
1163 continue;
1164
1165 // When we're performing lookup for the purposes of redeclaration, just
1166 // add the conversion function template. When we deduce template
1167 // arguments for specializations, we'll end up unifying the return
1168 // type of the new declaration with the type of the function template.
1169 if (R.isForRedeclaration()) {
1170 R.addDecl(ConvTemplate);
1171 Found = true;
1172 continue;
1173 }
1174
1175 // C++ [temp.mem]p6:
1176 // [...] For each such operator, if argument deduction succeeds
1177 // (14.9.2.3), the resulting specialization is used as if found by
1178 // name lookup.
1179 //
1180 // When referencing a conversion function for any purpose other than
1181 // a redeclaration (such that we'll be building an expression with the
1182 // result), perform template argument deduction and place the
1183 // specialization into the result set. We do this to avoid forcing all
1184 // callers to perform special deduction for conversion functions.
1186 FunctionDecl *Specialization = nullptr;
1187
1188 const FunctionProtoType *ConvProto
1189 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
1190 assert(ConvProto && "Nonsensical conversion function template type");
1191
1192 // Compute the type of the function that we would expect the conversion
1193 // function to have, if it were to match the name given.
1194 // FIXME: Calling convention!
1197 EPI.ExceptionSpec = EST_None;
1199 R.getLookupName().getCXXNameType(), std::nullopt, EPI);
1200
1201 // Perform template argument deduction against the type that we would
1202 // expect the function to have.
1203 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
1204 Specialization, Info) ==
1207 Found = true;
1208 }
1209 }
1210
1211 return Found;
1212}
1213
1214// Performs C++ unqualified lookup into the given file context.
1215static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
1216 const DeclContext *NS,
1217 UnqualUsingDirectiveSet &UDirs) {
1218
1219 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1220
1221 // Perform direct name lookup into the LookupCtx.
1222 bool Found = LookupDirect(S, R, NS);
1223
1224 // Perform direct name lookup into the namespaces nominated by the
1225 // using directives whose common ancestor is this namespace.
1226 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
1227 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
1228 Found = true;
1229
1230 R.resolveKind();
1231
1232 return Found;
1233}
1234
1236 if (DeclContext *Ctx = S->getEntity())
1237 return Ctx->isFileContext();
1238 return false;
1239}
1240
1241/// Find the outer declaration context from this scope. This indicates the
1242/// context that we should search up to (exclusive) before considering the
1243/// parent of the specified scope.
1245 for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
1246 if (DeclContext *DC = OuterS->getLookupEntity())
1247 return DC;
1248 return nullptr;
1249}
1250
1251namespace {
1252/// An RAII object to specify that we want to find block scope extern
1253/// declarations.
1254struct FindLocalExternScope {
1255 FindLocalExternScope(LookupResult &R)
1256 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1257 Decl::IDNS_LocalExtern) {
1260 }
1261 void restore() {
1262 R.setFindLocalExtern(OldFindLocalExtern);
1263 }
1264 ~FindLocalExternScope() {
1265 restore();
1266 }
1267 LookupResult &R;
1268 bool OldFindLocalExtern;
1269};
1270} // end anonymous namespace
1271
1272bool Sema::CppLookupName(LookupResult &R, Scope *S) {
1273 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
1274
1275 DeclarationName Name = R.getLookupName();
1276 Sema::LookupNameKind NameKind = R.getLookupKind();
1277
1278 // If this is the name of an implicitly-declared special member function,
1279 // go through the scope stack to implicitly declare
1281 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1282 if (DeclContext *DC = PreS->getEntity())
1284 }
1285
1286 // Implicitly declare member functions with the name we're looking for, if in
1287 // fact we are in a scope where it matters.
1288
1289 Scope *Initial = S;
1291 I = IdResolver.begin(Name),
1292 IEnd = IdResolver.end();
1293
1294 // First we lookup local scope.
1295 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1296 // ...During unqualified name lookup (3.4.1), the names appear as if
1297 // they were declared in the nearest enclosing namespace which contains
1298 // both the using-directive and the nominated namespace.
1299 // [Note: in this context, "contains" means "contains directly or
1300 // indirectly".
1301 //
1302 // For example:
1303 // namespace A { int i; }
1304 // void foo() {
1305 // int i;
1306 // {
1307 // using namespace A;
1308 // ++i; // finds local 'i', A::i appears at global scope
1309 // }
1310 // }
1311 //
1312 UnqualUsingDirectiveSet UDirs(*this);
1313 bool VisitedUsingDirectives = false;
1314 bool LeftStartingScope = false;
1315
1316 // When performing a scope lookup, we want to find local extern decls.
1317 FindLocalExternScope FindLocals(R);
1318
1319 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1320 bool SearchNamespaceScope = true;
1321 // Check whether the IdResolver has anything in this scope.
1322 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1323 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1324 if (NameKind == LookupRedeclarationWithLinkage &&
1325 !(*I)->isTemplateParameter()) {
1326 // If it's a template parameter, we still find it, so we can diagnose
1327 // the invalid redeclaration.
1328
1329 // Determine whether this (or a previous) declaration is
1330 // out-of-scope.
1331 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1332 LeftStartingScope = true;
1333
1334 // If we found something outside of our starting scope that
1335 // does not have linkage, skip it.
1336 if (LeftStartingScope && !((*I)->hasLinkage())) {
1337 R.setShadowed();
1338 continue;
1339 }
1340 } else {
1341 // We found something in this scope, we should not look at the
1342 // namespace scope
1343 SearchNamespaceScope = false;
1344 }
1345 R.addDecl(ND);
1346 }
1347 }
1348 if (!SearchNamespaceScope) {
1349 R.resolveKind();
1350 if (S->isClassScope())
1351 if (auto *Record = dyn_cast_if_present<CXXRecordDecl>(S->getEntity()))
1353 return true;
1354 }
1355
1356 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1357 // C++11 [class.friend]p11:
1358 // If a friend declaration appears in a local class and the name
1359 // specified is an unqualified name, a prior declaration is
1360 // looked up without considering scopes that are outside the
1361 // innermost enclosing non-class scope.
1362 return false;
1363 }
1364
1365 if (DeclContext *Ctx = S->getLookupEntity()) {
1366 DeclContext *OuterCtx = findOuterContext(S);
1367 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1368 // We do not directly look into transparent contexts, since
1369 // those entities will be found in the nearest enclosing
1370 // non-transparent context.
1371 if (Ctx->isTransparentContext())
1372 continue;
1373
1374 // We do not look directly into function or method contexts,
1375 // since all of the local variables and parameters of the
1376 // function/method are present within the Scope.
1377 if (Ctx->isFunctionOrMethod()) {
1378 // If we have an Objective-C instance method, look for ivars
1379 // in the corresponding interface.
1380 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1381 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1382 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1383 ObjCInterfaceDecl *ClassDeclared;
1384 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1385 Name.getAsIdentifierInfo(),
1386 ClassDeclared)) {
1387 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1388 R.addDecl(ND);
1389 R.resolveKind();
1390 return true;
1391 }
1392 }
1393 }
1394 }
1395
1396 continue;
1397 }
1398
1399 // If this is a file context, we need to perform unqualified name
1400 // lookup considering using directives.
1401 if (Ctx->isFileContext()) {
1402 // If we haven't handled using directives yet, do so now.
1403 if (!VisitedUsingDirectives) {
1404 // Add using directives from this context up to the top level.
1405 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1406 if (UCtx->isTransparentContext())
1407 continue;
1408
1409 UDirs.visit(UCtx, UCtx);
1410 }
1411
1412 // Find the innermost file scope, so we can add using directives
1413 // from local scopes.
1414 Scope *InnermostFileScope = S;
1415 while (InnermostFileScope &&
1416 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1417 InnermostFileScope = InnermostFileScope->getParent();
1418 UDirs.visitScopeChain(Initial, InnermostFileScope);
1419
1420 UDirs.done();
1421
1422 VisitedUsingDirectives = true;
1423 }
1424
1425 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1426 R.resolveKind();
1427 return true;
1428 }
1429
1430 continue;
1431 }
1432
1433 // Perform qualified name lookup into this context.
1434 // FIXME: In some cases, we know that every name that could be found by
1435 // this qualified name lookup will also be on the identifier chain. For
1436 // example, inside a class without any base classes, we never need to
1437 // perform qualified lookup because all of the members are on top of the
1438 // identifier chain.
1439 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1440 return true;
1441 }
1442 }
1443 }
1444
1445 // Stop if we ran out of scopes.
1446 // FIXME: This really, really shouldn't be happening.
1447 if (!S) return false;
1448
1449 // If we are looking for members, no need to look into global/namespace scope.
1450 if (NameKind == LookupMemberName)
1451 return false;
1452
1453 // Collect UsingDirectiveDecls in all scopes, and recursively all
1454 // nominated namespaces by those using-directives.
1455 //
1456 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1457 // don't build it for each lookup!
1458 if (!VisitedUsingDirectives) {
1459 UDirs.visitScopeChain(Initial, S);
1460 UDirs.done();
1461 }
1462
1463 // If we're not performing redeclaration lookup, do not look for local
1464 // extern declarations outside of a function scope.
1465 if (!R.isForRedeclaration())
1466 FindLocals.restore();
1467
1468 // Lookup namespace scope, and global scope.
1469 // Unqualified name lookup in C++ requires looking into scopes
1470 // that aren't strictly lexical, and therefore we walk through the
1471 // context as well as walking through the scopes.
1472 for (; S; S = S->getParent()) {
1473 // Check whether the IdResolver has anything in this scope.
1474 bool Found = false;
1475 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1476 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1477 // We found something. Look for anything else in our scope
1478 // with this same name and in an acceptable identifier
1479 // namespace, so that we can construct an overload set if we
1480 // need to.
1481 Found = true;
1482 R.addDecl(ND);
1483 }
1484 }
1485
1486 if (Found && S->isTemplateParamScope()) {
1487 R.resolveKind();
1488 return true;
1489 }
1490
1491 DeclContext *Ctx = S->getLookupEntity();
1492 if (Ctx) {
1493 DeclContext *OuterCtx = findOuterContext(S);
1494 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1495 // We do not directly look into transparent contexts, since
1496 // those entities will be found in the nearest enclosing
1497 // non-transparent context.
1498 if (Ctx->isTransparentContext())
1499 continue;
1500
1501 // If we have a context, and it's not a context stashed in the
1502 // template parameter scope for an out-of-line definition, also
1503 // look into that context.
1504 if (!(Found && S->isTemplateParamScope())) {
1505 assert(Ctx->isFileContext() &&
1506 "We should have been looking only at file context here already.");
1507
1508 // Look into context considering using-directives.
1509 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1510 Found = true;
1511 }
1512
1513 if (Found) {
1514 R.resolveKind();
1515 return true;
1516 }
1517
1518 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1519 return false;
1520 }
1521 }
1522
1523 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1524 return false;
1525 }
1526
1527 return !R.empty();
1528}
1529
1531 if (auto *M = getCurrentModule())
1533 else
1534 // We're not building a module; just make the definition visible.
1536
1537 // If ND is a template declaration, make the template parameters
1538 // visible too. They're not (necessarily) within a mergeable DeclContext.
1539 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1540 for (auto *Param : *TD->getTemplateParameters())
1542}
1543
1544/// Find the module in which the given declaration was defined.
1545static Module *getDefiningModule(Sema &S, Decl *Entity) {
1546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1547 // If this function was instantiated from a template, the defining module is
1548 // the module containing the pattern.
1549 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1550 Entity = Pattern;
1551 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1553 Entity = Pattern;
1554 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1555 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1556 Entity = Pattern;
1557 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1558 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1559 Entity = Pattern;
1560 }
1561
1562 // Walk up to the containing context. That might also have been instantiated
1563 // from a template.
1564 DeclContext *Context = Entity->getLexicalDeclContext();
1565 if (Context->isFileContext())
1566 return S.getOwningModule(Entity);
1567 return getDefiningModule(S, cast<Decl>(Context));
1568}
1569
1571 unsigned N = CodeSynthesisContexts.size();
1572 for (unsigned I = CodeSynthesisContextLookupModules.size();
1573 I != N; ++I) {
1574 Module *M = CodeSynthesisContexts[I].Entity ?
1575 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
1576 nullptr;
1577 if (M && !LookupModulesCache.insert(M).second)
1578 M = nullptr;
1580 }
1581 return LookupModulesCache;
1582}
1583
1584/// Determine if we could use all the declarations in the module.
1585bool Sema::isUsableModule(const Module *M) {
1586 assert(M && "We shouldn't check nullness for module here");
1587 // Return quickly if we cached the result.
1588 if (UsableModuleUnitsCache.count(M))
1589 return true;
1590
1591 // If M is the global module fragment of the current translation unit. So it
1592 // should be usable.
1593 // [module.global.frag]p1:
1594 // The global module fragment can be used to provide declarations that are
1595 // attached to the global module and usable within the module unit.
1596 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment ||
1597 // If M is the module we're parsing, it should be usable. This covers the
1598 // private module fragment. The private module fragment is usable only if
1599 // it is within the current module unit. And it must be the current
1600 // parsing module unit if it is within the current module unit according
1601 // to the grammar of the private module fragment. NOTE: This is covered by
1602 // the following condition. The intention of the check is to avoid string
1603 // comparison as much as possible.
1604 M == getCurrentModule() ||
1605 // The module unit which is in the same module with the current module
1606 // unit is usable.
1607 //
1608 // FIXME: Here we judge if they are in the same module by comparing the
1609 // string. Is there any better solution?
1611 llvm::StringRef(getLangOpts().CurrentModule).split(':').first) {
1612 UsableModuleUnitsCache.insert(M);
1613 return true;
1614 }
1615
1616 return false;
1617}
1618
1620 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1621 if (isModuleVisible(Merged))
1622 return true;
1623 return false;
1624}
1625
1627 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1628 if (isUsableModule(Merged))
1629 return true;
1630 return false;
1631}
1632
1633template <typename ParmDecl>
1634static bool
1637 Sema::AcceptableKind Kind) {
1638 if (!D->hasDefaultArgument())
1639 return false;
1640
1642 while (D && Visited.insert(D).second) {
1643 auto &DefaultArg = D->getDefaultArgStorage();
1644 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
1645 return true;
1646
1647 if (!DefaultArg.isInherited() && Modules) {
1648 auto *NonConstD = const_cast<ParmDecl*>(D);
1649 Modules->push_back(S.getOwningModule(NonConstD));
1650 }
1651
1652 // If there was a previous default argument, maybe its parameter is
1653 // acceptable.
1654 D = DefaultArg.getInheritedFrom();
1655 }
1656 return false;
1657}
1658
1660 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,
1661 Sema::AcceptableKind Kind) {
1662 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1663 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1664
1665 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1666 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1667
1668 return ::hasAcceptableDefaultArgument(
1669 *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
1670}
1671
1674 return hasAcceptableDefaultArgument(D, Modules,
1676}
1677
1679 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1680 return hasAcceptableDefaultArgument(D, Modules,
1682}
1683
1684template <typename Filter>
1685static bool
1687 llvm::SmallVectorImpl<Module *> *Modules, Filter F,
1688 Sema::AcceptableKind Kind) {
1689 bool HasFilteredRedecls = false;
1690
1691 for (auto *Redecl : D->redecls()) {
1692 auto *R = cast<NamedDecl>(Redecl);
1693 if (!F(R))
1694 continue;
1695
1696 if (S.isAcceptable(R, Kind))
1697 return true;
1698
1699 HasFilteredRedecls = true;
1700
1701 if (Modules)
1702 Modules->push_back(R->getOwningModule());
1703 }
1704
1705 // Only return false if there is at least one redecl that is not filtered out.
1706 if (HasFilteredRedecls)
1707 return false;
1708
1709 return true;
1710}
1711
1712static bool
1715 Sema::AcceptableKind Kind) {
1717 S, D, Modules,
1718 [](const NamedDecl *D) {
1719 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1720 return RD->getTemplateSpecializationKind() ==
1722 if (auto *FD = dyn_cast<FunctionDecl>(D))
1723 return FD->getTemplateSpecializationKind() ==
1725 if (auto *VD = dyn_cast<VarDecl>(D))
1726 return VD->getTemplateSpecializationKind() ==
1728 llvm_unreachable("unknown explicit specialization kind");
1729 },
1730 Kind);
1731}
1732
1734 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1735 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1737}
1738
1740 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1741 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1743}
1744
1745static bool
1748 Sema::AcceptableKind Kind) {
1749 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1750 "not a member specialization");
1752 S, D, Modules,
1753 [](const NamedDecl *D) {
1754 // If the specialization is declared at namespace scope, then it's a
1755 // member specialization declaration. If it's lexically inside the class
1756 // definition then it was instantiated.
1757 //
1758 // FIXME: This is a hack. There should be a better way to determine
1759 // this.
1760 // FIXME: What about MS-style explicit specializations declared within a
1761 // class definition?
1762 return D->getLexicalDeclContext()->isFileContext();
1763 },
1764 Kind);
1765}
1766
1768 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1769 return hasAcceptableMemberSpecialization(*this, D, Modules,
1771}
1772
1774 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1775 return hasAcceptableMemberSpecialization(*this, D, Modules,
1777}
1778
1779/// Determine whether a declaration is acceptable to name lookup.
1780///
1781/// This routine determines whether the declaration D is acceptable in the
1782/// current lookup context, taking into account the current template
1783/// instantiation stack. During template instantiation, a declaration is
1784/// acceptable if it is acceptable from a module containing any entity on the
1785/// template instantiation path (by instantiating a template, you allow it to
1786/// see the declarations that your module can see, including those later on in
1787/// your module).
1788bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
1789 Sema::AcceptableKind Kind) {
1790 assert(!D->isUnconditionallyVisible() &&
1791 "should not call this: not in slow case");
1792
1793 Module *DeclModule = SemaRef.getOwningModule(D);
1794 assert(DeclModule && "hidden decl has no owning module");
1795
1796 // If the owning module is visible, the decl is acceptable.
1797 if (SemaRef.isModuleVisible(DeclModule,
1799 return true;
1800
1801 // Determine whether a decl context is a file context for the purpose of
1802 // visibility/reachability. This looks through some (export and linkage spec)
1803 // transparent contexts, but not others (enums).
1804 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1805 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1806 isa<ExportDecl>(DC);
1807 };
1808
1809 // If this declaration is not at namespace scope
1810 // then it is acceptable if its lexical parent has a acceptable definition.
1812 if (DC && !IsEffectivelyFileContext(DC)) {
1813 // For a parameter, check whether our current template declaration's
1814 // lexical context is acceptable, not whether there's some other acceptable
1815 // definition of it, because parameters aren't "within" the definition.
1816 //
1817 // In C++ we need to check for a acceptable definition due to ODR merging,
1818 // and in C we must not because each declaration of a function gets its own
1819 // set of declarations for tags in prototype scope.
1820 bool AcceptableWithinParent;
1821 if (D->isTemplateParameter()) {
1822 bool SearchDefinitions = true;
1823 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1824 if (const auto *TD = DCD->getDescribedTemplate()) {
1825 TemplateParameterList *TPL = TD->getTemplateParameters();
1826 auto Index = getDepthAndIndex(D).second;
1827 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1828 }
1829 }
1830 if (SearchDefinitions)
1831 AcceptableWithinParent =
1832 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1833 else
1834 AcceptableWithinParent =
1835 isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1836 } else if (isa<ParmVarDecl>(D) ||
1837 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1838 AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1839 else if (D->isModulePrivate()) {
1840 // A module-private declaration is only acceptable if an enclosing lexical
1841 // parent was merged with another definition in the current module.
1842 AcceptableWithinParent = false;
1843 do {
1844 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1845 AcceptableWithinParent = true;
1846 break;
1847 }
1848 DC = DC->getLexicalParent();
1849 } while (!IsEffectivelyFileContext(DC));
1850 } else {
1851 AcceptableWithinParent =
1852 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1853 }
1854
1855 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1857 // FIXME: Do something better in this case.
1858 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1859 // Cache the fact that this declaration is implicitly visible because
1860 // its parent has a visible definition.
1862 }
1863 return AcceptableWithinParent;
1864 }
1865
1867 return false;
1868
1869 assert(Kind == Sema::AcceptableKind::Reachable &&
1870 "Additional Sema::AcceptableKind?");
1871 return isReachableSlow(SemaRef, D);
1872}
1873
1874bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1875 // The module might be ordinarily visible. For a module-private query, that
1876 // means it is part of the current module.
1877 if (ModulePrivate && isUsableModule(M))
1878 return true;
1879
1880 // For a query which is not module-private, that means it is in our visible
1881 // module set.
1882 if (!ModulePrivate && VisibleModules.isVisible(M))
1883 return true;
1884
1885 // Otherwise, it might be visible by virtue of the query being within a
1886 // template instantiation or similar that is permitted to look inside M.
1887
1888 // Find the extra places where we need to look.
1889 const auto &LookupModules = getLookupModules();
1890 if (LookupModules.empty())
1891 return false;
1892
1893 // If our lookup set contains the module, it's visible.
1894 if (LookupModules.count(M))
1895 return true;
1896
1897 // The global module fragments are visible to its corresponding module unit.
1898 // So the global module fragment should be visible if the its corresponding
1899 // module unit is visible.
1900 if (M->isGlobalModule() && LookupModules.count(M->getTopLevelModule()))
1901 return true;
1902
1903 // For a module-private query, that's everywhere we get to look.
1904 if (ModulePrivate)
1905 return false;
1906
1907 // Check whether M is transitively exported to an import of the lookup set.
1908 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1909 return LookupM->isModuleVisible(M);
1910 });
1911}
1912
1913// FIXME: Return false directly if we don't have an interface dependency on the
1914// translation unit containing D.
1915bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
1916 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
1917
1918 Module *DeclModule = SemaRef.getOwningModule(D);
1919 assert(DeclModule && "hidden decl has no owning module");
1920
1921 // Entities in header like modules are reachable only if they're visible.
1922 if (DeclModule->isHeaderLikeModule())
1923 return false;
1924
1925 if (!D->isInAnotherModuleUnit())
1926 return true;
1927
1928 // [module.reach]/p3:
1929 // A declaration D is reachable from a point P if:
1930 // ...
1931 // - D is not discarded ([module.global.frag]), appears in a translation unit
1932 // that is reachable from P, and does not appear within a private module
1933 // fragment.
1934 //
1935 // A declaration that's discarded in the GMF should be module-private.
1936 if (D->isModulePrivate())
1937 return false;
1938
1939 // [module.reach]/p1
1940 // A translation unit U is necessarily reachable from a point P if U is a
1941 // module interface unit on which the translation unit containing P has an
1942 // interface dependency, or the translation unit containing P imports U, in
1943 // either case prior to P ([module.import]).
1944 //
1945 // [module.import]/p10
1946 // A translation unit has an interface dependency on a translation unit U if
1947 // it contains a declaration (possibly a module-declaration) that imports U
1948 // or if it has an interface dependency on a translation unit that has an
1949 // interface dependency on U.
1950 //
1951 // So we could conclude the module unit U is necessarily reachable if:
1952 // (1) The module unit U is module interface unit.
1953 // (2) The current unit has an interface dependency on the module unit U.
1954 //
1955 // Here we only check for the first condition. Since we couldn't see
1956 // DeclModule if it isn't (transitively) imported.
1957 if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit())
1958 return true;
1959
1960 // [module.reach]/p2
1961 // Additional translation units on
1962 // which the point within the program has an interface dependency may be
1963 // considered reachable, but it is unspecified which are and under what
1964 // circumstances.
1965 //
1966 // The decision here is to treat all additional tranditional units as
1967 // unreachable.
1968 return false;
1969}
1970
1971bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
1972 return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);
1973}
1974
1975bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1976 // FIXME: If there are both visible and hidden declarations, we need to take
1977 // into account whether redeclaration is possible. Example:
1978 //
1979 // Non-imported module:
1980 // int f(T); // #1
1981 // Some TU:
1982 // static int f(U); // #2, not a redeclaration of #1
1983 // int f(T); // #3, finds both, should link with #1 if T != U, but
1984 // // with #2 if T == U; neither should be ambiguous.
1985 for (auto *D : R) {
1986 if (isVisible(D))
1987 return true;
1988 assert(D->isExternallyDeclarable() &&
1989 "should not have hidden, non-externally-declarable result here");
1990 }
1991
1992 // This function is called once "New" is essentially complete, but before a
1993 // previous declaration is attached. We can't query the linkage of "New" in
1994 // general, because attaching the previous declaration can change the
1995 // linkage of New to match the previous declaration.
1996 //
1997 // However, because we've just determined that there is no *visible* prior
1998 // declaration, we can compute the linkage here. There are two possibilities:
1999 //
2000 // * This is not a redeclaration; it's safe to compute the linkage now.
2001 //
2002 // * This is a redeclaration of a prior declaration that is externally
2003 // redeclarable. In that case, the linkage of the declaration is not
2004 // changed by attaching the prior declaration, because both are externally
2005 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
2006 //
2007 // FIXME: This is subtle and fragile.
2008 return New->isExternallyDeclarable();
2009}
2010
2011/// Retrieve the visible declaration corresponding to D, if any.
2012///
2013/// This routine determines whether the declaration D is visible in the current
2014/// module, with the current imports. If not, it checks whether any
2015/// redeclaration of D is visible, and if so, returns that declaration.
2016///
2017/// \returns D, or a visible previous declaration of D, whichever is more recent
2018/// and visible. If no declaration of D is visible, returns null.
2020 unsigned IDNS) {
2021 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
2022
2023 for (auto *RD : D->redecls()) {
2024 // Don't bother with extra checks if we already know this one isn't visible.
2025 if (RD == D)
2026 continue;
2027
2028 auto ND = cast<NamedDecl>(RD);
2029 // FIXME: This is wrong in the case where the previous declaration is not
2030 // visible in the same scope as D. This needs to be done much more
2031 // carefully.
2032 if (ND->isInIdentifierNamespace(IDNS) &&
2034 return ND;
2035 }
2036
2037 return nullptr;
2038}
2039
2042 assert(!isVisible(D) && "not in slow case");
2044 *this, D, Modules, [](const NamedDecl *) { return true; },
2046}
2047
2049 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
2050 assert(!isReachable(D) && "not in slow case");
2052 *this, D, Modules, [](const NamedDecl *) { return true; },
2054}
2055
2056NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
2057 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
2058 // Namespaces are a bit of a special case: we expect there to be a lot of
2059 // redeclarations of some namespaces, all declarations of a namespace are
2060 // essentially interchangeable, all declarations are found by name lookup
2061 // if any is, and namespaces are never looked up during template
2062 // instantiation. So we benefit from caching the check in this case, and
2063 // it is correct to do so.
2064 auto *Key = ND->getCanonicalDecl();
2065 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
2066 return Acceptable;
2067 auto *Acceptable = isVisible(getSema(), Key)
2068 ? Key
2069 : findAcceptableDecl(getSema(), Key, IDNS);
2070 if (Acceptable)
2071 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
2072 return Acceptable;
2073 }
2074
2075 return findAcceptableDecl(getSema(), D, IDNS);
2076}
2077
2079 // If this declaration is already visible, return it directly.
2080 if (D->isUnconditionallyVisible())
2081 return true;
2082
2083 // During template instantiation, we can refer to hidden declarations, if
2084 // they were visible in any module along the path of instantiation.
2085 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);
2086}
2087
2089 if (D->isUnconditionallyVisible())
2090 return true;
2091
2092 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);
2093}
2094
2096 // We should check the visibility at the callsite already.
2097 if (isVisible(SemaRef, ND))
2098 return true;
2099
2100 // Deduction guide lives in namespace scope generally, but it is just a
2101 // hint to the compilers. What we actually lookup for is the generated member
2102 // of the corresponding template. So it is sufficient to check the
2103 // reachability of the template decl.
2104 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())
2105 return SemaRef.hasReachableDefinition(DeductionGuide);
2106
2107 // FIXME: The lookup for allocation function is a standalone process.
2108 // (We can find the logics in Sema::FindAllocationFunctions)
2109 //
2110 // Such structure makes it a problem when we instantiate a template
2111 // declaration using placement allocation function if the placement
2112 // allocation function is invisible.
2113 // (See https://github.com/llvm/llvm-project/issues/59601)
2114 //
2115 // Here we workaround it by making the placement allocation functions
2116 // always acceptable. The downside is that we can't diagnose the direct
2117 // use of the invisible placement allocation functions. (Although such uses
2118 // should be rare).
2119 if (auto *FD = dyn_cast<FunctionDecl>(ND);
2120 FD && FD->isReservedGlobalPlacementOperator())
2121 return true;
2122
2123 auto *DC = ND->getDeclContext();
2124 // If ND is not visible and it is at namespace scope, it shouldn't be found
2125 // by name lookup.
2126 if (DC->isFileContext())
2127 return false;
2128
2129 // [module.interface]p7
2130 // Class and enumeration member names can be found by name lookup in any
2131 // context in which a definition of the type is reachable.
2132 //
2133 // FIXME: The current implementation didn't consider about scope. For example,
2134 // ```
2135 // // m.cppm
2136 // export module m;
2137 // enum E1 { e1 };
2138 // // Use.cpp
2139 // import m;
2140 // void test() {
2141 // auto a = E1::e1; // Error as expected.
2142 // auto b = e1; // Should be error. namespace-scope name e1 is not visible
2143 // }
2144 // ```
2145 // For the above example, the current implementation would emit error for `a`
2146 // correctly. However, the implementation wouldn't diagnose about `b` now.
2147 // Since we only check the reachability for the parent only.
2148 // See clang/test/CXX/module/module.interface/p7.cpp for example.
2149 if (auto *TD = dyn_cast<TagDecl>(DC))
2150 return SemaRef.hasReachableDefinition(TD);
2151
2152 return false;
2153}
2154
2155/// Perform unqualified name lookup starting from a given
2156/// scope.
2157///
2158/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
2159/// used to find names within the current scope. For example, 'x' in
2160/// @code
2161/// int x;
2162/// int f() {
2163/// return x; // unqualified name look finds 'x' in the global scope
2164/// }
2165/// @endcode
2166///
2167/// Different lookup criteria can find different names. For example, a
2168/// particular scope can have both a struct and a function of the same
2169/// name, and each can be found by certain lookup criteria. For more
2170/// information about lookup criteria, see the documentation for the
2171/// class LookupCriteria.
2172///
2173/// @param S The scope from which unqualified name lookup will
2174/// begin. If the lookup criteria permits, name lookup may also search
2175/// in the parent scopes.
2176///
2177/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
2178/// look up and the lookup kind), and is updated with the results of lookup
2179/// including zero or more declarations and possibly additional information
2180/// used to diagnose ambiguities.
2181///
2182/// @returns \c true if lookup succeeded and false otherwise.
2183bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
2184 bool ForceNoCPlusPlus) {
2185 DeclarationName Name = R.getLookupName();
2186 if (!Name) return false;
2187
2188 LookupNameKind NameKind = R.getLookupKind();
2189
2190 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
2191 // Unqualified name lookup in C/Objective-C is purely lexical, so
2192 // search in the declarations attached to the name.
2193 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
2194 // Find the nearest non-transparent declaration scope.
2195 while (!(S->getFlags() & Scope::DeclScope) ||
2196 (S->getEntity() && S->getEntity()->isTransparentContext()))
2197 S = S->getParent();
2198 }
2199
2200 // When performing a scope lookup, we want to find local extern decls.
2201 FindLocalExternScope FindLocals(R);
2202
2203 // Scan up the scope chain looking for a decl that matches this
2204 // identifier that is in the appropriate namespace. This search
2205 // should not take long, as shadowing of names is uncommon, and
2206 // deep shadowing is extremely uncommon.
2207 bool LeftStartingScope = false;
2208
2210 IEnd = IdResolver.end();
2211 I != IEnd; ++I)
2212 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
2213 if (NameKind == LookupRedeclarationWithLinkage) {
2214 // Determine whether this (or a previous) declaration is
2215 // out-of-scope.
2216 if (!LeftStartingScope && !S->isDeclScope(*I))
2217 LeftStartingScope = true;
2218
2219 // If we found something outside of our starting scope that
2220 // does not have linkage, skip it.
2221 if (LeftStartingScope && !((*I)->hasLinkage())) {
2222 R.setShadowed();
2223 continue;
2224 }
2225 }
2226 else if (NameKind == LookupObjCImplicitSelfParam &&
2227 !isa<ImplicitParamDecl>(*I))
2228 continue;
2229
2230 R.addDecl(D);
2231
2232 // Check whether there are any other declarations with the same name
2233 // and in the same scope.
2234 if (I != IEnd) {
2235 // Find the scope in which this declaration was declared (if it
2236 // actually exists in a Scope).
2237 while (S && !S->isDeclScope(D))
2238 S = S->getParent();
2239
2240 // If the scope containing the declaration is the translation unit,
2241 // then we'll need to perform our checks based on the matching
2242 // DeclContexts rather than matching scopes.
2244 S = nullptr;
2245
2246 // Compute the DeclContext, if we need it.
2247 DeclContext *DC = nullptr;
2248 if (!S)
2249 DC = (*I)->getDeclContext()->getRedeclContext();
2250
2252 for (++LastI; LastI != IEnd; ++LastI) {
2253 if (S) {
2254 // Match based on scope.
2255 if (!S->isDeclScope(*LastI))
2256 break;
2257 } else {
2258 // Match based on DeclContext.
2259 DeclContext *LastDC
2260 = (*LastI)->getDeclContext()->getRedeclContext();
2261 if (!LastDC->Equals(DC))
2262 break;
2263 }
2264
2265 // If the declaration is in the right namespace and visible, add it.
2266 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
2267 R.addDecl(LastD);
2268 }
2269
2270 R.resolveKind();
2271 }
2272
2273 return true;
2274 }
2275 } else {
2276 // Perform C++ unqualified name lookup.
2277 if (CppLookupName(R, S))
2278 return true;
2279 }
2280
2281 // If we didn't find a use of this identifier, and if the identifier
2282 // corresponds to a compiler builtin, create the decl object for the builtin
2283 // now, injecting it into translation unit scope, and return it.
2284 if (AllowBuiltinCreation && LookupBuiltin(R))
2285 return true;
2286
2287 // If we didn't find a use of this identifier, the ExternalSource
2288 // may be able to handle the situation.
2289 // Note: some lookup failures are expected!
2290 // See e.g. R.isForRedeclaration().
2291 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2292}
2293
2294/// Perform qualified name lookup in the namespaces nominated by
2295/// using directives by the given context.
2296///
2297/// C++98 [namespace.qual]p2:
2298/// Given X::m (where X is a user-declared namespace), or given \::m
2299/// (where X is the global namespace), let S be the set of all
2300/// declarations of m in X and in the transitive closure of all
2301/// namespaces nominated by using-directives in X and its used
2302/// namespaces, except that using-directives are ignored in any
2303/// namespace, including X, directly containing one or more
2304/// declarations of m. No namespace is searched more than once in
2305/// the lookup of a name. If S is the empty set, the program is
2306/// ill-formed. Otherwise, if S has exactly one member, or if the
2307/// context of the reference is a using-declaration
2308/// (namespace.udecl), S is the required set of declarations of
2309/// m. Otherwise if the use of m is not one that allows a unique
2310/// declaration to be chosen from S, the program is ill-formed.
2311///
2312/// C++98 [namespace.qual]p5:
2313/// During the lookup of a qualified namespace member name, if the
2314/// lookup finds more than one declaration of the member, and if one
2315/// declaration introduces a class name or enumeration name and the
2316/// other declarations either introduce the same object, the same
2317/// enumerator or a set of functions, the non-type name hides the
2318/// class or enumeration name if and only if the declarations are
2319/// from the same namespace; otherwise (the declarations are from
2320/// different namespaces), the program is ill-formed.
2322 DeclContext *StartDC) {
2323 assert(StartDC->isFileContext() && "start context is not a file context");
2324
2325 // We have not yet looked into these namespaces, much less added
2326 // their "using-children" to the queue.
2328
2329 // We have at least added all these contexts to the queue.
2331 Visited.insert(StartDC);
2332
2333 // We have already looked into the initial namespace; seed the queue
2334 // with its using-children.
2335 for (auto *I : StartDC->using_directives()) {
2336 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
2337 if (S.isVisible(I) && Visited.insert(ND).second)
2338 Queue.push_back(ND);
2339 }
2340
2341 // The easiest way to implement the restriction in [namespace.qual]p5
2342 // is to check whether any of the individual results found a tag
2343 // and, if so, to declare an ambiguity if the final result is not
2344 // a tag.
2345 bool FoundTag = false;
2346 bool FoundNonTag = false;
2347
2349
2350 bool Found = false;
2351 while (!Queue.empty()) {
2352 NamespaceDecl *ND = Queue.pop_back_val();
2353
2354 // We go through some convolutions here to avoid copying results
2355 // between LookupResults.
2356 bool UseLocal = !R.empty();
2357 LookupResult &DirectR = UseLocal ? LocalR : R;
2358 bool FoundDirect = LookupDirect(S, DirectR, ND);
2359
2360 if (FoundDirect) {
2361 // First do any local hiding.
2362 DirectR.resolveKind();
2363
2364 // If the local result is a tag, remember that.
2365 if (DirectR.isSingleTagDecl())
2366 FoundTag = true;
2367 else
2368 FoundNonTag = true;
2369
2370 // Append the local results to the total results if necessary.
2371 if (UseLocal) {
2372 R.addAllDecls(LocalR);
2373 LocalR.clear();
2374 }
2375 }
2376
2377 // If we find names in this namespace, ignore its using directives.
2378 if (FoundDirect) {
2379 Found = true;
2380 continue;
2381 }
2382
2383 for (auto *I : ND->using_directives()) {
2384 NamespaceDecl *Nom = I->getNominatedNamespace();
2385 if (S.isVisible(I) && Visited.insert(Nom).second)
2386 Queue.push_back(Nom);
2387 }
2388 }
2389
2390 if (Found) {
2391 if (FoundTag && FoundNonTag)
2393 else
2394 R.resolveKind();
2395 }
2396
2397 return Found;
2398}
2399
2400/// Perform qualified name lookup into a given context.
2401///
2402/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2403/// names when the context of those names is explicit specified, e.g.,
2404/// "std::vector" or "x->member", or as part of unqualified name lookup.
2405///
2406/// Different lookup criteria can find different names. For example, a
2407/// particular scope can have both a struct and a function of the same
2408/// name, and each can be found by certain lookup criteria. For more
2409/// information about lookup criteria, see the documentation for the
2410/// class LookupCriteria.
2411///
2412/// \param R captures both the lookup criteria and any lookup results found.
2413///
2414/// \param LookupCtx The context in which qualified name lookup will
2415/// search. If the lookup criteria permits, name lookup may also search
2416/// in the parent contexts or (for C++ classes) base classes.
2417///
2418/// \param InUnqualifiedLookup true if this is qualified name lookup that
2419/// occurs as part of unqualified name lookup.
2420///
2421/// \returns true if lookup succeeded, false if it failed.
2423 bool InUnqualifiedLookup) {
2424 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2425
2426 if (!R.getLookupName())
2427 return false;
2428
2429 // Make sure that the declaration context is complete.
2430 assert((!isa<TagDecl>(LookupCtx) ||
2431 LookupCtx->isDependentContext() ||
2432 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2433 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2434 "Declaration context must already be complete!");
2435
2436 struct QualifiedLookupInScope {
2437 bool oldVal;
2438 DeclContext *Context;
2439 // Set flag in DeclContext informing debugger that we're looking for qualified name
2440 QualifiedLookupInScope(DeclContext *ctx)
2441 : oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) {
2442 ctx->setUseQualifiedLookup();
2443 }
2444 ~QualifiedLookupInScope() {
2445 Context->setUseQualifiedLookup(oldVal);
2446 }
2447 } QL(LookupCtx);
2448
2449 if (LookupDirect(*this, R, LookupCtx)) {
2450 R.resolveKind();
2451 if (isa<CXXRecordDecl>(LookupCtx))
2452 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2453 return true;
2454 }
2455
2456 // Don't descend into implied contexts for redeclarations.
2457 // C++98 [namespace.qual]p6:
2458 // In a declaration for a namespace member in which the
2459 // declarator-id is a qualified-id, given that the qualified-id
2460 // for the namespace member has the form
2461 // nested-name-specifier unqualified-id
2462 // the unqualified-id shall name a member of the namespace
2463 // designated by the nested-name-specifier.
2464 // See also [class.mfct]p5 and [class.static.data]p2.
2465 if (R.isForRedeclaration())
2466 return false;
2467
2468 // If this is a namespace, look it up in the implied namespaces.
2469 if (LookupCtx->isFileContext())
2470 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2471
2472 // If this isn't a C++ class, we aren't allowed to look into base
2473 // classes, we're done.
2474 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2475 if (!LookupRec || !LookupRec->getDefinition())
2476 return false;
2477
2478 // We're done for lookups that can never succeed for C++ classes.
2479 if (R.getLookupKind() == LookupOperatorName ||
2483 return false;
2484
2485 // If we're performing qualified name lookup into a dependent class,
2486 // then we are actually looking into a current instantiation. If we have any
2487 // dependent base classes, then we either have to delay lookup until
2488 // template instantiation time (at which point all bases will be available)
2489 // or we have to fail.
2490 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2491 LookupRec->hasAnyDependentBases()) {
2493 return false;
2494 }
2495
2496 // Perform lookup into our base classes.
2497
2498 DeclarationName Name = R.getLookupName();
2499 unsigned IDNS = R.getIdentifierNamespace();
2500
2501 // Look for this member in our base classes.
2502 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2503 CXXBasePath &Path) -> bool {
2504 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2505 // Drop leading non-matching lookup results from the declaration list so
2506 // we don't need to consider them again below.
2507 for (Path.Decls = BaseRecord->lookup(Name).begin();
2508 Path.Decls != Path.Decls.end(); ++Path.Decls) {
2509 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2510 return true;
2511 }
2512 return false;
2513 };
2514
2515 CXXBasePaths Paths;
2516 Paths.setOrigin(LookupRec);
2517 if (!LookupRec->lookupInBases(BaseCallback, Paths))
2518 return false;
2519
2520 R.setNamingClass(LookupRec);
2521
2522 // C++ [class.member.lookup]p2:
2523 // [...] If the resulting set of declarations are not all from
2524 // sub-objects of the same type, or the set has a nonstatic member
2525 // and includes members from distinct sub-objects, there is an
2526 // ambiguity and the program is ill-formed. Otherwise that set is
2527 // the result of the lookup.
2528 QualType SubobjectType;
2529 int SubobjectNumber = 0;
2530 AccessSpecifier SubobjectAccess = AS_none;
2531
2532 // Check whether the given lookup result contains only static members.
2533 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2534 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2535 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2536 return false;
2537 return true;
2538 };
2539
2540 bool TemplateNameLookup = R.isTemplateNameLookup();
2541
2542 // Determine whether two sets of members contain the same members, as
2543 // required by C++ [class.member.lookup]p6.
2544 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2546 using Iterator = DeclContextLookupResult::iterator;
2547 using Result = const void *;
2548
2549 auto Next = [&](Iterator &It, Iterator End) -> Result {
2550 while (It != End) {
2551 NamedDecl *ND = *It++;
2552 if (!ND->isInIdentifierNamespace(IDNS))
2553 continue;
2554
2555 // C++ [temp.local]p3:
2556 // A lookup that finds an injected-class-name (10.2) can result in
2557 // an ambiguity in certain cases (for example, if it is found in
2558 // more than one base class). If all of the injected-class-names
2559 // that are found refer to specializations of the same class
2560 // template, and if the name is used as a template-name, the
2561 // reference refers to the class template itself and not a
2562 // specialization thereof, and is not ambiguous.
2563 if (TemplateNameLookup)
2564 if (auto *TD = getAsTemplateNameDecl(ND))
2565 ND = TD;
2566
2567 // C++ [class.member.lookup]p3:
2568 // type declarations (including injected-class-names) are replaced by
2569 // the types they designate
2570 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
2572 return T.getCanonicalType().getAsOpaquePtr();
2573 }
2574
2575 return ND->getUnderlyingDecl()->getCanonicalDecl();
2576 }
2577 return nullptr;
2578 };
2579
2580 // We'll often find the declarations are in the same order. Handle this
2581 // case (and the special case of only one declaration) efficiently.
2582 Iterator AIt = A, BIt = B, AEnd, BEnd;
2583 while (true) {
2584 Result AResult = Next(AIt, AEnd);
2585 Result BResult = Next(BIt, BEnd);
2586 if (!AResult && !BResult)
2587 return true;
2588 if (!AResult || !BResult)
2589 return false;
2590 if (AResult != BResult) {
2591 // Found a mismatch; carefully check both lists, accounting for the
2592 // possibility of declarations appearing more than once.
2593 llvm::SmallDenseMap<Result, bool, 32> AResults;
2594 for (; AResult; AResult = Next(AIt, AEnd))
2595 AResults.insert({AResult, /*FoundInB*/false});
2596 unsigned Found = 0;
2597 for (; BResult; BResult = Next(BIt, BEnd)) {
2598 auto It = AResults.find(BResult);
2599 if (It == AResults.end())
2600 return false;
2601 if (!It->second) {
2602 It->second = true;
2603 ++Found;
2604 }
2605 }
2606 return AResults.size() == Found;
2607 }
2608 }
2609 };
2610
2611 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2612 Path != PathEnd; ++Path) {
2613 const CXXBasePathElement &PathElement = Path->back();
2614
2615 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2616 // across all paths.
2617 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2618
2619 // Determine whether we're looking at a distinct sub-object or not.
2620 if (SubobjectType.isNull()) {
2621 // This is the first subobject we've looked at. Record its type.
2622 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2623 SubobjectNumber = PathElement.SubobjectNumber;
2624 continue;
2625 }
2626
2627 if (SubobjectType !=
2628 Context.getCanonicalType(PathElement.Base->getType())) {
2629 // We found members of the given name in two subobjects of
2630 // different types. If the declaration sets aren't the same, this
2631 // lookup is ambiguous.
2632 //
2633 // FIXME: The language rule says that this applies irrespective of
2634 // whether the sets contain only static members.
2635 if (HasOnlyStaticMembers(Path->Decls) &&
2636 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2637 continue;
2638
2639 R.setAmbiguousBaseSubobjectTypes(Paths);
2640 return true;
2641 }
2642
2643 // FIXME: This language rule no longer exists. Checking for ambiguous base
2644 // subobjects should be done as part of formation of a class member access
2645 // expression (when converting the object parameter to the member's type).
2646 if (SubobjectNumber != PathElement.SubobjectNumber) {
2647 // We have a different subobject of the same type.
2648
2649 // C++ [class.member.lookup]p5:
2650 // A static member, a nested type or an enumerator defined in
2651 // a base class T can unambiguously be found even if an object
2652 // has more than one base class subobject of type T.
2653 if (HasOnlyStaticMembers(Path->Decls))
2654 continue;
2655
2656 // We have found a nonstatic member name in multiple, distinct
2657 // subobjects. Name lookup is ambiguous.
2658 R.setAmbiguousBaseSubobjects(Paths);
2659 return true;
2660 }
2661 }
2662
2663 // Lookup in a base class succeeded; return these results.
2664
2665 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2666 I != E; ++I) {
2667 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2668 (*I)->getAccess());
2669 if (NamedDecl *ND = R.getAcceptableDecl(*I))
2670 R.addDecl(ND, AS);
2671 }
2672 R.resolveKind();
2673 return true;
2674}
2675
2676/// Performs qualified name lookup or special type of lookup for
2677/// "__super::" scope specifier.
2678///
2679/// This routine is a convenience overload meant to be called from contexts
2680/// that need to perform a qualified name lookup with an optional C++ scope
2681/// specifier that might require special kind of lookup.
2682///
2683/// \param R captures both the lookup criteria and any lookup results found.
2684///
2685/// \param LookupCtx The context in which qualified name lookup will
2686/// search.
2687///
2688/// \param SS An optional C++ scope-specifier.
2689///
2690/// \returns true if lookup succeeded, false if it failed.
2692 CXXScopeSpec &SS) {
2693 auto *NNS = SS.getScopeRep();
2694 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2695 return LookupInSuper(R, NNS->getAsRecordDecl());
2696 else
2697
2698 return LookupQualifiedName(R, LookupCtx);
2699}
2700
2701/// Performs name lookup for a name that was parsed in the
2702/// source code, and may contain a C++ scope specifier.
2703///
2704/// This routine is a convenience routine meant to be called from
2705/// contexts that receive a name and an optional C++ scope specifier
2706/// (e.g., "N::M::x"). It will then perform either qualified or
2707/// unqualified name lookup (with LookupQualifiedName or LookupName,
2708/// respectively) on the given name and return those results. It will
2709/// perform a special type of lookup for "__super::" scope specifier.
2710///
2711/// @param S The scope from which unqualified name lookup will
2712/// begin.
2713///
2714/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
2715///
2716/// @param EnteringContext Indicates whether we are going to enter the
2717/// context of the scope-specifier SS (if present).
2718///
2719/// @returns True if any decls were found (but possibly ambiguous)
2721 bool AllowBuiltinCreation, bool EnteringContext) {
2722 if (SS && SS->isInvalid()) {
2723 // When the scope specifier is invalid, don't even look for
2724 // anything.
2725 return false;
2726 }
2727
2728 if (SS && SS->isSet()) {
2729 NestedNameSpecifier *NNS = SS->getScopeRep();
2730 if (NNS->getKind() == NestedNameSpecifier::Super)
2731 return LookupInSuper(R, NNS->getAsRecordDecl());
2732
2733 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2734 // We have resolved the scope specifier to a particular declaration
2735 // contex, and will perform name lookup in that context.
2736 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2737 return false;
2738
2739 R.setContextRange(SS->getRange());
2740 return LookupQualifiedName(R, DC);
2741 }
2742
2743 // We could not resolve the scope specified to a specific declaration
2744 // context, which means that SS refers to an unknown specialization.
2745 // Name lookup can't find anything in this case.
2747 R.setContextRange(SS->getRange());
2748 return false;
2749 }
2750
2751 // Perform unqualified name lookup starting in the given scope.
2752 return LookupName(R, S, AllowBuiltinCreation);
2753}
2754
2755/// Perform qualified name lookup into all base classes of the given
2756/// class.
2757///
2758/// \param R captures both the lookup criteria and any lookup results found.
2759///
2760/// \param Class The context in which qualified name lookup will
2761/// search. Name lookup will search in all base classes merging the results.
2762///
2763/// @returns True if any decls were found (but possibly ambiguous)
2765 // The access-control rules we use here are essentially the rules for
2766 // doing a lookup in Class that just magically skipped the direct
2767 // members of Class itself. That is, the naming class is Class, and the
2768 // access includes the access of the base.
2769 for (const auto &BaseSpec : Class->bases()) {
2770 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2771 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2773 Result.setBaseObjectType(Context.getRecordType(Class));
2775
2776 // Copy the lookup results into the target, merging the base's access into
2777 // the path access.
2778 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2779 R.addDecl(I.getDecl(),
2780 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2781 I.getAccess()));
2782 }
2783
2784 Result.suppressDiagnostics();
2785 }
2786
2787 R.resolveKind();
2789
2790 return !R.empty();
2791}
2792
2793/// Produce a diagnostic describing the ambiguity that resulted
2794/// from name lookup.
2795///
2796/// \param Result The result of the ambiguous lookup to be diagnosed.
2798 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2799
2800 DeclarationName Name = Result.getLookupName();
2801 SourceLocation NameLoc = Result.getNameLoc();
2802 SourceRange LookupRange = Result.getContextRange();
2803
2804 switch (Result.getAmbiguityKind()) {
2806 CXXBasePaths *Paths = Result.getBasePaths();
2807 QualType SubobjectType = Paths->front().back().Base->getType();
2808 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2809 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2810 << LookupRange;
2811
2812 DeclContext::lookup_iterator Found = Paths->front().Decls;
2813 while (isa<CXXMethodDecl>(*Found) &&
2814 cast<CXXMethodDecl>(*Found)->isStatic())
2815 ++Found;
2816
2817 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2818 break;
2819 }
2820
2822 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2823 << Name << LookupRange;
2824
2825 CXXBasePaths *Paths = Result.getBasePaths();
2826 std::set<const NamedDecl *> DeclsPrinted;
2827 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2828 PathEnd = Paths->end();
2829 Path != PathEnd; ++Path) {
2830 const NamedDecl *D = *Path->Decls;
2831 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2832 continue;
2833 if (DeclsPrinted.insert(D).second) {
2834 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2835 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2836 << TD->getUnderlyingType();
2837 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2838 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2839 << Context.getTypeDeclType(TD);
2840 else
2841 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2842 }
2843 }
2844 break;
2845 }
2846
2848 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2849
2851
2852 for (auto *D : Result)
2853 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2854 TagDecls.insert(TD);
2855 Diag(TD->getLocation(), diag::note_hidden_tag);
2856 }
2857
2858 for (auto *D : Result)
2859 if (!isa<TagDecl>(D))
2860 Diag(D->getLocation(), diag::note_hiding_object);
2861
2862 // For recovery purposes, go ahead and implement the hiding.
2863 LookupResult::Filter F = Result.makeFilter();
2864 while (F.hasNext()) {
2865 if (TagDecls.count(F.next()))
2866 F.erase();
2867 }
2868 F.done();
2869 break;
2870 }
2871
2873 Diag(NameLoc, diag::err_using_placeholder_variable) << Name << LookupRange;
2874 DeclContext *DC = nullptr;
2875 for (auto *D : Result) {
2876 Diag(D->getLocation(), diag::note_reference_placeholder) << D;
2877 if (DC != nullptr && DC != D->getDeclContext())
2878 break;
2879 DC = D->getDeclContext();
2880 }
2881 break;
2882 }
2883
2885 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2886
2887 for (auto *D : Result)
2888 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2889 break;
2890 }
2891 }
2892}
2893
2894namespace {
2895 struct AssociatedLookup {
2896 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2897 Sema::AssociatedNamespaceSet &Namespaces,
2898 Sema::AssociatedClassSet &Classes)
2899 : S(S), Namespaces(Namespaces), Classes(Classes),
2900 InstantiationLoc(InstantiationLoc) {
2901 }
2902
2903 bool addClassTransitive(CXXRecordDecl *RD) {
2904 Classes.insert(RD);
2905 return ClassesTransitive.insert(RD);
2906 }
2907
2908 Sema &S;
2909 Sema::AssociatedNamespaceSet &Namespaces;
2910 Sema::AssociatedClassSet &Classes;
2911 SourceLocation InstantiationLoc;
2912
2913 private:
2914 Sema::AssociatedClassSet ClassesTransitive;
2915 };
2916} // end anonymous namespace
2917
2918static void
2920
2921// Given the declaration context \param Ctx of a class, class template or
2922// enumeration, add the associated namespaces to \param Namespaces as described
2923// in [basic.lookup.argdep]p2.
2925 DeclContext *Ctx) {
2926 // The exact wording has been changed in C++14 as a result of
2927 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2928 // to all language versions since it is possible to return a local type
2929 // from a lambda in C++11.
2930 //
2931 // C++14 [basic.lookup.argdep]p2:
2932 // If T is a class type [...]. Its associated namespaces are the innermost
2933 // enclosing namespaces of its associated classes. [...]
2934 //
2935 // If T is an enumeration type, its associated namespace is the innermost
2936 // enclosing namespace of its declaration. [...]
2937
2938 // We additionally skip inline namespaces. The innermost non-inline namespace
2939 // contains all names of all its nested inline namespaces anyway, so we can
2940 // replace the entire inline namespace tree with its root.
2941 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2942 Ctx = Ctx->getParent();
2943
2944 Namespaces.insert(Ctx->getPrimaryContext());
2945}
2946
2947// Add the associated classes and namespaces for argument-dependent
2948// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2949static void
2951 const TemplateArgument &Arg) {
2952 // C++ [basic.lookup.argdep]p2, last bullet:
2953 // -- [...] ;
2954 switch (Arg.getKind()) {
2956 break;
2957
2959 // [...] the namespaces and classes associated with the types of the
2960 // template arguments provided for template type parameters (excluding
2961 // template template parameters)
2963 break;
2964
2967 // [...] the namespaces in which any template template arguments are
2968 // defined; and the classes in which any member templates used as
2969 // template template arguments are defined.
2971 if (ClassTemplateDecl *ClassTemplate
2972 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2973 DeclContext *Ctx = ClassTemplate->getDeclContext();
2974 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2975 Result.Classes.insert(EnclosingClass);
2976 // Add the associated namespace for this class.
2977 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2978 }
2979 break;
2980 }
2981
2987 // [Note: non-type template arguments do not contribute to the set of
2988 // associated namespaces. ]
2989 break;
2990
2992 for (const auto &P : Arg.pack_elements())
2994 break;
2995 }
2996}
2997
2998// Add the associated classes and namespaces for argument-dependent lookup
2999// with an argument of class type (C++ [basic.lookup.argdep]p2).
3000static void
3003
3004 // Just silently ignore anything whose name is __va_list_tag.
3005 if (Class->getDeclName() == Result.S.VAListTagName)
3006 return;
3007
3008 // C++ [basic.lookup.argdep]p2:
3009 // [...]
3010 // -- If T is a class type (including unions), its associated
3011 // classes are: the class itself; the class of which it is a
3012 // member, if any; and its direct and indirect base classes.
3013 // Its associated namespaces are the innermost enclosing
3014 // namespaces of its associated classes.
3015
3016 // Add the class of which it is a member, if any.
3017 DeclContext *Ctx = Class->getDeclContext();
3018 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3019 Result.Classes.insert(EnclosingClass);
3020
3021 // Add the associated namespace for this class.
3022 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3023
3024 // -- If T is a template-id, its associated namespaces and classes are
3025 // the namespace in which the template is defined; for member
3026 // templates, the member template's class; the namespaces and classes
3027 // associated with the types of the template arguments provided for
3028 // template type parameters (excluding template template parameters); the
3029 // namespaces in which any template template arguments are defined; and
3030 // the classes in which any member templates used as template template
3031 // arguments are defined. [Note: non-type template arguments do not
3032 // contribute to the set of associated namespaces. ]
3034 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
3035 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
3036 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3037 Result.Classes.insert(EnclosingClass);
3038 // Add the associated namespace for this class.
3039 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3040
3041 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3042 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3043 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
3044 }
3045
3046 // Add the class itself. If we've already transitively visited this class,
3047 // we don't need to visit base classes.
3048 if (!Result.addClassTransitive(Class))
3049 return;
3050
3051 // Only recurse into base classes for complete types.
3052 if (!Result.S.isCompleteType(Result.InstantiationLoc,
3053 Result.S.Context.getRecordType(Class)))
3054 return;
3055
3056 // Add direct and indirect base classes along with their associated
3057 // namespaces.
3059 Bases.push_back(Class);
3060 while (!Bases.empty()) {
3061 // Pop this class off the stack.
3062 Class = Bases.pop_back_val();
3063
3064 // Visit the base classes.
3065 for (const auto &Base : Class->bases()) {
3066 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
3067 // In dependent contexts, we do ADL twice, and the first time around,
3068 // the base type might be a dependent TemplateSpecializationType, or a
3069 // TemplateTypeParmType. If that happens, simply ignore it.
3070 // FIXME: If we want to support export, we probably need to add the
3071 // namespace of the template in a TemplateSpecializationType, or even
3072 // the classes and namespaces of known non-dependent arguments.
3073 if (!BaseType)
3074 continue;
3075 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3076 if (Result.addClassTransitive(BaseDecl)) {
3077 // Find the associated namespace for this base class.
3078 DeclContext *BaseCtx = BaseDecl->getDeclContext();
3079 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
3080
3081 // Make sure we visit the bases of this base class.
3082 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
3083 Bases.push_back(BaseDecl);
3084 }
3085 }
3086 }
3087}
3088
3089// Add the associated classes and namespaces for
3090// argument-dependent lookup with an argument of type T
3091// (C++ [basic.lookup.koenig]p2).
3092static void
3094 // C++ [basic.lookup.koenig]p2:
3095 //
3096 // For each argument type T in the function call, there is a set
3097 // of zero or more associated namespaces and a set of zero or more
3098 // associated classes to be considered. The sets of namespaces and
3099 // classes is determined entirely by the types of the function
3100 // arguments (and the namespace of any template template
3101 // argument). Typedef names and using-declarations used to specify
3102 // the types do not contribute to this set. The sets of namespaces
3103 // and classes are determined in the following way:
3104
3106 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
3107
3108 while (true) {
3109 switch (T->getTypeClass()) {
3110
3111#define TYPE(Class, Base)
3112#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3113#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3114#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3115#define ABSTRACT_TYPE(Class, Base)
3116#include "clang/AST/TypeNodes.inc"
3117 // T is canonical. We can also ignore dependent types because
3118 // we don't need to do ADL at the definition point, but if we
3119 // wanted to implement template export (or if we find some other
3120 // use for associated classes and namespaces...) this would be
3121 // wrong.
3122 break;
3123
3124 // -- If T is a pointer to U or an array of U, its associated
3125 // namespaces and classes are those associated with U.
3126 case Type::Pointer:
3127 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
3128 continue;
3129 case Type::ConstantArray:
3130 case Type::IncompleteArray:
3131 case Type::VariableArray:
3132 T = cast<ArrayType>(T)->getElementType().getTypePtr();
3133 continue;
3134
3135 // -- If T is a fundamental type, its associated sets of
3136 // namespaces and classes are both empty.
3137 case Type::Builtin:
3138 break;
3139
3140 // -- If T is a class type (including unions), its associated
3141 // classes are: the class itself; the class of which it is
3142 // a member, if any; and its direct and indirect base classes.
3143 // Its associated namespaces are the innermost enclosing
3144 // namespaces of its associated classes.
3145 case Type::Record: {
3147 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
3149 break;
3150 }
3151
3152 // -- If T is an enumeration type, its associated namespace
3153 // is the innermost enclosing namespace of its declaration.
3154 // If it is a class member, its associated class is the
3155 // member’s class; else it has no associated class.
3156 case Type::Enum: {
3157 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
3158
3159 DeclContext *Ctx = Enum->getDeclContext();
3160 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3161 Result.Classes.insert(EnclosingClass);
3162
3163 // Add the associated namespace for this enumeration.
3164 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3165
3166 break;
3167 }
3168
3169 // -- If T is a function type, its associated namespaces and
3170 // classes are those associated with the function parameter
3171 // types and those associated with the return type.
3172 case Type::FunctionProto: {
3173 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
3174 for (const auto &Arg : Proto->param_types())
3175 Queue.push_back(Arg.getTypePtr());
3176 // fallthrough
3177 [[fallthrough]];
3178 }
3179 case Type::FunctionNoProto: {
3180 const FunctionType *FnType = cast<FunctionType>(T);
3181 T = FnType->getReturnType().getTypePtr();
3182 continue;
3183 }
3184
3185 // -- If T is a pointer to a member function of a class X, its
3186 // associated namespaces and classes are those associated
3187 // with the function parameter types and return type,
3188 // together with those associated with X.
3189 //
3190 // -- If T is a pointer to a data member of class X, its
3191 // associated namespaces and classes are those associated
3192 // with the member type together with those associated with
3193 // X.
3194 case Type::MemberPointer: {
3195 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
3196
3197 // Queue up the class type into which this points.
3198 Queue.push_back(MemberPtr->getClass());
3199
3200 // And directly continue with the pointee type.
3201 T = MemberPtr->getPointeeType().getTypePtr();
3202 continue;
3203 }
3204
3205 // As an extension, treat this like a normal pointer.
3206 case Type::BlockPointer:
3207 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
3208 continue;
3209
3210 // References aren't covered by the standard, but that's such an
3211 // obvious defect that we cover them anyway.
3212 case Type::LValueReference:
3213 case Type::RValueReference:
3214 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
3215 continue;
3216
3217 // These are fundamental types.
3218 case Type::Vector:
3219 case Type::ExtVector:
3220 case Type::ConstantMatrix:
3221 case Type::Complex:
3222 case Type::BitInt:
3223 break;
3224
3225 // Non-deduced auto types only get here for error cases.
3226 case Type::Auto:
3227 case Type::DeducedTemplateSpecialization:
3228 break;
3229
3230 // If T is an Objective-C object or interface type, or a pointer to an
3231 // object or interface type, the associated namespace is the global
3232 // namespace.
3233 case Type::ObjCObject:
3234 case Type::ObjCInterface:
3235 case Type::ObjCObjectPointer:
3236 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
3237 break;
3238
3239 // Atomic types are just wrappers; use the associations of the
3240 // contained type.
3241 case Type::Atomic:
3242 T = cast<AtomicType>(T)->getValueType().getTypePtr();
3243 continue;
3244 case Type::Pipe:
3245 T = cast<PipeType>(T)->getElementType().getTypePtr();
3246 continue;
3247
3248 // Array parameter types are treated as fundamental types.
3249 case Type::ArrayParameter:
3250 break;
3251 }
3252
3253 if (Queue.empty())
3254 break;
3255 T = Queue.pop_back_val();
3256 }
3257}
3258
3259/// Find the associated classes and namespaces for
3260/// argument-dependent lookup for a call with the given set of
3261/// arguments.
3262///
3263/// This routine computes the sets of associated classes and associated
3264/// namespaces searched by argument-dependent lookup
3265/// (C++ [basic.lookup.argdep]) for a given set of arguments.
3267 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3268 AssociatedNamespaceSet &AssociatedNamespaces,
3269 AssociatedClassSet &AssociatedClasses) {
3270 AssociatedNamespaces.clear();
3271 AssociatedClasses.clear();
3272
3273 AssociatedLookup Result(*this, InstantiationLoc,
3274 AssociatedNamespaces, AssociatedClasses);
3275
3276 // C++ [basic.lookup.koenig]p2:
3277 // For each argument type T in the function call, there is a set
3278 // of zero or more associated namespaces and a set of zero or more
3279 // associated classes to be considered. The sets of namespaces and
3280 // classes is determined entirely by the types of the function
3281 // arguments (and the namespace of any template template
3282 // argument).
3283 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3284 Expr *Arg = Args[ArgIdx];
3285
3286 if (Arg->getType() != Context.OverloadTy) {
3288 continue;
3289 }
3290
3291 // [...] In addition, if the argument is the name or address of a
3292 // set of overloaded functions and/or function templates, its
3293 // associated classes and namespaces are the union of those
3294 // associated with each of the members of the set: the namespace
3295 // in which the function or function template is defined and the
3296 // classes and namespaces associated with its (non-dependent)
3297 // parameter types and return type.
3299
3300 for (const NamedDecl *D : OE->decls()) {
3301 // Look through any using declarations to find the underlying function.
3302 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3303
3304 // Add the classes and namespaces associated with the parameter
3305 // types and return type of this function.
3307 }
3308 }
3309}
3310
3312 SourceLocation Loc,
3313 LookupNameKind NameKind,
3314 RedeclarationKind Redecl) {
3315 LookupResult R(*this, Name, Loc, NameKind, Redecl);
3316 LookupName(R, S);
3317 return R.getAsSingle<NamedDecl>();
3318}
3319
3320/// Find the protocol with the given name, if any.
3322 SourceLocation IdLoc,
3323 RedeclarationKind Redecl) {
3324 Decl *D = LookupSingleName(TUScope, II, IdLoc,
3325 LookupObjCProtocolName, Redecl);
3326 return cast_or_null<ObjCProtocolDecl>(D);
3327}
3328
3330 UnresolvedSetImpl &Functions) {
3331 // C++ [over.match.oper]p3:
3332 // -- The set of non-member candidates is the result of the
3333 // unqualified lookup of operator@ in the context of the
3334 // expression according to the usual rules for name lookup in
3335 // unqualified function calls (3.4.2) except that all member
3336 // functions are ignored.
3338 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3339 LookupName(Operators, S);
3340
3341 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3342 Functions.append(Operators.begin(), Operators.end());
3343}
3344
3347 bool ConstArg, bool VolatileArg, bool RValueThis,
3348 bool ConstThis, bool VolatileThis) {
3350 "doing special member lookup into record that isn't fully complete");
3351 RD = RD->getDefinition();
3352 if (RValueThis || ConstThis || VolatileThis)
3355 "constructors and destructors always have unqualified lvalue this");
3356 if (ConstArg || VolatileArg)
3359 "parameter-less special members can't have qualified arguments");
3360
3361 // FIXME: Get the caller to pass in a location for the lookup.
3362 SourceLocation LookupLoc = RD->getLocation();
3363
3364 llvm::FoldingSetNodeID ID;
3365 ID.AddPointer(RD);
3366 ID.AddInteger(llvm::to_underlying(SM));
3367 ID.AddInteger(ConstArg);
3368 ID.AddInteger(VolatileArg);
3369 ID.AddInteger(RValueThis);
3370 ID.AddInteger(ConstThis);
3371 ID.AddInteger(VolatileThis);
3372
3373 void *InsertPoint;
3375 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3376
3377 // This was already cached
3378 if (Result)
3379 return *Result;
3380
3383 SpecialMemberCache.InsertNode(Result, InsertPoint);
3384
3386 if (RD->needsImplicitDestructor()) {
3388 DeclareImplicitDestructor(RD);
3389 });
3390 }
3391 CXXDestructorDecl *DD = RD->getDestructor();
3392 Result->setMethod(DD);
3393 Result->setKind(DD && !DD->isDeleted()
3396 return *Result;
3397 }
3398
3399 // Prepare for overload resolution. Here we construct a synthetic argument
3400 // if necessary and make sure that implicit functions are declared.
3402 DeclarationName Name;
3403 Expr *Arg = nullptr;
3404 unsigned NumArgs;
3405
3406 QualType ArgType = CanTy;
3408
3411 NumArgs = 0;
3414 DeclareImplicitDefaultConstructor(RD);
3415 });
3416 }
3417 } else {
3421 if (RD->needsImplicitCopyConstructor()) {
3423 DeclareImplicitCopyConstructor(RD);
3424 });
3425 }
3428 DeclareImplicitMoveConstructor(RD);
3429 });
3430 }
3431 } else {
3433 if (RD->needsImplicitCopyAssignment()) {
3435 DeclareImplicitCopyAssignment(RD);
3436 });
3437 }
3440 DeclareImplicitMoveAssignment(RD);
3441 });
3442 }
3443 }
3444
3445 if (ConstArg)
3446 ArgType.addConst();
3447 if (VolatileArg)
3448 ArgType.addVolatile();
3449
3450 // This isn't /really/ specified by the standard, but it's implied
3451 // we should be working from a PRValue in the case of move to ensure
3452 // that we prefer to bind to rvalue references, and an LValue in the
3453 // case of copy to ensure we don't bind to rvalue references.
3454 // Possibly an XValue is actually correct in the case of move, but
3455 // there is no semantic difference for class types in this restricted
3456 // case.
3459 VK = VK_LValue;
3460 else
3461 VK = VK_PRValue;
3462 }
3463
3464 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3465
3467 NumArgs = 1;
3468 Arg = &FakeArg;
3469 }
3470
3471 // Create the object argument
3472 QualType ThisTy = CanTy;
3473 if (ConstThis)
3474 ThisTy.addConst();
3475 if (VolatileThis)
3476 ThisTy.addVolatile();
3477 Expr::Classification Classification =
3478 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3479 .Classify(Context);
3480
3481 // Now we perform lookup on the name we computed earlier and do overload
3482 // resolution. Lookup is only performed directly into the class since there
3483 // will always be a (possibly implicit) declaration to shadow any others.
3485 DeclContext::lookup_result R = RD->lookup(Name);
3486
3487 if (R.empty()) {
3488 // We might have no default constructor because we have a lambda's closure
3489 // type, rather than because there's some other declared constructor.
3490 // Every class has a copy/move constructor, copy/move assignment, and
3491 // destructor.
3493 "lookup for a constructor or assignment operator was empty");
3494 Result->setMethod(nullptr);
3496 return *Result;
3497 }
3498
3499 // Copy the candidates as our processing of them may load new declarations
3500 // from an external source and invalidate lookup_result.
3501 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3502
3503 for (NamedDecl *CandDecl : Candidates) {
3504 if (CandDecl->isInvalidDecl())
3505 continue;
3506
3508 auto CtorInfo = getConstructorInfo(Cand);
3509 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3512 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3513 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3514 else if (CtorInfo)
3515 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3516 llvm::ArrayRef(&Arg, NumArgs), OCS,
3517 /*SuppressUserConversions*/ true);
3518 else
3519 AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS,
3520 /*SuppressUserConversions*/ true);
3521 } else if (FunctionTemplateDecl *Tmpl =
3522 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3525 AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy,
3526 Classification,
3527 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3528 else if (CtorInfo)
3529 AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl,
3530 CtorInfo.FoundDecl, nullptr,
3531 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3532 else
3533 AddTemplateOverloadCandidate(Tmpl, Cand, nullptr,
3534 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3535 } else {
3536 assert(isa<UsingDecl>(Cand.getDecl()) &&
3537 "illegal Kind of operator = Decl");
3538 }
3539 }
3540
3542 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3543 case OR_Success:
3544 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3546 break;
3547
3548 case OR_Deleted:
3549 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3551 break;
3552
3553 case OR_Ambiguous:
3554 Result->setMethod(nullptr);
3556 break;
3557
3559 Result->setMethod(nullptr);
3561 break;
3562 }
3563
3564 return *Result;
3565}
3566
3567/// Look up the default constructor for the given class.
3571 false, false, false, false, false);
3572
3573 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3574}
3575
3576/// Look up the copying constructor for the given class.
3578 unsigned Quals) {
3579 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3580 "non-const, non-volatile qualifiers for copy ctor arg");
3583 Quals & Qualifiers::Volatile, false, false, false);
3584
3585 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3586}
3587
3588/// Look up the moving constructor for the given class.
3590 unsigned Quals) {
3593 Quals & Qualifiers::Volatile, false, false, false);
3594
3595 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3596}
3597
3598/// Look up the constructors for the given class.
3600 // If the implicit constructors have not yet been declared, do so now.
3602 runWithSufficientStackSpace(Class->getLocation(), [&] {
3603 if (Class->needsImplicitDefaultConstructor())
3604 DeclareImplicitDefaultConstructor(Class);
3605 if (Class->needsImplicitCopyConstructor())
3606 DeclareImplicitCopyConstructor(Class);
3607 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3608 DeclareImplicitMoveConstructor(Class);
3609 });
3610 }
3611
3614 return Class->lookup(Name);
3615}
3616
3617/// Look up the copying assignment operator for the given class.
3619 unsigned Quals, bool RValueThis,
3620 unsigned ThisQuals) {
3621 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3622 "non-const, non-volatile qualifiers for copy assignment arg");
3623 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3624 "non-const, non-volatile qualifiers for copy assignment this");
3627 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,
3628 ThisQuals & Qualifiers::Volatile);
3629
3630 return Result.getMethod();
3631}
3632
3633/// Look up the moving assignment operator for the given class.
3635 unsigned Quals,
3636 bool RValueThis,
3637 unsigned ThisQuals) {
3638 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3639 "non-const, non-volatile qualifiers for copy assignment this");
3642 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,
3643 ThisQuals & Qualifiers::Volatile);
3644
3645 return Result.getMethod();
3646}
3647
3648/// Look for the destructor of the given class.
3649///
3650/// During semantic analysis, this routine should be used in lieu of
3651/// CXXRecordDecl::getDestructor().
3652///
3653/// \returns The destructor for this class.
3655 return cast_or_null<CXXDestructorDecl>(
3657 false, false, false)
3658 .getMethod());
3659}
3660
3661/// LookupLiteralOperator - Determine which literal operator should be used for
3662/// a user-defined literal, per C++11 [lex.ext].
3663///
3664/// Normal overload resolution is not used to select which literal operator to
3665/// call for a user-defined literal. Look up the provided literal operator name,
3666/// and filter the results to the appropriate set for the given argument types.
3669 ArrayRef<QualType> ArgTys, bool AllowRaw,
3670 bool AllowTemplate, bool AllowStringTemplatePack,
3671 bool DiagnoseMissing, StringLiteral *StringLit) {
3672 LookupName(R, S);
3673 assert(R.getResultKind() != LookupResult::Ambiguous &&
3674 "literal operator lookup can't be ambiguous");
3675
3676 // Filter the lookup results appropriately.
3678
3679 bool AllowCooked = true;
3680 bool FoundRaw = false;
3681 bool FoundTemplate = false;
3682 bool FoundStringTemplatePack = false;
3683 bool FoundCooked = false;
3684
3685 while (F.hasNext()) {
3686 Decl *D = F.next();
3687 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3688 D = USD->getTargetDecl();
3689
3690 // If the declaration we found is invalid, skip it.
3691 if (D->isInvalidDecl()) {
3692 F.erase();
3693 continue;
3694 }
3695
3696 bool IsRaw = false;
3697 bool IsTemplate = false;
3698 bool IsStringTemplatePack = false;
3699 bool IsCooked = false;
3700
3701 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3702 if (FD->getNumParams() == 1 &&
3703 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3704 IsRaw = true;
3705 else if (FD->getNumParams() == ArgTys.size()) {
3706 IsCooked = true;
3707 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3708 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3709 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3710 IsCooked = false;
3711 break;
3712 }
3713 }
3714 }
3715 }
3716 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3717 TemplateParameterList *Params = FD->getTemplateParameters();
3718 if (Params->size() == 1) {
3719 IsTemplate = true;
3720 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3721 // Implied but not stated: user-defined integer and floating literals
3722 // only ever use numeric literal operator templates, not templates
3723 // taking a parameter of class type.
3724 F.erase();
3725 continue;
3726 }
3727
3728 // A string literal template is only considered if the string literal
3729 // is a well-formed template argument for the template parameter.
3730 if (StringLit) {
3731 SFINAETrap Trap(*this);
3732 SmallVector<TemplateArgument, 1> SugaredChecked, CanonicalChecked;
3733 TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
3735 Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(),
3736 0, SugaredChecked, CanonicalChecked, CTAK_Specified) ||
3737 Trap.hasErrorOccurred())
3738 IsTemplate = false;
3739 }
3740 } else {
3741 IsStringTemplatePack = true;
3742 }
3743 }
3744
3745 if (AllowTemplate && StringLit && IsTemplate) {
3746 FoundTemplate = true;
3747 AllowRaw = false;
3748 AllowCooked = false;
3749 AllowStringTemplatePack = false;
3750 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3751 F.restart();
3752 FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3753 }
3754 } else if (AllowCooked && IsCooked) {
3755 FoundCooked = true;
3756 AllowRaw = false;
3757 AllowTemplate = StringLit;
3758 AllowStringTemplatePack = false;
3759 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3760 // Go through again and remove the raw and template decls we've
3761 // already found.
3762 F.restart();
3763 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3764 }
3765 } else if (AllowRaw && IsRaw) {
3766 FoundRaw = true;
3767 } else if (AllowTemplate && IsTemplate) {
3768 FoundTemplate = true;
3769 } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3770 FoundStringTemplatePack = true;
3771 } else {
3772 F.erase();
3773 }
3774 }
3775
3776 F.done();
3777
3778 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3779 // form for string literal operator templates.
3780 if (StringLit && FoundTemplate)
3781 return LOLR_Template;
3782
3783 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3784 // parameter type, that is used in preference to a raw literal operator
3785 // or literal operator template.
3786 if (FoundCooked)
3787 return LOLR_Cooked;
3788
3789 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3790 // operator template, but not both.
3791 if (FoundRaw && FoundTemplate) {
3792 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3793 for (const NamedDecl *D : R)
3795 return LOLR_Error;
3796 }
3797
3798 if (FoundRaw)
3799 return LOLR_Raw;
3800
3801 if (FoundTemplate)
3802 return LOLR_Template;
3803
3804 if (FoundStringTemplatePack)
3806
3807 // Didn't find anything we could use.
3808 if (DiagnoseMissing) {
3809 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3810 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3811 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3812 << (AllowTemplate || AllowStringTemplatePack);
3813 return LOLR_Error;
3814 }
3815
3817}
3818
3820 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3821
3822 // If we haven't yet seen a decl for this key, or the last decl
3823 // was exactly this one, we're done.
3824 if (Old == nullptr || Old == New) {
3825 Old = New;
3826 return;
3827 }
3828
3829 // Otherwise, decide which is a more recent redeclaration.
3830 FunctionDecl *OldFD = Old->getAsFunction();
3831 FunctionDecl *NewFD = New->getAsFunction();
3832
3833 FunctionDecl *Cursor = NewFD;
3834 while (true) {
3835 Cursor = Cursor->getPreviousDecl();
3836
3837 // If we got to the end without finding OldFD, OldFD is the newer
3838 // declaration; leave things as they are.
3839 if (!Cursor) return;
3840
3841 // If we do find OldFD, then NewFD is newer.
3842 if (Cursor == OldFD) break;
3843
3844 // Otherwise, keep looking.
3845 }
3846
3847 Old = New;
3848}
3849
3852 // Find all of the associated namespaces and classes based on the
3853 // arguments we have.
3854 AssociatedNamespaceSet AssociatedNamespaces;
3855 AssociatedClassSet AssociatedClasses;
3857 AssociatedNamespaces,
3858 AssociatedClasses);
3859
3860 // C++ [basic.lookup.argdep]p3:
3861 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3862 // and let Y be the lookup set produced by argument dependent
3863 // lookup (defined as follows). If X contains [...] then Y is
3864 // empty. Otherwise Y is the set of declarations found in the
3865 // namespaces associated with the argument types as described
3866 // below. The set of declarations found by the lookup of the name
3867 // is the union of X and Y.
3868 //
3869 // Here, we compute Y and add its members to the overloaded
3870 // candidate set.
3871 for (auto *NS : AssociatedNamespaces) {
3872 // When considering an associated namespace, the lookup is the
3873 // same as the lookup performed when the associated namespace is
3874 // used as a qualifier (3.4.3.2) except that:
3875 //
3876 // -- Any using-directives in the associated namespace are
3877 // ignored.
3878 //
3879 // -- Any namespace-scope friend functions declared in
3880 // associated classes are visible within their respective
3881 // namespaces even if they are not visible during an ordinary
3882 // lookup (11.4).
3883 //
3884 // C++20 [basic.lookup.argdep] p4.3
3885 // -- are exported, are attached to a named module M, do not appear
3886 // in the translation unit containing the point of the lookup, and
3887 // have the same innermost enclosing non-inline namespace scope as
3888 // a declaration of an associated entity attached to M.
3889 DeclContext::lookup_result R = NS->lookup(Name);
3890 for (auto *D : R) {
3891 auto *Underlying = D;
3892 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3893 Underlying = USD->getTargetDecl();
3894
3895 if (!isa<FunctionDecl>(Underlying) &&
3896 !isa<FunctionTemplateDecl>(Underlying))
3897 continue;
3898
3899 // The declaration is visible to argument-dependent lookup if either
3900 // it's ordinarily visible or declared as a friend in an associated
3901 // class.
3902 bool Visible = false;
3903 for (D = D->getMostRecentDecl(); D;
3904 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3906 if (isVisible(D)) {
3907 Visible = true;
3908 break;
3909 }
3910
3911 if (!getLangOpts().CPlusPlusModules)
3912 continue;
3913
3914 if (D->isInExportDeclContext()) {
3915 Module *FM = D->getOwningModule();
3916 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
3917 // exports are only valid in module purview and outside of any
3918 // PMF (although a PMF should not even be present in a module
3919 // with an import).
3920 assert(FM && FM->isNamedModule() && !FM->isPrivateModule() &&
3921 "bad export context");
3922 // .. are attached to a named module M, do not appear in the
3923 // translation unit containing the point of the lookup..
3924 if (D->isInAnotherModuleUnit() &&
3925 llvm::any_of(AssociatedClasses, [&](auto *E) {
3926 // ... and have the same innermost enclosing non-inline
3927 // namespace scope as a declaration of an associated entity
3928 // attached to M
3929 if (E->getOwningModule() != FM)
3930 return false;
3931 // TODO: maybe this could be cached when generating the
3932 // associated namespaces / entities.
3933 DeclContext *Ctx = E->getDeclContext();
3934 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
3935 Ctx = Ctx->getParent();
3936 return Ctx == NS;
3937 })) {
3938 Visible = true;
3939 break;
3940 }
3941 }
3942 } else if (D->getFriendObjectKind()) {
3943 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3944 // [basic.lookup.argdep]p4:
3945 // Argument-dependent lookup finds all declarations of functions and
3946 // function templates that
3947 // - ...
3948 // - are declared as a friend ([class.friend]) of any class with a
3949 // reachable definition in the set of associated entities,
3950 //
3951 // FIXME: If there's a merged definition of D that is reachable, then
3952 // the friend declaration should be considered.
3953 if (AssociatedClasses.count(RD) && isReachable(D)) {
3954 Visible = true;
3955 break;
3956 }
3957 }
3958 }
3959
3960 // FIXME: Preserve D as the FoundDecl.
3961 if (Visible)
3962 Result.insert(Underlying);
3963 }
3964 }
3965}
3966
3967//----------------------------------------------------------------------------
3968// Search for all visible declarations.
3969//----------------------------------------------------------------------------
3971
3972bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3973
3974namespace {
3975
3976class ShadowContextRAII;
3977
3978class VisibleDeclsRecord {
3979public:
3980 /// An entry in the shadow map, which is optimized to store a
3981 /// single declaration (the common case) but can also store a list
3982 /// of declarations.
3983 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3984
3985private:
3986 /// A mapping from declaration names to the declarations that have
3987 /// this name within a particular scope.
3988 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3989
3990 /// A list of shadow maps, which is used to model name hiding.
3991 std::list<ShadowMap> ShadowMaps;
3992
3993 /// The declaration contexts we have already visited.
3995
3996 friend class ShadowContextRAII;
3997
3998public:
3999 /// Determine whether we have already visited this context
4000 /// (and, if not, note that we are going to visit that context now).
4001 bool visitedContext(DeclContext *Ctx) {
4002 return !VisitedContexts.insert(Ctx).second;
4003 }
4004
4005 bool alreadyVisitedContext(DeclContext *Ctx) {
4006 return VisitedContexts.count(Ctx);
4007 }
4008
4009 /// Determine whether the given declaration is hidden in the
4010 /// current scope.
4011 ///
4012 /// \returns the declaration that hides the given declaration, or
4013 /// NULL if no such declaration exists.
4014 NamedDecl *checkHidden(NamedDecl *ND);
4015
4016 /// Add a declaration to the current shadow map.
4017 void add(NamedDecl *ND) {
4018 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
4019 }
4020};
4021
4022/// RAII object that records when we've entered a shadow context.
4023class ShadowContextRAII {
4024 VisibleDeclsRecord &Visible;
4025
4026 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
4027
4028public:
4029 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
4030 Visible.ShadowMaps.emplace_back();
4031 }
4032
4033 ~ShadowContextRAII() {
4034 Visible.ShadowMaps.pop_back();
4035 }
4036};
4037
4038} // end anonymous namespace
4039
4040NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
4041 unsigned IDNS = ND->getIdentifierNamespace();
4042 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
4043 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
4044 SM != SMEnd; ++SM) {
4045 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
4046 if (Pos == SM->end())
4047 continue;
4048
4049 for (auto *D : Pos->second) {
4050 // A tag declaration does not hide a non-tag declaration.
4051 if (D->hasTagIdentifierNamespace() &&
4054 continue;
4055
4056 // Protocols are in distinct namespaces from everything else.
4058 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
4059 D->getIdentifierNamespace() != IDNS)
4060 continue;
4061
4062 // Functions and function templates in the same scope overload
4063 // rather than hide. FIXME: Look for hiding based on function
4064 // signatures!
4067 SM == ShadowMaps.rbegin())
4068 continue;
4069
4070 // A shadow declaration that's created by a resolved using declaration
4071 // is not hidden by the same using declaration.
4072 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
4073 cast<UsingShadowDecl>(ND)->getIntroducer() == D)
4074 continue;
4075
4076 // We've found a declaration that hides this one.
4077 return D;
4078 }
4079 }
4080
4081 return nullptr;
4082}
4083
4084namespace {
4085class LookupVisibleHelper {
4086public:
4087 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
4088 bool LoadExternal)
4089 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4090 LoadExternal(LoadExternal) {}
4091
4092 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4093 bool IncludeGlobalScope) {
4094 // Determine the set of using directives available during
4095 // unqualified name lookup.
4096 Scope *Initial = S;
4097 UnqualUsingDirectiveSet UDirs(SemaRef);
4098 if (SemaRef.getLangOpts().CPlusPlus) {
4099 // Find the first namespace or translation-unit scope.
4100 while (S && !isNamespaceOrTranslationUnitScope(S))
4101 S = S->getParent();
4102
4103 UDirs.visitScopeChain(Initial, S);
4104 }
4105 UDirs.done();
4106
4107 // Look for visible declarations.
4108 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4109 Result.setAllowHidden(Consumer.includeHiddenDecls());
4110 if (!IncludeGlobalScope)
4111 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4112 ShadowContextRAII Shadow(Visited);
4113 lookupInScope(Initial, Result, UDirs);
4114 }
4115
4116 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4117 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4118 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4119 Result.setAllowHidden(Consumer.includeHiddenDecls());
4120 if (!IncludeGlobalScope)
4121 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4122
4123 ShadowContextRAII Shadow(Visited);
4124 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4125 /*InBaseClass=*/false);
4126 }
4127
4128private:
4129 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4130 bool QualifiedNameLookup, bool InBaseClass) {
4131 if (!Ctx)
4132 return;
4133
4134 // Make sure we don't visit the same context twice.
4135 if (Visited.visitedContext(Ctx->getPrimaryContext()))
4136 return;
4137
4138 Consumer.EnteredContext(Ctx);
4139
4140 // Outside C++, lookup results for the TU live on identifiers.
4141 if (isa<TranslationUnitDecl>(Ctx) &&
4142 !Result.getSema().getLangOpts().CPlusPlus) {
4143 auto &S = Result.getSema();
4144 auto &Idents = S.Context.Idents;
4145
4146 // Ensure all external identifiers are in the identifier table.
4147 if (LoadExternal)
4149 Idents.getExternalIdentifierLookup()) {
4150 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4151 for (StringRef Name = Iter->Next(); !Name.empty();
4152 Name = Iter->Next())
4153 Idents.get(Name);
4154 }
4155
4156 // Walk all lookup results in the TU for each identifier.
4157 for (const auto &Ident : Idents) {
4158 for (auto I = S.IdResolver.begin(Ident.getValue()),
4159 E = S.IdResolver.end();
4160 I != E; ++I) {
4161 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
4162 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4163 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4164 Visited.add(ND);
4165 }
4166 }
4167 }
4168 }
4169
4170 return;
4171 }
4172
4173 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
4174 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4175
4177 // We sometimes skip loading namespace-level results (they tend to be huge).
4178 bool Load = LoadExternal ||
4179 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
4180 // Enumerate all of the results in this context.
4182 Load ? Ctx->lookups()
4183 : Ctx->noload_lookups(/*PreserveInternalState=*/false))
4184 for (auto *D : R)
4185 // Rather than visit immediately, we put ND into a vector and visit
4186 // all decls, in order, outside of this loop. The reason is that
4187 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)
4188 // may invalidate the iterators used in the two
4189 // loops above.
4190 DeclsToVisit.push_back(D);
4191
4192 for (auto *D : DeclsToVisit)
4193 if (auto *ND = Result.getAcceptableDecl(D)) {
4194 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4195 Visited.add(ND);
4196 }
4197
4198 DeclsToVisit.clear();
4199
4200 // Traverse using directives for qualified name lookup.
4201 if (QualifiedNameLookup) {
4202 ShadowContextRAII Shadow(Visited);
4203 for (auto *I : Ctx->using_directives()) {
4204 if (!Result.getSema().isVisible(I))
4205 continue;
4206 lookupInDeclContext(I->getNominatedNamespace(), Result,
4207 QualifiedNameLookup, InBaseClass);
4208 }
4209 }
4210
4211 // Traverse the contexts of inherited C++ classes.
4212 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
4213 if (!Record->hasDefinition())
4214 return;
4215
4216 for (const auto &B : Record->bases()) {
4217 QualType BaseType = B.getType();
4218
4219 RecordDecl *RD;
4220 if (BaseType->isDependentType()) {
4221 if (!IncludeDependentBases) {
4222 // Don't look into dependent bases, because name lookup can't look
4223 // there anyway.
4224 continue;
4225 }
4226 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
4227 if (!TST)
4228 continue;
4229 TemplateName TN = TST->getTemplateName();
4230 const auto *TD =
4231 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
4232 if (!TD)
4233 continue;
4234 RD = TD->getTemplatedDecl();
4235 } else {
4236 const auto *Record = BaseType->getAs<RecordType>();
4237 if (!Record)
4238 continue;
4239 RD = Record->getDecl();
4240 }
4241
4242 // FIXME: It would be nice to be able to determine whether referencing
4243 // a particular member would be ambiguous. For example, given
4244 //
4245 // struct A { int member; };
4246 // struct B { int member; };
4247 // struct C : A, B { };
4248 //
4249 // void f(C *c) { c->### }
4250 //
4251 // accessing 'member' would result in an ambiguity. However, we
4252 // could be smart enough to qualify the member with the base
4253 // class, e.g.,
4254 //
4255 // c->B::member
4256 //
4257 // or
4258 //
4259 // c->A::member
4260
4261 // Find results in this base class (and its bases).
4262 ShadowContextRAII Shadow(Visited);
4263 lookupInDeclContext(RD, Result, QualifiedNameLookup,
4264 /*InBaseClass=*/true);
4265 }
4266 }
4267
4268 // Traverse the contexts of Objective-C classes.
4269 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
4270 // Traverse categories.
4271 for (auto *Cat : IFace->visible_categories()) {
4272 ShadowContextRAII Shadow(Visited);
4273 lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4274 /*InBaseClass=*/false);
4275 }
4276
4277 // Traverse protocols.
4278 for (auto *I : IFace->all_referenced_protocols()) {
4279 ShadowContextRAII Shadow(Visited);
4280 lookupInDeclContext(I, Result, QualifiedNameLookup,
4281 /*InBaseClass=*/false);
4282 }
4283
4284 // Traverse the superclass.
4285 if (IFace->getSuperClass()) {
4286 ShadowContextRAII Shadow(Visited);
4287 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4288 /*InBaseClass=*/true);
4289 }
4290
4291 // If there is an implementation, traverse it. We do this to find
4292 // synthesized ivars.
4293 if (IFace->getImplementation()) {
4294 ShadowContextRAII Shadow(Visited);
4295 lookupInDeclContext(IFace->getImplementation(), Result,
4296 QualifiedNameLookup, InBaseClass);
4297 }
4298 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4299 for (auto *I : Protocol->protocols()) {
4300 ShadowContextRAII Shadow(Visited);
4301 lookupInDeclContext(I, Result, QualifiedNameLookup,
4302 /*InBaseClass=*/false);
4303 }
4304 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4305 for (auto *I : Category->protocols()) {
4306 ShadowContextRAII Shadow(Visited);
4307 lookupInDeclContext(I, Result, QualifiedNameLookup,
4308 /*InBaseClass=*/false);
4309 }
4310
4311 // If there is an implementation, traverse it.
4312 if (Category->getImplementation()) {
4313 ShadowContextRAII Shadow(Visited);
4314 lookupInDeclContext(Category->getImplementation(), Result,
4315 QualifiedNameLookup, /*InBaseClass=*/true);
4316 }
4317 }
4318 }
4319
4320 void lookupInScope(Scope *S, LookupResult &Result,
4321 UnqualUsingDirectiveSet &UDirs) {
4322 // No clients run in this mode and it's not supported. Please add tests and
4323 // remove the assertion if you start relying on it.
4324 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4325
4326 if (!S)
4327 return;
4328
4329 if (!S->getEntity() ||
4330 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4331 (S->getEntity())->isFunctionOrMethod()) {
4332 FindLocalExternScope FindLocals(Result);
4333 // Walk through the declarations in this Scope. The consumer might add new
4334 // decls to the scope as part of deserialization, so make a copy first.
4335 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4336 for (Decl *D : ScopeDecls) {
4337 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4338 if ((ND = Result.getAcceptableDecl(ND))) {
4339 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4340 Visited.add(ND);
4341 }
4342 }
4343 }
4344
4345 DeclContext *Entity = S->getLookupEntity();
4346 if (Entity) {
4347 // Look into this scope's declaration context, along with any of its
4348 // parent lookup contexts (e.g., enclosing classes), up to the point
4349 // where we hit the context stored in the next outer scope.
4350 DeclContext *OuterCtx = findOuterContext(S);
4351
4352 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4353 Ctx = Ctx->getLookupParent()) {
4354 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4355 if (Method->isInstanceMethod()) {
4356 // For instance methods, look for ivars in the method's interface.
4357 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4358 Result.getNameLoc(),
4360 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4361 lookupInDeclContext(IFace, IvarResult,
4362 /*QualifiedNameLookup=*/false,
4363 /*InBaseClass=*/false);
4364 }
4365 }
4366
4367 // We've already performed all of the name lookup that we need
4368 // to for Objective-C methods; the next context will be the
4369 // outer scope.
4370 break;
4371 }
4372
4373 if (Ctx->isFunctionOrMethod())
4374 continue;
4375
4376 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4377 /*InBaseClass=*/false);
4378 }
4379 } else if (!S->getParent()) {
4380 // Look into the translation unit scope. We walk through the translation
4381 // unit's declaration context, because the Scope itself won't have all of
4382 // the declarations if we loaded a precompiled header.
4383 // FIXME: We would like the translation unit's Scope object to point to
4384 // the translation unit, so we don't need this special "if" branch.
4385 // However, doing so would force the normal C++ name-lookup code to look
4386 // into the translation unit decl when the IdentifierInfo chains would
4387 // suffice. Once we fix that problem (which is part of a more general
4388 // "don't look in DeclContexts unless we have to" optimization), we can
4389 // eliminate this.
4390 Entity = Result.getSema().Context.getTranslationUnitDecl();
4391 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4392 /*InBaseClass=*/false);
4393 }
4394
4395 if (Entity) {
4396 // Lookup visible declarations in any namespaces found by using
4397 // directives.
4398 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4399 lookupInDeclContext(
4400 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4401 /*QualifiedNameLookup=*/false,
4402 /*InBaseClass=*/false);
4403 }
4404
4405 // Lookup names in the parent scope.
4406 ShadowContextRAII Shadow(Visited);
4407 lookupInScope(S->getParent(), Result, UDirs);
4408 }
4409
4410private:
4411 VisibleDeclsRecord Visited;
4412 VisibleDeclConsumer &Consumer;
4413 bool IncludeDependentBases;
4414 bool LoadExternal;
4415};
4416} // namespace
4417
4419 VisibleDeclConsumer &Consumer,
4420 bool IncludeGlobalScope, bool LoadExternal) {
4421 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4422 LoadExternal);
4423 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4424}
4425
4427 VisibleDeclConsumer &Consumer,
4428 bool IncludeGlobalScope,
4429 bool IncludeDependentBases, bool LoadExternal) {
4430 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4431 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4432}
4433
4434/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
4435/// If GnuLabelLoc is a valid source location, then this is a definition
4436/// of an __label__ label name, otherwise it is a normal label definition
4437/// or use.
4439 SourceLocation GnuLabelLoc) {
4440 // Do a lookup to see if we have a label with this name already.
4441 NamedDecl *Res = nullptr;
4442
4443 if (GnuLabelLoc.isValid()) {
4444 // Local label definitions always shadow existing labels.
4445 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4446 Scope *S = CurScope;
4447 PushOnScopeChains(Res, S, true);
4448 return cast<LabelDecl>(Res);
4449 }
4450
4451 // Not a GNU local label.
4452 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
4453 // If we found a label, check to see if it is in the same context as us.
4454 // When in a Block, we don't want to reuse a label in an enclosing function.
4455 if (Res && Res->getDeclContext() != CurContext)
4456 Res = nullptr;
4457 if (!Res) {
4458 // If not forward referenced or defined already, create the backing decl.
4459 Res = LabelDecl::Create(Context, CurContext, Loc, II);
4460 Scope *S = CurScope->getFnParent();
4461 assert(S && "Not in a function?");
4462 PushOnScopeChains(Res, S, true);
4463 }
4464 return cast<LabelDecl>(Res);
4465}
4466
4467//===----------------------------------------------------------------------===//
4468// Typo correction
4469//===----------------------------------------------------------------------===//
4470
4472 TypoCorrection &Candidate) {
4473 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4474 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4475}
4476
4477static void LookupPotentialTypoResult(Sema &SemaRef,
4478 LookupResult &Res,
4479 IdentifierInfo *Name,
4480 Scope *S, CXXScopeSpec *SS,
4481 DeclContext *MemberContext,
4482 bool EnteringContext,
4483 bool isObjCIvarLookup,
4484 bool FindHidden);
4485
4486/// Check whether the declarations found for a typo correction are
4487/// visible. Set the correction's RequiresImport flag to true if none of the
4488/// declarations are visible, false otherwise.
4490 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4491
4492 for (/**/; DI != DE; ++DI)
4493 if (!LookupResult::isVisible(SemaRef, *DI))
4494 break;
4495 // No filtering needed if all decls are visible.
4496 if (DI == DE) {
4497 TC.setRequiresImport(false);
4498 return;
4499 }
4500
4501 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4502 bool AnyVisibleDecls = !NewDecls.empty();
4503
4504 for (/**/; DI != DE; ++DI) {
4505 if (LookupResult::isVisible(SemaRef, *DI)) {
4506 if (!AnyVisibleDecls) {
4507 // Found a visible decl, discard all hidden ones.
4508 AnyVisibleDecls = true;
4509 NewDecls.clear();
4510 }
4511 NewDecls.push_back(*DI);
4512 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4513 NewDecls.push_back(*DI);
4514 }
4515
4516 if (NewDecls.empty())
4517 TC = TypoCorrection();
4518 else {
4519 TC.setCorrectionDecls(NewDecls);
4520 TC.setRequiresImport(!AnyVisibleDecls);
4521 }
4522}
4523
4524// Fill the supplied vector with the IdentifierInfo pointers for each piece of
4525// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4526// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4530 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4531 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4532 else
4533 Identifiers.clear();
4534
4535 const IdentifierInfo *II = nullptr;
4536
4537 switch (NNS->getKind()) {
4539 II = NNS->getAsIdentifier();
4540 break;
4541
4544 return;
4545 II = NNS->getAsNamespace()->getIdentifier();
4546 break;
4547
4549 II = NNS->getAsNamespaceAlias()->getIdentifier();
4550 break;
4551
4554 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4555 break;
4556
4559 return;
4560 }
4561
4562 if (II)
4563 Identifiers.push_back(II);
4564}
4565
4567 DeclContext *Ctx, bool InBaseClass) {
4568 // Don't consider hidden names for typo correction.
4569 if (Hiding)
4570 return;
4571
4572 // Only consider entities with identifiers for names, ignoring
4573 // special names (constructors, overloaded operators, selectors,
4574 // etc.).
4575 IdentifierInfo *Name = ND->getIdentifier();
4576 if (!Name)
4577 return;
4578
4579 // Only consider visible declarations and declarations from modules with
4580 // names that exactly match.
4581 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4582 return;
4583
4584 FoundName(Name->getName());
4585}
4586
4588 // Compute the edit distance between the typo and the name of this
4589 // entity, and add the identifier to the list of results.
4590 addName(Name, nullptr);
4591}
4592
4594 // Compute the edit distance between the typo and this keyword,
4595 // and add the keyword to the list of results.
4596 addName(Keyword, nullptr, nullptr, true);
4597}
4598
4599void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4600 NestedNameSpecifier *NNS, bool isKeyword) {
4601 // Use a simple length-based heuristic to determine the minimum possible
4602 // edit distance. If the minimum isn't good enough, bail out early.
4603 StringRef TypoStr = Typo->getName();
4604 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4605 if (MinED && TypoStr.size() / MinED < 3)
4606 return;
4607
4608 // Compute an upper bound on the allowable edit distance, so that the
4609 // edit-distance algorithm can short-circuit.
4610 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4611 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4612 if (ED > UpperBound) return;
4613
4614 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4615 if (isKeyword) TC.makeKeyword();
4616 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4617 addCorrection(TC);
4618}
4619
4620static const unsigned MaxTypoDistanceResultSets = 5;
4621
4623 StringRef TypoStr = Typo->getName();
4624 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4625
4626 // For very short typos, ignore potential corrections that have a different
4627 // base identifier from the typo or which have a normalized edit distance
4628 // longer than the typo itself.
4629 if (TypoStr.size() < 3 &&
4630 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4631 return;
4632
4633 // If the correction is resolved but is not viable, ignore it.
4634 if (Correction.isResolved()) {
4635 checkCorrectionVisibility(SemaRef, Correction);
4636 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4637 return;
4638 }
4639
4640 TypoResultList &CList =
4641 CorrectionResults[Correction.getEditDistance(false)][Name];
4642
4643 if (!CList.empty() && !CList.back().isResolved())
4644 CList.pop_back();
4645 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4646 auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4647 return TypoCorr.getCorrectionDecl() == NewND;
4648 });
4649 if (RI != CList.end()) {
4650 // The Correction refers to a decl already in the list. No insertion is
4651 // necessary and all further cases will return.
4652
4653 auto IsDeprecated = [](Decl *D) {
4654 while (D) {
4655 if (D->isDeprecated())
4656 return true;
4657 D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4658 }
4659 return false;
4660 };
4661
4662 // Prefer non deprecated Corrections over deprecated and only then
4663 // sort using an alphabetical order.
4664 std::pair<bool, std::string> NewKey = {
4665 IsDeprecated(Correction.getFoundDecl()),
4666 Correction.getAsString(SemaRef.getLangOpts())};
4667
4668 std::pair<bool, std::string> PrevKey = {
4669 IsDeprecated(RI->getFoundDecl()),
4670 RI->getAsString(SemaRef.getLangOpts())};
4671
4672 if (NewKey < PrevKey)
4673 *RI = Correction;
4674 return;
4675 }
4676 }
4677 if (CList.empty() || Correction.isResolved())
4678 CList.push_back(Correction);
4679
4680 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4681 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4682}
4683
4685 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4686 SearchNamespaces = true;
4687
4688 for (auto KNPair : KnownNamespaces)
4689 Namespaces.addNameSpecifier(KNPair.first);
4690
4691 bool SSIsTemplate = false;
4692 if (NestedNameSpecifier *NNS =
4693 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4694 if (const Type *T = NNS->getAsType())
4695 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4696 }
4697 // Do not transform this into an iterator-based loop. The loop body can
4698 // trigger the creation of further types (through lazy deserialization) and
4699 // invalid iterators into this list.
4700 auto &Types = SemaRef.getASTContext().getTypes();
4701 for (unsigned I = 0; I != Types.size(); ++I) {
4702 const auto *TI = Types[I];
4703 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4704 CD = CD->getCanonicalDecl();
4705 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4706 !CD->isUnion() && CD->getIdentifier() &&
4707 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4708 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4709 Namespaces.addNameSpecifier(CD);
4710 }
4711 }
4712}
4713
4715 if (++CurrentTCIndex < ValidatedCorrections.size())
4716 return ValidatedCorrections[CurrentTCIndex];
4717
4718 CurrentTCIndex = ValidatedCorrections.size();
4719 while (!CorrectionResults.empty()) {
4720 auto DI = CorrectionResults.begin();
4721 if (DI->second.empty()) {
4722 CorrectionResults.erase(DI);
4723 continue;
4724 }
4725
4726 auto RI = DI->second.begin();
4727 if (RI->second.empty()) {
4728 DI->second.erase(RI);
4729 performQualifiedLookups();
4730 continue;
4731 }
4732
4733 TypoCorrection TC = RI->second.pop_back_val();
4734 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4735 ValidatedCorrections.push_back(TC);
4736 return ValidatedCorrections[CurrentTCIndex];
4737 }
4738 }
4739 return ValidatedCorrections[0]; // The empty correction.
4740}
4741
4742bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4744 DeclContext *TempMemberContext = MemberContext;
4745 CXXScopeSpec *TempSS = SS.get();
4746retry_lookup:
4747 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4748 EnteringContext,
4749 CorrectionValidator->IsObjCIvarLookup,
4750 Name == Typo && !Candidate.WillReplaceSpecifier());
4751 switch (Result.getResultKind()) {
4755 if (TempSS) {
4756 // Immediately retry the lookup without the given CXXScopeSpec
4757 TempSS = nullptr;
4758 Candidate.WillReplaceSpecifier(true);
4759 goto retry_lookup;
4760 }
4761 if (TempMemberContext) {
4762 if (SS && !TempSS)
4763 TempSS = SS.get();
4764 TempMemberContext = nullptr;
4765 goto retry_lookup;
4766 }
4767 if (SearchNamespaces)
4768 QualifiedResults.push_back(Candidate);
4769 break;
4770
4772 // We don't deal with ambiguities.
4773 break;
4774
4777 // Store all of the Decls for overloaded symbols
4778 for (auto *TRD : Result)
4779 Candidate.addCorrectionDecl(TRD);
4780 checkCorrectionVisibility(SemaRef, Candidate);
4781 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4782 if (SearchNamespaces)
4783 QualifiedResults.push_back(Candidate);
4784 break;
4785 }
4786 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4787 return true;
4788 }
4789 return false;
4790}
4791
4792void TypoCorrectionConsumer::performQualifiedLookups() {
4793 unsigned TypoLen = Typo->getName().size();
4794 for (const TypoCorrection &QR : QualifiedResults) {
4795 for (const auto &NSI : Namespaces) {
4796 DeclContext *Ctx = NSI.DeclCtx;
4797 const Type *NSType = NSI.NameSpecifier->getAsType();
4798
4799 // If the current NestedNameSpecifier refers to a class and the
4800 // current correction candidate is the name of that class, then skip
4801 // it as it is unlikely a qualified version of the class' constructor
4802 // is an appropriate correction.
4803 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4804 nullptr) {
4805 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4806 continue;
4807 }
4808
4809 TypoCorrection TC(QR);
4810 TC.ClearCorrectionDecls();
4811 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4812 TC.setQualifierDistance(NSI.EditDistance);
4813 TC.setCallbackDistance(0); // Reset the callback distance
4814
4815 // If the current correction candidate and namespace combination are
4816 // too far away from the original typo based on the normalized edit
4817 // distance, then skip performing a qualified name lookup.
4818 unsigned TmpED = TC.getEditDistance(true);
4819 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4820 TypoLen / TmpED < 3)
4821 continue;
4822
4823 Result.clear();
4824 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4825 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4826 continue;
4827
4828 // Any corrections added below will be validated in subsequent
4829 // iterations of the main while() loop over the Consumer's contents.
4830 switch (Result.getResultKind()) {
4833 if (SS && SS->isValid()) {
4834 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4835 std::string OldQualified;
4836 llvm::raw_string_ostream OldOStream(OldQualified);
4837 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4838 OldOStream << Typo->getName();
4839 // If correction candidate would be an identical written qualified
4840 // identifier, then the existing CXXScopeSpec probably included a
4841 // typedef that didn't get accounted for properly.
4842 if (OldOStream.str() == NewQualified)
4843 break;
4844 }
4845 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4846 TRD != TRDEnd; ++TRD) {
4847 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4848 NSType ? NSType->getAsCXXRecordDecl()
4849 : nullptr,
4850 TRD.getPair()) == Sema::AR_accessible)
4851 TC.addCorrectionDecl(*TRD);
4852 }
4853 if (TC.isResolved()) {
4854 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4855 addCorrection(TC);
4856 }
4857 break;
4858 }
4863 break;
4864 }
4865 }
4866 }
4867 QualifiedResults.clear();
4868}
4869
4870TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4871 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4872 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4873 if (NestedNameSpecifier *NNS =
4874 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4875 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4876 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4877
4878 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4879 }
4880 // Build the list of identifiers that would be used for an absolute
4881 // (from the global context) NestedNameSpecifier referring to the current
4882 // context.
4883 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4884 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4885 CurContextIdentifiers.push_back(ND->getIdentifier());
4886 }
4887
4888 // Add the global context as a NestedNameSpecifier
4889 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4891 DistanceMap[1].push_back(SI);
4892}
4893
4894auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4895 DeclContext *Start) -> DeclContextList {
4896 assert(Start && "Building a context chain from a null context");
4897 DeclContextList Chain;
4898 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4899 DC = DC->getLookupParent()) {
4900 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4901 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4902 !(ND && ND->isAnonymousNamespace()))
4903 Chain.push_back(DC->getPrimaryContext());
4904 }
4905 return Chain;
4906}
4907
4908unsigned
4909TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4910 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4911 unsigned NumSpecifiers = 0;
4912 for (DeclContext *C : llvm::reverse(DeclChain)) {
4913 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4914 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4915 ++NumSpecifiers;
4916 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4917 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4918 RD->getTypeForDecl());
4919 ++NumSpecifiers;
4920 }
4921 }
4922 return NumSpecifiers;
4923}
4924
4925void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4926 DeclContext *Ctx) {
4927 NestedNameSpecifier *NNS = nullptr;
4928 unsigned NumSpecifiers = 0;
4929 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4930 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4931
4932 // Eliminate common elements from the two DeclContext chains.
4933 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4934 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4935 break;
4936 NamespaceDeclChain.pop_back();
4937 }
4938
4939 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4940 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4941
4942 // Add an explicit leading '::' specifier if needed.
4943 if (NamespaceDeclChain.empty()) {
4944 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4946 NumSpecifiers =
4947 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4948 } else if (NamedDecl *ND =
4949 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4950 IdentifierInfo *Name = ND->getIdentifier();
4951 bool SameNameSpecifier = false;
4952 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
4953 std::string NewNameSpecifier;
4954 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4955 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4956 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4957 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4958 SpecifierOStream.flush();
4959 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4960 }
4961 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
4962 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4964 NumSpecifiers =
4965 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4966 }
4967 }
4968
4969 // If the built NestedNameSpecifier would be replacing an existing
4970 // NestedNameSpecifier, use the number of component identifiers that
4971 // would need to be changed as the edit distance instead of the number
4972 // of components in the built NestedNameSpecifier.
4973 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4974 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4975 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4976 NumSpecifiers =
4977 llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),
4978 llvm::ArrayRef(NewNameSpecifierIdentifiers));
4979 }
4980
4981 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4982 DistanceMap[NumSpecifiers].push_back(SI);
4983}
4984
4985/// Perform name lookup for a possible result for typo correction.
4986static void LookupPotentialTypoResult(Sema &SemaRef,
4987 LookupResult &Res,
4988 IdentifierInfo *Name,
4989 Scope *S, CXXScopeSpec *SS,
4990 DeclContext *MemberContext,
4991 bool EnteringContext,
4992 bool isObjCIvarLookup,
4993 bool FindHidden) {
4994 Res.suppressDiagnostics();
4995 Res.clear();
4996 Res.setLookupName(Name);
4997 Res.setAllowHidden(FindHidden);
4998 if (MemberContext) {
4999 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
5000 if (isObjCIvarLookup) {
5001 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
5002 Res.addDecl(Ivar);
5003 Res.resolveKind();
5004 return;
5005 }
5006 }
5007
5008 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
5010 Res.addDecl(Prop);
5011 Res.resolveKind();
5012 return;
5013 }
5014 }
5015
5016 SemaRef.LookupQualifiedName(Res, MemberContext);
5017 return;
5018 }
5019
5020 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
5021 EnteringContext);
5022
5023 // Fake ivar lookup; this should really be part of
5024 // LookupParsedName.
5025 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
5026 if (Method->isInstanceMethod() && Method->getClassInterface() &&
5027 (Res.empty() ||
5028 (Res.isSingleResult() &&
5030 if (ObjCIvarDecl *IV
5031 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
5032 Res.addDecl(IV);
5033 Res.resolveKind();
5034 }
5035 }
5036 }
5037}
5038
5039/// Add keywords to the consumer as possible typo corrections.
5040static void AddKeywordsToConsumer(Sema &SemaRef,
5041 TypoCorrectionConsumer &Consumer,
5043 bool AfterNestedNameSpecifier) {
5044 if (AfterNestedNameSpecifier) {
5045 // For 'X::', we know exactly which keywords can appear next.
5046 Consumer.addKeywordResult("template");
5047 if (CCC.WantExpressionKeywords)
5048 Consumer.addKeywordResult("operator");
5049 return;
5050 }
5051
5052 if (CCC.WantObjCSuper)
5053 Consumer.addKeywordResult("super");
5054
5055 if (CCC.WantTypeSpecifiers) {
5056 // Add type-specifier keywords to the set of results.
5057 static const char *const CTypeSpecs[] = {
5058 "char", "const", "double", "enum", "float", "int", "long", "short",
5059 "signed", "struct", "union", "unsigned", "void", "volatile",
5060 "_Complex", "_Imaginary",
5061 // storage-specifiers as well
5062 "extern", "inline", "static", "typedef"
5063 };
5064
5065 for (const auto *CTS : CTypeSpecs)
5066 Consumer.addKeywordResult(CTS);
5067
5068 if (SemaRef.getLangOpts().C99)
5069 Consumer.addKeywordResult("restrict");
5070 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
5071 Consumer.addKeywordResult("bool");
5072 else if (SemaRef.getLangOpts().C99)
5073 Consumer.addKeywordResult("_Bool");
5074
5075 if (SemaRef.getLangOpts().CPlusPlus) {
5076 Consumer.addKeywordResult("class");
5077 Consumer.addKeywordResult("typename");
5078 Consumer.addKeywordResult("wchar_t");
5079
5080 if (SemaRef.getLangOpts().CPlusPlus11) {
5081 Consumer.addKeywordResult("char16_t");
5082 Consumer.addKeywordResult("char32_t");
5083 Consumer.addKeywordResult("constexpr");
5084 Consumer.addKeywordResult("decltype");
5085 Consumer.addKeywordResult("thread_local");
5086 }
5087 }
5088
5089 if (SemaRef.getLangOpts().GNUKeywords)
5090 Consumer.addKeywordResult("typeof");
5091 } else if (CCC.WantFunctionLikeCasts) {
5092 static const char *const CastableTypeSpecs[] = {
5093 "char", "double", "float", "int", "long", "short",
5094 "signed", "unsigned", "void"
5095 };
5096 for (auto *kw : CastableTypeSpecs)
5097 Consumer.addKeywordResult(kw);
5098 }
5099
5100 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5101 Consumer.addKeywordResult("const_cast");
5102 Consumer.addKeywordResult("dynamic_cast");
5103 Consumer.addKeywordResult("reinterpret_cast");
5104 Consumer.addKeywordResult("static_cast");
5105 }
5106
5107 if (CCC.WantExpressionKeywords) {
5108 Consumer.addKeywordResult("sizeof");
5109 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5110 Consumer.addKeywordResult("false");
5111 Consumer.addKeywordResult("true");
5112 }
5113
5114 if (SemaRef.getLangOpts().CPlusPlus) {
5115 static const char *const CXXExprs[] = {
5116 "delete", "new", "operator", "throw", "typeid"
5117 };
5118 for (const auto *CE : CXXExprs)
5119 Consumer.addKeywordResult(CE);
5120
5121 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
5122 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
5123 Consumer.addKeywordResult("this");
5124
5125 if (SemaRef.getLangOpts().CPlusPlus11) {
5126 Consumer.addKeywordResult("alignof");
5127 Consumer.addKeywordResult("nullptr");
5128 }
5129 }
5130
5131 if (SemaRef.getLangOpts().C11) {
5132 // FIXME: We should not suggest _Alignof if the alignof macro
5133 // is present.
5134 Consumer.addKeywordResult("_Alignof");
5135 }
5136 }
5137
5138 if (CCC.WantRemainingKeywords) {
5139 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5140 // Statements.
5141 static const char *const CStmts[] = {
5142 "do", "else", "for", "goto", "if", "return", "switch", "while" };
5143 for (const auto *CS : CStmts)
5144 Consumer.addKeywordResult(CS);
5145
5146 if (SemaRef.getLangOpts().CPlusPlus) {
5147 Consumer.addKeywordResult("catch");
5148 Consumer.addKeywordResult("try");
5149 }
5150
5151 if (S && S->getBreakParent())
5152 Consumer.addKeywordResult("break");
5153
5154 if (S && S->getContinueParent())
5155 Consumer.addKeywordResult("continue");
5156
5157 if (SemaRef.getCurFunction() &&
5158 !SemaRef.getCurFunction()->SwitchStack.empty()) {
5159 Consumer.addKeywordResult("case");
5160 Consumer.addKeywordResult("default");
5161 }
5162 } else {
5163 if (SemaRef.getLangOpts().CPlusPlus) {
5164 Consumer.addKeywordResult("namespace");
5165 Consumer.addKeywordResult("template");
5166 }
5167
5168 if (S && S->isClassScope()) {
5169 Consumer.addKeywordResult("explicit");
5170 Consumer.addKeywordResult("friend");
5171 Consumer.addKeywordResult("mutable");
5172 Consumer.addKeywordResult("private");
5173 Consumer.addKeywordResult("protected");
5174 Consumer.addKeywordResult("public");
5175 Consumer.addKeywordResult("virtual");
5176 }
5177 }
5178
5179 if (SemaRef.getLangOpts().CPlusPlus) {
5180 Consumer.addKeywordResult("using");
5181
5182 if (SemaRef.getLangOpts().CPlusPlus11)
5183 Consumer.addKeywordResult("static_assert");
5184 }
5185 }
5186}
5187
5188std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5189 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5191 DeclContext *MemberContext, bool EnteringContext,
5192 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5193
5194 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5196 return nullptr;
5197
5198 // In Microsoft mode, don't perform typo correction in a template member
5199 // function dependent context because it interferes with the "lookup into
5200 // dependent bases of class templates" feature.
5201 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5202 isa<CXXMethodDecl>(CurContext))
5203 return nullptr;
5204
5205 // We only attempt to correct typos for identifiers.
5206 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5207 if (!Typo)
5208 return nullptr;
5209
5210 // If the scope specifier itself was invalid, don't try to correct
5211 // typos.
5212 if (SS && SS->isInvalid())
5213 return nullptr;
5214
5215 // Never try to correct typos during any kind of code synthesis.
5216 if (!CodeSynthesisContexts.empty())
5217 return nullptr;
5218
5219 // Don't try to correct 'super'.
5220 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5221 return nullptr;
5222
5223 // Abort if typo correction already failed for this specific typo.
5224 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
5225 if (locs != TypoCorrectionFailures.end() &&
5226 locs->second.count(TypoName.getLoc()))
5227 return nullptr;
5228
5229 // Don't try to correct the identifier "vector" when in AltiVec mode.
5230 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5231 // remove this workaround.
5232 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
5233 return nullptr;
5234
5235 // Provide a stop gap for files that are just seriously broken. Trying
5236 // to correct all typos can turn into a HUGE performance penalty, causing
5237 // some files to take minutes to get rejected by the parser.
5238 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5239 if (Limit && TyposCorrected >= Limit)
5240 return nullptr;
5242
5243 // If we're handling a missing symbol error, using modules, and the
5244 // special search all modules option is used, look for a missing import.
5245 if (ErrorRecovery && getLangOpts().Modules &&
5246 getLangOpts().ModulesSearchAll) {
5247 // The following has the side effect of loading the missing module.
5248 getModuleLoader().lookupMissingImports(Typo->getName(),
5249 TypoName.getBeginLoc());
5250 }
5251
5252 // Extend the lifetime of the callback. We delayed this until here
5253 // to avoid allocations in the hot path (which is where no typo correction
5254 // occurs). Note that CorrectionCandidateCallback is polymorphic and
5255 // initially stack-allocated.
5256 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5257 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5258 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5259 EnteringContext);
5260
5261 // Perform name lookup to find visible, similarly-named entities.
5262 bool IsUnqualifiedLookup = false;
5263 DeclContext *QualifiedDC = MemberContext;
5264 if (MemberContext) {
5265 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
5266
5267 // Look in qualified interfaces.
5268 if (OPT) {
5269 for (auto *I : OPT->quals())
5270 LookupVisibleDecls(I, LookupKind, *Consumer);
5271 }
5272 } else if (SS && SS->isSet()) {
5273 QualifiedDC = computeDeclContext(*SS, EnteringContext);
5274 if (!QualifiedDC)
5275 return nullptr;
5276
5277 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
5278 } else {
5279 IsUnqualifiedLookup = true;
5280 }
5281
5282 // Determine whether we are going to search in the various namespaces for
5283 // corrections.
5284 bool SearchNamespaces
5285 = getLangOpts().CPlusPlus &&
5286 (IsUnqualifiedLookup || (SS && SS->isSet()));
5287
5288 if (IsUnqualifiedLookup || SearchNamespaces) {
5289 // For unqualified lookup, look through all of the names that we have
5290 // seen in this translation unit.
5291 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5292 for (const auto &I : Context.Idents)
5293 Consumer->FoundName(I.getKey());
5294
5295 // Walk through identifiers in external identifier sources.
5296 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5299 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5300 do {
5301 StringRef Name = Iter->Next();
5302 if (Name.empty())
5303 break;
5304
5305 Consumer->FoundName(Name);
5306 } while (true);
5307 }
5308 }
5309
5311 *Consumer->getCorrectionValidator(),
5312 SS && SS->isNotEmpty());
5313
5314 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5315 // to search those namespaces.
5316 if (SearchNamespaces) {
5317 // Load any externally-known namespaces.
5318 if (