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