Some name-lookup-related fixes, from Piotr Rak!

- Changes Lookup*Name functions to return NamedDecls, instead of
Decls. Unfortunately my recent statement that it will simplify lot of
code, was not quite right, but it simplifies some...
- Makes MergeLookupResult SmallPtrSet instead of vector, following
Douglas suggestions.
- Adds %qN format for printing qualified names to Diagnostic.
- Avoids searching for using-directives in Scopes, which are not
DeclScope, during unqualified name lookup.



git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@63739 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Sema/Sema.cpp b/lib/Sema/Sema.cpp
index 6041736..03a6b3c 100644
--- a/lib/Sema/Sema.cpp
+++ b/lib/Sema/Sema.cpp
@@ -36,8 +36,7 @@
     assert(ModLen == 0 && ArgLen == 0 &&
            "Invalid modifier for QualType argument");
     
-  } else {
-    assert(Kind == Diagnostic::ak_declarationname);
+  } else if (Kind == Diagnostic::ak_declarationname) {
    
     DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
     S = N.getAsString();
@@ -49,6 +48,13 @@
     else
       assert(ModLen == 0 && ArgLen == 0 &&
              "Invalid modifier for DeclarationName argument");
+  } else {
+    assert(Kind == Diagnostic::ak_nameddecl);
+    assert(ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0 &&
+           "Invalid modifier for NamedDecl* argument");
+
+    S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString();
+
   }
   Output.append(S.begin(), S.end());
 }
diff --git a/lib/Sema/Sema.h b/lib/Sema/Sema.h
index 9810ba0..b0e24f5 100644
--- a/lib/Sema/Sema.h
+++ b/lib/Sema/Sema.h
@@ -607,7 +607,7 @@
   /// results occurred for a given lookup. 
   ///
   /// Any non-ambiguous lookup can be converted into a single
-  /// (possibly NULL) @c Decl* via a conversion function or the
+  /// (possibly NULL) @c NamedDecl* via a conversion function or the
   /// getAsDecl() method. This conversion permits the common-case
   /// usage in C and Objective-C where name lookup will always return
   /// a single declaration.
@@ -615,7 +615,7 @@
     /// The kind of entity that is actually stored within the
     /// LookupResult object.
     enum {
-      /// First is a single declaration (a Decl*), which may be NULL.
+      /// First is a single declaration (a NamedDecl*), which may be NULL.
       SingleDecl,
 
       /// First is a single declaration (an OverloadedFunctionDecl*).
@@ -643,8 +643,9 @@
     } StoredKind;
 
     /// The first lookup result, whose contents depend on the kind of
-    /// lookup result. This may be a Decl* (if StoredKind ==
-    /// SingleDecl), the opaque pointer from an
+    /// lookup result. This may be a NamedDecl* (if StoredKind ==
+    /// SingleDecl), OverloadedFunctionDecl* (if StoredKind ==
+    /// OverloadedDeclSingleDecl), the opaque pointer from an
     /// IdentifierResolver::iterator (if StoredKind ==
     /// OverloadedDeclFromIdResolver), a DeclContext::lookup_iterator
     /// (if StoredKind == OverloadedDeclFromDeclContext), or a
@@ -721,7 +722,7 @@
       AmbiguousReference
     };
 
-    static LookupResult CreateLookupResult(ASTContext &Context, Decl *D);
+    static LookupResult CreateLookupResult(ASTContext &Context, NamedDecl *D);
 
     static LookupResult CreateLookupResult(ASTContext &Context, 
                                            IdentifierResolver::iterator F, 
@@ -744,7 +745,7 @@
     template <typename Iterator>
     static LookupResult CreateLookupResult(ASTContext &Context,
                                            Iterator B, std::size_t Len) {
-      Decl ** Array = new Decl*[Len];
+      NamedDecl ** Array = new NamedDecl*[Len];
       for (std::size_t Idx = 0; Idx < Len; ++Idx, ++B)
         Array[Idx] = *B;
       LookupResult Result;
@@ -768,9 +769,9 @@
 
     /// @brief Allows conversion of a lookup result into a
     /// declaration, with the same behavior as getAsDecl.
-    operator Decl*() const { return getAsDecl(); }
+    operator NamedDecl*() const { return getAsDecl(); }
 
-    Decl* getAsDecl() const;
+    NamedDecl* getAsDecl() const;
 
     BasePaths *getBasePaths() const;
 
@@ -788,9 +789,9 @@
       mutable uintptr_t Current;
 
     public:
-      typedef Decl *                     value_type;
-      typedef Decl *                     reference;
-      typedef Decl *                     pointer;
+      typedef NamedDecl *                value_type;
+      typedef NamedDecl *                reference;
+      typedef NamedDecl *                pointer;
       typedef std::ptrdiff_t             difference_type;
       typedef std::forward_iterator_tag  iterator_category;
 
diff --git a/lib/Sema/SemaCXXScopeSpec.cpp b/lib/Sema/SemaCXXScopeSpec.cpp
index c77325f..8a257f7 100644
--- a/lib/Sema/SemaCXXScopeSpec.cpp
+++ b/lib/Sema/SemaCXXScopeSpec.cpp
@@ -36,7 +36,7 @@
                                                     SourceLocation IdLoc,

                                                     SourceLocation CCLoc,

                                                     IdentifierInfo &II) {

-  Decl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName);

+  NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName);

 

   if (SD) {

     if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {

diff --git a/lib/Sema/SemaDecl.cpp b/lib/Sema/SemaDecl.cpp
index fbf4be7..a3ca97b 100644
--- a/lib/Sema/SemaDecl.cpp
+++ b/lib/Sema/SemaDecl.cpp
@@ -207,7 +207,7 @@
 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
   // The third "scope" argument is 0 since we aren't enabling lazy built-in
   // creation from this context.
-  Decl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
+  NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
   
   return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
 }
@@ -249,7 +249,7 @@
     return;
   
   IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
-  Decl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
+  NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
   TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
   Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
 }
@@ -741,8 +741,8 @@
                                FEnd = AnonRecord->field_end();
        F != FEnd; ++F) {
     if ((*F)->getDeclName()) {
-      Decl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
-                                           LookupOrdinaryName, true);
+      NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
+                                                LookupOrdinaryName, true);
       if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
         // C++ [class.union]p2:
         //   The names of the members of an anonymous union shall be
@@ -1174,7 +1174,7 @@
     S = S->getParent();
   
   DeclContext *DC;
-  Decl *PrevDecl;
+  NamedDecl *PrevDecl;
   NamedDecl *New;
   bool InvalidDecl = false;
  
@@ -2523,7 +2523,7 @@
   // among each other.  Here they can only shadow globals, which is ok.
   IdentifierInfo *II = D.getIdentifier();
   if (II) {
-    if (Decl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
+    if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
       if (PrevDecl->isTemplateParameter()) {
         // Maybe we will complain about the shadowed template parameter.
         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
@@ -2798,7 +2798,7 @@
   
   DeclContext *SearchDC = CurContext;
   DeclContext *DC = CurContext;
-  Decl *PrevDecl = 0;
+  NamedDecl *PrevDecl = 0;
 
   bool Invalid = false;
 
@@ -2843,7 +2843,7 @@
       Invalid = true;
     }
     else
-      PrevDecl = dyn_cast_or_null<NamedDecl>(static_cast<Decl*>(R));
+      PrevDecl = R;
 
     if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
       // FIXME: This makes sure that we ignore the contexts associated
@@ -3217,7 +3217,7 @@
                               DeclSpec::SCS_mutable);
 
   if (II) {
-    Decl *PrevDecl = LookupName(S, II, LookupMemberName, true);
+    NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
     if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
         && !isa<TagDecl>(PrevDecl)) {
       Diag(Loc, diag::err_duplicate_member) << II;
@@ -3309,7 +3309,7 @@
                                              (Expr *)BitfieldWidth);
   
   if (II) {
-    Decl *PrevDecl = LookupName(S, II, LookupMemberName, true);
+    NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
     if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
         && !isa<TagDecl>(PrevDecl)) {
       Diag(Loc, diag::err_duplicate_member) << II;
@@ -3485,7 +3485,7 @@
   
   // Verify that there isn't already something declared with this name in this
   // scope.
-  Decl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
+  NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
   if (PrevDecl && PrevDecl->isTemplateParameter()) {
     // Maybe we will complain about the shadowed template parameter.
     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
diff --git a/lib/Sema/SemaDeclAttr.cpp b/lib/Sema/SemaDeclAttr.cpp
index 33985ee..231efc7 100644
--- a/lib/Sema/SemaDeclAttr.cpp
+++ b/lib/Sema/SemaDeclAttr.cpp
@@ -865,8 +865,8 @@
   }
   
   // Look up the function
-  Decl *CleanupDecl = S.LookupName(S.TUScope, Attr.getParameterName(), 
-                                   Sema::LookupOrdinaryName);
+  NamedDecl *CleanupDecl = S.LookupName(S.TUScope, Attr.getParameterName(),
+                                        Sema::LookupOrdinaryName);
   if (!CleanupDecl) {
     S.Diag(Attr.getLoc(), diag::err_attribute_cleanup_arg_not_found) << 
       Attr.getParameterName();
diff --git a/lib/Sema/SemaDeclCXX.cpp b/lib/Sema/SemaDeclCXX.cpp
index 2175ad3..5595215 100644
--- a/lib/Sema/SemaDeclCXX.cpp
+++ b/lib/Sema/SemaDeclCXX.cpp
@@ -1375,8 +1375,8 @@
     // original-namespace-definition is the name of the namespace. Subsequently
     // in that declarative region, it is treated as an original-namespace-name.
 
-    Decl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
-                                true);
+    NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
+                                     true);
     
     if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
       // This is an extended namespace definition.
@@ -1444,7 +1444,7 @@
     DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
     return 0;
   }
-  if (Decl *NS = R) {
+  if (NamedDecl *NS = R) {
     assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
     // C++ [namespace.udir]p1:
     //   A using-directive specifies that the names in the nominated
@@ -2230,7 +2230,7 @@
   // FIXME: Need to check for abstract classes.
 
   IdentifierInfo *II = D.getIdentifier();
-  if (Decl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
+  if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
     // The scope should be freshly made just for us. There is just no way
     // it contains any previous declaration.
     assert(!S->isDeclScope(PrevDecl));
diff --git a/lib/Sema/SemaDeclObjC.cpp b/lib/Sema/SemaDeclObjC.cpp
index 7c76f16..1e87a6f 100644
--- a/lib/Sema/SemaDeclObjC.cpp
+++ b/lib/Sema/SemaDeclObjC.cpp
@@ -64,7 +64,7 @@
   assert(ClassName && "Missing class identifier");
   
   // Check for another declaration kind with the same name.
-  Decl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
+  NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
   if (PrevDecl && PrevDecl->isTemplateParameter()) {
     // Maybe we will complain about the shadowed template parameter.
     DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl);
@@ -164,7 +164,7 @@
                                            IdentifierInfo *ClassName,
                                            SourceLocation ClassLocation) {
   // Look for previous declaration of alias name
-  Decl *ADecl = LookupName(TUScope, AliasName, LookupOrdinaryName);
+  NamedDecl *ADecl = LookupName(TUScope, AliasName, LookupOrdinaryName);
   if (ADecl) {
     if (isa<ObjCCompatibleAliasDecl>(ADecl))
       Diag(AliasLocation, diag::warn_previous_alias_decl);
@@ -174,7 +174,7 @@
     return 0;
   }
   // Check for class declaration
-  Decl *CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName);
+  NamedDecl *CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName);
   if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
     QualType T = TDecl->getUnderlyingType();
     if (T->isObjCInterfaceType()) {
@@ -550,7 +550,7 @@
                       SourceLocation SuperClassLoc) {
   ObjCInterfaceDecl* IDecl = 0;
   // Check for another declaration kind with the same name.
-  Decl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
+  NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
@@ -924,7 +924,7 @@
   
   for (unsigned i = 0; i != NumElts; ++i) {
     // Check for another declaration kind with the same name.
-    Decl *PrevDecl = LookupName(TUScope, IdentList[i], LookupOrdinaryName);
+    NamedDecl *PrevDecl = LookupName(TUScope, IdentList[i], LookupOrdinaryName);
     if (PrevDecl && PrevDecl->isTemplateParameter()) {
       // Maybe we will complain about the shadowed template parameter.
       DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp
index d408def..0c755f6 100644
--- a/lib/Sema/SemaExpr.cpp
+++ b/lib/Sema/SemaExpr.cpp
@@ -563,7 +563,7 @@
                                                           Loc));
   }
 
-  Decl *D = 0;
+  NamedDecl *D = 0;
   if (Lookup.isAmbiguous()) {
     DiagnoseAmbiguousLookup(Lookup, Name, Loc,
                             SS && SS->isSet() ? SS->getRange()
@@ -627,9 +627,8 @@
   // implicit member ref, because we want a pointer to the member in general,
   // not any specific instance's member.
   if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
-    NamedDecl *ND = dyn_cast<NamedDecl>(D);
     DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
-    if (ND && isa<CXXRecordDecl>(DC)) {
+    if (D && isa<CXXRecordDecl>(DC)) {
       QualType DType;
       if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
         DType = FD->getType().getNonReferenceType();
@@ -653,7 +652,7 @@
             }
           }
         }
-        return Owned(BuildDeclRefExpr(ND, DType, Loc, Dependent, Dependent,SS));
+        return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
       }
     }
   }
@@ -714,7 +713,7 @@
           // Build the implicit member access expression.
           Expr *This = new (Context) CXXThisExpr(SourceLocation(),
                                        MD->getThisType(Context));
-          return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
+          return Owned(new (Context) MemberExpr(This, true, D,
                                       SourceLocation(), MemberType));
         }
       }
@@ -1559,7 +1558,7 @@
       = LookupQualifiedName(RDecl, DeclarationName(&Member), 
                             LookupMemberName, false);
 
-    Decl *MemberDecl = 0;
+    NamedDecl *MemberDecl = 0;
     if (!Result)
       return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
                << &Member << BaseExpr->getSourceRange());
diff --git a/lib/Sema/SemaExprObjC.cpp b/lib/Sema/SemaExprObjC.cpp
index f893f1e..983231c 100644
--- a/lib/Sema/SemaExprObjC.cpp
+++ b/lib/Sema/SemaExprObjC.cpp
@@ -52,7 +52,7 @@
     // Initialize the constant string interface lazily. This assumes
     // the NSConstantString interface is seen in this translation unit.
     IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
-    Decl *IFace = LookupName(TUScope, NSIdent, LookupOrdinaryName);
+    NamedDecl *IFace = LookupName(TUScope, NSIdent, LookupOrdinaryName);
     ObjCInterfaceDecl *strIFace = dyn_cast_or_null<ObjCInterfaceDecl>(IFace);
     if (strIFace)
       Context.setObjCConstantStringInterface(strIFace);
@@ -209,7 +209,7 @@
     } else {
       // 'super' has been used outside a method context. If a variable named
       // 'super' has been declared, redirect. If not, produce a diagnostic.
-      Decl *SuperDecl = LookupName(S, receiverName, LookupOrdinaryName);
+      NamedDecl *SuperDecl = LookupName(S, receiverName, LookupOrdinaryName);
       ValueDecl *VD = dyn_cast_or_null<ValueDecl>(SuperDecl);
       if (VD) {
         ExprResult ReceiverExpr = new DeclRefExpr(VD, VD->getType(), 
@@ -234,7 +234,7 @@
   //
   // If necessary, the following lookup could move to getObjCInterfaceDecl().
   if (!ClassDecl) {
-    Decl *IDecl = LookupName(TUScope, receiverName, LookupOrdinaryName);
+    NamedDecl *IDecl = LookupName(TUScope, receiverName, LookupOrdinaryName);
     if (TypedefDecl *OCTD = dyn_cast_or_null<TypedefDecl>(IDecl)) {
       const ObjCInterfaceType *OCIT;
       OCIT = OCTD->getUnderlyingType()->getAsObjCInterfaceType();
diff --git a/lib/Sema/SemaLookup.cpp b/lib/Sema/SemaLookup.cpp
index 4cdd4ab..65dd949 100644
--- a/lib/Sema/SemaLookup.cpp
+++ b/lib/Sema/SemaLookup.cpp
@@ -114,7 +114,7 @@
 /// ambiguity and overloaded functions without needing to create a
 /// Decl node.
 template<typename DeclIterator>
-static Decl *
+static NamedDecl *
 MaybeConstructOverloadSet(ASTContext &Context, 
                           DeclIterator I, DeclIterator IEnd) {
   assert(I != IEnd && "Iterator range cannot be empty");
@@ -151,9 +151,9 @@
 static Sema::LookupResult
 MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
   typedef Sema::LookupResult LResult;
-  typedef llvm::SmallVector<NamedDecl*, 3> DeclsVecTy;
+  typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
 
-  DeclsVecTy FoundDecls;
+  DeclsSetTy FoundDecls;
   OverloadedFunctionDecl *FoundOverloaded = 0;
 
   LookupResultsTy::iterator I = Results.begin(), End = Results.end();
@@ -171,58 +171,27 @@
       break;
 
     case LResult::Found:
-      FoundDecls.push_back(cast<NamedDecl>(I->getAsDecl()));
+      FoundDecls.insert(I->getAsDecl());
       break;
 
     case LResult::AmbiguousBaseSubobjectTypes:
     case LResult::AmbiguousBaseSubobjects: {
-      LResult Ambig = *I;
-      // Free rest of OverloadedFunctionDecl, and other BasePaths
-      // stored in LookupResults.
-#if 0
-     // FIXME:
-     // It should not happen, when we look start in each DeclContext only once.
-     // See FIXME in CppLookupName.
-     assert(Results.size() == 1 && "Multiple LookupResults should be not case "
-            "here, since using-directives can't occur at class scope.");
-#else
-      if (FoundOverloaded)
-        FoundOverloaded->Destroy(Context);
-
-      for (++I; I != End; ++I) {
-        if (I->getKind() == LResult::FoundOverloaded)
-          cast<OverloadedFunctionDecl>(I->getAsDecl())->Destroy(Context);
-        else if (BasePaths *Paths = I->getBasePaths())
-          delete Paths;
-        assert(I->getKind() != LResult::AmbiguousReference &&
-               "Shouldn't get ambiguous reference here.");
-      }
-#endif
-      return Ambig;
+      assert(Results.size() == 1 && "Multiple LookupResults should be not case "
+             "here, since using-directives can't occur at class scope.");
+      return *I;
     }
 
     case LResult::FoundOverloaded:
-      if (FoundOverloaded) {
+      if (FoundOverloaded)
         // We have one spare OverloadedFunctionDecl already, so we store
         // its function decls.
-#if 0
-        FIXME: As soon as, stop call MaybeConstructOverloadSet here,
-          which requires iterator::reference of type NamedDecl*, FoundDecls
-          can be SmallVector<Decl*, >
-        or when Lookup*Name() starts return NamedDecl's* instead of Decl's
-
-        this will work:
-        std::copy(I->begin(), I->end(), std::back_inserter(FoundDecls));
-#else
-        Sema::LookupResult::iterator OI = I->begin(), OEnd = I->end();
-        for (; OI != OEnd; ++OI)
-          FoundDecls.push_back(cast<NamedDecl>(*OI));
-#endif
-      } else {
+        for (LResult::iterator
+             FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
+          FoundDecls.insert(*FI);
+      else
         // First time we found OverloadedFunctionDecl, we want to conserve
         // it, and possibly add other found Decls later.
         FoundOverloaded = cast<OverloadedFunctionDecl>(I->getAsDecl());
-      }
       break;
     }
   }
@@ -246,35 +215,33 @@
   //
   // FIXME: At this point happens too, because we are doing redundant lookups.
   //
-  DeclsVecTy::iterator DI = FoundDecls.begin(), DEnd = FoundDecls.end();
-  // FIXME: Using SmallPtrSet instead would be better, once OverloadedFunctionDecl
-  // dies.
-  std::sort(DI, DEnd);
-  DEnd = std::unique(DI, DEnd);
+  DeclsSetTy::iterator DI = FoundDecls.begin(), DEnd = FoundDecls.end();
 
   if (FoundOverloaded) {
     // We found overloaded functions result. We want to add any other
     // found decls, that are not already in FoundOverloaded, and are functions
     // or methods.
     OverloadedFunctionDecl::function_iterator 
-      FBegin = FoundOverloaded->function_begin(),
+      FI = FoundOverloaded->function_begin(),
       FEnd = FoundOverloaded->function_end();
-    // FIXME: This is O(n^2)!
-    for (; DI < DEnd; ++DI) {
-      FunctionDecl *Fun = dyn_cast<FunctionDecl>(*DI);
-      if (Fun && (std::find(FBegin, FEnd, Fun) != FEnd)) { /* Skip.*/  }
-      else DEnd = std::remove(DI, DEnd, *DI);
+
+    for (; FI < FEnd; ++FI) {
+      if (FoundDecls.count(*FI))
+        FoundDecls.erase(*FI);
     }
 
-    for (DI = FoundDecls.begin(); DI != DEnd; ++DI)
-      FoundOverloaded->addOverload(cast<FunctionDecl>(*DI));
+    DI = FoundDecls.begin(), DEnd = FoundDecls.end();
+
+    for (; DI != DEnd; ++DI)
+      if (FunctionDecl *Fun = dyn_cast<FunctionDecl>(*DI))
+        FoundOverloaded->addOverload(Fun);
 
     return LResult::CreateLookupResult(Context, FoundOverloaded);
-  } else if (std::size_t FoundLen = std::distance(FoundDecls.begin(), DEnd)) {
+  } else if (std::size_t FoundLen = FoundDecls.size()) {
     // We might found multiple TagDecls pointing at same definition.
     if (TagDecl *R = dyn_cast<TagDecl>(*FoundDecls.begin())) {
       TagDecl *Canonical = Context.getCanonicalDecl(R);
-      DeclsVecTy::iterator RI = FoundDecls.begin(), REnd = DEnd;
+      DeclsSetTy::iterator RI = FoundDecls.begin(), REnd = DEnd;
       for (;;) {
         ++RI;
         if (RI == REnd) {
@@ -288,12 +255,14 @@
     }
 
     // We might find FunctionDecls in two (or more) distinct DeclContexts.
-    // 3.4.1.p1 ... Name lookup may associate more than one  declaration with
+    //
+    // C++ [basic.lookup].p1:
+    // ... Name lookup may associate more than one declaration with
     // a name if it finds the name to be a function name; the declarations
     // are said to form a set of overloaded functions (13.1).
     // Overload resolution (13.3) takes place after name lookup has succeeded.
-
-    Decl *D = MaybeConstructOverloadSet(Context, DI, DEnd);
+    //
+    NamedDecl *D = MaybeConstructOverloadSet(Context, DI, DEnd);
     if ((FoundLen == 1) || isa<OverloadedFunctionDecl>(D))
       return LResult::CreateLookupResult(Context, D);
 
@@ -337,38 +306,8 @@
   return IDNS;
 }
 
-// Return qualified name for Decl D, like A::B::i, for i being member of
-// namespace A::B.
-std::string
-getQualifiedName(Decl *D) {
-  std::vector<std::string> Names;
-  std::string QualName;
-  DeclContext *Ctx = D->getDeclContext();
-
-  if (Ctx->isFunctionOrMethod())
-    return cast<NamedDecl>(D)->getNameAsString();
-
-  while (Ctx) {
-    if (Ctx->isFunctionOrMethod()) {
-      // FIXME: That probably is happend, because D was member of local
-      // scope class/struct/union. How do we handle this case?
-      break;
-    }
-    if (NamedDecl *ND = dyn_cast<NamedDecl>(Ctx)) {
-      Names.push_back(ND->getNameAsString());
-    } else {
-      break;
-    }
-    Ctx = Ctx->getParent();
-  }
-  for (std::vector<std::string>::reverse_iterator I= Names.rbegin(), End =Names.rend(); I!=End; ++I)
-    QualName += *I + "::";
-  QualName += cast<NamedDecl>(D)->getNameAsString();
-  return QualName;
-}
-
 Sema::LookupResult
-Sema::LookupResult::CreateLookupResult(ASTContext &Context, Decl *D) {
+Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
   LookupResult Result;
   Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
     OverloadedDeclSingleDecl : SingleDecl;
@@ -462,10 +401,10 @@
 /// solution, since it causes the OverloadedFunctionDecl to be
 /// leaked. FIXME: Eventually, there will be a better way to iterate
 /// over the set of overloaded functions returned by name lookup.
-Decl *Sema::LookupResult::getAsDecl() const {
+NamedDecl *Sema::LookupResult::getAsDecl() const {
   switch (StoredKind) {
   case SingleDecl:
-    return reinterpret_cast<Decl *>(First);
+    return reinterpret_cast<NamedDecl *>(First);
 
   case OverloadedDeclFromIdResolver:
     return MaybeConstructOverloadSet(*Context,
@@ -502,10 +441,10 @@
 Sema::LookupResult::iterator::operator*() const {
   switch (Result->StoredKind) {
   case SingleDecl:
-    return reinterpret_cast<Decl*>(Current);
+    return reinterpret_cast<NamedDecl*>(Current);
 
   case OverloadedDeclSingleDecl:
-    return *reinterpret_cast<Decl**>(Current);
+    return *reinterpret_cast<NamedDecl**>(Current);
 
   case OverloadedDeclFromIdResolver:
     return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
@@ -525,11 +464,11 @@
 Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
   switch (Result->StoredKind) {
   case SingleDecl:
-    Current = reinterpret_cast<uintptr_t>((Decl*)0);
+    Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
     break;
 
   case OverloadedDeclSingleDecl: {
-    Decl ** I = reinterpret_cast<Decl**>(Current);
+    NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
     ++I;
     Current = reinterpret_cast<uintptr_t>(I);
     break;
@@ -590,7 +529,7 @@
   assert(getLangOptions().CPlusPlus &&
          "Can perform only C++ lookup");
   unsigned IDNS 
-      = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
+    = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
   Scope *Initial = S;
   IdentifierResolver::iterator 
     I = IdResolver.begin(Name),
@@ -613,7 +552,7 @@
   //     ++i; // finds local 'i', A::i appears at global scope
   //   }
   // }
-  // 
+  //
   for (; S && isFunctionLocalScope(S); S = S->getParent()) {
     // Check whether the IdResolver has anything in this scope.
     for (; I != IEnd && S->isDeclScope(*I); ++I) {
@@ -658,7 +597,8 @@
   // DeclContext, so we don't build it for each lookup!
   UsingDirectivesTy UDirs;
   for (Scope *SC = Initial; SC; SC = SC->getParent())
-     AddScopeUsingDirectives(SC, UDirs);
+    if (SC->getFlags() & Scope::DeclScope)
+      AddScopeUsingDirectives(SC, UDirs);
 
   // Sort heapified UsingDirectiveDecls.
   std::sort_heap(UDirs.begin(), UDirs.end());
@@ -1131,14 +1071,13 @@
 
     Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
 
-    Decl **DI = reinterpret_cast<Decl **>(Result.First),
-       **DEnd = reinterpret_cast<Decl **>(Result.Last);
+    NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
+       **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
 
     for (; DI != DEnd; ++DI)
-      Diag((*DI)->getLocation(), diag::note_ambiguous_candidate)
-        <<  getQualifiedName(*DI);
+      Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
 
-    delete[] reinterpret_cast<Decl **>(Result.First);
+    delete[] reinterpret_cast<NamedDecl **>(Result.First);
 
     return true;
   }
diff --git a/lib/Sema/SemaTemplate.cpp b/lib/Sema/SemaTemplate.cpp
index f1b8617..c46731e 100644
--- a/lib/Sema/SemaTemplate.cpp
+++ b/lib/Sema/SemaTemplate.cpp
@@ -32,7 +32,7 @@
       return 0;
     DC = static_cast<DeclContext*>(SS->getScopeRep());
   }
-  Decl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
+  NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
 
   if (IIDecl) {
     // FIXME: We need to represent templates via some kind of
@@ -94,7 +94,7 @@
   bool Invalid = false;
 
   if (ParamName) {
-    Decl *PrevDecl = LookupName(S, ParamName, LookupTagName);
+    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
     if (PrevDecl && PrevDecl->isTemplateParameter())
       Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
 							   PrevDecl);
@@ -130,7 +130,7 @@
 
   IdentifierInfo *ParamName = D.getIdentifier();
   if (ParamName) {
-    Decl *PrevDecl = LookupName(S, ParamName, LookupTagName);
+    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
     if (PrevDecl && PrevDecl->isTemplateParameter())
       Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
 							   PrevDecl);