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