xref: /llvm-project/clang/lib/Sema/SemaLookup.cpp (revision f5be5cdaad7edf52e39ad439cf5d608c930efca2)
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 && FM->isNamedModule() && !FM->isPrivateModule() &&
3854                    "bad export context");
3855             // .. are attached to a named module M, do not appear in the
3856             // translation unit containing the point of the lookup..
3857             if (D->isInAnotherModuleUnit() &&
3858                 llvm::any_of(AssociatedClasses, [&](auto *E) {
3859                   // ... and have the same innermost enclosing non-inline
3860                   // namespace scope as a declaration of an associated entity
3861                   // attached to M
3862                   if (E->getOwningModule() != FM)
3863                     return false;
3864                   // TODO: maybe this could be cached when generating the
3865                   // associated namespaces / entities.
3866                   DeclContext *Ctx = E->getDeclContext();
3867                   while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
3868                     Ctx = Ctx->getParent();
3869                   return Ctx == NS;
3870                 })) {
3871               Visible = true;
3872               break;
3873             }
3874           }
3875         } else if (D->getFriendObjectKind()) {
3876           auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3877           // [basic.lookup.argdep]p4:
3878           //   Argument-dependent lookup finds all declarations of functions and
3879           //   function templates that
3880           //  - ...
3881           //  - are declared as a friend ([class.friend]) of any class with a
3882           //  reachable definition in the set of associated entities,
3883           //
3884           // FIXME: If there's a merged definition of D that is reachable, then
3885           // the friend declaration should be considered.
3886           if (AssociatedClasses.count(RD) && isReachable(D)) {
3887             Visible = true;
3888             break;
3889           }
3890         }
3891       }
3892 
3893       // FIXME: Preserve D as the FoundDecl.
3894       if (Visible)
3895         Result.insert(Underlying);
3896     }
3897   }
3898 }
3899 
3900 //----------------------------------------------------------------------------
3901 // Search for all visible declarations.
3902 //----------------------------------------------------------------------------
3903 VisibleDeclConsumer::~VisibleDeclConsumer() { }
3904 
3905 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3906 
3907 namespace {
3908 
3909 class ShadowContextRAII;
3910 
3911 class VisibleDeclsRecord {
3912 public:
3913   /// An entry in the shadow map, which is optimized to store a
3914   /// single declaration (the common case) but can also store a list
3915   /// of declarations.
3916   typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3917 
3918 private:
3919   /// A mapping from declaration names to the declarations that have
3920   /// this name within a particular scope.
3921   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3922 
3923   /// A list of shadow maps, which is used to model name hiding.
3924   std::list<ShadowMap> ShadowMaps;
3925 
3926   /// The declaration contexts we have already visited.
3927   llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3928 
3929   friend class ShadowContextRAII;
3930 
3931 public:
3932   /// Determine whether we have already visited this context
3933   /// (and, if not, note that we are going to visit that context now).
3934   bool visitedContext(DeclContext *Ctx) {
3935     return !VisitedContexts.insert(Ctx).second;
3936   }
3937 
3938   bool alreadyVisitedContext(DeclContext *Ctx) {
3939     return VisitedContexts.count(Ctx);
3940   }
3941 
3942   /// Determine whether the given declaration is hidden in the
3943   /// current scope.
3944   ///
3945   /// \returns the declaration that hides the given declaration, or
3946   /// NULL if no such declaration exists.
3947   NamedDecl *checkHidden(NamedDecl *ND);
3948 
3949   /// Add a declaration to the current shadow map.
3950   void add(NamedDecl *ND) {
3951     ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3952   }
3953 };
3954 
3955 /// RAII object that records when we've entered a shadow context.
3956 class ShadowContextRAII {
3957   VisibleDeclsRecord &Visible;
3958 
3959   typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3960 
3961 public:
3962   ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3963     Visible.ShadowMaps.emplace_back();
3964   }
3965 
3966   ~ShadowContextRAII() {
3967     Visible.ShadowMaps.pop_back();
3968   }
3969 };
3970 
3971 } // end anonymous namespace
3972 
3973 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3974   unsigned IDNS = ND->getIdentifierNamespace();
3975   std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3976   for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3977        SM != SMEnd; ++SM) {
3978     ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3979     if (Pos == SM->end())
3980       continue;
3981 
3982     for (auto *D : Pos->second) {
3983       // A tag declaration does not hide a non-tag declaration.
3984       if (D->hasTagIdentifierNamespace() &&
3985           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
3986                    Decl::IDNS_ObjCProtocol)))
3987         continue;
3988 
3989       // Protocols are in distinct namespaces from everything else.
3990       if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3991            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3992           D->getIdentifierNamespace() != IDNS)
3993         continue;
3994 
3995       // Functions and function templates in the same scope overload
3996       // rather than hide.  FIXME: Look for hiding based on function
3997       // signatures!
3998       if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3999           ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4000           SM == ShadowMaps.rbegin())
4001         continue;
4002 
4003       // A shadow declaration that's created by a resolved using declaration
4004       // is not hidden by the same using declaration.
4005       if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
4006           cast<UsingShadowDecl>(ND)->getIntroducer() == D)
4007         continue;
4008 
4009       // We've found a declaration that hides this one.
4010       return D;
4011     }
4012   }
4013 
4014   return nullptr;
4015 }
4016 
4017 namespace {
4018 class LookupVisibleHelper {
4019 public:
4020   LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
4021                       bool LoadExternal)
4022       : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4023         LoadExternal(LoadExternal) {}
4024 
4025   void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4026                           bool IncludeGlobalScope) {
4027     // Determine the set of using directives available during
4028     // unqualified name lookup.
4029     Scope *Initial = S;
4030     UnqualUsingDirectiveSet UDirs(SemaRef);
4031     if (SemaRef.getLangOpts().CPlusPlus) {
4032       // Find the first namespace or translation-unit scope.
4033       while (S && !isNamespaceOrTranslationUnitScope(S))
4034         S = S->getParent();
4035 
4036       UDirs.visitScopeChain(Initial, S);
4037     }
4038     UDirs.done();
4039 
4040     // Look for visible declarations.
4041     LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4042     Result.setAllowHidden(Consumer.includeHiddenDecls());
4043     if (!IncludeGlobalScope)
4044       Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4045     ShadowContextRAII Shadow(Visited);
4046     lookupInScope(Initial, Result, UDirs);
4047   }
4048 
4049   void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4050                           Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4051     LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4052     Result.setAllowHidden(Consumer.includeHiddenDecls());
4053     if (!IncludeGlobalScope)
4054       Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4055 
4056     ShadowContextRAII Shadow(Visited);
4057     lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4058                         /*InBaseClass=*/false);
4059   }
4060 
4061 private:
4062   void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4063                            bool QualifiedNameLookup, bool InBaseClass) {
4064     if (!Ctx)
4065       return;
4066 
4067     // Make sure we don't visit the same context twice.
4068     if (Visited.visitedContext(Ctx->getPrimaryContext()))
4069       return;
4070 
4071     Consumer.EnteredContext(Ctx);
4072 
4073     // Outside C++, lookup results for the TU live on identifiers.
4074     if (isa<TranslationUnitDecl>(Ctx) &&
4075         !Result.getSema().getLangOpts().CPlusPlus) {
4076       auto &S = Result.getSema();
4077       auto &Idents = S.Context.Idents;
4078 
4079       // Ensure all external identifiers are in the identifier table.
4080       if (LoadExternal)
4081         if (IdentifierInfoLookup *External =
4082                 Idents.getExternalIdentifierLookup()) {
4083           std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4084           for (StringRef Name = Iter->Next(); !Name.empty();
4085                Name = Iter->Next())
4086             Idents.get(Name);
4087         }
4088 
4089       // Walk all lookup results in the TU for each identifier.
4090       for (const auto &Ident : Idents) {
4091         for (auto I = S.IdResolver.begin(Ident.getValue()),
4092                   E = S.IdResolver.end();
4093              I != E; ++I) {
4094           if (S.IdResolver.isDeclInScope(*I, Ctx)) {
4095             if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4096               Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4097               Visited.add(ND);
4098             }
4099           }
4100         }
4101       }
4102 
4103       return;
4104     }
4105 
4106     if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
4107       Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4108 
4109     llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;
4110     // We sometimes skip loading namespace-level results (they tend to be huge).
4111     bool Load = LoadExternal ||
4112                 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
4113     // Enumerate all of the results in this context.
4114     for (DeclContextLookupResult R :
4115          Load ? Ctx->lookups()
4116               : Ctx->noload_lookups(/*PreserveInternalState=*/false))
4117       for (auto *D : R)
4118         // Rather than visit immediately, we put ND into a vector and visit
4119         // all decls, in order, outside of this loop. The reason is that
4120         // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)
4121         // may invalidate the iterators used in the two
4122         // loops above.
4123         DeclsToVisit.push_back(D);
4124 
4125     for (auto *D : DeclsToVisit)
4126       if (auto *ND = Result.getAcceptableDecl(D)) {
4127         Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4128         Visited.add(ND);
4129       }
4130 
4131     DeclsToVisit.clear();
4132 
4133     // Traverse using directives for qualified name lookup.
4134     if (QualifiedNameLookup) {
4135       ShadowContextRAII Shadow(Visited);
4136       for (auto *I : Ctx->using_directives()) {
4137         if (!Result.getSema().isVisible(I))
4138           continue;
4139         lookupInDeclContext(I->getNominatedNamespace(), Result,
4140                             QualifiedNameLookup, InBaseClass);
4141       }
4142     }
4143 
4144     // Traverse the contexts of inherited C++ classes.
4145     if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
4146       if (!Record->hasDefinition())
4147         return;
4148 
4149       for (const auto &B : Record->bases()) {
4150         QualType BaseType = B.getType();
4151 
4152         RecordDecl *RD;
4153         if (BaseType->isDependentType()) {
4154           if (!IncludeDependentBases) {
4155             // Don't look into dependent bases, because name lookup can't look
4156             // there anyway.
4157             continue;
4158           }
4159           const auto *TST = BaseType->getAs<TemplateSpecializationType>();
4160           if (!TST)
4161             continue;
4162           TemplateName TN = TST->getTemplateName();
4163           const auto *TD =
4164               dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
4165           if (!TD)
4166             continue;
4167           RD = TD->getTemplatedDecl();
4168         } else {
4169           const auto *Record = BaseType->getAs<RecordType>();
4170           if (!Record)
4171             continue;
4172           RD = Record->getDecl();
4173         }
4174 
4175         // FIXME: It would be nice to be able to determine whether referencing
4176         // a particular member would be ambiguous. For example, given
4177         //
4178         //   struct A { int member; };
4179         //   struct B { int member; };
4180         //   struct C : A, B { };
4181         //
4182         //   void f(C *c) { c->### }
4183         //
4184         // accessing 'member' would result in an ambiguity. However, we
4185         // could be smart enough to qualify the member with the base
4186         // class, e.g.,
4187         //
4188         //   c->B::member
4189         //
4190         // or
4191         //
4192         //   c->A::member
4193 
4194         // Find results in this base class (and its bases).
4195         ShadowContextRAII Shadow(Visited);
4196         lookupInDeclContext(RD, Result, QualifiedNameLookup,
4197                             /*InBaseClass=*/true);
4198       }
4199     }
4200 
4201     // Traverse the contexts of Objective-C classes.
4202     if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
4203       // Traverse categories.
4204       for (auto *Cat : IFace->visible_categories()) {
4205         ShadowContextRAII Shadow(Visited);
4206         lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4207                             /*InBaseClass=*/false);
4208       }
4209 
4210       // Traverse protocols.
4211       for (auto *I : IFace->all_referenced_protocols()) {
4212         ShadowContextRAII Shadow(Visited);
4213         lookupInDeclContext(I, Result, QualifiedNameLookup,
4214                             /*InBaseClass=*/false);
4215       }
4216 
4217       // Traverse the superclass.
4218       if (IFace->getSuperClass()) {
4219         ShadowContextRAII Shadow(Visited);
4220         lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4221                             /*InBaseClass=*/true);
4222       }
4223 
4224       // If there is an implementation, traverse it. We do this to find
4225       // synthesized ivars.
4226       if (IFace->getImplementation()) {
4227         ShadowContextRAII Shadow(Visited);
4228         lookupInDeclContext(IFace->getImplementation(), Result,
4229                             QualifiedNameLookup, InBaseClass);
4230       }
4231     } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4232       for (auto *I : Protocol->protocols()) {
4233         ShadowContextRAII Shadow(Visited);
4234         lookupInDeclContext(I, Result, QualifiedNameLookup,
4235                             /*InBaseClass=*/false);
4236       }
4237     } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4238       for (auto *I : Category->protocols()) {
4239         ShadowContextRAII Shadow(Visited);
4240         lookupInDeclContext(I, Result, QualifiedNameLookup,
4241                             /*InBaseClass=*/false);
4242       }
4243 
4244       // If there is an implementation, traverse it.
4245       if (Category->getImplementation()) {
4246         ShadowContextRAII Shadow(Visited);
4247         lookupInDeclContext(Category->getImplementation(), Result,
4248                             QualifiedNameLookup, /*InBaseClass=*/true);
4249       }
4250     }
4251   }
4252 
4253   void lookupInScope(Scope *S, LookupResult &Result,
4254                      UnqualUsingDirectiveSet &UDirs) {
4255     // No clients run in this mode and it's not supported. Please add tests and
4256     // remove the assertion if you start relying on it.
4257     assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4258 
4259     if (!S)
4260       return;
4261 
4262     if (!S->getEntity() ||
4263         (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4264         (S->getEntity())->isFunctionOrMethod()) {
4265       FindLocalExternScope FindLocals(Result);
4266       // Walk through the declarations in this Scope. The consumer might add new
4267       // decls to the scope as part of deserialization, so make a copy first.
4268       SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4269       for (Decl *D : ScopeDecls) {
4270         if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4271           if ((ND = Result.getAcceptableDecl(ND))) {
4272             Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4273             Visited.add(ND);
4274           }
4275       }
4276     }
4277 
4278     DeclContext *Entity = S->getLookupEntity();
4279     if (Entity) {
4280       // Look into this scope's declaration context, along with any of its
4281       // parent lookup contexts (e.g., enclosing classes), up to the point
4282       // where we hit the context stored in the next outer scope.
4283       DeclContext *OuterCtx = findOuterContext(S);
4284 
4285       for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4286            Ctx = Ctx->getLookupParent()) {
4287         if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4288           if (Method->isInstanceMethod()) {
4289             // For instance methods, look for ivars in the method's interface.
4290             LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4291                                     Result.getNameLoc(),
4292                                     Sema::LookupMemberName);
4293             if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4294               lookupInDeclContext(IFace, IvarResult,
4295                                   /*QualifiedNameLookup=*/false,
4296                                   /*InBaseClass=*/false);
4297             }
4298           }
4299 
4300           // We've already performed all of the name lookup that we need
4301           // to for Objective-C methods; the next context will be the
4302           // outer scope.
4303           break;
4304         }
4305 
4306         if (Ctx->isFunctionOrMethod())
4307           continue;
4308 
4309         lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4310                             /*InBaseClass=*/false);
4311       }
4312     } else if (!S->getParent()) {
4313       // Look into the translation unit scope. We walk through the translation
4314       // unit's declaration context, because the Scope itself won't have all of
4315       // the declarations if we loaded a precompiled header.
4316       // FIXME: We would like the translation unit's Scope object to point to
4317       // the translation unit, so we don't need this special "if" branch.
4318       // However, doing so would force the normal C++ name-lookup code to look
4319       // into the translation unit decl when the IdentifierInfo chains would
4320       // suffice. Once we fix that problem (which is part of a more general
4321       // "don't look in DeclContexts unless we have to" optimization), we can
4322       // eliminate this.
4323       Entity = Result.getSema().Context.getTranslationUnitDecl();
4324       lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4325                           /*InBaseClass=*/false);
4326     }
4327 
4328     if (Entity) {
4329       // Lookup visible declarations in any namespaces found by using
4330       // directives.
4331       for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4332         lookupInDeclContext(
4333             const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4334             /*QualifiedNameLookup=*/false,
4335             /*InBaseClass=*/false);
4336     }
4337 
4338     // Lookup names in the parent scope.
4339     ShadowContextRAII Shadow(Visited);
4340     lookupInScope(S->getParent(), Result, UDirs);
4341   }
4342 
4343 private:
4344   VisibleDeclsRecord Visited;
4345   VisibleDeclConsumer &Consumer;
4346   bool IncludeDependentBases;
4347   bool LoadExternal;
4348 };
4349 } // namespace
4350 
4351 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4352                               VisibleDeclConsumer &Consumer,
4353                               bool IncludeGlobalScope, bool LoadExternal) {
4354   LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4355                         LoadExternal);
4356   H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4357 }
4358 
4359 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4360                               VisibleDeclConsumer &Consumer,
4361                               bool IncludeGlobalScope,
4362                               bool IncludeDependentBases, bool LoadExternal) {
4363   LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4364   H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4365 }
4366 
4367 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
4368                                      SourceLocation GnuLabelLoc) {
4369   // Do a lookup to see if we have a label with this name already.
4370   NamedDecl *Res = nullptr;
4371 
4372   if (GnuLabelLoc.isValid()) {
4373     // Local label definitions always shadow existing labels.
4374     Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4375     Scope *S = CurScope;
4376     PushOnScopeChains(Res, S, true);
4377     return cast<LabelDecl>(Res);
4378   }
4379 
4380   // Not a GNU local label.
4381   Res = LookupSingleName(CurScope, II, Loc, LookupLabel,
4382                          RedeclarationKind::NotForRedeclaration);
4383   // If we found a label, check to see if it is in the same context as us.
4384   // When in a Block, we don't want to reuse a label in an enclosing function.
4385   if (Res && Res->getDeclContext() != CurContext)
4386     Res = nullptr;
4387   if (!Res) {
4388     // If not forward referenced or defined already, create the backing decl.
4389     Res = LabelDecl::Create(Context, CurContext, Loc, II);
4390     Scope *S = CurScope->getFnParent();
4391     assert(S && "Not in a function?");
4392     PushOnScopeChains(Res, S, true);
4393   }
4394   return cast<LabelDecl>(Res);
4395 }
4396 
4397 //===----------------------------------------------------------------------===//
4398 // Typo correction
4399 //===----------------------------------------------------------------------===//
4400 
4401 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
4402                               TypoCorrection &Candidate) {
4403   Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4404   return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4405 }
4406 
4407 static void LookupPotentialTypoResult(Sema &SemaRef,
4408                                       LookupResult &Res,
4409                                       IdentifierInfo *Name,
4410                                       Scope *S, CXXScopeSpec *SS,
4411                                       DeclContext *MemberContext,
4412                                       bool EnteringContext,
4413                                       bool isObjCIvarLookup,
4414                                       bool FindHidden);
4415 
4416 /// Check whether the declarations found for a typo correction are
4417 /// visible. Set the correction's RequiresImport flag to true if none of the
4418 /// declarations are visible, false otherwise.
4419 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
4420   TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4421 
4422   for (/**/; DI != DE; ++DI)
4423     if (!LookupResult::isVisible(SemaRef, *DI))
4424       break;
4425   // No filtering needed if all decls are visible.
4426   if (DI == DE) {
4427     TC.setRequiresImport(false);
4428     return;
4429   }
4430 
4431   llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4432   bool AnyVisibleDecls = !NewDecls.empty();
4433 
4434   for (/**/; DI != DE; ++DI) {
4435     if (LookupResult::isVisible(SemaRef, *DI)) {
4436       if (!AnyVisibleDecls) {
4437         // Found a visible decl, discard all hidden ones.
4438         AnyVisibleDecls = true;
4439         NewDecls.clear();
4440       }
4441       NewDecls.push_back(*DI);
4442     } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4443       NewDecls.push_back(*DI);
4444   }
4445 
4446   if (NewDecls.empty())
4447     TC = TypoCorrection();
4448   else {
4449     TC.setCorrectionDecls(NewDecls);
4450     TC.setRequiresImport(!AnyVisibleDecls);
4451   }
4452 }
4453 
4454 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
4455 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4456 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4457 static void getNestedNameSpecifierIdentifiers(
4458     NestedNameSpecifier *NNS,
4459     SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
4460   if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4461     getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4462   else
4463     Identifiers.clear();
4464 
4465   const IdentifierInfo *II = nullptr;
4466 
4467   switch (NNS->getKind()) {
4468   case NestedNameSpecifier::Identifier:
4469     II = NNS->getAsIdentifier();
4470     break;
4471 
4472   case NestedNameSpecifier::Namespace:
4473     if (NNS->getAsNamespace()->isAnonymousNamespace())
4474       return;
4475     II = NNS->getAsNamespace()->getIdentifier();
4476     break;
4477 
4478   case NestedNameSpecifier::NamespaceAlias:
4479     II = NNS->getAsNamespaceAlias()->getIdentifier();
4480     break;
4481 
4482   case NestedNameSpecifier::TypeSpecWithTemplate:
4483   case NestedNameSpecifier::TypeSpec:
4484     II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4485     break;
4486 
4487   case NestedNameSpecifier::Global:
4488   case NestedNameSpecifier::Super:
4489     return;
4490   }
4491 
4492   if (II)
4493     Identifiers.push_back(II);
4494 }
4495 
4496 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
4497                                        DeclContext *Ctx, bool InBaseClass) {
4498   // Don't consider hidden names for typo correction.
4499   if (Hiding)
4500     return;
4501 
4502   // Only consider entities with identifiers for names, ignoring
4503   // special names (constructors, overloaded operators, selectors,
4504   // etc.).
4505   IdentifierInfo *Name = ND->getIdentifier();
4506   if (!Name)
4507     return;
4508 
4509   // Only consider visible declarations and declarations from modules with
4510   // names that exactly match.
4511   if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4512     return;
4513 
4514   FoundName(Name->getName());
4515 }
4516 
4517 void TypoCorrectionConsumer::FoundName(StringRef Name) {
4518   // Compute the edit distance between the typo and the name of this
4519   // entity, and add the identifier to the list of results.
4520   addName(Name, nullptr);
4521 }
4522 
4523 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4524   // Compute the edit distance between the typo and this keyword,
4525   // and add the keyword to the list of results.
4526   addName(Keyword, nullptr, nullptr, true);
4527 }
4528 
4529 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4530                                      NestedNameSpecifier *NNS, bool isKeyword) {
4531   // Use a simple length-based heuristic to determine the minimum possible
4532   // edit distance. If the minimum isn't good enough, bail out early.
4533   StringRef TypoStr = Typo->getName();
4534   unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4535   if (MinED && TypoStr.size() / MinED < 3)
4536     return;
4537 
4538   // Compute an upper bound on the allowable edit distance, so that the
4539   // edit-distance algorithm can short-circuit.
4540   unsigned UpperBound = (TypoStr.size() + 2) / 3;
4541   unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4542   if (ED > UpperBound) return;
4543 
4544   TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4545   if (isKeyword) TC.makeKeyword();
4546   TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4547   addCorrection(TC);
4548 }
4549 
4550 static const unsigned MaxTypoDistanceResultSets = 5;
4551 
4552 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
4553   StringRef TypoStr = Typo->getName();
4554   StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4555 
4556   // For very short typos, ignore potential corrections that have a different
4557   // base identifier from the typo or which have a normalized edit distance
4558   // longer than the typo itself.
4559   if (TypoStr.size() < 3 &&
4560       (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4561     return;
4562 
4563   // If the correction is resolved but is not viable, ignore it.
4564   if (Correction.isResolved()) {
4565     checkCorrectionVisibility(SemaRef, Correction);
4566     if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4567       return;
4568   }
4569 
4570   TypoResultList &CList =
4571       CorrectionResults[Correction.getEditDistance(false)][Name];
4572 
4573   if (!CList.empty() && !CList.back().isResolved())
4574     CList.pop_back();
4575   if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4576     auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4577       return TypoCorr.getCorrectionDecl() == NewND;
4578     });
4579     if (RI != CList.end()) {
4580       // The Correction refers to a decl already in the list. No insertion is
4581       // necessary and all further cases will return.
4582 
4583       auto IsDeprecated = [](Decl *D) {
4584         while (D) {
4585           if (D->isDeprecated())
4586             return true;
4587           D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4588         }
4589         return false;
4590       };
4591 
4592       // Prefer non deprecated Corrections over deprecated and only then
4593       // sort using an alphabetical order.
4594       std::pair<bool, std::string> NewKey = {
4595           IsDeprecated(Correction.getFoundDecl()),
4596           Correction.getAsString(SemaRef.getLangOpts())};
4597 
4598       std::pair<bool, std::string> PrevKey = {
4599           IsDeprecated(RI->getFoundDecl()),
4600           RI->getAsString(SemaRef.getLangOpts())};
4601 
4602       if (NewKey < PrevKey)
4603         *RI = Correction;
4604       return;
4605     }
4606   }
4607   if (CList.empty() || Correction.isResolved())
4608     CList.push_back(Correction);
4609 
4610   while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4611     CorrectionResults.erase(std::prev(CorrectionResults.end()));
4612 }
4613 
4614 void TypoCorrectionConsumer::addNamespaces(
4615     const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4616   SearchNamespaces = true;
4617 
4618   for (auto KNPair : KnownNamespaces)
4619     Namespaces.addNameSpecifier(KNPair.first);
4620 
4621   bool SSIsTemplate = false;
4622   if (NestedNameSpecifier *NNS =
4623           (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4624     if (const Type *T = NNS->getAsType())
4625       SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4626   }
4627   // Do not transform this into an iterator-based loop. The loop body can
4628   // trigger the creation of further types (through lazy deserialization) and
4629   // invalid iterators into this list.
4630   auto &Types = SemaRef.getASTContext().getTypes();
4631   for (unsigned I = 0; I != Types.size(); ++I) {
4632     const auto *TI = Types[I];
4633     if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4634       CD = CD->getCanonicalDecl();
4635       if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4636           !CD->isUnion() && CD->getIdentifier() &&
4637           (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4638           (CD->isBeingDefined() || CD->isCompleteDefinition()))
4639         Namespaces.addNameSpecifier(CD);
4640     }
4641   }
4642 }
4643 
4644 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4645   if (++CurrentTCIndex < ValidatedCorrections.size())
4646     return ValidatedCorrections[CurrentTCIndex];
4647 
4648   CurrentTCIndex = ValidatedCorrections.size();
4649   while (!CorrectionResults.empty()) {
4650     auto DI = CorrectionResults.begin();
4651     if (DI->second.empty()) {
4652       CorrectionResults.erase(DI);
4653       continue;
4654     }
4655 
4656     auto RI = DI->second.begin();
4657     if (RI->second.empty()) {
4658       DI->second.erase(RI);
4659       performQualifiedLookups();
4660       continue;
4661     }
4662 
4663     TypoCorrection TC = RI->second.pop_back_val();
4664     if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4665       ValidatedCorrections.push_back(TC);
4666       return ValidatedCorrections[CurrentTCIndex];
4667     }
4668   }
4669   return ValidatedCorrections[0];  // The empty correction.
4670 }
4671 
4672 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4673   IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4674   DeclContext *TempMemberContext = MemberContext;
4675   CXXScopeSpec *TempSS = SS.get();
4676 retry_lookup:
4677   LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4678                             EnteringContext,
4679                             CorrectionValidator->IsObjCIvarLookup,
4680                             Name == Typo && !Candidate.WillReplaceSpecifier());
4681   switch (Result.getResultKind()) {
4682   case LookupResult::NotFound:
4683   case LookupResult::NotFoundInCurrentInstantiation:
4684   case LookupResult::FoundUnresolvedValue:
4685     if (TempSS) {
4686       // Immediately retry the lookup without the given CXXScopeSpec
4687       TempSS = nullptr;
4688       Candidate.WillReplaceSpecifier(true);
4689       goto retry_lookup;
4690     }
4691     if (TempMemberContext) {
4692       if (SS && !TempSS)
4693         TempSS = SS.get();
4694       TempMemberContext = nullptr;
4695       goto retry_lookup;
4696     }
4697     if (SearchNamespaces)
4698       QualifiedResults.push_back(Candidate);
4699     break;
4700 
4701   case LookupResult::Ambiguous:
4702     // We don't deal with ambiguities.
4703     break;
4704 
4705   case LookupResult::Found:
4706   case LookupResult::FoundOverloaded:
4707     // Store all of the Decls for overloaded symbols
4708     for (auto *TRD : Result)
4709       Candidate.addCorrectionDecl(TRD);
4710     checkCorrectionVisibility(SemaRef, Candidate);
4711     if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4712       if (SearchNamespaces)
4713         QualifiedResults.push_back(Candidate);
4714       break;
4715     }
4716     Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4717     return true;
4718   }
4719   return false;
4720 }
4721 
4722 void TypoCorrectionConsumer::performQualifiedLookups() {
4723   unsigned TypoLen = Typo->getName().size();
4724   for (const TypoCorrection &QR : QualifiedResults) {
4725     for (const auto &NSI : Namespaces) {
4726       DeclContext *Ctx = NSI.DeclCtx;
4727       const Type *NSType = NSI.NameSpecifier->getAsType();
4728 
4729       // If the current NestedNameSpecifier refers to a class and the
4730       // current correction candidate is the name of that class, then skip
4731       // it as it is unlikely a qualified version of the class' constructor
4732       // is an appropriate correction.
4733       if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4734                                            nullptr) {
4735         if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4736           continue;
4737       }
4738 
4739       TypoCorrection TC(QR);
4740       TC.ClearCorrectionDecls();
4741       TC.setCorrectionSpecifier(NSI.NameSpecifier);
4742       TC.setQualifierDistance(NSI.EditDistance);
4743       TC.setCallbackDistance(0); // Reset the callback distance
4744 
4745       // If the current correction candidate and namespace combination are
4746       // too far away from the original typo based on the normalized edit
4747       // distance, then skip performing a qualified name lookup.
4748       unsigned TmpED = TC.getEditDistance(true);
4749       if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4750           TypoLen / TmpED < 3)
4751         continue;
4752 
4753       Result.clear();
4754       Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4755       if (!SemaRef.LookupQualifiedName(Result, Ctx))
4756         continue;
4757 
4758       // Any corrections added below will be validated in subsequent
4759       // iterations of the main while() loop over the Consumer's contents.
4760       switch (Result.getResultKind()) {
4761       case LookupResult::Found:
4762       case LookupResult::FoundOverloaded: {
4763         if (SS && SS->isValid()) {
4764           std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4765           std::string OldQualified;
4766           llvm::raw_string_ostream OldOStream(OldQualified);
4767           SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4768           OldOStream << Typo->getName();
4769           // If correction candidate would be an identical written qualified
4770           // identifier, then the existing CXXScopeSpec probably included a
4771           // typedef that didn't get accounted for properly.
4772           if (OldOStream.str() == NewQualified)
4773             break;
4774         }
4775         for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4776              TRD != TRDEnd; ++TRD) {
4777           if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4778                                         NSType ? NSType->getAsCXXRecordDecl()
4779                                                : nullptr,
4780                                         TRD.getPair()) == Sema::AR_accessible)
4781             TC.addCorrectionDecl(*TRD);
4782         }
4783         if (TC.isResolved()) {
4784           TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4785           addCorrection(TC);
4786         }
4787         break;
4788       }
4789       case LookupResult::NotFound:
4790       case LookupResult::NotFoundInCurrentInstantiation:
4791       case LookupResult::Ambiguous:
4792       case LookupResult::FoundUnresolvedValue:
4793         break;
4794       }
4795     }
4796   }
4797   QualifiedResults.clear();
4798 }
4799 
4800 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4801     ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4802     : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4803   if (NestedNameSpecifier *NNS =
4804           CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4805     llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4806     NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4807 
4808     getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4809   }
4810   // Build the list of identifiers that would be used for an absolute
4811   // (from the global context) NestedNameSpecifier referring to the current
4812   // context.
4813   for (DeclContext *C : llvm::reverse(CurContextChain)) {
4814     if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4815       CurContextIdentifiers.push_back(ND->getIdentifier());
4816   }
4817 
4818   // Add the global context as a NestedNameSpecifier
4819   SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4820                       NestedNameSpecifier::GlobalSpecifier(Context), 1};
4821   DistanceMap[1].push_back(SI);
4822 }
4823 
4824 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4825     DeclContext *Start) -> DeclContextList {
4826   assert(Start && "Building a context chain from a null context");
4827   DeclContextList Chain;
4828   for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4829        DC = DC->getLookupParent()) {
4830     NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4831     if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4832         !(ND && ND->isAnonymousNamespace()))
4833       Chain.push_back(DC->getPrimaryContext());
4834   }
4835   return Chain;
4836 }
4837 
4838 unsigned
4839 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4840     DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4841   unsigned NumSpecifiers = 0;
4842   for (DeclContext *C : llvm::reverse(DeclChain)) {
4843     if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4844       NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4845       ++NumSpecifiers;
4846     } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4847       NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4848                                         RD->getTypeForDecl());
4849       ++NumSpecifiers;
4850     }
4851   }
4852   return NumSpecifiers;
4853 }
4854 
4855 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4856     DeclContext *Ctx) {
4857   NestedNameSpecifier *NNS = nullptr;
4858   unsigned NumSpecifiers = 0;
4859   DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4860   DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4861 
4862   // Eliminate common elements from the two DeclContext chains.
4863   for (DeclContext *C : llvm::reverse(CurContextChain)) {
4864     if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4865       break;
4866     NamespaceDeclChain.pop_back();
4867   }
4868 
4869   // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4870   NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4871 
4872   // Add an explicit leading '::' specifier if needed.
4873   if (NamespaceDeclChain.empty()) {
4874     // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4875     NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4876     NumSpecifiers =
4877         buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4878   } else if (NamedDecl *ND =
4879                  dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4880     IdentifierInfo *Name = ND->getIdentifier();
4881     bool SameNameSpecifier = false;
4882     if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
4883       std::string NewNameSpecifier;
4884       llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4885       SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4886       getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4887       NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4888       SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4889     }
4890     if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
4891       // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4892       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4893       NumSpecifiers =
4894           buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4895     }
4896   }
4897 
4898   // If the built NestedNameSpecifier would be replacing an existing
4899   // NestedNameSpecifier, use the number of component identifiers that
4900   // would need to be changed as the edit distance instead of the number
4901   // of components in the built NestedNameSpecifier.
4902   if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4903     SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4904     getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4905     NumSpecifiers =
4906         llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),
4907                                   llvm::ArrayRef(NewNameSpecifierIdentifiers));
4908   }
4909 
4910   SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4911   DistanceMap[NumSpecifiers].push_back(SI);
4912 }
4913 
4914 /// Perform name lookup for a possible result for typo correction.
4915 static void LookupPotentialTypoResult(Sema &SemaRef,
4916                                       LookupResult &Res,
4917                                       IdentifierInfo *Name,
4918                                       Scope *S, CXXScopeSpec *SS,
4919                                       DeclContext *MemberContext,
4920                                       bool EnteringContext,
4921                                       bool isObjCIvarLookup,
4922                                       bool FindHidden) {
4923   Res.suppressDiagnostics();
4924   Res.clear();
4925   Res.setLookupName(Name);
4926   Res.setAllowHidden(FindHidden);
4927   if (MemberContext) {
4928     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4929       if (isObjCIvarLookup) {
4930         if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4931           Res.addDecl(Ivar);
4932           Res.resolveKind();
4933           return;
4934         }
4935       }
4936 
4937       if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4938               Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
4939         Res.addDecl(Prop);
4940         Res.resolveKind();
4941         return;
4942       }
4943     }
4944 
4945     SemaRef.LookupQualifiedName(Res, MemberContext);
4946     return;
4947   }
4948 
4949   SemaRef.LookupParsedName(Res, S, SS,
4950                            /*ObjectType=*/QualType(),
4951                            /*AllowBuiltinCreation=*/false, EnteringContext);
4952 
4953   // Fake ivar lookup; this should really be part of
4954   // LookupParsedName.
4955   if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4956     if (Method->isInstanceMethod() && Method->getClassInterface() &&
4957         (Res.empty() ||
4958          (Res.isSingleResult() &&
4959           Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4960        if (ObjCIvarDecl *IV
4961              = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4962          Res.addDecl(IV);
4963          Res.resolveKind();
4964        }
4965      }
4966   }
4967 }
4968 
4969 /// Add keywords to the consumer as possible typo corrections.
4970 static void AddKeywordsToConsumer(Sema &SemaRef,
4971                                   TypoCorrectionConsumer &Consumer,
4972                                   Scope *S, CorrectionCandidateCallback &CCC,
4973                                   bool AfterNestedNameSpecifier) {
4974   if (AfterNestedNameSpecifier) {
4975     // For 'X::', we know exactly which keywords can appear next.
4976     Consumer.addKeywordResult("template");
4977     if (CCC.WantExpressionKeywords)
4978       Consumer.addKeywordResult("operator");
4979     return;
4980   }
4981 
4982   if (CCC.WantObjCSuper)
4983     Consumer.addKeywordResult("super");
4984 
4985   if (CCC.WantTypeSpecifiers) {
4986     // Add type-specifier keywords to the set of results.
4987     static const char *const CTypeSpecs[] = {
4988       "char", "const", "double", "enum", "float", "int", "long", "short",
4989       "signed", "struct", "union", "unsigned", "void", "volatile",
4990       "_Complex",
4991       // storage-specifiers as well
4992       "extern", "inline", "static", "typedef"
4993     };
4994 
4995     for (const auto *CTS : CTypeSpecs)
4996       Consumer.addKeywordResult(CTS);
4997 
4998     if (SemaRef.getLangOpts().C99 && !SemaRef.getLangOpts().C2y)
4999       Consumer.addKeywordResult("_Imaginary");
5000 
5001     if (SemaRef.getLangOpts().C99)
5002       Consumer.addKeywordResult("restrict");
5003     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
5004       Consumer.addKeywordResult("bool");
5005     else if (SemaRef.getLangOpts().C99)
5006       Consumer.addKeywordResult("_Bool");
5007 
5008     if (SemaRef.getLangOpts().CPlusPlus) {
5009       Consumer.addKeywordResult("class");
5010       Consumer.addKeywordResult("typename");
5011       Consumer.addKeywordResult("wchar_t");
5012 
5013       if (SemaRef.getLangOpts().CPlusPlus11) {
5014         Consumer.addKeywordResult("char16_t");
5015         Consumer.addKeywordResult("char32_t");
5016         Consumer.addKeywordResult("constexpr");
5017         Consumer.addKeywordResult("decltype");
5018         Consumer.addKeywordResult("thread_local");
5019       }
5020     }
5021 
5022     if (SemaRef.getLangOpts().GNUKeywords)
5023       Consumer.addKeywordResult("typeof");
5024   } else if (CCC.WantFunctionLikeCasts) {
5025     static const char *const CastableTypeSpecs[] = {
5026       "char", "double", "float", "int", "long", "short",
5027       "signed", "unsigned", "void"
5028     };
5029     for (auto *kw : CastableTypeSpecs)
5030       Consumer.addKeywordResult(kw);
5031   }
5032 
5033   if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5034     Consumer.addKeywordResult("const_cast");
5035     Consumer.addKeywordResult("dynamic_cast");
5036     Consumer.addKeywordResult("reinterpret_cast");
5037     Consumer.addKeywordResult("static_cast");
5038   }
5039 
5040   if (CCC.WantExpressionKeywords) {
5041     Consumer.addKeywordResult("sizeof");
5042     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5043       Consumer.addKeywordResult("false");
5044       Consumer.addKeywordResult("true");
5045     }
5046 
5047     if (SemaRef.getLangOpts().CPlusPlus) {
5048       static const char *const CXXExprs[] = {
5049         "delete", "new", "operator", "throw", "typeid"
5050       };
5051       for (const auto *CE : CXXExprs)
5052         Consumer.addKeywordResult(CE);
5053 
5054       if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
5055           cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
5056         Consumer.addKeywordResult("this");
5057 
5058       if (SemaRef.getLangOpts().CPlusPlus11) {
5059         Consumer.addKeywordResult("alignof");
5060         Consumer.addKeywordResult("nullptr");
5061       }
5062     }
5063 
5064     if (SemaRef.getLangOpts().C11) {
5065       // FIXME: We should not suggest _Alignof if the alignof macro
5066       // is present.
5067       Consumer.addKeywordResult("_Alignof");
5068     }
5069   }
5070 
5071   if (CCC.WantRemainingKeywords) {
5072     if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5073       // Statements.
5074       static const char *const CStmts[] = {
5075         "do", "else", "for", "goto", "if", "return", "switch", "while" };
5076       for (const auto *CS : CStmts)
5077         Consumer.addKeywordResult(CS);
5078 
5079       if (SemaRef.getLangOpts().CPlusPlus) {
5080         Consumer.addKeywordResult("catch");
5081         Consumer.addKeywordResult("try");
5082       }
5083 
5084       if (S && S->getBreakParent())
5085         Consumer.addKeywordResult("break");
5086 
5087       if (S && S->getContinueParent())
5088         Consumer.addKeywordResult("continue");
5089 
5090       if (SemaRef.getCurFunction() &&
5091           !SemaRef.getCurFunction()->SwitchStack.empty()) {
5092         Consumer.addKeywordResult("case");
5093         Consumer.addKeywordResult("default");
5094       }
5095     } else {
5096       if (SemaRef.getLangOpts().CPlusPlus) {
5097         Consumer.addKeywordResult("namespace");
5098         Consumer.addKeywordResult("template");
5099       }
5100 
5101       if (S && S->isClassScope()) {
5102         Consumer.addKeywordResult("explicit");
5103         Consumer.addKeywordResult("friend");
5104         Consumer.addKeywordResult("mutable");
5105         Consumer.addKeywordResult("private");
5106         Consumer.addKeywordResult("protected");
5107         Consumer.addKeywordResult("public");
5108         Consumer.addKeywordResult("virtual");
5109       }
5110     }
5111 
5112     if (SemaRef.getLangOpts().CPlusPlus) {
5113       Consumer.addKeywordResult("using");
5114 
5115       if (SemaRef.getLangOpts().CPlusPlus11)
5116         Consumer.addKeywordResult("static_assert");
5117     }
5118   }
5119 }
5120 
5121 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5122     const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5123     Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5124     DeclContext *MemberContext, bool EnteringContext,
5125     const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5126 
5127   if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5128       DisableTypoCorrection)
5129     return nullptr;
5130 
5131   // In Microsoft mode, don't perform typo correction in a template member
5132   // function dependent context because it interferes with the "lookup into
5133   // dependent bases of class templates" feature.
5134   if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5135       isa<CXXMethodDecl>(CurContext))
5136     return nullptr;
5137 
5138   // We only attempt to correct typos for identifiers.
5139   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5140   if (!Typo)
5141     return nullptr;
5142 
5143   // If the scope specifier itself was invalid, don't try to correct
5144   // typos.
5145   if (SS && SS->isInvalid())
5146     return nullptr;
5147 
5148   // Never try to correct typos during any kind of code synthesis.
5149   if (!CodeSynthesisContexts.empty())
5150     return nullptr;
5151 
5152   // Don't try to correct 'super'.
5153   if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5154     return nullptr;
5155 
5156   // Abort if typo correction already failed for this specific typo.
5157   IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
5158   if (locs != TypoCorrectionFailures.end() &&
5159       locs->second.count(TypoName.getLoc()))
5160     return nullptr;
5161 
5162   // Don't try to correct the identifier "vector" when in AltiVec mode.
5163   // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5164   // remove this workaround.
5165   if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
5166     return nullptr;
5167 
5168   // Provide a stop gap for files that are just seriously broken.  Trying
5169   // to correct all typos can turn into a HUGE performance penalty, causing
5170   // some files to take minutes to get rejected by the parser.
5171   unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5172   if (Limit && TyposCorrected >= Limit)
5173     return nullptr;
5174   ++TyposCorrected;
5175 
5176   // If we're handling a missing symbol error, using modules, and the
5177   // special search all modules option is used, look for a missing import.
5178   if (ErrorRecovery && getLangOpts().Modules &&
5179       getLangOpts().ModulesSearchAll) {
5180     // The following has the side effect of loading the missing module.
5181     getModuleLoader().lookupMissingImports(Typo->getName(),
5182                                            TypoName.getBeginLoc());
5183   }
5184 
5185   // Extend the lifetime of the callback. We delayed this until here
5186   // to avoid allocations in the hot path (which is where no typo correction
5187   // occurs). Note that CorrectionCandidateCallback is polymorphic and
5188   // initially stack-allocated.
5189   std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5190   auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5191       *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5192       EnteringContext);
5193 
5194   // Perform name lookup to find visible, similarly-named entities.
5195   bool IsUnqualifiedLookup = false;
5196   DeclContext *QualifiedDC = MemberContext;
5197   if (MemberContext) {
5198     LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
5199 
5200     // Look in qualified interfaces.
5201     if (OPT) {
5202       for (auto *I : OPT->quals())
5203         LookupVisibleDecls(I, LookupKind, *Consumer);
5204     }
5205   } else if (SS && SS->isSet()) {
5206     QualifiedDC = computeDeclContext(*SS, EnteringContext);
5207     if (!QualifiedDC)
5208       return nullptr;
5209 
5210     LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
5211   } else {
5212     IsUnqualifiedLookup = true;
5213   }
5214 
5215   // Determine whether we are going to search in the various namespaces for
5216   // corrections.
5217   bool SearchNamespaces
5218     = getLangOpts().CPlusPlus &&
5219       (IsUnqualifiedLookup || (SS && SS->isSet()));
5220 
5221   if (IsUnqualifiedLookup || SearchNamespaces) {
5222     // For unqualified lookup, look through all of the names that we have
5223     // seen in this translation unit.
5224     // FIXME: Re-add the ability to skip very unlikely potential corrections.
5225     for (const auto &I : Context.Idents)
5226       Consumer->FoundName(I.getKey());
5227 
5228     // Walk through identifiers in external identifier sources.
5229     // FIXME: Re-add the ability to skip very unlikely potential corrections.
5230     if (IdentifierInfoLookup *External
5231                             = Context.Idents.getExternalIdentifierLookup()) {
5232       std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5233       do {
5234         StringRef Name = Iter->Next();
5235         if (Name.empty())
5236           break;
5237 
5238         Consumer->FoundName(Name);
5239       } while (true);
5240     }
5241   }
5242 
5243   AddKeywordsToConsumer(*this, *Consumer, S,
5244                         *Consumer->getCorrectionValidator(),
5245                         SS && SS->isNotEmpty());
5246 
5247   // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5248   // to search those namespaces.
5249   if (SearchNamespaces) {
5250     // Load any externally-known namespaces.
5251     if (ExternalSource && !LoadedExternalKnownNamespaces) {
5252       SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5253       LoadedExternalKnownNamespaces = true;
5254       ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5255       for (auto *N : ExternalKnownNamespaces)
5256         KnownNamespaces[N] = true;
5257     }
5258 
5259     Consumer->addNamespaces(KnownNamespaces);
5260   }
5261 
5262   return Consumer;
5263 }
5264 
5265 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
5266                                  Sema::LookupNameKind LookupKind,
5267                                  Scope *S, CXXScopeSpec *SS,
5268                                  CorrectionCandidateCallback &CCC,
5269                                  CorrectTypoKind Mode,
5270                                  DeclContext *MemberContext,
5271                                  bool EnteringContext,
5272                                  const ObjCObjectPointerType *OPT,
5273                                  bool RecordFailure) {
5274   // Always let the ExternalSource have the first chance at correction, even
5275   // if we would otherwise have given up.
5276   if (ExternalSource) {
5277     if (TypoCorrection Correction =
5278             ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5279                                         MemberContext, EnteringContext, OPT))
5280       return Correction;
5281   }
5282 
5283   // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5284   // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5285   // some instances of CTC_Unknown, while WantRemainingKeywords is true
5286   // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5287   bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5288 
5289   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5290   auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5291                                              MemberContext, EnteringContext,
5292                                              OPT, Mode == CTK_ErrorRecovery);
5293 
5294   if (!Consumer)
5295     return TypoCorrection();
5296 
5297   // If we haven't found anything, we're done.
5298   if (Consumer->empty())
5299     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5300 
5301   // Make sure the best edit distance (prior to adding any namespace qualifiers)
5302   // is not more that about a third of the length of the typo's identifier.
5303   unsigned ED = Consumer->getBestEditDistance(true);
5304   unsigned TypoLen = Typo->getName().size();
5305   if (ED > 0 && TypoLen / ED < 3)
5306     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5307 
5308   TypoCorrection BestTC = Consumer->getNextCorrection();
5309   TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5310   if (!BestTC)
5311     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5312 
5313   ED = BestTC.getEditDistance();
5314 
5315   if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5316     // If this was an unqualified lookup and we believe the callback
5317     // object wouldn't have filtered out possible corrections, note
5318     // that no correction was found.
5319     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5320   }
5321 
5322   // If only a single name remains, return that result.
5323   if (!SecondBestTC ||
5324       SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5325     const TypoCorrection &Result = BestTC;
5326 
5327     // Don't correct to a keyword that's the same as the typo; the keyword
5328     // wasn't actually in scope.
5329     if (ED == 0 && Result.isKeyword())
5330       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5331 
5332     TypoCorrection TC = Result;
5333     TC.setCorrectionRange(SS, TypoName);
5334     checkCorrectionVisibility(*this, TC);
5335     return TC;
5336   } else if (SecondBestTC && ObjCMessageReceiver) {
5337     // Prefer 'super' when we're completing in a message-receiver
5338     // context.
5339 
5340     if (BestTC.getCorrection().getAsString() != "super") {
5341       if (SecondBestTC.getCorrection().getAsString() == "super")
5342         BestTC = SecondBestTC;
5343       else if ((*Consumer)["super"].front().isKeyword())
5344         BestTC = (*Consumer)["super"].front();
5345     }
5346     // Don't correct to a keyword that's the same as the typo; the keyword
5347     // wasn't actually in scope.
5348     if (BestTC.getEditDistance() == 0 ||
5349         BestTC.getCorrection().getAsString() != "super")
5350       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5351 
5352     BestTC.setCorrectionRange(SS, TypoName);
5353     return BestTC;
5354   }
5355 
5356   // Record the failure's location if needed and return an empty correction. If
5357   // this was an unqualified lookup and we believe the callback object did not
5358   // filter out possible corrections, also cache the failure for the typo.
5359   return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5360 }
5361 
5362 TypoExpr *Sema::CorrectTypoDelayed(
5363     const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5364     Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5365     TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
5366     DeclContext *MemberContext, bool EnteringContext,
5367     const ObjCObjectPointerType *OPT) {
5368   auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5369                                              MemberContext, EnteringContext,
5370                                              OPT, Mode == CTK_ErrorRecovery);
5371 
5372   // Give the external sema source a chance to correct the typo.
5373   TypoCorrection ExternalTypo;
5374   if (ExternalSource && Consumer) {
5375     ExternalTypo = ExternalSource->CorrectTypo(
5376         TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5377         MemberContext, EnteringContext, OPT);
5378     if (ExternalTypo)
5379       Consumer->addCorrection(ExternalTypo);
5380   }
5381 
5382   if (!Consumer || Consumer->empty())
5383     return nullptr;
5384 
5385   // Make sure the best edit distance (prior to adding any namespace qualifiers)
5386   // is not more that about a third of the length of the typo's identifier.
5387   unsigned ED = Consumer->getBestEditDistance(true);
5388   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5389   if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
5390     return nullptr;
5391   ExprEvalContexts.back().NumTypos++;
5392   return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
5393                            TypoName.getLoc());
5394 }
5395 
5396 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5397   if (!CDecl) return;
5398 
5399   if (isKeyword())
5400     CorrectionDecls.clear();
5401 
5402   CorrectionDecls.push_back(CDecl);
5403 
5404   if (!CorrectionName)
5405     CorrectionName = CDecl->getDeclName();
5406 }
5407 
5408 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5409   if (CorrectionNameSpec) {
5410     std::string tmpBuffer;
5411     llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5412     CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
5413     PrefixOStream << CorrectionName;
5414     return PrefixOStream.str();
5415   }
5416 
5417   return CorrectionName.getAsString();
5418 }
5419 
5420 bool CorrectionCandidateCallback::ValidateCandidate(
5421     const TypoCorrection &candidate) {
5422   if (!candidate.isResolved())
5423     return true;
5424 
5425   if (candidate.isKeyword())
5426     return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5427            WantRemainingKeywords || WantObjCSuper;
5428 
5429   bool HasNonType = false;
5430   bool HasStaticMethod = false;
5431   bool HasNonStaticMethod = false;
5432   for (Decl *D : candidate) {
5433     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5434       D = FTD->getTemplatedDecl();
5435     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5436       if (Method->isStatic())
5437         HasStaticMethod = true;
5438       else
5439         HasNonStaticMethod = true;
5440     }
5441     if (!isa<TypeDecl>(D))
5442       HasNonType = true;
5443   }
5444 
5445   if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5446       !candidate.getCorrectionSpecifier())
5447     return false;
5448 
5449   return WantTypeSpecifiers || HasNonType;
5450 }
5451 
5452 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
5453                                              bool HasExplicitTemplateArgs,
5454                                              MemberExpr *ME)
5455     : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5456       CurContext(SemaRef.CurContext), MemberFn(ME) {
5457   WantTypeSpecifiers = false;
5458   WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5459                           !HasExplicitTemplateArgs && NumArgs == 1;
5460   WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5461   WantRemainingKeywords = false;
5462 }
5463 
5464 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5465   if (!candidate.getCorrectionDecl())
5466     return candidate.isKeyword();
5467 
5468   for (auto *C : candidate) {
5469     FunctionDecl *FD = nullptr;
5470     NamedDecl *ND = C->getUnderlyingDecl();
5471     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5472       FD = FTD->getTemplatedDecl();
5473     if (!HasExplicitTemplateArgs && !FD) {
5474       if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5475         // If the Decl is neither a function nor a template function,
5476         // determine if it is a pointer or reference to a function. If so,
5477         // check against the number of arguments expected for the pointee.
5478         QualType ValType = cast<ValueDecl>(ND)->getType();
5479         if (ValType.isNull())
5480           continue;
5481         if (ValType->isAnyPointerType() || ValType->isReferenceType())
5482           ValType = ValType->getPointeeType();
5483         if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5484           if (FPT->getNumParams() == NumArgs)
5485             return true;
5486       }
5487     }
5488 
5489     // A typo for a function-style cast can look like a function call in C++.
5490     if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5491                                  : isa<TypeDecl>(ND)) &&
5492         CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5493       // Only a class or class template can take two or more arguments.
5494       return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5495 
5496     // Skip the current candidate if it is not a FunctionDecl or does not accept
5497     // the current number of arguments.
5498     if (!FD || !(FD->getNumParams() >= NumArgs &&
5499                  FD->getMinRequiredArguments() <= NumArgs))
5500       continue;
5501 
5502     // If the current candidate is a non-static C++ method, skip the candidate
5503     // unless the method being corrected--or the current DeclContext, if the
5504     // function being corrected is not a method--is a method in the same class
5505     // or a descendent class of the candidate's parent class.
5506     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
5507       if (MemberFn || !MD->isStatic()) {
5508         const auto *CurMD =
5509             MemberFn
5510                 ? dyn_cast_if_present<CXXMethodDecl>(MemberFn->getMemberDecl())
5511                 : dyn_cast_if_present<CXXMethodDecl>(CurContext);
5512         const CXXRecordDecl *CurRD =
5513             CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5514         const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5515         if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5516           continue;
5517       }
5518     }
5519     return true;
5520   }
5521   return false;
5522 }
5523 
5524 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5525                         const PartialDiagnostic &TypoDiag,
5526                         bool ErrorRecovery) {
5527   diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5528                ErrorRecovery);
5529 }
5530 
5531 /// Find which declaration we should import to provide the definition of
5532 /// the given declaration.
5533 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
5534   if (const auto *VD = dyn_cast<VarDecl>(D))
5535     return VD->getDefinition();
5536   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5537     return FD->getDefinition();
5538   if (const auto *TD = dyn_cast<TagDecl>(D))
5539     return TD->getDefinition();
5540   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
5541     return ID->getDefinition();
5542   if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))
5543     return PD->getDefinition();
5544   if (const auto *TD = dyn_cast<TemplateDecl>(D))
5545     if (const NamedDecl *TTD = TD->getTemplatedDecl())
5546       return getDefinitionToImport(TTD);
5547   return nullptr;
5548 }
5549 
5550 void Sema::diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
5551                                  MissingImportKind MIK, bool Recover) {
5552   // Suggest importing a module providing the definition of this entity, if
5553   // possible.
5554   const NamedDecl *Def = getDefinitionToImport(Decl);
5555   if (!Def)
5556     Def = Decl;
5557 
5558   Module *Owner = getOwningModule(Def);
5559   assert(Owner && "definition of hidden declaration is not in a module");
5560 
5561   llvm::SmallVector<Module*, 8> OwningModules;
5562   OwningModules.push_back(Owner);
5563   auto Merged = Context.getModulesWithMergedDefinition(Def);
5564   OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5565 
5566   diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5567                         Recover);
5568 }
5569 
5570 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5571 /// suggesting the addition of a #include of the specified file.
5572 static std::string getHeaderNameForHeader(Preprocessor &PP, FileEntryRef E,
5573                                           llvm::StringRef IncludingFile) {
5574   bool IsAngled = false;
5575   auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5576       E, IncludingFile, &IsAngled);
5577   return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');
5578 }
5579 
5580 void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl,
5581                                  SourceLocation DeclLoc,
5582                                  ArrayRef<Module *> Modules,
5583                                  MissingImportKind MIK, bool Recover) {
5584   assert(!Modules.empty());
5585 
5586   // See https://github.com/llvm/llvm-project/issues/73893. It is generally
5587   // confusing than helpful to show the namespace is not visible.
5588   if (isa<NamespaceDecl>(Decl))
5589     return;
5590 
5591   auto NotePrevious = [&] {
5592     // FIXME: Suppress the note backtrace even under
5593     // -fdiagnostics-show-note-include-stack. We don't care how this
5594     // declaration was previously reached.
5595     Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5596   };
5597 
5598   // Weed out duplicates from module list.
5599   llvm::SmallVector<Module*, 8> UniqueModules;
5600   llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5601   for (auto *M : Modules) {
5602     if (M->isExplicitGlobalModule() || M->isPrivateModule())
5603       continue;
5604     if (UniqueModuleSet.insert(M).second)
5605       UniqueModules.push_back(M);
5606   }
5607 
5608   // Try to find a suitable header-name to #include.
5609   std::string HeaderName;
5610   if (OptionalFileEntryRef Header =
5611           PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5612     if (const FileEntry *FE =
5613             SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5614       HeaderName =
5615           getHeaderNameForHeader(PP, *Header, FE->tryGetRealPathName());
5616   }
5617 
5618   // If we have a #include we should suggest, or if all definition locations
5619   // were in global module fragments, don't suggest an import.
5620   if (!HeaderName.empty() || UniqueModules.empty()) {
5621     // FIXME: Find a smart place to suggest inserting a #include, and add
5622     // a FixItHint there.
5623     Diag(UseLoc, diag::err_module_unimported_use_header)
5624         << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5625     // Produce a note showing where the entity was declared.
5626     NotePrevious();
5627     if (Recover)
5628       createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5629     return;
5630   }
5631 
5632   Modules = UniqueModules;
5633 
5634   auto GetModuleNameForDiagnostic = [this](const Module *M) -> std::string {
5635     if (M->isModuleMapModule())
5636       return M->getFullModuleName();
5637 
5638     if (M->isImplicitGlobalModule())
5639       M = M->getTopLevelModule();
5640 
5641     // If the current module unit is in the same module with M, it is OK to show
5642     // the partition name. Otherwise, it'll be sufficient to show the primary
5643     // module name.
5644     if (getASTContext().isInSameModule(M, getCurrentModule()))
5645       return M->getTopLevelModuleName().str();
5646     else
5647       return M->getPrimaryModuleInterfaceName().str();
5648   };
5649 
5650   if (Modules.size() > 1) {
5651     std::string ModuleList;
5652     unsigned N = 0;
5653     for (const auto *M : Modules) {
5654       ModuleList += "\n        ";
5655       if (++N == 5 && N != Modules.size()) {
5656         ModuleList += "[...]";
5657         break;
5658       }
5659       ModuleList += GetModuleNameForDiagnostic(M);
5660     }
5661 
5662     Diag(UseLoc, diag::err_module_unimported_use_multiple)
5663       << (int)MIK << Decl << ModuleList;
5664   } else {
5665     // FIXME: Add a FixItHint that imports the corresponding module.
5666     Diag(UseLoc, diag::err_module_unimported_use)
5667         << (int)MIK << Decl << GetModuleNameForDiagnostic(Modules[0]);
5668   }
5669 
5670   NotePrevious();
5671 
5672   // Try to recover by implicitly importing this module.
5673   if (Recover)
5674     createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5675 }
5676 
5677 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5678                         const PartialDiagnostic &TypoDiag,
5679                         const PartialDiagnostic &PrevNote,
5680                         bool ErrorRecovery) {
5681   std::string CorrectedStr = Correction.getAsString(getLangOpts());
5682   std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5683   FixItHint FixTypo = FixItHint::CreateReplacement(
5684       Correction.getCorrectionRange(), CorrectedStr);
5685 
5686   // Maybe we're just missing a module import.
5687   if (Correction.requiresImport()) {
5688     NamedDecl *Decl = Correction.getFoundDecl();
5689     assert(Decl && "import required but no declaration to import");
5690 
5691     diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5692                           MissingImportKind::Declaration, ErrorRecovery);
5693     return;
5694   }
5695 
5696   Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5697     << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5698 
5699   NamedDecl *ChosenDecl =
5700       Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5701 
5702   // For builtin functions which aren't declared anywhere in source,
5703   // don't emit the "declared here" note.
5704   if (const auto *FD = dyn_cast_if_present<FunctionDecl>(ChosenDecl);
5705       FD && FD->getBuiltinID() &&
5706       PrevNote.getDiagID() == diag::note_previous_decl &&
5707       Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {
5708     ChosenDecl = nullptr;
5709   }
5710 
5711   if (PrevNote.getDiagID() && ChosenDecl)
5712     Diag(ChosenDecl->getLocation(), PrevNote)
5713       << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5714 
5715   // Add any extra diagnostics.
5716   for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5717     Diag(Correction.getCorrectionRange().getBegin(), PD);
5718 }
5719 
5720 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5721                                   TypoDiagnosticGenerator TDG,
5722                                   TypoRecoveryCallback TRC,
5723                                   SourceLocation TypoLoc) {
5724   assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5725   auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
5726   auto &State = DelayedTypos[TE];
5727   State.Consumer = std::move(TCC);
5728   State.DiagHandler = std::move(TDG);
5729   State.RecoveryHandler = std::move(TRC);
5730   if (TE)
5731     TypoExprs.push_back(TE);
5732   return TE;
5733 }
5734 
5735 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5736   auto Entry = DelayedTypos.find(TE);
5737   assert(Entry != DelayedTypos.end() &&
5738          "Failed to get the state for a TypoExpr!");
5739   return Entry->second;
5740 }
5741 
5742 void Sema::clearDelayedTypo(TypoExpr *TE) {
5743   DelayedTypos.erase(TE);
5744 }
5745 
5746 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5747   DeclarationNameInfo Name(II, IILoc);
5748   LookupResult R(*this, Name, LookupAnyName,
5749                  RedeclarationKind::NotForRedeclaration);
5750   R.suppressDiagnostics();
5751   R.setHideTags(false);
5752   LookupName(R, S);
5753   R.dump();
5754 }
5755 
5756 void Sema::ActOnPragmaDump(Expr *E) {
5757   E->dump();
5758 }
5759 
5760 RedeclarationKind Sema::forRedeclarationInCurContext() const {
5761   // A declaration with an owning module for linkage can never link against
5762   // anything that is not visible. We don't need to check linkage here; if
5763   // the context has internal linkage, redeclaration lookup won't find things
5764   // from other TUs, and we can't safely compute linkage yet in general.
5765   if (cast<Decl>(CurContext)->getOwningModuleForLinkage())
5766     return RedeclarationKind::ForVisibleRedeclaration;
5767   return RedeclarationKind::ForExternalRedeclaration;
5768 }
5769