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