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