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