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