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