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