]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaLookup.cpp
Import Clang r74383.
[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 "SemaInherit.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/Parse/DeclSpec.h"
23 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include <set>
28 #include <vector>
29 #include <iterator>
30 #include <utility>
31 #include <algorithm>
32
33 using namespace clang;
34
35 typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
36 typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
37 typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
38
39 /// UsingDirAncestorCompare - Implements strict weak ordering of
40 /// UsingDirectives. It orders them by address of its common ancestor.
41 struct UsingDirAncestorCompare {
42
43   /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
44   bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
45     return U->getCommonAncestor() < Ctx;
46   }
47
48   /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
49   bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
50     return Ctx < U->getCommonAncestor();
51   }
52
53   /// @brief Compares UsingDirectiveDecl common ancestors.
54   bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
55     return U1->getCommonAncestor() < U2->getCommonAncestor();
56   }
57 };
58
59 /// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
60 /// (ordered by common ancestors), found in namespace NS,
61 /// including all found (recursively) in their nominated namespaces.
62 void AddNamespaceUsingDirectives(ASTContext &Context, 
63                                  DeclContext *NS,
64                                  UsingDirectivesTy &UDirs,
65                                  NamespaceSet &Visited) {
66   DeclContext::udir_iterator I, End;
67
68   for (llvm::tie(I, End) = NS->getUsingDirectives(Context); I !=End; ++I) {
69     UDirs.push_back(*I);
70     std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
71     NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
72     if (Visited.insert(Nominated).second)
73       AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
74   }
75 }
76
77 /// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
78 /// including all found in the namespaces they nominate.
79 static void AddScopeUsingDirectives(ASTContext &Context, Scope *S, 
80                                     UsingDirectivesTy &UDirs) {
81   NamespaceSet VisitedNS;
82
83   if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
84
85     if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
86       VisitedNS.insert(NS);
87
88     AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
89
90   } else {
91     Scope::udir_iterator I = S->using_directives_begin(),
92                          End = S->using_directives_end();
93
94     for (; I != End; ++I) {
95       UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
96       UDirs.push_back(UD);
97       std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
98
99       NamespaceDecl *Nominated = UD->getNominatedNamespace();
100       if (!VisitedNS.count(Nominated)) {
101         VisitedNS.insert(Nominated);
102         AddNamespaceUsingDirectives(Context, Nominated, UDirs, 
103                                     /*ref*/ VisitedNS);
104       }
105     }
106   }
107 }
108
109 /// MaybeConstructOverloadSet - Name lookup has determined that the
110 /// elements in [I, IEnd) have the name that we are looking for, and
111 /// *I is a match for the namespace. This routine returns an
112 /// appropriate Decl for name lookup, which may either be *I or an
113 /// OverloadedFunctionDecl that represents the overloaded functions in
114 /// [I, IEnd). 
115 ///
116 /// The existance of this routine is temporary; users of LookupResult
117 /// should be able to handle multiple results, to deal with cases of
118 /// ambiguity and overloaded functions without needing to create a
119 /// Decl node.
120 template<typename DeclIterator>
121 static NamedDecl *
122 MaybeConstructOverloadSet(ASTContext &Context, 
123                           DeclIterator I, DeclIterator IEnd) {
124   assert(I != IEnd && "Iterator range cannot be empty");
125   assert(!isa<OverloadedFunctionDecl>(*I) && 
126          "Cannot have an overloaded function");
127
128   if ((*I)->isFunctionOrFunctionTemplate()) {
129     // If we found a function, there might be more functions. If
130     // so, collect them into an overload set.
131     DeclIterator Last = I;
132     OverloadedFunctionDecl *Ovl = 0;
133     for (++Last; 
134          Last != IEnd && (*Last)->isFunctionOrFunctionTemplate(); 
135          ++Last) {
136       if (!Ovl) {
137         // FIXME: We leak this overload set. Eventually, we want to stop
138         // building the declarations for these overload sets, so there will be
139         // nothing to leak.
140         Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
141                                              (*I)->getDeclName());
142         NamedDecl *ND = (*I)->getUnderlyingDecl();
143         if (isa<FunctionDecl>(ND))
144           Ovl->addOverload(cast<FunctionDecl>(ND));
145         else
146           Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
147       }
148
149       NamedDecl *ND = (*Last)->getUnderlyingDecl();
150       if (isa<FunctionDecl>(ND))
151         Ovl->addOverload(cast<FunctionDecl>(ND));
152       else
153         Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
154     }
155     
156     // If we had more than one function, we built an overload
157     // set. Return it.
158     if (Ovl)
159       return Ovl;
160   }
161   
162   return *I;
163 }
164
165 /// Merges together multiple LookupResults dealing with duplicated Decl's.
166 static Sema::LookupResult
167 MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
168   typedef Sema::LookupResult LResult;
169   typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
170
171   // Remove duplicated Decl pointing at same Decl, by storing them in
172   // associative collection. This might be case for code like:
173   //
174   //    namespace A { int i; }
175   //    namespace B { using namespace A; }
176   //    namespace C { using namespace A; }
177   //
178   //    void foo() {
179   //      using namespace B;
180   //      using namespace C;
181   //      ++i; // finds A::i, from both namespace B and C at global scope
182   //    }
183   //
184   //  C++ [namespace.qual].p3:
185   //    The same declaration found more than once is not an ambiguity
186   //    (because it is still a unique declaration).
187   DeclsSetTy FoundDecls;
188
189   // Counter of tag names, and functions for resolving ambiguity
190   // and name hiding.
191   std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
192
193   LookupResultsTy::iterator I = Results.begin(), End = Results.end();
194
195   // No name lookup results, return early.
196   if (I == End) return LResult::CreateLookupResult(Context, 0);
197
198   // Keep track of the tag declaration we found. We only use this if
199   // we find a single tag declaration.
200   TagDecl *TagFound = 0;
201
202   for (; I != End; ++I) {
203     switch (I->getKind()) {
204     case LResult::NotFound:
205       assert(false &&
206              "Should be always successful name lookup result here.");
207       break;
208
209     case LResult::AmbiguousReference:
210     case LResult::AmbiguousBaseSubobjectTypes:
211     case LResult::AmbiguousBaseSubobjects:
212       assert(false && "Shouldn't get ambiguous lookup here.");
213       break;
214
215     case LResult::Found: {
216       NamedDecl *ND = I->getAsDecl()->getUnderlyingDecl();
217         
218       if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
219         TagFound = Context.getCanonicalDecl(TD);
220         TagNames += FoundDecls.insert(TagFound)?  1 : 0;
221       } else if (ND->isFunctionOrFunctionTemplate())
222         Functions += FoundDecls.insert(ND)? 1 : 0;
223       else
224         FoundDecls.insert(ND);
225       break;
226     }
227
228     case LResult::FoundOverloaded:
229       for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
230         Functions += FoundDecls.insert(*FI)? 1 : 0;
231       break;
232     }
233   }
234   OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
235   bool Ambiguous = false, NameHidesTags = false;
236   
237   if (FoundDecls.size() == 1) {
238     // 1) Exactly one result.
239   } else if (TagNames > 1) {
240     // 2) Multiple tag names (even though they may be hidden by an
241     // object name).
242     Ambiguous = true;
243   } else if (FoundDecls.size() - TagNames == 1) {
244     // 3) Ordinary name hides (optional) tag.
245     NameHidesTags = TagFound;
246   } else if (Functions) {
247     // C++ [basic.lookup].p1:
248     // ... Name lookup may associate more than one declaration with
249     // a name if it finds the name to be a function name; the declarations
250     // are said to form a set of overloaded functions (13.1).
251     // Overload resolution (13.3) takes place after name lookup has succeeded.
252     //
253     if (!OrdinaryNonFunc) {
254       // 4) Functions hide tag names.
255       NameHidesTags = TagFound;
256     } else {
257       // 5) Functions + ordinary names.
258       Ambiguous = true;
259     }
260   } else {
261     // 6) Multiple non-tag names
262     Ambiguous = true;
263   }
264
265   if (Ambiguous)
266     return LResult::CreateLookupResult(Context, 
267                                        FoundDecls.begin(), FoundDecls.size());
268   if (NameHidesTags) {
269     // There's only one tag, TagFound. Remove it.
270     assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
271     FoundDecls.erase(TagFound);
272   }
273
274   // Return successful name lookup result.
275   return LResult::CreateLookupResult(Context,
276                                 MaybeConstructOverloadSet(Context,
277                                                           FoundDecls.begin(),
278                                                           FoundDecls.end()));
279 }
280
281 // Retrieve the set of identifier namespaces that correspond to a
282 // specific kind of name lookup.
283 inline unsigned 
284 getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind, 
285                                           bool CPlusPlus) {
286   unsigned IDNS = 0;
287   switch (NameKind) {
288   case Sema::LookupOrdinaryName:
289   case Sema::LookupOperatorName:
290   case Sema::LookupRedeclarationWithLinkage:
291     IDNS = Decl::IDNS_Ordinary;
292     if (CPlusPlus)
293       IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
294     break;
295
296   case Sema::LookupTagName:
297     IDNS = Decl::IDNS_Tag;
298     break;
299
300   case Sema::LookupMemberName:
301     IDNS = Decl::IDNS_Member;
302     if (CPlusPlus)
303       IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;    
304     break;
305
306   case Sema::LookupNestedNameSpecifierName:
307   case Sema::LookupNamespaceName:
308     IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
309     break;
310
311   case Sema::LookupObjCProtocolName:
312     IDNS = Decl::IDNS_ObjCProtocol;
313     break;
314
315   case Sema::LookupObjCImplementationName:
316     IDNS = Decl::IDNS_ObjCImplementation;
317     break;
318
319   case Sema::LookupObjCCategoryImplName:
320     IDNS = Decl::IDNS_ObjCCategoryImpl;
321     break;
322   }
323   return IDNS;
324 }
325
326 Sema::LookupResult
327 Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
328   if (D)
329     D = D->getUnderlyingDecl();
330   
331   LookupResult Result;
332   Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
333     OverloadedDeclSingleDecl : SingleDecl;
334   Result.First = reinterpret_cast<uintptr_t>(D);
335   Result.Last = 0;
336   Result.Context = &Context;
337   return Result;
338 }
339
340 /// @brief Moves the name-lookup results from Other to this LookupResult.
341 Sema::LookupResult
342 Sema::LookupResult::CreateLookupResult(ASTContext &Context, 
343                                        IdentifierResolver::iterator F, 
344                                        IdentifierResolver::iterator L) {
345   LookupResult Result;
346   Result.Context = &Context;
347
348   if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
349     IdentifierResolver::iterator Next = F;
350     ++Next;
351     if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
352       Result.StoredKind = OverloadedDeclFromIdResolver;
353       Result.First = F.getAsOpaqueValue();
354       Result.Last = L.getAsOpaqueValue();
355       return Result;
356     }
357   } 
358
359   NamedDecl *D = *F;
360   if (D)
361     D = D->getUnderlyingDecl();
362
363   Result.StoredKind = SingleDecl;
364   Result.First = reinterpret_cast<uintptr_t>(D);
365   Result.Last = 0;
366   return Result;
367 }
368
369 Sema::LookupResult
370 Sema::LookupResult::CreateLookupResult(ASTContext &Context, 
371                                        DeclContext::lookup_iterator F, 
372                                        DeclContext::lookup_iterator L) {
373   LookupResult Result;
374   Result.Context = &Context;
375
376   if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
377     DeclContext::lookup_iterator Next = F;
378     ++Next;
379     if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
380       Result.StoredKind = OverloadedDeclFromDeclContext;
381       Result.First = reinterpret_cast<uintptr_t>(F);
382       Result.Last = reinterpret_cast<uintptr_t>(L);
383       return Result;
384     }
385   }
386
387   NamedDecl *D = *F;
388   if (D)
389     D = D->getUnderlyingDecl();
390   
391   Result.StoredKind = SingleDecl;
392   Result.First = reinterpret_cast<uintptr_t>(D);
393   Result.Last = 0;
394   return Result;
395 }
396
397 /// @brief Determine the result of name lookup.
398 Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
399   switch (StoredKind) {
400   case SingleDecl:
401     return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
402
403   case OverloadedDeclSingleDecl:
404   case OverloadedDeclFromIdResolver:
405   case OverloadedDeclFromDeclContext:
406     return FoundOverloaded;
407
408   case AmbiguousLookupStoresBasePaths:
409     return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
410
411   case AmbiguousLookupStoresDecls:
412     return AmbiguousReference;
413   }
414
415   // We can't ever get here.
416   return NotFound;
417 }
418
419 /// @brief Converts the result of name lookup into a single (possible
420 /// NULL) pointer to a declaration.
421 ///
422 /// The resulting declaration will either be the declaration we found
423 /// (if only a single declaration was found), an
424 /// OverloadedFunctionDecl (if an overloaded function was found), or
425 /// NULL (if no declaration was found). This conversion must not be
426 /// used anywhere where name lookup could result in an ambiguity. 
427 ///
428 /// The OverloadedFunctionDecl conversion is meant as a stop-gap
429 /// solution, since it causes the OverloadedFunctionDecl to be
430 /// leaked. FIXME: Eventually, there will be a better way to iterate
431 /// over the set of overloaded functions returned by name lookup.
432 NamedDecl *Sema::LookupResult::getAsDecl() const {
433   switch (StoredKind) {
434   case SingleDecl:
435     return reinterpret_cast<NamedDecl *>(First);
436
437   case OverloadedDeclFromIdResolver:
438     return MaybeConstructOverloadSet(*Context,
439                          IdentifierResolver::iterator::getFromOpaqueValue(First),
440                          IdentifierResolver::iterator::getFromOpaqueValue(Last));
441
442   case OverloadedDeclFromDeclContext:
443     return MaybeConstructOverloadSet(*Context, 
444                            reinterpret_cast<DeclContext::lookup_iterator>(First),
445                            reinterpret_cast<DeclContext::lookup_iterator>(Last));
446
447   case OverloadedDeclSingleDecl:
448     return reinterpret_cast<OverloadedFunctionDecl*>(First);
449
450   case AmbiguousLookupStoresDecls:
451   case AmbiguousLookupStoresBasePaths:
452     assert(false && 
453            "Name lookup returned an ambiguity that could not be handled");
454     break;
455   }
456
457   return 0;
458 }
459
460 /// @brief Retrieves the BasePaths structure describing an ambiguous
461 /// name lookup, or null.
462 BasePaths *Sema::LookupResult::getBasePaths() const {
463   if (StoredKind == AmbiguousLookupStoresBasePaths)
464       return reinterpret_cast<BasePaths *>(First);
465   return 0;
466 }
467
468 Sema::LookupResult::iterator::reference 
469 Sema::LookupResult::iterator::operator*() const {
470   switch (Result->StoredKind) {
471   case SingleDecl:
472     return reinterpret_cast<NamedDecl*>(Current);
473
474   case OverloadedDeclSingleDecl:
475     return *reinterpret_cast<NamedDecl**>(Current);
476
477   case OverloadedDeclFromIdResolver:
478     return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
479
480   case AmbiguousLookupStoresBasePaths:
481     if (Result->Last)
482       return *reinterpret_cast<NamedDecl**>(Current);
483
484     // Fall through to handle the DeclContext::lookup_iterator we're
485     // storing.
486
487   case OverloadedDeclFromDeclContext:
488   case AmbiguousLookupStoresDecls:
489     return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
490   }
491
492   return 0;
493 }
494
495 Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
496   switch (Result->StoredKind) {
497   case SingleDecl:
498     Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
499     break;
500
501   case OverloadedDeclSingleDecl: {
502     NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
503     ++I;
504     Current = reinterpret_cast<uintptr_t>(I);
505     break;
506   }
507
508   case OverloadedDeclFromIdResolver: {
509     IdentifierResolver::iterator I 
510       = IdentifierResolver::iterator::getFromOpaqueValue(Current);
511     ++I;
512     Current = I.getAsOpaqueValue();
513     break;
514   }
515
516   case AmbiguousLookupStoresBasePaths: 
517     if (Result->Last) {
518       NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
519       ++I;
520       Current = reinterpret_cast<uintptr_t>(I);
521       break;
522     }
523     // Fall through to handle the DeclContext::lookup_iterator we're
524     // storing.
525
526   case OverloadedDeclFromDeclContext:
527   case AmbiguousLookupStoresDecls: {
528     DeclContext::lookup_iterator I 
529       = reinterpret_cast<DeclContext::lookup_iterator>(Current);
530     ++I;
531     Current = reinterpret_cast<uintptr_t>(I);
532     break;
533   }
534   }
535
536   return *this;
537 }
538
539 Sema::LookupResult::iterator Sema::LookupResult::begin() {
540   switch (StoredKind) {
541   case SingleDecl:
542   case OverloadedDeclFromIdResolver:
543   case OverloadedDeclFromDeclContext:
544   case AmbiguousLookupStoresDecls:
545     return iterator(this, First);
546
547   case OverloadedDeclSingleDecl: {
548     OverloadedFunctionDecl * Ovl =
549       reinterpret_cast<OverloadedFunctionDecl*>(First);
550     return iterator(this, 
551                     reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
552   }
553
554   case AmbiguousLookupStoresBasePaths:
555     if (Last)
556       return iterator(this, 
557               reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
558     else
559       return iterator(this,
560               reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
561   }
562
563   // Required to suppress GCC warning.
564   return iterator();
565 }
566
567 Sema::LookupResult::iterator Sema::LookupResult::end() {
568   switch (StoredKind) {
569   case SingleDecl:
570   case OverloadedDeclFromIdResolver:
571   case OverloadedDeclFromDeclContext:
572   case AmbiguousLookupStoresDecls:
573     return iterator(this, Last);
574
575   case OverloadedDeclSingleDecl: {
576     OverloadedFunctionDecl * Ovl =
577       reinterpret_cast<OverloadedFunctionDecl*>(First);
578     return iterator(this, 
579                     reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
580   }
581
582   case AmbiguousLookupStoresBasePaths:
583     if (Last)
584       return iterator(this, 
585                reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
586     else
587       return iterator(this, reinterpret_cast<uintptr_t>(
588                                      getBasePaths()->front().Decls.second));
589   }
590
591   // Required to suppress GCC warning.
592   return iterator();
593 }
594
595 void Sema::LookupResult::Destroy() {
596   if (BasePaths *Paths = getBasePaths())
597     delete Paths;
598   else if (getKind() == AmbiguousReference)
599     delete[] reinterpret_cast<NamedDecl **>(First);
600 }
601
602 static void
603 CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
604                    DeclarationName Name, Sema::LookupNameKind NameKind,
605                    unsigned IDNS, LookupResultsTy &Results,
606                    UsingDirectivesTy *UDirs = 0) {
607
608   assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
609
610   // Perform qualified name lookup into the LookupCtx.
611   DeclContext::lookup_iterator I, E;
612   for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I)
613     if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
614       Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
615       break;
616     }
617
618   if (UDirs) {
619     // For each UsingDirectiveDecl, which common ancestor is equal
620     // to NS, we preform qualified name lookup into namespace nominated by it.
621     UsingDirectivesTy::const_iterator UI, UEnd;
622     llvm::tie(UI, UEnd) =
623       std::equal_range(UDirs->begin(), UDirs->end(), NS,
624                        UsingDirAncestorCompare());
625  
626     for (; UI != UEnd; ++UI)
627       CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
628                          Name, NameKind, IDNS, Results);
629   }
630 }
631
632 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
633   if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
634     return Ctx->isFileContext();
635   return false;
636 }
637
638 std::pair<bool, Sema::LookupResult>
639 Sema::CppLookupName(Scope *S, DeclarationName Name,
640                     LookupNameKind NameKind, bool RedeclarationOnly) {
641   assert(getLangOptions().CPlusPlus &&
642          "Can perform only C++ lookup");
643   unsigned IDNS 
644     = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
645   Scope *Initial = S;
646   DeclContext *OutOfLineCtx = 0;
647   IdentifierResolver::iterator 
648     I = IdResolver.begin(Name),
649     IEnd = IdResolver.end();
650
651   // First we lookup local scope.
652   // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
653   // ...During unqualified name lookup (3.4.1), the names appear as if
654   // they were declared in the nearest enclosing namespace which contains
655   // both the using-directive and the nominated namespace.
656   // [Note: in this context, “contains” means “contains directly or
657   // indirectly”. 
658   //
659   // For example:
660   // namespace A { int i; }
661   // void foo() {
662   //   int i;
663   //   {
664   //     using namespace A;
665   //     ++i; // finds local 'i', A::i appears at global scope
666   //   }
667   // }
668   //
669   for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
670     // Check whether the IdResolver has anything in this scope.
671     for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
672       if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
673         // We found something.  Look for anything else in our scope
674         // with this same name and in an acceptable identifier
675         // namespace, so that we can construct an overload set if we
676         // need to.
677         IdentifierResolver::iterator LastI = I;
678         for (++LastI; LastI != IEnd; ++LastI) {
679           if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
680             break;
681         }
682         LookupResult Result =
683           LookupResult::CreateLookupResult(Context, I, LastI);
684         return std::make_pair(true, Result);
685       }
686     }
687     if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
688       LookupResult R;
689       // Perform member lookup into struct.
690       // FIXME: In some cases, we know that every name that could be found by
691       // this qualified name lookup will also be on the identifier chain. For
692       // example, inside a class without any base classes, we never need to
693       // perform qualified lookup because all of the members are on top of the
694       // identifier chain.
695       if (isa<RecordDecl>(Ctx)) {
696         R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
697         if (R)
698           return std::make_pair(true, R);
699       }
700       if (Ctx->getParent() != Ctx->getLexicalParent() 
701           || isa<CXXMethodDecl>(Ctx)) {
702         // It is out of line defined C++ method or struct, we continue
703         // doing name lookup in parent context. Once we will find namespace
704         // or translation-unit we save it for possible checking
705         // using-directives later.
706         for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
707              OutOfLineCtx = OutOfLineCtx->getParent()) {
708           R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
709           if (R)
710             return std::make_pair(true, R);
711         }
712       }
713     }
714   }
715
716   // Collect UsingDirectiveDecls in all scopes, and recursively all
717   // nominated namespaces by those using-directives.
718   // UsingDirectives are pushed to heap, in common ancestor pointer value order.
719   // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
720   // don't build it for each lookup!
721   UsingDirectivesTy UDirs;
722   for (Scope *SC = Initial; SC; SC = SC->getParent())
723     if (SC->getFlags() & Scope::DeclScope)
724       AddScopeUsingDirectives(Context, SC, UDirs);
725
726   // Sort heapified UsingDirectiveDecls.
727   std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
728
729   // Lookup namespace scope, and global scope.
730   // Unqualified name lookup in C++ requires looking into scopes
731   // that aren't strictly lexical, and therefore we walk through the
732   // context as well as walking through the scopes.
733
734   LookupResultsTy LookupResults;
735   assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
736          "We should have been looking only at file context here already.");
737   bool LookedInCtx = false;
738   LookupResult Result;
739   while (OutOfLineCtx &&
740          OutOfLineCtx != S->getEntity() &&
741          OutOfLineCtx->isNamespace()) {
742     LookedInCtx = true;
743
744     // Look into context considering using-directives.
745     CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
746                        LookupResults, &UDirs);
747
748     if ((Result = MergeLookupResults(Context, LookupResults)) ||
749         (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
750       return std::make_pair(true, Result);
751
752     OutOfLineCtx = OutOfLineCtx->getParent();
753   }
754
755   for (; S; S = S->getParent()) {
756     DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
757     assert(Ctx && Ctx->isFileContext() &&
758            "We should have been looking only at file context here already.");
759
760     // Check whether the IdResolver has anything in this scope.
761     for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
762       if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
763         // We found something.  Look for anything else in our scope
764         // with this same name and in an acceptable identifier
765         // namespace, so that we can construct an overload set if we
766         // need to.
767         IdentifierResolver::iterator LastI = I;
768         for (++LastI; LastI != IEnd; ++LastI) {
769           if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
770             break;
771         }
772         
773         // We store name lookup result, and continue trying to look into
774         // associated context, and maybe namespaces nominated by
775         // using-directives.
776         LookupResults.push_back(
777           LookupResult::CreateLookupResult(Context, I, LastI));
778         break;
779       }
780     }
781
782     LookedInCtx = true;
783     // Look into context considering using-directives.
784     CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
785                        LookupResults, &UDirs);
786
787     if ((Result = MergeLookupResults(Context, LookupResults)) ||
788         (RedeclarationOnly && !Ctx->isTransparentContext()))
789       return std::make_pair(true, Result);
790   }
791
792   if (!(LookedInCtx || LookupResults.empty())) {
793     // We didn't Performed lookup in Scope entity, so we return
794     // result form IdentifierResolver.
795     assert((LookupResults.size() == 1) && "Wrong size!");
796     return std::make_pair(true, LookupResults.front());
797   }
798   return std::make_pair(false, LookupResult());
799 }
800
801 /// @brief Perform unqualified name lookup starting from a given
802 /// scope.
803 ///
804 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
805 /// used to find names within the current scope. For example, 'x' in
806 /// @code
807 /// int x;
808 /// int f() {
809 ///   return x; // unqualified name look finds 'x' in the global scope
810 /// }
811 /// @endcode
812 ///
813 /// Different lookup criteria can find different names. For example, a
814 /// particular scope can have both a struct and a function of the same
815 /// name, and each can be found by certain lookup criteria. For more
816 /// information about lookup criteria, see the documentation for the
817 /// class LookupCriteria.
818 ///
819 /// @param S        The scope from which unqualified name lookup will
820 /// begin. If the lookup criteria permits, name lookup may also search
821 /// in the parent scopes.
822 ///
823 /// @param Name     The name of the entity that we are searching for.
824 ///
825 /// @param Loc      If provided, the source location where we're performing
826 /// name lookup. At present, this is only used to produce diagnostics when 
827 /// C library functions (like "malloc") are implicitly declared.
828 ///
829 /// @returns The result of name lookup, which includes zero or more
830 /// declarations and possibly additional information used to diagnose
831 /// ambiguities.
832 Sema::LookupResult 
833 Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
834                  bool RedeclarationOnly, bool AllowBuiltinCreation,
835                  SourceLocation Loc) {
836   if (!Name) return LookupResult::CreateLookupResult(Context, 0);
837
838   if (!getLangOptions().CPlusPlus) {
839     // Unqualified name lookup in C/Objective-C is purely lexical, so
840     // search in the declarations attached to the name.
841     unsigned IDNS = 0;
842     switch (NameKind) {
843     case Sema::LookupOrdinaryName:
844       IDNS = Decl::IDNS_Ordinary;
845       break;
846
847     case Sema::LookupTagName:
848       IDNS = Decl::IDNS_Tag;
849       break;
850
851     case Sema::LookupMemberName:
852       IDNS = Decl::IDNS_Member;
853       break;
854
855     case Sema::LookupOperatorName:
856     case Sema::LookupNestedNameSpecifierName:
857     case Sema::LookupNamespaceName:
858       assert(false && "C does not perform these kinds of name lookup");
859       break;
860
861     case Sema::LookupRedeclarationWithLinkage:
862       // Find the nearest non-transparent declaration scope.
863       while (!(S->getFlags() & Scope::DeclScope) ||
864              (S->getEntity() && 
865               static_cast<DeclContext *>(S->getEntity())
866                 ->isTransparentContext()))
867         S = S->getParent();
868       IDNS = Decl::IDNS_Ordinary;
869       break;
870
871     case Sema::LookupObjCProtocolName:
872       IDNS = Decl::IDNS_ObjCProtocol;
873       break;
874
875     case Sema::LookupObjCImplementationName:
876       IDNS = Decl::IDNS_ObjCImplementation;
877       break;
878       
879     case Sema::LookupObjCCategoryImplName:
880       IDNS = Decl::IDNS_ObjCCategoryImpl;
881       break;
882     }
883
884     // Scan up the scope chain looking for a decl that matches this
885     // identifier that is in the appropriate namespace.  This search
886     // should not take long, as shadowing of names is uncommon, and
887     // deep shadowing is extremely uncommon.
888     bool LeftStartingScope = false;
889
890     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
891                                    IEnd = IdResolver.end(); 
892          I != IEnd; ++I)
893       if ((*I)->isInIdentifierNamespace(IDNS)) {
894         if (NameKind == LookupRedeclarationWithLinkage) {
895           // Determine whether this (or a previous) declaration is
896           // out-of-scope.
897           if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
898             LeftStartingScope = true;
899
900           // If we found something outside of our starting scope that
901           // does not have linkage, skip it.
902           if (LeftStartingScope && !((*I)->hasLinkage()))
903             continue;
904         }
905
906         if ((*I)->getAttr<OverloadableAttr>(Context)) {
907           // If this declaration has the "overloadable" attribute, we
908           // might have a set of overloaded functions.
909
910           // Figure out what scope the identifier is in.
911           while (!(S->getFlags() & Scope::DeclScope) ||
912                  !S->isDeclScope(DeclPtrTy::make(*I)))
913             S = S->getParent();
914
915           // Find the last declaration in this scope (with the same
916           // name, naturally).
917           IdentifierResolver::iterator LastI = I;
918           for (++LastI; LastI != IEnd; ++LastI) {
919             if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
920               break;
921           }
922
923           return LookupResult::CreateLookupResult(Context, I, LastI);
924         }
925
926         // We have a single lookup result.
927         return LookupResult::CreateLookupResult(Context, *I);
928       }
929   } else {
930     // Perform C++ unqualified name lookup.
931     std::pair<bool, LookupResult> MaybeResult =
932       CppLookupName(S, Name, NameKind, RedeclarationOnly);
933     if (MaybeResult.first)
934       return MaybeResult.second;
935   }
936
937   // If we didn't find a use of this identifier, and if the identifier
938   // corresponds to a compiler builtin, create the decl object for the builtin
939   // now, injecting it into translation unit scope, and return it.
940   if (NameKind == LookupOrdinaryName || 
941       NameKind == LookupRedeclarationWithLinkage) {
942     IdentifierInfo *II = Name.getAsIdentifierInfo();
943     if (II && AllowBuiltinCreation) {
944       // If this is a builtin on this (or all) targets, create the decl.
945       if (unsigned BuiltinID = II->getBuiltinID()) {
946         // In C++, we don't have any predefined library functions like
947         // 'malloc'. Instead, we'll just error.
948         if (getLangOptions().CPlusPlus && 
949             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
950           return LookupResult::CreateLookupResult(Context, 0);
951
952         return LookupResult::CreateLookupResult(Context,
953                             LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
954                                                 S, RedeclarationOnly, Loc));
955       }
956     }
957   }
958   return LookupResult::CreateLookupResult(Context, 0);
959 }
960
961 /// @brief Perform qualified name lookup into a given context.
962 ///
963 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
964 /// names when the context of those names is explicit specified, e.g.,
965 /// "std::vector" or "x->member".
966 ///
967 /// Different lookup criteria can find different names. For example, a
968 /// particular scope can have both a struct and a function of the same
969 /// name, and each can be found by certain lookup criteria. For more
970 /// information about lookup criteria, see the documentation for the
971 /// class LookupCriteria.
972 ///
973 /// @param LookupCtx The context in which qualified name lookup will
974 /// search. If the lookup criteria permits, name lookup may also search
975 /// in the parent contexts or (for C++ classes) base classes.
976 ///
977 /// @param Name     The name of the entity that we are searching for.
978 ///
979 /// @param Criteria The criteria that this routine will use to
980 /// determine which names are visible and which names will be
981 /// found. Note that name lookup will find a name that is visible by
982 /// the given criteria, but the entity itself may not be semantically
983 /// correct or even the kind of entity expected based on the
984 /// lookup. For example, searching for a nested-name-specifier name
985 /// might result in an EnumDecl, which is visible but is not permitted
986 /// as a nested-name-specifier in C++03.
987 ///
988 /// @returns The result of name lookup, which includes zero or more
989 /// declarations and possibly additional information used to diagnose
990 /// ambiguities.
991 Sema::LookupResult
992 Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
993                           LookupNameKind NameKind, bool RedeclarationOnly) {
994   assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
995   
996   if (!Name) return LookupResult::CreateLookupResult(Context, 0);
997
998   // If we're performing qualified name lookup (e.g., lookup into a
999   // struct), find fields as part of ordinary name lookup.
1000   unsigned IDNS
1001     = getIdentifierNamespacesFromLookupNameKind(NameKind, 
1002                                                 getLangOptions().CPlusPlus);
1003   if (NameKind == LookupOrdinaryName)
1004     IDNS |= Decl::IDNS_Member;
1005
1006   // Perform qualified name lookup into the LookupCtx.
1007   DeclContext::lookup_iterator I, E;
1008   for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
1009     if (isAcceptableLookupResult(*I, NameKind, IDNS))
1010       return LookupResult::CreateLookupResult(Context, I, E);
1011
1012   // If this isn't a C++ class or we aren't allowed to look into base
1013   // classes, we're done.
1014   if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
1015     return LookupResult::CreateLookupResult(Context, 0);
1016
1017   // Perform lookup into our base classes.
1018   BasePaths Paths;
1019   Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
1020
1021   // Look for this member in our base classes
1022   if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx), 
1023                      MemberLookupCriteria(Name, NameKind, IDNS), Paths))
1024     return LookupResult::CreateLookupResult(Context, 0);
1025
1026   // C++ [class.member.lookup]p2:
1027   //   [...] If the resulting set of declarations are not all from
1028   //   sub-objects of the same type, or the set has a nonstatic member
1029   //   and includes members from distinct sub-objects, there is an
1030   //   ambiguity and the program is ill-formed. Otherwise that set is
1031   //   the result of the lookup.
1032   // FIXME: support using declarations!
1033   QualType SubobjectType;
1034   int SubobjectNumber = 0;
1035   for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1036        Path != PathEnd; ++Path) {
1037     const BasePathElement &PathElement = Path->back();
1038
1039     // Determine whether we're looking at a distinct sub-object or not.
1040     if (SubobjectType.isNull()) {
1041       // This is the first subobject we've looked at. Record it's type.
1042       SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1043       SubobjectNumber = PathElement.SubobjectNumber;
1044     } else if (SubobjectType 
1045                  != Context.getCanonicalType(PathElement.Base->getType())) {
1046       // We found members of the given name in two subobjects of
1047       // different types. This lookup is ambiguous.
1048       BasePaths *PathsOnHeap = new BasePaths;
1049       PathsOnHeap->swap(Paths);
1050       return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
1051     } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1052       // We have a different subobject of the same type.
1053
1054       // C++ [class.member.lookup]p5:
1055       //   A static member, a nested type or an enumerator defined in
1056       //   a base class T can unambiguously be found even if an object
1057       //   has more than one base class subobject of type T. 
1058       Decl *FirstDecl = *Path->Decls.first;
1059       if (isa<VarDecl>(FirstDecl) ||
1060           isa<TypeDecl>(FirstDecl) ||
1061           isa<EnumConstantDecl>(FirstDecl))
1062         continue;
1063
1064       if (isa<CXXMethodDecl>(FirstDecl)) {
1065         // Determine whether all of the methods are static.
1066         bool AllMethodsAreStatic = true;
1067         for (DeclContext::lookup_iterator Func = Path->Decls.first;
1068              Func != Path->Decls.second; ++Func) {
1069           if (!isa<CXXMethodDecl>(*Func)) {
1070             assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1071             break;
1072           }
1073
1074           if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1075             AllMethodsAreStatic = false;
1076             break;
1077           }
1078         }
1079
1080         if (AllMethodsAreStatic)
1081           continue;
1082       }
1083
1084       // We have found a nonstatic member name in multiple, distinct
1085       // subobjects. Name lookup is ambiguous.
1086       BasePaths *PathsOnHeap = new BasePaths;
1087       PathsOnHeap->swap(Paths);
1088       return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
1089     }
1090   }
1091
1092   // Lookup in a base class succeeded; return these results.
1093
1094   // If we found a function declaration, return an overload set.
1095   if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
1096     return LookupResult::CreateLookupResult(Context, 
1097                         Paths.front().Decls.first, Paths.front().Decls.second);
1098
1099   // We found a non-function declaration; return a single declaration.
1100   return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
1101 }
1102
1103 /// @brief Performs name lookup for a name that was parsed in the
1104 /// source code, and may contain a C++ scope specifier.
1105 ///
1106 /// This routine is a convenience routine meant to be called from
1107 /// contexts that receive a name and an optional C++ scope specifier
1108 /// (e.g., "N::M::x"). It will then perform either qualified or
1109 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1110 /// respectively) on the given name and return those results.
1111 ///
1112 /// @param S        The scope from which unqualified name lookup will
1113 /// begin.
1114 /// 
1115 /// @param SS       An optional C++ scope-specified, e.g., "::N::M".
1116 ///
1117 /// @param Name     The name of the entity that name lookup will
1118 /// search for.
1119 ///
1120 /// @param Loc      If provided, the source location where we're performing
1121 /// name lookup. At present, this is only used to produce diagnostics when 
1122 /// C library functions (like "malloc") are implicitly declared.
1123 ///
1124 /// @returns The result of qualified or unqualified name lookup.
1125 Sema::LookupResult
1126 Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS, 
1127                        DeclarationName Name, LookupNameKind NameKind,
1128                        bool RedeclarationOnly, bool AllowBuiltinCreation,
1129                        SourceLocation Loc) {
1130   if (SS && (SS->isSet() || SS->isInvalid())) {
1131     // If the scope specifier is invalid, don't even look for
1132     // anything.
1133     if (SS->isInvalid())
1134       return LookupResult::CreateLookupResult(Context, 0);
1135
1136     assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1137
1138     if (isDependentScopeSpecifier(*SS)) {
1139       // Determine whether we are looking into the current
1140       // instantiation. 
1141       NestedNameSpecifier *NNS 
1142         = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1143       CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1144       assert(Current && "Bad dependent scope specifier");
1145       
1146       // We nested name specifier refers to the current instantiation,
1147       // so now we will look for a member of the current instantiation
1148       // (C++0x [temp.dep.type]).
1149       unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1150       DeclContext::lookup_iterator I, E;
1151       for (llvm::tie(I, E) = Current->lookup(Context, Name); I != E; ++I)
1152         if (isAcceptableLookupResult(*I, NameKind, IDNS))
1153           return LookupResult::CreateLookupResult(Context, I, E);
1154     }
1155
1156     if (RequireCompleteDeclContext(*SS))
1157       return LookupResult::CreateLookupResult(Context, 0);
1158
1159     return LookupQualifiedName(computeDeclContext(*SS),
1160                                Name, NameKind, RedeclarationOnly);
1161   }
1162
1163   LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly, 
1164                     AllowBuiltinCreation, Loc));
1165   
1166   return(result);
1167 }
1168
1169
1170 /// @brief Produce a diagnostic describing the ambiguity that resulted
1171 /// from name lookup.
1172 ///
1173 /// @param Result       The ambiguous name lookup result.
1174 /// 
1175 /// @param Name         The name of the entity that name lookup was
1176 /// searching for.
1177 ///
1178 /// @param NameLoc      The location of the name within the source code.
1179 ///
1180 /// @param LookupRange  A source range that provides more
1181 /// source-location information concerning the lookup itself. For
1182 /// example, this range might highlight a nested-name-specifier that
1183 /// precedes the name.
1184 ///
1185 /// @returns true
1186 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1187                                    SourceLocation NameLoc, 
1188                                    SourceRange LookupRange) {
1189   assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1190
1191   if (BasePaths *Paths = Result.getBasePaths()) {
1192     if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1193       QualType SubobjectType = Paths->front().back().Base->getType();
1194       Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1195         << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1196         << LookupRange;
1197
1198       DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1199       while (isa<CXXMethodDecl>(*Found) && 
1200              cast<CXXMethodDecl>(*Found)->isStatic())
1201         ++Found;
1202
1203       Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1204
1205       Result.Destroy();
1206       return true;
1207     } 
1208
1209     assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1210            "Unhandled form of name lookup ambiguity");
1211
1212     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1213       << Name << LookupRange;
1214
1215     std::set<Decl *> DeclsPrinted;
1216     for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1217          Path != PathEnd; ++Path) {
1218       Decl *D = *Path->Decls.first;
1219       if (DeclsPrinted.insert(D).second)
1220         Diag(D->getLocation(), diag::note_ambiguous_member_found);
1221     }
1222
1223     Result.Destroy();
1224     return true;
1225   } else if (Result.getKind() == LookupResult::AmbiguousReference) {
1226     Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1227
1228     NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
1229             **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
1230
1231     for (; DI != DEnd; ++DI)
1232       Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1233
1234     Result.Destroy();
1235     return true;
1236   }
1237
1238   assert(false && "Unhandled form of name lookup ambiguity");
1239
1240   // We can't reach here.
1241   return true;
1242 }
1243
1244 // \brief Add the associated classes and namespaces for
1245 // argument-dependent lookup with an argument of class type 
1246 // (C++ [basic.lookup.koenig]p2). 
1247 static void 
1248 addAssociatedClassesAndNamespaces(CXXRecordDecl *Class, 
1249                                   ASTContext &Context,
1250                             Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1251                             Sema::AssociatedClassSet &AssociatedClasses,
1252                                   bool &GlobalScope) {
1253   // C++ [basic.lookup.koenig]p2:
1254   //   [...]
1255   //     -- If T is a class type (including unions), its associated
1256   //        classes are: the class itself; the class of which it is a
1257   //        member, if any; and its direct and indirect base
1258   //        classes. Its associated namespaces are the namespaces in
1259   //        which its associated classes are defined. 
1260
1261   // Add the class of which it is a member, if any.
1262   DeclContext *Ctx = Class->getDeclContext();
1263   if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1264     AssociatedClasses.insert(EnclosingClass);
1265   // Add the associated namespace for this class.
1266   while (Ctx->isRecord())
1267     Ctx = Ctx->getParent();
1268   if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1269     AssociatedNamespaces.insert(EnclosingNamespace);
1270   else if (Ctx->isTranslationUnit())
1271     GlobalScope = true;
1272   
1273   // Add the class itself. If we've already seen this class, we don't
1274   // need to visit base classes.
1275   if (!AssociatedClasses.insert(Class))
1276     return;
1277
1278   // FIXME: Handle class template specializations
1279
1280   // Add direct and indirect base classes along with their associated
1281   // namespaces.
1282   llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1283   Bases.push_back(Class);
1284   while (!Bases.empty()) {
1285     // Pop this class off the stack.
1286     Class = Bases.back();
1287     Bases.pop_back();
1288
1289     // Visit the base classes.
1290     for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1291                                          BaseEnd = Class->bases_end();
1292          Base != BaseEnd; ++Base) {
1293       const RecordType *BaseType = Base->getType()->getAsRecordType();
1294       CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1295       if (AssociatedClasses.insert(BaseDecl)) {
1296         // Find the associated namespace for this base class.
1297         DeclContext *BaseCtx = BaseDecl->getDeclContext();
1298         while (BaseCtx->isRecord())
1299           BaseCtx = BaseCtx->getParent();
1300         if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1301           AssociatedNamespaces.insert(EnclosingNamespace);
1302         else if (BaseCtx->isTranslationUnit())
1303           GlobalScope = true;
1304
1305         // Make sure we visit the bases of this base class.
1306         if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1307           Bases.push_back(BaseDecl);
1308       }
1309     }
1310   }
1311 }
1312
1313 // \brief Add the associated classes and namespaces for
1314 // argument-dependent lookup with an argument of type T
1315 // (C++ [basic.lookup.koenig]p2). 
1316 static void 
1317 addAssociatedClassesAndNamespaces(QualType T, 
1318                                   ASTContext &Context,
1319                             Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1320                                   Sema::AssociatedClassSet &AssociatedClasses,
1321                                   bool &GlobalScope) {
1322   // C++ [basic.lookup.koenig]p2:
1323   //
1324   //   For each argument type T in the function call, there is a set
1325   //   of zero or more associated namespaces and a set of zero or more
1326   //   associated classes to be considered. The sets of namespaces and
1327   //   classes is determined entirely by the types of the function
1328   //   arguments (and the namespace of any template template
1329   //   argument). Typedef names and using-declarations used to specify
1330   //   the types do not contribute to this set. The sets of namespaces
1331   //   and classes are determined in the following way:
1332   T = Context.getCanonicalType(T).getUnqualifiedType();
1333
1334   //    -- If T is a pointer to U or an array of U, its associated
1335   //       namespaces and classes are those associated with U. 
1336   //
1337   // We handle this by unwrapping pointer and array types immediately,
1338   // to avoid unnecessary recursion.
1339   while (true) {
1340     if (const PointerType *Ptr = T->getAsPointerType())
1341       T = Ptr->getPointeeType();
1342     else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1343       T = Ptr->getElementType();
1344     else 
1345       break;
1346   }
1347
1348   //     -- If T is a fundamental type, its associated sets of
1349   //        namespaces and classes are both empty.
1350   if (T->getAsBuiltinType())
1351     return;
1352
1353   //     -- If T is a class type (including unions), its associated
1354   //        classes are: the class itself; the class of which it is a
1355   //        member, if any; and its direct and indirect base
1356   //        classes. Its associated namespaces are the namespaces in
1357   //        which its associated classes are defined. 
1358   if (const RecordType *ClassType = T->getAsRecordType())
1359     if (CXXRecordDecl *ClassDecl 
1360         = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1361       addAssociatedClassesAndNamespaces(ClassDecl, Context, 
1362                                         AssociatedNamespaces, 
1363                                         AssociatedClasses,
1364                                         GlobalScope);
1365       return;
1366     }
1367
1368   //     -- If T is an enumeration type, its associated namespace is
1369   //        the namespace in which it is defined. If it is class
1370   //        member, its associated class is the member’s class; else
1371   //        it has no associated class. 
1372   if (const EnumType *EnumT = T->getAsEnumType()) {
1373     EnumDecl *Enum = EnumT->getDecl();
1374
1375     DeclContext *Ctx = Enum->getDeclContext();
1376     if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1377       AssociatedClasses.insert(EnclosingClass);
1378
1379     // Add the associated namespace for this class.
1380     while (Ctx->isRecord())
1381       Ctx = Ctx->getParent();
1382     if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1383       AssociatedNamespaces.insert(EnclosingNamespace);
1384     else if (Ctx->isTranslationUnit())
1385       GlobalScope = true;
1386
1387     return;
1388   }
1389
1390   //     -- If T is a function type, its associated namespaces and
1391   //        classes are those associated with the function parameter
1392   //        types and those associated with the return type.
1393   if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1394     // Return type
1395     addAssociatedClassesAndNamespaces(FunctionType->getResultType(), 
1396                                       Context,
1397                                       AssociatedNamespaces, AssociatedClasses,
1398                                       GlobalScope);
1399
1400     const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
1401     if (!Proto)
1402       return;
1403
1404     // Argument types
1405     for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1406                                            ArgEnd = Proto->arg_type_end(); 
1407          Arg != ArgEnd; ++Arg)
1408       addAssociatedClassesAndNamespaces(*Arg, Context,
1409                                         AssociatedNamespaces, AssociatedClasses,
1410                                         GlobalScope);
1411       
1412     return;
1413   }
1414
1415   //     -- If T is a pointer to a member function of a class X, its
1416   //        associated namespaces and classes are those associated
1417   //        with the function parameter types and return type,
1418   //        together with those associated with X. 
1419   //
1420   //     -- If T is a pointer to a data member of class X, its
1421   //        associated namespaces and classes are those associated
1422   //        with the member type together with those associated with
1423   //        X. 
1424   if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1425     // Handle the type that the pointer to member points to.
1426     addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1427                                       Context,
1428                                       AssociatedNamespaces, AssociatedClasses,
1429                                       GlobalScope);
1430
1431     // Handle the class type into which this points.
1432     if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1433       addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1434                                         Context,
1435                                         AssociatedNamespaces, AssociatedClasses,
1436                                         GlobalScope);
1437
1438     return;
1439   }
1440
1441   // FIXME: What about block pointers?
1442   // FIXME: What about Objective-C message sends?
1443 }
1444
1445 /// \brief Find the associated classes and namespaces for
1446 /// argument-dependent lookup for a call with the given set of
1447 /// arguments.
1448 ///
1449 /// This routine computes the sets of associated classes and associated
1450 /// namespaces searched by argument-dependent lookup 
1451 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1452 void 
1453 Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1454                                  AssociatedNamespaceSet &AssociatedNamespaces,
1455                                  AssociatedClassSet &AssociatedClasses,
1456                                          bool &GlobalScope) {
1457   AssociatedNamespaces.clear();
1458   AssociatedClasses.clear();
1459
1460   // C++ [basic.lookup.koenig]p2:
1461   //   For each argument type T in the function call, there is a set
1462   //   of zero or more associated namespaces and a set of zero or more
1463   //   associated classes to be considered. The sets of namespaces and
1464   //   classes is determined entirely by the types of the function
1465   //   arguments (and the namespace of any template template
1466   //   argument). 
1467   for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1468     Expr *Arg = Args[ArgIdx];
1469
1470     if (Arg->getType() != Context.OverloadTy) {
1471       addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1472                                         AssociatedNamespaces, AssociatedClasses,
1473                                         GlobalScope);
1474       continue;
1475     }
1476
1477     // [...] In addition, if the argument is the name or address of a
1478     // set of overloaded functions and/or function templates, its
1479     // associated classes and namespaces are the union of those
1480     // associated with each of the members of the set: the namespace
1481     // in which the function or function template is defined and the
1482     // classes and namespaces associated with its (non-dependent)
1483     // parameter types and return type.
1484     DeclRefExpr *DRE = 0;
1485     if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1486       if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1487         DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1488     } else
1489       DRE = dyn_cast<DeclRefExpr>(Arg);
1490     if (!DRE)
1491       continue;
1492
1493     OverloadedFunctionDecl *Ovl 
1494       = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1495     if (!Ovl)
1496       continue;
1497
1498     for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1499                                                 FuncEnd = Ovl->function_end();
1500          Func != FuncEnd; ++Func) {
1501       FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1502       if (!FDecl)
1503         FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
1504
1505       // Add the namespace in which this function was defined. Note
1506       // that, if this is a member function, we do *not* consider the
1507       // enclosing namespace of its class.
1508       DeclContext *Ctx = FDecl->getDeclContext();
1509       if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1510         AssociatedNamespaces.insert(EnclosingNamespace);
1511       else if (Ctx->isTranslationUnit())
1512         GlobalScope = true;
1513
1514       // Add the classes and namespaces associated with the parameter
1515       // types and return type of this function.
1516       addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1517                                         AssociatedNamespaces, AssociatedClasses,
1518                                         GlobalScope);
1519     }
1520   }
1521 }
1522
1523 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1524 /// an acceptable non-member overloaded operator for a call whose
1525 /// arguments have types T1 (and, if non-empty, T2). This routine
1526 /// implements the check in C++ [over.match.oper]p3b2 concerning
1527 /// enumeration types.
1528 static bool 
1529 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1530                                        QualType T1, QualType T2,
1531                                        ASTContext &Context) {
1532   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1533     return true;
1534
1535   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1536     return true;
1537
1538   const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1539   if (Proto->getNumArgs() < 1)
1540     return false;
1541
1542   if (T1->isEnumeralType()) {
1543     QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1544     if (Context.getCanonicalType(T1).getUnqualifiedType()
1545           == Context.getCanonicalType(ArgType).getUnqualifiedType())
1546       return true;
1547   }
1548
1549   if (Proto->getNumArgs() < 2)
1550     return false;
1551
1552   if (!T2.isNull() && T2->isEnumeralType()) {
1553     QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1554     if (Context.getCanonicalType(T2).getUnqualifiedType()
1555           == Context.getCanonicalType(ArgType).getUnqualifiedType())
1556       return true;
1557   }
1558
1559   return false;
1560 }
1561
1562 /// \brief Find the protocol with the given name, if any.
1563 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
1564   Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
1565   return cast_or_null<ObjCProtocolDecl>(D);
1566 }
1567
1568 /// \brief Find the Objective-C implementation with the given name, if
1569 /// any.
1570 ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1571   Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1572   return cast_or_null<ObjCImplementationDecl>(D);
1573 }
1574
1575 /// \brief Find the Objective-C category implementation with the given
1576 /// name, if any.
1577 ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1578   Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1579   return cast_or_null<ObjCCategoryImplDecl>(D);
1580 }
1581
1582 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1583                                         QualType T1, QualType T2, 
1584                                         FunctionSet &Functions) {
1585   // C++ [over.match.oper]p3:
1586   //     -- The set of non-member candidates is the result of the
1587   //        unqualified lookup of operator@ in the context of the
1588   //        expression according to the usual rules for name lookup in
1589   //        unqualified function calls (3.4.2) except that all member
1590   //        functions are ignored. However, if no operand has a class
1591   //        type, only those non-member functions in the lookup set
1592   //        that have a first parameter of type T1 or “reference to
1593   //        (possibly cv-qualified) T1”, when T1 is an enumeration
1594   //        type, or (if there is a right operand) a second parameter
1595   //        of type T2 or “reference to (possibly cv-qualified) T2”,
1596   //        when T2 is an enumeration type, are candidate functions.
1597   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1598   LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1599   
1600   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1601
1602   if (!Operators)
1603     return;
1604
1605   for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1606        Op != OpEnd; ++Op) {
1607     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1608       if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1609         Functions.insert(FD); // FIXME: canonical FD
1610   }
1611 }
1612
1613 void Sema::ArgumentDependentLookup(DeclarationName Name,
1614                                    Expr **Args, unsigned NumArgs,
1615                                    FunctionSet &Functions) {
1616   // Find all of the associated namespaces and classes based on the
1617   // arguments we have.
1618   AssociatedNamespaceSet AssociatedNamespaces;
1619   AssociatedClassSet AssociatedClasses;
1620   bool GlobalScope = false;
1621   FindAssociatedClassesAndNamespaces(Args, NumArgs, 
1622                                      AssociatedNamespaces, AssociatedClasses,
1623                                      GlobalScope);
1624
1625   // C++ [basic.lookup.argdep]p3:
1626   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
1627   //   and let Y be the lookup set produced by argument dependent
1628   //   lookup (defined as follows). If X contains [...] then Y is
1629   //   empty. Otherwise Y is the set of declarations found in the
1630   //   namespaces associated with the argument types as described
1631   //   below. The set of declarations found by the lookup of the name
1632   //   is the union of X and Y.
1633   //
1634   // Here, we compute Y and add its members to the overloaded
1635   // candidate set.
1636   for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1637                                      NSEnd = AssociatedNamespaces.end(); 
1638        NS != NSEnd; ++NS) { 
1639     //   When considering an associated namespace, the lookup is the
1640     //   same as the lookup performed when the associated namespace is
1641     //   used as a qualifier (3.4.3.2) except that:
1642     //
1643     //     -- Any using-directives in the associated namespace are
1644     //        ignored.
1645     //
1646     //     -- FIXME: Any namespace-scope friend functions declared in
1647     //        associated classes are visible within their respective
1648     //        namespaces even if they are not visible during an ordinary
1649     //        lookup (11.4).
1650     DeclContext::lookup_iterator I, E;
1651     for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) {
1652       FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1653       if (!Func)
1654         break;
1655
1656       Functions.insert(Func);
1657     }
1658   }
1659   
1660   if (GlobalScope) {
1661     DeclContext::lookup_iterator I, E;
1662     for (llvm::tie(I, E) 
1663            = Context.getTranslationUnitDecl()->lookup(Context, Name); 
1664          I != E; ++I) {
1665       FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1666       if (!Func)
1667         break;
1668       
1669       Functions.insert(Func);
1670     }
1671   }
1672 }