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