]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaLookup.cpp
Update clang to 97654.
[FreeBSD/FreeBSD.git] / lib / Sema / SemaLookup.cpp
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 "Sema.h"
15 #include "Lookup.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.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/Parse/DeclSpec.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include <list>
31 #include <set>
32 #include <vector>
33 #include <iterator>
34 #include <utility>
35 #include <algorithm>
36
37 using namespace clang;
38
39 namespace {
40   class UnqualUsingEntry {
41     const DeclContext *Nominated;
42     const DeclContext *CommonAncestor;
43
44   public:
45     UnqualUsingEntry(const DeclContext *Nominated,
46                      const DeclContext *CommonAncestor)
47       : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48     }
49
50     const DeclContext *getCommonAncestor() const {
51       return CommonAncestor;
52     }
53
54     const DeclContext *getNominatedNamespace() const {
55       return Nominated;
56     }
57
58     // Sort by the pointer value of the common ancestor.
59     struct Comparator {
60       bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61         return L.getCommonAncestor() < R.getCommonAncestor();
62       }
63
64       bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65         return E.getCommonAncestor() < DC;
66       }
67
68       bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69         return DC < E.getCommonAncestor();
70       }
71     };
72   };
73
74   /// A collection of using directives, as used by C++ unqualified
75   /// lookup.
76   class UnqualUsingDirectiveSet {
77     typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
78
79     ListTy list;
80     llvm::SmallPtrSet<DeclContext*, 8> visited;
81
82   public:
83     UnqualUsingDirectiveSet() {}
84
85     void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86       // C++ [namespace.udir]p1: 
87       //   During unqualified name lookup, the names appear as if they
88       //   were declared in the nearest enclosing namespace which contains
89       //   both the using-directive and the nominated namespace.
90       DeclContext *InnermostFileDC
91         = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92       assert(InnermostFileDC && InnermostFileDC->isFileContext());
93
94       for (; S; S = S->getParent()) {
95         if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96           DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97           visit(Ctx, EffectiveDC);
98         } else {
99           Scope::udir_iterator I = S->using_directives_begin(),
100                              End = S->using_directives_end();
101           
102           for (; I != End; ++I)
103             visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104         }
105       }
106     }
107
108     // Visits a context and collect all of its using directives
109     // recursively.  Treats all using directives as if they were
110     // declared in the context.
111     //
112     // A given context is only every visited once, so it is important
113     // that contexts be visited from the inside out in order to get
114     // the effective DCs right.
115     void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116       if (!visited.insert(DC))
117         return;
118
119       addUsingDirectives(DC, EffectiveDC);
120     }
121
122     // Visits a using directive and collects all of its using
123     // directives recursively.  Treats all using directives as if they
124     // were declared in the effective DC.
125     void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126       DeclContext *NS = UD->getNominatedNamespace();
127       if (!visited.insert(NS))
128         return;
129
130       addUsingDirective(UD, EffectiveDC);
131       addUsingDirectives(NS, EffectiveDC);
132     }
133
134     // Adds all the using directives in a context (and those nominated
135     // by its using directives, transitively) as if they appeared in
136     // the given effective context.
137     void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138       llvm::SmallVector<DeclContext*,4> queue;
139       while (true) {
140         DeclContext::udir_iterator I, End;
141         for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142           UsingDirectiveDecl *UD = *I;
143           DeclContext *NS = UD->getNominatedNamespace();
144           if (visited.insert(NS)) {
145             addUsingDirective(UD, EffectiveDC);
146             queue.push_back(NS);
147           }
148         }
149
150         if (queue.empty())
151           return;
152
153         DC = queue.back();
154         queue.pop_back();
155       }
156     }
157
158     // Add a using directive as if it had been declared in the given
159     // context.  This helps implement C++ [namespace.udir]p3:
160     //   The using-directive is transitive: if a scope contains a
161     //   using-directive that nominates a second namespace that itself
162     //   contains using-directives, the effect is as if the
163     //   using-directives from the second namespace also appeared in
164     //   the first.
165     void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166       // Find the common ancestor between the effective context and
167       // the nominated namespace.
168       DeclContext *Common = UD->getNominatedNamespace();
169       while (!Common->Encloses(EffectiveDC))
170         Common = Common->getParent();
171       Common = Common->getPrimaryContext();
172       
173       list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174     }
175
176     void done() {
177       std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178     }
179
180     typedef ListTy::iterator iterator;
181     typedef ListTy::const_iterator const_iterator;
182     
183     iterator begin() { return list.begin(); }
184     iterator end() { return list.end(); }
185     const_iterator begin() const { return list.begin(); }
186     const_iterator end() const { return list.end(); }
187
188     std::pair<const_iterator,const_iterator>
189     getNamespacesFor(DeclContext *DC) const {
190       return std::equal_range(begin(), end(), DC->getPrimaryContext(),
191                               UnqualUsingEntry::Comparator());
192     }
193   };
194 }
195
196 static bool IsAcceptableIDNS(NamedDecl *D, unsigned IDNS) {
197   return D->isInIdentifierNamespace(IDNS);
198 }
199
200 static bool IsAcceptableOperatorName(NamedDecl *D, unsigned IDNS) {
201   return D->isInIdentifierNamespace(IDNS) &&
202     !D->getDeclContext()->isRecord();
203 }
204
205 static bool IsAcceptableNestedNameSpecifierName(NamedDecl *D, unsigned IDNS) {
206   // This lookup ignores everything that isn't a type.
207
208   // This is a fast check for the far most common case.
209   if (D->isInIdentifierNamespace(Decl::IDNS_Tag))
210     return true;
211
212   if (isa<UsingShadowDecl>(D))
213     D = cast<UsingShadowDecl>(D)->getTargetDecl();
214
215   return isa<TypeDecl>(D);
216 }
217
218 static bool IsAcceptableNamespaceName(NamedDecl *D, unsigned IDNS) {
219   // We don't need to look through using decls here because
220   // using decls aren't allowed to name namespaces.
221
222   return isa<NamespaceDecl>(D) || isa<NamespaceAliasDecl>(D);
223 }
224
225 /// Gets the default result filter for the given lookup.
226 static inline
227 LookupResult::ResultFilter getResultFilter(Sema::LookupNameKind NameKind) {
228   switch (NameKind) {
229   case Sema::LookupOrdinaryName:
230   case Sema::LookupTagName:
231   case Sema::LookupMemberName:
232   case Sema::LookupRedeclarationWithLinkage: // FIXME: check linkage, scoping
233   case Sema::LookupUsingDeclName:
234   case Sema::LookupObjCProtocolName:
235   case Sema::LookupObjCImplementationName:
236     return &IsAcceptableIDNS;
237
238   case Sema::LookupOperatorName:
239     return &IsAcceptableOperatorName;
240
241   case Sema::LookupNestedNameSpecifierName:
242     return &IsAcceptableNestedNameSpecifierName;
243
244   case Sema::LookupNamespaceName:
245     return &IsAcceptableNamespaceName;
246   }
247
248   llvm_unreachable("unkknown lookup kind");
249   return 0;
250 }
251
252 // Retrieve the set of identifier namespaces that correspond to a
253 // specific kind of name lookup.
254 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
255                                bool CPlusPlus,
256                                bool Redeclaration) {
257   unsigned IDNS = 0;
258   switch (NameKind) {
259   case Sema::LookupOrdinaryName:
260   case Sema::LookupOperatorName:
261   case Sema::LookupRedeclarationWithLinkage:
262     IDNS = Decl::IDNS_Ordinary;
263     if (CPlusPlus) {
264       IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
265       if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
266     }
267     break;
268
269   case Sema::LookupTagName:
270     IDNS = Decl::IDNS_Tag;
271     if (CPlusPlus && Redeclaration)
272       IDNS |= Decl::IDNS_TagFriend;
273     break;
274
275   case Sema::LookupMemberName:
276     IDNS = Decl::IDNS_Member;
277     if (CPlusPlus)
278       IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
279     break;
280
281   case Sema::LookupNestedNameSpecifierName:
282   case Sema::LookupNamespaceName:
283     IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
284     break;
285
286   case Sema::LookupUsingDeclName:
287     IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
288          | Decl::IDNS_Member | Decl::IDNS_Using;
289     break;
290
291   case Sema::LookupObjCProtocolName:
292     IDNS = Decl::IDNS_ObjCProtocol;
293     break;
294
295   case Sema::LookupObjCImplementationName:
296     IDNS = Decl::IDNS_ObjCImplementation;
297     break;
298   }
299   return IDNS;
300 }
301
302 void LookupResult::configure() {
303   IDNS = getIDNS(LookupKind,
304                  SemaRef.getLangOptions().CPlusPlus,
305                  isForRedeclaration());
306   IsAcceptableFn = getResultFilter(LookupKind);
307 }
308
309 // Necessary because CXXBasePaths is not complete in Sema.h
310 void LookupResult::deletePaths(CXXBasePaths *Paths) {
311   delete Paths;
312 }
313
314 /// Resolves the result kind of this lookup.
315 void LookupResult::resolveKind() {
316   unsigned N = Decls.size();
317  
318   // Fast case: no possible ambiguity.
319   if (N == 0) {
320     assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
321     return;
322   }
323
324   // If there's a single decl, we need to examine it to decide what
325   // kind of lookup this is.
326   if (N == 1) {
327     if (isa<FunctionTemplateDecl>(*Decls.begin()))
328       ResultKind = FoundOverloaded;
329     else if (isa<UnresolvedUsingValueDecl>(*Decls.begin()))
330       ResultKind = FoundUnresolvedValue;
331     return;
332   }
333
334   // Don't do any extra resolution if we've already resolved as ambiguous.
335   if (ResultKind == Ambiguous) return;
336
337   llvm::SmallPtrSet<NamedDecl*, 16> Unique;
338
339   bool Ambiguous = false;
340   bool HasTag = false, HasFunction = false, HasNonFunction = false;
341   bool HasFunctionTemplate = false, HasUnresolved = false;
342
343   unsigned UniqueTagIndex = 0;
344   
345   unsigned I = 0;
346   while (I < N) {
347     NamedDecl *D = Decls[I]->getUnderlyingDecl();
348     D = cast<NamedDecl>(D->getCanonicalDecl());
349
350     if (!Unique.insert(D)) {
351       // If it's not unique, pull something off the back (and
352       // continue at this index).
353       Decls[I] = Decls[--N];
354     } else {
355       // Otherwise, do some decl type analysis and then continue.
356
357       if (isa<UnresolvedUsingValueDecl>(D)) {
358         HasUnresolved = true;
359       } else if (isa<TagDecl>(D)) {
360         if (HasTag)
361           Ambiguous = true;
362         UniqueTagIndex = I;
363         HasTag = true;
364       } else if (isa<FunctionTemplateDecl>(D)) {
365         HasFunction = true;
366         HasFunctionTemplate = true;
367       } else if (isa<FunctionDecl>(D)) {
368         HasFunction = true;
369       } else {
370         if (HasNonFunction)
371           Ambiguous = true;
372         HasNonFunction = true;
373       }
374       I++;
375     }
376   }
377
378   // C++ [basic.scope.hiding]p2:
379   //   A class name or enumeration name can be hidden by the name of
380   //   an object, function, or enumerator declared in the same
381   //   scope. If a class or enumeration name and an object, function,
382   //   or enumerator are declared in the same scope (in any order)
383   //   with the same name, the class or enumeration name is hidden
384   //   wherever the object, function, or enumerator name is visible.
385   // But it's still an error if there are distinct tag types found,
386   // even if they're not visible. (ref?)
387   if (HideTags && HasTag && !Ambiguous &&
388       (HasFunction || HasNonFunction || HasUnresolved))
389     Decls[UniqueTagIndex] = Decls[--N];
390
391   Decls.set_size(N);
392
393   if (HasNonFunction && (HasFunction || HasUnresolved))
394     Ambiguous = true;
395
396   if (Ambiguous)
397     setAmbiguous(LookupResult::AmbiguousReference);
398   else if (HasUnresolved)
399     ResultKind = LookupResult::FoundUnresolvedValue;
400   else if (N > 1 || HasFunctionTemplate)
401     ResultKind = LookupResult::FoundOverloaded;
402   else
403     ResultKind = LookupResult::Found;
404 }
405
406 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
407   CXXBasePaths::const_paths_iterator I, E;
408   DeclContext::lookup_iterator DI, DE;
409   for (I = P.begin(), E = P.end(); I != E; ++I)
410     for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
411       addDecl(*DI);
412 }
413
414 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
415   Paths = new CXXBasePaths;
416   Paths->swap(P);
417   addDeclsFromBasePaths(*Paths);
418   resolveKind();
419   setAmbiguous(AmbiguousBaseSubobjects);
420 }
421
422 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
423   Paths = new CXXBasePaths;
424   Paths->swap(P);
425   addDeclsFromBasePaths(*Paths);
426   resolveKind();
427   setAmbiguous(AmbiguousBaseSubobjectTypes);
428 }
429
430 void LookupResult::print(llvm::raw_ostream &Out) {
431   Out << Decls.size() << " result(s)";
432   if (isAmbiguous()) Out << ", ambiguous";
433   if (Paths) Out << ", base paths present";
434   
435   for (iterator I = begin(), E = end(); I != E; ++I) {
436     Out << "\n";
437     (*I)->print(Out, 2);
438   }
439 }
440
441 /// \brief Lookup a builtin function, when name lookup would otherwise
442 /// fail.
443 static bool LookupBuiltin(Sema &S, LookupResult &R) {
444   Sema::LookupNameKind NameKind = R.getLookupKind();
445
446   // If we didn't find a use of this identifier, and if the identifier
447   // corresponds to a compiler builtin, create the decl object for the builtin
448   // now, injecting it into translation unit scope, and return it.
449   if (NameKind == Sema::LookupOrdinaryName ||
450       NameKind == Sema::LookupRedeclarationWithLinkage) {
451     IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
452     if (II) {
453       // If this is a builtin on this (or all) targets, create the decl.
454       if (unsigned BuiltinID = II->getBuiltinID()) {
455         // In C++, we don't have any predefined library functions like
456         // 'malloc'. Instead, we'll just error.
457         if (S.getLangOptions().CPlusPlus &&
458             S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
459           return false;
460
461         NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
462                                              S.TUScope, R.isForRedeclaration(),
463                                              R.getNameLoc());
464         if (D) 
465           R.addDecl(D);
466         return (D != NULL);
467       }
468     }
469   }
470
471   return false;
472 }
473
474 // Adds all qualifying matches for a name within a decl context to the
475 // given lookup result.  Returns true if any matches were found.
476 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
477   bool Found = false;
478
479   DeclContext::lookup_const_iterator I, E;
480   for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
481     NamedDecl *D = *I;
482     if (R.isAcceptableDecl(D)) {
483       R.addDecl(D);
484       Found = true;
485     }
486   }
487
488   if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
489     return true;
490
491   if (R.getLookupName().getNameKind()
492         != DeclarationName::CXXConversionFunctionName ||
493       R.getLookupName().getCXXNameType()->isDependentType() ||
494       !isa<CXXRecordDecl>(DC))
495     return Found;
496
497   // C++ [temp.mem]p6:
498   //   A specialization of a conversion function template is not found by 
499   //   name lookup. Instead, any conversion function templates visible in the
500   //   context of the use are considered. [...]
501   const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
502   if (!Record->isDefinition())
503     return Found;
504
505   const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
506   for (UnresolvedSetImpl::iterator U = Unresolved->begin(), 
507          UEnd = Unresolved->end(); U != UEnd; ++U) {
508     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
509     if (!ConvTemplate)
510       continue;
511     
512     // When we're performing lookup for the purposes of redeclaration, just
513     // add the conversion function template. When we deduce template 
514     // arguments for specializations, we'll end up unifying the return 
515     // type of the new declaration with the type of the function template.
516     if (R.isForRedeclaration()) {
517       R.addDecl(ConvTemplate);
518       Found = true;
519       continue;
520     }
521     
522     // C++ [temp.mem]p6:
523     //   [...] For each such operator, if argument deduction succeeds 
524     //   (14.9.2.3), the resulting specialization is used as if found by 
525     //   name lookup.
526     //
527     // When referencing a conversion function for any purpose other than
528     // a redeclaration (such that we'll be building an expression with the
529     // result), perform template argument deduction and place the 
530     // specialization into the result set. We do this to avoid forcing all
531     // callers to perform special deduction for conversion functions.
532     Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
533     FunctionDecl *Specialization = 0;
534     
535     const FunctionProtoType *ConvProto        
536       = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
537     assert(ConvProto && "Nonsensical conversion function template type");
538
539     // Compute the type of the function that we would expect the conversion
540     // function to have, if it were to match the name given.
541     // FIXME: Calling convention!
542     QualType ExpectedType
543       = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
544                                             0, 0, ConvProto->isVariadic(),
545                                             ConvProto->getTypeQuals(),
546                                             false, false, 0, 0,
547                                             ConvProto->getNoReturnAttr(),
548                                             CC_Default);
549  
550     // Perform template argument deduction against the type that we would
551     // expect the function to have.
552     if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
553                                             Specialization, Info)
554           == Sema::TDK_Success) {
555       R.addDecl(Specialization);
556       Found = true;
557     }
558   }
559
560   return Found;
561 }
562
563 // Performs C++ unqualified lookup into the given file context.
564 static bool
565 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, 
566                    DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
567
568   assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
569
570   // Perform direct name lookup into the LookupCtx.
571   bool Found = LookupDirect(S, R, NS);
572
573   // Perform direct name lookup into the namespaces nominated by the
574   // using directives whose common ancestor is this namespace.
575   UnqualUsingDirectiveSet::const_iterator UI, UEnd;
576   llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
577
578   for (; UI != UEnd; ++UI)
579     if (LookupDirect(S, R, UI->getNominatedNamespace()))
580       Found = true;
581
582   R.resolveKind();
583
584   return Found;
585 }
586
587 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
588   if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
589     return Ctx->isFileContext();
590   return false;
591 }
592
593 // Find the next outer declaration context corresponding to this scope.
594 static DeclContext *findOuterContext(Scope *S) {
595   for (S = S->getParent(); S; S = S->getParent())
596     if (S->getEntity())
597       return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
598   
599   return 0;
600 }
601
602 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
603   assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
604
605   DeclarationName Name = R.getLookupName();
606
607   Scope *Initial = S;
608   IdentifierResolver::iterator
609     I = IdResolver.begin(Name),
610     IEnd = IdResolver.end();
611
612   // First we lookup local scope.
613   // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
614   // ...During unqualified name lookup (3.4.1), the names appear as if
615   // they were declared in the nearest enclosing namespace which contains
616   // both the using-directive and the nominated namespace.
617   // [Note: in this context, "contains" means "contains directly or
618   // indirectly".
619   //
620   // For example:
621   // namespace A { int i; }
622   // void foo() {
623   //   int i;
624   //   {
625   //     using namespace A;
626   //     ++i; // finds local 'i', A::i appears at global scope
627   //   }
628   // }
629   //
630   for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
631     // Check whether the IdResolver has anything in this scope.
632     bool Found = false;
633     for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
634       if (R.isAcceptableDecl(*I)) {
635         Found = true;
636         R.addDecl(*I);
637       }
638     }
639     if (Found) {
640       R.resolveKind();
641       return true;
642     }
643
644     if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
645       DeclContext *OuterCtx = findOuterContext(S);
646       for (; Ctx && Ctx->getPrimaryContext() != OuterCtx; 
647            Ctx = Ctx->getLookupParent()) {
648         // We do not directly look into transparent contexts, since
649         // those entities will be found in the nearest enclosing
650         // non-transparent context.
651         if (Ctx->isTransparentContext())
652           continue;
653
654         // We do not look directly into function or method contexts,
655         // since all of the local variables and parameters of the
656         // function/method are present within the Scope.
657         if (Ctx->isFunctionOrMethod()) {
658           // If we have an Objective-C instance method, look for ivars
659           // in the corresponding interface.
660           if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
661             if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
662               if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
663                 ObjCInterfaceDecl *ClassDeclared;
664                 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
665                                                  Name.getAsIdentifierInfo(), 
666                                                              ClassDeclared)) {
667                   if (R.isAcceptableDecl(Ivar)) {
668                     R.addDecl(Ivar);
669                     R.resolveKind();
670                     return true;
671                   }
672                 }
673               }
674           }
675
676           continue;
677         }
678
679         // Perform qualified name lookup into this context.
680         // FIXME: In some cases, we know that every name that could be found by
681         // this qualified name lookup will also be on the identifier chain. For
682         // example, inside a class without any base classes, we never need to
683         // perform qualified lookup because all of the members are on top of the
684         // identifier chain.
685         if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
686           return true;
687       }
688     }
689   }
690
691   // Stop if we ran out of scopes.
692   // FIXME:  This really, really shouldn't be happening.
693   if (!S) return false;
694
695   // Collect UsingDirectiveDecls in all scopes, and recursively all
696   // nominated namespaces by those using-directives.
697   //
698   // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
699   // don't build it for each lookup!
700
701   UnqualUsingDirectiveSet UDirs;
702   UDirs.visitScopeChain(Initial, S);
703   UDirs.done();
704
705   // Lookup namespace scope, and global scope.
706   // Unqualified name lookup in C++ requires looking into scopes
707   // that aren't strictly lexical, and therefore we walk through the
708   // context as well as walking through the scopes.
709
710   for (; S; S = S->getParent()) {
711     DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
712     if (Ctx && Ctx->isTransparentContext())
713       continue;
714
715     // Check whether the IdResolver has anything in this scope.
716     bool Found = false;
717     for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
718       if (R.isAcceptableDecl(*I)) {
719         // We found something.  Look for anything else in our scope
720         // with this same name and in an acceptable identifier
721         // namespace, so that we can construct an overload set if we
722         // need to.
723         Found = true;
724         R.addDecl(*I);
725       }
726     }
727
728     if (Ctx) {
729       assert(Ctx->isFileContext() &&
730              "We should have been looking only at file context here already.");
731
732       // Look into context considering using-directives.
733       if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
734         Found = true;
735     }
736
737     if (Found) {
738       R.resolveKind();
739       return true;
740     }
741
742     if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
743       return false;
744   }
745
746   return !R.empty();
747 }
748
749 /// @brief Perform unqualified name lookup starting from a given
750 /// scope.
751 ///
752 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
753 /// used to find names within the current scope. For example, 'x' in
754 /// @code
755 /// int x;
756 /// int f() {
757 ///   return x; // unqualified name look finds 'x' in the global scope
758 /// }
759 /// @endcode
760 ///
761 /// Different lookup criteria can find different names. For example, a
762 /// particular scope can have both a struct and a function of the same
763 /// name, and each can be found by certain lookup criteria. For more
764 /// information about lookup criteria, see the documentation for the
765 /// class LookupCriteria.
766 ///
767 /// @param S        The scope from which unqualified name lookup will
768 /// begin. If the lookup criteria permits, name lookup may also search
769 /// in the parent scopes.
770 ///
771 /// @param Name     The name of the entity that we are searching for.
772 ///
773 /// @param Loc      If provided, the source location where we're performing
774 /// name lookup. At present, this is only used to produce diagnostics when
775 /// C library functions (like "malloc") are implicitly declared.
776 ///
777 /// @returns The result of name lookup, which includes zero or more
778 /// declarations and possibly additional information used to diagnose
779 /// ambiguities.
780 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
781   DeclarationName Name = R.getLookupName();
782   if (!Name) return false;
783
784   LookupNameKind NameKind = R.getLookupKind();
785
786   if (!getLangOptions().CPlusPlus) {
787     // Unqualified name lookup in C/Objective-C is purely lexical, so
788     // search in the declarations attached to the name.
789
790     if (NameKind == Sema::LookupRedeclarationWithLinkage) {
791       // Find the nearest non-transparent declaration scope.
792       while (!(S->getFlags() & Scope::DeclScope) ||
793              (S->getEntity() &&
794               static_cast<DeclContext *>(S->getEntity())
795                 ->isTransparentContext()))
796         S = S->getParent();
797     }
798
799     unsigned IDNS = R.getIdentifierNamespace();
800
801     // Scan up the scope chain looking for a decl that matches this
802     // identifier that is in the appropriate namespace.  This search
803     // should not take long, as shadowing of names is uncommon, and
804     // deep shadowing is extremely uncommon.
805     bool LeftStartingScope = false;
806
807     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
808                                    IEnd = IdResolver.end();
809          I != IEnd; ++I)
810       if ((*I)->isInIdentifierNamespace(IDNS)) {
811         if (NameKind == LookupRedeclarationWithLinkage) {
812           // Determine whether this (or a previous) declaration is
813           // out-of-scope.
814           if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
815             LeftStartingScope = true;
816
817           // If we found something outside of our starting scope that
818           // does not have linkage, skip it.
819           if (LeftStartingScope && !((*I)->hasLinkage()))
820             continue;
821         }
822
823         R.addDecl(*I);
824
825         if ((*I)->getAttr<OverloadableAttr>()) {
826           // If this declaration has the "overloadable" attribute, we
827           // might have a set of overloaded functions.
828
829           // Figure out what scope the identifier is in.
830           while (!(S->getFlags() & Scope::DeclScope) ||
831                  !S->isDeclScope(DeclPtrTy::make(*I)))
832             S = S->getParent();
833
834           // Find the last declaration in this scope (with the same
835           // name, naturally).
836           IdentifierResolver::iterator LastI = I;
837           for (++LastI; LastI != IEnd; ++LastI) {
838             if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
839               break;
840             R.addDecl(*LastI);
841           }
842         }
843
844         R.resolveKind();
845
846         return true;
847       }
848   } else {
849     // Perform C++ unqualified name lookup.
850     if (CppLookupName(R, S))
851       return true;
852   }
853
854   // If we didn't find a use of this identifier, and if the identifier
855   // corresponds to a compiler builtin, create the decl object for the builtin
856   // now, injecting it into translation unit scope, and return it.
857   if (AllowBuiltinCreation)
858     return LookupBuiltin(*this, R);
859
860   return false;
861 }
862
863 /// @brief Perform qualified name lookup in the namespaces nominated by
864 /// using directives by the given context.
865 ///
866 /// C++98 [namespace.qual]p2:
867 ///   Given X::m (where X is a user-declared namespace), or given ::m
868 ///   (where X is the global namespace), let S be the set of all
869 ///   declarations of m in X and in the transitive closure of all
870 ///   namespaces nominated by using-directives in X and its used
871 ///   namespaces, except that using-directives are ignored in any
872 ///   namespace, including X, directly containing one or more
873 ///   declarations of m. No namespace is searched more than once in
874 ///   the lookup of a name. If S is the empty set, the program is
875 ///   ill-formed. Otherwise, if S has exactly one member, or if the
876 ///   context of the reference is a using-declaration
877 ///   (namespace.udecl), S is the required set of declarations of
878 ///   m. Otherwise if the use of m is not one that allows a unique
879 ///   declaration to be chosen from S, the program is ill-formed.
880 /// C++98 [namespace.qual]p5:
881 ///   During the lookup of a qualified namespace member name, if the
882 ///   lookup finds more than one declaration of the member, and if one
883 ///   declaration introduces a class name or enumeration name and the
884 ///   other declarations either introduce the same object, the same
885 ///   enumerator or a set of functions, the non-type name hides the
886 ///   class or enumeration name if and only if the declarations are
887 ///   from the same namespace; otherwise (the declarations are from
888 ///   different namespaces), the program is ill-formed.
889 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
890                                                  DeclContext *StartDC) {
891   assert(StartDC->isFileContext() && "start context is not a file context");
892
893   DeclContext::udir_iterator I = StartDC->using_directives_begin();
894   DeclContext::udir_iterator E = StartDC->using_directives_end();
895
896   if (I == E) return false;
897
898   // We have at least added all these contexts to the queue.
899   llvm::DenseSet<DeclContext*> Visited;
900   Visited.insert(StartDC);
901
902   // We have not yet looked into these namespaces, much less added
903   // their "using-children" to the queue.
904   llvm::SmallVector<NamespaceDecl*, 8> Queue;
905
906   // We have already looked into the initial namespace; seed the queue
907   // with its using-children.
908   for (; I != E; ++I) {
909     NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
910     if (Visited.insert(ND).second)
911       Queue.push_back(ND);
912   }
913
914   // The easiest way to implement the restriction in [namespace.qual]p5
915   // is to check whether any of the individual results found a tag
916   // and, if so, to declare an ambiguity if the final result is not
917   // a tag.
918   bool FoundTag = false;
919   bool FoundNonTag = false;
920
921   LookupResult LocalR(LookupResult::Temporary, R);
922
923   bool Found = false;
924   while (!Queue.empty()) {
925     NamespaceDecl *ND = Queue.back();
926     Queue.pop_back();
927
928     // We go through some convolutions here to avoid copying results
929     // between LookupResults.
930     bool UseLocal = !R.empty();
931     LookupResult &DirectR = UseLocal ? LocalR : R;
932     bool FoundDirect = LookupDirect(S, DirectR, ND);
933
934     if (FoundDirect) {
935       // First do any local hiding.
936       DirectR.resolveKind();
937
938       // If the local result is a tag, remember that.
939       if (DirectR.isSingleTagDecl())
940         FoundTag = true;
941       else
942         FoundNonTag = true;
943
944       // Append the local results to the total results if necessary.
945       if (UseLocal) {
946         R.addAllDecls(LocalR);
947         LocalR.clear();
948       }
949     }
950
951     // If we find names in this namespace, ignore its using directives.
952     if (FoundDirect) {
953       Found = true;
954       continue;
955     }
956
957     for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
958       NamespaceDecl *Nom = (*I)->getNominatedNamespace();
959       if (Visited.insert(Nom).second)
960         Queue.push_back(Nom);
961     }
962   }
963
964   if (Found) {
965     if (FoundTag && FoundNonTag)
966       R.setAmbiguousQualifiedTagHiding();
967     else
968       R.resolveKind();
969   }
970
971   return Found;
972 }
973
974 /// \brief Perform qualified name lookup into a given context.
975 ///
976 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
977 /// names when the context of those names is explicit specified, e.g.,
978 /// "std::vector" or "x->member", or as part of unqualified name lookup.
979 ///
980 /// Different lookup criteria can find different names. For example, a
981 /// particular scope can have both a struct and a function of the same
982 /// name, and each can be found by certain lookup criteria. For more
983 /// information about lookup criteria, see the documentation for the
984 /// class LookupCriteria.
985 ///
986 /// \param R captures both the lookup criteria and any lookup results found.
987 ///
988 /// \param LookupCtx The context in which qualified name lookup will
989 /// search. If the lookup criteria permits, name lookup may also search
990 /// in the parent contexts or (for C++ classes) base classes.
991 ///
992 /// \param InUnqualifiedLookup true if this is qualified name lookup that 
993 /// occurs as part of unqualified name lookup.
994 ///
995 /// \returns true if lookup succeeded, false if it failed.
996 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
997                                bool InUnqualifiedLookup) {
998   assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
999
1000   if (!R.getLookupName())
1001     return false;
1002
1003   // Make sure that the declaration context is complete.
1004   assert((!isa<TagDecl>(LookupCtx) ||
1005           LookupCtx->isDependentContext() ||
1006           cast<TagDecl>(LookupCtx)->isDefinition() ||
1007           Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1008             ->isBeingDefined()) &&
1009          "Declaration context must already be complete!");
1010
1011   // Perform qualified name lookup into the LookupCtx.
1012   if (LookupDirect(*this, R, LookupCtx)) {
1013     R.resolveKind();
1014     if (isa<CXXRecordDecl>(LookupCtx))
1015       R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1016     return true;
1017   }
1018
1019   // Don't descend into implied contexts for redeclarations.
1020   // C++98 [namespace.qual]p6:
1021   //   In a declaration for a namespace member in which the
1022   //   declarator-id is a qualified-id, given that the qualified-id
1023   //   for the namespace member has the form
1024   //     nested-name-specifier unqualified-id
1025   //   the unqualified-id shall name a member of the namespace
1026   //   designated by the nested-name-specifier.
1027   // See also [class.mfct]p5 and [class.static.data]p2.
1028   if (R.isForRedeclaration())
1029     return false;
1030
1031   // If this is a namespace, look it up in the implied namespaces.
1032   if (LookupCtx->isFileContext())
1033     return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1034
1035   // If this isn't a C++ class, we aren't allowed to look into base
1036   // classes, we're done.
1037   CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1038   if (!LookupRec)
1039     return false;
1040
1041   // If we're performing qualified name lookup into a dependent class,
1042   // then we are actually looking into a current instantiation. If we have any
1043   // dependent base classes, then we either have to delay lookup until 
1044   // template instantiation time (at which point all bases will be available)
1045   // or we have to fail.
1046   if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1047       LookupRec->hasAnyDependentBases()) {
1048     R.setNotFoundInCurrentInstantiation();
1049     return false;
1050   }
1051     
1052   // Perform lookup into our base classes.
1053   CXXBasePaths Paths;
1054   Paths.setOrigin(LookupRec);
1055
1056   // Look for this member in our base classes
1057   CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1058   switch (R.getLookupKind()) {
1059     case LookupOrdinaryName:
1060     case LookupMemberName:
1061     case LookupRedeclarationWithLinkage:
1062       BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1063       break;
1064       
1065     case LookupTagName:
1066       BaseCallback = &CXXRecordDecl::FindTagMember;
1067       break;
1068
1069     case LookupUsingDeclName:
1070       // This lookup is for redeclarations only.
1071       
1072     case LookupOperatorName:
1073     case LookupNamespaceName:
1074     case LookupObjCProtocolName:
1075     case LookupObjCImplementationName:
1076       // These lookups will never find a member in a C++ class (or base class).
1077       return false;
1078       
1079     case LookupNestedNameSpecifierName:
1080       BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1081       break;
1082   }
1083   
1084   if (!LookupRec->lookupInBases(BaseCallback,
1085                                 R.getLookupName().getAsOpaquePtr(), Paths))
1086     return false;
1087
1088   R.setNamingClass(LookupRec);
1089
1090   // C++ [class.member.lookup]p2:
1091   //   [...] If the resulting set of declarations are not all from
1092   //   sub-objects of the same type, or the set has a nonstatic member
1093   //   and includes members from distinct sub-objects, there is an
1094   //   ambiguity and the program is ill-formed. Otherwise that set is
1095   //   the result of the lookup.
1096   // FIXME: support using declarations!
1097   QualType SubobjectType;
1098   int SubobjectNumber = 0;
1099   AccessSpecifier SubobjectAccess = AS_private;
1100   for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1101        Path != PathEnd; ++Path) {
1102     const CXXBasePathElement &PathElement = Path->back();
1103
1104     // Pick the best (i.e. most permissive i.e. numerically lowest) access
1105     // across all paths.
1106     SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1107     
1108     // Determine whether we're looking at a distinct sub-object or not.
1109     if (SubobjectType.isNull()) {
1110       // This is the first subobject we've looked at. Record its type.
1111       SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1112       SubobjectNumber = PathElement.SubobjectNumber;
1113     } else if (SubobjectType
1114                  != Context.getCanonicalType(PathElement.Base->getType())) {
1115       // We found members of the given name in two subobjects of
1116       // different types. This lookup is ambiguous.
1117       R.setAmbiguousBaseSubobjectTypes(Paths);
1118       return true;
1119     } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1120       // We have a different subobject of the same type.
1121
1122       // C++ [class.member.lookup]p5:
1123       //   A static member, a nested type or an enumerator defined in
1124       //   a base class T can unambiguously be found even if an object
1125       //   has more than one base class subobject of type T.
1126       Decl *FirstDecl = *Path->Decls.first;
1127       if (isa<VarDecl>(FirstDecl) ||
1128           isa<TypeDecl>(FirstDecl) ||
1129           isa<EnumConstantDecl>(FirstDecl))
1130         continue;
1131
1132       if (isa<CXXMethodDecl>(FirstDecl)) {
1133         // Determine whether all of the methods are static.
1134         bool AllMethodsAreStatic = true;
1135         for (DeclContext::lookup_iterator Func = Path->Decls.first;
1136              Func != Path->Decls.second; ++Func) {
1137           if (!isa<CXXMethodDecl>(*Func)) {
1138             assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1139             break;
1140           }
1141
1142           if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1143             AllMethodsAreStatic = false;
1144             break;
1145           }
1146         }
1147
1148         if (AllMethodsAreStatic)
1149           continue;
1150       }
1151
1152       // We have found a nonstatic member name in multiple, distinct
1153       // subobjects. Name lookup is ambiguous.
1154       R.setAmbiguousBaseSubobjects(Paths);
1155       return true;
1156     }
1157   }
1158
1159   // Lookup in a base class succeeded; return these results.
1160
1161   DeclContext::lookup_iterator I, E;
1162   for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1163     NamedDecl *D = *I;
1164     AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1165                                                     D->getAccess());
1166     R.addDecl(D, AS);
1167   }
1168   R.resolveKind();
1169   return true;
1170 }
1171
1172 /// @brief Performs name lookup for a name that was parsed in the
1173 /// source code, and may contain a C++ scope specifier.
1174 ///
1175 /// This routine is a convenience routine meant to be called from
1176 /// contexts that receive a name and an optional C++ scope specifier
1177 /// (e.g., "N::M::x"). It will then perform either qualified or
1178 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1179 /// respectively) on the given name and return those results.
1180 ///
1181 /// @param S        The scope from which unqualified name lookup will
1182 /// begin.
1183 ///
1184 /// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
1185 ///
1186 /// @param Name     The name of the entity that name lookup will
1187 /// search for.
1188 ///
1189 /// @param Loc      If provided, the source location where we're performing
1190 /// name lookup. At present, this is only used to produce diagnostics when
1191 /// C library functions (like "malloc") are implicitly declared.
1192 ///
1193 /// @param EnteringContext Indicates whether we are going to enter the
1194 /// context of the scope-specifier SS (if present).
1195 ///
1196 /// @returns True if any decls were found (but possibly ambiguous)
1197 bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
1198                             bool AllowBuiltinCreation, bool EnteringContext) {
1199   if (SS && SS->isInvalid()) {
1200     // When the scope specifier is invalid, don't even look for
1201     // anything.
1202     return false;
1203   }
1204
1205   if (SS && SS->isSet()) {
1206     if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1207       // We have resolved the scope specifier to a particular declaration
1208       // contex, and will perform name lookup in that context.
1209       if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
1210         return false;
1211
1212       R.setContextRange(SS->getRange());
1213
1214       return LookupQualifiedName(R, DC);
1215     }
1216
1217     // We could not resolve the scope specified to a specific declaration
1218     // context, which means that SS refers to an unknown specialization.
1219     // Name lookup can't find anything in this case.
1220     return false;
1221   }
1222
1223   // Perform unqualified name lookup starting in the given scope.
1224   return LookupName(R, S, AllowBuiltinCreation);
1225 }
1226
1227
1228 /// @brief Produce a diagnostic describing the ambiguity that resulted
1229 /// from name lookup.
1230 ///
1231 /// @param Result       The ambiguous name lookup result.
1232 ///
1233 /// @param Name         The name of the entity that name lookup was
1234 /// searching for.
1235 ///
1236 /// @param NameLoc      The location of the name within the source code.
1237 ///
1238 /// @param LookupRange  A source range that provides more
1239 /// source-location information concerning the lookup itself. For
1240 /// example, this range might highlight a nested-name-specifier that
1241 /// precedes the name.
1242 ///
1243 /// @returns true
1244 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1245   assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1246
1247   DeclarationName Name = Result.getLookupName();
1248   SourceLocation NameLoc = Result.getNameLoc();
1249   SourceRange LookupRange = Result.getContextRange();
1250
1251   switch (Result.getAmbiguityKind()) {
1252   case LookupResult::AmbiguousBaseSubobjects: {
1253     CXXBasePaths *Paths = Result.getBasePaths();
1254     QualType SubobjectType = Paths->front().back().Base->getType();
1255     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1256       << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1257       << LookupRange;
1258     
1259     DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1260     while (isa<CXXMethodDecl>(*Found) &&
1261            cast<CXXMethodDecl>(*Found)->isStatic())
1262       ++Found;
1263     
1264     Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1265     
1266     return true;
1267   }
1268
1269   case LookupResult::AmbiguousBaseSubobjectTypes: {
1270     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1271       << Name << LookupRange;
1272     
1273     CXXBasePaths *Paths = Result.getBasePaths();
1274     std::set<Decl *> DeclsPrinted;
1275     for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1276                                       PathEnd = Paths->end();
1277          Path != PathEnd; ++Path) {
1278       Decl *D = *Path->Decls.first;
1279       if (DeclsPrinted.insert(D).second)
1280         Diag(D->getLocation(), diag::note_ambiguous_member_found);
1281     }
1282
1283     return true;
1284   }
1285
1286   case LookupResult::AmbiguousTagHiding: {
1287     Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1288
1289     llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1290
1291     LookupResult::iterator DI, DE = Result.end();
1292     for (DI = Result.begin(); DI != DE; ++DI)
1293       if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1294         TagDecls.insert(TD);
1295         Diag(TD->getLocation(), diag::note_hidden_tag);
1296       }
1297
1298     for (DI = Result.begin(); DI != DE; ++DI)
1299       if (!isa<TagDecl>(*DI))
1300         Diag((*DI)->getLocation(), diag::note_hiding_object);
1301
1302     // For recovery purposes, go ahead and implement the hiding.
1303     LookupResult::Filter F = Result.makeFilter();
1304     while (F.hasNext()) {
1305       if (TagDecls.count(F.next()))
1306         F.erase();
1307     }
1308     F.done();
1309
1310     return true;
1311   }
1312
1313   case LookupResult::AmbiguousReference: {
1314     Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1315   
1316     LookupResult::iterator DI = Result.begin(), DE = Result.end();
1317     for (; DI != DE; ++DI)
1318       Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1319
1320     return true;
1321   }
1322   }
1323
1324   llvm_unreachable("unknown ambiguity kind");
1325   return true;
1326 }
1327
1328 static void
1329 addAssociatedClassesAndNamespaces(QualType T,
1330                                   ASTContext &Context,
1331                           Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1332                                   Sema::AssociatedClassSet &AssociatedClasses);
1333
1334 static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1335                              DeclContext *Ctx) {
1336   if (Ctx->isFileContext())
1337     Namespaces.insert(Ctx);
1338 }
1339
1340 // \brief Add the associated classes and namespaces for argument-dependent
1341 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1342 static void
1343 addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
1344                                   ASTContext &Context,
1345                            Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1346                                   Sema::AssociatedClassSet &AssociatedClasses) {
1347   // C++ [basic.lookup.koenig]p2, last bullet:
1348   //   -- [...] ;
1349   switch (Arg.getKind()) {
1350     case TemplateArgument::Null:
1351       break;
1352
1353     case TemplateArgument::Type:
1354       // [...] the namespaces and classes associated with the types of the
1355       // template arguments provided for template type parameters (excluding
1356       // template template parameters)
1357       addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1358                                         AssociatedNamespaces,
1359                                         AssociatedClasses);
1360       break;
1361
1362     case TemplateArgument::Template: {
1363       // [...] the namespaces in which any template template arguments are
1364       // defined; and the classes in which any member templates used as
1365       // template template arguments are defined.
1366       TemplateName Template = Arg.getAsTemplate();
1367       if (ClassTemplateDecl *ClassTemplate
1368                  = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1369         DeclContext *Ctx = ClassTemplate->getDeclContext();
1370         if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1371           AssociatedClasses.insert(EnclosingClass);
1372         // Add the associated namespace for this class.
1373         while (Ctx->isRecord())
1374           Ctx = Ctx->getParent();
1375         CollectNamespace(AssociatedNamespaces, Ctx);
1376       }
1377       break;
1378     }
1379       
1380     case TemplateArgument::Declaration:
1381     case TemplateArgument::Integral:
1382     case TemplateArgument::Expression:
1383       // [Note: non-type template arguments do not contribute to the set of
1384       //  associated namespaces. ]
1385       break;
1386
1387     case TemplateArgument::Pack:
1388       for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1389                                         PEnd = Arg.pack_end();
1390            P != PEnd; ++P)
1391         addAssociatedClassesAndNamespaces(*P, Context,
1392                                           AssociatedNamespaces,
1393                                           AssociatedClasses);
1394       break;
1395   }
1396 }
1397
1398 // \brief Add the associated classes and namespaces for
1399 // argument-dependent lookup with an argument of class type
1400 // (C++ [basic.lookup.koenig]p2).
1401 static void
1402 addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1403                                   ASTContext &Context,
1404                             Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1405                             Sema::AssociatedClassSet &AssociatedClasses) {
1406   // C++ [basic.lookup.koenig]p2:
1407   //   [...]
1408   //     -- If T is a class type (including unions), its associated
1409   //        classes are: the class itself; the class of which it is a
1410   //        member, if any; and its direct and indirect base
1411   //        classes. Its associated namespaces are the namespaces in
1412   //        which its associated classes are defined.
1413
1414   // Add the class of which it is a member, if any.
1415   DeclContext *Ctx = Class->getDeclContext();
1416   if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1417     AssociatedClasses.insert(EnclosingClass);
1418   // Add the associated namespace for this class.
1419   while (Ctx->isRecord())
1420     Ctx = Ctx->getParent();
1421   CollectNamespace(AssociatedNamespaces, Ctx);
1422
1423   // Add the class itself. If we've already seen this class, we don't
1424   // need to visit base classes.
1425   if (!AssociatedClasses.insert(Class))
1426     return;
1427
1428   // -- If T is a template-id, its associated namespaces and classes are
1429   //    the namespace in which the template is defined; for member
1430   //    templates, the member template’s class; the namespaces and classes
1431   //    associated with the types of the template arguments provided for
1432   //    template type parameters (excluding template template parameters); the
1433   //    namespaces in which any template template arguments are defined; and
1434   //    the classes in which any member templates used as template template
1435   //    arguments are defined. [Note: non-type template arguments do not
1436   //    contribute to the set of associated namespaces. ]
1437   if (ClassTemplateSpecializationDecl *Spec
1438         = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1439     DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1440     if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1441       AssociatedClasses.insert(EnclosingClass);
1442     // Add the associated namespace for this class.
1443     while (Ctx->isRecord())
1444       Ctx = Ctx->getParent();
1445     CollectNamespace(AssociatedNamespaces, Ctx);
1446
1447     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1448     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1449       addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1450                                         AssociatedNamespaces,
1451                                         AssociatedClasses);
1452   }
1453
1454   // Only recurse into base classes for complete types.
1455   if (!Class->hasDefinition()) {
1456     // FIXME: we might need to instantiate templates here
1457     return;
1458   }
1459
1460   // Add direct and indirect base classes along with their associated
1461   // namespaces.
1462   llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1463   Bases.push_back(Class);
1464   while (!Bases.empty()) {
1465     // Pop this class off the stack.
1466     Class = Bases.back();
1467     Bases.pop_back();
1468
1469     // Visit the base classes.
1470     for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1471                                          BaseEnd = Class->bases_end();
1472          Base != BaseEnd; ++Base) {
1473       const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1474       // In dependent contexts, we do ADL twice, and the first time around,
1475       // the base type might be a dependent TemplateSpecializationType, or a
1476       // TemplateTypeParmType. If that happens, simply ignore it.
1477       // FIXME: If we want to support export, we probably need to add the
1478       // namespace of the template in a TemplateSpecializationType, or even
1479       // the classes and namespaces of known non-dependent arguments.
1480       if (!BaseType)
1481         continue;
1482       CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1483       if (AssociatedClasses.insert(BaseDecl)) {
1484         // Find the associated namespace for this base class.
1485         DeclContext *BaseCtx = BaseDecl->getDeclContext();
1486         while (BaseCtx->isRecord())
1487           BaseCtx = BaseCtx->getParent();
1488         CollectNamespace(AssociatedNamespaces, BaseCtx);
1489
1490         // Make sure we visit the bases of this base class.
1491         if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1492           Bases.push_back(BaseDecl);
1493       }
1494     }
1495   }
1496 }
1497
1498 // \brief Add the associated classes and namespaces for
1499 // argument-dependent lookup with an argument of type T
1500 // (C++ [basic.lookup.koenig]p2).
1501 static void
1502 addAssociatedClassesAndNamespaces(QualType T,
1503                                   ASTContext &Context,
1504                             Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1505                                   Sema::AssociatedClassSet &AssociatedClasses) {
1506   // C++ [basic.lookup.koenig]p2:
1507   //
1508   //   For each argument type T in the function call, there is a set
1509   //   of zero or more associated namespaces and a set of zero or more
1510   //   associated classes to be considered. The sets of namespaces and
1511   //   classes is determined entirely by the types of the function
1512   //   arguments (and the namespace of any template template
1513   //   argument). Typedef names and using-declarations used to specify
1514   //   the types do not contribute to this set. The sets of namespaces
1515   //   and classes are determined in the following way:
1516   T = Context.getCanonicalType(T).getUnqualifiedType();
1517
1518   //    -- If T is a pointer to U or an array of U, its associated
1519   //       namespaces and classes are those associated with U.
1520   //
1521   // We handle this by unwrapping pointer and array types immediately,
1522   // to avoid unnecessary recursion.
1523   while (true) {
1524     if (const PointerType *Ptr = T->getAs<PointerType>())
1525       T = Ptr->getPointeeType();
1526     else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1527       T = Ptr->getElementType();
1528     else
1529       break;
1530   }
1531
1532   //     -- If T is a fundamental type, its associated sets of
1533   //        namespaces and classes are both empty.
1534   if (T->getAs<BuiltinType>())
1535     return;
1536
1537   //     -- If T is a class type (including unions), its associated
1538   //        classes are: the class itself; the class of which it is a
1539   //        member, if any; and its direct and indirect base
1540   //        classes. Its associated namespaces are the namespaces in
1541   //        which its associated classes are defined.
1542   if (const RecordType *ClassType = T->getAs<RecordType>())
1543     if (CXXRecordDecl *ClassDecl
1544         = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1545       addAssociatedClassesAndNamespaces(ClassDecl, Context,
1546                                         AssociatedNamespaces,
1547                                         AssociatedClasses);
1548       return;
1549     }
1550
1551   //     -- If T is an enumeration type, its associated namespace is
1552   //        the namespace in which it is defined. If it is class
1553   //        member, its associated class is the member’s class; else
1554   //        it has no associated class.
1555   if (const EnumType *EnumT = T->getAs<EnumType>()) {
1556     EnumDecl *Enum = EnumT->getDecl();
1557
1558     DeclContext *Ctx = Enum->getDeclContext();
1559     if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1560       AssociatedClasses.insert(EnclosingClass);
1561
1562     // Add the associated namespace for this class.
1563     while (Ctx->isRecord())
1564       Ctx = Ctx->getParent();
1565     CollectNamespace(AssociatedNamespaces, Ctx);
1566
1567     return;
1568   }
1569
1570   //     -- If T is a function type, its associated namespaces and
1571   //        classes are those associated with the function parameter
1572   //        types and those associated with the return type.
1573   if (const FunctionType *FnType = T->getAs<FunctionType>()) {
1574     // Return type
1575     addAssociatedClassesAndNamespaces(FnType->getResultType(),
1576                                       Context,
1577                                       AssociatedNamespaces, AssociatedClasses);
1578
1579     const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
1580     if (!Proto)
1581       return;
1582
1583     // Argument types
1584     for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1585                                            ArgEnd = Proto->arg_type_end();
1586          Arg != ArgEnd; ++Arg)
1587       addAssociatedClassesAndNamespaces(*Arg, Context,
1588                                         AssociatedNamespaces, AssociatedClasses);
1589
1590     return;
1591   }
1592
1593   //     -- If T is a pointer to a member function of a class X, its
1594   //        associated namespaces and classes are those associated
1595   //        with the function parameter types and return type,
1596   //        together with those associated with X.
1597   //
1598   //     -- If T is a pointer to a data member of class X, its
1599   //        associated namespaces and classes are those associated
1600   //        with the member type together with those associated with
1601   //        X.
1602   if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
1603     // Handle the type that the pointer to member points to.
1604     addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1605                                       Context,
1606                                       AssociatedNamespaces,
1607                                       AssociatedClasses);
1608
1609     // Handle the class type into which this points.
1610     if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
1611       addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1612                                         Context,
1613                                         AssociatedNamespaces,
1614                                         AssociatedClasses);
1615
1616     return;
1617   }
1618
1619   // FIXME: What about block pointers?
1620   // FIXME: What about Objective-C message sends?
1621 }
1622
1623 /// \brief Find the associated classes and namespaces for
1624 /// argument-dependent lookup for a call with the given set of
1625 /// arguments.
1626 ///
1627 /// This routine computes the sets of associated classes and associated
1628 /// namespaces searched by argument-dependent lookup
1629 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1630 void
1631 Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1632                                  AssociatedNamespaceSet &AssociatedNamespaces,
1633                                  AssociatedClassSet &AssociatedClasses) {
1634   AssociatedNamespaces.clear();
1635   AssociatedClasses.clear();
1636
1637   // C++ [basic.lookup.koenig]p2:
1638   //   For each argument type T in the function call, there is a set
1639   //   of zero or more associated namespaces and a set of zero or more
1640   //   associated classes to be considered. The sets of namespaces and
1641   //   classes is determined entirely by the types of the function
1642   //   arguments (and the namespace of any template template
1643   //   argument).
1644   for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1645     Expr *Arg = Args[ArgIdx];
1646
1647     if (Arg->getType() != Context.OverloadTy) {
1648       addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1649                                         AssociatedNamespaces,
1650                                         AssociatedClasses);
1651       continue;
1652     }
1653
1654     // [...] In addition, if the argument is the name or address of a
1655     // set of overloaded functions and/or function templates, its
1656     // associated classes and namespaces are the union of those
1657     // associated with each of the members of the set: the namespace
1658     // in which the function or function template is defined and the
1659     // classes and namespaces associated with its (non-dependent)
1660     // parameter types and return type.
1661     Arg = Arg->IgnoreParens();
1662     if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1663       if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1664         Arg = unaryOp->getSubExpr();
1665
1666     // TODO: avoid the copies.  This should be easy when the cases
1667     // share a storage implementation.
1668     llvm::SmallVector<NamedDecl*, 8> Functions;
1669
1670     if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1671       Functions.append(ULE->decls_begin(), ULE->decls_end());
1672     else
1673       continue;
1674
1675     for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1676            E = Functions.end(); I != E; ++I) {
1677       // Look through any using declarations to find the underlying function.
1678       NamedDecl *Fn = (*I)->getUnderlyingDecl();
1679
1680       FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1681       if (!FDecl)
1682         FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
1683
1684       // Add the classes and namespaces associated with the parameter
1685       // types and return type of this function.
1686       addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1687                                         AssociatedNamespaces,
1688                                         AssociatedClasses);
1689     }
1690   }
1691 }
1692
1693 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1694 /// an acceptable non-member overloaded operator for a call whose
1695 /// arguments have types T1 (and, if non-empty, T2). This routine
1696 /// implements the check in C++ [over.match.oper]p3b2 concerning
1697 /// enumeration types.
1698 static bool
1699 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1700                                        QualType T1, QualType T2,
1701                                        ASTContext &Context) {
1702   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1703     return true;
1704
1705   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1706     return true;
1707
1708   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
1709   if (Proto->getNumArgs() < 1)
1710     return false;
1711
1712   if (T1->isEnumeralType()) {
1713     QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1714     if (Context.hasSameUnqualifiedType(T1, ArgType))
1715       return true;
1716   }
1717
1718   if (Proto->getNumArgs() < 2)
1719     return false;
1720
1721   if (!T2.isNull() && T2->isEnumeralType()) {
1722     QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1723     if (Context.hasSameUnqualifiedType(T2, ArgType))
1724       return true;
1725   }
1726
1727   return false;
1728 }
1729
1730 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1731                                   LookupNameKind NameKind,
1732                                   RedeclarationKind Redecl) {
1733   LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1734   LookupName(R, S);
1735   return R.getAsSingle<NamedDecl>();
1736 }
1737
1738 /// \brief Find the protocol with the given name, if any.
1739 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
1740   Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
1741   return cast_or_null<ObjCProtocolDecl>(D);
1742 }
1743
1744 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1745                                         QualType T1, QualType T2,
1746                                         UnresolvedSetImpl &Functions) {
1747   // C++ [over.match.oper]p3:
1748   //     -- The set of non-member candidates is the result of the
1749   //        unqualified lookup of operator@ in the context of the
1750   //        expression according to the usual rules for name lookup in
1751   //        unqualified function calls (3.4.2) except that all member
1752   //        functions are ignored. However, if no operand has a class
1753   //        type, only those non-member functions in the lookup set
1754   //        that have a first parameter of type T1 or "reference to
1755   //        (possibly cv-qualified) T1", when T1 is an enumeration
1756   //        type, or (if there is a right operand) a second parameter
1757   //        of type T2 or "reference to (possibly cv-qualified) T2",
1758   //        when T2 is an enumeration type, are candidate functions.
1759   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1760   LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1761   LookupName(Operators, S);
1762
1763   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1764
1765   if (Operators.empty())
1766     return;
1767
1768   for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1769        Op != OpEnd; ++Op) {
1770     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
1771       if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1772         Functions.addDecl(FD, Op.getAccess()); // FIXME: canonical FD
1773     } else if (FunctionTemplateDecl *FunTmpl
1774                  = dyn_cast<FunctionTemplateDecl>(*Op)) {
1775       // FIXME: friend operators?
1776       // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
1777       // later?
1778       if (!FunTmpl->getDeclContext()->isRecord())
1779         Functions.addDecl(FunTmpl, Op.getAccess());
1780     }
1781   }
1782 }
1783
1784 void ADLResult::insert(NamedDecl *New) {
1785   NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1786
1787   // If we haven't yet seen a decl for this key, or the last decl
1788   // was exactly this one, we're done.
1789   if (Old == 0 || Old == New) {
1790     Old = New;
1791     return;
1792   }
1793
1794   // Otherwise, decide which is a more recent redeclaration.
1795   FunctionDecl *OldFD, *NewFD;
1796   if (isa<FunctionTemplateDecl>(New)) {
1797     OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1798     NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1799   } else {
1800     OldFD = cast<FunctionDecl>(Old);
1801     NewFD = cast<FunctionDecl>(New);
1802   }
1803
1804   FunctionDecl *Cursor = NewFD;
1805   while (true) {
1806     Cursor = Cursor->getPreviousDeclaration();
1807
1808     // If we got to the end without finding OldFD, OldFD is the newer
1809     // declaration;  leave things as they are.
1810     if (!Cursor) return;
1811
1812     // If we do find OldFD, then NewFD is newer.
1813     if (Cursor == OldFD) break;
1814
1815     // Otherwise, keep looking.
1816   }
1817
1818   Old = New;
1819 }
1820
1821 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
1822                                    Expr **Args, unsigned NumArgs,
1823                                    ADLResult &Result) {
1824   // Find all of the associated namespaces and classes based on the
1825   // arguments we have.
1826   AssociatedNamespaceSet AssociatedNamespaces;
1827   AssociatedClassSet AssociatedClasses;
1828   FindAssociatedClassesAndNamespaces(Args, NumArgs,
1829                                      AssociatedNamespaces,
1830                                      AssociatedClasses);
1831
1832   QualType T1, T2;
1833   if (Operator) {
1834     T1 = Args[0]->getType();
1835     if (NumArgs >= 2)
1836       T2 = Args[1]->getType();
1837   }
1838
1839   // C++ [basic.lookup.argdep]p3:
1840   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
1841   //   and let Y be the lookup set produced by argument dependent
1842   //   lookup (defined as follows). If X contains [...] then Y is
1843   //   empty. Otherwise Y is the set of declarations found in the
1844   //   namespaces associated with the argument types as described
1845   //   below. The set of declarations found by the lookup of the name
1846   //   is the union of X and Y.
1847   //
1848   // Here, we compute Y and add its members to the overloaded
1849   // candidate set.
1850   for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1851                                      NSEnd = AssociatedNamespaces.end();
1852        NS != NSEnd; ++NS) {
1853     //   When considering an associated namespace, the lookup is the
1854     //   same as the lookup performed when the associated namespace is
1855     //   used as a qualifier (3.4.3.2) except that:
1856     //
1857     //     -- Any using-directives in the associated namespace are
1858     //        ignored.
1859     //
1860     //     -- Any namespace-scope friend functions declared in
1861     //        associated classes are visible within their respective
1862     //        namespaces even if they are not visible during an ordinary
1863     //        lookup (11.4).
1864     DeclContext::lookup_iterator I, E;
1865     for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
1866       NamedDecl *D = *I;
1867       // If the only declaration here is an ordinary friend, consider
1868       // it only if it was declared in an associated classes.
1869       if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
1870         DeclContext *LexDC = D->getLexicalDeclContext();
1871         if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1872           continue;
1873       }
1874
1875       if (isa<UsingShadowDecl>(D))
1876         D = cast<UsingShadowDecl>(D)->getTargetDecl();
1877
1878       if (isa<FunctionDecl>(D)) {
1879         if (Operator &&
1880             !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1881                                                     T1, T2, Context))
1882           continue;
1883       } else if (!isa<FunctionTemplateDecl>(D))
1884         continue;
1885
1886       Result.insert(D);
1887     }
1888   }
1889 }
1890
1891 //----------------------------------------------------------------------------
1892 // Search for all visible declarations.
1893 //----------------------------------------------------------------------------
1894 VisibleDeclConsumer::~VisibleDeclConsumer() { }
1895
1896 namespace {
1897
1898 class ShadowContextRAII;
1899
1900 class VisibleDeclsRecord {
1901 public:
1902   /// \brief An entry in the shadow map, which is optimized to store a
1903   /// single declaration (the common case) but can also store a list
1904   /// of declarations.
1905   class ShadowMapEntry {
1906     typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1907     
1908     /// \brief Contains either the solitary NamedDecl * or a vector
1909     /// of declarations.
1910     llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1911
1912   public:
1913     ShadowMapEntry() : DeclOrVector() { }
1914
1915     void Add(NamedDecl *ND);
1916     void Destroy();
1917
1918     // Iteration.
1919     typedef NamedDecl **iterator;
1920     iterator begin();
1921     iterator end();
1922   };
1923
1924 private:
1925   /// \brief A mapping from declaration names to the declarations that have
1926   /// this name within a particular scope.
1927   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1928
1929   /// \brief A list of shadow maps, which is used to model name hiding.
1930   std::list<ShadowMap> ShadowMaps;
1931
1932   /// \brief The declaration contexts we have already visited.
1933   llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1934
1935   friend class ShadowContextRAII;
1936
1937 public:
1938   /// \brief Determine whether we have already visited this context
1939   /// (and, if not, note that we are going to visit that context now).
1940   bool visitedContext(DeclContext *Ctx) {
1941     return !VisitedContexts.insert(Ctx);
1942   }
1943
1944   /// \brief Determine whether the given declaration is hidden in the
1945   /// current scope.
1946   ///
1947   /// \returns the declaration that hides the given declaration, or
1948   /// NULL if no such declaration exists.
1949   NamedDecl *checkHidden(NamedDecl *ND);
1950
1951   /// \brief Add a declaration to the current shadow map.
1952   void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
1953 };
1954
1955 /// \brief RAII object that records when we've entered a shadow context.
1956 class ShadowContextRAII {
1957   VisibleDeclsRecord &Visible;
1958
1959   typedef VisibleDeclsRecord::ShadowMap ShadowMap;
1960
1961 public:
1962   ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
1963     Visible.ShadowMaps.push_back(ShadowMap());
1964   }
1965
1966   ~ShadowContextRAII() {
1967     for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
1968                           EEnd = Visible.ShadowMaps.back().end();
1969          E != EEnd;
1970          ++E)
1971       E->second.Destroy();
1972
1973     Visible.ShadowMaps.pop_back();
1974   }
1975 };
1976
1977 } // end anonymous namespace
1978
1979 void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
1980   if (DeclOrVector.isNull()) {
1981     // 0 - > 1 elements: just set the single element information.
1982     DeclOrVector = ND;
1983     return;
1984   }
1985   
1986   if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
1987     // 1 -> 2 elements: create the vector of results and push in the
1988     // existing declaration.
1989     DeclVector *Vec = new DeclVector;
1990     Vec->push_back(PrevND);
1991     DeclOrVector = Vec;
1992   }
1993
1994   // Add the new element to the end of the vector.
1995   DeclOrVector.get<DeclVector*>()->push_back(ND);
1996 }
1997
1998 void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
1999   if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2000     delete Vec;
2001     DeclOrVector = ((NamedDecl *)0);
2002   }
2003 }
2004
2005 VisibleDeclsRecord::ShadowMapEntry::iterator 
2006 VisibleDeclsRecord::ShadowMapEntry::begin() {
2007   if (DeclOrVector.isNull())
2008     return 0;
2009
2010   if (DeclOrVector.dyn_cast<NamedDecl *>())
2011     return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2012
2013   return DeclOrVector.get<DeclVector *>()->begin();
2014 }
2015
2016 VisibleDeclsRecord::ShadowMapEntry::iterator 
2017 VisibleDeclsRecord::ShadowMapEntry::end() {
2018   if (DeclOrVector.isNull())
2019     return 0;
2020
2021   if (DeclOrVector.dyn_cast<NamedDecl *>())
2022     return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2023
2024   return DeclOrVector.get<DeclVector *>()->end();
2025 }
2026
2027 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2028   // Look through using declarations.
2029   ND = ND->getUnderlyingDecl();
2030   
2031   unsigned IDNS = ND->getIdentifierNamespace();
2032   std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2033   for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2034        SM != SMEnd; ++SM) {
2035     ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2036     if (Pos == SM->end())
2037       continue;
2038
2039     for (ShadowMapEntry::iterator I = Pos->second.begin(), 
2040                                IEnd = Pos->second.end();
2041          I != IEnd; ++I) {
2042       // A tag declaration does not hide a non-tag declaration.
2043       if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
2044           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 
2045                    Decl::IDNS_ObjCProtocol)))
2046         continue;
2047
2048       // Protocols are in distinct namespaces from everything else.
2049       if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2050            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2051           (*I)->getIdentifierNamespace() != IDNS)
2052         continue;
2053
2054       // Functions and function templates in the same scope overload
2055       // rather than hide.  FIXME: Look for hiding based on function
2056       // signatures!
2057       if ((*I)->isFunctionOrFunctionTemplate() &&
2058           ND->isFunctionOrFunctionTemplate() &&
2059           SM == ShadowMaps.rbegin())
2060         continue;
2061           
2062       // We've found a declaration that hides this one.
2063       return *I;
2064     }
2065   }
2066
2067   return 0;
2068 }
2069
2070 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2071                                bool QualifiedNameLookup,
2072                                bool InBaseClass,
2073                                VisibleDeclConsumer &Consumer,
2074                                VisibleDeclsRecord &Visited) {
2075   if (!Ctx)
2076     return;
2077
2078   // Make sure we don't visit the same context twice.
2079   if (Visited.visitedContext(Ctx->getPrimaryContext()))
2080     return;
2081   
2082   // Enumerate all of the results in this context.
2083   for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx; 
2084        CurCtx = CurCtx->getNextContext()) {
2085     for (DeclContext::decl_iterator D = CurCtx->decls_begin(), 
2086                                  DEnd = CurCtx->decls_end();
2087          D != DEnd; ++D) {
2088       if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2089         if (Result.isAcceptableDecl(ND)) {
2090           Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
2091           Visited.add(ND);
2092         }
2093
2094       // Visit transparent contexts inside this context.
2095       if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2096         if (InnerCtx->isTransparentContext())
2097           LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
2098                              Consumer, Visited);
2099       }
2100     }
2101   }
2102
2103   // Traverse using directives for qualified name lookup.
2104   if (QualifiedNameLookup) {
2105     ShadowContextRAII Shadow(Visited);
2106     DeclContext::udir_iterator I, E;
2107     for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2108       LookupVisibleDecls((*I)->getNominatedNamespace(), Result, 
2109                          QualifiedNameLookup, InBaseClass, Consumer, Visited);
2110     }
2111   }
2112
2113   // Traverse the contexts of inherited C++ classes.
2114   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2115     if (!Record->hasDefinition())
2116       return;
2117
2118     for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2119                                          BEnd = Record->bases_end();
2120          B != BEnd; ++B) {
2121       QualType BaseType = B->getType();
2122       
2123       // Don't look into dependent bases, because name lookup can't look
2124       // there anyway.
2125       if (BaseType->isDependentType())
2126         continue;
2127       
2128       const RecordType *Record = BaseType->getAs<RecordType>();
2129       if (!Record)
2130         continue;
2131       
2132       // FIXME: It would be nice to be able to determine whether referencing
2133       // a particular member would be ambiguous. For example, given
2134       //
2135       //   struct A { int member; };
2136       //   struct B { int member; };
2137       //   struct C : A, B { };
2138       //
2139       //   void f(C *c) { c->### }
2140       //
2141       // accessing 'member' would result in an ambiguity. However, we
2142       // could be smart enough to qualify the member with the base
2143       // class, e.g.,
2144       //
2145       //   c->B::member
2146       //
2147       // or
2148       //
2149       //   c->A::member
2150       
2151       // Find results in this base class (and its bases).
2152       ShadowContextRAII Shadow(Visited);
2153       LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2154                          true, Consumer, Visited);
2155     }
2156   }
2157   
2158   // Traverse the contexts of Objective-C classes.
2159   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2160     // Traverse categories.
2161     for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2162          Category; Category = Category->getNextClassCategory()) {
2163       ShadowContextRAII Shadow(Visited);
2164       LookupVisibleDecls(Category, Result, QualifiedNameLookup, false, 
2165                          Consumer, Visited);
2166     }
2167
2168     // Traverse protocols.
2169     for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2170          E = IFace->protocol_end(); I != E; ++I) {
2171       ShadowContextRAII Shadow(Visited);
2172       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 
2173                          Visited);
2174     }
2175
2176     // Traverse the superclass.
2177     if (IFace->getSuperClass()) {
2178       ShadowContextRAII Shadow(Visited);
2179       LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
2180                          true, Consumer, Visited);
2181     }
2182   } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2183     for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2184            E = Protocol->protocol_end(); I != E; ++I) {
2185       ShadowContextRAII Shadow(Visited);
2186       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 
2187                          Visited);
2188     }
2189   } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2190     for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2191            E = Category->protocol_end(); I != E; ++I) {
2192       ShadowContextRAII Shadow(Visited);
2193       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 
2194                          Visited);
2195     }
2196   }
2197 }
2198
2199 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2200                                UnqualUsingDirectiveSet &UDirs,
2201                                VisibleDeclConsumer &Consumer,
2202                                VisibleDeclsRecord &Visited) {
2203   if (!S)
2204     return;
2205
2206   if (!S->getEntity() || !S->getParent() ||
2207       ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2208     // Walk through the declarations in this Scope.
2209     for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2210          D != DEnd; ++D) {
2211       if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2212         if (Result.isAcceptableDecl(ND)) {
2213           Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
2214           Visited.add(ND);
2215         }
2216     }
2217   }
2218   
2219   DeclContext *Entity = 0;
2220   if (S->getEntity()) {
2221     // Look into this scope's declaration context, along with any of its
2222     // parent lookup contexts (e.g., enclosing classes), up to the point
2223     // where we hit the context stored in the next outer scope.
2224     Entity = (DeclContext *)S->getEntity();
2225     DeclContext *OuterCtx = findOuterContext(S);
2226     
2227     for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
2228          Ctx = Ctx->getLookupParent()) {
2229       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2230         if (Method->isInstanceMethod()) {
2231           // For instance methods, look for ivars in the method's interface.
2232           LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2233                                   Result.getNameLoc(), Sema::LookupMemberName);
2234           if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2235             LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false, 
2236                                /*InBaseClass=*/false, Consumer, Visited);
2237         }
2238
2239         // We've already performed all of the name lookup that we need
2240         // to for Objective-C methods; the next context will be the
2241         // outer scope.
2242         break;
2243       }
2244
2245       if (Ctx->isFunctionOrMethod())
2246         continue;
2247       
2248       LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false, 
2249                          /*InBaseClass=*/false, Consumer, Visited);
2250     }
2251   } else if (!S->getParent()) {
2252     // Look into the translation unit scope. We walk through the translation
2253     // unit's declaration context, because the Scope itself won't have all of
2254     // the declarations if we loaded a precompiled header.
2255     // FIXME: We would like the translation unit's Scope object to point to the
2256     // translation unit, so we don't need this special "if" branch. However,
2257     // doing so would force the normal C++ name-lookup code to look into the
2258     // translation unit decl when the IdentifierInfo chains would suffice. 
2259     // Once we fix that problem (which is part of a more general "don't look
2260     // in DeclContexts unless we have to" optimization), we can eliminate this.
2261     Entity = Result.getSema().Context.getTranslationUnitDecl();
2262     LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false, 
2263                        /*InBaseClass=*/false, Consumer, Visited);
2264   } 
2265   
2266   if (Entity) {
2267     // Lookup visible declarations in any namespaces found by using
2268     // directives.
2269     UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2270     llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2271     for (; UI != UEnd; ++UI)
2272       LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
2273                          Result, /*QualifiedNameLookup=*/false, 
2274                          /*InBaseClass=*/false, Consumer, Visited);
2275   }
2276
2277   // Lookup names in the parent scope.
2278   ShadowContextRAII Shadow(Visited);
2279   LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2280 }
2281
2282 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2283                               VisibleDeclConsumer &Consumer) {
2284   // Determine the set of using directives available during
2285   // unqualified name lookup.
2286   Scope *Initial = S;
2287   UnqualUsingDirectiveSet UDirs;
2288   if (getLangOptions().CPlusPlus) {
2289     // Find the first namespace or translation-unit scope.
2290     while (S && !isNamespaceOrTranslationUnitScope(S))
2291       S = S->getParent();
2292
2293     UDirs.visitScopeChain(Initial, S);
2294   }
2295   UDirs.done();
2296
2297   // Look for visible declarations.
2298   LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2299   VisibleDeclsRecord Visited;
2300   ShadowContextRAII Shadow(Visited);
2301   ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2302 }
2303
2304 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2305                               VisibleDeclConsumer &Consumer) {
2306   LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2307   VisibleDeclsRecord Visited;
2308   ShadowContextRAII Shadow(Visited);
2309   ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, 
2310                        /*InBaseClass=*/false, Consumer, Visited);
2311 }
2312
2313 //----------------------------------------------------------------------------
2314 // Typo correction
2315 //----------------------------------------------------------------------------
2316
2317 namespace {
2318 class TypoCorrectionConsumer : public VisibleDeclConsumer {
2319   /// \brief The name written that is a typo in the source.
2320   llvm::StringRef Typo;
2321
2322   /// \brief The results found that have the smallest edit distance
2323   /// found (so far) with the typo name.
2324   llvm::SmallVector<NamedDecl *, 4> BestResults;
2325
2326   /// \brief The best edit distance found so far.
2327   unsigned BestEditDistance;
2328   
2329 public:
2330   explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2331     : Typo(Typo->getName()) { }
2332
2333   virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
2334
2335   typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2336   iterator begin() const { return BestResults.begin(); }
2337   iterator end() const { return BestResults.end(); }
2338   bool empty() const { return BestResults.empty(); }
2339
2340   unsigned getBestEditDistance() const { return BestEditDistance; }
2341 };
2342
2343 }
2344
2345 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 
2346                                        bool InBaseClass) {
2347   // Don't consider hidden names for typo correction.
2348   if (Hiding)
2349     return;
2350   
2351   // Only consider entities with identifiers for names, ignoring
2352   // special names (constructors, overloaded operators, selectors,
2353   // etc.).
2354   IdentifierInfo *Name = ND->getIdentifier();
2355   if (!Name)
2356     return;
2357
2358   // Compute the edit distance between the typo and the name of this
2359   // entity. If this edit distance is not worse than the best edit
2360   // distance we've seen so far, add it to the list of results.
2361   unsigned ED = Typo.edit_distance(Name->getName());
2362   if (!BestResults.empty()) {
2363     if (ED < BestEditDistance) {
2364       // This result is better than any we've seen before; clear out
2365       // the previous results.
2366       BestResults.clear();
2367       BestEditDistance = ED;
2368     } else if (ED > BestEditDistance) {
2369       // This result is worse than the best results we've seen so far;
2370       // ignore it.
2371       return;
2372     }
2373   } else
2374     BestEditDistance = ED;
2375
2376   BestResults.push_back(ND);
2377 }
2378
2379 /// \brief Try to "correct" a typo in the source code by finding
2380 /// visible declarations whose names are similar to the name that was
2381 /// present in the source code.
2382 ///
2383 /// \param Res the \c LookupResult structure that contains the name
2384 /// that was present in the source code along with the name-lookup
2385 /// criteria used to search for the name. On success, this structure
2386 /// will contain the results of name lookup.
2387 ///
2388 /// \param S the scope in which name lookup occurs.
2389 ///
2390 /// \param SS the nested-name-specifier that precedes the name we're
2391 /// looking for, if present.
2392 ///
2393 /// \param MemberContext if non-NULL, the context in which to look for
2394 /// a member access expression.
2395 ///
2396 /// \param EnteringContext whether we're entering the context described by 
2397 /// the nested-name-specifier SS.
2398 ///
2399 /// \param OPT when non-NULL, the search for visible declarations will
2400 /// also walk the protocols in the qualified interfaces of \p OPT.
2401 ///
2402 /// \returns true if the typo was corrected, in which case the \p Res
2403 /// structure will contain the results of name lookup for the
2404 /// corrected name. Otherwise, returns false.
2405 bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
2406                        DeclContext *MemberContext, bool EnteringContext,
2407                        const ObjCObjectPointerType *OPT) {
2408   if (Diags.hasFatalErrorOccurred())
2409     return false;
2410
2411   // Provide a stop gap for files that are just seriously broken.  Trying
2412   // to correct all typos can turn into a HUGE performance penalty, causing
2413   // some files to take minutes to get rejected by the parser.
2414   // FIXME: Is this the right solution?
2415   if (TyposCorrected == 20)
2416     return false;
2417   ++TyposCorrected;
2418   
2419   // We only attempt to correct typos for identifiers.
2420   IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2421   if (!Typo)
2422     return false;
2423
2424   // If the scope specifier itself was invalid, don't try to correct
2425   // typos.
2426   if (SS && SS->isInvalid())
2427     return false;
2428
2429   // Never try to correct typos during template deduction or
2430   // instantiation.
2431   if (!ActiveTemplateInstantiations.empty())
2432     return false;
2433
2434   TypoCorrectionConsumer Consumer(Typo);
2435   if (MemberContext) {
2436     LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
2437
2438     // Look in qualified interfaces.
2439     if (OPT) {
2440       for (ObjCObjectPointerType::qual_iterator 
2441              I = OPT->qual_begin(), E = OPT->qual_end(); 
2442            I != E; ++I)
2443         LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2444     }
2445   } else if (SS && SS->isSet()) {
2446     DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2447     if (!DC)
2448       return false;
2449     
2450     LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2451   } else {
2452     LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2453   }
2454
2455   if (Consumer.empty())
2456     return false;
2457
2458   // Only allow a single, closest name in the result set (it's okay to
2459   // have overloads of that name, though).
2460   TypoCorrectionConsumer::iterator I = Consumer.begin();
2461   DeclarationName BestName = (*I)->getDeclName();
2462
2463   // If we've found an Objective-C ivar or property, don't perform
2464   // name lookup again; we'll just return the result directly.
2465   NamedDecl *FoundBest = 0;
2466   if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I))
2467     FoundBest = *I;
2468   ++I;
2469   for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
2470     if (BestName != (*I)->getDeclName())
2471       return false;
2472
2473     // FIXME: If there are both ivars and properties of the same name,
2474     // don't return both because the callee can't handle two
2475     // results. We really need to separate ivar lookup from property
2476     // lookup to avoid this problem.
2477     FoundBest = 0;
2478   }
2479
2480   // BestName is the closest viable name to what the user
2481   // typed. However, to make sure that we don't pick something that's
2482   // way off, make sure that the user typed at least 3 characters for
2483   // each correction.
2484   unsigned ED = Consumer.getBestEditDistance();
2485   if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2486     return false;
2487
2488   // Perform name lookup again with the name we chose, and declare
2489   // success if we found something that was not ambiguous.
2490   Res.clear();
2491   Res.setLookupName(BestName);
2492
2493   // If we found an ivar or property, add that result; no further
2494   // lookup is required.
2495   if (FoundBest)
2496     Res.addDecl(FoundBest);  
2497   // If we're looking into the context of a member, perform qualified
2498   // name lookup on the best name.
2499   else if (MemberContext)
2500     LookupQualifiedName(Res, MemberContext);
2501   // Perform lookup as if we had just parsed the best name.
2502   else
2503     LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 
2504                      EnteringContext);
2505
2506   if (Res.isAmbiguous()) {
2507     Res.suppressDiagnostics();
2508     return false;
2509   }
2510
2511   return Res.getResultKind() != LookupResult::NotFound;
2512 }