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