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