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   while (D) {
1619     auto &DefaultArg = D->getDefaultArgStorage();
1620     if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
1621       return true;
1622 
1623     if (!DefaultArg.isInherited() && Modules) {
1624       auto *NonConstD = const_cast<ParmDecl*>(D);
1625       Modules->push_back(S.getOwningModule(NonConstD));
1626     }
1627 
1628     // If there was a previous default argument, maybe its parameter is visible.
1629     D = DefaultArg.getInheritedFrom();
1630   }
1631   return false;
1632 }
1633 
1634 bool Sema::hasAcceptableDefaultArgument(
1635     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,
1636     Sema::AcceptableKind Kind) {
1637   if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1638     return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1639 
1640   if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1641     return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1642 
1643   return ::hasAcceptableDefaultArgument(
1644       *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
1645 }
1646 
1647 bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1648                                      llvm::SmallVectorImpl<Module *> *Modules) {
1649   return hasAcceptableDefaultArgument(D, Modules,
1650                                       Sema::AcceptableKind::Visible);
1651 }
1652 
1653 bool Sema::hasReachableDefaultArgument(
1654     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1655   return hasAcceptableDefaultArgument(D, Modules,
1656                                       Sema::AcceptableKind::Reachable);
1657 }
1658 
1659 template <typename Filter>
1660 static bool
1661 hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,
1662                              llvm::SmallVectorImpl<Module *> *Modules, Filter F,
1663                              Sema::AcceptableKind Kind) {
1664   bool HasFilteredRedecls = false;
1665 
1666   for (auto *Redecl : D->redecls()) {
1667     auto *R = cast<NamedDecl>(Redecl);
1668     if (!F(R))
1669       continue;
1670 
1671     if (S.isAcceptable(R, Kind))
1672       return true;
1673 
1674     HasFilteredRedecls = true;
1675 
1676     if (Modules)
1677       Modules->push_back(R->getOwningModule());
1678   }
1679 
1680   // Only return false if there is at least one redecl that is not filtered out.
1681   if (HasFilteredRedecls)
1682     return false;
1683 
1684   return true;
1685 }
1686 
1687 static bool
1688 hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,
1689                                     llvm::SmallVectorImpl<Module *> *Modules,
1690                                     Sema::AcceptableKind Kind) {
1691   return hasAcceptableDeclarationImpl(
1692       S, D, Modules,
1693       [](const NamedDecl *D) {
1694         if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1695           return RD->getTemplateSpecializationKind() ==
1696                  TSK_ExplicitSpecialization;
1697         if (auto *FD = dyn_cast<FunctionDecl>(D))
1698           return FD->getTemplateSpecializationKind() ==
1699                  TSK_ExplicitSpecialization;
1700         if (auto *VD = dyn_cast<VarDecl>(D))
1701           return VD->getTemplateSpecializationKind() ==
1702                  TSK_ExplicitSpecialization;
1703         llvm_unreachable("unknown explicit specialization kind");
1704       },
1705       Kind);
1706 }
1707 
1708 bool Sema::hasVisibleExplicitSpecialization(
1709     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1710   return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1711                                                Sema::AcceptableKind::Visible);
1712 }
1713 
1714 bool Sema::hasReachableExplicitSpecialization(
1715     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1716   return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1717                                                Sema::AcceptableKind::Reachable);
1718 }
1719 
1720 static bool
1721 hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,
1722                                   llvm::SmallVectorImpl<Module *> *Modules,
1723                                   Sema::AcceptableKind Kind) {
1724   assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1725          "not a member specialization");
1726   return hasAcceptableDeclarationImpl(
1727       S, D, Modules,
1728       [](const NamedDecl *D) {
1729         // If the specialization is declared at namespace scope, then it's a
1730         // member specialization declaration. If it's lexically inside the class
1731         // definition then it was instantiated.
1732         //
1733         // FIXME: This is a hack. There should be a better way to determine
1734         // this.
1735         // FIXME: What about MS-style explicit specializations declared within a
1736         //        class definition?
1737         return D->getLexicalDeclContext()->isFileContext();
1738       },
1739       Kind);
1740 }
1741 
1742 bool Sema::hasVisibleMemberSpecialization(
1743     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1744   return hasAcceptableMemberSpecialization(*this, D, Modules,
1745                                            Sema::AcceptableKind::Visible);
1746 }
1747 
1748 bool Sema::hasReachableMemberSpecialization(
1749     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1750   return hasAcceptableMemberSpecialization(*this, D, Modules,
1751                                            Sema::AcceptableKind::Reachable);
1752 }
1753 
1754 /// Determine whether a declaration is acceptable to name lookup.
1755 ///
1756 /// This routine determines whether the declaration D is acceptable in the
1757 /// current lookup context, taking into account the current template
1758 /// instantiation stack. During template instantiation, a declaration is
1759 /// acceptable if it is acceptable from a module containing any entity on the
1760 /// template instantiation path (by instantiating a template, you allow it to
1761 /// see the declarations that your module can see, including those later on in
1762 /// your module).
1763 bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
1764                                     Sema::AcceptableKind Kind) {
1765   assert(!D->isUnconditionallyVisible() &&
1766          "should not call this: not in slow case");
1767 
1768   Module *DeclModule = SemaRef.getOwningModule(D);
1769   assert(DeclModule && "hidden decl has no owning module");
1770 
1771   // If the owning module is visible, the decl is acceptable.
1772   if (SemaRef.isModuleVisible(DeclModule,
1773                               D->isInvisibleOutsideTheOwningModule()))
1774     return true;
1775 
1776   // Determine whether a decl context is a file context for the purpose of
1777   // visibility/reachability. This looks through some (export and linkage spec)
1778   // transparent contexts, but not others (enums).
1779   auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1780     return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1781            isa<ExportDecl>(DC);
1782   };
1783 
1784   // If this declaration is not at namespace scope
1785   // then it is acceptable if its lexical parent has a acceptable definition.
1786   DeclContext *DC = D->getLexicalDeclContext();
1787   if (DC && !IsEffectivelyFileContext(DC)) {
1788     // For a parameter, check whether our current template declaration's
1789     // lexical context is acceptable, not whether there's some other acceptable
1790     // definition of it, because parameters aren't "within" the definition.
1791     //
1792     // In C++ we need to check for a acceptable definition due to ODR merging,
1793     // and in C we must not because each declaration of a function gets its own
1794     // set of declarations for tags in prototype scope.
1795     bool AcceptableWithinParent;
1796     if (D->isTemplateParameter()) {
1797       bool SearchDefinitions = true;
1798       if (const auto *DCD = dyn_cast<Decl>(DC)) {
1799         if (const auto *TD = DCD->getDescribedTemplate()) {
1800           TemplateParameterList *TPL = TD->getTemplateParameters();
1801           auto Index = getDepthAndIndex(D).second;
1802           SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1803         }
1804       }
1805       if (SearchDefinitions)
1806         AcceptableWithinParent =
1807             SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1808       else
1809         AcceptableWithinParent =
1810             isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1811     } else if (isa<ParmVarDecl>(D) ||
1812                (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1813       AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1814     else if (D->isModulePrivate()) {
1815       // A module-private declaration is only acceptable if an enclosing lexical
1816       // parent was merged with another definition in the current module.
1817       AcceptableWithinParent = false;
1818       do {
1819         if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1820           AcceptableWithinParent = true;
1821           break;
1822         }
1823         DC = DC->getLexicalParent();
1824       } while (!IsEffectivelyFileContext(DC));
1825     } else {
1826       AcceptableWithinParent =
1827           SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1828     }
1829 
1830     if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1831         Kind == Sema::AcceptableKind::Visible &&
1832         // FIXME: Do something better in this case.
1833         !SemaRef.getLangOpts().ModulesLocalVisibility) {
1834       // Cache the fact that this declaration is implicitly visible because
1835       // its parent has a visible definition.
1836       D->setVisibleDespiteOwningModule();
1837     }
1838     return AcceptableWithinParent;
1839   }
1840 
1841   if (Kind == Sema::AcceptableKind::Visible)
1842     return false;
1843 
1844   assert(Kind == Sema::AcceptableKind::Reachable &&
1845          "Additional Sema::AcceptableKind?");
1846   return isReachableSlow(SemaRef, D);
1847 }
1848 
1849 bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1850   // [module.global.frag]p2:
1851   // A global-module-fragment specifies the contents of the global module
1852   // fragment for a module unit. The global module fragment can be used to
1853   // provide declarations that are attached to the global module and usable
1854   // within the module unit.
1855   //
1856   // Global module fragment is special. Global Module fragment is only usable
1857   // within the module unit it got defined [module.global.frag]p2. So here we
1858   // check if the Module is the global module fragment in current translation
1859   // unit.
1860   if (M->isGlobalModule() && M != this->GlobalModuleFragment)
1861     return false;
1862 
1863   // The module might be ordinarily visible. For a module-private query, that
1864   // means it is part of the current module.
1865   if (ModulePrivate && isUsableModule(M))
1866     return true;
1867 
1868   // For a query which is not module-private, that means it is in our visible
1869   // module set.
1870   if (!ModulePrivate && VisibleModules.isVisible(M))
1871     return true;
1872 
1873   // Otherwise, it might be visible by virtue of the query being within a
1874   // template instantiation or similar that is permitted to look inside M.
1875 
1876   // Find the extra places where we need to look.
1877   const auto &LookupModules = getLookupModules();
1878   if (LookupModules.empty())
1879     return false;
1880 
1881   // If our lookup set contains the module, it's visible.
1882   if (LookupModules.count(M))
1883     return true;
1884 
1885   // For a module-private query, that's everywhere we get to look.
1886   if (ModulePrivate)
1887     return false;
1888 
1889   // Check whether M is transitively exported to an import of the lookup set.
1890   return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1891     return LookupM->isModuleVisible(M);
1892   });
1893 }
1894 
1895 // FIXME: Return false directly if we don't have an interface dependency on the
1896 // translation unit containing D.
1897 bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
1898   assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
1899 
1900   Module *DeclModule = SemaRef.getOwningModule(D);
1901   assert(DeclModule && "hidden decl has no owning module");
1902 
1903   // Entities in module map modules are reachable only if they're visible.
1904   if (DeclModule->isModuleMapModule())
1905     return false;
1906 
1907   // If D comes from a module and SemaRef doesn't own a module, it implies D
1908   // comes from another TU. In case SemaRef owns a module, we could judge if D
1909   // comes from another TU by comparing the module unit.
1910   //
1911   // FIXME: It would look better if we have direct method to judge whether D is
1912   // in another TU.
1913   if (SemaRef.getCurrentModule() &&
1914       SemaRef.getCurrentModule()->getTopLevelModule() ==
1915           DeclModule->getTopLevelModule())
1916     return true;
1917 
1918   // [module.reach]/p3:
1919   // A declaration D is reachable from a point P if:
1920   // ...
1921   // - D is not discarded ([module.global.frag]), appears in a translation unit
1922   //   that is reachable from P, and does not appear within a private module
1923   //   fragment.
1924   //
1925   // A declaration that's discarded in the GMF should be module-private.
1926   if (D->isModulePrivate())
1927     return false;
1928 
1929   // [module.reach]/p1
1930   //   A translation unit U is necessarily reachable from a point P if U is a
1931   //   module interface unit on which the translation unit containing P has an
1932   //   interface dependency, or the translation unit containing P imports U, in
1933   //   either case prior to P ([module.import]).
1934   //
1935   // [module.import]/p10
1936   //   A translation unit has an interface dependency on a translation unit U if
1937   //   it contains a declaration (possibly a module-declaration) that imports U
1938   //   or if it has an interface dependency on a translation unit that has an
1939   //   interface dependency on U.
1940   //
1941   // So we could conclude the module unit U is necessarily reachable if:
1942   // (1) The module unit U is module interface unit.
1943   // (2) The current unit has an interface dependency on the module unit U.
1944   //
1945   // Here we only check for the first condition. Since we couldn't see
1946   // DeclModule if it isn't (transitively) imported.
1947   if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit())
1948     return true;
1949 
1950   // [module.reach]/p2
1951   //   Additional translation units on
1952   //   which the point within the program has an interface dependency may be
1953   //   considered reachable, but it is unspecified which are and under what
1954   //   circumstances.
1955   //
1956   // The decision here is to treat all additional tranditional units as
1957   // unreachable.
1958   return false;
1959 }
1960 
1961 bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
1962   return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);
1963 }
1964 
1965 bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1966   // FIXME: If there are both visible and hidden declarations, we need to take
1967   // into account whether redeclaration is possible. Example:
1968   //
1969   // Non-imported module:
1970   //   int f(T);        // #1
1971   // Some TU:
1972   //   static int f(U); // #2, not a redeclaration of #1
1973   //   int f(T);        // #3, finds both, should link with #1 if T != U, but
1974   //                    // with #2 if T == U; neither should be ambiguous.
1975   for (auto *D : R) {
1976     if (isVisible(D))
1977       return true;
1978     assert(D->isExternallyDeclarable() &&
1979            "should not have hidden, non-externally-declarable result here");
1980   }
1981 
1982   // This function is called once "New" is essentially complete, but before a
1983   // previous declaration is attached. We can't query the linkage of "New" in
1984   // general, because attaching the previous declaration can change the
1985   // linkage of New to match the previous declaration.
1986   //
1987   // However, because we've just determined that there is no *visible* prior
1988   // declaration, we can compute the linkage here. There are two possibilities:
1989   //
1990   //  * This is not a redeclaration; it's safe to compute the linkage now.
1991   //
1992   //  * This is a redeclaration of a prior declaration that is externally
1993   //    redeclarable. In that case, the linkage of the declaration is not
1994   //    changed by attaching the prior declaration, because both are externally
1995   //    declarable (and thus ExternalLinkage or VisibleNoLinkage).
1996   //
1997   // FIXME: This is subtle and fragile.
1998   return New->isExternallyDeclarable();
1999 }
2000 
2001 /// Retrieve the visible declaration corresponding to D, if any.
2002 ///
2003 /// This routine determines whether the declaration D is visible in the current
2004 /// module, with the current imports. If not, it checks whether any
2005 /// redeclaration of D is visible, and if so, returns that declaration.
2006 ///
2007 /// \returns D, or a visible previous declaration of D, whichever is more recent
2008 /// and visible. If no declaration of D is visible, returns null.
2009 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
2010                                      unsigned IDNS) {
2011   assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
2012 
2013   for (auto RD : D->redecls()) {
2014     // Don't bother with extra checks if we already know this one isn't visible.
2015     if (RD == D)
2016       continue;
2017 
2018     auto ND = cast<NamedDecl>(RD);
2019     // FIXME: This is wrong in the case where the previous declaration is not
2020     // visible in the same scope as D. This needs to be done much more
2021     // carefully.
2022     if (ND->isInIdentifierNamespace(IDNS) &&
2023         LookupResult::isAvailableForLookup(SemaRef, ND))
2024       return ND;
2025   }
2026 
2027   return nullptr;
2028 }
2029 
2030 bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
2031                                      llvm::SmallVectorImpl<Module *> *Modules) {
2032   assert(!isVisible(D) && "not in slow case");
2033   return hasAcceptableDeclarationImpl(
2034       *this, D, Modules, [](const NamedDecl *) { return true; },
2035       Sema::AcceptableKind::Visible);
2036 }
2037 
2038 bool Sema::hasReachableDeclarationSlow(
2039     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
2040   assert(!isReachable(D) && "not in slow case");
2041   return hasAcceptableDeclarationImpl(
2042       *this, D, Modules, [](const NamedDecl *) { return true; },
2043       Sema::AcceptableKind::Reachable);
2044 }
2045 
2046 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
2047   if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
2048     // Namespaces are a bit of a special case: we expect there to be a lot of
2049     // redeclarations of some namespaces, all declarations of a namespace are
2050     // essentially interchangeable, all declarations are found by name lookup
2051     // if any is, and namespaces are never looked up during template
2052     // instantiation. So we benefit from caching the check in this case, and
2053     // it is correct to do so.
2054     auto *Key = ND->getCanonicalDecl();
2055     if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
2056       return Acceptable;
2057     auto *Acceptable = isVisible(getSema(), Key)
2058                            ? Key
2059                            : findAcceptableDecl(getSema(), Key, IDNS);
2060     if (Acceptable)
2061       getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
2062     return Acceptable;
2063   }
2064 
2065   return findAcceptableDecl(getSema(), D, IDNS);
2066 }
2067 
2068 bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) {
2069   // If this declaration is already visible, return it directly.
2070   if (D->isUnconditionallyVisible())
2071     return true;
2072 
2073   // During template instantiation, we can refer to hidden declarations, if
2074   // they were visible in any module along the path of instantiation.
2075   return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);
2076 }
2077 
2078 bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) {
2079   if (D->isUnconditionallyVisible())
2080     return true;
2081 
2082   return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);
2083 }
2084 
2085 bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) {
2086   // We should check the visibility at the callsite already.
2087   if (isVisible(SemaRef, ND))
2088     return true;
2089 
2090   auto *DC = ND->getDeclContext();
2091   // If ND is not visible and it is at namespace scope, it shouldn't be found
2092   // by name lookup.
2093   if (DC->isFileContext())
2094     return false;
2095 
2096   // [module.interface]p7
2097   // Class and enumeration member names can be found by name lookup in any
2098   // context in which a definition of the type is reachable.
2099   //
2100   // FIXME: The current implementation didn't consider about scope. For example,
2101   // ```
2102   // // m.cppm
2103   // export module m;
2104   // enum E1 { e1 };
2105   // // Use.cpp
2106   // import m;
2107   // void test() {
2108   //   auto a = E1::e1; // Error as expected.
2109   //   auto b = e1; // Should be error. namespace-scope name e1 is not visible
2110   // }
2111   // ```
2112   // For the above example, the current implementation would emit error for `a`
2113   // correctly. However, the implementation wouldn't diagnose about `b` now.
2114   // Since we only check the reachability for the parent only.
2115   // See clang/test/CXX/module/module.interface/p7.cpp for example.
2116   if (auto *TD = dyn_cast<TagDecl>(DC))
2117     return SemaRef.hasReachableDefinition(TD);
2118 
2119   return false;
2120 }
2121 
2122 /// Perform unqualified name lookup starting from a given
2123 /// scope.
2124 ///
2125 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
2126 /// used to find names within the current scope. For example, 'x' in
2127 /// @code
2128 /// int x;
2129 /// int f() {
2130 ///   return x; // unqualified name look finds 'x' in the global scope
2131 /// }
2132 /// @endcode
2133 ///
2134 /// Different lookup criteria can find different names. For example, a
2135 /// particular scope can have both a struct and a function of the same
2136 /// name, and each can be found by certain lookup criteria. For more
2137 /// information about lookup criteria, see the documentation for the
2138 /// class LookupCriteria.
2139 ///
2140 /// @param S        The scope from which unqualified name lookup will
2141 /// begin. If the lookup criteria permits, name lookup may also search
2142 /// in the parent scopes.
2143 ///
2144 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
2145 /// look up and the lookup kind), and is updated with the results of lookup
2146 /// including zero or more declarations and possibly additional information
2147 /// used to diagnose ambiguities.
2148 ///
2149 /// @returns \c true if lookup succeeded and false otherwise.
2150 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
2151                       bool ForceNoCPlusPlus) {
2152   DeclarationName Name = R.getLookupName();
2153   if (!Name) return false;
2154 
2155   LookupNameKind NameKind = R.getLookupKind();
2156 
2157   if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
2158     // Unqualified name lookup in C/Objective-C is purely lexical, so
2159     // search in the declarations attached to the name.
2160     if (NameKind == Sema::LookupRedeclarationWithLinkage) {
2161       // Find the nearest non-transparent declaration scope.
2162       while (!(S->getFlags() & Scope::DeclScope) ||
2163              (S->getEntity() && S->getEntity()->isTransparentContext()))
2164         S = S->getParent();
2165     }
2166 
2167     // When performing a scope lookup, we want to find local extern decls.
2168     FindLocalExternScope FindLocals(R);
2169 
2170     // Scan up the scope chain looking for a decl that matches this
2171     // identifier that is in the appropriate namespace.  This search
2172     // should not take long, as shadowing of names is uncommon, and
2173     // deep shadowing is extremely uncommon.
2174     bool LeftStartingScope = false;
2175 
2176     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2177                                    IEnd = IdResolver.end();
2178          I != IEnd; ++I)
2179       if (NamedDecl *D = R.getAcceptableDecl(*I)) {
2180         if (NameKind == LookupRedeclarationWithLinkage) {
2181           // Determine whether this (or a previous) declaration is
2182           // out-of-scope.
2183           if (!LeftStartingScope && !S->isDeclScope(*I))
2184             LeftStartingScope = true;
2185 
2186           // If we found something outside of our starting scope that
2187           // does not have linkage, skip it.
2188           if (LeftStartingScope && !((*I)->hasLinkage())) {
2189             R.setShadowed();
2190             continue;
2191           }
2192         }
2193         else if (NameKind == LookupObjCImplicitSelfParam &&
2194                  !isa<ImplicitParamDecl>(*I))
2195           continue;
2196 
2197         R.addDecl(D);
2198 
2199         // Check whether there are any other declarations with the same name
2200         // and in the same scope.
2201         if (I != IEnd) {
2202           // Find the scope in which this declaration was declared (if it
2203           // actually exists in a Scope).
2204           while (S && !S->isDeclScope(D))
2205             S = S->getParent();
2206 
2207           // If the scope containing the declaration is the translation unit,
2208           // then we'll need to perform our checks based on the matching
2209           // DeclContexts rather than matching scopes.
2210           if (S && isNamespaceOrTranslationUnitScope(S))
2211             S = nullptr;
2212 
2213           // Compute the DeclContext, if we need it.
2214           DeclContext *DC = nullptr;
2215           if (!S)
2216             DC = (*I)->getDeclContext()->getRedeclContext();
2217 
2218           IdentifierResolver::iterator LastI = I;
2219           for (++LastI; LastI != IEnd; ++LastI) {
2220             if (S) {
2221               // Match based on scope.
2222               if (!S->isDeclScope(*LastI))
2223                 break;
2224             } else {
2225               // Match based on DeclContext.
2226               DeclContext *LastDC
2227                 = (*LastI)->getDeclContext()->getRedeclContext();
2228               if (!LastDC->Equals(DC))
2229                 break;
2230             }
2231 
2232             // If the declaration is in the right namespace and visible, add it.
2233             if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
2234               R.addDecl(LastD);
2235           }
2236 
2237           R.resolveKind();
2238         }
2239 
2240         return true;
2241       }
2242   } else {
2243     // Perform C++ unqualified name lookup.
2244     if (CppLookupName(R, S))
2245       return true;
2246   }
2247 
2248   // If we didn't find a use of this identifier, and if the identifier
2249   // corresponds to a compiler builtin, create the decl object for the builtin
2250   // now, injecting it into translation unit scope, and return it.
2251   if (AllowBuiltinCreation && LookupBuiltin(R))
2252     return true;
2253 
2254   // If we didn't find a use of this identifier, the ExternalSource
2255   // may be able to handle the situation.
2256   // Note: some lookup failures are expected!
2257   // See e.g. R.isForRedeclaration().
2258   return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2259 }
2260 
2261 /// Perform qualified name lookup in the namespaces nominated by
2262 /// using directives by the given context.
2263 ///
2264 /// C++98 [namespace.qual]p2:
2265 ///   Given X::m (where X is a user-declared namespace), or given \::m
2266 ///   (where X is the global namespace), let S be the set of all
2267 ///   declarations of m in X and in the transitive closure of all
2268 ///   namespaces nominated by using-directives in X and its used
2269 ///   namespaces, except that using-directives are ignored in any
2270 ///   namespace, including X, directly containing one or more
2271 ///   declarations of m. No namespace is searched more than once in
2272 ///   the lookup of a name. If S is the empty set, the program is
2273 ///   ill-formed. Otherwise, if S has exactly one member, or if the
2274 ///   context of the reference is a using-declaration
2275 ///   (namespace.udecl), S is the required set of declarations of
2276 ///   m. Otherwise if the use of m is not one that allows a unique
2277 ///   declaration to be chosen from S, the program is ill-formed.
2278 ///
2279 /// C++98 [namespace.qual]p5:
2280 ///   During the lookup of a qualified namespace member name, if the
2281 ///   lookup finds more than one declaration of the member, and if one
2282 ///   declaration introduces a class name or enumeration name and the
2283 ///   other declarations either introduce the same object, the same
2284 ///   enumerator or a set of functions, the non-type name hides the
2285 ///   class or enumeration name if and only if the declarations are
2286 ///   from the same namespace; otherwise (the declarations are from
2287 ///   different namespaces), the program is ill-formed.
2288 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
2289                                                  DeclContext *StartDC) {
2290   assert(StartDC->isFileContext() && "start context is not a file context");
2291 
2292   // We have not yet looked into these namespaces, much less added
2293   // their "using-children" to the queue.
2294   SmallVector<NamespaceDecl*, 8> Queue;
2295 
2296   // We have at least added all these contexts to the queue.
2297   llvm::SmallPtrSet<DeclContext*, 8> Visited;
2298   Visited.insert(StartDC);
2299 
2300   // We have already looked into the initial namespace; seed the queue
2301   // with its using-children.
2302   for (auto *I : StartDC->using_directives()) {
2303     NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
2304     if (S.isVisible(I) && Visited.insert(ND).second)
2305       Queue.push_back(ND);
2306   }
2307 
2308   // The easiest way to implement the restriction in [namespace.qual]p5
2309   // is to check whether any of the individual results found a tag
2310   // and, if so, to declare an ambiguity if the final result is not
2311   // a tag.
2312   bool FoundTag = false;
2313   bool FoundNonTag = false;
2314 
2315   LookupResult LocalR(LookupResult::Temporary, R);
2316 
2317   bool Found = false;
2318   while (!Queue.empty()) {
2319     NamespaceDecl *ND = Queue.pop_back_val();
2320 
2321     // We go through some convolutions here to avoid copying results
2322     // between LookupResults.
2323     bool UseLocal = !R.empty();
2324     LookupResult &DirectR = UseLocal ? LocalR : R;
2325     bool FoundDirect = LookupDirect(S, DirectR, ND);
2326 
2327     if (FoundDirect) {
2328       // First do any local hiding.
2329       DirectR.resolveKind();
2330 
2331       // If the local result is a tag, remember that.
2332       if (DirectR.isSingleTagDecl())
2333         FoundTag = true;
2334       else
2335         FoundNonTag = true;
2336 
2337       // Append the local results to the total results if necessary.
2338       if (UseLocal) {
2339         R.addAllDecls(LocalR);
2340         LocalR.clear();
2341       }
2342     }
2343 
2344     // If we find names in this namespace, ignore its using directives.
2345     if (FoundDirect) {
2346       Found = true;
2347       continue;
2348     }
2349 
2350     for (auto I : ND->using_directives()) {
2351       NamespaceDecl *Nom = I->getNominatedNamespace();
2352       if (S.isVisible(I) && Visited.insert(Nom).second)
2353         Queue.push_back(Nom);
2354     }
2355   }
2356 
2357   if (Found) {
2358     if (FoundTag && FoundNonTag)
2359       R.setAmbiguousQualifiedTagHiding();
2360     else
2361       R.resolveKind();
2362   }
2363 
2364   return Found;
2365 }
2366 
2367 /// Perform qualified name lookup into a given context.
2368 ///
2369 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2370 /// names when the context of those names is explicit specified, e.g.,
2371 /// "std::vector" or "x->member", or as part of unqualified name lookup.
2372 ///
2373 /// Different lookup criteria can find different names. For example, a
2374 /// particular scope can have both a struct and a function of the same
2375 /// name, and each can be found by certain lookup criteria. For more
2376 /// information about lookup criteria, see the documentation for the
2377 /// class LookupCriteria.
2378 ///
2379 /// \param R captures both the lookup criteria and any lookup results found.
2380 ///
2381 /// \param LookupCtx The context in which qualified name lookup will
2382 /// search. If the lookup criteria permits, name lookup may also search
2383 /// in the parent contexts or (for C++ classes) base classes.
2384 ///
2385 /// \param InUnqualifiedLookup true if this is qualified name lookup that
2386 /// occurs as part of unqualified name lookup.
2387 ///
2388 /// \returns true if lookup succeeded, false if it failed.
2389 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2390                                bool InUnqualifiedLookup) {
2391   assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2392 
2393   if (!R.getLookupName())
2394     return false;
2395 
2396   // Make sure that the declaration context is complete.
2397   assert((!isa<TagDecl>(LookupCtx) ||
2398           LookupCtx->isDependentContext() ||
2399           cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2400           cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2401          "Declaration context must already be complete!");
2402 
2403   struct QualifiedLookupInScope {
2404     bool oldVal;
2405     DeclContext *Context;
2406     // Set flag in DeclContext informing debugger that we're looking for qualified name
2407     QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2408       oldVal = ctx->setUseQualifiedLookup();
2409     }
2410     ~QualifiedLookupInScope() {
2411       Context->setUseQualifiedLookup(oldVal);
2412     }
2413   } QL(LookupCtx);
2414 
2415   if (LookupDirect(*this, R, LookupCtx)) {
2416     R.resolveKind();
2417     if (isa<CXXRecordDecl>(LookupCtx))
2418       R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2419     return true;
2420   }
2421 
2422   // Don't descend into implied contexts for redeclarations.
2423   // C++98 [namespace.qual]p6:
2424   //   In a declaration for a namespace member in which the
2425   //   declarator-id is a qualified-id, given that the qualified-id
2426   //   for the namespace member has the form
2427   //     nested-name-specifier unqualified-id
2428   //   the unqualified-id shall name a member of the namespace
2429   //   designated by the nested-name-specifier.
2430   // See also [class.mfct]p5 and [class.static.data]p2.
2431   if (R.isForRedeclaration())
2432     return false;
2433 
2434   // If this is a namespace, look it up in the implied namespaces.
2435   if (LookupCtx->isFileContext())
2436     return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2437 
2438   // If this isn't a C++ class, we aren't allowed to look into base
2439   // classes, we're done.
2440   CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2441   if (!LookupRec || !LookupRec->getDefinition())
2442     return false;
2443 
2444   // We're done for lookups that can never succeed for C++ classes.
2445   if (R.getLookupKind() == LookupOperatorName ||
2446       R.getLookupKind() == LookupNamespaceName ||
2447       R.getLookupKind() == LookupObjCProtocolName ||
2448       R.getLookupKind() == LookupLabel)
2449     return false;
2450 
2451   // If we're performing qualified name lookup into a dependent class,
2452   // then we are actually looking into a current instantiation. If we have any
2453   // dependent base classes, then we either have to delay lookup until
2454   // template instantiation time (at which point all bases will be available)
2455   // or we have to fail.
2456   if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2457       LookupRec->hasAnyDependentBases()) {
2458     R.setNotFoundInCurrentInstantiation();
2459     return false;
2460   }
2461 
2462   // Perform lookup into our base classes.
2463 
2464   DeclarationName Name = R.getLookupName();
2465   unsigned IDNS = R.getIdentifierNamespace();
2466 
2467   // Look for this member in our base classes.
2468   auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2469                                    CXXBasePath &Path) -> bool {
2470     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2471     // Drop leading non-matching lookup results from the declaration list so
2472     // we don't need to consider them again below.
2473     for (Path.Decls = BaseRecord->lookup(Name).begin();
2474          Path.Decls != Path.Decls.end(); ++Path.Decls) {
2475       if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2476         return true;
2477     }
2478     return false;
2479   };
2480 
2481   CXXBasePaths Paths;
2482   Paths.setOrigin(LookupRec);
2483   if (!LookupRec->lookupInBases(BaseCallback, Paths))
2484     return false;
2485 
2486   R.setNamingClass(LookupRec);
2487 
2488   // C++ [class.member.lookup]p2:
2489   //   [...] If the resulting set of declarations are not all from
2490   //   sub-objects of the same type, or the set has a nonstatic member
2491   //   and includes members from distinct sub-objects, there is an
2492   //   ambiguity and the program is ill-formed. Otherwise that set is
2493   //   the result of the lookup.
2494   QualType SubobjectType;
2495   int SubobjectNumber = 0;
2496   AccessSpecifier SubobjectAccess = AS_none;
2497 
2498   // Check whether the given lookup result contains only static members.
2499   auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2500     for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2501       if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2502         return false;
2503     return true;
2504   };
2505 
2506   bool TemplateNameLookup = R.isTemplateNameLookup();
2507 
2508   // Determine whether two sets of members contain the same members, as
2509   // required by C++ [class.member.lookup]p6.
2510   auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2511                                  DeclContext::lookup_iterator B) {
2512     using Iterator = DeclContextLookupResult::iterator;
2513     using Result = const void *;
2514 
2515     auto Next = [&](Iterator &It, Iterator End) -> Result {
2516       while (It != End) {
2517         NamedDecl *ND = *It++;
2518         if (!ND->isInIdentifierNamespace(IDNS))
2519           continue;
2520 
2521         // C++ [temp.local]p3:
2522         //   A lookup that finds an injected-class-name (10.2) can result in
2523         //   an ambiguity in certain cases (for example, if it is found in
2524         //   more than one base class). If all of the injected-class-names
2525         //   that are found refer to specializations of the same class
2526         //   template, and if the name is used as a template-name, the
2527         //   reference refers to the class template itself and not a
2528         //   specialization thereof, and is not ambiguous.
2529         if (TemplateNameLookup)
2530           if (auto *TD = getAsTemplateNameDecl(ND))
2531             ND = TD;
2532 
2533         // C++ [class.member.lookup]p3:
2534         //   type declarations (including injected-class-names) are replaced by
2535         //   the types they designate
2536         if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
2537           QualType T = Context.getTypeDeclType(TD);
2538           return T.getCanonicalType().getAsOpaquePtr();
2539         }
2540 
2541         return ND->getUnderlyingDecl()->getCanonicalDecl();
2542       }
2543       return nullptr;
2544     };
2545 
2546     // We'll often find the declarations are in the same order. Handle this
2547     // case (and the special case of only one declaration) efficiently.
2548     Iterator AIt = A, BIt = B, AEnd, BEnd;
2549     while (true) {
2550       Result AResult = Next(AIt, AEnd);
2551       Result BResult = Next(BIt, BEnd);
2552       if (!AResult && !BResult)
2553         return true;
2554       if (!AResult || !BResult)
2555         return false;
2556       if (AResult != BResult) {
2557         // Found a mismatch; carefully check both lists, accounting for the
2558         // possibility of declarations appearing more than once.
2559         llvm::SmallDenseMap<Result, bool, 32> AResults;
2560         for (; AResult; AResult = Next(AIt, AEnd))
2561           AResults.insert({AResult, /*FoundInB*/false});
2562         unsigned Found = 0;
2563         for (; BResult; BResult = Next(BIt, BEnd)) {
2564           auto It = AResults.find(BResult);
2565           if (It == AResults.end())
2566             return false;
2567           if (!It->second) {
2568             It->second = true;
2569             ++Found;
2570           }
2571         }
2572         return AResults.size() == Found;
2573       }
2574     }
2575   };
2576 
2577   for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2578        Path != PathEnd; ++Path) {
2579     const CXXBasePathElement &PathElement = Path->back();
2580 
2581     // Pick the best (i.e. most permissive i.e. numerically lowest) access
2582     // across all paths.
2583     SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2584 
2585     // Determine whether we're looking at a distinct sub-object or not.
2586     if (SubobjectType.isNull()) {
2587       // This is the first subobject we've looked at. Record its type.
2588       SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2589       SubobjectNumber = PathElement.SubobjectNumber;
2590       continue;
2591     }
2592 
2593     if (SubobjectType !=
2594         Context.getCanonicalType(PathElement.Base->getType())) {
2595       // We found members of the given name in two subobjects of
2596       // different types. If the declaration sets aren't the same, this
2597       // lookup is ambiguous.
2598       //
2599       // FIXME: The language rule says that this applies irrespective of
2600       // whether the sets contain only static members.
2601       if (HasOnlyStaticMembers(Path->Decls) &&
2602           HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2603         continue;
2604 
2605       R.setAmbiguousBaseSubobjectTypes(Paths);
2606       return true;
2607     }
2608 
2609     // FIXME: This language rule no longer exists. Checking for ambiguous base
2610     // subobjects should be done as part of formation of a class member access
2611     // expression (when converting the object parameter to the member's type).
2612     if (SubobjectNumber != PathElement.SubobjectNumber) {
2613       // We have a different subobject of the same type.
2614 
2615       // C++ [class.member.lookup]p5:
2616       //   A static member, a nested type or an enumerator defined in
2617       //   a base class T can unambiguously be found even if an object
2618       //   has more than one base class subobject of type T.
2619       if (HasOnlyStaticMembers(Path->Decls))
2620         continue;
2621 
2622       // We have found a nonstatic member name in multiple, distinct
2623       // subobjects. Name lookup is ambiguous.
2624       R.setAmbiguousBaseSubobjects(Paths);
2625       return true;
2626     }
2627   }
2628 
2629   // Lookup in a base class succeeded; return these results.
2630 
2631   for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2632        I != E; ++I) {
2633     AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2634                                                     (*I)->getAccess());
2635     if (NamedDecl *ND = R.getAcceptableDecl(*I))
2636       R.addDecl(ND, AS);
2637   }
2638   R.resolveKind();
2639   return true;
2640 }
2641 
2642 /// Performs qualified name lookup or special type of lookup for
2643 /// "__super::" scope specifier.
2644 ///
2645 /// This routine is a convenience overload meant to be called from contexts
2646 /// that need to perform a qualified name lookup with an optional C++ scope
2647 /// specifier that might require special kind of lookup.
2648 ///
2649 /// \param R captures both the lookup criteria and any lookup results found.
2650 ///
2651 /// \param LookupCtx The context in which qualified name lookup will
2652 /// search.
2653 ///
2654 /// \param SS An optional C++ scope-specifier.
2655 ///
2656 /// \returns true if lookup succeeded, false if it failed.
2657 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2658                                CXXScopeSpec &SS) {
2659   auto *NNS = SS.getScopeRep();
2660   if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2661     return LookupInSuper(R, NNS->getAsRecordDecl());
2662   else
2663 
2664     return LookupQualifiedName(R, LookupCtx);
2665 }
2666 
2667 /// Performs name lookup for a name that was parsed in the
2668 /// source code, and may contain a C++ scope specifier.
2669 ///
2670 /// This routine is a convenience routine meant to be called from
2671 /// contexts that receive a name and an optional C++ scope specifier
2672 /// (e.g., "N::M::x"). It will then perform either qualified or
2673 /// unqualified name lookup (with LookupQualifiedName or LookupName,
2674 /// respectively) on the given name and return those results. It will
2675 /// perform a special type of lookup for "__super::" scope specifier.
2676 ///
2677 /// @param S        The scope from which unqualified name lookup will
2678 /// begin.
2679 ///
2680 /// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
2681 ///
2682 /// @param EnteringContext Indicates whether we are going to enter the
2683 /// context of the scope-specifier SS (if present).
2684 ///
2685 /// @returns True if any decls were found (but possibly ambiguous)
2686 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2687                             bool AllowBuiltinCreation, bool EnteringContext) {
2688   if (SS && SS->isInvalid()) {
2689     // When the scope specifier is invalid, don't even look for
2690     // anything.
2691     return false;
2692   }
2693 
2694   if (SS && SS->isSet()) {
2695     NestedNameSpecifier *NNS = SS->getScopeRep();
2696     if (NNS->getKind() == NestedNameSpecifier::Super)
2697       return LookupInSuper(R, NNS->getAsRecordDecl());
2698 
2699     if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2700       // We have resolved the scope specifier to a particular declaration
2701       // contex, and will perform name lookup in that context.
2702       if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2703         return false;
2704 
2705       R.setContextRange(SS->getRange());
2706       return LookupQualifiedName(R, DC);
2707     }
2708 
2709     // We could not resolve the scope specified to a specific declaration
2710     // context, which means that SS refers to an unknown specialization.
2711     // Name lookup can't find anything in this case.
2712     R.setNotFoundInCurrentInstantiation();
2713     R.setContextRange(SS->getRange());
2714     return false;
2715   }
2716 
2717   // Perform unqualified name lookup starting in the given scope.
2718   return LookupName(R, S, AllowBuiltinCreation);
2719 }
2720 
2721 /// Perform qualified name lookup into all base classes of the given
2722 /// class.
2723 ///
2724 /// \param R captures both the lookup criteria and any lookup results found.
2725 ///
2726 /// \param Class The context in which qualified name lookup will
2727 /// search. Name lookup will search in all base classes merging the results.
2728 ///
2729 /// @returns True if any decls were found (but possibly ambiguous)
2730 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2731   // The access-control rules we use here are essentially the rules for
2732   // doing a lookup in Class that just magically skipped the direct
2733   // members of Class itself.  That is, the naming class is Class, and the
2734   // access includes the access of the base.
2735   for (const auto &BaseSpec : Class->bases()) {
2736     CXXRecordDecl *RD = cast<CXXRecordDecl>(
2737         BaseSpec.getType()->castAs<RecordType>()->getDecl());
2738     LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2739     Result.setBaseObjectType(Context.getRecordType(Class));
2740     LookupQualifiedName(Result, RD);
2741 
2742     // Copy the lookup results into the target, merging the base's access into
2743     // the path access.
2744     for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2745       R.addDecl(I.getDecl(),
2746                 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2747                                            I.getAccess()));
2748     }
2749 
2750     Result.suppressDiagnostics();
2751   }
2752 
2753   R.resolveKind();
2754   R.setNamingClass(Class);
2755 
2756   return !R.empty();
2757 }
2758 
2759 /// Produce a diagnostic describing the ambiguity that resulted
2760 /// from name lookup.
2761 ///
2762 /// \param Result The result of the ambiguous lookup to be diagnosed.
2763 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2764   assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2765 
2766   DeclarationName Name = Result.getLookupName();
2767   SourceLocation NameLoc = Result.getNameLoc();
2768   SourceRange LookupRange = Result.getContextRange();
2769 
2770   switch (Result.getAmbiguityKind()) {
2771   case LookupResult::AmbiguousBaseSubobjects: {
2772     CXXBasePaths *Paths = Result.getBasePaths();
2773     QualType SubobjectType = Paths->front().back().Base->getType();
2774     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2775       << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2776       << LookupRange;
2777 
2778     DeclContext::lookup_iterator Found = Paths->front().Decls;
2779     while (isa<CXXMethodDecl>(*Found) &&
2780            cast<CXXMethodDecl>(*Found)->isStatic())
2781       ++Found;
2782 
2783     Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2784     break;
2785   }
2786 
2787   case LookupResult::AmbiguousBaseSubobjectTypes: {
2788     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2789       << Name << LookupRange;
2790 
2791     CXXBasePaths *Paths = Result.getBasePaths();
2792     std::set<const NamedDecl *> DeclsPrinted;
2793     for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2794                                       PathEnd = Paths->end();
2795          Path != PathEnd; ++Path) {
2796       const NamedDecl *D = *Path->Decls;
2797       if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2798         continue;
2799       if (DeclsPrinted.insert(D).second) {
2800         if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2801           Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2802               << TD->getUnderlyingType();
2803         else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2804           Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2805               << Context.getTypeDeclType(TD);
2806         else
2807           Diag(D->getLocation(), diag::note_ambiguous_member_found);
2808       }
2809     }
2810     break;
2811   }
2812 
2813   case LookupResult::AmbiguousTagHiding: {
2814     Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2815 
2816     llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2817 
2818     for (auto *D : Result)
2819       if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2820         TagDecls.insert(TD);
2821         Diag(TD->getLocation(), diag::note_hidden_tag);
2822       }
2823 
2824     for (auto *D : Result)
2825       if (!isa<TagDecl>(D))
2826         Diag(D->getLocation(), diag::note_hiding_object);
2827 
2828     // For recovery purposes, go ahead and implement the hiding.
2829     LookupResult::Filter F = Result.makeFilter();
2830     while (F.hasNext()) {
2831       if (TagDecls.count(F.next()))
2832         F.erase();
2833     }
2834     F.done();
2835     break;
2836   }
2837 
2838   case LookupResult::AmbiguousReference: {
2839     Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2840 
2841     for (auto *D : Result)
2842       Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2843     break;
2844   }
2845   }
2846 }
2847 
2848 namespace {
2849   struct AssociatedLookup {
2850     AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2851                      Sema::AssociatedNamespaceSet &Namespaces,
2852                      Sema::AssociatedClassSet &Classes)
2853       : S(S), Namespaces(Namespaces), Classes(Classes),
2854         InstantiationLoc(InstantiationLoc) {
2855     }
2856 
2857     bool addClassTransitive(CXXRecordDecl *RD) {
2858       Classes.insert(RD);
2859       return ClassesTransitive.insert(RD);
2860     }
2861 
2862     Sema &S;
2863     Sema::AssociatedNamespaceSet &Namespaces;
2864     Sema::AssociatedClassSet &Classes;
2865     SourceLocation InstantiationLoc;
2866 
2867   private:
2868     Sema::AssociatedClassSet ClassesTransitive;
2869   };
2870 } // end anonymous namespace
2871 
2872 static void
2873 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2874 
2875 // Given the declaration context \param Ctx of a class, class template or
2876 // enumeration, add the associated namespaces to \param Namespaces as described
2877 // in [basic.lookup.argdep]p2.
2878 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2879                                       DeclContext *Ctx) {
2880   // The exact wording has been changed in C++14 as a result of
2881   // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2882   // to all language versions since it is possible to return a local type
2883   // from a lambda in C++11.
2884   //
2885   // C++14 [basic.lookup.argdep]p2:
2886   //   If T is a class type [...]. Its associated namespaces are the innermost
2887   //   enclosing namespaces of its associated classes. [...]
2888   //
2889   //   If T is an enumeration type, its associated namespace is the innermost
2890   //   enclosing namespace of its declaration. [...]
2891 
2892   // We additionally skip inline namespaces. The innermost non-inline namespace
2893   // contains all names of all its nested inline namespaces anyway, so we can
2894   // replace the entire inline namespace tree with its root.
2895   while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2896     Ctx = Ctx->getParent();
2897 
2898   Namespaces.insert(Ctx->getPrimaryContext());
2899 }
2900 
2901 // Add the associated classes and namespaces for argument-dependent
2902 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2903 static void
2904 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2905                                   const TemplateArgument &Arg) {
2906   // C++ [basic.lookup.argdep]p2, last bullet:
2907   //   -- [...] ;
2908   switch (Arg.getKind()) {
2909     case TemplateArgument::Null:
2910       break;
2911 
2912     case TemplateArgument::Type:
2913       // [...] the namespaces and classes associated with the types of the
2914       // template arguments provided for template type parameters (excluding
2915       // template template parameters)
2916       addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2917       break;
2918 
2919     case TemplateArgument::Template:
2920     case TemplateArgument::TemplateExpansion: {
2921       // [...] the namespaces in which any template template arguments are
2922       // defined; and the classes in which any member templates used as
2923       // template template arguments are defined.
2924       TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2925       if (ClassTemplateDecl *ClassTemplate
2926                  = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2927         DeclContext *Ctx = ClassTemplate->getDeclContext();
2928         if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2929           Result.Classes.insert(EnclosingClass);
2930         // Add the associated namespace for this class.
2931         CollectEnclosingNamespace(Result.Namespaces, Ctx);
2932       }
2933       break;
2934     }
2935 
2936     case TemplateArgument::Declaration:
2937     case TemplateArgument::Integral:
2938     case TemplateArgument::Expression:
2939     case TemplateArgument::NullPtr:
2940       // [Note: non-type template arguments do not contribute to the set of
2941       //  associated namespaces. ]
2942       break;
2943 
2944     case TemplateArgument::Pack:
2945       for (const auto &P : Arg.pack_elements())
2946         addAssociatedClassesAndNamespaces(Result, P);
2947       break;
2948   }
2949 }
2950 
2951 // Add the associated classes and namespaces for argument-dependent lookup
2952 // with an argument of class type (C++ [basic.lookup.argdep]p2).
2953 static void
2954 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2955                                   CXXRecordDecl *Class) {
2956 
2957   // Just silently ignore anything whose name is __va_list_tag.
2958   if (Class->getDeclName() == Result.S.VAListTagName)
2959     return;
2960 
2961   // C++ [basic.lookup.argdep]p2:
2962   //   [...]
2963   //     -- If T is a class type (including unions), its associated
2964   //        classes are: the class itself; the class of which it is a
2965   //        member, if any; and its direct and indirect base classes.
2966   //        Its associated namespaces are the innermost enclosing
2967   //        namespaces of its associated classes.
2968 
2969   // Add the class of which it is a member, if any.
2970   DeclContext *Ctx = Class->getDeclContext();
2971   if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2972     Result.Classes.insert(EnclosingClass);
2973 
2974   // Add the associated namespace for this class.
2975   CollectEnclosingNamespace(Result.Namespaces, Ctx);
2976 
2977   // -- If T is a template-id, its associated namespaces and classes are
2978   //    the namespace in which the template is defined; for member
2979   //    templates, the member template's class; the namespaces and classes
2980   //    associated with the types of the template arguments provided for
2981   //    template type parameters (excluding template template parameters); the
2982   //    namespaces in which any template template arguments are defined; and
2983   //    the classes in which any member templates used as template template
2984   //    arguments are defined. [Note: non-type template arguments do not
2985   //    contribute to the set of associated namespaces. ]
2986   if (ClassTemplateSpecializationDecl *Spec
2987         = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2988     DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2989     if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2990       Result.Classes.insert(EnclosingClass);
2991     // Add the associated namespace for this class.
2992     CollectEnclosingNamespace(Result.Namespaces, Ctx);
2993 
2994     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2995     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2996       addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2997   }
2998 
2999   // Add the class itself. If we've already transitively visited this class,
3000   // we don't need to visit base classes.
3001   if (!Result.addClassTransitive(Class))
3002     return;
3003 
3004   // Only recurse into base classes for complete types.
3005   if (!Result.S.isCompleteType(Result.InstantiationLoc,
3006                                Result.S.Context.getRecordType(Class)))
3007     return;
3008 
3009   // Add direct and indirect base classes along with their associated
3010   // namespaces.
3011   SmallVector<CXXRecordDecl *, 32> Bases;
3012   Bases.push_back(Class);
3013   while (!Bases.empty()) {
3014     // Pop this class off the stack.
3015     Class = Bases.pop_back_val();
3016 
3017     // Visit the base classes.
3018     for (const auto &Base : Class->bases()) {
3019       const RecordType *BaseType = Base.getType()->getAs<RecordType>();
3020       // In dependent contexts, we do ADL twice, and the first time around,
3021       // the base type might be a dependent TemplateSpecializationType, or a
3022       // TemplateTypeParmType. If that happens, simply ignore it.
3023       // FIXME: If we want to support export, we probably need to add the
3024       // namespace of the template in a TemplateSpecializationType, or even
3025       // the classes and namespaces of known non-dependent arguments.
3026       if (!BaseType)
3027         continue;
3028       CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3029       if (Result.addClassTransitive(BaseDecl)) {
3030         // Find the associated namespace for this base class.
3031         DeclContext *BaseCtx = BaseDecl->getDeclContext();
3032         CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
3033 
3034         // Make sure we visit the bases of this base class.
3035         if (BaseDecl->bases_begin() != BaseDecl->bases_end())
3036           Bases.push_back(BaseDecl);
3037       }
3038     }
3039   }
3040 }
3041 
3042 // Add the associated classes and namespaces for
3043 // argument-dependent lookup with an argument of type T
3044 // (C++ [basic.lookup.koenig]p2).
3045 static void
3046 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
3047   // C++ [basic.lookup.koenig]p2:
3048   //
3049   //   For each argument type T in the function call, there is a set
3050   //   of zero or more associated namespaces and a set of zero or more
3051   //   associated classes to be considered. The sets of namespaces and
3052   //   classes is determined entirely by the types of the function
3053   //   arguments (and the namespace of any template template
3054   //   argument). Typedef names and using-declarations used to specify
3055   //   the types do not contribute to this set. The sets of namespaces
3056   //   and classes are determined in the following way:
3057 
3058   SmallVector<const Type *, 16> Queue;
3059   const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
3060 
3061   while (true) {
3062     switch (T->getTypeClass()) {
3063 
3064 #define TYPE(Class, Base)
3065 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3066 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3067 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3068 #define ABSTRACT_TYPE(Class, Base)
3069 #include "clang/AST/TypeNodes.inc"
3070       // T is canonical.  We can also ignore dependent types because
3071       // we don't need to do ADL at the definition point, but if we
3072       // wanted to implement template export (or if we find some other
3073       // use for associated classes and namespaces...) this would be
3074       // wrong.
3075       break;
3076 
3077     //    -- If T is a pointer to U or an array of U, its associated
3078     //       namespaces and classes are those associated with U.
3079     case Type::Pointer:
3080       T = cast<PointerType>(T)->getPointeeType().getTypePtr();
3081       continue;
3082     case Type::ConstantArray:
3083     case Type::IncompleteArray:
3084     case Type::VariableArray:
3085       T = cast<ArrayType>(T)->getElementType().getTypePtr();
3086       continue;
3087 
3088     //     -- If T is a fundamental type, its associated sets of
3089     //        namespaces and classes are both empty.
3090     case Type::Builtin:
3091       break;
3092 
3093     //     -- If T is a class type (including unions), its associated
3094     //        classes are: the class itself; the class of which it is
3095     //        a member, if any; and its direct and indirect base classes.
3096     //        Its associated namespaces are the innermost enclosing
3097     //        namespaces of its associated classes.
3098     case Type::Record: {
3099       CXXRecordDecl *Class =
3100           cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
3101       addAssociatedClassesAndNamespaces(Result, Class);
3102       break;
3103     }
3104 
3105     //     -- If T is an enumeration type, its associated namespace
3106     //        is the innermost enclosing namespace of its declaration.
3107     //        If it is a class member, its associated class is the
3108     //        member’s class; else it has no associated class.
3109     case Type::Enum: {
3110       EnumDecl *Enum = cast<EnumType>(T)->getDecl();
3111 
3112       DeclContext *Ctx = Enum->getDeclContext();
3113       if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3114         Result.Classes.insert(EnclosingClass);
3115 
3116       // Add the associated namespace for this enumeration.
3117       CollectEnclosingNamespace(Result.Namespaces, Ctx);
3118 
3119       break;
3120     }
3121 
3122     //     -- If T is a function type, its associated namespaces and
3123     //        classes are those associated with the function parameter
3124     //        types and those associated with the return type.
3125     case Type::FunctionProto: {
3126       const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
3127       for (const auto &Arg : Proto->param_types())
3128         Queue.push_back(Arg.getTypePtr());
3129       // fallthrough
3130       LLVM_FALLTHROUGH;
3131     }
3132     case Type::FunctionNoProto: {
3133       const FunctionType *FnType = cast<FunctionType>(T);
3134       T = FnType->getReturnType().getTypePtr();
3135       continue;
3136     }
3137 
3138     //     -- If T is a pointer to a member function of a class X, its
3139     //        associated namespaces and classes are those associated
3140     //        with the function parameter types and return type,
3141     //        together with those associated with X.
3142     //
3143     //     -- If T is a pointer to a data member of class X, its
3144     //        associated namespaces and classes are those associated
3145     //        with the member type together with those associated with
3146     //        X.
3147     case Type::MemberPointer: {
3148       const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
3149 
3150       // Queue up the class type into which this points.
3151       Queue.push_back(MemberPtr->getClass());
3152 
3153       // And directly continue with the pointee type.
3154       T = MemberPtr->getPointeeType().getTypePtr();
3155       continue;
3156     }
3157 
3158     // As an extension, treat this like a normal pointer.
3159     case Type::BlockPointer:
3160       T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
3161       continue;
3162 
3163     // References aren't covered by the standard, but that's such an
3164     // obvious defect that we cover them anyway.
3165     case Type::LValueReference:
3166     case Type::RValueReference:
3167       T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
3168       continue;
3169 
3170     // These are fundamental types.
3171     case Type::Vector:
3172     case Type::ExtVector:
3173     case Type::ConstantMatrix:
3174     case Type::Complex:
3175     case Type::BitInt:
3176       break;
3177 
3178     // Non-deduced auto types only get here for error cases.
3179     case Type::Auto:
3180     case Type::DeducedTemplateSpecialization:
3181       break;
3182 
3183     // If T is an Objective-C object or interface type, or a pointer to an
3184     // object or interface type, the associated namespace is the global
3185     // namespace.
3186     case Type::ObjCObject:
3187     case Type::ObjCInterface:
3188     case Type::ObjCObjectPointer:
3189       Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
3190       break;
3191 
3192     // Atomic types are just wrappers; use the associations of the
3193     // contained type.
3194     case Type::Atomic:
3195       T = cast<AtomicType>(T)->getValueType().getTypePtr();
3196       continue;
3197     case Type::Pipe:
3198       T = cast<PipeType>(T)->getElementType().getTypePtr();
3199       continue;
3200     }
3201 
3202     if (Queue.empty())
3203       break;
3204     T = Queue.pop_back_val();
3205   }
3206 }
3207 
3208 /// Find the associated classes and namespaces for
3209 /// argument-dependent lookup for a call with the given set of
3210 /// arguments.
3211 ///
3212 /// This routine computes the sets of associated classes and associated
3213 /// namespaces searched by argument-dependent lookup
3214 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
3215 void Sema::FindAssociatedClassesAndNamespaces(
3216     SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3217     AssociatedNamespaceSet &AssociatedNamespaces,
3218     AssociatedClassSet &AssociatedClasses) {
3219   AssociatedNamespaces.clear();
3220   AssociatedClasses.clear();
3221 
3222   AssociatedLookup Result(*this, InstantiationLoc,
3223                           AssociatedNamespaces, AssociatedClasses);
3224 
3225   // C++ [basic.lookup.koenig]p2:
3226   //   For each argument type T in the function call, there is a set
3227   //   of zero or more associated namespaces and a set of zero or more
3228   //   associated classes to be considered. The sets of namespaces and
3229   //   classes is determined entirely by the types of the function
3230   //   arguments (and the namespace of any template template
3231   //   argument).
3232   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3233     Expr *Arg = Args[ArgIdx];
3234 
3235     if (Arg->getType() != Context.OverloadTy) {
3236       addAssociatedClassesAndNamespaces(Result, Arg->getType());
3237       continue;
3238     }
3239 
3240     // [...] In addition, if the argument is the name or address of a
3241     // set of overloaded functions and/or function templates, its
3242     // associated classes and namespaces are the union of those
3243     // associated with each of the members of the set: the namespace
3244     // in which the function or function template is defined and the
3245     // classes and namespaces associated with its (non-dependent)
3246     // parameter types and return type.
3247     OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
3248 
3249     for (const NamedDecl *D : OE->decls()) {
3250       // Look through any using declarations to find the underlying function.
3251       const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3252 
3253       // Add the classes and namespaces associated with the parameter
3254       // types and return type of this function.
3255       addAssociatedClassesAndNamespaces(Result, FDecl->getType());
3256     }
3257   }
3258 }
3259 
3260 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
3261                                   SourceLocation Loc,
3262                                   LookupNameKind NameKind,
3263                                   RedeclarationKind Redecl) {
3264   LookupResult R(*this, Name, Loc, NameKind, Redecl);
3265   LookupName(R, S);
3266   return R.getAsSingle<NamedDecl>();
3267 }
3268 
3269 /// Find the protocol with the given name, if any.
3270 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
3271                                        SourceLocation IdLoc,
3272                                        RedeclarationKind Redecl) {
3273   Decl *D = LookupSingleName(TUScope, II, IdLoc,
3274                              LookupObjCProtocolName, Redecl);
3275   return cast_or_null<ObjCProtocolDecl>(D);
3276 }
3277 
3278 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3279                                         UnresolvedSetImpl &Functions) {
3280   // C++ [over.match.oper]p3:
3281   //     -- The set of non-member candidates is the result of the
3282   //        unqualified lookup of operator@ in the context of the
3283   //        expression according to the usual rules for name lookup in
3284   //        unqualified function calls (3.4.2) except that all member
3285   //        functions are ignored.
3286   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3287   LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3288   LookupName(Operators, S);
3289 
3290   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3291   Functions.append(Operators.begin(), Operators.end());
3292 }
3293 
3294 Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
3295                                                            CXXSpecialMember SM,
3296                                                            bool ConstArg,
3297                                                            bool VolatileArg,
3298                                                            bool RValueThis,
3299                                                            bool ConstThis,
3300                                                            bool VolatileThis) {
3301   assert(CanDeclareSpecialMemberFunction(RD) &&
3302          "doing special member lookup into record that isn't fully complete");
3303   RD = RD->getDefinition();
3304   if (RValueThis || ConstThis || VolatileThis)
3305     assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
3306            "constructors and destructors always have unqualified lvalue this");
3307   if (ConstArg || VolatileArg)
3308     assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
3309            "parameter-less special members can't have qualified arguments");
3310 
3311   // FIXME: Get the caller to pass in a location for the lookup.
3312   SourceLocation LookupLoc = RD->getLocation();
3313 
3314   llvm::FoldingSetNodeID ID;
3315   ID.AddPointer(RD);
3316   ID.AddInteger(SM);
3317   ID.AddInteger(ConstArg);
3318   ID.AddInteger(VolatileArg);
3319   ID.AddInteger(RValueThis);
3320   ID.AddInteger(ConstThis);
3321   ID.AddInteger(VolatileThis);
3322 
3323   void *InsertPoint;
3324   SpecialMemberOverloadResultEntry *Result =
3325     SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3326 
3327   // This was already cached
3328   if (Result)
3329     return *Result;
3330 
3331   Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
3332   Result = new (Result) SpecialMemberOverloadResultEntry(ID);
3333   SpecialMemberCache.InsertNode(Result, InsertPoint);
3334 
3335   if (SM == CXXDestructor) {
3336     if (RD->needsImplicitDestructor()) {
3337       runWithSufficientStackSpace(RD->getLocation(), [&] {
3338         DeclareImplicitDestructor(RD);
3339       });
3340     }
3341     CXXDestructorDecl *DD = RD->getDestructor();
3342     Result->setMethod(DD);
3343     Result->setKind(DD && !DD->isDeleted()
3344                         ? SpecialMemberOverloadResult::Success
3345                         : SpecialMemberOverloadResult::NoMemberOrDeleted);
3346     return *Result;
3347   }
3348 
3349   // Prepare for overload resolution. Here we construct a synthetic argument
3350   // if necessary and make sure that implicit functions are declared.
3351   CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
3352   DeclarationName Name;
3353   Expr *Arg = nullptr;
3354   unsigned NumArgs;
3355 
3356   QualType ArgType = CanTy;
3357   ExprValueKind VK = VK_LValue;
3358 
3359   if (SM == CXXDefaultConstructor) {
3360     Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3361     NumArgs = 0;
3362     if (RD->needsImplicitDefaultConstructor()) {
3363       runWithSufficientStackSpace(RD->getLocation(), [&] {
3364         DeclareImplicitDefaultConstructor(RD);
3365       });
3366     }
3367   } else {
3368     if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
3369       Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3370       if (RD->needsImplicitCopyConstructor()) {
3371         runWithSufficientStackSpace(RD->getLocation(), [&] {
3372           DeclareImplicitCopyConstructor(RD);
3373         });
3374       }
3375       if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {
3376         runWithSufficientStackSpace(RD->getLocation(), [&] {
3377           DeclareImplicitMoveConstructor(RD);
3378         });
3379       }
3380     } else {
3381       Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3382       if (RD->needsImplicitCopyAssignment()) {
3383         runWithSufficientStackSpace(RD->getLocation(), [&] {
3384           DeclareImplicitCopyAssignment(RD);
3385         });
3386       }
3387       if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {
3388         runWithSufficientStackSpace(RD->getLocation(), [&] {
3389           DeclareImplicitMoveAssignment(RD);
3390         });
3391       }
3392     }
3393 
3394     if (ConstArg)
3395       ArgType.addConst();
3396     if (VolatileArg)
3397       ArgType.addVolatile();
3398 
3399     // This isn't /really/ specified by the standard, but it's implied
3400     // we should be working from a PRValue in the case of move to ensure
3401     // that we prefer to bind to rvalue references, and an LValue in the
3402     // case of copy to ensure we don't bind to rvalue references.
3403     // Possibly an XValue is actually correct in the case of move, but
3404     // there is no semantic difference for class types in this restricted
3405     // case.
3406     if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
3407       VK = VK_LValue;
3408     else
3409       VK = VK_PRValue;
3410   }
3411 
3412   OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3413 
3414   if (SM != CXXDefaultConstructor) {
3415     NumArgs = 1;
3416     Arg = &FakeArg;
3417   }
3418 
3419   // Create the object argument
3420   QualType ThisTy = CanTy;
3421   if (ConstThis)
3422     ThisTy.addConst();
3423   if (VolatileThis)
3424     ThisTy.addVolatile();
3425   Expr::Classification Classification =
3426       OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3427           .Classify(Context);
3428 
3429   // Now we perform lookup on the name we computed earlier and do overload
3430   // resolution. Lookup is only performed directly into the class since there
3431   // will always be a (possibly implicit) declaration to shadow any others.
3432   OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
3433   DeclContext::lookup_result R = RD->lookup(Name);
3434 
3435   if (R.empty()) {
3436     // We might have no default constructor because we have a lambda's closure
3437     // type, rather than because there's some other declared constructor.
3438     // Every class has a copy/move constructor, copy/move assignment, and
3439     // destructor.
3440     assert(SM == CXXDefaultConstructor &&
3441            "lookup for a constructor or assignment operator was empty");
3442     Result->setMethod(nullptr);
3443     Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3444     return *Result;
3445   }
3446 
3447   // Copy the candidates as our processing of them may load new declarations
3448   // from an external source and invalidate lookup_result.
3449   SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3450 
3451   for (NamedDecl *CandDecl : Candidates) {
3452     if (CandDecl->isInvalidDecl())
3453       continue;
3454 
3455     DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
3456     auto CtorInfo = getConstructorInfo(Cand);
3457     if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3458       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3459         AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3460                            llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3461       else if (CtorInfo)
3462         AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3463                              llvm::makeArrayRef(&Arg, NumArgs), OCS,
3464                              /*SuppressUserConversions*/ true);
3465       else
3466         AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3467                              /*SuppressUserConversions*/ true);
3468     } else if (FunctionTemplateDecl *Tmpl =
3469                  dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3470       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3471         AddMethodTemplateCandidate(
3472             Tmpl, Cand, RD, nullptr, ThisTy, Classification,
3473             llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3474       else if (CtorInfo)
3475         AddTemplateOverloadCandidate(
3476             CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3477             llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3478       else
3479         AddTemplateOverloadCandidate(
3480             Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3481     } else {
3482       assert(isa<UsingDecl>(Cand.getDecl()) &&
3483              "illegal Kind of operator = Decl");
3484     }
3485   }
3486 
3487   OverloadCandidateSet::iterator Best;
3488   switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3489     case OR_Success:
3490       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3491       Result->setKind(SpecialMemberOverloadResult::Success);
3492       break;
3493 
3494     case OR_Deleted:
3495       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3496       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3497       break;
3498 
3499     case OR_Ambiguous:
3500       Result->setMethod(nullptr);
3501       Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3502       break;
3503 
3504     case OR_No_Viable_Function:
3505       Result->setMethod(nullptr);
3506       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3507       break;
3508   }
3509 
3510   return *Result;
3511 }
3512 
3513 /// Look up the default constructor for the given class.
3514 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
3515   SpecialMemberOverloadResult Result =
3516     LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3517                         false, false);
3518 
3519   return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3520 }
3521 
3522 /// Look up the copying constructor for the given class.
3523 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
3524                                                    unsigned Quals) {
3525   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3526          "non-const, non-volatile qualifiers for copy ctor arg");
3527   SpecialMemberOverloadResult Result =
3528     LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3529                         Quals & Qualifiers::Volatile, false, false, false);
3530 
3531   return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3532 }
3533 
3534 /// Look up the moving constructor for the given class.
3535 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3536                                                   unsigned Quals) {
3537   SpecialMemberOverloadResult Result =
3538     LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3539                         Quals & Qualifiers::Volatile, false, false, false);
3540 
3541   return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3542 }
3543 
3544 /// Look up the constructors for the given class.
3545 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
3546   // If the implicit constructors have not yet been declared, do so now.
3547   if (CanDeclareSpecialMemberFunction(Class)) {
3548     runWithSufficientStackSpace(Class->getLocation(), [&] {
3549       if (Class->needsImplicitDefaultConstructor())
3550         DeclareImplicitDefaultConstructor(Class);
3551       if (Class->needsImplicitCopyConstructor())
3552         DeclareImplicitCopyConstructor(Class);
3553       if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3554         DeclareImplicitMoveConstructor(Class);
3555     });
3556   }
3557 
3558   CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3559   DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3560   return Class->lookup(Name);
3561 }
3562 
3563 /// Look up the copying assignment operator for the given class.
3564 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3565                                              unsigned Quals, bool RValueThis,
3566                                              unsigned ThisQuals) {
3567   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3568          "non-const, non-volatile qualifiers for copy assignment arg");
3569   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3570          "non-const, non-volatile qualifiers for copy assignment this");
3571   SpecialMemberOverloadResult Result =
3572     LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3573                         Quals & Qualifiers::Volatile, RValueThis,
3574                         ThisQuals & Qualifiers::Const,
3575                         ThisQuals & Qualifiers::Volatile);
3576 
3577   return Result.getMethod();
3578 }
3579 
3580 /// Look up the moving assignment operator for the given class.
3581 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
3582                                             unsigned Quals,
3583                                             bool RValueThis,
3584                                             unsigned ThisQuals) {
3585   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3586          "non-const, non-volatile qualifiers for copy assignment this");
3587   SpecialMemberOverloadResult Result =
3588     LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3589                         Quals & Qualifiers::Volatile, RValueThis,
3590                         ThisQuals & Qualifiers::Const,
3591                         ThisQuals & Qualifiers::Volatile);
3592 
3593   return Result.getMethod();
3594 }
3595 
3596 /// Look for the destructor of the given class.
3597 ///
3598 /// During semantic analysis, this routine should be used in lieu of
3599 /// CXXRecordDecl::getDestructor().
3600 ///
3601 /// \returns The destructor for this class.
3602 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3603   return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3604                                                      false, false, false,
3605                                                      false, false).getMethod());
3606 }
3607 
3608 /// LookupLiteralOperator - Determine which literal operator should be used for
3609 /// a user-defined literal, per C++11 [lex.ext].
3610 ///
3611 /// Normal overload resolution is not used to select which literal operator to
3612 /// call for a user-defined literal. Look up the provided literal operator name,
3613 /// and filter the results to the appropriate set for the given argument types.
3614 Sema::LiteralOperatorLookupResult
3615 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3616                             ArrayRef<QualType> ArgTys, bool AllowRaw,
3617                             bool AllowTemplate, bool AllowStringTemplatePack,
3618                             bool DiagnoseMissing, StringLiteral *StringLit) {
3619   LookupName(R, S);
3620   assert(R.getResultKind() != LookupResult::Ambiguous &&
3621          "literal operator lookup can't be ambiguous");
3622 
3623   // Filter the lookup results appropriately.
3624   LookupResult::Filter F = R.makeFilter();
3625 
3626   bool AllowCooked = true;
3627   bool FoundRaw = false;
3628   bool FoundTemplate = false;
3629   bool FoundStringTemplatePack = false;
3630   bool FoundCooked = false;
3631 
3632   while (F.hasNext()) {
3633     Decl *D = F.next();
3634     if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3635       D = USD->getTargetDecl();
3636 
3637     // If the declaration we found is invalid, skip it.
3638     if (D->isInvalidDecl()) {
3639       F.erase();
3640       continue;
3641     }
3642 
3643     bool IsRaw = false;
3644     bool IsTemplate = false;
3645     bool IsStringTemplatePack = false;
3646     bool IsCooked = false;
3647 
3648     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3649       if (FD->getNumParams() == 1 &&
3650           FD->getParamDecl(0)->getType()->getAs<PointerType>())
3651         IsRaw = true;
3652       else if (FD->getNumParams() == ArgTys.size()) {
3653         IsCooked = true;
3654         for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3655           QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3656           if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3657             IsCooked = false;
3658             break;
3659           }
3660         }
3661       }
3662     }
3663     if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3664       TemplateParameterList *Params = FD->getTemplateParameters();
3665       if (Params->size() == 1) {
3666         IsTemplate = true;
3667         if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3668           // Implied but not stated: user-defined integer and floating literals
3669           // only ever use numeric literal operator templates, not templates
3670           // taking a parameter of class type.
3671           F.erase();
3672           continue;
3673         }
3674 
3675         // A string literal template is only considered if the string literal
3676         // is a well-formed template argument for the template parameter.
3677         if (StringLit) {
3678           SFINAETrap Trap(*this);
3679           SmallVector<TemplateArgument, 1> Checked;
3680           TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
3681           if (CheckTemplateArgument(Params->getParam(0), Arg, FD,
3682                                     R.getNameLoc(), R.getNameLoc(), 0,
3683                                     Checked) ||
3684               Trap.hasErrorOccurred())
3685             IsTemplate = false;
3686         }
3687       } else {
3688         IsStringTemplatePack = true;
3689       }
3690     }
3691 
3692     if (AllowTemplate && StringLit && IsTemplate) {
3693       FoundTemplate = true;
3694       AllowRaw = false;
3695       AllowCooked = false;
3696       AllowStringTemplatePack = false;
3697       if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3698         F.restart();
3699         FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3700       }
3701     } else if (AllowCooked && IsCooked) {
3702       FoundCooked = true;
3703       AllowRaw = false;
3704       AllowTemplate = StringLit;
3705       AllowStringTemplatePack = false;
3706       if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3707         // Go through again and remove the raw and template decls we've
3708         // already found.
3709         F.restart();
3710         FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3711       }
3712     } else if (AllowRaw && IsRaw) {
3713       FoundRaw = true;
3714     } else if (AllowTemplate && IsTemplate) {
3715       FoundTemplate = true;
3716     } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3717       FoundStringTemplatePack = true;
3718     } else {
3719       F.erase();
3720     }
3721   }
3722 
3723   F.done();
3724 
3725   // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3726   // form for string literal operator templates.
3727   if (StringLit && FoundTemplate)
3728     return LOLR_Template;
3729 
3730   // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3731   // parameter type, that is used in preference to a raw literal operator
3732   // or literal operator template.
3733   if (FoundCooked)
3734     return LOLR_Cooked;
3735 
3736   // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3737   // operator template, but not both.
3738   if (FoundRaw && FoundTemplate) {
3739     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3740     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3741       NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
3742     return LOLR_Error;
3743   }
3744 
3745   if (FoundRaw)
3746     return LOLR_Raw;
3747 
3748   if (FoundTemplate)
3749     return LOLR_Template;
3750 
3751   if (FoundStringTemplatePack)
3752     return LOLR_StringTemplatePack;
3753 
3754   // Didn't find anything we could use.
3755   if (DiagnoseMissing) {
3756     Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3757         << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3758         << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3759         << (AllowTemplate || AllowStringTemplatePack);
3760     return LOLR_Error;
3761   }
3762 
3763   return LOLR_ErrorNoDiagnostic;
3764 }
3765 
3766 void ADLResult::insert(NamedDecl *New) {
3767   NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3768 
3769   // If we haven't yet seen a decl for this key, or the last decl
3770   // was exactly this one, we're done.
3771   if (Old == nullptr || Old == New) {
3772     Old = New;
3773     return;
3774   }
3775 
3776   // Otherwise, decide which is a more recent redeclaration.
3777   FunctionDecl *OldFD = Old->getAsFunction();
3778   FunctionDecl *NewFD = New->getAsFunction();
3779 
3780   FunctionDecl *Cursor = NewFD;
3781   while (true) {
3782     Cursor = Cursor->getPreviousDecl();
3783 
3784     // If we got to the end without finding OldFD, OldFD is the newer
3785     // declaration;  leave things as they are.
3786     if (!Cursor) return;
3787 
3788     // If we do find OldFD, then NewFD is newer.
3789     if (Cursor == OldFD) break;
3790 
3791     // Otherwise, keep looking.
3792   }
3793 
3794   Old = New;
3795 }
3796 
3797 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3798                                    ArrayRef<Expr *> Args, ADLResult &Result) {
3799   // Find all of the associated namespaces and classes based on the
3800   // arguments we have.
3801   AssociatedNamespaceSet AssociatedNamespaces;
3802   AssociatedClassSet AssociatedClasses;
3803   FindAssociatedClassesAndNamespaces(Loc, Args,
3804                                      AssociatedNamespaces,
3805                                      AssociatedClasses);
3806 
3807   // C++ [basic.lookup.argdep]p3:
3808   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
3809   //   and let Y be the lookup set produced by argument dependent
3810   //   lookup (defined as follows). If X contains [...] then Y is
3811   //   empty. Otherwise Y is the set of declarations found in the
3812   //   namespaces associated with the argument types as described
3813   //   below. The set of declarations found by the lookup of the name
3814   //   is the union of X and Y.
3815   //
3816   // Here, we compute Y and add its members to the overloaded
3817   // candidate set.
3818   for (auto *NS : AssociatedNamespaces) {
3819     //   When considering an associated namespace, the lookup is the
3820     //   same as the lookup performed when the associated namespace is
3821     //   used as a qualifier (3.4.3.2) except that:
3822     //
3823     //     -- Any using-directives in the associated namespace are
3824     //        ignored.
3825     //
3826     //     -- Any namespace-scope friend functions declared in
3827     //        associated classes are visible within their respective
3828     //        namespaces even if they are not visible during an ordinary
3829     //        lookup (11.4).
3830     DeclContext::lookup_result R = NS->lookup(Name);
3831     for (auto *D : R) {
3832       auto *Underlying = D;
3833       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3834         Underlying = USD->getTargetDecl();
3835 
3836       if (!isa<FunctionDecl>(Underlying) &&
3837           !isa<FunctionTemplateDecl>(Underlying))
3838         continue;
3839 
3840       // The declaration is visible to argument-dependent lookup if either
3841       // it's ordinarily visible or declared as a friend in an associated
3842       // class.
3843       bool Visible = false;
3844       for (D = D->getMostRecentDecl(); D;
3845            D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3846         if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3847           if (isVisible(D)) {
3848             Visible = true;
3849             break;
3850           }
3851         } else if (D->getFriendObjectKind()) {
3852           auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3853           // [basic.lookup.argdep]p4:
3854           //   Argument-dependent lookup finds all declarations of functions and
3855           //   function templates that
3856           //  - ...
3857           //  - are declared as a friend ([class.friend]) of any class with a
3858           //  reachable definition in the set of associated entities,
3859           //
3860           // FIXME: If there's a merged definition of D that is reachable, then
3861           // the friend declaration should be considered.
3862           if (AssociatedClasses.count(RD) && isReachable(D)) {
3863             Visible = true;
3864             break;
3865           }
3866         }
3867       }
3868 
3869       // FIXME: Preserve D as the FoundDecl.
3870       if (Visible)
3871         Result.insert(Underlying);
3872     }
3873   }
3874 }
3875 
3876 //----------------------------------------------------------------------------
3877 // Search for all visible declarations.
3878 //----------------------------------------------------------------------------
3879 VisibleDeclConsumer::~VisibleDeclConsumer() { }
3880 
3881 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3882 
3883 namespace {
3884 
3885 class ShadowContextRAII;
3886 
3887 class VisibleDeclsRecord {
3888 public:
3889   /// An entry in the shadow map, which is optimized to store a
3890   /// single declaration (the common case) but can also store a list
3891   /// of declarations.
3892   typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3893 
3894 private:
3895   /// A mapping from declaration names to the declarations that have
3896   /// this name within a particular scope.
3897   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3898 
3899   /// A list of shadow maps, which is used to model name hiding.
3900   std::list<ShadowMap> ShadowMaps;
3901 
3902   /// The declaration contexts we have already visited.
3903   llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3904 
3905   friend class ShadowContextRAII;
3906 
3907 public:
3908   /// Determine whether we have already visited this context
3909   /// (and, if not, note that we are going to visit that context now).
3910   bool visitedContext(DeclContext *Ctx) {
3911     return !VisitedContexts.insert(Ctx).second;
3912   }
3913 
3914   bool alreadyVisitedContext(DeclContext *Ctx) {
3915     return VisitedContexts.count(Ctx);
3916   }
3917 
3918   /// Determine whether the given declaration is hidden in the
3919   /// current scope.
3920   ///
3921   /// \returns the declaration that hides the given declaration, or
3922   /// NULL if no such declaration exists.
3923   NamedDecl *checkHidden(NamedDecl *ND);
3924 
3925   /// Add a declaration to the current shadow map.
3926   void add(NamedDecl *ND) {
3927     ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3928   }
3929 };
3930 
3931 /// RAII object that records when we've entered a shadow context.
3932 class ShadowContextRAII {
3933   VisibleDeclsRecord &Visible;
3934 
3935   typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3936 
3937 public:
3938   ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3939     Visible.ShadowMaps.emplace_back();
3940   }
3941 
3942   ~ShadowContextRAII() {
3943     Visible.ShadowMaps.pop_back();
3944   }
3945 };
3946 
3947 } // end anonymous namespace
3948 
3949 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3950   unsigned IDNS = ND->getIdentifierNamespace();
3951   std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3952   for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3953        SM != SMEnd; ++SM) {
3954     ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3955     if (Pos == SM->end())
3956       continue;
3957 
3958     for (auto *D : Pos->second) {
3959       // A tag declaration does not hide a non-tag declaration.
3960       if (D->hasTagIdentifierNamespace() &&
3961           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
3962                    Decl::IDNS_ObjCProtocol)))
3963         continue;
3964 
3965       // Protocols are in distinct namespaces from everything else.
3966       if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3967            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3968           D->getIdentifierNamespace() != IDNS)
3969         continue;
3970 
3971       // Functions and function templates in the same scope overload
3972       // rather than hide.  FIXME: Look for hiding based on function
3973       // signatures!
3974       if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3975           ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3976           SM == ShadowMaps.rbegin())
3977         continue;
3978 
3979       // A shadow declaration that's created by a resolved using declaration
3980       // is not hidden by the same using declaration.
3981       if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3982           cast<UsingShadowDecl>(ND)->getIntroducer() == D)
3983         continue;
3984 
3985       // We've found a declaration that hides this one.
3986       return D;
3987     }
3988   }
3989 
3990   return nullptr;
3991 }
3992 
3993 namespace {
3994 class LookupVisibleHelper {
3995 public:
3996   LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
3997                       bool LoadExternal)
3998       : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
3999         LoadExternal(LoadExternal) {}
4000 
4001   void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4002                           bool IncludeGlobalScope) {
4003     // Determine the set of using directives available during
4004     // unqualified name lookup.
4005     Scope *Initial = S;
4006     UnqualUsingDirectiveSet UDirs(SemaRef);
4007     if (SemaRef.getLangOpts().CPlusPlus) {
4008       // Find the first namespace or translation-unit scope.
4009       while (S && !isNamespaceOrTranslationUnitScope(S))
4010         S = S->getParent();
4011 
4012       UDirs.visitScopeChain(Initial, S);
4013     }
4014     UDirs.done();
4015 
4016     // Look for visible declarations.
4017     LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4018     Result.setAllowHidden(Consumer.includeHiddenDecls());
4019     if (!IncludeGlobalScope)
4020       Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4021     ShadowContextRAII Shadow(Visited);
4022     lookupInScope(Initial, Result, UDirs);
4023   }
4024 
4025   void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4026                           Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4027     LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4028     Result.setAllowHidden(Consumer.includeHiddenDecls());
4029     if (!IncludeGlobalScope)
4030       Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4031 
4032     ShadowContextRAII Shadow(Visited);
4033     lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4034                         /*InBaseClass=*/false);
4035   }
4036 
4037 private:
4038   void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4039                            bool QualifiedNameLookup, bool InBaseClass) {
4040     if (!Ctx)
4041       return;
4042 
4043     // Make sure we don't visit the same context twice.
4044     if (Visited.visitedContext(Ctx->getPrimaryContext()))
4045       return;
4046 
4047     Consumer.EnteredContext(Ctx);
4048 
4049     // Outside C++, lookup results for the TU live on identifiers.
4050     if (isa<TranslationUnitDecl>(Ctx) &&
4051         !Result.getSema().getLangOpts().CPlusPlus) {
4052       auto &S = Result.getSema();
4053       auto &Idents = S.Context.Idents;
4054 
4055       // Ensure all external identifiers are in the identifier table.
4056       if (LoadExternal)
4057         if (IdentifierInfoLookup *External =
4058                 Idents.getExternalIdentifierLookup()) {
4059           std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4060           for (StringRef Name = Iter->Next(); !Name.empty();
4061                Name = Iter->Next())
4062             Idents.get(Name);
4063         }
4064 
4065       // Walk all lookup results in the TU for each identifier.
4066       for (const auto &Ident : Idents) {
4067         for (auto I = S.IdResolver.begin(Ident.getValue()),
4068                   E = S.IdResolver.end();
4069              I != E; ++I) {
4070           if (S.IdResolver.isDeclInScope(*I, Ctx)) {
4071             if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4072               Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4073               Visited.add(ND);
4074             }
4075           }
4076         }
4077       }
4078 
4079       return;
4080     }
4081 
4082     if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
4083       Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4084 
4085     llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;
4086     // We sometimes skip loading namespace-level results (they tend to be huge).
4087     bool Load = LoadExternal ||
4088                 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
4089     // Enumerate all of the results in this context.
4090     for (DeclContextLookupResult R :
4091          Load ? Ctx->lookups()
4092               : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
4093       for (auto *D : R) {
4094         if (auto *ND = Result.getAcceptableDecl(D)) {
4095           // Rather than visit immediately, we put ND into a vector and visit
4096           // all decls, in order, outside of this loop. The reason is that
4097           // Consumer.FoundDecl() may invalidate the iterators used in the two
4098           // loops above.
4099           DeclsToVisit.push_back(ND);
4100         }
4101       }
4102     }
4103 
4104     for (auto *ND : DeclsToVisit) {
4105       Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4106       Visited.add(ND);
4107     }
4108     DeclsToVisit.clear();
4109 
4110     // Traverse using directives for qualified name lookup.
4111     if (QualifiedNameLookup) {
4112       ShadowContextRAII Shadow(Visited);
4113       for (auto I : Ctx->using_directives()) {
4114         if (!Result.getSema().isVisible(I))
4115           continue;
4116         lookupInDeclContext(I->getNominatedNamespace(), Result,
4117                             QualifiedNameLookup, InBaseClass);
4118       }
4119     }
4120 
4121     // Traverse the contexts of inherited C++ classes.
4122     if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
4123       if (!Record->hasDefinition())
4124         return;
4125 
4126       for (const auto &B : Record->bases()) {
4127         QualType BaseType = B.getType();
4128 
4129         RecordDecl *RD;
4130         if (BaseType->isDependentType()) {
4131           if (!IncludeDependentBases) {
4132             // Don't look into dependent bases, because name lookup can't look
4133             // there anyway.
4134             continue;
4135           }
4136           const auto *TST = BaseType->getAs<TemplateSpecializationType>();
4137           if (!TST)
4138             continue;
4139           TemplateName TN = TST->getTemplateName();
4140           const auto *TD =
4141               dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
4142           if (!TD)
4143             continue;
4144           RD = TD->getTemplatedDecl();
4145         } else {
4146           const auto *Record = BaseType->getAs<RecordType>();
4147           if (!Record)
4148             continue;
4149           RD = Record->getDecl();
4150         }
4151 
4152         // FIXME: It would be nice to be able to determine whether referencing
4153         // a particular member would be ambiguous. For example, given
4154         //
4155         //   struct A { int member; };
4156         //   struct B { int member; };
4157         //   struct C : A, B { };
4158         //
4159         //   void f(C *c) { c->### }
4160         //
4161         // accessing 'member' would result in an ambiguity. However, we
4162         // could be smart enough to qualify the member with the base
4163         // class, e.g.,
4164         //
4165         //   c->B::member
4166         //
4167         // or
4168         //
4169         //   c->A::member
4170 
4171         // Find results in this base class (and its bases).
4172         ShadowContextRAII Shadow(Visited);
4173         lookupInDeclContext(RD, Result, QualifiedNameLookup,
4174                             /*InBaseClass=*/true);
4175       }
4176     }
4177 
4178     // Traverse the contexts of Objective-C classes.
4179     if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
4180       // Traverse categories.
4181       for (auto *Cat : IFace->visible_categories()) {
4182         ShadowContextRAII Shadow(Visited);
4183         lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4184                             /*InBaseClass=*/false);
4185       }
4186 
4187       // Traverse protocols.
4188       for (auto *I : IFace->all_referenced_protocols()) {
4189         ShadowContextRAII Shadow(Visited);
4190         lookupInDeclContext(I, Result, QualifiedNameLookup,
4191                             /*InBaseClass=*/false);
4192       }
4193 
4194       // Traverse the superclass.
4195       if (IFace->getSuperClass()) {
4196         ShadowContextRAII Shadow(Visited);
4197         lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4198                             /*InBaseClass=*/true);
4199       }
4200 
4201       // If there is an implementation, traverse it. We do this to find
4202       // synthesized ivars.
4203       if (IFace->getImplementation()) {
4204         ShadowContextRAII Shadow(Visited);
4205         lookupInDeclContext(IFace->getImplementation(), Result,
4206                             QualifiedNameLookup, InBaseClass);
4207       }
4208     } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4209       for (auto *I : Protocol->protocols()) {
4210         ShadowContextRAII Shadow(Visited);
4211         lookupInDeclContext(I, Result, QualifiedNameLookup,
4212                             /*InBaseClass=*/false);
4213       }
4214     } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4215       for (auto *I : Category->protocols()) {
4216         ShadowContextRAII Shadow(Visited);
4217         lookupInDeclContext(I, Result, QualifiedNameLookup,
4218                             /*InBaseClass=*/false);
4219       }
4220 
4221       // If there is an implementation, traverse it.
4222       if (Category->getImplementation()) {
4223         ShadowContextRAII Shadow(Visited);
4224         lookupInDeclContext(Category->getImplementation(), Result,
4225                             QualifiedNameLookup, /*InBaseClass=*/true);
4226       }
4227     }
4228   }
4229 
4230   void lookupInScope(Scope *S, LookupResult &Result,
4231                      UnqualUsingDirectiveSet &UDirs) {
4232     // No clients run in this mode and it's not supported. Please add tests and
4233     // remove the assertion if you start relying on it.
4234     assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4235 
4236     if (!S)
4237       return;
4238 
4239     if (!S->getEntity() ||
4240         (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4241         (S->getEntity())->isFunctionOrMethod()) {
4242       FindLocalExternScope FindLocals(Result);
4243       // Walk through the declarations in this Scope. The consumer might add new
4244       // decls to the scope as part of deserialization, so make a copy first.
4245       SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4246       for (Decl *D : ScopeDecls) {
4247         if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4248           if ((ND = Result.getAcceptableDecl(ND))) {
4249             Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4250             Visited.add(ND);
4251           }
4252       }
4253     }
4254 
4255     DeclContext *Entity = S->getLookupEntity();
4256     if (Entity) {
4257       // Look into this scope's declaration context, along with any of its
4258       // parent lookup contexts (e.g., enclosing classes), up to the point
4259       // where we hit the context stored in the next outer scope.
4260       DeclContext *OuterCtx = findOuterContext(S);
4261 
4262       for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4263            Ctx = Ctx->getLookupParent()) {
4264         if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4265           if (Method->isInstanceMethod()) {
4266             // For instance methods, look for ivars in the method's interface.
4267             LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4268                                     Result.getNameLoc(),
4269                                     Sema::LookupMemberName);
4270             if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4271               lookupInDeclContext(IFace, IvarResult,
4272                                   /*QualifiedNameLookup=*/false,
4273                                   /*InBaseClass=*/false);
4274             }
4275           }
4276 
4277           // We've already performed all of the name lookup that we need
4278           // to for Objective-C methods; the next context will be the
4279           // outer scope.
4280           break;
4281         }
4282 
4283         if (Ctx->isFunctionOrMethod())
4284           continue;
4285 
4286         lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4287                             /*InBaseClass=*/false);
4288       }
4289     } else if (!S->getParent()) {
4290       // Look into the translation unit scope. We walk through the translation
4291       // unit's declaration context, because the Scope itself won't have all of
4292       // the declarations if we loaded a precompiled header.
4293       // FIXME: We would like the translation unit's Scope object to point to
4294       // the translation unit, so we don't need this special "if" branch.
4295       // However, doing so would force the normal C++ name-lookup code to look
4296       // into the translation unit decl when the IdentifierInfo chains would
4297       // suffice. Once we fix that problem (which is part of a more general
4298       // "don't look in DeclContexts unless we have to" optimization), we can
4299       // eliminate this.
4300       Entity = Result.getSema().Context.getTranslationUnitDecl();
4301       lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4302                           /*InBaseClass=*/false);
4303     }
4304 
4305     if (Entity) {
4306       // Lookup visible declarations in any namespaces found by using
4307       // directives.
4308       for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4309         lookupInDeclContext(
4310             const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4311             /*QualifiedNameLookup=*/false,
4312             /*InBaseClass=*/false);
4313     }
4314 
4315     // Lookup names in the parent scope.
4316     ShadowContextRAII Shadow(Visited);
4317     lookupInScope(S->getParent(), Result, UDirs);
4318   }
4319 
4320 private:
4321   VisibleDeclsRecord Visited;
4322   VisibleDeclConsumer &Consumer;
4323   bool IncludeDependentBases;
4324   bool LoadExternal;
4325 };
4326 } // namespace
4327 
4328 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4329                               VisibleDeclConsumer &Consumer,
4330                               bool IncludeGlobalScope, bool LoadExternal) {
4331   LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4332                         LoadExternal);
4333   H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4334 }
4335 
4336 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4337                               VisibleDeclConsumer &Consumer,
4338                               bool IncludeGlobalScope,
4339                               bool IncludeDependentBases, bool LoadExternal) {
4340   LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4341   H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4342 }
4343 
4344 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
4345 /// If GnuLabelLoc is a valid source location, then this is a definition
4346 /// of an __label__ label name, otherwise it is a normal label definition
4347 /// or use.
4348 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
4349                                      SourceLocation GnuLabelLoc) {
4350   // Do a lookup to see if we have a label with this name already.
4351   NamedDecl *Res = nullptr;
4352 
4353   if (GnuLabelLoc.isValid()) {
4354     // Local label definitions always shadow existing labels.
4355     Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4356     Scope *S = CurScope;
4357     PushOnScopeChains(Res, S, true);
4358     return cast<LabelDecl>(Res);
4359   }
4360 
4361   // Not a GNU local label.
4362   Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
4363   // If we found a label, check to see if it is in the same context as us.
4364   // When in a Block, we don't want to reuse a label in an enclosing function.
4365   if (Res && Res->getDeclContext() != CurContext)
4366     Res = nullptr;
4367   if (!Res) {
4368     // If not forward referenced or defined already, create the backing decl.
4369     Res = LabelDecl::Create(Context, CurContext, Loc, II);
4370     Scope *S = CurScope->getFnParent();
4371     assert(S && "Not in a function?");
4372     PushOnScopeChains(Res, S, true);
4373   }
4374   return cast<LabelDecl>(Res);
4375 }
4376 
4377 //===----------------------------------------------------------------------===//
4378 // Typo correction
4379 //===----------------------------------------------------------------------===//
4380 
4381 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
4382                               TypoCorrection &Candidate) {
4383   Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4384   return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4385 }
4386 
4387 static void LookupPotentialTypoResult(Sema &SemaRef,
4388                                       LookupResult &Res,
4389                                       IdentifierInfo *Name,
4390                                       Scope *S, CXXScopeSpec *SS,
4391                                       DeclContext *MemberContext,
4392                                       bool EnteringContext,
4393                                       bool isObjCIvarLookup,
4394                                       bool FindHidden);
4395 
4396 /// Check whether the declarations found for a typo correction are
4397 /// visible. Set the correction's RequiresImport flag to true if none of the
4398 /// declarations are visible, false otherwise.
4399 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
4400   TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4401 
4402   for (/**/; DI != DE; ++DI)
4403     if (!LookupResult::isVisible(SemaRef, *DI))
4404       break;
4405   // No filtering needed if all decls are visible.
4406   if (DI == DE) {
4407     TC.setRequiresImport(false);
4408     return;
4409   }
4410 
4411   llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4412   bool AnyVisibleDecls = !NewDecls.empty();
4413 
4414   for (/**/; DI != DE; ++DI) {
4415     if (LookupResult::isVisible(SemaRef, *DI)) {
4416       if (!AnyVisibleDecls) {
4417         // Found a visible decl, discard all hidden ones.
4418         AnyVisibleDecls = true;
4419         NewDecls.clear();
4420       }
4421       NewDecls.push_back(*DI);
4422     } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4423       NewDecls.push_back(*DI);
4424   }
4425 
4426   if (NewDecls.empty())
4427     TC = TypoCorrection();
4428   else {
4429     TC.setCorrectionDecls(NewDecls);
4430     TC.setRequiresImport(!AnyVisibleDecls);
4431   }
4432 }
4433 
4434 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
4435 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4436 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4437 static void getNestedNameSpecifierIdentifiers(
4438     NestedNameSpecifier *NNS,
4439     SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
4440   if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4441     getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4442   else
4443     Identifiers.clear();
4444 
4445   const IdentifierInfo *II = nullptr;
4446 
4447   switch (NNS->getKind()) {
4448   case NestedNameSpecifier::Identifier:
4449     II = NNS->getAsIdentifier();
4450     break;
4451 
4452   case NestedNameSpecifier::Namespace:
4453     if (NNS->getAsNamespace()->isAnonymousNamespace())
4454       return;
4455     II = NNS->getAsNamespace()->getIdentifier();
4456     break;
4457 
4458   case NestedNameSpecifier::NamespaceAlias:
4459     II = NNS->getAsNamespaceAlias()->getIdentifier();
4460     break;
4461 
4462   case NestedNameSpecifier::TypeSpecWithTemplate:
4463   case NestedNameSpecifier::TypeSpec:
4464     II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4465     break;
4466 
4467   case NestedNameSpecifier::Global:
4468   case NestedNameSpecifier::Super:
4469     return;
4470   }
4471 
4472   if (II)
4473     Identifiers.push_back(II);
4474 }
4475 
4476 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
4477                                        DeclContext *Ctx, bool InBaseClass) {
4478   // Don't consider hidden names for typo correction.
4479   if (Hiding)
4480     return;
4481 
4482   // Only consider entities with identifiers for names, ignoring
4483   // special names (constructors, overloaded operators, selectors,
4484   // etc.).
4485   IdentifierInfo *Name = ND->getIdentifier();
4486   if (!Name)
4487     return;
4488 
4489   // Only consider visible declarations and declarations from modules with
4490   // names that exactly match.
4491   if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4492     return;
4493 
4494   FoundName(Name->getName());
4495 }
4496 
4497 void TypoCorrectionConsumer::FoundName(StringRef Name) {
4498   // Compute the edit distance between the typo and the name of this
4499   // entity, and add the identifier to the list of results.
4500   addName(Name, nullptr);
4501 }
4502 
4503 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4504   // Compute the edit distance between the typo and this keyword,
4505   // and add the keyword to the list of results.
4506   addName(Keyword, nullptr, nullptr, true);
4507 }
4508 
4509 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4510                                      NestedNameSpecifier *NNS, bool isKeyword) {
4511   // Use a simple length-based heuristic to determine the minimum possible
4512   // edit distance. If the minimum isn't good enough, bail out early.
4513   StringRef TypoStr = Typo->getName();
4514   unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4515   if (MinED && TypoStr.size() / MinED < 3)
4516     return;
4517 
4518   // Compute an upper bound on the allowable edit distance, so that the
4519   // edit-distance algorithm can short-circuit.
4520   unsigned UpperBound = (TypoStr.size() + 2) / 3;
4521   unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4522   if (ED > UpperBound) return;
4523 
4524   TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4525   if (isKeyword) TC.makeKeyword();
4526   TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4527   addCorrection(TC);
4528 }
4529 
4530 static const unsigned MaxTypoDistanceResultSets = 5;
4531 
4532 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
4533   StringRef TypoStr = Typo->getName();
4534   StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4535 
4536   // For very short typos, ignore potential corrections that have a different
4537   // base identifier from the typo or which have a normalized edit distance
4538   // longer than the typo itself.
4539   if (TypoStr.size() < 3 &&
4540       (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4541     return;
4542 
4543   // If the correction is resolved but is not viable, ignore it.
4544   if (Correction.isResolved()) {
4545     checkCorrectionVisibility(SemaRef, Correction);
4546     if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4547       return;
4548   }
4549 
4550   TypoResultList &CList =
4551       CorrectionResults[Correction.getEditDistance(false)][Name];
4552 
4553   if (!CList.empty() && !CList.back().isResolved())
4554     CList.pop_back();
4555   if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4556     auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4557       return TypoCorr.getCorrectionDecl() == NewND;
4558     });
4559     if (RI != CList.end()) {
4560       // The Correction refers to a decl already in the list. No insertion is
4561       // necessary and all further cases will return.
4562 
4563       auto IsDeprecated = [](Decl *D) {
4564         while (D) {
4565           if (D->isDeprecated())
4566             return true;
4567           D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4568         }
4569         return false;
4570       };
4571 
4572       // Prefer non deprecated Corrections over deprecated and only then
4573       // sort using an alphabetical order.
4574       std::pair<bool, std::string> NewKey = {
4575           IsDeprecated(Correction.getFoundDecl()),
4576           Correction.getAsString(SemaRef.getLangOpts())};
4577 
4578       std::pair<bool, std::string> PrevKey = {
4579           IsDeprecated(RI->getFoundDecl()),
4580           RI->getAsString(SemaRef.getLangOpts())};
4581 
4582       if (NewKey < PrevKey)
4583         *RI = Correction;
4584       return;
4585     }
4586   }
4587   if (CList.empty() || Correction.isResolved())
4588     CList.push_back(Correction);
4589 
4590   while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4591     CorrectionResults.erase(std::prev(CorrectionResults.end()));
4592 }
4593 
4594 void TypoCorrectionConsumer::addNamespaces(
4595     const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4596   SearchNamespaces = true;
4597 
4598   for (auto KNPair : KnownNamespaces)
4599     Namespaces.addNameSpecifier(KNPair.first);
4600 
4601   bool SSIsTemplate = false;
4602   if (NestedNameSpecifier *NNS =
4603           (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4604     if (const Type *T = NNS->getAsType())
4605       SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4606   }
4607   // Do not transform this into an iterator-based loop. The loop body can
4608   // trigger the creation of further types (through lazy deserialization) and
4609   // invalid iterators into this list.
4610   auto &Types = SemaRef.getASTContext().getTypes();
4611   for (unsigned I = 0; I != Types.size(); ++I) {
4612     const auto *TI = Types[I];
4613     if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4614       CD = CD->getCanonicalDecl();
4615       if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4616           !CD->isUnion() && CD->getIdentifier() &&
4617           (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4618           (CD->isBeingDefined() || CD->isCompleteDefinition()))
4619         Namespaces.addNameSpecifier(CD);
4620     }
4621   }
4622 }
4623 
4624 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4625   if (++CurrentTCIndex < ValidatedCorrections.size())
4626     return ValidatedCorrections[CurrentTCIndex];
4627 
4628   CurrentTCIndex = ValidatedCorrections.size();
4629   while (!CorrectionResults.empty()) {
4630     auto DI = CorrectionResults.begin();
4631     if (DI->second.empty()) {
4632       CorrectionResults.erase(DI);
4633       continue;
4634     }
4635 
4636     auto RI = DI->second.begin();
4637     if (RI->second.empty()) {
4638       DI->second.erase(RI);
4639       performQualifiedLookups();
4640       continue;
4641     }
4642 
4643     TypoCorrection TC = RI->second.pop_back_val();
4644     if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4645       ValidatedCorrections.push_back(TC);
4646       return ValidatedCorrections[CurrentTCIndex];
4647     }
4648   }
4649   return ValidatedCorrections[0];  // The empty correction.
4650 }
4651 
4652 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4653   IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4654   DeclContext *TempMemberContext = MemberContext;
4655   CXXScopeSpec *TempSS = SS.get();
4656 retry_lookup:
4657   LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4658                             EnteringContext,
4659                             CorrectionValidator->IsObjCIvarLookup,
4660                             Name == Typo && !Candidate.WillReplaceSpecifier());
4661   switch (Result.getResultKind()) {
4662   case LookupResult::NotFound:
4663   case LookupResult::NotFoundInCurrentInstantiation:
4664   case LookupResult::FoundUnresolvedValue:
4665     if (TempSS) {
4666       // Immediately retry the lookup without the given CXXScopeSpec
4667       TempSS = nullptr;
4668       Candidate.WillReplaceSpecifier(true);
4669       goto retry_lookup;
4670     }
4671     if (TempMemberContext) {
4672       if (SS && !TempSS)
4673         TempSS = SS.get();
4674       TempMemberContext = nullptr;
4675       goto retry_lookup;
4676     }
4677     if (SearchNamespaces)
4678       QualifiedResults.push_back(Candidate);
4679     break;
4680 
4681   case LookupResult::Ambiguous:
4682     // We don't deal with ambiguities.
4683     break;
4684 
4685   case LookupResult::Found:
4686   case LookupResult::FoundOverloaded:
4687     // Store all of the Decls for overloaded symbols
4688     for (auto *TRD : Result)
4689       Candidate.addCorrectionDecl(TRD);
4690     checkCorrectionVisibility(SemaRef, Candidate);
4691     if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4692       if (SearchNamespaces)
4693         QualifiedResults.push_back(Candidate);
4694       break;
4695     }
4696     Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4697     return true;
4698   }
4699   return false;
4700 }
4701 
4702 void TypoCorrectionConsumer::performQualifiedLookups() {
4703   unsigned TypoLen = Typo->getName().size();
4704   for (const TypoCorrection &QR : QualifiedResults) {
4705     for (const auto &NSI : Namespaces) {
4706       DeclContext *Ctx = NSI.DeclCtx;
4707       const Type *NSType = NSI.NameSpecifier->getAsType();
4708 
4709       // If the current NestedNameSpecifier refers to a class and the
4710       // current correction candidate is the name of that class, then skip
4711       // it as it is unlikely a qualified version of the class' constructor
4712       // is an appropriate correction.
4713       if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4714                                            nullptr) {
4715         if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4716           continue;
4717       }
4718 
4719       TypoCorrection TC(QR);
4720       TC.ClearCorrectionDecls();
4721       TC.setCorrectionSpecifier(NSI.NameSpecifier);
4722       TC.setQualifierDistance(NSI.EditDistance);
4723       TC.setCallbackDistance(0); // Reset the callback distance
4724 
4725       // If the current correction candidate and namespace combination are
4726       // too far away from the original typo based on the normalized edit
4727       // distance, then skip performing a qualified name lookup.
4728       unsigned TmpED = TC.getEditDistance(true);
4729       if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4730           TypoLen / TmpED < 3)
4731         continue;
4732 
4733       Result.clear();
4734       Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4735       if (!SemaRef.LookupQualifiedName(Result, Ctx))
4736         continue;
4737 
4738       // Any corrections added below will be validated in subsequent
4739       // iterations of the main while() loop over the Consumer's contents.
4740       switch (Result.getResultKind()) {
4741       case LookupResult::Found:
4742       case LookupResult::FoundOverloaded: {
4743         if (SS && SS->isValid()) {
4744           std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4745           std::string OldQualified;
4746           llvm::raw_string_ostream OldOStream(OldQualified);
4747           SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4748           OldOStream << Typo->getName();
4749           // If correction candidate would be an identical written qualified
4750           // identifier, then the existing CXXScopeSpec probably included a
4751           // typedef that didn't get accounted for properly.
4752           if (OldOStream.str() == NewQualified)
4753             break;
4754         }
4755         for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4756              TRD != TRDEnd; ++TRD) {
4757           if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4758                                         NSType ? NSType->getAsCXXRecordDecl()
4759                                                : nullptr,
4760                                         TRD.getPair()) == Sema::AR_accessible)
4761             TC.addCorrectionDecl(*TRD);
4762         }
4763         if (TC.isResolved()) {
4764           TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4765           addCorrection(TC);
4766         }
4767         break;
4768       }
4769       case LookupResult::NotFound:
4770       case LookupResult::NotFoundInCurrentInstantiation:
4771       case LookupResult::Ambiguous:
4772       case LookupResult::FoundUnresolvedValue:
4773         break;
4774       }
4775     }
4776   }
4777   QualifiedResults.clear();
4778 }
4779 
4780 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4781     ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4782     : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4783   if (NestedNameSpecifier *NNS =
4784           CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4785     llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4786     NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4787 
4788     getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4789   }
4790   // Build the list of identifiers that would be used for an absolute
4791   // (from the global context) NestedNameSpecifier referring to the current
4792   // context.
4793   for (DeclContext *C : llvm::reverse(CurContextChain)) {
4794     if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4795       CurContextIdentifiers.push_back(ND->getIdentifier());
4796   }
4797 
4798   // Add the global context as a NestedNameSpecifier
4799   SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4800                       NestedNameSpecifier::GlobalSpecifier(Context), 1};
4801   DistanceMap[1].push_back(SI);
4802 }
4803 
4804 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4805     DeclContext *Start) -> DeclContextList {
4806   assert(Start && "Building a context chain from a null context");
4807   DeclContextList Chain;
4808   for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4809        DC = DC->getLookupParent()) {
4810     NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4811     if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4812         !(ND && ND->isAnonymousNamespace()))
4813       Chain.push_back(DC->getPrimaryContext());
4814   }
4815   return Chain;
4816 }
4817 
4818 unsigned
4819 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4820     DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4821   unsigned NumSpecifiers = 0;
4822   for (DeclContext *C : llvm::reverse(DeclChain)) {
4823     if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4824       NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4825       ++NumSpecifiers;
4826     } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4827       NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4828                                         RD->getTypeForDecl());
4829       ++NumSpecifiers;
4830     }
4831   }
4832   return NumSpecifiers;
4833 }
4834 
4835 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4836     DeclContext *Ctx) {
4837   NestedNameSpecifier *NNS = nullptr;
4838   unsigned NumSpecifiers = 0;
4839   DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4840   DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4841 
4842   // Eliminate common elements from the two DeclContext chains.
4843   for (DeclContext *C : llvm::reverse(CurContextChain)) {
4844     if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4845       break;
4846     NamespaceDeclChain.pop_back();
4847   }
4848 
4849   // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4850   NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4851 
4852   // Add an explicit leading '::' specifier if needed.
4853   if (NamespaceDeclChain.empty()) {
4854     // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4855     NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4856     NumSpecifiers =
4857         buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4858   } else if (NamedDecl *ND =
4859                  dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4860     IdentifierInfo *Name = ND->getIdentifier();
4861     bool SameNameSpecifier = false;
4862     if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
4863       std::string NewNameSpecifier;
4864       llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4865       SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4866       getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4867       NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4868       SpecifierOStream.flush();
4869       SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4870     }
4871     if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
4872       // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4873       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4874       NumSpecifiers =
4875           buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4876     }
4877   }
4878 
4879   // If the built NestedNameSpecifier would be replacing an existing
4880   // NestedNameSpecifier, use the number of component identifiers that
4881   // would need to be changed as the edit distance instead of the number
4882   // of components in the built NestedNameSpecifier.
4883   if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4884     SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4885     getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4886     NumSpecifiers = llvm::ComputeEditDistance(
4887         llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4888         llvm::makeArrayRef(NewNameSpecifierIdentifiers));
4889   }
4890 
4891   SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4892   DistanceMap[NumSpecifiers].push_back(SI);
4893 }
4894 
4895 /// Perform name lookup for a possible result for typo correction.
4896 static void LookupPotentialTypoResult(Sema &SemaRef,
4897                                       LookupResult &Res,
4898                                       IdentifierInfo *Name,
4899                                       Scope *S, CXXScopeSpec *SS,
4900                                       DeclContext *MemberContext,
4901                                       bool EnteringContext,
4902                                       bool isObjCIvarLookup,
4903                                       bool FindHidden) {
4904   Res.suppressDiagnostics();
4905   Res.clear();
4906   Res.setLookupName(Name);
4907   Res.setAllowHidden(FindHidden);
4908   if (MemberContext) {
4909     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4910       if (isObjCIvarLookup) {
4911         if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4912           Res.addDecl(Ivar);
4913           Res.resolveKind();
4914           return;
4915         }
4916       }
4917 
4918       if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4919               Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
4920         Res.addDecl(Prop);
4921         Res.resolveKind();
4922         return;
4923       }
4924     }
4925 
4926     SemaRef.LookupQualifiedName(Res, MemberContext);
4927     return;
4928   }
4929 
4930   SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
4931                            EnteringContext);
4932 
4933   // Fake ivar lookup; this should really be part of
4934   // LookupParsedName.
4935   if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4936     if (Method->isInstanceMethod() && Method->getClassInterface() &&
4937         (Res.empty() ||
4938          (Res.isSingleResult() &&
4939           Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4940        if (ObjCIvarDecl *IV
4941              = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4942          Res.addDecl(IV);
4943          Res.resolveKind();
4944        }
4945      }
4946   }
4947 }
4948 
4949 /// Add keywords to the consumer as possible typo corrections.
4950 static void AddKeywordsToConsumer(Sema &SemaRef,
4951                                   TypoCorrectionConsumer &Consumer,
4952                                   Scope *S, CorrectionCandidateCallback &CCC,
4953                                   bool AfterNestedNameSpecifier) {
4954   if (AfterNestedNameSpecifier) {
4955     // For 'X::', we know exactly which keywords can appear next.
4956     Consumer.addKeywordResult("template");
4957     if (CCC.WantExpressionKeywords)
4958       Consumer.addKeywordResult("operator");
4959     return;
4960   }
4961 
4962   if (CCC.WantObjCSuper)
4963     Consumer.addKeywordResult("super");
4964 
4965   if (CCC.WantTypeSpecifiers) {
4966     // Add type-specifier keywords to the set of results.
4967     static const char *const CTypeSpecs[] = {
4968       "char", "const", "double", "enum", "float", "int", "long", "short",
4969       "signed", "struct", "union", "unsigned", "void", "volatile",
4970       "_Complex", "_Imaginary",
4971       // storage-specifiers as well
4972       "extern", "inline", "static", "typedef"
4973     };
4974 
4975     const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
4976     for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4977       Consumer.addKeywordResult(CTypeSpecs[I]);
4978 
4979     if (SemaRef.getLangOpts().C99)
4980       Consumer.addKeywordResult("restrict");
4981     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
4982       Consumer.addKeywordResult("bool");
4983     else if (SemaRef.getLangOpts().C99)
4984       Consumer.addKeywordResult("_Bool");
4985 
4986     if (SemaRef.getLangOpts().CPlusPlus) {
4987       Consumer.addKeywordResult("class");
4988       Consumer.addKeywordResult("typename");
4989       Consumer.addKeywordResult("wchar_t");
4990 
4991       if (SemaRef.getLangOpts().CPlusPlus11) {
4992         Consumer.addKeywordResult("char16_t");
4993         Consumer.addKeywordResult("char32_t");
4994         Consumer.addKeywordResult("constexpr");
4995         Consumer.addKeywordResult("decltype");
4996         Consumer.addKeywordResult("thread_local");
4997       }
4998     }
4999 
5000     if (SemaRef.getLangOpts().GNUKeywords)
5001       Consumer.addKeywordResult("typeof");
5002   } else if (CCC.WantFunctionLikeCasts) {
5003     static const char *const CastableTypeSpecs[] = {
5004       "char", "double", "float", "int", "long", "short",
5005       "signed", "unsigned", "void"
5006     };
5007     for (auto *kw : CastableTypeSpecs)
5008       Consumer.addKeywordResult(kw);
5009   }
5010 
5011   if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5012     Consumer.addKeywordResult("const_cast");
5013     Consumer.addKeywordResult("dynamic_cast");
5014     Consumer.addKeywordResult("reinterpret_cast");
5015     Consumer.addKeywordResult("static_cast");
5016   }
5017 
5018   if (CCC.WantExpressionKeywords) {
5019     Consumer.addKeywordResult("sizeof");
5020     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5021       Consumer.addKeywordResult("false");
5022       Consumer.addKeywordResult("true");
5023     }
5024 
5025     if (SemaRef.getLangOpts().CPlusPlus) {
5026       static const char *const CXXExprs[] = {
5027         "delete", "new", "operator", "throw", "typeid"
5028       };
5029       const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
5030       for (unsigned I = 0; I != NumCXXExprs; ++I)
5031         Consumer.addKeywordResult(CXXExprs[I]);
5032 
5033       if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
5034           cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
5035         Consumer.addKeywordResult("this");
5036 
5037       if (SemaRef.getLangOpts().CPlusPlus11) {
5038         Consumer.addKeywordResult("alignof");
5039         Consumer.addKeywordResult("nullptr");
5040       }
5041     }
5042 
5043     if (SemaRef.getLangOpts().C11) {
5044       // FIXME: We should not suggest _Alignof if the alignof macro
5045       // is present.
5046       Consumer.addKeywordResult("_Alignof");
5047     }
5048   }
5049 
5050   if (CCC.WantRemainingKeywords) {
5051     if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5052       // Statements.
5053       static const char *const CStmts[] = {
5054         "do", "else", "for", "goto", "if", "return", "switch", "while" };
5055       const unsigned NumCStmts = llvm::array_lengthof(CStmts);
5056       for (unsigned I = 0; I != NumCStmts; ++I)
5057         Consumer.addKeywordResult(CStmts[I]);
5058 
5059       if (SemaRef.getLangOpts().CPlusPlus) {
5060         Consumer.addKeywordResult("catch");
5061         Consumer.addKeywordResult("try");
5062       }
5063 
5064       if (S && S->getBreakParent())
5065         Consumer.addKeywordResult("break");
5066 
5067       if (S && S->getContinueParent())
5068         Consumer.addKeywordResult("continue");
5069 
5070       if (SemaRef.getCurFunction() &&
5071           !SemaRef.getCurFunction()->SwitchStack.empty()) {
5072         Consumer.addKeywordResult("case");
5073         Consumer.addKeywordResult("default");
5074       }
5075     } else {
5076       if (SemaRef.getLangOpts().CPlusPlus) {
5077         Consumer.addKeywordResult("namespace");
5078         Consumer.addKeywordResult("template");
5079       }
5080 
5081       if (S && S->isClassScope()) {
5082         Consumer.addKeywordResult("explicit");
5083         Consumer.addKeywordResult("friend");
5084         Consumer.addKeywordResult("mutable");
5085         Consumer.addKeywordResult("private");
5086         Consumer.addKeywordResult("protected");
5087         Consumer.addKeywordResult("public");
5088         Consumer.addKeywordResult("virtual");
5089       }
5090     }
5091 
5092     if (SemaRef.getLangOpts().CPlusPlus) {
5093       Consumer.addKeywordResult("using");
5094 
5095       if (SemaRef.getLangOpts().CPlusPlus11)
5096         Consumer.addKeywordResult("static_assert");
5097     }
5098   }
5099 }
5100 
5101 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5102     const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5103     Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5104     DeclContext *MemberContext, bool EnteringContext,
5105     const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5106 
5107   if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5108       DisableTypoCorrection)
5109     return nullptr;
5110 
5111   // In Microsoft mode, don't perform typo correction in a template member
5112   // function dependent context because it interferes with the "lookup into
5113   // dependent bases of class templates" feature.
5114   if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5115       isa<CXXMethodDecl>(CurContext))
5116     return nullptr;
5117 
5118   // We only attempt to correct typos for identifiers.
5119   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5120   if (!Typo)
5121     return nullptr;
5122 
5123   // If the scope specifier itself was invalid, don't try to correct
5124   // typos.
5125   if (SS && SS->isInvalid())
5126     return nullptr;
5127 
5128   // Never try to correct typos during any kind of code synthesis.
5129   if (!CodeSynthesisContexts.empty())
5130     return nullptr;
5131 
5132   // Don't try to correct 'super'.
5133   if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5134     return nullptr;
5135 
5136   // Abort if typo correction already failed for this specific typo.
5137   IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
5138   if (locs != TypoCorrectionFailures.end() &&
5139       locs->second.count(TypoName.getLoc()))
5140     return nullptr;
5141 
5142   // Don't try to correct the identifier "vector" when in AltiVec mode.
5143   // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5144   // remove this workaround.
5145   if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
5146     return nullptr;
5147 
5148   // Provide a stop gap for files that are just seriously broken.  Trying
5149   // to correct all typos can turn into a HUGE performance penalty, causing
5150   // some files to take minutes to get rejected by the parser.
5151   unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5152   if (Limit && TyposCorrected >= Limit)
5153     return nullptr;
5154   ++TyposCorrected;
5155 
5156   // If we're handling a missing symbol error, using modules, and the
5157   // special search all modules option is used, look for a missing import.
5158   if (ErrorRecovery && getLangOpts().Modules &&
5159       getLangOpts().ModulesSearchAll) {
5160     // The following has the side effect of loading the missing module.
5161     getModuleLoader().lookupMissingImports(Typo->getName(),
5162                                            TypoName.getBeginLoc());
5163   }
5164 
5165   // Extend the lifetime of the callback. We delayed this until here
5166   // to avoid allocations in the hot path (which is where no typo correction
5167   // occurs). Note that CorrectionCandidateCallback is polymorphic and
5168   // initially stack-allocated.
5169   std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5170   auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5171       *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5172       EnteringContext);
5173 
5174   // Perform name lookup to find visible, similarly-named entities.
5175   bool IsUnqualifiedLookup = false;
5176   DeclContext *QualifiedDC = MemberContext;
5177   if (MemberContext) {
5178     LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
5179 
5180     // Look in qualified interfaces.
5181     if (OPT) {
5182       for (auto *I : OPT->quals())
5183         LookupVisibleDecls(I, LookupKind, *Consumer);
5184     }
5185   } else if (SS && SS->isSet()) {
5186     QualifiedDC = computeDeclContext(*SS, EnteringContext);
5187     if (!QualifiedDC)
5188       return nullptr;
5189 
5190     LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
5191   } else {
5192     IsUnqualifiedLookup = true;
5193   }
5194 
5195   // Determine whether we are going to search in the various namespaces for
5196   // corrections.
5197   bool SearchNamespaces
5198     = getLangOpts().CPlusPlus &&
5199       (IsUnqualifiedLookup || (SS && SS->isSet()));
5200 
5201   if (IsUnqualifiedLookup || SearchNamespaces) {
5202     // For unqualified lookup, look through all of the names that we have
5203     // seen in this translation unit.
5204     // FIXME: Re-add the ability to skip very unlikely potential corrections.
5205     for (const auto &I : Context.Idents)
5206       Consumer->FoundName(I.getKey());
5207 
5208     // Walk through identifiers in external identifier sources.
5209     // FIXME: Re-add the ability to skip very unlikely potential corrections.
5210     if (IdentifierInfoLookup *External
5211                             = Context.Idents.getExternalIdentifierLookup()) {
5212       std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5213       do {
5214         StringRef Name = Iter->Next();
5215         if (Name.empty())
5216           break;
5217 
5218         Consumer->FoundName(Name);
5219       } while (true);
5220     }
5221   }
5222 
5223   AddKeywordsToConsumer(*this, *Consumer, S,
5224                         *Consumer->getCorrectionValidator(),
5225                         SS && SS->isNotEmpty());
5226 
5227   // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5228   // to search those namespaces.
5229   if (SearchNamespaces) {
5230     // Load any externally-known namespaces.
5231     if (ExternalSource && !LoadedExternalKnownNamespaces) {
5232       SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5233       LoadedExternalKnownNamespaces = true;
5234       ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5235       for (auto *N : ExternalKnownNamespaces)
5236         KnownNamespaces[N] = true;
5237     }
5238 
5239     Consumer->addNamespaces(KnownNamespaces);
5240   }
5241 
5242   return Consumer;
5243 }
5244 
5245 /// Try to "correct" a typo in the source code by finding
5246 /// visible declarations whose names are similar to the name that was
5247 /// present in the source code.
5248 ///
5249 /// \param TypoName the \c DeclarationNameInfo structure that contains
5250 /// the name that was present in the source code along with its location.
5251 ///
5252 /// \param LookupKind the name-lookup criteria used to search for the name.
5253 ///
5254 /// \param S the scope in which name lookup occurs.
5255 ///
5256 /// \param SS the nested-name-specifier that precedes the name we're
5257 /// looking for, if present.
5258 ///
5259 /// \param CCC A CorrectionCandidateCallback object that provides further
5260 /// validation of typo correction candidates. It also provides flags for
5261 /// determining the set of keywords permitted.
5262 ///
5263 /// \param MemberContext if non-NULL, the context in which to look for
5264 /// a member access expression.
5265 ///
5266 /// \param EnteringContext whether we're entering the context described by
5267 /// the nested-name-specifier SS.
5268 ///
5269 /// \param OPT when non-NULL, the search for visible declarations will
5270 /// also walk the protocols in the qualified interfaces of \p OPT.
5271 ///
5272 /// \returns a \c TypoCorrection containing the corrected name if the typo
5273 /// along with information such as the \c NamedDecl where the corrected name
5274 /// was declared, and any additional \c NestedNameSpecifier needed to access
5275 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
5276 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
5277                                  Sema::LookupNameKind LookupKind,
5278                                  Scope *S, CXXScopeSpec *SS,
5279                                  CorrectionCandidateCallback &CCC,
5280                                  CorrectTypoKind Mode,
5281                                  DeclContext *MemberContext,
5282                                  bool EnteringContext,
5283                                  const ObjCObjectPointerType *OPT,
5284                                  bool RecordFailure) {
5285   // Always let the ExternalSource have the first chance at correction, even
5286   // if we would otherwise have given up.
5287   if (ExternalSource) {
5288     if (TypoCorrection Correction =
5289             ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5290                                         MemberContext, EnteringContext, OPT))
5291       return Correction;
5292   }
5293 
5294   // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5295   // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5296   // some instances of CTC_Unknown, while WantRemainingKeywords is true
5297   // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5298   bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5299 
5300   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5301   auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5302                                              MemberContext, EnteringContext,
5303                                              OPT, Mode == CTK_ErrorRecovery);
5304 
5305   if (!Consumer)
5306     return TypoCorrection();
5307 
5308   // If we haven't found anything, we're done.
5309   if (Consumer->empty())
5310     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5311 
5312   // Make sure the best edit distance (prior to adding any namespace qualifiers)
5313   // is not more that about a third of the length of the typo's identifier.
5314   unsigned ED = Consumer->getBestEditDistance(true);
5315   unsigned TypoLen = Typo->getName().size();
5316   if (ED > 0 && TypoLen / ED < 3)
5317     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5318 
5319   TypoCorrection BestTC = Consumer->getNextCorrection();
5320   TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5321   if (!BestTC)
5322     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5323 
5324   ED = BestTC.getEditDistance();
5325 
5326   if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5327     // If this was an unqualified lookup and we believe the callback
5328     // object wouldn't have filtered out possible corrections, note
5329     // that no correction was found.
5330     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5331   }
5332 
5333   // If only a single name remains, return that result.
5334   if (!SecondBestTC ||
5335       SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5336     const TypoCorrection &Result = BestTC;
5337 
5338     // Don't correct to a keyword that's the same as the typo; the keyword
5339     // wasn't actually in scope.
5340     if (ED == 0 && Result.isKeyword())
5341       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5342 
5343     TypoCorrection TC = Result;
5344     TC.setCorrectionRange(SS, TypoName);
5345     checkCorrectionVisibility(*this, TC);
5346     return TC;
5347   } else if (SecondBestTC && ObjCMessageReceiver) {
5348     // Prefer 'super' when we're completing in a message-receiver
5349     // context.
5350 
5351     if (BestTC.getCorrection().getAsString() != "super") {
5352       if (SecondBestTC.getCorrection().getAsString() == "super")
5353         BestTC = SecondBestTC;
5354       else if ((*Consumer)["super"].front().isKeyword())
5355         BestTC = (*Consumer)["super"].front();
5356     }
5357     // Don't correct to a keyword that's the same as the typo; the keyword
5358     // wasn't actually in scope.
5359     if (BestTC.getEditDistance() == 0 ||
5360         BestTC.getCorrection().getAsString() != "super")
5361       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5362 
5363     BestTC.setCorrectionRange(SS, TypoName);
5364     return BestTC;
5365   }
5366 
5367   // Record the failure's location if needed and return an empty correction. If
5368   // this was an unqualified lookup and we believe the callback object did not
5369   // filter out possible corrections, also cache the failure for the typo.
5370   return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5371 }
5372 
5373 /// Try to "correct" a typo in the source code by finding
5374 /// visible declarations whose names are similar to the name that was
5375 /// present in the source code.
5376 ///
5377 /// \param TypoName the \c DeclarationNameInfo structure that contains
5378 /// the name that was present in the source code along with its location.
5379 ///
5380 /// \param LookupKind the name-lookup criteria used to search for the name.
5381 ///
5382 /// \param S the scope in which name lookup occurs.
5383 ///
5384 /// \param SS the nested-name-specifier that precedes the name we're
5385 /// looking for, if present.
5386 ///
5387 /// \param CCC A CorrectionCandidateCallback object that provides further
5388 /// validation of typo correction candidates. It also provides flags for
5389 /// determining the set of keywords permitted.
5390 ///
5391 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
5392 /// diagnostics when the actual typo correction is attempted.
5393 ///
5394 /// \param TRC A TypoRecoveryCallback functor that will be used to build an
5395 /// Expr from a typo correction candidate.
5396 ///
5397 /// \param MemberContext if non-NULL, the context in which to look for
5398 /// a member access expression.
5399 ///
5400 /// \param EnteringContext whether we're entering the context described by
5401 /// the nested-name-specifier SS.
5402 ///
5403 /// \param OPT when non-NULL, the search for visible declarations will
5404 /// also walk the protocols in the qualified interfaces of \p OPT.
5405 ///
5406 /// \returns a new \c TypoExpr that will later be replaced in the AST with an
5407 /// Expr representing the result of performing typo correction, or nullptr if
5408 /// typo correction is not possible. If nullptr is returned, no diagnostics will
5409 /// be emitted and it is the responsibility of the caller to emit any that are
5410 /// needed.
5411 TypoExpr *Sema::CorrectTypoDelayed(
5412     const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5413     Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5414     TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
5415     DeclContext *MemberContext, bool EnteringContext,
5416     const ObjCObjectPointerType *OPT) {
5417   auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5418                                              MemberContext, EnteringContext,
5419                                              OPT, Mode == CTK_ErrorRecovery);
5420 
5421   // Give the external sema source a chance to correct the typo.
5422   TypoCorrection ExternalTypo;
5423   if (ExternalSource && Consumer) {
5424     ExternalTypo = ExternalSource->CorrectTypo(
5425         TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5426         MemberContext, EnteringContext, OPT);
5427     if (ExternalTypo)
5428       Consumer->addCorrection(ExternalTypo);
5429   }
5430 
5431   if (!Consumer || Consumer->empty())
5432     return nullptr;
5433 
5434   // Make sure the best edit distance (prior to adding any namespace qualifiers)
5435   // is not more that about a third of the length of the typo's identifier.
5436   unsigned ED = Consumer->getBestEditDistance(true);
5437   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5438   if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
5439     return nullptr;
5440   ExprEvalContexts.back().NumTypos++;
5441   return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
5442                            TypoName.getLoc());
5443 }
5444 
5445 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5446   if (!CDecl) return;
5447 
5448   if (isKeyword())
5449     CorrectionDecls.clear();
5450 
5451   CorrectionDecls.push_back(CDecl);
5452 
5453   if (!CorrectionName)
5454     CorrectionName = CDecl->getDeclName();
5455 }
5456 
5457 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5458   if (CorrectionNameSpec) {
5459     std::string tmpBuffer;
5460     llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5461     CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
5462     PrefixOStream << CorrectionName;
5463     return PrefixOStream.str();
5464   }
5465 
5466   return CorrectionName.getAsString();
5467 }
5468 
5469 bool CorrectionCandidateCallback::ValidateCandidate(
5470     const TypoCorrection &candidate) {
5471   if (!candidate.isResolved())
5472     return true;
5473 
5474   if (candidate.isKeyword())
5475     return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5476            WantRemainingKeywords || WantObjCSuper;
5477 
5478   bool HasNonType = false;
5479   bool HasStaticMethod = false;
5480   bool HasNonStaticMethod = false;
5481   for (Decl *D : candidate) {
5482     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5483       D = FTD->getTemplatedDecl();
5484     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5485       if (Method->isStatic())
5486         HasStaticMethod = true;
5487       else
5488         HasNonStaticMethod = true;
5489     }
5490     if (!isa<TypeDecl>(D))
5491       HasNonType = true;
5492   }
5493 
5494   if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5495       !candidate.getCorrectionSpecifier())
5496     return false;
5497 
5498   return WantTypeSpecifiers || HasNonType;
5499 }
5500 
5501 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
5502                                              bool HasExplicitTemplateArgs,
5503                                              MemberExpr *ME)
5504     : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5505       CurContext(SemaRef.CurContext), MemberFn(ME) {
5506   WantTypeSpecifiers = false;
5507   WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5508                           !HasExplicitTemplateArgs && NumArgs == 1;
5509   WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5510   WantRemainingKeywords = false;
5511 }
5512 
5513 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5514   if (!candidate.getCorrectionDecl())
5515     return candidate.isKeyword();
5516 
5517   for (auto *C : candidate) {
5518     FunctionDecl *FD = nullptr;
5519     NamedDecl *ND = C->getUnderlyingDecl();
5520     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5521       FD = FTD->getTemplatedDecl();
5522     if (!HasExplicitTemplateArgs && !FD) {
5523       if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5524         // If the Decl is neither a function nor a template function,
5525         // determine if it is a pointer or reference to a function. If so,
5526         // check against the number of arguments expected for the pointee.
5527         QualType ValType = cast<ValueDecl>(ND)->getType();
5528         if (ValType.isNull())
5529           continue;
5530         if (ValType->isAnyPointerType() || ValType->isReferenceType())
5531           ValType = ValType->getPointeeType();
5532         if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5533           if (FPT->getNumParams() == NumArgs)
5534             return true;
5535       }
5536     }
5537 
5538     // A typo for a function-style cast can look like a function call in C++.
5539     if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5540                                  : isa<TypeDecl>(ND)) &&
5541         CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5542       // Only a class or class template can take two or more arguments.
5543       return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5544 
5545     // Skip the current candidate if it is not a FunctionDecl or does not accept
5546     // the current number of arguments.
5547     if (!FD || !(FD->getNumParams() >= NumArgs &&
5548                  FD->getMinRequiredArguments() <= NumArgs))
5549       continue;
5550 
5551     // If the current candidate is a non-static C++ method, skip the candidate
5552     // unless the method being corrected--or the current DeclContext, if the
5553     // function being corrected is not a method--is a method in the same class
5554     // or a descendent class of the candidate's parent class.
5555     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5556       if (MemberFn || !MD->isStatic()) {
5557         CXXMethodDecl *CurMD =
5558             MemberFn
5559                 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5560                 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
5561         CXXRecordDecl *CurRD =
5562             CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5563         CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5564         if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5565           continue;
5566       }
5567     }
5568     return true;
5569   }
5570   return false;
5571 }
5572 
5573 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5574                         const PartialDiagnostic &TypoDiag,
5575                         bool ErrorRecovery) {
5576   diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5577                ErrorRecovery);
5578 }
5579 
5580 /// Find which declaration we should import to provide the definition of
5581 /// the given declaration.
5582 static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5583   if (VarDecl *VD = dyn_cast<VarDecl>(D))
5584     return VD->getDefinition();
5585   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5586     return FD->getDefinition();
5587   if (TagDecl *TD = dyn_cast<TagDecl>(D))
5588     return TD->getDefinition();
5589   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
5590     return ID->getDefinition();
5591   if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
5592     return PD->getDefinition();
5593   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5594     if (NamedDecl *TTD = TD->getTemplatedDecl())
5595       return getDefinitionToImport(TTD);
5596   return nullptr;
5597 }
5598 
5599 void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
5600                                  MissingImportKind MIK, bool Recover) {
5601   // Suggest importing a module providing the definition of this entity, if
5602   // possible.
5603   NamedDecl *Def = getDefinitionToImport(Decl);
5604   if (!Def)
5605     Def = Decl;
5606 
5607   Module *Owner = getOwningModule(Def);
5608   assert(Owner && "definition of hidden declaration is not in a module");
5609 
5610   llvm::SmallVector<Module*, 8> OwningModules;
5611   OwningModules.push_back(Owner);
5612   auto Merged = Context.getModulesWithMergedDefinition(Def);
5613   OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5614 
5615   diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5616                         Recover);
5617 }
5618 
5619 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5620 /// suggesting the addition of a #include of the specified file.
5621 static std::string getHeaderNameForHeader(Preprocessor &PP, const FileEntry *E,
5622                                           llvm::StringRef IncludingFile) {
5623   bool IsSystem = false;
5624   auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5625       E, IncludingFile, &IsSystem);
5626   return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5627 }
5628 
5629 void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5630                                  SourceLocation DeclLoc,
5631                                  ArrayRef<Module *> Modules,
5632                                  MissingImportKind MIK, bool Recover) {
5633   assert(!Modules.empty());
5634 
5635   auto NotePrevious = [&] {
5636     // FIXME: Suppress the note backtrace even under
5637     // -fdiagnostics-show-note-include-stack. We don't care how this
5638     // declaration was previously reached.
5639     Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5640   };
5641 
5642   // Weed out duplicates from module list.
5643   llvm::SmallVector<Module*, 8> UniqueModules;
5644   llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5645   for (auto *M : Modules) {
5646     if (M->Kind == Module::GlobalModuleFragment)
5647       continue;
5648     if (UniqueModuleSet.insert(M).second)
5649       UniqueModules.push_back(M);
5650   }
5651 
5652   // Try to find a suitable header-name to #include.
5653   std::string HeaderName;
5654   if (const FileEntry *Header =
5655           PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5656     if (const FileEntry *FE =
5657             SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5658       HeaderName = getHeaderNameForHeader(PP, Header, FE->tryGetRealPathName());
5659   }
5660 
5661   // If we have a #include we should suggest, or if all definition locations
5662   // were in global module fragments, don't suggest an import.
5663   if (!HeaderName.empty() || UniqueModules.empty()) {
5664     // FIXME: Find a smart place to suggest inserting a #include, and add
5665     // a FixItHint there.
5666     Diag(UseLoc, diag::err_module_unimported_use_header)
5667         << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5668     // Produce a note showing where the entity was declared.
5669     NotePrevious();
5670     if (Recover)
5671       createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5672     return;
5673   }
5674 
5675   Modules = UniqueModules;
5676 
5677   if (Modules.size() > 1) {
5678     std::string ModuleList;
5679     unsigned N = 0;
5680     for (Module *M : Modules) {
5681       ModuleList += "\n        ";
5682       if (++N == 5 && N != Modules.size()) {
5683         ModuleList += "[...]";
5684         break;
5685       }
5686       ModuleList += M->getFullModuleName();
5687     }
5688 
5689     Diag(UseLoc, diag::err_module_unimported_use_multiple)
5690       << (int)MIK << Decl << ModuleList;
5691   } else {
5692     // FIXME: Add a FixItHint that imports the corresponding module.
5693     Diag(UseLoc, diag::err_module_unimported_use)
5694       << (int)MIK << Decl << Modules[0]->getFullModuleName();
5695   }
5696 
5697   NotePrevious();
5698 
5699   // Try to recover by implicitly importing this module.
5700   if (Recover)
5701     createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5702 }
5703 
5704 /// Diagnose a successfully-corrected typo. Separated from the correction
5705 /// itself to allow external validation of the result, etc.
5706 ///
5707 /// \param Correction The result of performing typo correction.
5708 /// \param TypoDiag The diagnostic to produce. This will have the corrected
5709 ///        string added to it (and usually also a fixit).
5710 /// \param PrevNote A note to use when indicating the location of the entity to
5711 ///        which we are correcting. Will have the correction string added to it.
5712 /// \param ErrorRecovery If \c true (the default), the caller is going to
5713 ///        recover from the typo as if the corrected string had been typed.
5714 ///        In this case, \c PDiag must be an error, and we will attach a fixit
5715 ///        to it.
5716 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5717                         const PartialDiagnostic &TypoDiag,
5718                         const PartialDiagnostic &PrevNote,
5719                         bool ErrorRecovery) {
5720   std::string CorrectedStr = Correction.getAsString(getLangOpts());
5721   std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5722   FixItHint FixTypo = FixItHint::CreateReplacement(
5723       Correction.getCorrectionRange(), CorrectedStr);
5724 
5725   // Maybe we're just missing a module import.
5726   if (Correction.requiresImport()) {
5727     NamedDecl *Decl = Correction.getFoundDecl();
5728     assert(Decl && "import required but no declaration to import");
5729 
5730     diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5731                           MissingImportKind::Declaration, ErrorRecovery);
5732     return;
5733   }
5734 
5735   Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5736     << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5737 
5738   NamedDecl *ChosenDecl =
5739       Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5740   if (PrevNote.getDiagID() && ChosenDecl)
5741     Diag(ChosenDecl->getLocation(), PrevNote)
5742       << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5743 
5744   // Add any extra diagnostics.
5745   for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5746     Diag(Correction.getCorrectionRange().getBegin(), PD);
5747 }
5748 
5749 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5750                                   TypoDiagnosticGenerator TDG,
5751                                   TypoRecoveryCallback TRC,
5752                                   SourceLocation TypoLoc) {
5753   assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5754   auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
5755   auto &State = DelayedTypos[TE];
5756   State.Consumer = std::move(TCC);
5757   State.DiagHandler = std::move(TDG);
5758   State.RecoveryHandler = std::move(TRC);
5759   if (TE)
5760     TypoExprs.push_back(TE);
5761   return TE;
5762 }
5763 
5764 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5765   auto Entry = DelayedTypos.find(TE);
5766   assert(Entry != DelayedTypos.end() &&
5767          "Failed to get the state for a TypoExpr!");
5768   return Entry->second;
5769 }
5770 
5771 void Sema::clearDelayedTypo(TypoExpr *TE) {
5772   DelayedTypos.erase(TE);
5773 }
5774 
5775 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5776   DeclarationNameInfo Name(II, IILoc);
5777   LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5778   R.suppressDiagnostics();
5779   R.setHideTags(false);
5780   LookupName(R, S);
5781   R.dump();
5782 }
5783