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 (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1179       Entity = Pattern;
1180   } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1181     if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1182       Entity = getInstantiatedFrom(ED, MSInfo);
1183   } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1184     // FIXME: Map from variable template specializations back to the template.
1185     if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1186       Entity = getInstantiatedFrom(VD, MSInfo);
1187   }
1188 
1189   // Walk up to the containing context. That might also have been instantiated
1190   // from a template.
1191   DeclContext *Context = Entity->getDeclContext();
1192   if (Context->isFileContext())
1193     return Entity->getOwningModule();
1194   return getDefiningModule(cast<Decl>(Context));
1195 }
1196 
1197 llvm::DenseSet<Module*> &Sema::getLookupModules() {
1198   unsigned N = ActiveTemplateInstantiations.size();
1199   for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1200        I != N; ++I) {
1201     Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1202     if (M && !LookupModulesCache.insert(M).second)
1203       M = nullptr;
1204     ActiveTemplateInstantiationLookupModules.push_back(M);
1205   }
1206   return LookupModulesCache;
1207 }
1208 
1209 /// \brief Determine whether a declaration is visible to name lookup.
1210 ///
1211 /// This routine determines whether the declaration D is visible in the current
1212 /// lookup context, taking into account the current template instantiation
1213 /// stack. During template instantiation, a declaration is visible if it is
1214 /// visible from a module containing any entity on the template instantiation
1215 /// path (by instantiating a template, you allow it to see the declarations that
1216 /// your module can see, including those later on in your module).
1217 bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1218   assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1219          "should not call this: not in slow case");
1220   Module *DeclModule = D->getOwningModule();
1221   assert(DeclModule && "hidden decl not from a module");
1222 
1223   // Find the extra places where we need to look.
1224   llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1225   if (LookupModules.empty())
1226     return false;
1227 
1228   // If our lookup set contains the decl's module, it's visible.
1229   if (LookupModules.count(DeclModule))
1230     return true;
1231 
1232   // If the declaration isn't exported, it's not visible in any other module.
1233   if (D->isModulePrivate())
1234     return false;
1235 
1236   // Check whether DeclModule is transitively exported to an import of
1237   // the lookup set.
1238   for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1239                                           E = LookupModules.end();
1240        I != E; ++I)
1241     if ((*I)->isModuleVisible(DeclModule))
1242       return true;
1243   return false;
1244 }
1245 
1246 /// \brief Retrieve the visible declaration corresponding to D, if any.
1247 ///
1248 /// This routine determines whether the declaration D is visible in the current
1249 /// module, with the current imports. If not, it checks whether any
1250 /// redeclaration of D is visible, and if so, returns that declaration.
1251 ///
1252 /// \returns D, or a visible previous declaration of D, whichever is more recent
1253 /// and visible. If no declaration of D is visible, returns null.
1254 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1255   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
1256 
1257   for (auto RD : D->redecls()) {
1258     if (auto ND = dyn_cast<NamedDecl>(RD)) {
1259       if (LookupResult::isVisible(SemaRef, ND))
1260         return ND;
1261     }
1262   }
1263 
1264   return nullptr;
1265 }
1266 
1267 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1268   return findAcceptableDecl(SemaRef, D);
1269 }
1270 
1271 /// @brief Perform unqualified name lookup starting from a given
1272 /// scope.
1273 ///
1274 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1275 /// used to find names within the current scope. For example, 'x' in
1276 /// @code
1277 /// int x;
1278 /// int f() {
1279 ///   return x; // unqualified name look finds 'x' in the global scope
1280 /// }
1281 /// @endcode
1282 ///
1283 /// Different lookup criteria can find different names. For example, a
1284 /// particular scope can have both a struct and a function of the same
1285 /// name, and each can be found by certain lookup criteria. For more
1286 /// information about lookup criteria, see the documentation for the
1287 /// class LookupCriteria.
1288 ///
1289 /// @param S        The scope from which unqualified name lookup will
1290 /// begin. If the lookup criteria permits, name lookup may also search
1291 /// in the parent scopes.
1292 ///
1293 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1294 /// look up and the lookup kind), and is updated with the results of lookup
1295 /// including zero or more declarations and possibly additional information
1296 /// used to diagnose ambiguities.
1297 ///
1298 /// @returns \c true if lookup succeeded and false otherwise.
1299 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1300   DeclarationName Name = R.getLookupName();
1301   if (!Name) return false;
1302 
1303   LookupNameKind NameKind = R.getLookupKind();
1304 
1305   if (!getLangOpts().CPlusPlus) {
1306     // Unqualified name lookup in C/Objective-C is purely lexical, so
1307     // search in the declarations attached to the name.
1308     if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1309       // Find the nearest non-transparent declaration scope.
1310       while (!(S->getFlags() & Scope::DeclScope) ||
1311              (S->getEntity() && S->getEntity()->isTransparentContext()))
1312         S = S->getParent();
1313     }
1314 
1315     // When performing a scope lookup, we want to find local extern decls.
1316     FindLocalExternScope FindLocals(R);
1317 
1318     // Scan up the scope chain looking for a decl that matches this
1319     // identifier that is in the appropriate namespace.  This search
1320     // should not take long, as shadowing of names is uncommon, and
1321     // deep shadowing is extremely uncommon.
1322     bool LeftStartingScope = false;
1323 
1324     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1325                                    IEnd = IdResolver.end();
1326          I != IEnd; ++I)
1327       if (NamedDecl *D = R.getAcceptableDecl(*I)) {
1328         if (NameKind == LookupRedeclarationWithLinkage) {
1329           // Determine whether this (or a previous) declaration is
1330           // out-of-scope.
1331           if (!LeftStartingScope && !S->isDeclScope(*I))
1332             LeftStartingScope = true;
1333 
1334           // If we found something outside of our starting scope that
1335           // does not have linkage, skip it.
1336           if (LeftStartingScope && !((*I)->hasLinkage())) {
1337             R.setShadowed();
1338             continue;
1339           }
1340         }
1341         else if (NameKind == LookupObjCImplicitSelfParam &&
1342                  !isa<ImplicitParamDecl>(*I))
1343           continue;
1344 
1345         R.addDecl(D);
1346 
1347         // Check whether there are any other declarations with the same name
1348         // and in the same scope.
1349         if (I != IEnd) {
1350           // Find the scope in which this declaration was declared (if it
1351           // actually exists in a Scope).
1352           while (S && !S->isDeclScope(D))
1353             S = S->getParent();
1354 
1355           // If the scope containing the declaration is the translation unit,
1356           // then we'll need to perform our checks based on the matching
1357           // DeclContexts rather than matching scopes.
1358           if (S && isNamespaceOrTranslationUnitScope(S))
1359             S = nullptr;
1360 
1361           // Compute the DeclContext, if we need it.
1362           DeclContext *DC = nullptr;
1363           if (!S)
1364             DC = (*I)->getDeclContext()->getRedeclContext();
1365 
1366           IdentifierResolver::iterator LastI = I;
1367           for (++LastI; LastI != IEnd; ++LastI) {
1368             if (S) {
1369               // Match based on scope.
1370               if (!S->isDeclScope(*LastI))
1371                 break;
1372             } else {
1373               // Match based on DeclContext.
1374               DeclContext *LastDC
1375                 = (*LastI)->getDeclContext()->getRedeclContext();
1376               if (!LastDC->Equals(DC))
1377                 break;
1378             }
1379 
1380             // If the declaration is in the right namespace and visible, add it.
1381             if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1382               R.addDecl(LastD);
1383           }
1384 
1385           R.resolveKind();
1386         }
1387 
1388         return true;
1389       }
1390   } else {
1391     // Perform C++ unqualified name lookup.
1392     if (CppLookupName(R, S))
1393       return true;
1394   }
1395 
1396   // If we didn't find a use of this identifier, and if the identifier
1397   // corresponds to a compiler builtin, create the decl object for the builtin
1398   // now, injecting it into translation unit scope, and return it.
1399   if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1400     return true;
1401 
1402   // If we didn't find a use of this identifier, the ExternalSource
1403   // may be able to handle the situation.
1404   // Note: some lookup failures are expected!
1405   // See e.g. R.isForRedeclaration().
1406   return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1407 }
1408 
1409 /// @brief Perform qualified name lookup in the namespaces nominated by
1410 /// using directives by the given context.
1411 ///
1412 /// C++98 [namespace.qual]p2:
1413 ///   Given X::m (where X is a user-declared namespace), or given \::m
1414 ///   (where X is the global namespace), let S be the set of all
1415 ///   declarations of m in X and in the transitive closure of all
1416 ///   namespaces nominated by using-directives in X and its used
1417 ///   namespaces, except that using-directives are ignored in any
1418 ///   namespace, including X, directly containing one or more
1419 ///   declarations of m. No namespace is searched more than once in
1420 ///   the lookup of a name. If S is the empty set, the program is
1421 ///   ill-formed. Otherwise, if S has exactly one member, or if the
1422 ///   context of the reference is a using-declaration
1423 ///   (namespace.udecl), S is the required set of declarations of
1424 ///   m. Otherwise if the use of m is not one that allows a unique
1425 ///   declaration to be chosen from S, the program is ill-formed.
1426 ///
1427 /// C++98 [namespace.qual]p5:
1428 ///   During the lookup of a qualified namespace member name, if the
1429 ///   lookup finds more than one declaration of the member, and if one
1430 ///   declaration introduces a class name or enumeration name and the
1431 ///   other declarations either introduce the same object, the same
1432 ///   enumerator or a set of functions, the non-type name hides the
1433 ///   class or enumeration name if and only if the declarations are
1434 ///   from the same namespace; otherwise (the declarations are from
1435 ///   different namespaces), the program is ill-formed.
1436 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1437                                                  DeclContext *StartDC) {
1438   assert(StartDC->isFileContext() && "start context is not a file context");
1439 
1440   DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1441   if (UsingDirectives.begin() == UsingDirectives.end()) return false;
1442 
1443   // We have at least added all these contexts to the queue.
1444   llvm::SmallPtrSet<DeclContext*, 8> Visited;
1445   Visited.insert(StartDC);
1446 
1447   // We have not yet looked into these namespaces, much less added
1448   // their "using-children" to the queue.
1449   SmallVector<NamespaceDecl*, 8> Queue;
1450 
1451   // We have already looked into the initial namespace; seed the queue
1452   // with its using-children.
1453   for (auto *I : UsingDirectives) {
1454     NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
1455     if (Visited.insert(ND))
1456       Queue.push_back(ND);
1457   }
1458 
1459   // The easiest way to implement the restriction in [namespace.qual]p5
1460   // is to check whether any of the individual results found a tag
1461   // and, if so, to declare an ambiguity if the final result is not
1462   // a tag.
1463   bool FoundTag = false;
1464   bool FoundNonTag = false;
1465 
1466   LookupResult LocalR(LookupResult::Temporary, R);
1467 
1468   bool Found = false;
1469   while (!Queue.empty()) {
1470     NamespaceDecl *ND = Queue.pop_back_val();
1471 
1472     // We go through some convolutions here to avoid copying results
1473     // between LookupResults.
1474     bool UseLocal = !R.empty();
1475     LookupResult &DirectR = UseLocal ? LocalR : R;
1476     bool FoundDirect = LookupDirect(S, DirectR, ND);
1477 
1478     if (FoundDirect) {
1479       // First do any local hiding.
1480       DirectR.resolveKind();
1481 
1482       // If the local result is a tag, remember that.
1483       if (DirectR.isSingleTagDecl())
1484         FoundTag = true;
1485       else
1486         FoundNonTag = true;
1487 
1488       // Append the local results to the total results if necessary.
1489       if (UseLocal) {
1490         R.addAllDecls(LocalR);
1491         LocalR.clear();
1492       }
1493     }
1494 
1495     // If we find names in this namespace, ignore its using directives.
1496     if (FoundDirect) {
1497       Found = true;
1498       continue;
1499     }
1500 
1501     for (auto I : ND->using_directives()) {
1502       NamespaceDecl *Nom = I->getNominatedNamespace();
1503       if (Visited.insert(Nom))
1504         Queue.push_back(Nom);
1505     }
1506   }
1507 
1508   if (Found) {
1509     if (FoundTag && FoundNonTag)
1510       R.setAmbiguousQualifiedTagHiding();
1511     else
1512       R.resolveKind();
1513   }
1514 
1515   return Found;
1516 }
1517 
1518 /// \brief Callback that looks for any member of a class with the given name.
1519 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1520                             CXXBasePath &Path,
1521                             void *Name) {
1522   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1523 
1524   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1525   Path.Decls = BaseRecord->lookup(N);
1526   return !Path.Decls.empty();
1527 }
1528 
1529 /// \brief Determine whether the given set of member declarations contains only
1530 /// static members, nested types, and enumerators.
1531 template<typename InputIterator>
1532 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1533   Decl *D = (*First)->getUnderlyingDecl();
1534   if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1535     return true;
1536 
1537   if (isa<CXXMethodDecl>(D)) {
1538     // Determine whether all of the methods are static.
1539     bool AllMethodsAreStatic = true;
1540     for(; First != Last; ++First) {
1541       D = (*First)->getUnderlyingDecl();
1542 
1543       if (!isa<CXXMethodDecl>(D)) {
1544         assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1545         break;
1546       }
1547 
1548       if (!cast<CXXMethodDecl>(D)->isStatic()) {
1549         AllMethodsAreStatic = false;
1550         break;
1551       }
1552     }
1553 
1554     if (AllMethodsAreStatic)
1555       return true;
1556   }
1557 
1558   return false;
1559 }
1560 
1561 /// \brief Perform qualified name lookup into a given context.
1562 ///
1563 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1564 /// names when the context of those names is explicit specified, e.g.,
1565 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1566 ///
1567 /// Different lookup criteria can find different names. For example, a
1568 /// particular scope can have both a struct and a function of the same
1569 /// name, and each can be found by certain lookup criteria. For more
1570 /// information about lookup criteria, see the documentation for the
1571 /// class LookupCriteria.
1572 ///
1573 /// \param R captures both the lookup criteria and any lookup results found.
1574 ///
1575 /// \param LookupCtx The context in which qualified name lookup will
1576 /// search. If the lookup criteria permits, name lookup may also search
1577 /// in the parent contexts or (for C++ classes) base classes.
1578 ///
1579 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1580 /// occurs as part of unqualified name lookup.
1581 ///
1582 /// \returns true if lookup succeeded, false if it failed.
1583 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1584                                bool InUnqualifiedLookup) {
1585   assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1586 
1587   if (!R.getLookupName())
1588     return false;
1589 
1590   // Make sure that the declaration context is complete.
1591   assert((!isa<TagDecl>(LookupCtx) ||
1592           LookupCtx->isDependentContext() ||
1593           cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
1594           cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
1595          "Declaration context must already be complete!");
1596 
1597   // Perform qualified name lookup into the LookupCtx.
1598   if (LookupDirect(*this, R, LookupCtx)) {
1599     R.resolveKind();
1600     if (isa<CXXRecordDecl>(LookupCtx))
1601       R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1602     return true;
1603   }
1604 
1605   // Don't descend into implied contexts for redeclarations.
1606   // C++98 [namespace.qual]p6:
1607   //   In a declaration for a namespace member in which the
1608   //   declarator-id is a qualified-id, given that the qualified-id
1609   //   for the namespace member has the form
1610   //     nested-name-specifier unqualified-id
1611   //   the unqualified-id shall name a member of the namespace
1612   //   designated by the nested-name-specifier.
1613   // See also [class.mfct]p5 and [class.static.data]p2.
1614   if (R.isForRedeclaration())
1615     return false;
1616 
1617   // If this is a namespace, look it up in the implied namespaces.
1618   if (LookupCtx->isFileContext())
1619     return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1620 
1621   // If this isn't a C++ class, we aren't allowed to look into base
1622   // classes, we're done.
1623   CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1624   if (!LookupRec || !LookupRec->getDefinition())
1625     return false;
1626 
1627   // If we're performing qualified name lookup into a dependent class,
1628   // then we are actually looking into a current instantiation. If we have any
1629   // dependent base classes, then we either have to delay lookup until
1630   // template instantiation time (at which point all bases will be available)
1631   // or we have to fail.
1632   if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1633       LookupRec->hasAnyDependentBases()) {
1634     R.setNotFoundInCurrentInstantiation();
1635     return false;
1636   }
1637 
1638   // Perform lookup into our base classes.
1639   CXXBasePaths Paths;
1640   Paths.setOrigin(LookupRec);
1641 
1642   // Look for this member in our base classes
1643   CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
1644   switch (R.getLookupKind()) {
1645     case LookupObjCImplicitSelfParam:
1646     case LookupOrdinaryName:
1647     case LookupMemberName:
1648     case LookupRedeclarationWithLinkage:
1649     case LookupLocalFriendName:
1650       BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1651       break;
1652 
1653     case LookupTagName:
1654       BaseCallback = &CXXRecordDecl::FindTagMember;
1655       break;
1656 
1657     case LookupAnyName:
1658       BaseCallback = &LookupAnyMember;
1659       break;
1660 
1661     case LookupUsingDeclName:
1662       // This lookup is for redeclarations only.
1663 
1664     case LookupOperatorName:
1665     case LookupNamespaceName:
1666     case LookupObjCProtocolName:
1667     case LookupLabel:
1668       // These lookups will never find a member in a C++ class (or base class).
1669       return false;
1670 
1671     case LookupNestedNameSpecifierName:
1672       BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1673       break;
1674   }
1675 
1676   if (!LookupRec->lookupInBases(BaseCallback,
1677                                 R.getLookupName().getAsOpaquePtr(), Paths))
1678     return false;
1679 
1680   R.setNamingClass(LookupRec);
1681 
1682   // C++ [class.member.lookup]p2:
1683   //   [...] If the resulting set of declarations are not all from
1684   //   sub-objects of the same type, or the set has a nonstatic member
1685   //   and includes members from distinct sub-objects, there is an
1686   //   ambiguity and the program is ill-formed. Otherwise that set is
1687   //   the result of the lookup.
1688   QualType SubobjectType;
1689   int SubobjectNumber = 0;
1690   AccessSpecifier SubobjectAccess = AS_none;
1691 
1692   for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1693        Path != PathEnd; ++Path) {
1694     const CXXBasePathElement &PathElement = Path->back();
1695 
1696     // Pick the best (i.e. most permissive i.e. numerically lowest) access
1697     // across all paths.
1698     SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1699 
1700     // Determine whether we're looking at a distinct sub-object or not.
1701     if (SubobjectType.isNull()) {
1702       // This is the first subobject we've looked at. Record its type.
1703       SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1704       SubobjectNumber = PathElement.SubobjectNumber;
1705       continue;
1706     }
1707 
1708     if (SubobjectType
1709                  != Context.getCanonicalType(PathElement.Base->getType())) {
1710       // We found members of the given name in two subobjects of
1711       // different types. If the declaration sets aren't the same, this
1712       // lookup is ambiguous.
1713       if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
1714         CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1715         DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1716         DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
1717 
1718         while (FirstD != FirstPath->Decls.end() &&
1719                CurrentD != Path->Decls.end()) {
1720          if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1721              (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1722            break;
1723 
1724           ++FirstD;
1725           ++CurrentD;
1726         }
1727 
1728         if (FirstD == FirstPath->Decls.end() &&
1729             CurrentD == Path->Decls.end())
1730           continue;
1731       }
1732 
1733       R.setAmbiguousBaseSubobjectTypes(Paths);
1734       return true;
1735     }
1736 
1737     if (SubobjectNumber != PathElement.SubobjectNumber) {
1738       // We have a different subobject of the same type.
1739 
1740       // C++ [class.member.lookup]p5:
1741       //   A static member, a nested type or an enumerator defined in
1742       //   a base class T can unambiguously be found even if an object
1743       //   has more than one base class subobject of type T.
1744       if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
1745         continue;
1746 
1747       // We have found a nonstatic member name in multiple, distinct
1748       // subobjects. Name lookup is ambiguous.
1749       R.setAmbiguousBaseSubobjects(Paths);
1750       return true;
1751     }
1752   }
1753 
1754   // Lookup in a base class succeeded; return these results.
1755 
1756   for (auto *D : Paths.front().Decls) {
1757     AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1758                                                     D->getAccess());
1759     R.addDecl(D, AS);
1760   }
1761   R.resolveKind();
1762   return true;
1763 }
1764 
1765 /// @brief Performs name lookup for a name that was parsed in the
1766 /// source code, and may contain a C++ scope specifier.
1767 ///
1768 /// This routine is a convenience routine meant to be called from
1769 /// contexts that receive a name and an optional C++ scope specifier
1770 /// (e.g., "N::M::x"). It will then perform either qualified or
1771 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1772 /// respectively) on the given name and return those results. It will
1773 /// perform a special type of lookup for "__super::" scope specifier.
1774 ///
1775 /// @param S        The scope from which unqualified name lookup will
1776 /// begin.
1777 ///
1778 /// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
1779 ///
1780 /// @param EnteringContext Indicates whether we are going to enter the
1781 /// context of the scope-specifier SS (if present).
1782 ///
1783 /// @returns True if any decls were found (but possibly ambiguous)
1784 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1785                             bool AllowBuiltinCreation, bool EnteringContext) {
1786   if (SS && SS->isInvalid()) {
1787     // When the scope specifier is invalid, don't even look for
1788     // anything.
1789     return false;
1790   }
1791 
1792   if (SS && SS->isSet()) {
1793     NestedNameSpecifier *NNS = SS->getScopeRep();
1794     if (NNS->getKind() == NestedNameSpecifier::Super)
1795       return LookupInSuper(R, NNS->getAsRecordDecl());
1796 
1797     if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1798       // We have resolved the scope specifier to a particular declaration
1799       // contex, and will perform name lookup in that context.
1800       if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1801         return false;
1802 
1803       R.setContextRange(SS->getRange());
1804       return LookupQualifiedName(R, DC);
1805     }
1806 
1807     // We could not resolve the scope specified to a specific declaration
1808     // context, which means that SS refers to an unknown specialization.
1809     // Name lookup can't find anything in this case.
1810     R.setNotFoundInCurrentInstantiation();
1811     R.setContextRange(SS->getRange());
1812     return false;
1813   }
1814 
1815   // Perform unqualified name lookup starting in the given scope.
1816   return LookupName(R, S, AllowBuiltinCreation);
1817 }
1818 
1819 /// \brief Perform qualified name lookup into all base classes of the given
1820 /// class.
1821 ///
1822 /// \param R captures both the lookup criteria and any lookup results found.
1823 ///
1824 /// \param Class The context in which qualified name lookup will
1825 /// search. Name lookup will search in all base classes merging the results.
1826 ///
1827 /// @returns True if any decls were found (but possibly ambiguous)
1828 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
1829   for (const auto &BaseSpec : Class->bases()) {
1830     CXXRecordDecl *RD = cast<CXXRecordDecl>(
1831         BaseSpec.getType()->castAs<RecordType>()->getDecl());
1832     LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
1833 	Result.setBaseObjectType(Context.getRecordType(Class));
1834     LookupQualifiedName(Result, RD);
1835     for (auto *Decl : Result)
1836       R.addDecl(Decl);
1837   }
1838 
1839   R.resolveKind();
1840 
1841   return !R.empty();
1842 }
1843 
1844 /// \brief Produce a diagnostic describing the ambiguity that resulted
1845 /// from name lookup.
1846 ///
1847 /// \param Result The result of the ambiguous lookup to be diagnosed.
1848 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1849   assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1850 
1851   DeclarationName Name = Result.getLookupName();
1852   SourceLocation NameLoc = Result.getNameLoc();
1853   SourceRange LookupRange = Result.getContextRange();
1854 
1855   switch (Result.getAmbiguityKind()) {
1856   case LookupResult::AmbiguousBaseSubobjects: {
1857     CXXBasePaths *Paths = Result.getBasePaths();
1858     QualType SubobjectType = Paths->front().back().Base->getType();
1859     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1860       << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1861       << LookupRange;
1862 
1863     DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
1864     while (isa<CXXMethodDecl>(*Found) &&
1865            cast<CXXMethodDecl>(*Found)->isStatic())
1866       ++Found;
1867 
1868     Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1869     break;
1870   }
1871 
1872   case LookupResult::AmbiguousBaseSubobjectTypes: {
1873     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1874       << Name << LookupRange;
1875 
1876     CXXBasePaths *Paths = Result.getBasePaths();
1877     std::set<Decl *> DeclsPrinted;
1878     for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1879                                       PathEnd = Paths->end();
1880          Path != PathEnd; ++Path) {
1881       Decl *D = Path->Decls.front();
1882       if (DeclsPrinted.insert(D).second)
1883         Diag(D->getLocation(), diag::note_ambiguous_member_found);
1884     }
1885     break;
1886   }
1887 
1888   case LookupResult::AmbiguousTagHiding: {
1889     Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1890 
1891     llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1892 
1893     for (auto *D : Result)
1894       if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1895         TagDecls.insert(TD);
1896         Diag(TD->getLocation(), diag::note_hidden_tag);
1897       }
1898 
1899     for (auto *D : Result)
1900       if (!isa<TagDecl>(D))
1901         Diag(D->getLocation(), diag::note_hiding_object);
1902 
1903     // For recovery purposes, go ahead and implement the hiding.
1904     LookupResult::Filter F = Result.makeFilter();
1905     while (F.hasNext()) {
1906       if (TagDecls.count(F.next()))
1907         F.erase();
1908     }
1909     F.done();
1910     break;
1911   }
1912 
1913   case LookupResult::AmbiguousReference: {
1914     Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1915 
1916     for (auto *D : Result)
1917       Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
1918     break;
1919   }
1920   }
1921 }
1922 
1923 namespace {
1924   struct AssociatedLookup {
1925     AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
1926                      Sema::AssociatedNamespaceSet &Namespaces,
1927                      Sema::AssociatedClassSet &Classes)
1928       : S(S), Namespaces(Namespaces), Classes(Classes),
1929         InstantiationLoc(InstantiationLoc) {
1930     }
1931 
1932     Sema &S;
1933     Sema::AssociatedNamespaceSet &Namespaces;
1934     Sema::AssociatedClassSet &Classes;
1935     SourceLocation InstantiationLoc;
1936   };
1937 }
1938 
1939 static void
1940 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1941 
1942 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1943                                       DeclContext *Ctx) {
1944   // Add the associated namespace for this class.
1945 
1946   // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1947   // be a locally scoped record.
1948 
1949   // We skip out of inline namespaces. The innermost non-inline namespace
1950   // contains all names of all its nested inline namespaces anyway, so we can
1951   // replace the entire inline namespace tree with its root.
1952   while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1953          Ctx->isInlineNamespace())
1954     Ctx = Ctx->getParent();
1955 
1956   if (Ctx->isFileContext())
1957     Namespaces.insert(Ctx->getPrimaryContext());
1958 }
1959 
1960 // \brief Add the associated classes and namespaces for argument-dependent
1961 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1962 static void
1963 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1964                                   const TemplateArgument &Arg) {
1965   // C++ [basic.lookup.koenig]p2, last bullet:
1966   //   -- [...] ;
1967   switch (Arg.getKind()) {
1968     case TemplateArgument::Null:
1969       break;
1970 
1971     case TemplateArgument::Type:
1972       // [...] the namespaces and classes associated with the types of the
1973       // template arguments provided for template type parameters (excluding
1974       // template template parameters)
1975       addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1976       break;
1977 
1978     case TemplateArgument::Template:
1979     case TemplateArgument::TemplateExpansion: {
1980       // [...] the namespaces in which any template template arguments are
1981       // defined; and the classes in which any member templates used as
1982       // template template arguments are defined.
1983       TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1984       if (ClassTemplateDecl *ClassTemplate
1985                  = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1986         DeclContext *Ctx = ClassTemplate->getDeclContext();
1987         if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1988           Result.Classes.insert(EnclosingClass);
1989         // Add the associated namespace for this class.
1990         CollectEnclosingNamespace(Result.Namespaces, Ctx);
1991       }
1992       break;
1993     }
1994 
1995     case TemplateArgument::Declaration:
1996     case TemplateArgument::Integral:
1997     case TemplateArgument::Expression:
1998     case TemplateArgument::NullPtr:
1999       // [Note: non-type template arguments do not contribute to the set of
2000       //  associated namespaces. ]
2001       break;
2002 
2003     case TemplateArgument::Pack:
2004       for (const auto &P : Arg.pack_elements())
2005         addAssociatedClassesAndNamespaces(Result, P);
2006       break;
2007   }
2008 }
2009 
2010 // \brief Add the associated classes and namespaces for
2011 // argument-dependent lookup with an argument of class type
2012 // (C++ [basic.lookup.koenig]p2).
2013 static void
2014 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2015                                   CXXRecordDecl *Class) {
2016 
2017   // Just silently ignore anything whose name is __va_list_tag.
2018   if (Class->getDeclName() == Result.S.VAListTagName)
2019     return;
2020 
2021   // C++ [basic.lookup.koenig]p2:
2022   //   [...]
2023   //     -- If T is a class type (including unions), its associated
2024   //        classes are: the class itself; the class of which it is a
2025   //        member, if any; and its direct and indirect base
2026   //        classes. Its associated namespaces are the namespaces in
2027   //        which its associated classes are defined.
2028 
2029   // Add the class of which it is a member, if any.
2030   DeclContext *Ctx = Class->getDeclContext();
2031   if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2032     Result.Classes.insert(EnclosingClass);
2033   // Add the associated namespace for this class.
2034   CollectEnclosingNamespace(Result.Namespaces, Ctx);
2035 
2036   // Add the class itself. If we've already seen this class, we don't
2037   // need to visit base classes.
2038   //
2039   // FIXME: That's not correct, we may have added this class only because it
2040   // was the enclosing class of another class, and in that case we won't have
2041   // added its base classes yet.
2042   if (!Result.Classes.insert(Class))
2043     return;
2044 
2045   // -- If T is a template-id, its associated namespaces and classes are
2046   //    the namespace in which the template is defined; for member
2047   //    templates, the member template's class; the namespaces and classes
2048   //    associated with the types of the template arguments provided for
2049   //    template type parameters (excluding template template parameters); the
2050   //    namespaces in which any template template arguments are defined; and
2051   //    the classes in which any member templates used as template template
2052   //    arguments are defined. [Note: non-type template arguments do not
2053   //    contribute to the set of associated namespaces. ]
2054   if (ClassTemplateSpecializationDecl *Spec
2055         = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2056     DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2057     if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2058       Result.Classes.insert(EnclosingClass);
2059     // Add the associated namespace for this class.
2060     CollectEnclosingNamespace(Result.Namespaces, Ctx);
2061 
2062     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2063     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2064       addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2065   }
2066 
2067   // Only recurse into base classes for complete types.
2068   if (!Class->hasDefinition())
2069     return;
2070 
2071   // Add direct and indirect base classes along with their associated
2072   // namespaces.
2073   SmallVector<CXXRecordDecl *, 32> Bases;
2074   Bases.push_back(Class);
2075   while (!Bases.empty()) {
2076     // Pop this class off the stack.
2077     Class = Bases.pop_back_val();
2078 
2079     // Visit the base classes.
2080     for (const auto &Base : Class->bases()) {
2081       const RecordType *BaseType = Base.getType()->getAs<RecordType>();
2082       // In dependent contexts, we do ADL twice, and the first time around,
2083       // the base type might be a dependent TemplateSpecializationType, or a
2084       // TemplateTypeParmType. If that happens, simply ignore it.
2085       // FIXME: If we want to support export, we probably need to add the
2086       // namespace of the template in a TemplateSpecializationType, or even
2087       // the classes and namespaces of known non-dependent arguments.
2088       if (!BaseType)
2089         continue;
2090       CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2091       if (Result.Classes.insert(BaseDecl)) {
2092         // Find the associated namespace for this base class.
2093         DeclContext *BaseCtx = BaseDecl->getDeclContext();
2094         CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2095 
2096         // Make sure we visit the bases of this base class.
2097         if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2098           Bases.push_back(BaseDecl);
2099       }
2100     }
2101   }
2102 }
2103 
2104 // \brief Add the associated classes and namespaces for
2105 // argument-dependent lookup with an argument of type T
2106 // (C++ [basic.lookup.koenig]p2).
2107 static void
2108 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2109   // C++ [basic.lookup.koenig]p2:
2110   //
2111   //   For each argument type T in the function call, there is a set
2112   //   of zero or more associated namespaces and a set of zero or more
2113   //   associated classes to be considered. The sets of namespaces and
2114   //   classes is determined entirely by the types of the function
2115   //   arguments (and the namespace of any template template
2116   //   argument). Typedef names and using-declarations used to specify
2117   //   the types do not contribute to this set. The sets of namespaces
2118   //   and classes are determined in the following way:
2119 
2120   SmallVector<const Type *, 16> Queue;
2121   const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2122 
2123   while (true) {
2124     switch (T->getTypeClass()) {
2125 
2126 #define TYPE(Class, Base)
2127 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2128 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2129 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2130 #define ABSTRACT_TYPE(Class, Base)
2131 #include "clang/AST/TypeNodes.def"
2132       // T is canonical.  We can also ignore dependent types because
2133       // we don't need to do ADL at the definition point, but if we
2134       // wanted to implement template export (or if we find some other
2135       // use for associated classes and namespaces...) this would be
2136       // wrong.
2137       break;
2138 
2139     //    -- If T is a pointer to U or an array of U, its associated
2140     //       namespaces and classes are those associated with U.
2141     case Type::Pointer:
2142       T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2143       continue;
2144     case Type::ConstantArray:
2145     case Type::IncompleteArray:
2146     case Type::VariableArray:
2147       T = cast<ArrayType>(T)->getElementType().getTypePtr();
2148       continue;
2149 
2150     //     -- If T is a fundamental type, its associated sets of
2151     //        namespaces and classes are both empty.
2152     case Type::Builtin:
2153       break;
2154 
2155     //     -- If T is a class type (including unions), its associated
2156     //        classes are: the class itself; the class of which it is a
2157     //        member, if any; and its direct and indirect base
2158     //        classes. Its associated namespaces are the namespaces in
2159     //        which its associated classes are defined.
2160     case Type::Record: {
2161       Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2162                                    /*no diagnostic*/ 0);
2163       CXXRecordDecl *Class
2164         = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2165       addAssociatedClassesAndNamespaces(Result, Class);
2166       break;
2167     }
2168 
2169     //     -- If T is an enumeration type, its associated namespace is
2170     //        the namespace in which it is defined. If it is class
2171     //        member, its associated class is the member's class; else
2172     //        it has no associated class.
2173     case Type::Enum: {
2174       EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2175 
2176       DeclContext *Ctx = Enum->getDeclContext();
2177       if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2178         Result.Classes.insert(EnclosingClass);
2179 
2180       // Add the associated namespace for this class.
2181       CollectEnclosingNamespace(Result.Namespaces, Ctx);
2182 
2183       break;
2184     }
2185 
2186     //     -- If T is a function type, its associated namespaces and
2187     //        classes are those associated with the function parameter
2188     //        types and those associated with the return type.
2189     case Type::FunctionProto: {
2190       const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2191       for (const auto &Arg : Proto->param_types())
2192         Queue.push_back(Arg.getTypePtr());
2193       // fallthrough
2194     }
2195     case Type::FunctionNoProto: {
2196       const FunctionType *FnType = cast<FunctionType>(T);
2197       T = FnType->getReturnType().getTypePtr();
2198       continue;
2199     }
2200 
2201     //     -- If T is a pointer to a member function of a class X, its
2202     //        associated namespaces and classes are those associated
2203     //        with the function parameter types and return type,
2204     //        together with those associated with X.
2205     //
2206     //     -- If T is a pointer to a data member of class X, its
2207     //        associated namespaces and classes are those associated
2208     //        with the member type together with those associated with
2209     //        X.
2210     case Type::MemberPointer: {
2211       const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2212 
2213       // Queue up the class type into which this points.
2214       Queue.push_back(MemberPtr->getClass());
2215 
2216       // And directly continue with the pointee type.
2217       T = MemberPtr->getPointeeType().getTypePtr();
2218       continue;
2219     }
2220 
2221     // As an extension, treat this like a normal pointer.
2222     case Type::BlockPointer:
2223       T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2224       continue;
2225 
2226     // References aren't covered by the standard, but that's such an
2227     // obvious defect that we cover them anyway.
2228     case Type::LValueReference:
2229     case Type::RValueReference:
2230       T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2231       continue;
2232 
2233     // These are fundamental types.
2234     case Type::Vector:
2235     case Type::ExtVector:
2236     case Type::Complex:
2237       break;
2238 
2239     // Non-deduced auto types only get here for error cases.
2240     case Type::Auto:
2241       break;
2242 
2243     // If T is an Objective-C object or interface type, or a pointer to an
2244     // object or interface type, the associated namespace is the global
2245     // namespace.
2246     case Type::ObjCObject:
2247     case Type::ObjCInterface:
2248     case Type::ObjCObjectPointer:
2249       Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2250       break;
2251 
2252     // Atomic types are just wrappers; use the associations of the
2253     // contained type.
2254     case Type::Atomic:
2255       T = cast<AtomicType>(T)->getValueType().getTypePtr();
2256       continue;
2257     }
2258 
2259     if (Queue.empty())
2260       break;
2261     T = Queue.pop_back_val();
2262   }
2263 }
2264 
2265 /// \brief Find the associated classes and namespaces for
2266 /// argument-dependent lookup for a call with the given set of
2267 /// arguments.
2268 ///
2269 /// This routine computes the sets of associated classes and associated
2270 /// namespaces searched by argument-dependent lookup
2271 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
2272 void Sema::FindAssociatedClassesAndNamespaces(
2273     SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2274     AssociatedNamespaceSet &AssociatedNamespaces,
2275     AssociatedClassSet &AssociatedClasses) {
2276   AssociatedNamespaces.clear();
2277   AssociatedClasses.clear();
2278 
2279   AssociatedLookup Result(*this, InstantiationLoc,
2280                           AssociatedNamespaces, AssociatedClasses);
2281 
2282   // C++ [basic.lookup.koenig]p2:
2283   //   For each argument type T in the function call, there is a set
2284   //   of zero or more associated namespaces and a set of zero or more
2285   //   associated classes to be considered. The sets of namespaces and
2286   //   classes is determined entirely by the types of the function
2287   //   arguments (and the namespace of any template template
2288   //   argument).
2289   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2290     Expr *Arg = Args[ArgIdx];
2291 
2292     if (Arg->getType() != Context.OverloadTy) {
2293       addAssociatedClassesAndNamespaces(Result, Arg->getType());
2294       continue;
2295     }
2296 
2297     // [...] In addition, if the argument is the name or address of a
2298     // set of overloaded functions and/or function templates, its
2299     // associated classes and namespaces are the union of those
2300     // associated with each of the members of the set: the namespace
2301     // in which the function or function template is defined and the
2302     // classes and namespaces associated with its (non-dependent)
2303     // parameter types and return type.
2304     Arg = Arg->IgnoreParens();
2305     if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2306       if (unaryOp->getOpcode() == UO_AddrOf)
2307         Arg = unaryOp->getSubExpr();
2308 
2309     UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2310     if (!ULE) continue;
2311 
2312     for (const auto *D : ULE->decls()) {
2313       // Look through any using declarations to find the underlying function.
2314       const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
2315 
2316       // Add the classes and namespaces associated with the parameter
2317       // types and return type of this function.
2318       addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2319     }
2320   }
2321 }
2322 
2323 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2324                                   SourceLocation Loc,
2325                                   LookupNameKind NameKind,
2326                                   RedeclarationKind Redecl) {
2327   LookupResult R(*this, Name, Loc, NameKind, Redecl);
2328   LookupName(R, S);
2329   return R.getAsSingle<NamedDecl>();
2330 }
2331 
2332 /// \brief Find the protocol with the given name, if any.
2333 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2334                                        SourceLocation IdLoc,
2335                                        RedeclarationKind Redecl) {
2336   Decl *D = LookupSingleName(TUScope, II, IdLoc,
2337                              LookupObjCProtocolName, Redecl);
2338   return cast_or_null<ObjCProtocolDecl>(D);
2339 }
2340 
2341 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2342                                         QualType T1, QualType T2,
2343                                         UnresolvedSetImpl &Functions) {
2344   // C++ [over.match.oper]p3:
2345   //     -- The set of non-member candidates is the result of the
2346   //        unqualified lookup of operator@ in the context of the
2347   //        expression according to the usual rules for name lookup in
2348   //        unqualified function calls (3.4.2) except that all member
2349   //        functions are ignored.
2350   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2351   LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2352   LookupName(Operators, S);
2353 
2354   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2355   Functions.append(Operators.begin(), Operators.end());
2356 }
2357 
2358 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
2359                                                             CXXSpecialMember SM,
2360                                                             bool ConstArg,
2361                                                             bool VolatileArg,
2362                                                             bool RValueThis,
2363                                                             bool ConstThis,
2364                                                             bool VolatileThis) {
2365   assert(CanDeclareSpecialMemberFunction(RD) &&
2366          "doing special member lookup into record that isn't fully complete");
2367   RD = RD->getDefinition();
2368   if (RValueThis || ConstThis || VolatileThis)
2369     assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2370            "constructors and destructors always have unqualified lvalue this");
2371   if (ConstArg || VolatileArg)
2372     assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2373            "parameter-less special members can't have qualified arguments");
2374 
2375   llvm::FoldingSetNodeID ID;
2376   ID.AddPointer(RD);
2377   ID.AddInteger(SM);
2378   ID.AddInteger(ConstArg);
2379   ID.AddInteger(VolatileArg);
2380   ID.AddInteger(RValueThis);
2381   ID.AddInteger(ConstThis);
2382   ID.AddInteger(VolatileThis);
2383 
2384   void *InsertPoint;
2385   SpecialMemberOverloadResult *Result =
2386     SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2387 
2388   // This was already cached
2389   if (Result)
2390     return Result;
2391 
2392   Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2393   Result = new (Result) SpecialMemberOverloadResult(ID);
2394   SpecialMemberCache.InsertNode(Result, InsertPoint);
2395 
2396   if (SM == CXXDestructor) {
2397     if (RD->needsImplicitDestructor())
2398       DeclareImplicitDestructor(RD);
2399     CXXDestructorDecl *DD = RD->getDestructor();
2400     assert(DD && "record without a destructor");
2401     Result->setMethod(DD);
2402     Result->setKind(DD->isDeleted() ?
2403                     SpecialMemberOverloadResult::NoMemberOrDeleted :
2404                     SpecialMemberOverloadResult::Success);
2405     return Result;
2406   }
2407 
2408   // Prepare for overload resolution. Here we construct a synthetic argument
2409   // if necessary and make sure that implicit functions are declared.
2410   CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2411   DeclarationName Name;
2412   Expr *Arg = nullptr;
2413   unsigned NumArgs;
2414 
2415   QualType ArgType = CanTy;
2416   ExprValueKind VK = VK_LValue;
2417 
2418   if (SM == CXXDefaultConstructor) {
2419     Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2420     NumArgs = 0;
2421     if (RD->needsImplicitDefaultConstructor())
2422       DeclareImplicitDefaultConstructor(RD);
2423   } else {
2424     if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2425       Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2426       if (RD->needsImplicitCopyConstructor())
2427         DeclareImplicitCopyConstructor(RD);
2428       if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
2429         DeclareImplicitMoveConstructor(RD);
2430     } else {
2431       Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2432       if (RD->needsImplicitCopyAssignment())
2433         DeclareImplicitCopyAssignment(RD);
2434       if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
2435         DeclareImplicitMoveAssignment(RD);
2436     }
2437 
2438     if (ConstArg)
2439       ArgType.addConst();
2440     if (VolatileArg)
2441       ArgType.addVolatile();
2442 
2443     // This isn't /really/ specified by the standard, but it's implied
2444     // we should be working from an RValue in the case of move to ensure
2445     // that we prefer to bind to rvalue references, and an LValue in the
2446     // case of copy to ensure we don't bind to rvalue references.
2447     // Possibly an XValue is actually correct in the case of move, but
2448     // there is no semantic difference for class types in this restricted
2449     // case.
2450     if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2451       VK = VK_LValue;
2452     else
2453       VK = VK_RValue;
2454   }
2455 
2456   OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2457 
2458   if (SM != CXXDefaultConstructor) {
2459     NumArgs = 1;
2460     Arg = &FakeArg;
2461   }
2462 
2463   // Create the object argument
2464   QualType ThisTy = CanTy;
2465   if (ConstThis)
2466     ThisTy.addConst();
2467   if (VolatileThis)
2468     ThisTy.addVolatile();
2469   Expr::Classification Classification =
2470     OpaqueValueExpr(SourceLocation(), ThisTy,
2471                     RValueThis ? VK_RValue : VK_LValue).Classify(Context);
2472 
2473   // Now we perform lookup on the name we computed earlier and do overload
2474   // resolution. Lookup is only performed directly into the class since there
2475   // will always be a (possibly implicit) declaration to shadow any others.
2476   OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
2477   DeclContext::lookup_result R = RD->lookup(Name);
2478   assert(!R.empty() &&
2479          "lookup for a constructor or assignment operator was empty");
2480 
2481   // Copy the candidates as our processing of them may load new declarations
2482   // from an external source and invalidate lookup_result.
2483   SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2484 
2485   for (auto *Cand : Candidates) {
2486     if (Cand->isInvalidDecl())
2487       continue;
2488 
2489     if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2490       // FIXME: [namespace.udecl]p15 says that we should only consider a
2491       // using declaration here if it does not match a declaration in the
2492       // derived class. We do not implement this correctly in other cases
2493       // either.
2494       Cand = U->getTargetDecl();
2495 
2496       if (Cand->isInvalidDecl())
2497         continue;
2498     }
2499 
2500     if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
2501       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2502         AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
2503                            Classification, llvm::makeArrayRef(&Arg, NumArgs),
2504                            OCS, true);
2505       else
2506         AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2507                              llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2508     } else if (FunctionTemplateDecl *Tmpl =
2509                  dyn_cast<FunctionTemplateDecl>(Cand)) {
2510       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2511         AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2512                                    RD, nullptr, ThisTy, Classification,
2513                                    llvm::makeArrayRef(&Arg, NumArgs),
2514                                    OCS, true);
2515       else
2516         AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2517                                      nullptr, llvm::makeArrayRef(&Arg, NumArgs),
2518                                      OCS, true);
2519     } else {
2520       assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
2521     }
2522   }
2523 
2524   OverloadCandidateSet::iterator Best;
2525   switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2526     case OR_Success:
2527       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2528       Result->setKind(SpecialMemberOverloadResult::Success);
2529       break;
2530 
2531     case OR_Deleted:
2532       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2533       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2534       break;
2535 
2536     case OR_Ambiguous:
2537       Result->setMethod(nullptr);
2538       Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2539       break;
2540 
2541     case OR_No_Viable_Function:
2542       Result->setMethod(nullptr);
2543       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2544       break;
2545   }
2546 
2547   return Result;
2548 }
2549 
2550 /// \brief Look up the default constructor for the given class.
2551 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
2552   SpecialMemberOverloadResult *Result =
2553     LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2554                         false, false);
2555 
2556   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2557 }
2558 
2559 /// \brief Look up the copying constructor for the given class.
2560 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2561                                                    unsigned Quals) {
2562   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2563          "non-const, non-volatile qualifiers for copy ctor arg");
2564   SpecialMemberOverloadResult *Result =
2565     LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2566                         Quals & Qualifiers::Volatile, false, false, false);
2567 
2568   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2569 }
2570 
2571 /// \brief Look up the moving constructor for the given class.
2572 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2573                                                   unsigned Quals) {
2574   SpecialMemberOverloadResult *Result =
2575     LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2576                         Quals & Qualifiers::Volatile, false, false, false);
2577 
2578   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2579 }
2580 
2581 /// \brief Look up the constructors for the given class.
2582 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2583   // If the implicit constructors have not yet been declared, do so now.
2584   if (CanDeclareSpecialMemberFunction(Class)) {
2585     if (Class->needsImplicitDefaultConstructor())
2586       DeclareImplicitDefaultConstructor(Class);
2587     if (Class->needsImplicitCopyConstructor())
2588       DeclareImplicitCopyConstructor(Class);
2589     if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
2590       DeclareImplicitMoveConstructor(Class);
2591   }
2592 
2593   CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2594   DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2595   return Class->lookup(Name);
2596 }
2597 
2598 /// \brief Look up the copying assignment operator for the given class.
2599 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2600                                              unsigned Quals, bool RValueThis,
2601                                              unsigned ThisQuals) {
2602   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2603          "non-const, non-volatile qualifiers for copy assignment arg");
2604   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2605          "non-const, non-volatile qualifiers for copy assignment this");
2606   SpecialMemberOverloadResult *Result =
2607     LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2608                         Quals & Qualifiers::Volatile, RValueThis,
2609                         ThisQuals & Qualifiers::Const,
2610                         ThisQuals & Qualifiers::Volatile);
2611 
2612   return Result->getMethod();
2613 }
2614 
2615 /// \brief Look up the moving assignment operator for the given class.
2616 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2617                                             unsigned Quals,
2618                                             bool RValueThis,
2619                                             unsigned ThisQuals) {
2620   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2621          "non-const, non-volatile qualifiers for copy assignment this");
2622   SpecialMemberOverloadResult *Result =
2623     LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2624                         Quals & Qualifiers::Volatile, RValueThis,
2625                         ThisQuals & Qualifiers::Const,
2626                         ThisQuals & Qualifiers::Volatile);
2627 
2628   return Result->getMethod();
2629 }
2630 
2631 /// \brief Look for the destructor of the given class.
2632 ///
2633 /// During semantic analysis, this routine should be used in lieu of
2634 /// CXXRecordDecl::getDestructor().
2635 ///
2636 /// \returns The destructor for this class.
2637 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2638   return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2639                                                      false, false, false,
2640                                                      false, false)->getMethod());
2641 }
2642 
2643 /// LookupLiteralOperator - Determine which literal operator should be used for
2644 /// a user-defined literal, per C++11 [lex.ext].
2645 ///
2646 /// Normal overload resolution is not used to select which literal operator to
2647 /// call for a user-defined literal. Look up the provided literal operator name,
2648 /// and filter the results to the appropriate set for the given argument types.
2649 Sema::LiteralOperatorLookupResult
2650 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2651                             ArrayRef<QualType> ArgTys,
2652                             bool AllowRaw, bool AllowTemplate,
2653                             bool AllowStringTemplate) {
2654   LookupName(R, S);
2655   assert(R.getResultKind() != LookupResult::Ambiguous &&
2656          "literal operator lookup can't be ambiguous");
2657 
2658   // Filter the lookup results appropriately.
2659   LookupResult::Filter F = R.makeFilter();
2660 
2661   bool FoundRaw = false;
2662   bool FoundTemplate = false;
2663   bool FoundStringTemplate = false;
2664   bool FoundExactMatch = false;
2665 
2666   while (F.hasNext()) {
2667     Decl *D = F.next();
2668     if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2669       D = USD->getTargetDecl();
2670 
2671     // If the declaration we found is invalid, skip it.
2672     if (D->isInvalidDecl()) {
2673       F.erase();
2674       continue;
2675     }
2676 
2677     bool IsRaw = false;
2678     bool IsTemplate = false;
2679     bool IsStringTemplate = false;
2680     bool IsExactMatch = false;
2681 
2682     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2683       if (FD->getNumParams() == 1 &&
2684           FD->getParamDecl(0)->getType()->getAs<PointerType>())
2685         IsRaw = true;
2686       else if (FD->getNumParams() == ArgTys.size()) {
2687         IsExactMatch = true;
2688         for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2689           QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2690           if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2691             IsExactMatch = false;
2692             break;
2693           }
2694         }
2695       }
2696     }
2697     if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2698       TemplateParameterList *Params = FD->getTemplateParameters();
2699       if (Params->size() == 1)
2700         IsTemplate = true;
2701       else
2702         IsStringTemplate = true;
2703     }
2704 
2705     if (IsExactMatch) {
2706       FoundExactMatch = true;
2707       AllowRaw = false;
2708       AllowTemplate = false;
2709       AllowStringTemplate = false;
2710       if (FoundRaw || FoundTemplate || FoundStringTemplate) {
2711         // Go through again and remove the raw and template decls we've
2712         // already found.
2713         F.restart();
2714         FoundRaw = FoundTemplate = FoundStringTemplate = false;
2715       }
2716     } else if (AllowRaw && IsRaw) {
2717       FoundRaw = true;
2718     } else if (AllowTemplate && IsTemplate) {
2719       FoundTemplate = true;
2720     } else if (AllowStringTemplate && IsStringTemplate) {
2721       FoundStringTemplate = true;
2722     } else {
2723       F.erase();
2724     }
2725   }
2726 
2727   F.done();
2728 
2729   // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2730   // parameter type, that is used in preference to a raw literal operator
2731   // or literal operator template.
2732   if (FoundExactMatch)
2733     return LOLR_Cooked;
2734 
2735   // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2736   // operator template, but not both.
2737   if (FoundRaw && FoundTemplate) {
2738     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2739     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2740       NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
2741     return LOLR_Error;
2742   }
2743 
2744   if (FoundRaw)
2745     return LOLR_Raw;
2746 
2747   if (FoundTemplate)
2748     return LOLR_Template;
2749 
2750   if (FoundStringTemplate)
2751     return LOLR_StringTemplate;
2752 
2753   // Didn't find anything we could use.
2754   Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2755     << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2756     << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2757     << (AllowTemplate || AllowStringTemplate);
2758   return LOLR_Error;
2759 }
2760 
2761 void ADLResult::insert(NamedDecl *New) {
2762   NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2763 
2764   // If we haven't yet seen a decl for this key, or the last decl
2765   // was exactly this one, we're done.
2766   if (Old == nullptr || Old == New) {
2767     Old = New;
2768     return;
2769   }
2770 
2771   // Otherwise, decide which is a more recent redeclaration.
2772   FunctionDecl *OldFD = Old->getAsFunction();
2773   FunctionDecl *NewFD = New->getAsFunction();
2774 
2775   FunctionDecl *Cursor = NewFD;
2776   while (true) {
2777     Cursor = Cursor->getPreviousDecl();
2778 
2779     // If we got to the end without finding OldFD, OldFD is the newer
2780     // declaration;  leave things as they are.
2781     if (!Cursor) return;
2782 
2783     // If we do find OldFD, then NewFD is newer.
2784     if (Cursor == OldFD) break;
2785 
2786     // Otherwise, keep looking.
2787   }
2788 
2789   Old = New;
2790 }
2791 
2792 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2793                                    ArrayRef<Expr *> Args, ADLResult &Result) {
2794   // Find all of the associated namespaces and classes based on the
2795   // arguments we have.
2796   AssociatedNamespaceSet AssociatedNamespaces;
2797   AssociatedClassSet AssociatedClasses;
2798   FindAssociatedClassesAndNamespaces(Loc, Args,
2799                                      AssociatedNamespaces,
2800                                      AssociatedClasses);
2801 
2802   // C++ [basic.lookup.argdep]p3:
2803   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
2804   //   and let Y be the lookup set produced by argument dependent
2805   //   lookup (defined as follows). If X contains [...] then Y is
2806   //   empty. Otherwise Y is the set of declarations found in the
2807   //   namespaces associated with the argument types as described
2808   //   below. The set of declarations found by the lookup of the name
2809   //   is the union of X and Y.
2810   //
2811   // Here, we compute Y and add its members to the overloaded
2812   // candidate set.
2813   for (auto *NS : AssociatedNamespaces) {
2814     //   When considering an associated namespace, the lookup is the
2815     //   same as the lookup performed when the associated namespace is
2816     //   used as a qualifier (3.4.3.2) except that:
2817     //
2818     //     -- Any using-directives in the associated namespace are
2819     //        ignored.
2820     //
2821     //     -- Any namespace-scope friend functions declared in
2822     //        associated classes are visible within their respective
2823     //        namespaces even if they are not visible during an ordinary
2824     //        lookup (11.4).
2825     DeclContext::lookup_result R = NS->lookup(Name);
2826     for (auto *D : R) {
2827       // If the only declaration here is an ordinary friend, consider
2828       // it only if it was declared in an associated classes.
2829       if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2830         // If it's neither ordinarily visible nor a friend, we can't find it.
2831         if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2832           continue;
2833 
2834         bool DeclaredInAssociatedClass = false;
2835         for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2836           DeclContext *LexDC = DI->getLexicalDeclContext();
2837           if (isa<CXXRecordDecl>(LexDC) &&
2838               AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2839             DeclaredInAssociatedClass = true;
2840             break;
2841           }
2842         }
2843         if (!DeclaredInAssociatedClass)
2844           continue;
2845       }
2846 
2847       if (isa<UsingShadowDecl>(D))
2848         D = cast<UsingShadowDecl>(D)->getTargetDecl();
2849 
2850       if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
2851         continue;
2852 
2853       Result.insert(D);
2854     }
2855   }
2856 }
2857 
2858 //----------------------------------------------------------------------------
2859 // Search for all visible declarations.
2860 //----------------------------------------------------------------------------
2861 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2862 
2863 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2864 
2865 namespace {
2866 
2867 class ShadowContextRAII;
2868 
2869 class VisibleDeclsRecord {
2870 public:
2871   /// \brief An entry in the shadow map, which is optimized to store a
2872   /// single declaration (the common case) but can also store a list
2873   /// of declarations.
2874   typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
2875 
2876 private:
2877   /// \brief A mapping from declaration names to the declarations that have
2878   /// this name within a particular scope.
2879   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2880 
2881   /// \brief A list of shadow maps, which is used to model name hiding.
2882   std::list<ShadowMap> ShadowMaps;
2883 
2884   /// \brief The declaration contexts we have already visited.
2885   llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2886 
2887   friend class ShadowContextRAII;
2888 
2889 public:
2890   /// \brief Determine whether we have already visited this context
2891   /// (and, if not, note that we are going to visit that context now).
2892   bool visitedContext(DeclContext *Ctx) {
2893     return !VisitedContexts.insert(Ctx);
2894   }
2895 
2896   bool alreadyVisitedContext(DeclContext *Ctx) {
2897     return VisitedContexts.count(Ctx);
2898   }
2899 
2900   /// \brief Determine whether the given declaration is hidden in the
2901   /// current scope.
2902   ///
2903   /// \returns the declaration that hides the given declaration, or
2904   /// NULL if no such declaration exists.
2905   NamedDecl *checkHidden(NamedDecl *ND);
2906 
2907   /// \brief Add a declaration to the current shadow map.
2908   void add(NamedDecl *ND) {
2909     ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2910   }
2911 };
2912 
2913 /// \brief RAII object that records when we've entered a shadow context.
2914 class ShadowContextRAII {
2915   VisibleDeclsRecord &Visible;
2916 
2917   typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2918 
2919 public:
2920   ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2921     Visible.ShadowMaps.push_back(ShadowMap());
2922   }
2923 
2924   ~ShadowContextRAII() {
2925     Visible.ShadowMaps.pop_back();
2926   }
2927 };
2928 
2929 } // end anonymous namespace
2930 
2931 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2932   // Look through using declarations.
2933   ND = ND->getUnderlyingDecl();
2934 
2935   unsigned IDNS = ND->getIdentifierNamespace();
2936   std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2937   for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2938        SM != SMEnd; ++SM) {
2939     ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2940     if (Pos == SM->end())
2941       continue;
2942 
2943     for (auto *D : Pos->second) {
2944       // A tag declaration does not hide a non-tag declaration.
2945       if (D->hasTagIdentifierNamespace() &&
2946           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2947                    Decl::IDNS_ObjCProtocol)))
2948         continue;
2949 
2950       // Protocols are in distinct namespaces from everything else.
2951       if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2952            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2953           D->getIdentifierNamespace() != IDNS)
2954         continue;
2955 
2956       // Functions and function templates in the same scope overload
2957       // rather than hide.  FIXME: Look for hiding based on function
2958       // signatures!
2959       if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
2960           ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
2961           SM == ShadowMaps.rbegin())
2962         continue;
2963 
2964       // We've found a declaration that hides this one.
2965       return D;
2966     }
2967   }
2968 
2969   return nullptr;
2970 }
2971 
2972 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2973                                bool QualifiedNameLookup,
2974                                bool InBaseClass,
2975                                VisibleDeclConsumer &Consumer,
2976                                VisibleDeclsRecord &Visited) {
2977   if (!Ctx)
2978     return;
2979 
2980   // Make sure we don't visit the same context twice.
2981   if (Visited.visitedContext(Ctx->getPrimaryContext()))
2982     return;
2983 
2984   if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2985     Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2986 
2987   // Enumerate all of the results in this context.
2988   for (const auto &R : Ctx->lookups()) {
2989     for (auto *I : R) {
2990       if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
2991         if ((ND = Result.getAcceptableDecl(ND))) {
2992           Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
2993           Visited.add(ND);
2994         }
2995       }
2996     }
2997   }
2998 
2999   // Traverse using directives for qualified name lookup.
3000   if (QualifiedNameLookup) {
3001     ShadowContextRAII Shadow(Visited);
3002     for (auto I : Ctx->using_directives()) {
3003       LookupVisibleDecls(I->getNominatedNamespace(), Result,
3004                          QualifiedNameLookup, InBaseClass, Consumer, Visited);
3005     }
3006   }
3007 
3008   // Traverse the contexts of inherited C++ classes.
3009   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
3010     if (!Record->hasDefinition())
3011       return;
3012 
3013     for (const auto &B : Record->bases()) {
3014       QualType BaseType = B.getType();
3015 
3016       // Don't look into dependent bases, because name lookup can't look
3017       // there anyway.
3018       if (BaseType->isDependentType())
3019         continue;
3020 
3021       const RecordType *Record = BaseType->getAs<RecordType>();
3022       if (!Record)
3023         continue;
3024 
3025       // FIXME: It would be nice to be able to determine whether referencing
3026       // a particular member would be ambiguous. For example, given
3027       //
3028       //   struct A { int member; };
3029       //   struct B { int member; };
3030       //   struct C : A, B { };
3031       //
3032       //   void f(C *c) { c->### }
3033       //
3034       // accessing 'member' would result in an ambiguity. However, we
3035       // could be smart enough to qualify the member with the base
3036       // class, e.g.,
3037       //
3038       //   c->B::member
3039       //
3040       // or
3041       //
3042       //   c->A::member
3043 
3044       // Find results in this base class (and its bases).
3045       ShadowContextRAII Shadow(Visited);
3046       LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
3047                          true, Consumer, Visited);
3048     }
3049   }
3050 
3051   // Traverse the contexts of Objective-C classes.
3052   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3053     // Traverse categories.
3054     for (auto *Cat : IFace->visible_categories()) {
3055       ShadowContextRAII Shadow(Visited);
3056       LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
3057                          Consumer, Visited);
3058     }
3059 
3060     // Traverse protocols.
3061     for (auto *I : IFace->all_referenced_protocols()) {
3062       ShadowContextRAII Shadow(Visited);
3063       LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3064                          Visited);
3065     }
3066 
3067     // Traverse the superclass.
3068     if (IFace->getSuperClass()) {
3069       ShadowContextRAII Shadow(Visited);
3070       LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
3071                          true, Consumer, Visited);
3072     }
3073 
3074     // If there is an implementation, traverse it. We do this to find
3075     // synthesized ivars.
3076     if (IFace->getImplementation()) {
3077       ShadowContextRAII Shadow(Visited);
3078       LookupVisibleDecls(IFace->getImplementation(), Result,
3079                          QualifiedNameLookup, InBaseClass, Consumer, Visited);
3080     }
3081   } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3082     for (auto *I : Protocol->protocols()) {
3083       ShadowContextRAII Shadow(Visited);
3084       LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3085                          Visited);
3086     }
3087   } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3088     for (auto *I : Category->protocols()) {
3089       ShadowContextRAII Shadow(Visited);
3090       LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3091                          Visited);
3092     }
3093 
3094     // If there is an implementation, traverse it.
3095     if (Category->getImplementation()) {
3096       ShadowContextRAII Shadow(Visited);
3097       LookupVisibleDecls(Category->getImplementation(), Result,
3098                          QualifiedNameLookup, true, Consumer, Visited);
3099     }
3100   }
3101 }
3102 
3103 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3104                                UnqualUsingDirectiveSet &UDirs,
3105                                VisibleDeclConsumer &Consumer,
3106                                VisibleDeclsRecord &Visited) {
3107   if (!S)
3108     return;
3109 
3110   if (!S->getEntity() ||
3111       (!S->getParent() &&
3112        !Visited.alreadyVisitedContext(S->getEntity())) ||
3113       (S->getEntity())->isFunctionOrMethod()) {
3114     FindLocalExternScope FindLocals(Result);
3115     // Walk through the declarations in this Scope.
3116     for (auto *D : S->decls()) {
3117       if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3118         if ((ND = Result.getAcceptableDecl(ND))) {
3119           Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
3120           Visited.add(ND);
3121         }
3122     }
3123   }
3124 
3125   // FIXME: C++ [temp.local]p8
3126   DeclContext *Entity = nullptr;
3127   if (S->getEntity()) {
3128     // Look into this scope's declaration context, along with any of its
3129     // parent lookup contexts (e.g., enclosing classes), up to the point
3130     // where we hit the context stored in the next outer scope.
3131     Entity = S->getEntity();
3132     DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3133 
3134     for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3135          Ctx = Ctx->getLookupParent()) {
3136       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3137         if (Method->isInstanceMethod()) {
3138           // For instance methods, look for ivars in the method's interface.
3139           LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3140                                   Result.getNameLoc(), Sema::LookupMemberName);
3141           if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3142             LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3143                                /*InBaseClass=*/false, Consumer, Visited);
3144           }
3145         }
3146 
3147         // We've already performed all of the name lookup that we need
3148         // to for Objective-C methods; the next context will be the
3149         // outer scope.
3150         break;
3151       }
3152 
3153       if (Ctx->isFunctionOrMethod())
3154         continue;
3155 
3156       LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3157                          /*InBaseClass=*/false, Consumer, Visited);
3158     }
3159   } else if (!S->getParent()) {
3160     // Look into the translation unit scope. We walk through the translation
3161     // unit's declaration context, because the Scope itself won't have all of
3162     // the declarations if we loaded a precompiled header.
3163     // FIXME: We would like the translation unit's Scope object to point to the
3164     // translation unit, so we don't need this special "if" branch. However,
3165     // doing so would force the normal C++ name-lookup code to look into the
3166     // translation unit decl when the IdentifierInfo chains would suffice.
3167     // Once we fix that problem (which is part of a more general "don't look
3168     // in DeclContexts unless we have to" optimization), we can eliminate this.
3169     Entity = Result.getSema().Context.getTranslationUnitDecl();
3170     LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3171                        /*InBaseClass=*/false, Consumer, Visited);
3172   }
3173 
3174   if (Entity) {
3175     // Lookup visible declarations in any namespaces found by using
3176     // directives.
3177     UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3178     std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3179     for (; UI != UEnd; ++UI)
3180       LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
3181                          Result, /*QualifiedNameLookup=*/false,
3182                          /*InBaseClass=*/false, Consumer, Visited);
3183   }
3184 
3185   // Lookup names in the parent scope.
3186   ShadowContextRAII Shadow(Visited);
3187   LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3188 }
3189 
3190 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3191                               VisibleDeclConsumer &Consumer,
3192                               bool IncludeGlobalScope) {
3193   // Determine the set of using directives available during
3194   // unqualified name lookup.
3195   Scope *Initial = S;
3196   UnqualUsingDirectiveSet UDirs;
3197   if (getLangOpts().CPlusPlus) {
3198     // Find the first namespace or translation-unit scope.
3199     while (S && !isNamespaceOrTranslationUnitScope(S))
3200       S = S->getParent();
3201 
3202     UDirs.visitScopeChain(Initial, S);
3203   }
3204   UDirs.done();
3205 
3206   // Look for visible declarations.
3207   LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3208   Result.setAllowHidden(Consumer.includeHiddenDecls());
3209   VisibleDeclsRecord Visited;
3210   if (!IncludeGlobalScope)
3211     Visited.visitedContext(Context.getTranslationUnitDecl());
3212   ShadowContextRAII Shadow(Visited);
3213   ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3214 }
3215 
3216 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3217                               VisibleDeclConsumer &Consumer,
3218                               bool IncludeGlobalScope) {
3219   LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3220   Result.setAllowHidden(Consumer.includeHiddenDecls());
3221   VisibleDeclsRecord Visited;
3222   if (!IncludeGlobalScope)
3223     Visited.visitedContext(Context.getTranslationUnitDecl());
3224   ShadowContextRAII Shadow(Visited);
3225   ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3226                        /*InBaseClass=*/false, Consumer, Visited);
3227 }
3228 
3229 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3230 /// If GnuLabelLoc is a valid source location, then this is a definition
3231 /// of an __label__ label name, otherwise it is a normal label definition
3232 /// or use.
3233 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3234                                      SourceLocation GnuLabelLoc) {
3235   // Do a lookup to see if we have a label with this name already.
3236   NamedDecl *Res = nullptr;
3237 
3238   if (GnuLabelLoc.isValid()) {
3239     // Local label definitions always shadow existing labels.
3240     Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3241     Scope *S = CurScope;
3242     PushOnScopeChains(Res, S, true);
3243     return cast<LabelDecl>(Res);
3244   }
3245 
3246   // Not a GNU local label.
3247   Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3248   // If we found a label, check to see if it is in the same context as us.
3249   // When in a Block, we don't want to reuse a label in an enclosing function.
3250   if (Res && Res->getDeclContext() != CurContext)
3251     Res = nullptr;
3252   if (!Res) {
3253     // If not forward referenced or defined already, create the backing decl.
3254     Res = LabelDecl::Create(Context, CurContext, Loc, II);
3255     Scope *S = CurScope->getFnParent();
3256     assert(S && "Not in a function?");
3257     PushOnScopeChains(Res, S, true);
3258   }
3259   return cast<LabelDecl>(Res);
3260 }
3261 
3262 //===----------------------------------------------------------------------===//
3263 // Typo correction
3264 //===----------------------------------------------------------------------===//
3265 
3266 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3267                               TypoCorrection &Candidate) {
3268   Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3269   return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3270 }
3271 
3272 static void LookupPotentialTypoResult(Sema &SemaRef,
3273                                       LookupResult &Res,
3274                                       IdentifierInfo *Name,
3275                                       Scope *S, CXXScopeSpec *SS,
3276                                       DeclContext *MemberContext,
3277                                       bool EnteringContext,
3278                                       bool isObjCIvarLookup,
3279                                       bool FindHidden);
3280 
3281 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
3282 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3283 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3284 static void getNestedNameSpecifierIdentifiers(
3285     NestedNameSpecifier *NNS,
3286     SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3287   if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3288     getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3289   else
3290     Identifiers.clear();
3291 
3292   const IdentifierInfo *II = nullptr;
3293 
3294   switch (NNS->getKind()) {
3295   case NestedNameSpecifier::Identifier:
3296     II = NNS->getAsIdentifier();
3297     break;
3298 
3299   case NestedNameSpecifier::Namespace:
3300     if (NNS->getAsNamespace()->isAnonymousNamespace())
3301       return;
3302     II = NNS->getAsNamespace()->getIdentifier();
3303     break;
3304 
3305   case NestedNameSpecifier::NamespaceAlias:
3306     II = NNS->getAsNamespaceAlias()->getIdentifier();
3307     break;
3308 
3309   case NestedNameSpecifier::TypeSpecWithTemplate:
3310   case NestedNameSpecifier::TypeSpec:
3311     II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3312     break;
3313 
3314   case NestedNameSpecifier::Global:
3315   case NestedNameSpecifier::Super:
3316     return;
3317   }
3318 
3319   if (II)
3320     Identifiers.push_back(II);
3321 }
3322 
3323 namespace {
3324 
3325 static const unsigned MaxTypoDistanceResultSets = 5;
3326 
3327 class TypoCorrectionConsumer : public VisibleDeclConsumer {
3328   typedef SmallVector<TypoCorrection, 1> TypoResultList;
3329   typedef llvm::StringMap<TypoResultList> TypoResultsMap;
3330   typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
3331 
3332 public:
3333   explicit TypoCorrectionConsumer(Sema &SemaRef,
3334                                   const DeclarationNameInfo &TypoName,
3335                                   Sema::LookupNameKind LookupKind,
3336                                   Scope *S, CXXScopeSpec *SS,
3337                                   CorrectionCandidateCallback &CCC,
3338                                   DeclContext *MemberContext,
3339                                   bool EnteringContext)
3340       : Typo(TypoName.getName().getAsIdentifierInfo()), SemaRef(SemaRef), S(S),
3341         SS(SS), CorrectionValidator(CCC), MemberContext(MemberContext),
3342         Result(SemaRef, TypoName, LookupKind),
3343         Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
3344         EnteringContext(EnteringContext), SearchNamespaces(false) {
3345     Result.suppressDiagnostics();
3346   }
3347 
3348   bool includeHiddenDecls() const override { return true; }
3349 
3350   // Methods for adding potential corrections to the consumer.
3351   void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3352                  bool InBaseClass) override;
3353   void FoundName(StringRef Name);
3354   void addKeywordResult(StringRef Keyword);
3355   void addCorrection(TypoCorrection Correction);
3356 
3357   bool empty() const { return CorrectionResults.empty(); }
3358 
3359   /// \brief Return the list of TypoCorrections for the given identifier from
3360   /// the set of corrections that have the closest edit distance, if any.
3361   TypoResultList &operator[](StringRef Name) {
3362     return CorrectionResults.begin()->second[Name];
3363   }
3364 
3365   /// \brief Return the edit distance of the corrections that have the
3366   /// closest/best edit distance from the original typop.
3367   unsigned getBestEditDistance(bool Normalized) {
3368     if (CorrectionResults.empty())
3369       return (std::numeric_limits<unsigned>::max)();
3370 
3371     unsigned BestED = CorrectionResults.begin()->first;
3372     return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
3373   }
3374 
3375   /// \brief Set-up method to add to the consumer the set of namespaces to use
3376   /// in performing corrections to nested name specifiers. This method also
3377   /// implicitly adds all of the known classes in the current AST context to the
3378   /// to the consumer for correcting nested name specifiers.
3379   void
3380   addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
3381 
3382   /// \brief Return the next typo correction that passes all internal filters
3383   /// and is deemed valid by the consumer's CorrectionCandidateCallback,
3384   /// starting with the corrections that have the closest edit distance. An
3385   /// empty TypoCorrection is returned once no more viable corrections remain
3386   /// in the consumer.
3387   TypoCorrection getNextCorrection();
3388 
3389 private:
3390   class NamespaceSpecifierSet {
3391     struct SpecifierInfo {
3392       DeclContext* DeclCtx;
3393       NestedNameSpecifier* NameSpecifier;
3394       unsigned EditDistance;
3395     };
3396 
3397     typedef SmallVector<DeclContext*, 4> DeclContextList;
3398     typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3399 
3400     ASTContext &Context;
3401     DeclContextList CurContextChain;
3402     std::string CurNameSpecifier;
3403     SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3404     SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
3405     bool isSorted;
3406 
3407     SpecifierInfoList Specifiers;
3408     llvm::SmallSetVector<unsigned, 4> Distances;
3409     llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3410 
3411     /// \brief Helper for building the list of DeclContexts between the current
3412     /// context and the top of the translation unit
3413     static DeclContextList buildContextChain(DeclContext *Start);
3414 
3415     void sortNamespaces();
3416 
3417     unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
3418                                       NestedNameSpecifier *&NNS);
3419 
3420    public:
3421     NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3422                           CXXScopeSpec *CurScopeSpec);
3423 
3424     /// \brief Add the DeclContext (a namespace or record) to the set, computing
3425     /// the corresponding NestedNameSpecifier and its distance in the process.
3426     void addNameSpecifier(DeclContext *Ctx);
3427 
3428     typedef SpecifierInfoList::iterator iterator;
3429     iterator begin() {
3430       if (!isSorted) sortNamespaces();
3431       return Specifiers.begin();
3432     }
3433     iterator end() { return Specifiers.end(); }
3434   };
3435 
3436   void addName(StringRef Name, NamedDecl *ND,
3437                NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
3438 
3439   /// \brief Find any visible decls for the given typo correction candidate.
3440   /// If none are found, it to the set of candidates for which qualified lookups
3441   /// will be performed to find possible nested name specifier changes.
3442   bool resolveCorrection(TypoCorrection &Candidate);
3443 
3444   /// \brief Perform qualified lookups on the queued set of typo correction
3445   /// candidates and add the nested name specifier changes to each candidate if
3446   /// a lookup succeeds (at which point the candidate will be returned to the
3447   /// main pool of potential corrections).
3448   void performQualifiedLookups();
3449 
3450   /// \brief The name written that is a typo in the source.
3451   IdentifierInfo *Typo;
3452 
3453   /// \brief The results found that have the smallest edit distance
3454   /// found (so far) with the typo name.
3455   ///
3456   /// The pointer value being set to the current DeclContext indicates
3457   /// whether there is a keyword with this name.
3458   TypoEditDistanceMap CorrectionResults;
3459 
3460   Sema &SemaRef;
3461   Scope *S;
3462   CXXScopeSpec *SS;
3463   CorrectionCandidateCallback &CorrectionValidator;
3464   DeclContext *MemberContext;
3465   LookupResult Result;
3466   NamespaceSpecifierSet Namespaces;
3467   SmallVector<TypoCorrection, 2> QualifiedResults;
3468   bool EnteringContext;
3469   bool SearchNamespaces;
3470 };
3471 
3472 }
3473 
3474 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3475                                        DeclContext *Ctx, bool InBaseClass) {
3476   // Don't consider hidden names for typo correction.
3477   if (Hiding)
3478     return;
3479 
3480   // Only consider entities with identifiers for names, ignoring
3481   // special names (constructors, overloaded operators, selectors,
3482   // etc.).
3483   IdentifierInfo *Name = ND->getIdentifier();
3484   if (!Name)
3485     return;
3486 
3487   // Only consider visible declarations and declarations from modules with
3488   // names that exactly match.
3489   if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
3490       !findAcceptableDecl(SemaRef, ND))
3491     return;
3492 
3493   FoundName(Name->getName());
3494 }
3495 
3496 void TypoCorrectionConsumer::FoundName(StringRef Name) {
3497   // Compute the edit distance between the typo and the name of this
3498   // entity, and add the identifier to the list of results.
3499   addName(Name, nullptr);
3500 }
3501 
3502 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3503   // Compute the edit distance between the typo and this keyword,
3504   // and add the keyword to the list of results.
3505   addName(Keyword, nullptr, nullptr, true);
3506 }
3507 
3508 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3509                                      NestedNameSpecifier *NNS, bool isKeyword) {
3510   // Use a simple length-based heuristic to determine the minimum possible
3511   // edit distance. If the minimum isn't good enough, bail out early.
3512   StringRef TypoStr = Typo->getName();
3513   unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3514   if (MinED && TypoStr.size() / MinED < 3)
3515     return;
3516 
3517   // Compute an upper bound on the allowable edit distance, so that the
3518   // edit-distance algorithm can short-circuit.
3519   unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3520   unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
3521   if (ED >= UpperBound) return;
3522 
3523   TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
3524   if (isKeyword) TC.makeKeyword();
3525   addCorrection(TC);
3526 }
3527 
3528 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3529   StringRef TypoStr = Typo->getName();
3530   StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3531 
3532   // For very short typos, ignore potential corrections that have a different
3533   // base identifier from the typo or which have a normalized edit distance
3534   // longer than the typo itself.
3535   if (TypoStr.size() < 3 &&
3536       (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3537     return;
3538 
3539   // If the correction is resolved but is not viable, ignore it.
3540   if (Correction.isResolved() &&
3541       !isCandidateViable(CorrectionValidator, Correction))
3542     return;
3543 
3544   TypoResultList &CList =
3545       CorrectionResults[Correction.getEditDistance(false)][Name];
3546 
3547   if (!CList.empty() && !CList.back().isResolved())
3548     CList.pop_back();
3549   if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3550     std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3551     for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3552          RI != RIEnd; ++RI) {
3553       // If the Correction refers to a decl already in the result list,
3554       // replace the existing result if the string representation of Correction
3555       // comes before the current result alphabetically, then stop as there is
3556       // nothing more to be done to add Correction to the candidate set.
3557       if (RI->getCorrectionDecl() == NewND) {
3558         if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3559           *RI = Correction;
3560         return;
3561       }
3562     }
3563   }
3564   if (CList.empty() || Correction.isResolved())
3565     CList.push_back(Correction);
3566 
3567   while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3568     CorrectionResults.erase(std::prev(CorrectionResults.end()));
3569 }
3570 
3571 void TypoCorrectionConsumer::addNamespaces(
3572     const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3573   SearchNamespaces = true;
3574 
3575   for (auto KNPair : KnownNamespaces)
3576     Namespaces.addNameSpecifier(KNPair.first);
3577 
3578   bool SSIsTemplate = false;
3579   if (NestedNameSpecifier *NNS =
3580           (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3581     if (const Type *T = NNS->getAsType())
3582       SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3583   }
3584   for (const auto *TI : SemaRef.getASTContext().types()) {
3585     if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3586       CD = CD->getCanonicalDecl();
3587       if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3588           !CD->isUnion() && CD->getIdentifier() &&
3589           (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3590           (CD->isBeingDefined() || CD->isCompleteDefinition()))
3591         Namespaces.addNameSpecifier(CD);
3592     }
3593   }
3594 }
3595 
3596 TypoCorrection TypoCorrectionConsumer::getNextCorrection() {
3597   while (!CorrectionResults.empty()) {
3598     auto DI = CorrectionResults.begin();
3599     if (DI->second.empty()) {
3600       CorrectionResults.erase(DI);
3601       continue;
3602     }
3603 
3604     auto RI = DI->second.begin();
3605     if (RI->second.empty()) {
3606       DI->second.erase(RI);
3607       performQualifiedLookups();
3608       continue;
3609     }
3610 
3611     TypoCorrection TC = RI->second.pop_back_val();
3612     if (TC.isResolved() || resolveCorrection(TC))
3613       return TC;
3614   }
3615   return TypoCorrection();
3616 }
3617 
3618 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3619   IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3620   DeclContext *TempMemberContext = MemberContext;
3621   CXXScopeSpec *TempSS = SS;
3622 retry_lookup:
3623   LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3624                             EnteringContext,
3625                             CorrectionValidator.IsObjCIvarLookup,
3626                             Name == Typo && !Candidate.WillReplaceSpecifier());
3627   switch (Result.getResultKind()) {
3628   case LookupResult::NotFound:
3629   case LookupResult::NotFoundInCurrentInstantiation:
3630   case LookupResult::FoundUnresolvedValue:
3631     if (TempSS) {
3632       // Immediately retry the lookup without the given CXXScopeSpec
3633       TempSS = nullptr;
3634       Candidate.WillReplaceSpecifier(true);
3635       goto retry_lookup;
3636     }
3637     if (TempMemberContext) {
3638       if (SS && !TempSS)
3639         TempSS = SS;
3640       TempMemberContext = nullptr;
3641       goto retry_lookup;
3642     }
3643     if (SearchNamespaces)
3644       QualifiedResults.push_back(Candidate);
3645     break;
3646 
3647   case LookupResult::Ambiguous:
3648     // We don't deal with ambiguities.
3649     break;
3650 
3651   case LookupResult::Found:
3652   case LookupResult::FoundOverloaded:
3653     // Store all of the Decls for overloaded symbols
3654     for (auto *TRD : Result)
3655       Candidate.addCorrectionDecl(TRD);
3656     if (!isCandidateViable(CorrectionValidator, Candidate)) {
3657       if (SearchNamespaces)
3658         QualifiedResults.push_back(Candidate);
3659       break;
3660     }
3661     return true;
3662   }
3663   return false;
3664 }
3665 
3666 void TypoCorrectionConsumer::performQualifiedLookups() {
3667   unsigned TypoLen = Typo->getName().size();
3668   for (auto QR : QualifiedResults) {
3669     for (auto NSI : Namespaces) {
3670       DeclContext *Ctx = NSI.DeclCtx;
3671       const Type *NSType = NSI.NameSpecifier->getAsType();
3672 
3673       // If the current NestedNameSpecifier refers to a class and the
3674       // current correction candidate is the name of that class, then skip
3675       // it as it is unlikely a qualified version of the class' constructor
3676       // is an appropriate correction.
3677       if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3678         if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3679           continue;
3680       }
3681 
3682       TypoCorrection TC(QR);
3683       TC.ClearCorrectionDecls();
3684       TC.setCorrectionSpecifier(NSI.NameSpecifier);
3685       TC.setQualifierDistance(NSI.EditDistance);
3686       TC.setCallbackDistance(0); // Reset the callback distance
3687 
3688       // If the current correction candidate and namespace combination are
3689       // too far away from the original typo based on the normalized edit
3690       // distance, then skip performing a qualified name lookup.
3691       unsigned TmpED = TC.getEditDistance(true);
3692       if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3693           TypoLen / TmpED < 3)
3694         continue;
3695 
3696       Result.clear();
3697       Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3698       if (!SemaRef.LookupQualifiedName(Result, Ctx))
3699         continue;
3700 
3701       // Any corrections added below will be validated in subsequent
3702       // iterations of the main while() loop over the Consumer's contents.
3703       switch (Result.getResultKind()) {
3704       case LookupResult::Found:
3705       case LookupResult::FoundOverloaded: {
3706         if (SS && SS->isValid()) {
3707           std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3708           std::string OldQualified;
3709           llvm::raw_string_ostream OldOStream(OldQualified);
3710           SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3711           OldOStream << Typo->getName();
3712           // If correction candidate would be an identical written qualified
3713           // identifer, then the existing CXXScopeSpec probably included a
3714           // typedef that didn't get accounted for properly.
3715           if (OldOStream.str() == NewQualified)
3716             break;
3717         }
3718         for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3719              TRD != TRDEnd; ++TRD) {
3720           if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3721                                         NSType ? NSType->getAsCXXRecordDecl()
3722                                                : nullptr,
3723                                         TRD.getPair()) == Sema::AR_accessible)
3724             TC.addCorrectionDecl(*TRD);
3725         }
3726         if (TC.isResolved())
3727           addCorrection(TC);
3728         break;
3729       }
3730       case LookupResult::NotFound:
3731       case LookupResult::NotFoundInCurrentInstantiation:
3732       case LookupResult::Ambiguous:
3733       case LookupResult::FoundUnresolvedValue:
3734         break;
3735       }
3736     }
3737   }
3738   QualifiedResults.clear();
3739 }
3740 
3741 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3742     ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
3743     : Context(Context), CurContextChain(buildContextChain(CurContext)),
3744       isSorted(false) {
3745   if (NestedNameSpecifier *NNS =
3746           CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3747     llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3748     NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3749 
3750     getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3751   }
3752   // Build the list of identifiers that would be used for an absolute
3753   // (from the global context) NestedNameSpecifier referring to the current
3754   // context.
3755   for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3756                                          CEnd = CurContextChain.rend();
3757        C != CEnd; ++C) {
3758     if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3759       CurContextIdentifiers.push_back(ND->getIdentifier());
3760   }
3761 
3762   // Add the global context as a NestedNameSpecifier
3763   Distances.insert(1);
3764   SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3765                       NestedNameSpecifier::GlobalSpecifier(Context), 1};
3766   DistanceMap[1].push_back(SI);
3767 }
3768 
3769 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3770     DeclContext *Start) -> DeclContextList {
3771   assert(Start && "Building a context chain from a null context");
3772   DeclContextList Chain;
3773   for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
3774        DC = DC->getLookupParent()) {
3775     NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3776     if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3777         !(ND && ND->isAnonymousNamespace()))
3778       Chain.push_back(DC->getPrimaryContext());
3779   }
3780   return Chain;
3781 }
3782 
3783 void TypoCorrectionConsumer::NamespaceSpecifierSet::sortNamespaces() {
3784   SmallVector<unsigned, 4> sortedDistances;
3785   sortedDistances.append(Distances.begin(), Distances.end());
3786 
3787   if (sortedDistances.size() > 1)
3788     std::sort(sortedDistances.begin(), sortedDistances.end());
3789 
3790   Specifiers.clear();
3791   for (auto D : sortedDistances) {
3792     SpecifierInfoList &SpecList = DistanceMap[D];
3793     Specifiers.append(SpecList.begin(), SpecList.end());
3794   }
3795 
3796   isSorted = true;
3797 }
3798 
3799 unsigned
3800 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3801     DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
3802   unsigned NumSpecifiers = 0;
3803   for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3804                                       CEnd = DeclChain.rend();
3805        C != CEnd; ++C) {
3806     if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3807       NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3808       ++NumSpecifiers;
3809     } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3810       NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3811                                         RD->getTypeForDecl());
3812       ++NumSpecifiers;
3813     }
3814   }
3815   return NumSpecifiers;
3816 }
3817 
3818 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3819     DeclContext *Ctx) {
3820   NestedNameSpecifier *NNS = nullptr;
3821   unsigned NumSpecifiers = 0;
3822   DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
3823   DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3824 
3825   // Eliminate common elements from the two DeclContext chains.
3826   for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3827                                       CEnd = CurContextChain.rend();
3828        C != CEnd && !NamespaceDeclChain.empty() &&
3829        NamespaceDeclChain.back() == *C; ++C) {
3830     NamespaceDeclChain.pop_back();
3831   }
3832 
3833   // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3834   NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
3835 
3836   // Add an explicit leading '::' specifier if needed.
3837   if (NamespaceDeclChain.empty()) {
3838     // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3839     NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3840     NumSpecifiers =
3841         buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
3842   } else if (NamedDecl *ND =
3843                  dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
3844     IdentifierInfo *Name = ND->getIdentifier();
3845     bool SameNameSpecifier = false;
3846     if (std::find(CurNameSpecifierIdentifiers.begin(),
3847                   CurNameSpecifierIdentifiers.end(),
3848                   Name) != CurNameSpecifierIdentifiers.end()) {
3849       std::string NewNameSpecifier;
3850       llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3851       SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3852       getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3853       NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3854       SpecifierOStream.flush();
3855       SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
3856     }
3857     if (SameNameSpecifier ||
3858         std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3859                   Name) != CurContextIdentifiers.end()) {
3860       // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3861       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3862       NumSpecifiers =
3863           buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
3864     }
3865   }
3866 
3867   // If the built NestedNameSpecifier would be replacing an existing
3868   // NestedNameSpecifier, use the number of component identifiers that
3869   // would need to be changed as the edit distance instead of the number
3870   // of components in the built NestedNameSpecifier.
3871   if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3872     SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3873     getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3874     NumSpecifiers = llvm::ComputeEditDistance(
3875         llvm::makeArrayRef(CurNameSpecifierIdentifiers),
3876         llvm::makeArrayRef(NewNameSpecifierIdentifiers));
3877   }
3878 
3879   isSorted = false;
3880   Distances.insert(NumSpecifiers);
3881   SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
3882   DistanceMap[NumSpecifiers].push_back(SI);
3883 }
3884 
3885 /// \brief Perform name lookup for a possible result for typo correction.
3886 static void LookupPotentialTypoResult(Sema &SemaRef,
3887                                       LookupResult &Res,
3888                                       IdentifierInfo *Name,
3889                                       Scope *S, CXXScopeSpec *SS,
3890                                       DeclContext *MemberContext,
3891                                       bool EnteringContext,
3892                                       bool isObjCIvarLookup,
3893                                       bool FindHidden) {
3894   Res.suppressDiagnostics();
3895   Res.clear();
3896   Res.setLookupName(Name);
3897   Res.setAllowHidden(FindHidden);
3898   if (MemberContext) {
3899     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3900       if (isObjCIvarLookup) {
3901         if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3902           Res.addDecl(Ivar);
3903           Res.resolveKind();
3904           return;
3905         }
3906       }
3907 
3908       if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3909         Res.addDecl(Prop);
3910         Res.resolveKind();
3911         return;
3912       }
3913     }
3914 
3915     SemaRef.LookupQualifiedName(Res, MemberContext);
3916     return;
3917   }
3918 
3919   SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3920                            EnteringContext);
3921 
3922   // Fake ivar lookup; this should really be part of
3923   // LookupParsedName.
3924   if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3925     if (Method->isInstanceMethod() && Method->getClassInterface() &&
3926         (Res.empty() ||
3927          (Res.isSingleResult() &&
3928           Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3929        if (ObjCIvarDecl *IV
3930              = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3931          Res.addDecl(IV);
3932          Res.resolveKind();
3933        }
3934      }
3935   }
3936 }
3937 
3938 /// \brief Add keywords to the consumer as possible typo corrections.
3939 static void AddKeywordsToConsumer(Sema &SemaRef,
3940                                   TypoCorrectionConsumer &Consumer,
3941                                   Scope *S, CorrectionCandidateCallback &CCC,
3942                                   bool AfterNestedNameSpecifier) {
3943   if (AfterNestedNameSpecifier) {
3944     // For 'X::', we know exactly which keywords can appear next.
3945     Consumer.addKeywordResult("template");
3946     if (CCC.WantExpressionKeywords)
3947       Consumer.addKeywordResult("operator");
3948     return;
3949   }
3950 
3951   if (CCC.WantObjCSuper)
3952     Consumer.addKeywordResult("super");
3953 
3954   if (CCC.WantTypeSpecifiers) {
3955     // Add type-specifier keywords to the set of results.
3956     static const char *const CTypeSpecs[] = {
3957       "char", "const", "double", "enum", "float", "int", "long", "short",
3958       "signed", "struct", "union", "unsigned", "void", "volatile",
3959       "_Complex", "_Imaginary",
3960       // storage-specifiers as well
3961       "extern", "inline", "static", "typedef"
3962     };
3963 
3964     const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
3965     for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3966       Consumer.addKeywordResult(CTypeSpecs[I]);
3967 
3968     if (SemaRef.getLangOpts().C99)
3969       Consumer.addKeywordResult("restrict");
3970     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
3971       Consumer.addKeywordResult("bool");
3972     else if (SemaRef.getLangOpts().C99)
3973       Consumer.addKeywordResult("_Bool");
3974 
3975     if (SemaRef.getLangOpts().CPlusPlus) {
3976       Consumer.addKeywordResult("class");
3977       Consumer.addKeywordResult("typename");
3978       Consumer.addKeywordResult("wchar_t");
3979 
3980       if (SemaRef.getLangOpts().CPlusPlus11) {
3981         Consumer.addKeywordResult("char16_t");
3982         Consumer.addKeywordResult("char32_t");
3983         Consumer.addKeywordResult("constexpr");
3984         Consumer.addKeywordResult("decltype");
3985         Consumer.addKeywordResult("thread_local");
3986       }
3987     }
3988 
3989     if (SemaRef.getLangOpts().GNUMode)
3990       Consumer.addKeywordResult("typeof");
3991   } else if (CCC.WantFunctionLikeCasts) {
3992     static const char *const CastableTypeSpecs[] = {
3993       "char", "double", "float", "int", "long", "short",
3994       "signed", "unsigned", "void"
3995     };
3996     for (auto *kw : CastableTypeSpecs)
3997       Consumer.addKeywordResult(kw);
3998   }
3999 
4000   if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
4001     Consumer.addKeywordResult("const_cast");
4002     Consumer.addKeywordResult("dynamic_cast");
4003     Consumer.addKeywordResult("reinterpret_cast");
4004     Consumer.addKeywordResult("static_cast");
4005   }
4006 
4007   if (CCC.WantExpressionKeywords) {
4008     Consumer.addKeywordResult("sizeof");
4009     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
4010       Consumer.addKeywordResult("false");
4011       Consumer.addKeywordResult("true");
4012     }
4013 
4014     if (SemaRef.getLangOpts().CPlusPlus) {
4015       static const char *const CXXExprs[] = {
4016         "delete", "new", "operator", "throw", "typeid"
4017       };
4018       const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
4019       for (unsigned I = 0; I != NumCXXExprs; ++I)
4020         Consumer.addKeywordResult(CXXExprs[I]);
4021 
4022       if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4023           cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4024         Consumer.addKeywordResult("this");
4025 
4026       if (SemaRef.getLangOpts().CPlusPlus11) {
4027         Consumer.addKeywordResult("alignof");
4028         Consumer.addKeywordResult("nullptr");
4029       }
4030     }
4031 
4032     if (SemaRef.getLangOpts().C11) {
4033       // FIXME: We should not suggest _Alignof if the alignof macro
4034       // is present.
4035       Consumer.addKeywordResult("_Alignof");
4036     }
4037   }
4038 
4039   if (CCC.WantRemainingKeywords) {
4040     if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4041       // Statements.
4042       static const char *const CStmts[] = {
4043         "do", "else", "for", "goto", "if", "return", "switch", "while" };
4044       const unsigned NumCStmts = llvm::array_lengthof(CStmts);
4045       for (unsigned I = 0; I != NumCStmts; ++I)
4046         Consumer.addKeywordResult(CStmts[I]);
4047 
4048       if (SemaRef.getLangOpts().CPlusPlus) {
4049         Consumer.addKeywordResult("catch");
4050         Consumer.addKeywordResult("try");
4051       }
4052 
4053       if (S && S->getBreakParent())
4054         Consumer.addKeywordResult("break");
4055 
4056       if (S && S->getContinueParent())
4057         Consumer.addKeywordResult("continue");
4058 
4059       if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4060         Consumer.addKeywordResult("case");
4061         Consumer.addKeywordResult("default");
4062       }
4063     } else {
4064       if (SemaRef.getLangOpts().CPlusPlus) {
4065         Consumer.addKeywordResult("namespace");
4066         Consumer.addKeywordResult("template");
4067       }
4068 
4069       if (S && S->isClassScope()) {
4070         Consumer.addKeywordResult("explicit");
4071         Consumer.addKeywordResult("friend");
4072         Consumer.addKeywordResult("mutable");
4073         Consumer.addKeywordResult("private");
4074         Consumer.addKeywordResult("protected");
4075         Consumer.addKeywordResult("public");
4076         Consumer.addKeywordResult("virtual");
4077       }
4078     }
4079 
4080     if (SemaRef.getLangOpts().CPlusPlus) {
4081       Consumer.addKeywordResult("using");
4082 
4083       if (SemaRef.getLangOpts().CPlusPlus11)
4084         Consumer.addKeywordResult("static_assert");
4085     }
4086   }
4087 }
4088 
4089 /// \brief Check whether the declarations found for a typo correction are
4090 /// visible, and if none of them are, convert the correction to an 'import
4091 /// a module' correction.
4092 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
4093   if (TC.begin() == TC.end())
4094     return;
4095 
4096   TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4097 
4098   for (/**/; DI != DE; ++DI)
4099     if (!LookupResult::isVisible(SemaRef, *DI))
4100       break;
4101   // Nothing to do if all decls are visible.
4102   if (DI == DE)
4103     return;
4104 
4105   llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4106   bool AnyVisibleDecls = !NewDecls.empty();
4107 
4108   for (/**/; DI != DE; ++DI) {
4109     NamedDecl *VisibleDecl = *DI;
4110     if (!LookupResult::isVisible(SemaRef, *DI))
4111       VisibleDecl = findAcceptableDecl(SemaRef, *DI);
4112 
4113     if (VisibleDecl) {
4114       if (!AnyVisibleDecls) {
4115         // Found a visible decl, discard all hidden ones.
4116         AnyVisibleDecls = true;
4117         NewDecls.clear();
4118       }
4119       NewDecls.push_back(VisibleDecl);
4120     } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4121       NewDecls.push_back(*DI);
4122   }
4123 
4124   if (NewDecls.empty())
4125     TC = TypoCorrection();
4126   else {
4127     TC.setCorrectionDecls(NewDecls);
4128     TC.setRequiresImport(!AnyVisibleDecls);
4129   }
4130 }
4131 
4132 /// \brief Try to "correct" a typo in the source code by finding
4133 /// visible declarations whose names are similar to the name that was
4134 /// present in the source code.
4135 ///
4136 /// \param TypoName the \c DeclarationNameInfo structure that contains
4137 /// the name that was present in the source code along with its location.
4138 ///
4139 /// \param LookupKind the name-lookup criteria used to search for the name.
4140 ///
4141 /// \param S the scope in which name lookup occurs.
4142 ///
4143 /// \param SS the nested-name-specifier that precedes the name we're
4144 /// looking for, if present.
4145 ///
4146 /// \param CCC A CorrectionCandidateCallback object that provides further
4147 /// validation of typo correction candidates. It also provides flags for
4148 /// determining the set of keywords permitted.
4149 ///
4150 /// \param MemberContext if non-NULL, the context in which to look for
4151 /// a member access expression.
4152 ///
4153 /// \param EnteringContext whether we're entering the context described by
4154 /// the nested-name-specifier SS.
4155 ///
4156 /// \param OPT when non-NULL, the search for visible declarations will
4157 /// also walk the protocols in the qualified interfaces of \p OPT.
4158 ///
4159 /// \returns a \c TypoCorrection containing the corrected name if the typo
4160 /// along with information such as the \c NamedDecl where the corrected name
4161 /// was declared, and any additional \c NestedNameSpecifier needed to access
4162 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4163 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4164                                  Sema::LookupNameKind LookupKind,
4165                                  Scope *S, CXXScopeSpec *SS,
4166                                  CorrectionCandidateCallback &CCC,
4167                                  CorrectTypoKind Mode,
4168                                  DeclContext *MemberContext,
4169                                  bool EnteringContext,
4170                                  const ObjCObjectPointerType *OPT,
4171                                  bool RecordFailure) {
4172   // Always let the ExternalSource have the first chance at correction, even
4173   // if we would otherwise have given up.
4174   if (ExternalSource) {
4175     if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4176         TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
4177       return Correction;
4178   }
4179 
4180   if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4181       DisableTypoCorrection)
4182     return TypoCorrection();
4183 
4184   // In Microsoft mode, don't perform typo correction in a template member
4185   // function dependent context because it interferes with the "lookup into
4186   // dependent bases of class templates" feature.
4187   if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4188       isa<CXXMethodDecl>(CurContext))
4189     return TypoCorrection();
4190 
4191   // We only attempt to correct typos for identifiers.
4192   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4193   if (!Typo)
4194     return TypoCorrection();
4195 
4196   // If the scope specifier itself was invalid, don't try to correct
4197   // typos.
4198   if (SS && SS->isInvalid())
4199     return TypoCorrection();
4200 
4201   // Never try to correct typos during template deduction or
4202   // instantiation.
4203   if (!ActiveTemplateInstantiations.empty())
4204     return TypoCorrection();
4205 
4206   // Don't try to correct 'super'.
4207   if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4208     return TypoCorrection();
4209 
4210   // Abort if typo correction already failed for this specific typo.
4211   IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4212   if (locs != TypoCorrectionFailures.end() &&
4213       locs->second.count(TypoName.getLoc()))
4214     return TypoCorrection();
4215 
4216   // Don't try to correct the identifier "vector" when in AltiVec mode.
4217   // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4218   // remove this workaround.
4219   if (getLangOpts().AltiVec && Typo->isStr("vector"))
4220     return TypoCorrection();
4221 
4222   // If we're handling a missing symbol error, using modules, and the
4223   // special search all modules option is used, look for a missing import.
4224   if ((Mode == CTK_ErrorRecovery) &&  getLangOpts().Modules &&
4225       getLangOpts().ModulesSearchAll) {
4226     // The following has the side effect of loading the missing module.
4227     getModuleLoader().lookupMissingImports(Typo->getName(),
4228                                            TypoName.getLocStart());
4229   }
4230 
4231   TypoCorrectionConsumer Consumer(*this, TypoName, LookupKind, S, SS, CCC,
4232                                   MemberContext, EnteringContext);
4233 
4234   // If a callback object considers an empty typo correction candidate to be
4235   // viable, assume it does not do any actual validation of the candidates.
4236   TypoCorrection EmptyCorrection;
4237   bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
4238 
4239   // Perform name lookup to find visible, similarly-named entities.
4240   bool IsUnqualifiedLookup = false;
4241   DeclContext *QualifiedDC = MemberContext;
4242   if (MemberContext) {
4243     LookupVisibleDecls(MemberContext, LookupKind, Consumer);
4244 
4245     // Look in qualified interfaces.
4246     if (OPT) {
4247       for (auto *I : OPT->quals())
4248         LookupVisibleDecls(I, LookupKind, Consumer);
4249     }
4250   } else if (SS && SS->isSet()) {
4251     QualifiedDC = computeDeclContext(*SS, EnteringContext);
4252     if (!QualifiedDC)
4253       return TypoCorrection();
4254 
4255     // Provide a stop gap for files that are just seriously broken.  Trying
4256     // to correct all typos can turn into a HUGE performance penalty, causing
4257     // some files to take minutes to get rejected by the parser.
4258     if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
4259       return TypoCorrection();
4260     ++TyposCorrected;
4261 
4262     LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
4263   } else {
4264     IsUnqualifiedLookup = true;
4265     UnqualifiedTyposCorrectedMap::iterator Cached
4266       = UnqualifiedTyposCorrected.find(Typo);
4267     if (Cached != UnqualifiedTyposCorrected.end()) {
4268       // Add the cached value, unless it's a keyword or fails validation. In the
4269       // keyword case, we'll end up adding the keyword below.
4270       if (Cached->second) {
4271         if (!Cached->second.isKeyword() &&
4272             isCandidateViable(CCC, Cached->second)) {
4273           // Do not use correction that is unaccessible in the given scope.
4274           NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
4275           DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4276                                        CorrectionDecl->getLocation());
4277           LookupResult R(*this, NameInfo, LookupOrdinaryName);
4278           if (LookupName(R, S))
4279             Consumer.addCorrection(Cached->second);
4280         }
4281       } else {
4282         // Only honor no-correction cache hits when a callback that will validate
4283         // correction candidates is not being used.
4284         if (!ValidatingCallback)
4285           return TypoCorrection();
4286       }
4287     }
4288     if (Cached == UnqualifiedTyposCorrected.end()) {
4289       // Provide a stop gap for files that are just seriously broken.  Trying
4290       // to correct all typos can turn into a HUGE performance penalty, causing
4291       // some files to take minutes to get rejected by the parser.
4292       if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
4293         return TypoCorrection();
4294     }
4295   }
4296 
4297   // Determine whether we are going to search in the various namespaces for
4298   // corrections.
4299   bool SearchNamespaces
4300     = getLangOpts().CPlusPlus &&
4301       (IsUnqualifiedLookup || (SS && SS->isSet()));
4302   // In a few cases we *only* want to search for corrections based on just
4303   // adding or changing the nested name specifier.
4304   unsigned TypoLen = Typo->getName().size();
4305   bool AllowOnlyNNSChanges = TypoLen < 3;
4306 
4307   if (IsUnqualifiedLookup || SearchNamespaces) {
4308     // For unqualified lookup, look through all of the names that we have
4309     // seen in this translation unit.
4310     // FIXME: Re-add the ability to skip very unlikely potential corrections.
4311     for (const auto &I : Context.Idents)
4312       Consumer.FoundName(I.getKey());
4313 
4314     // Walk through identifiers in external identifier sources.
4315     // FIXME: Re-add the ability to skip very unlikely potential corrections.
4316     if (IdentifierInfoLookup *External
4317                             = Context.Idents.getExternalIdentifierLookup()) {
4318       std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4319       do {
4320         StringRef Name = Iter->Next();
4321         if (Name.empty())
4322           break;
4323 
4324         Consumer.FoundName(Name);
4325       } while (true);
4326     }
4327   }
4328 
4329   AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
4330 
4331   // If we haven't found anything, we're done.
4332   if (Consumer.empty())
4333     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4334                             IsUnqualifiedLookup);
4335 
4336   // Make sure the best edit distance (prior to adding any namespace qualifiers)
4337   // is not more that about a third of the length of the typo's identifier.
4338   unsigned ED = Consumer.getBestEditDistance(true);
4339   if (ED > 0 && TypoLen / ED < 3)
4340     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4341                             IsUnqualifiedLookup);
4342 
4343   // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4344   // to search those namespaces.
4345   if (SearchNamespaces) {
4346     // Load any externally-known namespaces.
4347     if (ExternalSource && !LoadedExternalKnownNamespaces) {
4348       SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4349       LoadedExternalKnownNamespaces = true;
4350       ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4351       for (auto *N : ExternalKnownNamespaces)
4352         KnownNamespaces[N] = true;
4353     }
4354 
4355     Consumer.addNamespaces(KnownNamespaces);
4356   }
4357 
4358   TypoCorrection BestTC = Consumer.getNextCorrection();
4359   TypoCorrection SecondBestTC = Consumer.getNextCorrection();
4360   if (!BestTC)
4361     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4362 
4363   ED = BestTC.getEditDistance();
4364 
4365   if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
4366     // If this was an unqualified lookup and we believe the callback
4367     // object wouldn't have filtered out possible corrections, note
4368     // that no correction was found.
4369     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4370                             IsUnqualifiedLookup && !ValidatingCallback);
4371   }
4372 
4373   // If only a single name remains, return that result.
4374   if (!SecondBestTC ||
4375       SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4376     const TypoCorrection &Result = BestTC;
4377 
4378     // Don't correct to a keyword that's the same as the typo; the keyword
4379     // wasn't actually in scope.
4380     if (ED == 0 && Result.isKeyword())
4381       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4382 
4383     // Record the correction for unqualified lookup.
4384     if (IsUnqualifiedLookup)
4385       UnqualifiedTyposCorrected[Typo] = Result;
4386 
4387     TypoCorrection TC = Result;
4388     TC.setCorrectionRange(SS, TypoName);
4389     checkCorrectionVisibility(*this, TC);
4390     return TC;
4391   }
4392   // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4393   // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4394   // some instances of CTC_Unknown, while WantRemainingKeywords is true
4395   // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4396   else if (SecondBestTC && CCC.WantObjCSuper && !CCC.WantRemainingKeywords) {
4397     // Prefer 'super' when we're completing in a message-receiver
4398     // context.
4399 
4400     if (BestTC.getCorrection().getAsString() != "super") {
4401       if (SecondBestTC.getCorrection().getAsString() == "super")
4402         BestTC = SecondBestTC;
4403       else if (Consumer["super"].front().isKeyword())
4404         BestTC = Consumer["super"].front();
4405     }
4406     // Don't correct to a keyword that's the same as the typo; the keyword
4407     // wasn't actually in scope.
4408     if (BestTC.getEditDistance() == 0 ||
4409         BestTC.getCorrection().getAsString() != "super")
4410       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4411 
4412     // Record the correction for unqualified lookup.
4413     if (IsUnqualifiedLookup)
4414       UnqualifiedTyposCorrected[Typo] = BestTC;
4415 
4416     BestTC.setCorrectionRange(SS, TypoName);
4417     return BestTC;
4418   }
4419 
4420   // Record the failure's location if needed and return an empty correction. If
4421   // this was an unqualified lookup and we believe the callback object did not
4422   // filter out possible corrections, also cache the failure for the typo.
4423   return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4424                           IsUnqualifiedLookup && !ValidatingCallback);
4425 }
4426 
4427 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4428   if (!CDecl) return;
4429 
4430   if (isKeyword())
4431     CorrectionDecls.clear();
4432 
4433   CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
4434 
4435   if (!CorrectionName)
4436     CorrectionName = CDecl->getDeclName();
4437 }
4438 
4439 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4440   if (CorrectionNameSpec) {
4441     std::string tmpBuffer;
4442     llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4443     CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4444     PrefixOStream << CorrectionName;
4445     return PrefixOStream.str();
4446   }
4447 
4448   return CorrectionName.getAsString();
4449 }
4450 
4451 bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4452   if (!candidate.isResolved())
4453     return true;
4454 
4455   if (candidate.isKeyword())
4456     return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4457            WantRemainingKeywords || WantObjCSuper;
4458 
4459   bool HasNonType = false;
4460   bool HasStaticMethod = false;
4461   bool HasNonStaticMethod = false;
4462   for (Decl *D : candidate) {
4463     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4464       D = FTD->getTemplatedDecl();
4465     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4466       if (Method->isStatic())
4467         HasStaticMethod = true;
4468       else
4469         HasNonStaticMethod = true;
4470     }
4471     if (!isa<TypeDecl>(D))
4472       HasNonType = true;
4473   }
4474 
4475   if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4476       !candidate.getCorrectionSpecifier())
4477     return false;
4478 
4479   return WantTypeSpecifiers || HasNonType;
4480 }
4481 
4482 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4483                                              bool HasExplicitTemplateArgs,
4484                                              MemberExpr *ME)
4485     : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
4486       CurContext(SemaRef.CurContext), MemberFn(ME) {
4487   WantTypeSpecifiers = false;
4488   WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
4489   WantRemainingKeywords = false;
4490 }
4491 
4492 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4493   if (!candidate.getCorrectionDecl())
4494     return candidate.isKeyword();
4495 
4496   for (auto *C : candidate) {
4497     FunctionDecl *FD = nullptr;
4498     NamedDecl *ND = C->getUnderlyingDecl();
4499     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4500       FD = FTD->getTemplatedDecl();
4501     if (!HasExplicitTemplateArgs && !FD) {
4502       if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4503         // If the Decl is neither a function nor a template function,
4504         // determine if it is a pointer or reference to a function. If so,
4505         // check against the number of arguments expected for the pointee.
4506         QualType ValType = cast<ValueDecl>(ND)->getType();
4507         if (ValType->isAnyPointerType() || ValType->isReferenceType())
4508           ValType = ValType->getPointeeType();
4509         if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4510           if (FPT->getNumParams() == NumArgs)
4511             return true;
4512       }
4513     }
4514 
4515     // Skip the current candidate if it is not a FunctionDecl or does not accept
4516     // the current number of arguments.
4517     if (!FD || !(FD->getNumParams() >= NumArgs &&
4518                  FD->getMinRequiredArguments() <= NumArgs))
4519       continue;
4520 
4521     // If the current candidate is a non-static C++ method, skip the candidate
4522     // unless the method being corrected--or the current DeclContext, if the
4523     // function being corrected is not a method--is a method in the same class
4524     // or a descendent class of the candidate's parent class.
4525     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4526       if (MemberFn || !MD->isStatic()) {
4527         CXXMethodDecl *CurMD =
4528             MemberFn
4529                 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4530                 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
4531         CXXRecordDecl *CurRD =
4532             CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
4533         CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4534         if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4535           continue;
4536       }
4537     }
4538     return true;
4539   }
4540   return false;
4541 }
4542 
4543 void Sema::diagnoseTypo(const TypoCorrection &Correction,
4544                         const PartialDiagnostic &TypoDiag,
4545                         bool ErrorRecovery) {
4546   diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4547                ErrorRecovery);
4548 }
4549 
4550 /// Find which declaration we should import to provide the definition of
4551 /// the given declaration.
4552 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4553   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4554     return VD->getDefinition();
4555   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4556     return FD->isDefined(FD) ? FD : nullptr;
4557   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4558     return TD->getDefinition();
4559   if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4560     return ID->getDefinition();
4561   if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4562     return PD->getDefinition();
4563   if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4564     return getDefinitionToImport(TD->getTemplatedDecl());
4565   return nullptr;
4566 }
4567 
4568 /// \brief Diagnose a successfully-corrected typo. Separated from the correction
4569 /// itself to allow external validation of the result, etc.
4570 ///
4571 /// \param Correction The result of performing typo correction.
4572 /// \param TypoDiag The diagnostic to produce. This will have the corrected
4573 ///        string added to it (and usually also a fixit).
4574 /// \param PrevNote A note to use when indicating the location of the entity to
4575 ///        which we are correcting. Will have the correction string added to it.
4576 /// \param ErrorRecovery If \c true (the default), the caller is going to
4577 ///        recover from the typo as if the corrected string had been typed.
4578 ///        In this case, \c PDiag must be an error, and we will attach a fixit
4579 ///        to it.
4580 void Sema::diagnoseTypo(const TypoCorrection &Correction,
4581                         const PartialDiagnostic &TypoDiag,
4582                         const PartialDiagnostic &PrevNote,
4583                         bool ErrorRecovery) {
4584   std::string CorrectedStr = Correction.getAsString(getLangOpts());
4585   std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4586   FixItHint FixTypo = FixItHint::CreateReplacement(
4587       Correction.getCorrectionRange(), CorrectedStr);
4588 
4589   // Maybe we're just missing a module import.
4590   if (Correction.requiresImport()) {
4591     NamedDecl *Decl = Correction.getCorrectionDecl();
4592     assert(Decl && "import required but no declaration to import");
4593 
4594     // Suggest importing a module providing the definition of this entity, if
4595     // possible.
4596     const NamedDecl *Def = getDefinitionToImport(Decl);
4597     if (!Def)
4598       Def = Decl;
4599     Module *Owner = Def->getOwningModule();
4600     assert(Owner && "definition of hidden declaration is not in a module");
4601 
4602     Diag(Correction.getCorrectionRange().getBegin(),
4603          diag::err_module_private_declaration)
4604       << Def << Owner->getFullModuleName();
4605     Diag(Def->getLocation(), diag::note_previous_declaration);
4606 
4607     // Recover by implicitly importing this module.
4608     if (ErrorRecovery)
4609       createImplicitModuleImportForErrorRecovery(
4610           Correction.getCorrectionRange().getBegin(), Owner);
4611     return;
4612   }
4613 
4614   Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4615     << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4616 
4617   NamedDecl *ChosenDecl =
4618       Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
4619   if (PrevNote.getDiagID() && ChosenDecl)
4620     Diag(ChosenDecl->getLocation(), PrevNote)
4621       << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4622 }
4623