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