Home | History | Annotate | Download | only in Sema
      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 "clang/Sema/Lookup.h"
     15 #include "clang/AST/ASTContext.h"
     16 #include "clang/AST/CXXInheritance.h"
     17 #include "clang/AST/Decl.h"
     18 #include "clang/AST/DeclCXX.h"
     19 #include "clang/AST/DeclLookups.h"
     20 #include "clang/AST/DeclObjC.h"
     21 #include "clang/AST/DeclTemplate.h"
     22 #include "clang/AST/Expr.h"
     23 #include "clang/AST/ExprCXX.h"
     24 #include "clang/Basic/Builtins.h"
     25 #include "clang/Basic/LangOptions.h"
     26 #include "clang/Sema/DeclSpec.h"
     27 #include "clang/Sema/ExternalSemaSource.h"
     28 #include "clang/Sema/Overload.h"
     29 #include "clang/Sema/Scope.h"
     30 #include "clang/Sema/ScopeInfo.h"
     31 #include "clang/Sema/Sema.h"
     32 #include "clang/Sema/SemaInternal.h"
     33 #include "clang/Sema/TemplateDeduction.h"
     34 #include "clang/Sema/TypoCorrection.h"
     35 #include "llvm/ADT/STLExtras.h"
     36 #include "llvm/ADT/SetVector.h"
     37 #include "llvm/ADT/SmallPtrSet.h"
     38 #include "llvm/ADT/StringMap.h"
     39 #include "llvm/ADT/TinyPtrVector.h"
     40 #include "llvm/ADT/edit_distance.h"
     41 #include "llvm/Support/ErrorHandling.h"
     42 #include <algorithm>
     43 #include <iterator>
     44 #include <limits>
     45 #include <list>
     46 #include <map>
     47 #include <set>
     48 #include <utility>
     49 #include <vector>
     50 
     51 using namespace clang;
     52 using namespace sema;
     53 
     54 namespace {
     55   class UnqualUsingEntry {
     56     const DeclContext *Nominated;
     57     const DeclContext *CommonAncestor;
     58 
     59   public:
     60     UnqualUsingEntry(const DeclContext *Nominated,
     61                      const DeclContext *CommonAncestor)
     62       : Nominated(Nominated), CommonAncestor(CommonAncestor) {
     63     }
     64 
     65     const DeclContext *getCommonAncestor() const {
     66       return CommonAncestor;
     67     }
     68 
     69     const DeclContext *getNominatedNamespace() const {
     70       return Nominated;
     71     }
     72 
     73     // Sort by the pointer value of the common ancestor.
     74     struct Comparator {
     75       bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
     76         return L.getCommonAncestor() < R.getCommonAncestor();
     77       }
     78 
     79       bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
     80         return E.getCommonAncestor() < DC;
     81       }
     82 
     83       bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
     84         return DC < E.getCommonAncestor();
     85       }
     86     };
     87   };
     88 
     89   /// A collection of using directives, as used by C++ unqualified
     90   /// lookup.
     91   class UnqualUsingDirectiveSet {
     92     typedef SmallVector<UnqualUsingEntry, 8> ListTy;
     93 
     94     ListTy list;
     95     llvm::SmallPtrSet<DeclContext*, 8> visited;
     96 
     97   public:
     98     UnqualUsingDirectiveSet() {}
     99 
    100     void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
    101       // C++ [namespace.udir]p1:
    102       //   During unqualified name lookup, the names appear as if they
    103       //   were declared in the nearest enclosing namespace which contains
    104       //   both the using-directive and the nominated namespace.
    105       DeclContext *InnermostFileDC
    106         = static_cast<DeclContext*>(InnermostFileScope->getEntity());
    107       assert(InnermostFileDC && InnermostFileDC->isFileContext());
    108 
    109       for (; S; S = S->getParent()) {
    110         // C++ [namespace.udir]p1:
    111         //   A using-directive shall not appear in class scope, but may
    112         //   appear in namespace scope or in block scope.
    113         DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
    114         if (Ctx && Ctx->isFileContext()) {
    115           visit(Ctx, Ctx);
    116         } else if (!Ctx || Ctx->isFunctionOrMethod()) {
    117           Scope::udir_iterator I = S->using_directives_begin(),
    118                              End = S->using_directives_end();
    119           for (; I != End; ++I)
    120             visit(*I, InnermostFileDC);
    121         }
    122       }
    123     }
    124 
    125     // Visits a context and collect all of its using directives
    126     // recursively.  Treats all using directives as if they were
    127     // declared in the context.
    128     //
    129     // A given context is only every visited once, so it is important
    130     // that contexts be visited from the inside out in order to get
    131     // the effective DCs right.
    132     void visit(DeclContext *DC, DeclContext *EffectiveDC) {
    133       if (!visited.insert(DC))
    134         return;
    135 
    136       addUsingDirectives(DC, EffectiveDC);
    137     }
    138 
    139     // Visits a using directive and collects all of its using
    140     // directives recursively.  Treats all using directives as if they
    141     // were declared in the effective DC.
    142     void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
    143       DeclContext *NS = UD->getNominatedNamespace();
    144       if (!visited.insert(NS))
    145         return;
    146 
    147       addUsingDirective(UD, EffectiveDC);
    148       addUsingDirectives(NS, EffectiveDC);
    149     }
    150 
    151     // Adds all the using directives in a context (and those nominated
    152     // by its using directives, transitively) as if they appeared in
    153     // the given effective context.
    154     void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
    155       SmallVector<DeclContext*,4> queue;
    156       while (true) {
    157         DeclContext::udir_iterator I, End;
    158         for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
    159           UsingDirectiveDecl *UD = *I;
    160           DeclContext *NS = UD->getNominatedNamespace();
    161           if (visited.insert(NS)) {
    162             addUsingDirective(UD, EffectiveDC);
    163             queue.push_back(NS);
    164           }
    165         }
    166 
    167         if (queue.empty())
    168           return;
    169 
    170         DC = queue.back();
    171         queue.pop_back();
    172       }
    173     }
    174 
    175     // Add a using directive as if it had been declared in the given
    176     // context.  This helps implement C++ [namespace.udir]p3:
    177     //   The using-directive is transitive: if a scope contains a
    178     //   using-directive that nominates a second namespace that itself
    179     //   contains using-directives, the effect is as if the
    180     //   using-directives from the second namespace also appeared in
    181     //   the first.
    182     void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
    183       // Find the common ancestor between the effective context and
    184       // the nominated namespace.
    185       DeclContext *Common = UD->getNominatedNamespace();
    186       while (!Common->Encloses(EffectiveDC))
    187         Common = Common->getParent();
    188       Common = Common->getPrimaryContext();
    189 
    190       list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
    191     }
    192 
    193     void done() {
    194       std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
    195     }
    196 
    197     typedef ListTy::const_iterator const_iterator;
    198 
    199     const_iterator begin() const { return list.begin(); }
    200     const_iterator end() const { return list.end(); }
    201 
    202     std::pair<const_iterator,const_iterator>
    203     getNamespacesFor(DeclContext *DC) const {
    204       return std::equal_range(begin(), end(), DC->getPrimaryContext(),
    205                               UnqualUsingEntry::Comparator());
    206     }
    207   };
    208 }
    209 
    210 // Retrieve the set of identifier namespaces that correspond to a
    211 // specific kind of name lookup.
    212 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
    213                                bool CPlusPlus,
    214                                bool Redeclaration) {
    215   unsigned IDNS = 0;
    216   switch (NameKind) {
    217   case Sema::LookupObjCImplicitSelfParam:
    218   case Sema::LookupOrdinaryName:
    219   case Sema::LookupRedeclarationWithLinkage:
    220     IDNS = Decl::IDNS_Ordinary;
    221     if (CPlusPlus) {
    222       IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
    223       if (Redeclaration)
    224         IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
    225     }
    226     break;
    227 
    228   case Sema::LookupOperatorName:
    229     // Operator lookup is its own crazy thing;  it is not the same
    230     // as (e.g.) looking up an operator name for redeclaration.
    231     assert(!Redeclaration && "cannot do redeclaration operator lookup");
    232     IDNS = Decl::IDNS_NonMemberOperator;
    233     break;
    234 
    235   case Sema::LookupTagName:
    236     if (CPlusPlus) {
    237       IDNS = Decl::IDNS_Type;
    238 
    239       // When looking for a redeclaration of a tag name, we add:
    240       // 1) TagFriend to find undeclared friend decls
    241       // 2) Namespace because they can't "overload" with tag decls.
    242       // 3) Tag because it includes class templates, which can't
    243       //    "overload" with tag decls.
    244       if (Redeclaration)
    245         IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
    246     } else {
    247       IDNS = Decl::IDNS_Tag;
    248     }
    249     break;
    250   case Sema::LookupLabel:
    251     IDNS = Decl::IDNS_Label;
    252     break;
    253 
    254   case Sema::LookupMemberName:
    255     IDNS = Decl::IDNS_Member;
    256     if (CPlusPlus)
    257       IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
    258     break;
    259 
    260   case Sema::LookupNestedNameSpecifierName:
    261     IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
    262     break;
    263 
    264   case Sema::LookupNamespaceName:
    265     IDNS = Decl::IDNS_Namespace;
    266     break;
    267 
    268   case Sema::LookupUsingDeclName:
    269     IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
    270          | Decl::IDNS_Member | Decl::IDNS_Using;
    271     break;
    272 
    273   case Sema::LookupObjCProtocolName:
    274     IDNS = Decl::IDNS_ObjCProtocol;
    275     break;
    276 
    277   case Sema::LookupAnyName:
    278     IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
    279       | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
    280       | Decl::IDNS_Type;
    281     break;
    282   }
    283   return IDNS;
    284 }
    285 
    286 void LookupResult::configure() {
    287   IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
    288                  isForRedeclaration());
    289 
    290   // If we're looking for one of the allocation or deallocation
    291   // operators, make sure that the implicitly-declared new and delete
    292   // operators can be found.
    293   if (!isForRedeclaration()) {
    294     switch (NameInfo.getName().getCXXOverloadedOperator()) {
    295     case OO_New:
    296     case OO_Delete:
    297     case OO_Array_New:
    298     case OO_Array_Delete:
    299       SemaRef.DeclareGlobalNewDelete();
    300       break;
    301 
    302     default:
    303       break;
    304     }
    305   }
    306 }
    307 
    308 void LookupResult::sanityImpl() const {
    309   // Note that this function is never called by NDEBUG builds. See
    310   // LookupResult::sanity().
    311   assert(ResultKind != NotFound || Decls.size() == 0);
    312   assert(ResultKind != Found || Decls.size() == 1);
    313   assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
    314          (Decls.size() == 1 &&
    315           isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
    316   assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
    317   assert(ResultKind != Ambiguous || Decls.size() > 1 ||
    318          (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
    319                                 Ambiguity == AmbiguousBaseSubobjectTypes)));
    320   assert((Paths != NULL) == (ResultKind == Ambiguous &&
    321                              (Ambiguity == AmbiguousBaseSubobjectTypes ||
    322                               Ambiguity == AmbiguousBaseSubobjects)));
    323 }
    324 
    325 // Necessary because CXXBasePaths is not complete in Sema.h
    326 void LookupResult::deletePaths(CXXBasePaths *Paths) {
    327   delete Paths;
    328 }
    329 
    330 static NamedDecl *getVisibleDecl(NamedDecl *D);
    331 
    332 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
    333   return getVisibleDecl(D);
    334 }
    335 
    336 /// Resolves the result kind of this lookup.
    337 void LookupResult::resolveKind() {
    338   unsigned N = Decls.size();
    339 
    340   // Fast case: no possible ambiguity.
    341   if (N == 0) {
    342     assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
    343     return;
    344   }
    345 
    346   // If there's a single decl, we need to examine it to decide what
    347   // kind of lookup this is.
    348   if (N == 1) {
    349     NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
    350     if (isa<FunctionTemplateDecl>(D))
    351       ResultKind = FoundOverloaded;
    352     else if (isa<UnresolvedUsingValueDecl>(D))
    353       ResultKind = FoundUnresolvedValue;
    354     return;
    355   }
    356 
    357   // Don't do any extra resolution if we've already resolved as ambiguous.
    358   if (ResultKind == Ambiguous) return;
    359 
    360   llvm::SmallPtrSet<NamedDecl*, 16> Unique;
    361   llvm::SmallPtrSet<QualType, 16> UniqueTypes;
    362 
    363   bool Ambiguous = false;
    364   bool HasTag = false, HasFunction = false, HasNonFunction = false;
    365   bool HasFunctionTemplate = false, HasUnresolved = false;
    366 
    367   unsigned UniqueTagIndex = 0;
    368 
    369   unsigned I = 0;
    370   while (I < N) {
    371     NamedDecl *D = Decls[I]->getUnderlyingDecl();
    372     D = cast<NamedDecl>(D->getCanonicalDecl());
    373 
    374     // Ignore an invalid declaration unless it's the only one left.
    375     if (D->isInvalidDecl() && I < N-1) {
    376       Decls[I] = Decls[--N];
    377       continue;
    378     }
    379 
    380     // Redeclarations of types via typedef can occur both within a scope
    381     // and, through using declarations and directives, across scopes. There is
    382     // no ambiguity if they all refer to the same type, so unique based on the
    383     // canonical type.
    384     if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
    385       if (!TD->getDeclContext()->isRecord()) {
    386         QualType T = SemaRef.Context.getTypeDeclType(TD);
    387         if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
    388           // The type is not unique; pull something off the back and continue
    389           // at this index.
    390           Decls[I] = Decls[--N];
    391           continue;
    392         }
    393       }
    394     }
    395 
    396     if (!Unique.insert(D)) {
    397       // If it's not unique, pull something off the back (and
    398       // continue at this index).
    399       Decls[I] = Decls[--N];
    400       continue;
    401     }
    402 
    403     // Otherwise, do some decl type analysis and then continue.
    404 
    405     if (isa<UnresolvedUsingValueDecl>(D)) {
    406       HasUnresolved = true;
    407     } else if (isa<TagDecl>(D)) {
    408       if (HasTag)
    409         Ambiguous = true;
    410       UniqueTagIndex = I;
    411       HasTag = true;
    412     } else if (isa<FunctionTemplateDecl>(D)) {
    413       HasFunction = true;
    414       HasFunctionTemplate = true;
    415     } else if (isa<FunctionDecl>(D)) {
    416       HasFunction = true;
    417     } else {
    418       if (HasNonFunction)
    419         Ambiguous = true;
    420       HasNonFunction = true;
    421     }
    422     I++;
    423   }
    424 
    425   // C++ [basic.scope.hiding]p2:
    426   //   A class name or enumeration name can be hidden by the name of
    427   //   an object, function, or enumerator declared in the same
    428   //   scope. If a class or enumeration name and an object, function,
    429   //   or enumerator are declared in the same scope (in any order)
    430   //   with the same name, the class or enumeration name is hidden
    431   //   wherever the object, function, or enumerator name is visible.
    432   // But it's still an error if there are distinct tag types found,
    433   // even if they're not visible. (ref?)
    434   if (HideTags && HasTag && !Ambiguous &&
    435       (HasFunction || HasNonFunction || HasUnresolved)) {
    436     if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
    437          Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
    438       Decls[UniqueTagIndex] = Decls[--N];
    439     else
    440       Ambiguous = true;
    441   }
    442 
    443   Decls.set_size(N);
    444 
    445   if (HasNonFunction && (HasFunction || HasUnresolved))
    446     Ambiguous = true;
    447 
    448   if (Ambiguous)
    449     setAmbiguous(LookupResult::AmbiguousReference);
    450   else if (HasUnresolved)
    451     ResultKind = LookupResult::FoundUnresolvedValue;
    452   else if (N > 1 || HasFunctionTemplate)
    453     ResultKind = LookupResult::FoundOverloaded;
    454   else
    455     ResultKind = LookupResult::Found;
    456 }
    457 
    458 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
    459   CXXBasePaths::const_paths_iterator I, E;
    460   for (I = P.begin(), E = P.end(); I != E; ++I)
    461     for (DeclContext::lookup_iterator DI = I->Decls.begin(),
    462          DE = I->Decls.end(); DI != DE; ++DI)
    463       addDecl(*DI);
    464 }
    465 
    466 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
    467   Paths = new CXXBasePaths;
    468   Paths->swap(P);
    469   addDeclsFromBasePaths(*Paths);
    470   resolveKind();
    471   setAmbiguous(AmbiguousBaseSubobjects);
    472 }
    473 
    474 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
    475   Paths = new CXXBasePaths;
    476   Paths->swap(P);
    477   addDeclsFromBasePaths(*Paths);
    478   resolveKind();
    479   setAmbiguous(AmbiguousBaseSubobjectTypes);
    480 }
    481 
    482 void LookupResult::print(raw_ostream &Out) {
    483   Out << Decls.size() << " result(s)";
    484   if (isAmbiguous()) Out << ", ambiguous";
    485   if (Paths) Out << ", base paths present";
    486 
    487   for (iterator I = begin(), E = end(); I != E; ++I) {
    488     Out << "\n";
    489     (*I)->print(Out, 2);
    490   }
    491 }
    492 
    493 /// \brief Lookup a builtin function, when name lookup would otherwise
    494 /// fail.
    495 static bool LookupBuiltin(Sema &S, LookupResult &R) {
    496   Sema::LookupNameKind NameKind = R.getLookupKind();
    497 
    498   // If we didn't find a use of this identifier, and if the identifier
    499   // corresponds to a compiler builtin, create the decl object for the builtin
    500   // now, injecting it into translation unit scope, and return it.
    501   if (NameKind == Sema::LookupOrdinaryName ||
    502       NameKind == Sema::LookupRedeclarationWithLinkage) {
    503     IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
    504     if (II) {
    505       // If this is a builtin on this (or all) targets, create the decl.
    506       if (unsigned BuiltinID = II->getBuiltinID()) {
    507         // In C++, we don't have any predefined library functions like
    508         // 'malloc'. Instead, we'll just error.
    509         if (S.getLangOpts().CPlusPlus &&
    510             S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
    511           return false;
    512 
    513         if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
    514                                                  BuiltinID, S.TUScope,
    515                                                  R.isForRedeclaration(),
    516                                                  R.getNameLoc())) {
    517           R.addDecl(D);
    518           return true;
    519         }
    520 
    521         if (R.isForRedeclaration()) {
    522           // If we're redeclaring this function anyway, forget that
    523           // this was a builtin at all.
    524           S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
    525         }
    526 
    527         return false;
    528       }
    529     }
    530   }
    531 
    532   return false;
    533 }
    534 
    535 /// \brief Determine whether we can declare a special member function within
    536 /// the class at this point.
    537 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
    538   // We need to have a definition for the class.
    539   if (!Class->getDefinition() || Class->isDependentContext())
    540     return false;
    541 
    542   // We can't be in the middle of defining the class.
    543   return !Class->isBeingDefined();
    544 }
    545 
    546 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
    547   if (!CanDeclareSpecialMemberFunction(Class))
    548     return;
    549 
    550   // If the default constructor has not yet been declared, do so now.
    551   if (Class->needsImplicitDefaultConstructor())
    552     DeclareImplicitDefaultConstructor(Class);
    553 
    554   // If the copy constructor has not yet been declared, do so now.
    555   if (Class->needsImplicitCopyConstructor())
    556     DeclareImplicitCopyConstructor(Class);
    557 
    558   // If the copy assignment operator has not yet been declared, do so now.
    559   if (Class->needsImplicitCopyAssignment())
    560     DeclareImplicitCopyAssignment(Class);
    561 
    562   if (getLangOpts().CPlusPlus11) {
    563     // If the move constructor has not yet been declared, do so now.
    564     if (Class->needsImplicitMoveConstructor())
    565       DeclareImplicitMoveConstructor(Class); // might not actually do it
    566 
    567     // If the move assignment operator has not yet been declared, do so now.
    568     if (Class->needsImplicitMoveAssignment())
    569       DeclareImplicitMoveAssignment(Class); // might not actually do it
    570   }
    571 
    572   // If the destructor has not yet been declared, do so now.
    573   if (Class->needsImplicitDestructor())
    574     DeclareImplicitDestructor(Class);
    575 }
    576 
    577 /// \brief Determine whether this is the name of an implicitly-declared
    578 /// special member function.
    579 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
    580   switch (Name.getNameKind()) {
    581   case DeclarationName::CXXConstructorName:
    582   case DeclarationName::CXXDestructorName:
    583     return true;
    584 
    585   case DeclarationName::CXXOperatorName:
    586     return Name.getCXXOverloadedOperator() == OO_Equal;
    587 
    588   default:
    589     break;
    590   }
    591 
    592   return false;
    593 }
    594 
    595 /// \brief If there are any implicit member functions with the given name
    596 /// that need to be declared in the given declaration context, do so.
    597 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
    598                                                    DeclarationName Name,
    599                                                    const DeclContext *DC) {
    600   if (!DC)
    601     return;
    602 
    603   switch (Name.getNameKind()) {
    604   case DeclarationName::CXXConstructorName:
    605     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
    606       if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
    607         CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
    608         if (Record->needsImplicitDefaultConstructor())
    609           S.DeclareImplicitDefaultConstructor(Class);
    610         if (Record->needsImplicitCopyConstructor())
    611           S.DeclareImplicitCopyConstructor(Class);
    612         if (S.getLangOpts().CPlusPlus11 &&
    613             Record->needsImplicitMoveConstructor())
    614           S.DeclareImplicitMoveConstructor(Class);
    615       }
    616     break;
    617 
    618   case DeclarationName::CXXDestructorName:
    619     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
    620       if (Record->getDefinition() && Record->needsImplicitDestructor() &&
    621           CanDeclareSpecialMemberFunction(Record))
    622         S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
    623     break;
    624 
    625   case DeclarationName::CXXOperatorName:
    626     if (Name.getCXXOverloadedOperator() != OO_Equal)
    627       break;
    628 
    629     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
    630       if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
    631         CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
    632         if (Record->needsImplicitCopyAssignment())
    633           S.DeclareImplicitCopyAssignment(Class);
    634         if (S.getLangOpts().CPlusPlus11 &&
    635             Record->needsImplicitMoveAssignment())
    636           S.DeclareImplicitMoveAssignment(Class);
    637       }
    638     }
    639     break;
    640 
    641   default:
    642     break;
    643   }
    644 }
    645 
    646 // Adds all qualifying matches for a name within a decl context to the
    647 // given lookup result.  Returns true if any matches were found.
    648 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
    649   bool Found = false;
    650 
    651   // Lazily declare C++ special member functions.
    652   if (S.getLangOpts().CPlusPlus)
    653     DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
    654 
    655   // Perform lookup into this declaration context.
    656   DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
    657   for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
    658        ++I) {
    659     NamedDecl *D = *I;
    660     if ((D = R.getAcceptableDecl(D))) {
    661       R.addDecl(D);
    662       Found = true;
    663     }
    664   }
    665 
    666   if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
    667     return true;
    668 
    669   if (R.getLookupName().getNameKind()
    670         != DeclarationName::CXXConversionFunctionName ||
    671       R.getLookupName().getCXXNameType()->isDependentType() ||
    672       !isa<CXXRecordDecl>(DC))
    673     return Found;
    674 
    675   // C++ [temp.mem]p6:
    676   //   A specialization of a conversion function template is not found by
    677   //   name lookup. Instead, any conversion function templates visible in the
    678   //   context of the use are considered. [...]
    679   const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
    680   if (!Record->isCompleteDefinition())
    681     return Found;
    682 
    683   for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
    684          UEnd = Record->conversion_end(); U != UEnd; ++U) {
    685     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
    686     if (!ConvTemplate)
    687       continue;
    688 
    689     // When we're performing lookup for the purposes of redeclaration, just
    690     // add the conversion function template. When we deduce template
    691     // arguments for specializations, we'll end up unifying the return
    692     // type of the new declaration with the type of the function template.
    693     if (R.isForRedeclaration()) {
    694       R.addDecl(ConvTemplate);
    695       Found = true;
    696       continue;
    697     }
    698 
    699     // C++ [temp.mem]p6:
    700     //   [...] For each such operator, if argument deduction succeeds
    701     //   (14.9.2.3), the resulting specialization is used as if found by
    702     //   name lookup.
    703     //
    704     // When referencing a conversion function for any purpose other than
    705     // a redeclaration (such that we'll be building an expression with the
    706     // result), perform template argument deduction and place the
    707     // specialization into the result set. We do this to avoid forcing all
    708     // callers to perform special deduction for conversion functions.
    709     TemplateDeductionInfo Info(R.getNameLoc());
    710     FunctionDecl *Specialization = 0;
    711 
    712     const FunctionProtoType *ConvProto
    713       = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
    714     assert(ConvProto && "Nonsensical conversion function template type");
    715 
    716     // Compute the type of the function that we would expect the conversion
    717     // function to have, if it were to match the name given.
    718     // FIXME: Calling convention!
    719     FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
    720     EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
    721     EPI.ExceptionSpecType = EST_None;
    722     EPI.NumExceptions = 0;
    723     QualType ExpectedType
    724       = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
    725                                             ArrayRef<QualType>(), EPI);
    726 
    727     // Perform template argument deduction against the type that we would
    728     // expect the function to have.
    729     if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
    730                                             Specialization, Info)
    731           == Sema::TDK_Success) {
    732       R.addDecl(Specialization);
    733       Found = true;
    734     }
    735   }
    736 
    737   return Found;
    738 }
    739 
    740 // Performs C++ unqualified lookup into the given file context.
    741 static bool
    742 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
    743                    DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
    744 
    745   assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
    746 
    747   // Perform direct name lookup into the LookupCtx.
    748   bool Found = LookupDirect(S, R, NS);
    749 
    750   // Perform direct name lookup into the namespaces nominated by the
    751   // using directives whose common ancestor is this namespace.
    752   UnqualUsingDirectiveSet::const_iterator UI, UEnd;
    753   llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
    754 
    755   for (; UI != UEnd; ++UI)
    756     if (LookupDirect(S, R, UI->getNominatedNamespace()))
    757       Found = true;
    758 
    759   R.resolveKind();
    760 
    761   return Found;
    762 }
    763 
    764 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
    765   if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
    766     return Ctx->isFileContext();
    767   return false;
    768 }
    769 
    770 // Find the next outer declaration context from this scope. This
    771 // routine actually returns the semantic outer context, which may
    772 // differ from the lexical context (encoded directly in the Scope
    773 // stack) when we are parsing a member of a class template. In this
    774 // case, the second element of the pair will be true, to indicate that
    775 // name lookup should continue searching in this semantic context when
    776 // it leaves the current template parameter scope.
    777 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
    778   DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
    779   DeclContext *Lexical = 0;
    780   for (Scope *OuterS = S->getParent(); OuterS;
    781        OuterS = OuterS->getParent()) {
    782     if (OuterS->getEntity()) {
    783       Lexical = static_cast<DeclContext *>(OuterS->getEntity());
    784       break;
    785     }
    786   }
    787 
    788   // C++ [temp.local]p8:
    789   //   In the definition of a member of a class template that appears
    790   //   outside of the namespace containing the class template
    791   //   definition, the name of a template-parameter hides the name of
    792   //   a member of this namespace.
    793   //
    794   // Example:
    795   //
    796   //   namespace N {
    797   //     class C { };
    798   //
    799   //     template<class T> class B {
    800   //       void f(T);
    801   //     };
    802   //   }
    803   //
    804   //   template<class C> void N::B<C>::f(C) {
    805   //     C b;  // C is the template parameter, not N::C
    806   //   }
    807   //
    808   // In this example, the lexical context we return is the
    809   // TranslationUnit, while the semantic context is the namespace N.
    810   if (!Lexical || !DC || !S->getParent() ||
    811       !S->getParent()->isTemplateParamScope())
    812     return std::make_pair(Lexical, false);
    813 
    814   // Find the outermost template parameter scope.
    815   // For the example, this is the scope for the template parameters of
    816   // template<class C>.
    817   Scope *OutermostTemplateScope = S->getParent();
    818   while (OutermostTemplateScope->getParent() &&
    819          OutermostTemplateScope->getParent()->isTemplateParamScope())
    820     OutermostTemplateScope = OutermostTemplateScope->getParent();
    821 
    822   // Find the namespace context in which the original scope occurs. In
    823   // the example, this is namespace N.
    824   DeclContext *Semantic = DC;
    825   while (!Semantic->isFileContext())
    826     Semantic = Semantic->getParent();
    827 
    828   // Find the declaration context just outside of the template
    829   // parameter scope. This is the context in which the template is
    830   // being lexically declaration (a namespace context). In the
    831   // example, this is the global scope.
    832   if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
    833       Lexical->Encloses(Semantic))
    834     return std::make_pair(Semantic, true);
    835 
    836   return std::make_pair(Lexical, false);
    837 }
    838 
    839 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
    840   assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
    841 
    842   DeclarationName Name = R.getLookupName();
    843 
    844   // If this is the name of an implicitly-declared special member function,
    845   // go through the scope stack to implicitly declare
    846   if (isImplicitlyDeclaredMemberFunctionName(Name)) {
    847     for (Scope *PreS = S; PreS; PreS = PreS->getParent())
    848       if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
    849         DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
    850   }
    851 
    852   // Implicitly declare member functions with the name we're looking for, if in
    853   // fact we are in a scope where it matters.
    854 
    855   Scope *Initial = S;
    856   IdentifierResolver::iterator
    857     I = IdResolver.begin(Name),
    858     IEnd = IdResolver.end();
    859 
    860   // First we lookup local scope.
    861   // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
    862   // ...During unqualified name lookup (3.4.1), the names appear as if
    863   // they were declared in the nearest enclosing namespace which contains
    864   // both the using-directive and the nominated namespace.
    865   // [Note: in this context, "contains" means "contains directly or
    866   // indirectly".
    867   //
    868   // For example:
    869   // namespace A { int i; }
    870   // void foo() {
    871   //   int i;
    872   //   {
    873   //     using namespace A;
    874   //     ++i; // finds local 'i', A::i appears at global scope
    875   //   }
    876   // }
    877   //
    878   DeclContext *OutsideOfTemplateParamDC = 0;
    879   for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
    880     DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
    881 
    882     // Check whether the IdResolver has anything in this scope.
    883     bool Found = false;
    884     for (; I != IEnd && S->isDeclScope(*I); ++I) {
    885       if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
    886         Found = true;
    887         R.addDecl(ND);
    888       }
    889     }
    890     if (Found) {
    891       R.resolveKind();
    892       if (S->isClassScope())
    893         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
    894           R.setNamingClass(Record);
    895       return true;
    896     }
    897 
    898     if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
    899         S->getParent() && !S->getParent()->isTemplateParamScope()) {
    900       // We've just searched the last template parameter scope and
    901       // found nothing, so look into the contexts between the
    902       // lexical and semantic declaration contexts returned by
    903       // findOuterContext(). This implements the name lookup behavior
    904       // of C++ [temp.local]p8.
    905       Ctx = OutsideOfTemplateParamDC;
    906       OutsideOfTemplateParamDC = 0;
    907     }
    908 
    909     if (Ctx) {
    910       DeclContext *OuterCtx;
    911       bool SearchAfterTemplateScope;
    912       llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
    913       if (SearchAfterTemplateScope)
    914         OutsideOfTemplateParamDC = OuterCtx;
    915 
    916       for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
    917         // We do not directly look into transparent contexts, since
    918         // those entities will be found in the nearest enclosing
    919         // non-transparent context.
    920         if (Ctx->isTransparentContext())
    921           continue;
    922 
    923         // We do not look directly into function or method contexts,
    924         // since all of the local variables and parameters of the
    925         // function/method are present within the Scope.
    926         if (Ctx->isFunctionOrMethod()) {
    927           // If we have an Objective-C instance method, look for ivars
    928           // in the corresponding interface.
    929           if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
    930             if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
    931               if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
    932                 ObjCInterfaceDecl *ClassDeclared;
    933                 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
    934                                                  Name.getAsIdentifierInfo(),
    935                                                              ClassDeclared)) {
    936                   if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
    937                     R.addDecl(ND);
    938                     R.resolveKind();
    939                     return true;
    940                   }
    941                 }
    942               }
    943           }
    944 
    945           continue;
    946         }
    947 
    948         // Perform qualified name lookup into this context.
    949         // FIXME: In some cases, we know that every name that could be found by
    950         // this qualified name lookup will also be on the identifier chain. For
    951         // example, inside a class without any base classes, we never need to
    952         // perform qualified lookup because all of the members are on top of the
    953         // identifier chain.
    954         if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
    955           return true;
    956       }
    957     }
    958   }
    959 
    960   // Stop if we ran out of scopes.
    961   // FIXME:  This really, really shouldn't be happening.
    962   if (!S) return false;
    963 
    964   // If we are looking for members, no need to look into global/namespace scope.
    965   if (R.getLookupKind() == LookupMemberName)
    966     return false;
    967 
    968   // Collect UsingDirectiveDecls in all scopes, and recursively all
    969   // nominated namespaces by those using-directives.
    970   //
    971   // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
    972   // don't build it for each lookup!
    973 
    974   UnqualUsingDirectiveSet UDirs;
    975   UDirs.visitScopeChain(Initial, S);
    976   UDirs.done();
    977 
    978   // Lookup namespace scope, and global scope.
    979   // Unqualified name lookup in C++ requires looking into scopes
    980   // that aren't strictly lexical, and therefore we walk through the
    981   // context as well as walking through the scopes.
    982 
    983   for (; S; S = S->getParent()) {
    984     // Check whether the IdResolver has anything in this scope.
    985     bool Found = false;
    986     for (; I != IEnd && S->isDeclScope(*I); ++I) {
    987       if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
    988         // We found something.  Look for anything else in our scope
    989         // with this same name and in an acceptable identifier
    990         // namespace, so that we can construct an overload set if we
    991         // need to.
    992         Found = true;
    993         R.addDecl(ND);
    994       }
    995     }
    996 
    997     if (Found && S->isTemplateParamScope()) {
    998       R.resolveKind();
    999       return true;
   1000     }
   1001 
   1002     DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
   1003     if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
   1004         S->getParent() && !S->getParent()->isTemplateParamScope()) {
   1005       // We've just searched the last template parameter scope and
   1006       // found nothing, so look into the contexts between the
   1007       // lexical and semantic declaration contexts returned by
   1008       // findOuterContext(). This implements the name lookup behavior
   1009       // of C++ [temp.local]p8.
   1010       Ctx = OutsideOfTemplateParamDC;
   1011       OutsideOfTemplateParamDC = 0;
   1012     }
   1013 
   1014     if (Ctx) {
   1015       DeclContext *OuterCtx;
   1016       bool SearchAfterTemplateScope;
   1017       llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
   1018       if (SearchAfterTemplateScope)
   1019         OutsideOfTemplateParamDC = OuterCtx;
   1020 
   1021       for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
   1022         // We do not directly look into transparent contexts, since
   1023         // those entities will be found in the nearest enclosing
   1024         // non-transparent context.
   1025         if (Ctx->isTransparentContext())
   1026           continue;
   1027 
   1028         // If we have a context, and it's not a context stashed in the
   1029         // template parameter scope for an out-of-line definition, also
   1030         // look into that context.
   1031         if (!(Found && S && S->isTemplateParamScope())) {
   1032           assert(Ctx->isFileContext() &&
   1033               "We should have been looking only at file context here already.");
   1034 
   1035           // Look into context considering using-directives.
   1036           if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
   1037             Found = true;
   1038         }
   1039 
   1040         if (Found) {
   1041           R.resolveKind();
   1042           return true;
   1043         }
   1044 
   1045         if (R.isForRedeclaration() && !Ctx->isTransparentContext())
   1046           return false;
   1047       }
   1048     }
   1049 
   1050     if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
   1051       return false;
   1052   }
   1053 
   1054   return !R.empty();
   1055 }
   1056 
   1057 /// \brief Retrieve the visible declaration corresponding to D, if any.
   1058 ///
   1059 /// This routine determines whether the declaration D is visible in the current
   1060 /// module, with the current imports. If not, it checks whether any
   1061 /// redeclaration of D is visible, and if so, returns that declaration.
   1062 ///
   1063 /// \returns D, or a visible previous declaration of D, whichever is more recent
   1064 /// and visible. If no declaration of D is visible, returns null.
   1065 static NamedDecl *getVisibleDecl(NamedDecl *D) {
   1066   if (LookupResult::isVisible(D))
   1067     return D;
   1068 
   1069   for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
   1070        RD != RDEnd; ++RD) {
   1071     if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
   1072       if (LookupResult::isVisible(ND))
   1073         return ND;
   1074     }
   1075   }
   1076 
   1077   return 0;
   1078 }
   1079 
   1080 /// @brief Perform unqualified name lookup starting from a given
   1081 /// scope.
   1082 ///
   1083 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
   1084 /// used to find names within the current scope. For example, 'x' in
   1085 /// @code
   1086 /// int x;
   1087 /// int f() {
   1088 ///   return x; // unqualified name look finds 'x' in the global scope
   1089 /// }
   1090 /// @endcode
   1091 ///
   1092 /// Different lookup criteria can find different names. For example, a
   1093 /// particular scope can have both a struct and a function of the same
   1094 /// name, and each can be found by certain lookup criteria. For more
   1095 /// information about lookup criteria, see the documentation for the
   1096 /// class LookupCriteria.
   1097 ///
   1098 /// @param S        The scope from which unqualified name lookup will
   1099 /// begin. If the lookup criteria permits, name lookup may also search
   1100 /// in the parent scopes.
   1101 ///
   1102 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
   1103 /// look up and the lookup kind), and is updated with the results of lookup
   1104 /// including zero or more declarations and possibly additional information
   1105 /// used to diagnose ambiguities.
   1106 ///
   1107 /// @returns \c true if lookup succeeded and false otherwise.
   1108 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
   1109   DeclarationName Name = R.getLookupName();
   1110   if (!Name) return false;
   1111 
   1112   LookupNameKind NameKind = R.getLookupKind();
   1113 
   1114   if (!getLangOpts().CPlusPlus) {
   1115     // Unqualified name lookup in C/Objective-C is purely lexical, so
   1116     // search in the declarations attached to the name.
   1117     if (NameKind == Sema::LookupRedeclarationWithLinkage) {
   1118       // Find the nearest non-transparent declaration scope.
   1119       while (!(S->getFlags() & Scope::DeclScope) ||
   1120              (S->getEntity() &&
   1121               static_cast<DeclContext *>(S->getEntity())
   1122                 ->isTransparentContext()))
   1123         S = S->getParent();
   1124     }
   1125 
   1126     unsigned IDNS = R.getIdentifierNamespace();
   1127 
   1128     // Scan up the scope chain looking for a decl that matches this
   1129     // identifier that is in the appropriate namespace.  This search
   1130     // should not take long, as shadowing of names is uncommon, and
   1131     // deep shadowing is extremely uncommon.
   1132     bool LeftStartingScope = false;
   1133 
   1134     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
   1135                                    IEnd = IdResolver.end();
   1136          I != IEnd; ++I)
   1137       if ((*I)->isInIdentifierNamespace(IDNS)) {
   1138         if (NameKind == LookupRedeclarationWithLinkage) {
   1139           // Determine whether this (or a previous) declaration is
   1140           // out-of-scope.
   1141           if (!LeftStartingScope && !S->isDeclScope(*I))
   1142             LeftStartingScope = true;
   1143 
   1144           // If we found something outside of our starting scope that
   1145           // does not have linkage, skip it.
   1146           if (LeftStartingScope && !((*I)->hasLinkage()))
   1147             continue;
   1148         }
   1149         else if (NameKind == LookupObjCImplicitSelfParam &&
   1150                  !isa<ImplicitParamDecl>(*I))
   1151           continue;
   1152 
   1153         // If this declaration is module-private and it came from an AST
   1154         // file, we can't see it.
   1155         NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
   1156         if (!D)
   1157           continue;
   1158 
   1159         R.addDecl(D);
   1160 
   1161         // Check whether there are any other declarations with the same name
   1162         // and in the same scope.
   1163         if (I != IEnd) {
   1164           // Find the scope in which this declaration was declared (if it
   1165           // actually exists in a Scope).
   1166           while (S && !S->isDeclScope(D))
   1167             S = S->getParent();
   1168 
   1169           // If the scope containing the declaration is the translation unit,
   1170           // then we'll need to perform our checks based on the matching
   1171           // DeclContexts rather than matching scopes.
   1172           if (S && isNamespaceOrTranslationUnitScope(S))
   1173             S = 0;
   1174 
   1175           // Compute the DeclContext, if we need it.
   1176           DeclContext *DC = 0;
   1177           if (!S)
   1178             DC = (*I)->getDeclContext()->getRedeclContext();
   1179 
   1180           IdentifierResolver::iterator LastI = I;
   1181           for (++LastI; LastI != IEnd; ++LastI) {
   1182             if (S) {
   1183               // Match based on scope.
   1184               if (!S->isDeclScope(*LastI))
   1185                 break;
   1186             } else {
   1187               // Match based on DeclContext.
   1188               DeclContext *LastDC
   1189                 = (*LastI)->getDeclContext()->getRedeclContext();
   1190               if (!LastDC->Equals(DC))
   1191                 break;
   1192             }
   1193 
   1194             // If the declaration isn't in the right namespace, skip it.
   1195             if (!(*LastI)->isInIdentifierNamespace(IDNS))
   1196               continue;
   1197 
   1198             D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
   1199             if (D)
   1200               R.addDecl(D);
   1201           }
   1202 
   1203           R.resolveKind();
   1204         }
   1205         return true;
   1206       }
   1207   } else {
   1208     // Perform C++ unqualified name lookup.
   1209     if (CppLookupName(R, S))
   1210       return true;
   1211   }
   1212 
   1213   // If we didn't find a use of this identifier, and if the identifier
   1214   // corresponds to a compiler builtin, create the decl object for the builtin
   1215   // now, injecting it into translation unit scope, and return it.
   1216   if (AllowBuiltinCreation && LookupBuiltin(*this, R))
   1217     return true;
   1218 
   1219   // If we didn't find a use of this identifier, the ExternalSource
   1220   // may be able to handle the situation.
   1221   // Note: some lookup failures are expected!
   1222   // See e.g. R.isForRedeclaration().
   1223   return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
   1224 }
   1225 
   1226 /// @brief Perform qualified name lookup in the namespaces nominated by
   1227 /// using directives by the given context.
   1228 ///
   1229 /// C++98 [namespace.qual]p2:
   1230 ///   Given X::m (where X is a user-declared namespace), or given \::m
   1231 ///   (where X is the global namespace), let S be the set of all
   1232 ///   declarations of m in X and in the transitive closure of all
   1233 ///   namespaces nominated by using-directives in X and its used
   1234 ///   namespaces, except that using-directives are ignored in any
   1235 ///   namespace, including X, directly containing one or more
   1236 ///   declarations of m. No namespace is searched more than once in
   1237 ///   the lookup of a name. If S is the empty set, the program is
   1238 ///   ill-formed. Otherwise, if S has exactly one member, or if the
   1239 ///   context of the reference is a using-declaration
   1240 ///   (namespace.udecl), S is the required set of declarations of
   1241 ///   m. Otherwise if the use of m is not one that allows a unique
   1242 ///   declaration to be chosen from S, the program is ill-formed.
   1243 ///
   1244 /// C++98 [namespace.qual]p5:
   1245 ///   During the lookup of a qualified namespace member name, if the
   1246 ///   lookup finds more than one declaration of the member, and if one
   1247 ///   declaration introduces a class name or enumeration name and the
   1248 ///   other declarations either introduce the same object, the same
   1249 ///   enumerator or a set of functions, the non-type name hides the
   1250 ///   class or enumeration name if and only if the declarations are
   1251 ///   from the same namespace; otherwise (the declarations are from
   1252 ///   different namespaces), the program is ill-formed.
   1253 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
   1254                                                  DeclContext *StartDC) {
   1255   assert(StartDC->isFileContext() && "start context is not a file context");
   1256 
   1257   DeclContext::udir_iterator I = StartDC->using_directives_begin();
   1258   DeclContext::udir_iterator E = StartDC->using_directives_end();
   1259 
   1260   if (I == E) return false;
   1261 
   1262   // We have at least added all these contexts to the queue.
   1263   llvm::SmallPtrSet<DeclContext*, 8> Visited;
   1264   Visited.insert(StartDC);
   1265 
   1266   // We have not yet looked into these namespaces, much less added
   1267   // their "using-children" to the queue.
   1268   SmallVector<NamespaceDecl*, 8> Queue;
   1269 
   1270   // We have already looked into the initial namespace; seed the queue
   1271   // with its using-children.
   1272   for (; I != E; ++I) {
   1273     NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
   1274     if (Visited.insert(ND))
   1275       Queue.push_back(ND);
   1276   }
   1277 
   1278   // The easiest way to implement the restriction in [namespace.qual]p5
   1279   // is to check whether any of the individual results found a tag
   1280   // and, if so, to declare an ambiguity if the final result is not
   1281   // a tag.
   1282   bool FoundTag = false;
   1283   bool FoundNonTag = false;
   1284 
   1285   LookupResult LocalR(LookupResult::Temporary, R);
   1286 
   1287   bool Found = false;
   1288   while (!Queue.empty()) {
   1289     NamespaceDecl *ND = Queue.back();
   1290     Queue.pop_back();
   1291 
   1292     // We go through some convolutions here to avoid copying results
   1293     // between LookupResults.
   1294     bool UseLocal = !R.empty();
   1295     LookupResult &DirectR = UseLocal ? LocalR : R;
   1296     bool FoundDirect = LookupDirect(S, DirectR, ND);
   1297 
   1298     if (FoundDirect) {
   1299       // First do any local hiding.
   1300       DirectR.resolveKind();
   1301 
   1302       // If the local result is a tag, remember that.
   1303       if (DirectR.isSingleTagDecl())
   1304         FoundTag = true;
   1305       else
   1306         FoundNonTag = true;
   1307 
   1308       // Append the local results to the total results if necessary.
   1309       if (UseLocal) {
   1310         R.addAllDecls(LocalR);
   1311         LocalR.clear();
   1312       }
   1313     }
   1314 
   1315     // If we find names in this namespace, ignore its using directives.
   1316     if (FoundDirect) {
   1317       Found = true;
   1318       continue;
   1319     }
   1320 
   1321     for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
   1322       NamespaceDecl *Nom = (*I)->getNominatedNamespace();
   1323       if (Visited.insert(Nom))
   1324         Queue.push_back(Nom);
   1325     }
   1326   }
   1327 
   1328   if (Found) {
   1329     if (FoundTag && FoundNonTag)
   1330       R.setAmbiguousQualifiedTagHiding();
   1331     else
   1332       R.resolveKind();
   1333   }
   1334 
   1335   return Found;
   1336 }
   1337 
   1338 /// \brief Callback that looks for any member of a class with the given name.
   1339 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
   1340                             CXXBasePath &Path,
   1341                             void *Name) {
   1342   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
   1343 
   1344   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
   1345   Path.Decls = BaseRecord->lookup(N);
   1346   return !Path.Decls.empty();
   1347 }
   1348 
   1349 /// \brief Determine whether the given set of member declarations contains only
   1350 /// static members, nested types, and enumerators.
   1351 template<typename InputIterator>
   1352 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
   1353   Decl *D = (*First)->getUnderlyingDecl();
   1354   if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
   1355     return true;
   1356 
   1357   if (isa<CXXMethodDecl>(D)) {
   1358     // Determine whether all of the methods are static.
   1359     bool AllMethodsAreStatic = true;
   1360     for(; First != Last; ++First) {
   1361       D = (*First)->getUnderlyingDecl();
   1362 
   1363       if (!isa<CXXMethodDecl>(D)) {
   1364         assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
   1365         break;
   1366       }
   1367 
   1368       if (!cast<CXXMethodDecl>(D)->isStatic()) {
   1369         AllMethodsAreStatic = false;
   1370         break;
   1371       }
   1372     }
   1373 
   1374     if (AllMethodsAreStatic)
   1375       return true;
   1376   }
   1377 
   1378   return false;
   1379 }
   1380 
   1381 /// \brief Perform qualified name lookup into a given context.
   1382 ///
   1383 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
   1384 /// names when the context of those names is explicit specified, e.g.,
   1385 /// "std::vector" or "x->member", or as part of unqualified name lookup.
   1386 ///
   1387 /// Different lookup criteria can find different names. For example, a
   1388 /// particular scope can have both a struct and a function of the same
   1389 /// name, and each can be found by certain lookup criteria. For more
   1390 /// information about lookup criteria, see the documentation for the
   1391 /// class LookupCriteria.
   1392 ///
   1393 /// \param R captures both the lookup criteria and any lookup results found.
   1394 ///
   1395 /// \param LookupCtx The context in which qualified name lookup will
   1396 /// search. If the lookup criteria permits, name lookup may also search
   1397 /// in the parent contexts or (for C++ classes) base classes.
   1398 ///
   1399 /// \param InUnqualifiedLookup true if this is qualified name lookup that
   1400 /// occurs as part of unqualified name lookup.
   1401 ///
   1402 /// \returns true if lookup succeeded, false if it failed.
   1403 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
   1404                                bool InUnqualifiedLookup) {
   1405   assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
   1406 
   1407   if (!R.getLookupName())
   1408     return false;
   1409 
   1410   // Make sure that the declaration context is complete.
   1411   assert((!isa<TagDecl>(LookupCtx) ||
   1412           LookupCtx->isDependentContext() ||
   1413           cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
   1414           cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
   1415          "Declaration context must already be complete!");
   1416 
   1417   // Perform qualified name lookup into the LookupCtx.
   1418   if (LookupDirect(*this, R, LookupCtx)) {
   1419     R.resolveKind();
   1420     if (isa<CXXRecordDecl>(LookupCtx))
   1421       R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
   1422     return true;
   1423   }
   1424 
   1425   // Don't descend into implied contexts for redeclarations.
   1426   // C++98 [namespace.qual]p6:
   1427   //   In a declaration for a namespace member in which the
   1428   //   declarator-id is a qualified-id, given that the qualified-id
   1429   //   for the namespace member has the form
   1430   //     nested-name-specifier unqualified-id
   1431   //   the unqualified-id shall name a member of the namespace
   1432   //   designated by the nested-name-specifier.
   1433   // See also [class.mfct]p5 and [class.static.data]p2.
   1434   if (R.isForRedeclaration())
   1435     return false;
   1436 
   1437   // If this is a namespace, look it up in the implied namespaces.
   1438   if (LookupCtx->isFileContext())
   1439     return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
   1440 
   1441   // If this isn't a C++ class, we aren't allowed to look into base
   1442   // classes, we're done.
   1443   CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
   1444   if (!LookupRec || !LookupRec->getDefinition())
   1445     return false;
   1446 
   1447   // If we're performing qualified name lookup into a dependent class,
   1448   // then we are actually looking into a current instantiation. If we have any
   1449   // dependent base classes, then we either have to delay lookup until
   1450   // template instantiation time (at which point all bases will be available)
   1451   // or we have to fail.
   1452   if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
   1453       LookupRec->hasAnyDependentBases()) {
   1454     R.setNotFoundInCurrentInstantiation();
   1455     return false;
   1456   }
   1457 
   1458   // Perform lookup into our base classes.
   1459   CXXBasePaths Paths;
   1460   Paths.setOrigin(LookupRec);
   1461 
   1462   // Look for this member in our base classes
   1463   CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
   1464   switch (R.getLookupKind()) {
   1465     case LookupObjCImplicitSelfParam:
   1466     case LookupOrdinaryName:
   1467     case LookupMemberName:
   1468     case LookupRedeclarationWithLinkage:
   1469       BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
   1470       break;
   1471 
   1472     case LookupTagName:
   1473       BaseCallback = &CXXRecordDecl::FindTagMember;
   1474       break;
   1475 
   1476     case LookupAnyName:
   1477       BaseCallback = &LookupAnyMember;
   1478       break;
   1479 
   1480     case LookupUsingDeclName:
   1481       // This lookup is for redeclarations only.
   1482 
   1483     case LookupOperatorName:
   1484     case LookupNamespaceName:
   1485     case LookupObjCProtocolName:
   1486     case LookupLabel:
   1487       // These lookups will never find a member in a C++ class (or base class).
   1488       return false;
   1489 
   1490     case LookupNestedNameSpecifierName:
   1491       BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
   1492       break;
   1493   }
   1494 
   1495   if (!LookupRec->lookupInBases(BaseCallback,
   1496                                 R.getLookupName().getAsOpaquePtr(), Paths))
   1497     return false;
   1498 
   1499   R.setNamingClass(LookupRec);
   1500 
   1501   // C++ [class.member.lookup]p2:
   1502   //   [...] If the resulting set of declarations are not all from
   1503   //   sub-objects of the same type, or the set has a nonstatic member
   1504   //   and includes members from distinct sub-objects, there is an
   1505   //   ambiguity and the program is ill-formed. Otherwise that set is
   1506   //   the result of the lookup.
   1507   QualType SubobjectType;
   1508   int SubobjectNumber = 0;
   1509   AccessSpecifier SubobjectAccess = AS_none;
   1510 
   1511   for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
   1512        Path != PathEnd; ++Path) {
   1513     const CXXBasePathElement &PathElement = Path->back();
   1514 
   1515     // Pick the best (i.e. most permissive i.e. numerically lowest) access
   1516     // across all paths.
   1517     SubobjectAccess = std::min(SubobjectAccess, Path->Access);
   1518 
   1519     // Determine whether we're looking at a distinct sub-object or not.
   1520     if (SubobjectType.isNull()) {
   1521       // This is the first subobject we've looked at. Record its type.
   1522       SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
   1523       SubobjectNumber = PathElement.SubobjectNumber;
   1524       continue;
   1525     }
   1526 
   1527     if (SubobjectType
   1528                  != Context.getCanonicalType(PathElement.Base->getType())) {
   1529       // We found members of the given name in two subobjects of
   1530       // different types. If the declaration sets aren't the same, this
   1531       // this lookup is ambiguous.
   1532       if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
   1533         CXXBasePaths::paths_iterator FirstPath = Paths.begin();
   1534         DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
   1535         DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
   1536 
   1537         while (FirstD != FirstPath->Decls.end() &&
   1538                CurrentD != Path->Decls.end()) {
   1539          if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
   1540              (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
   1541            break;
   1542 
   1543           ++FirstD;
   1544           ++CurrentD;
   1545         }
   1546 
   1547         if (FirstD == FirstPath->Decls.end() &&
   1548             CurrentD == Path->Decls.end())
   1549           continue;
   1550       }
   1551 
   1552       R.setAmbiguousBaseSubobjectTypes(Paths);
   1553       return true;
   1554     }
   1555 
   1556     if (SubobjectNumber != PathElement.SubobjectNumber) {
   1557       // We have a different subobject of the same type.
   1558 
   1559       // C++ [class.member.lookup]p5:
   1560       //   A static member, a nested type or an enumerator defined in
   1561       //   a base class T can unambiguously be found even if an object
   1562       //   has more than one base class subobject of type T.
   1563       if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
   1564         continue;
   1565 
   1566       // We have found a nonstatic member name in multiple, distinct
   1567       // subobjects. Name lookup is ambiguous.
   1568       R.setAmbiguousBaseSubobjects(Paths);
   1569       return true;
   1570     }
   1571   }
   1572 
   1573   // Lookup in a base class succeeded; return these results.
   1574 
   1575   DeclContext::lookup_result DR = Paths.front().Decls;
   1576   for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
   1577     NamedDecl *D = *I;
   1578     AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
   1579                                                     D->getAccess());
   1580     R.addDecl(D, AS);
   1581   }
   1582   R.resolveKind();
   1583   return true;
   1584 }
   1585 
   1586 /// @brief Performs name lookup for a name that was parsed in the
   1587 /// source code, and may contain a C++ scope specifier.
   1588 ///
   1589 /// This routine is a convenience routine meant to be called from
   1590 /// contexts that receive a name and an optional C++ scope specifier
   1591 /// (e.g., "N::M::x"). It will then perform either qualified or
   1592 /// unqualified name lookup (with LookupQualifiedName or LookupName,
   1593 /// respectively) on the given name and return those results.
   1594 ///
   1595 /// @param S        The scope from which unqualified name lookup will
   1596 /// begin.
   1597 ///
   1598 /// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
   1599 ///
   1600 /// @param EnteringContext Indicates whether we are going to enter the
   1601 /// context of the scope-specifier SS (if present).
   1602 ///
   1603 /// @returns True if any decls were found (but possibly ambiguous)
   1604 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
   1605                             bool AllowBuiltinCreation, bool EnteringContext) {
   1606   if (SS && SS->isInvalid()) {
   1607     // When the scope specifier is invalid, don't even look for
   1608     // anything.
   1609     return false;
   1610   }
   1611 
   1612   if (SS && SS->isSet()) {
   1613     if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
   1614       // We have resolved the scope specifier to a particular declaration
   1615       // contex, and will perform name lookup in that context.
   1616       if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
   1617         return false;
   1618 
   1619       R.setContextRange(SS->getRange());
   1620       return LookupQualifiedName(R, DC);
   1621     }
   1622 
   1623     // We could not resolve the scope specified to a specific declaration
   1624     // context, which means that SS refers to an unknown specialization.
   1625     // Name lookup can't find anything in this case.
   1626     R.setNotFoundInCurrentInstantiation();
   1627     R.setContextRange(SS->getRange());
   1628     return false;
   1629   }
   1630 
   1631   // Perform unqualified name lookup starting in the given scope.
   1632   return LookupName(R, S, AllowBuiltinCreation);
   1633 }
   1634 
   1635 
   1636 /// \brief Produce a diagnostic describing the ambiguity that resulted
   1637 /// from name lookup.
   1638 ///
   1639 /// \param Result The result of the ambiguous lookup to be diagnosed.
   1640 ///
   1641 /// \returns true
   1642 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
   1643   assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
   1644 
   1645   DeclarationName Name = Result.getLookupName();
   1646   SourceLocation NameLoc = Result.getNameLoc();
   1647   SourceRange LookupRange = Result.getContextRange();
   1648 
   1649   switch (Result.getAmbiguityKind()) {
   1650   case LookupResult::AmbiguousBaseSubobjects: {
   1651     CXXBasePaths *Paths = Result.getBasePaths();
   1652     QualType SubobjectType = Paths->front().back().Base->getType();
   1653     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
   1654       << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
   1655       << LookupRange;
   1656 
   1657     DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
   1658     while (isa<CXXMethodDecl>(*Found) &&
   1659            cast<CXXMethodDecl>(*Found)->isStatic())
   1660       ++Found;
   1661 
   1662     Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
   1663 
   1664     return true;
   1665   }
   1666 
   1667   case LookupResult::AmbiguousBaseSubobjectTypes: {
   1668     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
   1669       << Name << LookupRange;
   1670 
   1671     CXXBasePaths *Paths = Result.getBasePaths();
   1672     std::set<Decl *> DeclsPrinted;
   1673     for (CXXBasePaths::paths_iterator Path = Paths->begin(),
   1674                                       PathEnd = Paths->end();
   1675          Path != PathEnd; ++Path) {
   1676       Decl *D = Path->Decls.front();
   1677       if (DeclsPrinted.insert(D).second)
   1678         Diag(D->getLocation(), diag::note_ambiguous_member_found);
   1679     }
   1680 
   1681     return true;
   1682   }
   1683 
   1684   case LookupResult::AmbiguousTagHiding: {
   1685     Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
   1686 
   1687     llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
   1688 
   1689     LookupResult::iterator DI, DE = Result.end();
   1690     for (DI = Result.begin(); DI != DE; ++DI)
   1691       if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
   1692         TagDecls.insert(TD);
   1693         Diag(TD->getLocation(), diag::note_hidden_tag);
   1694       }
   1695 
   1696     for (DI = Result.begin(); DI != DE; ++DI)
   1697       if (!isa<TagDecl>(*DI))
   1698         Diag((*DI)->getLocation(), diag::note_hiding_object);
   1699 
   1700     // For recovery purposes, go ahead and implement the hiding.
   1701     LookupResult::Filter F = Result.makeFilter();
   1702     while (F.hasNext()) {
   1703       if (TagDecls.count(F.next()))
   1704         F.erase();
   1705     }
   1706     F.done();
   1707 
   1708     return true;
   1709   }
   1710 
   1711   case LookupResult::AmbiguousReference: {
   1712     Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
   1713 
   1714     LookupResult::iterator DI = Result.begin(), DE = Result.end();
   1715     for (; DI != DE; ++DI)
   1716       Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
   1717 
   1718     return true;
   1719   }
   1720   }
   1721 
   1722   llvm_unreachable("unknown ambiguity kind");
   1723 }
   1724 
   1725 namespace {
   1726   struct AssociatedLookup {
   1727     AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
   1728                      Sema::AssociatedNamespaceSet &Namespaces,
   1729                      Sema::AssociatedClassSet &Classes)
   1730       : S(S), Namespaces(Namespaces), Classes(Classes),
   1731         InstantiationLoc(InstantiationLoc) {
   1732     }
   1733 
   1734     Sema &S;
   1735     Sema::AssociatedNamespaceSet &Namespaces;
   1736     Sema::AssociatedClassSet &Classes;
   1737     SourceLocation InstantiationLoc;
   1738   };
   1739 }
   1740 
   1741 static void
   1742 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
   1743 
   1744 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
   1745                                       DeclContext *Ctx) {
   1746   // Add the associated namespace for this class.
   1747 
   1748   // We don't use DeclContext::getEnclosingNamespaceContext() as this may
   1749   // be a locally scoped record.
   1750 
   1751   // We skip out of inline namespaces. The innermost non-inline namespace
   1752   // contains all names of all its nested inline namespaces anyway, so we can
   1753   // replace the entire inline namespace tree with its root.
   1754   while (Ctx->isRecord() || Ctx->isTransparentContext() ||
   1755          Ctx->isInlineNamespace())
   1756     Ctx = Ctx->getParent();
   1757 
   1758   if (Ctx->isFileContext())
   1759     Namespaces.insert(Ctx->getPrimaryContext());
   1760 }
   1761 
   1762 // \brief Add the associated classes and namespaces for argument-dependent
   1763 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
   1764 static void
   1765 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
   1766                                   const TemplateArgument &Arg) {
   1767   // C++ [basic.lookup.koenig]p2, last bullet:
   1768   //   -- [...] ;
   1769   switch (Arg.getKind()) {
   1770     case TemplateArgument::Null:
   1771       break;
   1772 
   1773     case TemplateArgument::Type:
   1774       // [...] the namespaces and classes associated with the types of the
   1775       // template arguments provided for template type parameters (excluding
   1776       // template template parameters)
   1777       addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
   1778       break;
   1779 
   1780     case TemplateArgument::Template:
   1781     case TemplateArgument::TemplateExpansion: {
   1782       // [...] the namespaces in which any template template arguments are
   1783       // defined; and the classes in which any member templates used as
   1784       // template template arguments are defined.
   1785       TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
   1786       if (ClassTemplateDecl *ClassTemplate
   1787                  = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
   1788         DeclContext *Ctx = ClassTemplate->getDeclContext();
   1789         if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
   1790           Result.Classes.insert(EnclosingClass);
   1791         // Add the associated namespace for this class.
   1792         CollectEnclosingNamespace(Result.Namespaces, Ctx);
   1793       }
   1794       break;
   1795     }
   1796 
   1797     case TemplateArgument::Declaration:
   1798     case TemplateArgument::Integral:
   1799     case TemplateArgument::Expression:
   1800     case TemplateArgument::NullPtr:
   1801       // [Note: non-type template arguments do not contribute to the set of
   1802       //  associated namespaces. ]
   1803       break;
   1804 
   1805     case TemplateArgument::Pack:
   1806       for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
   1807                                         PEnd = Arg.pack_end();
   1808            P != PEnd; ++P)
   1809         addAssociatedClassesAndNamespaces(Result, *P);
   1810       break;
   1811   }
   1812 }
   1813 
   1814 // \brief Add the associated classes and namespaces for
   1815 // argument-dependent lookup with an argument of class type
   1816 // (C++ [basic.lookup.koenig]p2).
   1817 static void
   1818 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
   1819                                   CXXRecordDecl *Class) {
   1820 
   1821   // Just silently ignore anything whose name is __va_list_tag.
   1822   if (Class->getDeclName() == Result.S.VAListTagName)
   1823     return;
   1824 
   1825   // C++ [basic.lookup.koenig]p2:
   1826   //   [...]
   1827   //     -- If T is a class type (including unions), its associated
   1828   //        classes are: the class itself; the class of which it is a
   1829   //        member, if any; and its direct and indirect base
   1830   //        classes. Its associated namespaces are the namespaces in
   1831   //        which its associated classes are defined.
   1832 
   1833   // Add the class of which it is a member, if any.
   1834   DeclContext *Ctx = Class->getDeclContext();
   1835   if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
   1836     Result.Classes.insert(EnclosingClass);
   1837   // Add the associated namespace for this class.
   1838   CollectEnclosingNamespace(Result.Namespaces, Ctx);
   1839 
   1840   // Add the class itself. If we've already seen this class, we don't
   1841   // need to visit base classes.
   1842   if (!Result.Classes.insert(Class))
   1843     return;
   1844 
   1845   // -- If T is a template-id, its associated namespaces and classes are
   1846   //    the namespace in which the template is defined; for member
   1847   //    templates, the member template's class; the namespaces and classes
   1848   //    associated with the types of the template arguments provided for
   1849   //    template type parameters (excluding template template parameters); the
   1850   //    namespaces in which any template template arguments are defined; and
   1851   //    the classes in which any member templates used as template template
   1852   //    arguments are defined. [Note: non-type template arguments do not
   1853   //    contribute to the set of associated namespaces. ]
   1854   if (ClassTemplateSpecializationDecl *Spec
   1855         = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
   1856     DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
   1857     if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
   1858       Result.Classes.insert(EnclosingClass);
   1859     // Add the associated namespace for this class.
   1860     CollectEnclosingNamespace(Result.Namespaces, Ctx);
   1861 
   1862     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
   1863     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
   1864       addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
   1865   }
   1866 
   1867   // Only recurse into base classes for complete types.
   1868   if (!Class->hasDefinition()) {
   1869     QualType type = Result.S.Context.getTypeDeclType(Class);
   1870     if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
   1871                                      /*no diagnostic*/ 0))
   1872       return;
   1873   }
   1874 
   1875   // Add direct and indirect base classes along with their associated
   1876   // namespaces.
   1877   SmallVector<CXXRecordDecl *, 32> Bases;
   1878   Bases.push_back(Class);
   1879   while (!Bases.empty()) {
   1880     // Pop this class off the stack.
   1881     Class = Bases.back();
   1882     Bases.pop_back();
   1883 
   1884     // Visit the base classes.
   1885     for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
   1886                                          BaseEnd = Class->bases_end();
   1887          Base != BaseEnd; ++Base) {
   1888       const RecordType *BaseType = Base->getType()->getAs<RecordType>();
   1889       // In dependent contexts, we do ADL twice, and the first time around,
   1890       // the base type might be a dependent TemplateSpecializationType, or a
   1891       // TemplateTypeParmType. If that happens, simply ignore it.
   1892       // FIXME: If we want to support export, we probably need to add the
   1893       // namespace of the template in a TemplateSpecializationType, or even
   1894       // the classes and namespaces of known non-dependent arguments.
   1895       if (!BaseType)
   1896         continue;
   1897       CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   1898       if (Result.Classes.insert(BaseDecl)) {
   1899         // Find the associated namespace for this base class.
   1900         DeclContext *BaseCtx = BaseDecl->getDeclContext();
   1901         CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
   1902 
   1903         // Make sure we visit the bases of this base class.
   1904         if (BaseDecl->bases_begin() != BaseDecl->bases_end())
   1905           Bases.push_back(BaseDecl);
   1906       }
   1907     }
   1908   }
   1909 }
   1910 
   1911 // \brief Add the associated classes and namespaces for
   1912 // argument-dependent lookup with an argument of type T
   1913 // (C++ [basic.lookup.koenig]p2).
   1914 static void
   1915 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
   1916   // C++ [basic.lookup.koenig]p2:
   1917   //
   1918   //   For each argument type T in the function call, there is a set
   1919   //   of zero or more associated namespaces and a set of zero or more
   1920   //   associated classes to be considered. The sets of namespaces and
   1921   //   classes is determined entirely by the types of the function
   1922   //   arguments (and the namespace of any template template
   1923   //   argument). Typedef names and using-declarations used to specify
   1924   //   the types do not contribute to this set. The sets of namespaces
   1925   //   and classes are determined in the following way:
   1926 
   1927   SmallVector<const Type *, 16> Queue;
   1928   const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
   1929 
   1930   while (true) {
   1931     switch (T->getTypeClass()) {
   1932 
   1933 #define TYPE(Class, Base)
   1934 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
   1935 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
   1936 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
   1937 #define ABSTRACT_TYPE(Class, Base)
   1938 #include "clang/AST/TypeNodes.def"
   1939       // T is canonical.  We can also ignore dependent types because
   1940       // we don't need to do ADL at the definition point, but if we
   1941       // wanted to implement template export (or if we find some other
   1942       // use for associated classes and namespaces...) this would be
   1943       // wrong.
   1944       break;
   1945 
   1946     //    -- If T is a pointer to U or an array of U, its associated
   1947     //       namespaces and classes are those associated with U.
   1948     case Type::Pointer:
   1949       T = cast<PointerType>(T)->getPointeeType().getTypePtr();
   1950       continue;
   1951     case Type::ConstantArray:
   1952     case Type::IncompleteArray:
   1953     case Type::VariableArray:
   1954       T = cast<ArrayType>(T)->getElementType().getTypePtr();
   1955       continue;
   1956 
   1957     //     -- If T is a fundamental type, its associated sets of
   1958     //        namespaces and classes are both empty.
   1959     case Type::Builtin:
   1960       break;
   1961 
   1962     //     -- If T is a class type (including unions), its associated
   1963     //        classes are: the class itself; the class of which it is a
   1964     //        member, if any; and its direct and indirect base
   1965     //        classes. Its associated namespaces are the namespaces in
   1966     //        which its associated classes are defined.
   1967     case Type::Record: {
   1968       CXXRecordDecl *Class
   1969         = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
   1970       addAssociatedClassesAndNamespaces(Result, Class);
   1971       break;
   1972     }
   1973 
   1974     //     -- If T is an enumeration type, its associated namespace is
   1975     //        the namespace in which it is defined. If it is class
   1976     //        member, its associated class is the member's class; else
   1977     //        it has no associated class.
   1978     case Type::Enum: {
   1979       EnumDecl *Enum = cast<EnumType>(T)->getDecl();
   1980 
   1981       DeclContext *Ctx = Enum->getDeclContext();
   1982       if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
   1983         Result.Classes.insert(EnclosingClass);
   1984 
   1985       // Add the associated namespace for this class.
   1986       CollectEnclosingNamespace(Result.Namespaces, Ctx);
   1987 
   1988       break;
   1989     }
   1990 
   1991     //     -- If T is a function type, its associated namespaces and
   1992     //        classes are those associated with the function parameter
   1993     //        types and those associated with the return type.
   1994     case Type::FunctionProto: {
   1995       const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
   1996       for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
   1997                                              ArgEnd = Proto->arg_type_end();
   1998              Arg != ArgEnd; ++Arg)
   1999         Queue.push_back(Arg->getTypePtr());
   2000       // fallthrough
   2001     }
   2002     case Type::FunctionNoProto: {
   2003       const FunctionType *FnType = cast<FunctionType>(T);
   2004       T = FnType->getResultType().getTypePtr();
   2005       continue;
   2006     }
   2007 
   2008     //     -- If T is a pointer to a member function of a class X, its
   2009     //        associated namespaces and classes are those associated
   2010     //        with the function parameter types and return type,
   2011     //        together with those associated with X.
   2012     //
   2013     //     -- If T is a pointer to a data member of class X, its
   2014     //        associated namespaces and classes are those associated
   2015     //        with the member type together with those associated with
   2016     //        X.
   2017     case Type::MemberPointer: {
   2018       const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
   2019 
   2020       // Queue up the class type into which this points.
   2021       Queue.push_back(MemberPtr->getClass());
   2022 
   2023       // And directly continue with the pointee type.
   2024       T = MemberPtr->getPointeeType().getTypePtr();
   2025       continue;
   2026     }
   2027 
   2028     // As an extension, treat this like a normal pointer.
   2029     case Type::BlockPointer:
   2030       T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
   2031       continue;
   2032 
   2033     // References aren't covered by the standard, but that's such an
   2034     // obvious defect that we cover them anyway.
   2035     case Type::LValueReference:
   2036     case Type::RValueReference:
   2037       T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
   2038       continue;
   2039 
   2040     // These are fundamental types.
   2041     case Type::Vector:
   2042     case Type::ExtVector:
   2043     case Type::Complex:
   2044       break;
   2045 
   2046     // If T is an Objective-C object or interface type, or a pointer to an
   2047     // object or interface type, the associated namespace is the global
   2048     // namespace.
   2049     case Type::ObjCObject:
   2050     case Type::ObjCInterface:
   2051     case Type::ObjCObjectPointer:
   2052       Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
   2053       break;
   2054 
   2055     // Atomic types are just wrappers; use the associations of the
   2056     // contained type.
   2057     case Type::Atomic:
   2058       T = cast<AtomicType>(T)->getValueType().getTypePtr();
   2059       continue;
   2060     }
   2061 
   2062     if (Queue.empty()) break;
   2063     T = Queue.back();
   2064     Queue.pop_back();
   2065   }
   2066 }
   2067 
   2068 /// \brief Find the associated classes and namespaces for
   2069 /// argument-dependent lookup for a call with the given set of
   2070 /// arguments.
   2071 ///
   2072 /// This routine computes the sets of associated classes and associated
   2073 /// namespaces searched by argument-dependent lookup
   2074 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
   2075 void
   2076 Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
   2077                                          llvm::ArrayRef<Expr *> Args,
   2078                                  AssociatedNamespaceSet &AssociatedNamespaces,
   2079                                  AssociatedClassSet &AssociatedClasses) {
   2080   AssociatedNamespaces.clear();
   2081   AssociatedClasses.clear();
   2082 
   2083   AssociatedLookup Result(*this, InstantiationLoc,
   2084                           AssociatedNamespaces, AssociatedClasses);
   2085 
   2086   // C++ [basic.lookup.koenig]p2:
   2087   //   For each argument type T in the function call, there is a set
   2088   //   of zero or more associated namespaces and a set of zero or more
   2089   //   associated classes to be considered. The sets of namespaces and
   2090   //   classes is determined entirely by the types of the function
   2091   //   arguments (and the namespace of any template template
   2092   //   argument).
   2093   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
   2094     Expr *Arg = Args[ArgIdx];
   2095 
   2096     if (Arg->getType() != Context.OverloadTy) {
   2097       addAssociatedClassesAndNamespaces(Result, Arg->getType());
   2098       continue;
   2099     }
   2100 
   2101     // [...] In addition, if the argument is the name or address of a
   2102     // set of overloaded functions and/or function templates, its
   2103     // associated classes and namespaces are the union of those
   2104     // associated with each of the members of the set: the namespace
   2105     // in which the function or function template is defined and the
   2106     // classes and namespaces associated with its (non-dependent)
   2107     // parameter types and return type.
   2108     Arg = Arg->IgnoreParens();
   2109     if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
   2110       if (unaryOp->getOpcode() == UO_AddrOf)
   2111         Arg = unaryOp->getSubExpr();
   2112 
   2113     UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
   2114     if (!ULE) continue;
   2115 
   2116     for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
   2117            I != E; ++I) {
   2118       // Look through any using declarations to find the underlying function.
   2119       NamedDecl *Fn = (*I)->getUnderlyingDecl();
   2120 
   2121       FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
   2122       if (!FDecl)
   2123         FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
   2124 
   2125       // Add the classes and namespaces associated with the parameter
   2126       // types and return type of this function.
   2127       addAssociatedClassesAndNamespaces(Result, FDecl->getType());
   2128     }
   2129   }
   2130 }
   2131 
   2132 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
   2133 /// an acceptable non-member overloaded operator for a call whose
   2134 /// arguments have types T1 (and, if non-empty, T2). This routine
   2135 /// implements the check in C++ [over.match.oper]p3b2 concerning
   2136 /// enumeration types.
   2137 static bool
   2138 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
   2139                                        QualType T1, QualType T2,
   2140                                        ASTContext &Context) {
   2141   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
   2142     return true;
   2143 
   2144   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
   2145     return true;
   2146 
   2147   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
   2148   if (Proto->getNumArgs() < 1)
   2149     return false;
   2150 
   2151   if (T1->isEnumeralType()) {
   2152     QualType ArgType = Proto->getArgType(0).getNonReferenceType();
   2153     if (Context.hasSameUnqualifiedType(T1, ArgType))
   2154       return true;
   2155   }
   2156 
   2157   if (Proto->getNumArgs() < 2)
   2158     return false;
   2159 
   2160   if (!T2.isNull() && T2->isEnumeralType()) {
   2161     QualType ArgType = Proto->getArgType(1).getNonReferenceType();
   2162     if (Context.hasSameUnqualifiedType(T2, ArgType))
   2163       return true;
   2164   }
   2165 
   2166   return false;
   2167 }
   2168 
   2169 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
   2170                                   SourceLocation Loc,
   2171                                   LookupNameKind NameKind,
   2172                                   RedeclarationKind Redecl) {
   2173   LookupResult R(*this, Name, Loc, NameKind, Redecl);
   2174   LookupName(R, S);
   2175   return R.getAsSingle<NamedDecl>();
   2176 }
   2177 
   2178 /// \brief Find the protocol with the given name, if any.
   2179 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
   2180                                        SourceLocation IdLoc,
   2181                                        RedeclarationKind Redecl) {
   2182   Decl *D = LookupSingleName(TUScope, II, IdLoc,
   2183                              LookupObjCProtocolName, Redecl);
   2184   return cast_or_null<ObjCProtocolDecl>(D);
   2185 }
   2186 
   2187 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
   2188                                         QualType T1, QualType T2,
   2189                                         UnresolvedSetImpl &Functions) {
   2190   // C++ [over.match.oper]p3:
   2191   //     -- The set of non-member candidates is the result of the
   2192   //        unqualified lookup of operator@ in the context of the
   2193   //        expression according to the usual rules for name lookup in
   2194   //        unqualified function calls (3.4.2) except that all member
   2195   //        functions are ignored. However, if no operand has a class
   2196   //        type, only those non-member functions in the lookup set
   2197   //        that have a first parameter of type T1 or "reference to
   2198   //        (possibly cv-qualified) T1", when T1 is an enumeration
   2199   //        type, or (if there is a right operand) a second parameter
   2200   //        of type T2 or "reference to (possibly cv-qualified) T2",
   2201   //        when T2 is an enumeration type, are candidate functions.
   2202   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
   2203   LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
   2204   LookupName(Operators, S);
   2205 
   2206   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
   2207 
   2208   if (Operators.empty())
   2209     return;
   2210 
   2211   for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
   2212        Op != OpEnd; ++Op) {
   2213     NamedDecl *Found = (*Op)->getUnderlyingDecl();
   2214     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
   2215       if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
   2216         Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
   2217     } else if (FunctionTemplateDecl *FunTmpl
   2218                  = dyn_cast<FunctionTemplateDecl>(Found)) {
   2219       // FIXME: friend operators?
   2220       // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
   2221       // later?
   2222       if (!FunTmpl->getDeclContext()->isRecord())
   2223         Functions.addDecl(*Op, Op.getAccess());
   2224     }
   2225   }
   2226 }
   2227 
   2228 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
   2229                                                             CXXSpecialMember SM,
   2230                                                             bool ConstArg,
   2231                                                             bool VolatileArg,
   2232                                                             bool RValueThis,
   2233                                                             bool ConstThis,
   2234                                                             bool VolatileThis) {
   2235   assert(CanDeclareSpecialMemberFunction(RD) &&
   2236          "doing special member lookup into record that isn't fully complete");
   2237   RD = RD->getDefinition();
   2238   if (RValueThis || ConstThis || VolatileThis)
   2239     assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
   2240            "constructors and destructors always have unqualified lvalue this");
   2241   if (ConstArg || VolatileArg)
   2242     assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
   2243            "parameter-less special members can't have qualified arguments");
   2244 
   2245   llvm::FoldingSetNodeID ID;
   2246   ID.AddPointer(RD);
   2247   ID.AddInteger(SM);
   2248   ID.AddInteger(ConstArg);
   2249   ID.AddInteger(VolatileArg);
   2250   ID.AddInteger(RValueThis);
   2251   ID.AddInteger(ConstThis);
   2252   ID.AddInteger(VolatileThis);
   2253 
   2254   void *InsertPoint;
   2255   SpecialMemberOverloadResult *Result =
   2256     SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
   2257 
   2258   // This was already cached
   2259   if (Result)
   2260     return Result;
   2261 
   2262   Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
   2263   Result = new (Result) SpecialMemberOverloadResult(ID);
   2264   SpecialMemberCache.InsertNode(Result, InsertPoint);
   2265 
   2266   if (SM == CXXDestructor) {
   2267     if (RD->needsImplicitDestructor())
   2268       DeclareImplicitDestructor(RD);
   2269     CXXDestructorDecl *DD = RD->getDestructor();
   2270     assert(DD && "record without a destructor");
   2271     Result->setMethod(DD);
   2272     Result->setKind(DD->isDeleted() ?
   2273                     SpecialMemberOverloadResult::NoMemberOrDeleted :
   2274                     SpecialMemberOverloadResult::Success);
   2275     return Result;
   2276   }
   2277 
   2278   // Prepare for overload resolution. Here we construct a synthetic argument
   2279   // if necessary and make sure that implicit functions are declared.
   2280   CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
   2281   DeclarationName Name;
   2282   Expr *Arg = 0;
   2283   unsigned NumArgs;
   2284 
   2285   QualType ArgType = CanTy;
   2286   ExprValueKind VK = VK_LValue;
   2287 
   2288   if (SM == CXXDefaultConstructor) {
   2289     Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
   2290     NumArgs = 0;
   2291     if (RD->needsImplicitDefaultConstructor())
   2292       DeclareImplicitDefaultConstructor(RD);
   2293   } else {
   2294     if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
   2295       Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
   2296       if (RD->needsImplicitCopyConstructor())
   2297         DeclareImplicitCopyConstructor(RD);
   2298       if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
   2299         DeclareImplicitMoveConstructor(RD);
   2300     } else {
   2301       Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
   2302       if (RD->needsImplicitCopyAssignment())
   2303         DeclareImplicitCopyAssignment(RD);
   2304       if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
   2305         DeclareImplicitMoveAssignment(RD);
   2306     }
   2307 
   2308     if (ConstArg)
   2309       ArgType.addConst();
   2310     if (VolatileArg)
   2311       ArgType.addVolatile();
   2312 
   2313     // This isn't /really/ specified by the standard, but it's implied
   2314     // we should be working from an RValue in the case of move to ensure
   2315     // that we prefer to bind to rvalue references, and an LValue in the
   2316     // case of copy to ensure we don't bind to rvalue references.
   2317     // Possibly an XValue is actually correct in the case of move, but
   2318     // there is no semantic difference for class types in this restricted
   2319     // case.
   2320     if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
   2321       VK = VK_LValue;
   2322     else
   2323       VK = VK_RValue;
   2324   }
   2325 
   2326   OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
   2327 
   2328   if (SM != CXXDefaultConstructor) {
   2329     NumArgs = 1;
   2330     Arg = &FakeArg;
   2331   }
   2332 
   2333   // Create the object argument
   2334   QualType ThisTy = CanTy;
   2335   if (ConstThis)
   2336     ThisTy.addConst();
   2337   if (VolatileThis)
   2338     ThisTy.addVolatile();
   2339   Expr::Classification Classification =
   2340     OpaqueValueExpr(SourceLocation(), ThisTy,
   2341                     RValueThis ? VK_RValue : VK_LValue).Classify(Context);
   2342 
   2343   // Now we perform lookup on the name we computed earlier and do overload
   2344   // resolution. Lookup is only performed directly into the class since there
   2345   // will always be a (possibly implicit) declaration to shadow any others.
   2346   OverloadCandidateSet OCS((SourceLocation()));
   2347   DeclContext::lookup_result R = RD->lookup(Name);
   2348 
   2349   assert(!R.empty() &&
   2350          "lookup for a constructor or assignment operator was empty");
   2351   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
   2352     Decl *Cand = *I;
   2353 
   2354     if (Cand->isInvalidDecl())
   2355       continue;
   2356 
   2357     if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
   2358       // FIXME: [namespace.udecl]p15 says that we should only consider a
   2359       // using declaration here if it does not match a declaration in the
   2360       // derived class. We do not implement this correctly in other cases
   2361       // either.
   2362       Cand = U->getTargetDecl();
   2363 
   2364       if (Cand->isInvalidDecl())
   2365         continue;
   2366     }
   2367 
   2368     if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
   2369       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
   2370         AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
   2371                            Classification, llvm::makeArrayRef(&Arg, NumArgs),
   2372                            OCS, true);
   2373       else
   2374         AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
   2375                              llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
   2376     } else if (FunctionTemplateDecl *Tmpl =
   2377                  dyn_cast<FunctionTemplateDecl>(Cand)) {
   2378       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
   2379         AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
   2380                                    RD, 0, ThisTy, Classification,
   2381                                    llvm::makeArrayRef(&Arg, NumArgs),
   2382                                    OCS, true);
   2383       else
   2384         AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
   2385                                      0, llvm::makeArrayRef(&Arg, NumArgs),
   2386                                      OCS, true);
   2387     } else {
   2388       assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
   2389     }
   2390   }
   2391 
   2392   OverloadCandidateSet::iterator Best;
   2393   switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
   2394     case OR_Success:
   2395       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
   2396       Result->setKind(SpecialMemberOverloadResult::Success);
   2397       break;
   2398 
   2399     case OR_Deleted:
   2400       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
   2401       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
   2402       break;
   2403 
   2404     case OR_Ambiguous:
   2405       Result->setMethod(0);
   2406       Result->setKind(SpecialMemberOverloadResult::Ambiguous);
   2407       break;
   2408 
   2409     case OR_No_Viable_Function:
   2410       Result->setMethod(0);
   2411       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
   2412       break;
   2413   }
   2414 
   2415   return Result;
   2416 }
   2417 
   2418 /// \brief Look up the default constructor for the given class.
   2419 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
   2420   SpecialMemberOverloadResult *Result =
   2421     LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
   2422                         false, false);
   2423 
   2424   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
   2425 }
   2426 
   2427 /// \brief Look up the copying constructor for the given class.
   2428 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
   2429                                                    unsigned Quals) {
   2430   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
   2431          "non-const, non-volatile qualifiers for copy ctor arg");
   2432   SpecialMemberOverloadResult *Result =
   2433     LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
   2434                         Quals & Qualifiers::Volatile, false, false, false);
   2435 
   2436   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
   2437 }
   2438 
   2439 /// \brief Look up the moving constructor for the given class.
   2440 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
   2441                                                   unsigned Quals) {
   2442   SpecialMemberOverloadResult *Result =
   2443     LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
   2444                         Quals & Qualifiers::Volatile, false, false, false);
   2445 
   2446   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
   2447 }
   2448 
   2449 /// \brief Look up the constructors for the given class.
   2450 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
   2451   // If the implicit constructors have not yet been declared, do so now.
   2452   if (CanDeclareSpecialMemberFunction(Class)) {
   2453     if (Class->needsImplicitDefaultConstructor())
   2454       DeclareImplicitDefaultConstructor(Class);
   2455     if (Class->needsImplicitCopyConstructor())
   2456       DeclareImplicitCopyConstructor(Class);
   2457     if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
   2458       DeclareImplicitMoveConstructor(Class);
   2459   }
   2460 
   2461   CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
   2462   DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
   2463   return Class->lookup(Name);
   2464 }
   2465 
   2466 /// \brief Look up the copying assignment operator for the given class.
   2467 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
   2468                                              unsigned Quals, bool RValueThis,
   2469                                              unsigned ThisQuals) {
   2470   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
   2471          "non-const, non-volatile qualifiers for copy assignment arg");
   2472   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
   2473          "non-const, non-volatile qualifiers for copy assignment this");
   2474   SpecialMemberOverloadResult *Result =
   2475     LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
   2476                         Quals & Qualifiers::Volatile, RValueThis,
   2477                         ThisQuals & Qualifiers::Const,
   2478                         ThisQuals & Qualifiers::Volatile);
   2479 
   2480   return Result->getMethod();
   2481 }
   2482 
   2483 /// \brief Look up the moving assignment operator for the given class.
   2484 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
   2485                                             unsigned Quals,
   2486                                             bool RValueThis,
   2487                                             unsigned ThisQuals) {
   2488   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
   2489          "non-const, non-volatile qualifiers for copy assignment this");
   2490   SpecialMemberOverloadResult *Result =
   2491     LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
   2492                         Quals & Qualifiers::Volatile, RValueThis,
   2493                         ThisQuals & Qualifiers::Const,
   2494                         ThisQuals & Qualifiers::Volatile);
   2495 
   2496   return Result->getMethod();
   2497 }
   2498 
   2499 /// \brief Look for the destructor of the given class.
   2500 ///
   2501 /// During semantic analysis, this routine should be used in lieu of
   2502 /// CXXRecordDecl::getDestructor().
   2503 ///
   2504 /// \returns The destructor for this class.
   2505 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
   2506   return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
   2507                                                      false, false, false,
   2508                                                      false, false)->getMethod());
   2509 }
   2510 
   2511 /// LookupLiteralOperator - Determine which literal operator should be used for
   2512 /// a user-defined literal, per C++11 [lex.ext].
   2513 ///
   2514 /// Normal overload resolution is not used to select which literal operator to
   2515 /// call for a user-defined literal. Look up the provided literal operator name,
   2516 /// and filter the results to the appropriate set for the given argument types.
   2517 Sema::LiteralOperatorLookupResult
   2518 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
   2519                             ArrayRef<QualType> ArgTys,
   2520                             bool AllowRawAndTemplate) {
   2521   LookupName(R, S);
   2522   assert(R.getResultKind() != LookupResult::Ambiguous &&
   2523          "literal operator lookup can't be ambiguous");
   2524 
   2525   // Filter the lookup results appropriately.
   2526   LookupResult::Filter F = R.makeFilter();
   2527 
   2528   bool FoundTemplate = false;
   2529   bool FoundRaw = false;
   2530   bool FoundExactMatch = false;
   2531 
   2532   while (F.hasNext()) {
   2533     Decl *D = F.next();
   2534     if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
   2535       D = USD->getTargetDecl();
   2536 
   2537     bool IsTemplate = isa<FunctionTemplateDecl>(D);
   2538     bool IsRaw = false;
   2539     bool IsExactMatch = false;
   2540 
   2541     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   2542       if (FD->getNumParams() == 1 &&
   2543           FD->getParamDecl(0)->getType()->getAs<PointerType>())
   2544         IsRaw = true;
   2545       else if (FD->getNumParams() == ArgTys.size()) {
   2546         IsExactMatch = true;
   2547         for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
   2548           QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
   2549           if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
   2550             IsExactMatch = false;
   2551             break;
   2552           }
   2553         }
   2554       }
   2555     }
   2556 
   2557     if (IsExactMatch) {
   2558       FoundExactMatch = true;
   2559       AllowRawAndTemplate = false;
   2560       if (FoundRaw || FoundTemplate) {
   2561         // Go through again and remove the raw and template decls we've
   2562         // already found.
   2563         F.restart();
   2564         FoundRaw = FoundTemplate = false;
   2565       }
   2566     } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
   2567       FoundTemplate |= IsTemplate;
   2568       FoundRaw |= IsRaw;
   2569     } else {
   2570       F.erase();
   2571     }
   2572   }
   2573 
   2574   F.done();
   2575 
   2576   // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
   2577   // parameter type, that is used in preference to a raw literal operator
   2578   // or literal operator template.
   2579   if (FoundExactMatch)
   2580     return LOLR_Cooked;
   2581 
   2582   // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
   2583   // operator template, but not both.
   2584   if (FoundRaw && FoundTemplate) {
   2585     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
   2586     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
   2587       Decl *D = *I;
   2588       if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
   2589         D = USD->getTargetDecl();
   2590       if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
   2591         D = FunTmpl->getTemplatedDecl();
   2592       NoteOverloadCandidate(cast<FunctionDecl>(D));
   2593     }
   2594     return LOLR_Error;
   2595   }
   2596 
   2597   if (FoundRaw)
   2598     return LOLR_Raw;
   2599 
   2600   if (FoundTemplate)
   2601     return LOLR_Template;
   2602 
   2603   // Didn't find anything we could use.
   2604   Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
   2605     << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
   2606     << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
   2607   return LOLR_Error;
   2608 }
   2609 
   2610 void ADLResult::insert(NamedDecl *New) {
   2611   NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
   2612 
   2613   // If we haven't yet seen a decl for this key, or the last decl
   2614   // was exactly this one, we're done.
   2615   if (Old == 0 || Old == New) {
   2616     Old = New;
   2617     return;
   2618   }
   2619 
   2620   // Otherwise, decide which is a more recent redeclaration.
   2621   FunctionDecl *OldFD, *NewFD;
   2622   if (isa<FunctionTemplateDecl>(New)) {
   2623     OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
   2624     NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
   2625   } else {
   2626     OldFD = cast<FunctionDecl>(Old);
   2627     NewFD = cast<FunctionDecl>(New);
   2628   }
   2629 
   2630   FunctionDecl *Cursor = NewFD;
   2631   while (true) {
   2632     Cursor = Cursor->getPreviousDecl();
   2633 
   2634     // If we got to the end without finding OldFD, OldFD is the newer
   2635     // declaration;  leave things as they are.
   2636     if (!Cursor) return;
   2637 
   2638     // If we do find OldFD, then NewFD is newer.
   2639     if (Cursor == OldFD) break;
   2640 
   2641     // Otherwise, keep looking.
   2642   }
   2643 
   2644   Old = New;
   2645 }
   2646 
   2647 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
   2648                                    SourceLocation Loc,
   2649                                    llvm::ArrayRef<Expr *> Args,
   2650                                    ADLResult &Result) {
   2651   // Find all of the associated namespaces and classes based on the
   2652   // arguments we have.
   2653   AssociatedNamespaceSet AssociatedNamespaces;
   2654   AssociatedClassSet AssociatedClasses;
   2655   FindAssociatedClassesAndNamespaces(Loc, Args,
   2656                                      AssociatedNamespaces,
   2657                                      AssociatedClasses);
   2658 
   2659   QualType T1, T2;
   2660   if (Operator) {
   2661     T1 = Args[0]->getType();
   2662     if (Args.size() >= 2)
   2663       T2 = Args[1]->getType();
   2664   }
   2665 
   2666   // C++ [basic.lookup.argdep]p3:
   2667   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
   2668   //   and let Y be the lookup set produced by argument dependent
   2669   //   lookup (defined as follows). If X contains [...] then Y is
   2670   //   empty. Otherwise Y is the set of declarations found in the
   2671   //   namespaces associated with the argument types as described
   2672   //   below. The set of declarations found by the lookup of the name
   2673   //   is the union of X and Y.
   2674   //
   2675   // Here, we compute Y and add its members to the overloaded
   2676   // candidate set.
   2677   for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
   2678                                      NSEnd = AssociatedNamespaces.end();
   2679        NS != NSEnd; ++NS) {
   2680     //   When considering an associated namespace, the lookup is the
   2681     //   same as the lookup performed when the associated namespace is
   2682     //   used as a qualifier (3.4.3.2) except that:
   2683     //
   2684     //     -- Any using-directives in the associated namespace are
   2685     //        ignored.
   2686     //
   2687     //     -- Any namespace-scope friend functions declared in
   2688     //        associated classes are visible within their respective
   2689     //        namespaces even if they are not visible during an ordinary
   2690     //        lookup (11.4).
   2691     DeclContext::lookup_result R = (*NS)->lookup(Name);
   2692     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
   2693          ++I) {
   2694       NamedDecl *D = *I;
   2695       // If the only declaration here is an ordinary friend, consider
   2696       // it only if it was declared in an associated classes.
   2697       if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
   2698         DeclContext *LexDC = D->getLexicalDeclContext();
   2699         if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
   2700           continue;
   2701       }
   2702 
   2703       if (isa<UsingShadowDecl>(D))
   2704         D = cast<UsingShadowDecl>(D)->getTargetDecl();
   2705 
   2706       if (isa<FunctionDecl>(D)) {
   2707         if (Operator &&
   2708             !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
   2709                                                     T1, T2, Context))
   2710           continue;
   2711       } else if (!isa<FunctionTemplateDecl>(D))
   2712         continue;
   2713 
   2714       Result.insert(D);
   2715     }
   2716   }
   2717 }
   2718 
   2719 //----------------------------------------------------------------------------
   2720 // Search for all visible declarations.
   2721 //----------------------------------------------------------------------------
   2722 VisibleDeclConsumer::~VisibleDeclConsumer() { }
   2723 
   2724 namespace {
   2725 
   2726 class ShadowContextRAII;
   2727 
   2728 class VisibleDeclsRecord {
   2729 public:
   2730   /// \brief An entry in the shadow map, which is optimized to store a
   2731   /// single declaration (the common case) but can also store a list
   2732   /// of declarations.
   2733   typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
   2734 
   2735 private:
   2736   /// \brief A mapping from declaration names to the declarations that have
   2737   /// this name within a particular scope.
   2738   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
   2739 
   2740   /// \brief A list of shadow maps, which is used to model name hiding.
   2741   std::list<ShadowMap> ShadowMaps;
   2742 
   2743   /// \brief The declaration contexts we have already visited.
   2744   llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
   2745 
   2746   friend class ShadowContextRAII;
   2747 
   2748 public:
   2749   /// \brief Determine whether we have already visited this context
   2750   /// (and, if not, note that we are going to visit that context now).
   2751   bool visitedContext(DeclContext *Ctx) {
   2752     return !VisitedContexts.insert(Ctx);
   2753   }
   2754 
   2755   bool alreadyVisitedContext(DeclContext *Ctx) {
   2756     return VisitedContexts.count(Ctx);
   2757   }
   2758 
   2759   /// \brief Determine whether the given declaration is hidden in the
   2760   /// current scope.
   2761   ///
   2762   /// \returns the declaration that hides the given declaration, or
   2763   /// NULL if no such declaration exists.
   2764   NamedDecl *checkHidden(NamedDecl *ND);
   2765 
   2766   /// \brief Add a declaration to the current shadow map.
   2767   void add(NamedDecl *ND) {
   2768     ShadowMaps.back()[ND->getDeclName()].push_back(ND);
   2769   }
   2770 };
   2771 
   2772 /// \brief RAII object that records when we've entered a shadow context.
   2773 class ShadowContextRAII {
   2774   VisibleDeclsRecord &Visible;
   2775 
   2776   typedef VisibleDeclsRecord::ShadowMap ShadowMap;
   2777 
   2778 public:
   2779   ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
   2780     Visible.ShadowMaps.push_back(ShadowMap());
   2781   }
   2782 
   2783   ~ShadowContextRAII() {
   2784     Visible.ShadowMaps.pop_back();
   2785   }
   2786 };
   2787 
   2788 } // end anonymous namespace
   2789 
   2790 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
   2791   // Look through using declarations.
   2792   ND = ND->getUnderlyingDecl();
   2793 
   2794   unsigned IDNS = ND->getIdentifierNamespace();
   2795   std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
   2796   for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
   2797        SM != SMEnd; ++SM) {
   2798     ShadowMap::iterator Pos = SM->find(ND->getDeclName());
   2799     if (Pos == SM->end())
   2800       continue;
   2801 
   2802     for (ShadowMapEntry::iterator I = Pos->second.begin(),
   2803                                IEnd = Pos->second.end();
   2804          I != IEnd; ++I) {
   2805       // A tag declaration does not hide a non-tag declaration.
   2806       if ((*I)->hasTagIdentifierNamespace() &&
   2807           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
   2808                    Decl::IDNS_ObjCProtocol)))
   2809         continue;
   2810 
   2811       // Protocols are in distinct namespaces from everything else.
   2812       if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
   2813            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
   2814           (*I)->getIdentifierNamespace() != IDNS)
   2815         continue;
   2816 
   2817       // Functions and function templates in the same scope overload
   2818       // rather than hide.  FIXME: Look for hiding based on function
   2819       // signatures!
   2820       if ((*I)->isFunctionOrFunctionTemplate() &&
   2821           ND->isFunctionOrFunctionTemplate() &&
   2822           SM == ShadowMaps.rbegin())
   2823         continue;
   2824 
   2825       // We've found a declaration that hides this one.
   2826       return *I;
   2827     }
   2828   }
   2829 
   2830   return 0;
   2831 }
   2832 
   2833 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
   2834                                bool QualifiedNameLookup,
   2835                                bool InBaseClass,
   2836                                VisibleDeclConsumer &Consumer,
   2837                                VisibleDeclsRecord &Visited) {
   2838   if (!Ctx)
   2839     return;
   2840 
   2841   // Make sure we don't visit the same context twice.
   2842   if (Visited.visitedContext(Ctx->getPrimaryContext()))
   2843     return;
   2844 
   2845   if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
   2846     Result.getSema().ForceDeclarationOfImplicitMembers(Class);
   2847 
   2848   // Enumerate all of the results in this context.
   2849   for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
   2850                                       LEnd = Ctx->lookups_end();
   2851        L != LEnd; ++L) {
   2852     DeclContext::lookup_result R = *L;
   2853     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
   2854          ++I) {
   2855       if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
   2856         if ((ND = Result.getAcceptableDecl(ND))) {
   2857           Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
   2858           Visited.add(ND);
   2859         }
   2860       }
   2861     }
   2862   }
   2863 
   2864   // Traverse using directives for qualified name lookup.
   2865   if (QualifiedNameLookup) {
   2866     ShadowContextRAII Shadow(Visited);
   2867     DeclContext::udir_iterator I, E;
   2868     for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
   2869       LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
   2870                          QualifiedNameLookup, InBaseClass, Consumer, Visited);
   2871     }
   2872   }
   2873 
   2874   // Traverse the contexts of inherited C++ classes.
   2875   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
   2876     if (!Record->hasDefinition())
   2877       return;
   2878 
   2879     for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
   2880                                          BEnd = Record->bases_end();
   2881          B != BEnd; ++B) {
   2882       QualType BaseType = B->getType();
   2883 
   2884       // Don't look into dependent bases, because name lookup can't look
   2885       // there anyway.
   2886       if (BaseType->isDependentType())
   2887         continue;
   2888 
   2889       const RecordType *Record = BaseType->getAs<RecordType>();
   2890       if (!Record)
   2891         continue;
   2892 
   2893       // FIXME: It would be nice to be able to determine whether referencing
   2894       // a particular member would be ambiguous. For example, given
   2895       //
   2896       //   struct A { int member; };
   2897       //   struct B { int member; };
   2898       //   struct C : A, B { };
   2899       //
   2900       //   void f(C *c) { c->### }
   2901       //
   2902       // accessing 'member' would result in an ambiguity. However, we
   2903       // could be smart enough to qualify the member with the base
   2904       // class, e.g.,
   2905       //
   2906       //   c->B::member
   2907       //
   2908       // or
   2909       //
   2910       //   c->A::member
   2911 
   2912       // Find results in this base class (and its bases).
   2913       ShadowContextRAII Shadow(Visited);
   2914       LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
   2915                          true, Consumer, Visited);
   2916     }
   2917   }
   2918 
   2919   // Traverse the contexts of Objective-C classes.
   2920   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
   2921     // Traverse categories.
   2922     for (ObjCInterfaceDecl::visible_categories_iterator
   2923            Cat = IFace->visible_categories_begin(),
   2924            CatEnd = IFace->visible_categories_end();
   2925          Cat != CatEnd; ++Cat) {
   2926       ShadowContextRAII Shadow(Visited);
   2927       LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
   2928                          Consumer, Visited);
   2929     }
   2930 
   2931     // Traverse protocols.
   2932     for (ObjCInterfaceDecl::all_protocol_iterator
   2933          I = IFace->all_referenced_protocol_begin(),
   2934          E = IFace->all_referenced_protocol_end(); I != E; ++I) {
   2935       ShadowContextRAII Shadow(Visited);
   2936       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
   2937                          Visited);
   2938     }
   2939 
   2940     // Traverse the superclass.
   2941     if (IFace->getSuperClass()) {
   2942       ShadowContextRAII Shadow(Visited);
   2943       LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
   2944                          true, Consumer, Visited);
   2945     }
   2946 
   2947     // If there is an implementation, traverse it. We do this to find
   2948     // synthesized ivars.
   2949     if (IFace->getImplementation()) {
   2950       ShadowContextRAII Shadow(Visited);
   2951       LookupVisibleDecls(IFace->getImplementation(), Result,
   2952                          QualifiedNameLookup, InBaseClass, Consumer, Visited);
   2953     }
   2954   } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
   2955     for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
   2956            E = Protocol->protocol_end(); I != E; ++I) {
   2957       ShadowContextRAII Shadow(Visited);
   2958       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
   2959                          Visited);
   2960     }
   2961   } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
   2962     for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
   2963            E = Category->protocol_end(); I != E; ++I) {
   2964       ShadowContextRAII Shadow(Visited);
   2965       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
   2966                          Visited);
   2967     }
   2968 
   2969     // If there is an implementation, traverse it.
   2970     if (Category->getImplementation()) {
   2971       ShadowContextRAII Shadow(Visited);
   2972       LookupVisibleDecls(Category->getImplementation(), Result,
   2973                          QualifiedNameLookup, true, Consumer, Visited);
   2974     }
   2975   }
   2976 }
   2977 
   2978 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
   2979                                UnqualUsingDirectiveSet &UDirs,
   2980                                VisibleDeclConsumer &Consumer,
   2981                                VisibleDeclsRecord &Visited) {
   2982   if (!S)
   2983     return;
   2984 
   2985   if (!S->getEntity() ||
   2986       (!S->getParent() &&
   2987        !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
   2988       ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
   2989     // Walk through the declarations in this Scope.
   2990     for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
   2991          D != DEnd; ++D) {
   2992       if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
   2993         if ((ND = Result.getAcceptableDecl(ND))) {
   2994           Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
   2995           Visited.add(ND);
   2996         }
   2997     }
   2998   }
   2999 
   3000   // FIXME: C++ [temp.local]p8
   3001   DeclContext *Entity = 0;
   3002   if (S->getEntity()) {
   3003     // Look into this scope's declaration context, along with any of its
   3004     // parent lookup contexts (e.g., enclosing classes), up to the point
   3005     // where we hit the context stored in the next outer scope.
   3006     Entity = (DeclContext *)S->getEntity();
   3007     DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
   3008 
   3009     for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
   3010          Ctx = Ctx->getLookupParent()) {
   3011       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
   3012         if (Method->isInstanceMethod()) {
   3013           // For instance methods, look for ivars in the method's interface.
   3014           LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
   3015                                   Result.getNameLoc(), Sema::LookupMemberName);
   3016           if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
   3017             LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
   3018                                /*InBaseClass=*/false, Consumer, Visited);
   3019           }
   3020         }
   3021 
   3022         // We've already performed all of the name lookup that we need
   3023         // to for Objective-C methods; the next context will be the
   3024         // outer scope.
   3025         break;
   3026       }
   3027 
   3028       if (Ctx->isFunctionOrMethod())
   3029         continue;
   3030 
   3031       LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
   3032                          /*InBaseClass=*/false, Consumer, Visited);
   3033     }
   3034   } else if (!S->getParent()) {
   3035     // Look into the translation unit scope. We walk through the translation
   3036     // unit's declaration context, because the Scope itself won't have all of
   3037     // the declarations if we loaded a precompiled header.
   3038     // FIXME: We would like the translation unit's Scope object to point to the
   3039     // translation unit, so we don't need this special "if" branch. However,
   3040     // doing so would force the normal C++ name-lookup code to look into the
   3041     // translation unit decl when the IdentifierInfo chains would suffice.
   3042     // Once we fix that problem (which is part of a more general "don't look
   3043     // in DeclContexts unless we have to" optimization), we can eliminate this.
   3044     Entity = Result.getSema().Context.getTranslationUnitDecl();
   3045     LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
   3046                        /*InBaseClass=*/false, Consumer, Visited);
   3047   }
   3048 
   3049   if (Entity) {
   3050     // Lookup visible declarations in any namespaces found by using
   3051     // directives.
   3052     UnqualUsingDirectiveSet::const_iterator UI, UEnd;
   3053     llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
   3054     for (; UI != UEnd; ++UI)
   3055       LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
   3056                          Result, /*QualifiedNameLookup=*/false,
   3057                          /*InBaseClass=*/false, Consumer, Visited);
   3058   }
   3059 
   3060   // Lookup names in the parent scope.
   3061   ShadowContextRAII Shadow(Visited);
   3062   LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
   3063 }
   3064 
   3065 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
   3066                               VisibleDeclConsumer &Consumer,
   3067                               bool IncludeGlobalScope) {
   3068   // Determine the set of using directives available during
   3069   // unqualified name lookup.
   3070   Scope *Initial = S;
   3071   UnqualUsingDirectiveSet UDirs;
   3072   if (getLangOpts().CPlusPlus) {
   3073     // Find the first namespace or translation-unit scope.
   3074     while (S && !isNamespaceOrTranslationUnitScope(S))
   3075       S = S->getParent();
   3076 
   3077     UDirs.visitScopeChain(Initial, S);
   3078   }
   3079   UDirs.done();
   3080 
   3081   // Look for visible declarations.
   3082   LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
   3083   VisibleDeclsRecord Visited;
   3084   if (!IncludeGlobalScope)
   3085     Visited.visitedContext(Context.getTranslationUnitDecl());
   3086   ShadowContextRAII Shadow(Visited);
   3087   ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
   3088 }
   3089 
   3090 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
   3091                               VisibleDeclConsumer &Consumer,
   3092                               bool IncludeGlobalScope) {
   3093   LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
   3094   VisibleDeclsRecord Visited;
   3095   if (!IncludeGlobalScope)
   3096     Visited.visitedContext(Context.getTranslationUnitDecl());
   3097   ShadowContextRAII Shadow(Visited);
   3098   ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
   3099                        /*InBaseClass=*/false, Consumer, Visited);
   3100 }
   3101 
   3102 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
   3103 /// If GnuLabelLoc is a valid source location, then this is a definition
   3104 /// of an __label__ label name, otherwise it is a normal label definition
   3105 /// or use.
   3106 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
   3107                                      SourceLocation GnuLabelLoc) {
   3108   // Do a lookup to see if we have a label with this name already.
   3109   NamedDecl *Res = 0;
   3110 
   3111   if (GnuLabelLoc.isValid()) {
   3112     // Local label definitions always shadow existing labels.
   3113     Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
   3114     Scope *S = CurScope;
   3115     PushOnScopeChains(Res, S, true);
   3116     return cast<LabelDecl>(Res);
   3117   }
   3118 
   3119   // Not a GNU local label.
   3120   Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
   3121   // If we found a label, check to see if it is in the same context as us.
   3122   // When in a Block, we don't want to reuse a label in an enclosing function.
   3123   if (Res && Res->getDeclContext() != CurContext)
   3124     Res = 0;
   3125   if (Res == 0) {
   3126     // If not forward referenced or defined already, create the backing decl.
   3127     Res = LabelDecl::Create(Context, CurContext, Loc, II);
   3128     Scope *S = CurScope->getFnParent();
   3129     assert(S && "Not in a function?");
   3130     PushOnScopeChains(Res, S, true);
   3131   }
   3132   return cast<LabelDecl>(Res);
   3133 }
   3134 
   3135 //===----------------------------------------------------------------------===//
   3136 // Typo correction
   3137 //===----------------------------------------------------------------------===//
   3138 
   3139 namespace {
   3140 
   3141 typedef SmallVector<TypoCorrection, 1> TypoResultList;
   3142 typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
   3143 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
   3144 
   3145 static const unsigned MaxTypoDistanceResultSets = 5;
   3146 
   3147 class TypoCorrectionConsumer : public VisibleDeclConsumer {
   3148   /// \brief The name written that is a typo in the source.
   3149   StringRef Typo;
   3150 
   3151   /// \brief The results found that have the smallest edit distance
   3152   /// found (so far) with the typo name.
   3153   ///
   3154   /// The pointer value being set to the current DeclContext indicates
   3155   /// whether there is a keyword with this name.
   3156   TypoEditDistanceMap CorrectionResults;
   3157 
   3158   Sema &SemaRef;
   3159 
   3160 public:
   3161   explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
   3162     : Typo(Typo->getName()),
   3163       SemaRef(SemaRef) { }
   3164 
   3165   virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
   3166                          bool InBaseClass);
   3167   void FoundName(StringRef Name);
   3168   void addKeywordResult(StringRef Keyword);
   3169   void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
   3170                NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
   3171   void addCorrection(TypoCorrection Correction);
   3172 
   3173   typedef TypoResultsMap::iterator result_iterator;
   3174   typedef TypoEditDistanceMap::iterator distance_iterator;
   3175   distance_iterator begin() { return CorrectionResults.begin(); }
   3176   distance_iterator end()  { return CorrectionResults.end(); }
   3177   void erase(distance_iterator I) { CorrectionResults.erase(I); }
   3178   unsigned size() const { return CorrectionResults.size(); }
   3179   bool empty() const { return CorrectionResults.empty(); }
   3180 
   3181   TypoResultList &operator[](StringRef Name) {
   3182     return CorrectionResults.begin()->second[Name];
   3183   }
   3184 
   3185   unsigned getBestEditDistance(bool Normalized) {
   3186     if (CorrectionResults.empty())
   3187       return (std::numeric_limits<unsigned>::max)();
   3188 
   3189     unsigned BestED = CorrectionResults.begin()->first;
   3190     return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
   3191   }
   3192 
   3193   TypoResultsMap &getBestResults() {
   3194     return CorrectionResults.begin()->second;
   3195   }
   3196 
   3197 };
   3198 
   3199 }
   3200 
   3201 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
   3202                                        DeclContext *Ctx, bool InBaseClass) {
   3203   // Don't consider hidden names for typo correction.
   3204   if (Hiding)
   3205     return;
   3206 
   3207   // Only consider entities with identifiers for names, ignoring
   3208   // special names (constructors, overloaded operators, selectors,
   3209   // etc.).
   3210   IdentifierInfo *Name = ND->getIdentifier();
   3211   if (!Name)
   3212     return;
   3213 
   3214   FoundName(Name->getName());
   3215 }
   3216 
   3217 void TypoCorrectionConsumer::FoundName(StringRef Name) {
   3218   // Use a simple length-based heuristic to determine the minimum possible
   3219   // edit distance. If the minimum isn't good enough, bail out early.
   3220   unsigned MinED = abs((int)Name.size() - (int)Typo.size());
   3221   if (MinED && Typo.size() / MinED < 3)
   3222     return;
   3223 
   3224   // Compute an upper bound on the allowable edit distance, so that the
   3225   // edit-distance algorithm can short-circuit.
   3226   unsigned UpperBound = (Typo.size() + 2) / 3;
   3227 
   3228   // Compute the edit distance between the typo and the name of this
   3229   // entity, and add the identifier to the list of results.
   3230   addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
   3231 }
   3232 
   3233 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
   3234   // Compute the edit distance between the typo and this keyword,
   3235   // and add the keyword to the list of results.
   3236   addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
   3237 }
   3238 
   3239 void TypoCorrectionConsumer::addName(StringRef Name,
   3240                                      NamedDecl *ND,
   3241                                      unsigned Distance,
   3242                                      NestedNameSpecifier *NNS,
   3243                                      bool isKeyword) {
   3244   TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
   3245   if (isKeyword) TC.makeKeyword();
   3246   addCorrection(TC);
   3247 }
   3248 
   3249 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
   3250   StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
   3251   TypoResultList &CList =
   3252       CorrectionResults[Correction.getEditDistance(false)][Name];
   3253 
   3254   if (!CList.empty() && !CList.back().isResolved())
   3255     CList.pop_back();
   3256   if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
   3257     std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
   3258     for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
   3259          RI != RIEnd; ++RI) {
   3260       // If the Correction refers to a decl already in the result list,
   3261       // replace the existing result if the string representation of Correction
   3262       // comes before the current result alphabetically, then stop as there is
   3263       // nothing more to be done to add Correction to the candidate set.
   3264       if (RI->getCorrectionDecl() == NewND) {
   3265         if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
   3266           *RI = Correction;
   3267         return;
   3268       }
   3269     }
   3270   }
   3271   if (CList.empty() || Correction.isResolved())
   3272     CList.push_back(Correction);
   3273 
   3274   while (CorrectionResults.size() > MaxTypoDistanceResultSets)
   3275     erase(llvm::prior(CorrectionResults.end()));
   3276 }
   3277 
   3278 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
   3279 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
   3280 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
   3281 static void getNestedNameSpecifierIdentifiers(
   3282     NestedNameSpecifier *NNS,
   3283     SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
   3284   if (NestedNameSpecifier *Prefix = NNS->getPrefix())
   3285     getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
   3286   else
   3287     Identifiers.clear();
   3288 
   3289   const IdentifierInfo *II = NULL;
   3290 
   3291   switch (NNS->getKind()) {
   3292   case NestedNameSpecifier::Identifier:
   3293     II = NNS->getAsIdentifier();
   3294     break;
   3295 
   3296   case NestedNameSpecifier::Namespace:
   3297     if (NNS->getAsNamespace()->isAnonymousNamespace())
   3298       return;
   3299     II = NNS->getAsNamespace()->getIdentifier();
   3300     break;
   3301 
   3302   case NestedNameSpecifier::NamespaceAlias:
   3303     II = NNS->getAsNamespaceAlias()->getIdentifier();
   3304     break;
   3305 
   3306   case NestedNameSpecifier::TypeSpecWithTemplate:
   3307   case NestedNameSpecifier::TypeSpec:
   3308     II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
   3309     break;
   3310 
   3311   case NestedNameSpecifier::Global:
   3312     return;
   3313   }
   3314 
   3315   if (II)
   3316     Identifiers.push_back(II);
   3317 }
   3318 
   3319 namespace {
   3320 
   3321 class SpecifierInfo {
   3322  public:
   3323   DeclContext* DeclCtx;
   3324   NestedNameSpecifier* NameSpecifier;
   3325   unsigned EditDistance;
   3326 
   3327   SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
   3328       : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
   3329 };
   3330 
   3331 typedef SmallVector<DeclContext*, 4> DeclContextList;
   3332 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
   3333 
   3334 class NamespaceSpecifierSet {
   3335   ASTContext &Context;
   3336   DeclContextList CurContextChain;
   3337   SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
   3338   SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
   3339   bool isSorted;
   3340 
   3341   SpecifierInfoList Specifiers;
   3342   llvm::SmallSetVector<unsigned, 4> Distances;
   3343   llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
   3344 
   3345   /// \brief Helper for building the list of DeclContexts between the current
   3346   /// context and the top of the translation unit
   3347   static DeclContextList BuildContextChain(DeclContext *Start);
   3348 
   3349   void SortNamespaces();
   3350 
   3351  public:
   3352   NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
   3353                         CXXScopeSpec *CurScopeSpec)
   3354       : Context(Context), CurContextChain(BuildContextChain(CurContext)),
   3355         isSorted(true) {
   3356     if (CurScopeSpec && CurScopeSpec->getScopeRep())
   3357       getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
   3358                                         CurNameSpecifierIdentifiers);
   3359     // Build the list of identifiers that would be used for an absolute
   3360     // (from the global context) NestedNameSpecifier referring to the current
   3361     // context.
   3362     for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
   3363                                         CEnd = CurContextChain.rend();
   3364          C != CEnd; ++C) {
   3365       if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
   3366         CurContextIdentifiers.push_back(ND->getIdentifier());
   3367     }
   3368   }
   3369 
   3370   /// \brief Add the namespace to the set, computing the corresponding
   3371   /// NestedNameSpecifier and its distance in the process.
   3372   void AddNamespace(NamespaceDecl *ND);
   3373 
   3374   typedef SpecifierInfoList::iterator iterator;
   3375   iterator begin() {
   3376     if (!isSorted) SortNamespaces();
   3377     return Specifiers.begin();
   3378   }
   3379   iterator end() { return Specifiers.end(); }
   3380 };
   3381 
   3382 }
   3383 
   3384 DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
   3385   assert(Start && "Bulding a context chain from a null context");
   3386   DeclContextList Chain;
   3387   for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
   3388        DC = DC->getLookupParent()) {
   3389     NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
   3390     if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
   3391         !(ND && ND->isAnonymousNamespace()))
   3392       Chain.push_back(DC->getPrimaryContext());
   3393   }
   3394   return Chain;
   3395 }
   3396 
   3397 void NamespaceSpecifierSet::SortNamespaces() {
   3398   SmallVector<unsigned, 4> sortedDistances;
   3399   sortedDistances.append(Distances.begin(), Distances.end());
   3400 
   3401   if (sortedDistances.size() > 1)
   3402     std::sort(sortedDistances.begin(), sortedDistances.end());
   3403 
   3404   Specifiers.clear();
   3405   for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
   3406                                        DIEnd = sortedDistances.end();
   3407        DI != DIEnd; ++DI) {
   3408     SpecifierInfoList &SpecList = DistanceMap[*DI];
   3409     Specifiers.append(SpecList.begin(), SpecList.end());
   3410   }
   3411 
   3412   isSorted = true;
   3413 }
   3414 
   3415 void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
   3416   DeclContext *Ctx = cast<DeclContext>(ND);
   3417   NestedNameSpecifier *NNS = NULL;
   3418   unsigned NumSpecifiers = 0;
   3419   DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
   3420   DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
   3421 
   3422   // Eliminate common elements from the two DeclContext chains.
   3423   for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
   3424                                       CEnd = CurContextChain.rend();
   3425        C != CEnd && !NamespaceDeclChain.empty() &&
   3426        NamespaceDeclChain.back() == *C; ++C) {
   3427     NamespaceDeclChain.pop_back();
   3428   }
   3429 
   3430   // Add an explicit leading '::' specifier if needed.
   3431   if (NamespaceDecl *ND =
   3432         NamespaceDeclChain.empty() ? NULL :
   3433           dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
   3434     IdentifierInfo *Name = ND->getIdentifier();
   3435     if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
   3436                   Name) != CurContextIdentifiers.end() ||
   3437         std::find(CurNameSpecifierIdentifiers.begin(),
   3438                   CurNameSpecifierIdentifiers.end(),
   3439                   Name) != CurNameSpecifierIdentifiers.end()) {
   3440       NamespaceDeclChain = FullNamespaceDeclChain;
   3441       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
   3442     }
   3443   }
   3444 
   3445   // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
   3446   for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
   3447                                       CEnd = NamespaceDeclChain.rend();
   3448        C != CEnd; ++C) {
   3449     NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
   3450     if (ND) {
   3451       NNS = NestedNameSpecifier::Create(Context, NNS, ND);
   3452       ++NumSpecifiers;
   3453     }
   3454   }
   3455 
   3456   // If the built NestedNameSpecifier would be replacing an existing
   3457   // NestedNameSpecifier, use the number of component identifiers that
   3458   // would need to be changed as the edit distance instead of the number
   3459   // of components in the built NestedNameSpecifier.
   3460   if (NNS && !CurNameSpecifierIdentifiers.empty()) {
   3461     SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
   3462     getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
   3463     NumSpecifiers = llvm::ComputeEditDistance(
   3464       llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
   3465       llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
   3466   }
   3467 
   3468   isSorted = false;
   3469   Distances.insert(NumSpecifiers);
   3470   DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
   3471 }
   3472 
   3473 /// \brief Perform name lookup for a possible result for typo correction.
   3474 static void LookupPotentialTypoResult(Sema &SemaRef,
   3475                                       LookupResult &Res,
   3476                                       IdentifierInfo *Name,
   3477                                       Scope *S, CXXScopeSpec *SS,
   3478                                       DeclContext *MemberContext,
   3479                                       bool EnteringContext,
   3480                                       bool isObjCIvarLookup) {
   3481   Res.suppressDiagnostics();
   3482   Res.clear();
   3483   Res.setLookupName(Name);
   3484   if (MemberContext) {
   3485     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
   3486       if (isObjCIvarLookup) {
   3487         if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
   3488           Res.addDecl(Ivar);
   3489           Res.resolveKind();
   3490           return;
   3491         }
   3492       }
   3493 
   3494       if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
   3495         Res.addDecl(Prop);
   3496         Res.resolveKind();
   3497         return;
   3498       }
   3499     }
   3500 
   3501     SemaRef.LookupQualifiedName(Res, MemberContext);
   3502     return;
   3503   }
   3504 
   3505   SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
   3506                            EnteringContext);
   3507 
   3508   // Fake ivar lookup; this should really be part of
   3509   // LookupParsedName.
   3510   if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
   3511     if (Method->isInstanceMethod() && Method->getClassInterface() &&
   3512         (Res.empty() ||
   3513          (Res.isSingleResult() &&
   3514           Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
   3515        if (ObjCIvarDecl *IV
   3516              = Method->getClassInterface()->lookupInstanceVariable(Name)) {
   3517          Res.addDecl(IV);
   3518          Res.resolveKind();
   3519        }
   3520      }
   3521   }
   3522 }
   3523 
   3524 /// \brief Add keywords to the consumer as possible typo corrections.
   3525 static void AddKeywordsToConsumer(Sema &SemaRef,
   3526                                   TypoCorrectionConsumer &Consumer,
   3527                                   Scope *S, CorrectionCandidateCallback &CCC,
   3528                                   bool AfterNestedNameSpecifier) {
   3529   if (AfterNestedNameSpecifier) {
   3530     // For 'X::', we know exactly which keywords can appear next.
   3531     Consumer.addKeywordResult("template");
   3532     if (CCC.WantExpressionKeywords)
   3533       Consumer.addKeywordResult("operator");
   3534     return;
   3535   }
   3536 
   3537   if (CCC.WantObjCSuper)
   3538     Consumer.addKeywordResult("super");
   3539 
   3540   if (CCC.WantTypeSpecifiers) {
   3541     // Add type-specifier keywords to the set of results.
   3542     const char *CTypeSpecs[] = {
   3543       "char", "const", "double", "enum", "float", "int", "long", "short",
   3544       "signed", "struct", "union", "unsigned", "void", "volatile",
   3545       "_Complex", "_Imaginary",
   3546       // storage-specifiers as well
   3547       "extern", "inline", "static", "typedef"
   3548     };
   3549 
   3550     const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
   3551     for (unsigned I = 0; I != NumCTypeSpecs; ++I)
   3552       Consumer.addKeywordResult(CTypeSpecs[I]);
   3553 
   3554     if (SemaRef.getLangOpts().C99)
   3555       Consumer.addKeywordResult("restrict");
   3556     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
   3557       Consumer.addKeywordResult("bool");
   3558     else if (SemaRef.getLangOpts().C99)
   3559       Consumer.addKeywordResult("_Bool");
   3560 
   3561     if (SemaRef.getLangOpts().CPlusPlus) {
   3562       Consumer.addKeywordResult("class");
   3563       Consumer.addKeywordResult("typename");
   3564       Consumer.addKeywordResult("wchar_t");
   3565 
   3566       if (SemaRef.getLangOpts().CPlusPlus11) {
   3567         Consumer.addKeywordResult("char16_t");
   3568         Consumer.addKeywordResult("char32_t");
   3569         Consumer.addKeywordResult("constexpr");
   3570         Consumer.addKeywordResult("decltype");
   3571         Consumer.addKeywordResult("thread_local");
   3572       }
   3573     }
   3574 
   3575     if (SemaRef.getLangOpts().GNUMode)
   3576       Consumer.addKeywordResult("typeof");
   3577   }
   3578 
   3579   if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
   3580     Consumer.addKeywordResult("const_cast");
   3581     Consumer.addKeywordResult("dynamic_cast");
   3582     Consumer.addKeywordResult("reinterpret_cast");
   3583     Consumer.addKeywordResult("static_cast");
   3584   }
   3585 
   3586   if (CCC.WantExpressionKeywords) {
   3587     Consumer.addKeywordResult("sizeof");
   3588     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
   3589       Consumer.addKeywordResult("false");
   3590       Consumer.addKeywordResult("true");
   3591     }
   3592 
   3593     if (SemaRef.getLangOpts().CPlusPlus) {
   3594       const char *CXXExprs[] = {
   3595         "delete", "new", "operator", "throw", "typeid"
   3596       };
   3597       const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
   3598       for (unsigned I = 0; I != NumCXXExprs; ++I)
   3599         Consumer.addKeywordResult(CXXExprs[I]);
   3600 
   3601       if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
   3602           cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
   3603         Consumer.addKeywordResult("this");
   3604 
   3605       if (SemaRef.getLangOpts().CPlusPlus11) {
   3606         Consumer.addKeywordResult("alignof");
   3607         Consumer.addKeywordResult("nullptr");
   3608       }
   3609     }
   3610 
   3611     if (SemaRef.getLangOpts().C11) {
   3612       // FIXME: We should not suggest _Alignof if the alignof macro
   3613       // is present.
   3614       Consumer.addKeywordResult("_Alignof");
   3615     }
   3616   }
   3617 
   3618   if (CCC.WantRemainingKeywords) {
   3619     if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
   3620       // Statements.
   3621       const char *CStmts[] = {
   3622         "do", "else", "for", "goto", "if", "return", "switch", "while" };
   3623       const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
   3624       for (unsigned I = 0; I != NumCStmts; ++I)
   3625         Consumer.addKeywordResult(CStmts[I]);
   3626 
   3627       if (SemaRef.getLangOpts().CPlusPlus) {
   3628         Consumer.addKeywordResult("catch");
   3629         Consumer.addKeywordResult("try");
   3630       }
   3631 
   3632       if (S && S->getBreakParent())
   3633         Consumer.addKeywordResult("break");
   3634 
   3635       if (S && S->getContinueParent())
   3636         Consumer.addKeywordResult("continue");
   3637 
   3638       if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
   3639         Consumer.addKeywordResult("case");
   3640         Consumer.addKeywordResult("default");
   3641       }
   3642     } else {
   3643       if (SemaRef.getLangOpts().CPlusPlus) {
   3644         Consumer.addKeywordResult("namespace");
   3645         Consumer.addKeywordResult("template");
   3646       }
   3647 
   3648       if (S && S->isClassScope()) {
   3649         Consumer.addKeywordResult("explicit");
   3650         Consumer.addKeywordResult("friend");
   3651         Consumer.addKeywordResult("mutable");
   3652         Consumer.addKeywordResult("private");
   3653         Consumer.addKeywordResult("protected");
   3654         Consumer.addKeywordResult("public");
   3655         Consumer.addKeywordResult("virtual");
   3656       }
   3657     }
   3658 
   3659     if (SemaRef.getLangOpts().CPlusPlus) {
   3660       Consumer.addKeywordResult("using");
   3661 
   3662       if (SemaRef.getLangOpts().CPlusPlus11)
   3663         Consumer.addKeywordResult("static_assert");
   3664     }
   3665   }
   3666 }
   3667 
   3668 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
   3669                               TypoCorrection &Candidate) {
   3670   Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
   3671   return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
   3672 }
   3673 
   3674 /// \brief Try to "correct" a typo in the source code by finding
   3675 /// visible declarations whose names are similar to the name that was
   3676 /// present in the source code.
   3677 ///
   3678 /// \param TypoName the \c DeclarationNameInfo structure that contains
   3679 /// the name that was present in the source code along with its location.
   3680 ///
   3681 /// \param LookupKind the name-lookup criteria used to search for the name.
   3682 ///
   3683 /// \param S the scope in which name lookup occurs.
   3684 ///
   3685 /// \param SS the nested-name-specifier that precedes the name we're
   3686 /// looking for, if present.
   3687 ///
   3688 /// \param CCC A CorrectionCandidateCallback object that provides further
   3689 /// validation of typo correction candidates. It also provides flags for
   3690 /// determining the set of keywords permitted.
   3691 ///
   3692 /// \param MemberContext if non-NULL, the context in which to look for
   3693 /// a member access expression.
   3694 ///
   3695 /// \param EnteringContext whether we're entering the context described by
   3696 /// the nested-name-specifier SS.
   3697 ///
   3698 /// \param OPT when non-NULL, the search for visible declarations will
   3699 /// also walk the protocols in the qualified interfaces of \p OPT.
   3700 ///
   3701 /// \returns a \c TypoCorrection containing the corrected name if the typo
   3702 /// along with information such as the \c NamedDecl where the corrected name
   3703 /// was declared, and any additional \c NestedNameSpecifier needed to access
   3704 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
   3705 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
   3706                                  Sema::LookupNameKind LookupKind,
   3707                                  Scope *S, CXXScopeSpec *SS,
   3708                                  CorrectionCandidateCallback &CCC,
   3709                                  DeclContext *MemberContext,
   3710                                  bool EnteringContext,
   3711                                  const ObjCObjectPointerType *OPT) {
   3712   if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
   3713     return TypoCorrection();
   3714 
   3715   // In Microsoft mode, don't perform typo correction in a template member
   3716   // function dependent context because it interferes with the "lookup into
   3717   // dependent bases of class templates" feature.
   3718   if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
   3719       isa<CXXMethodDecl>(CurContext))
   3720     return TypoCorrection();
   3721 
   3722   // We only attempt to correct typos for identifiers.
   3723   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
   3724   if (!Typo)
   3725     return TypoCorrection();
   3726 
   3727   // If the scope specifier itself was invalid, don't try to correct
   3728   // typos.
   3729   if (SS && SS->isInvalid())
   3730     return TypoCorrection();
   3731 
   3732   // Never try to correct typos during template deduction or
   3733   // instantiation.
   3734   if (!ActiveTemplateInstantiations.empty())
   3735     return TypoCorrection();
   3736 
   3737   // Don't try to correct 'super'.
   3738   if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
   3739     return TypoCorrection();
   3740 
   3741   // This is for testing.
   3742   if (Diags.getWarnOnSpellCheck()) {
   3743     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
   3744                                             "spell-checking initiated for %0");
   3745     Diag(TypoName.getLoc(), DiagID) << TypoName.getName();
   3746   }
   3747 
   3748   NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
   3749 
   3750   TypoCorrectionConsumer Consumer(*this, Typo);
   3751 
   3752   // If a callback object considers an empty typo correction candidate to be
   3753   // viable, assume it does not do any actual validation of the candidates.
   3754   TypoCorrection EmptyCorrection;
   3755   bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
   3756 
   3757   // Perform name lookup to find visible, similarly-named entities.
   3758   bool IsUnqualifiedLookup = false;
   3759   DeclContext *QualifiedDC = MemberContext;
   3760   if (MemberContext) {
   3761     LookupVisibleDecls(MemberContext, LookupKind, Consumer);
   3762 
   3763     // Look in qualified interfaces.
   3764     if (OPT) {
   3765       for (ObjCObjectPointerType::qual_iterator
   3766              I = OPT->qual_begin(), E = OPT->qual_end();
   3767            I != E; ++I)
   3768         LookupVisibleDecls(*I, LookupKind, Consumer);
   3769     }
   3770   } else if (SS && SS->isSet()) {
   3771     QualifiedDC = computeDeclContext(*SS, EnteringContext);
   3772     if (!QualifiedDC)
   3773       return TypoCorrection();
   3774 
   3775     // Provide a stop gap for files that are just seriously broken.  Trying
   3776     // to correct all typos can turn into a HUGE performance penalty, causing
   3777     // some files to take minutes to get rejected by the parser.
   3778     if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
   3779       return TypoCorrection();
   3780     ++TyposCorrected;
   3781 
   3782     LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
   3783   } else {
   3784     IsUnqualifiedLookup = true;
   3785     UnqualifiedTyposCorrectedMap::iterator Cached
   3786       = UnqualifiedTyposCorrected.find(Typo);
   3787     if (Cached != UnqualifiedTyposCorrected.end()) {
   3788       // Add the cached value, unless it's a keyword or fails validation. In the
   3789       // keyword case, we'll end up adding the keyword below.
   3790       if (Cached->second) {
   3791         if (!Cached->second.isKeyword() &&
   3792             isCandidateViable(CCC, Cached->second))
   3793           Consumer.addCorrection(Cached->second);
   3794       } else {
   3795         // Only honor no-correction cache hits when a callback that will validate
   3796         // correction candidates is not being used.
   3797         if (!ValidatingCallback)
   3798           return TypoCorrection();
   3799       }
   3800     }
   3801     if (Cached == UnqualifiedTyposCorrected.end()) {
   3802       // Provide a stop gap for files that are just seriously broken.  Trying
   3803       // to correct all typos can turn into a HUGE performance penalty, causing
   3804       // some files to take minutes to get rejected by the parser.
   3805       if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
   3806         return TypoCorrection();
   3807     }
   3808   }
   3809 
   3810   // Determine whether we are going to search in the various namespaces for
   3811   // corrections.
   3812   bool SearchNamespaces
   3813     = getLangOpts().CPlusPlus &&
   3814       (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
   3815   // In a few cases we *only* want to search for corrections bases on just
   3816   // adding or changing the nested name specifier.
   3817   bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
   3818 
   3819   if (IsUnqualifiedLookup || SearchNamespaces) {
   3820     // For unqualified lookup, look through all of the names that we have
   3821     // seen in this translation unit.
   3822     // FIXME: Re-add the ability to skip very unlikely potential corrections.
   3823     for (IdentifierTable::iterator I = Context.Idents.begin(),
   3824                                 IEnd = Context.Idents.end();
   3825          I != IEnd; ++I)
   3826       Consumer.FoundName(I->getKey());
   3827 
   3828     // Walk through identifiers in external identifier sources.
   3829     // FIXME: Re-add the ability to skip very unlikely potential corrections.
   3830     if (IdentifierInfoLookup *External
   3831                             = Context.Idents.getExternalIdentifierLookup()) {
   3832       OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
   3833       do {
   3834         StringRef Name = Iter->Next();
   3835         if (Name.empty())
   3836           break;
   3837 
   3838         Consumer.FoundName(Name);
   3839       } while (true);
   3840     }
   3841   }
   3842 
   3843   AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
   3844 
   3845   // If we haven't found anything, we're done.
   3846   if (Consumer.empty()) {
   3847     // If this was an unqualified lookup, note that no correction was found.
   3848     if (IsUnqualifiedLookup)
   3849       (void)UnqualifiedTyposCorrected[Typo];
   3850 
   3851     return TypoCorrection();
   3852   }
   3853 
   3854   // Make sure the best edit distance (prior to adding any namespace qualifiers)
   3855   // is not more that about a third of the length of the typo's identifier.
   3856   unsigned ED = Consumer.getBestEditDistance(true);
   3857   if (ED > 0 && Typo->getName().size() / ED < 3) {
   3858     // If this was an unqualified lookup, note that no correction was found.
   3859     if (IsUnqualifiedLookup)
   3860       (void)UnqualifiedTyposCorrected[Typo];
   3861 
   3862     return TypoCorrection();
   3863   }
   3864 
   3865   // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
   3866   // to search those namespaces.
   3867   if (SearchNamespaces) {
   3868     // Load any externally-known namespaces.
   3869     if (ExternalSource && !LoadedExternalKnownNamespaces) {
   3870       SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
   3871       LoadedExternalKnownNamespaces = true;
   3872       ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
   3873       for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
   3874         KnownNamespaces[ExternalKnownNamespaces[I]] = true;
   3875     }
   3876 
   3877     for (llvm::MapVector<NamespaceDecl*, bool>::iterator
   3878            KNI = KnownNamespaces.begin(),
   3879            KNIEnd = KnownNamespaces.end();
   3880          KNI != KNIEnd; ++KNI)
   3881       Namespaces.AddNamespace(KNI->first);
   3882   }
   3883 
   3884   // Weed out any names that could not be found by name lookup or, if a
   3885   // CorrectionCandidateCallback object was provided, failed validation.
   3886   SmallVector<TypoCorrection, 16> QualifiedResults;
   3887   LookupResult TmpRes(*this, TypoName, LookupKind);
   3888   TmpRes.suppressDiagnostics();
   3889   while (!Consumer.empty()) {
   3890     TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
   3891     unsigned ED = DI->first;
   3892     for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
   3893                                               IEnd = DI->second.end();
   3894          I != IEnd; /* Increment in loop. */) {
   3895       // If we only want nested name specifier corrections, ignore potential
   3896       // corrections that have a different base identifier from the typo.
   3897       if (AllowOnlyNNSChanges &&
   3898           I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
   3899         TypoCorrectionConsumer::result_iterator Prev = I;
   3900         ++I;
   3901         DI->second.erase(Prev);
   3902         continue;
   3903       }
   3904 
   3905       // If the item already has been looked up or is a keyword, keep it.
   3906       // If a validator callback object was given, drop the correction
   3907       // unless it passes validation.
   3908       bool Viable = false;
   3909       for (TypoResultList::iterator RI = I->second.begin();
   3910            RI != I->second.end(); /* Increment in loop. */) {
   3911         TypoResultList::iterator Prev = RI;
   3912         ++RI;
   3913         if (Prev->isResolved()) {
   3914           if (!isCandidateViable(CCC, *Prev))
   3915             RI = I->second.erase(Prev);
   3916           else
   3917             Viable = true;
   3918         }
   3919       }
   3920       if (Viable || I->second.empty()) {
   3921         TypoCorrectionConsumer::result_iterator Prev = I;
   3922         ++I;
   3923         if (!Viable)
   3924           DI->second.erase(Prev);
   3925         continue;
   3926       }
   3927       assert(I->second.size() == 1 && "Expected a single unresolved candidate");
   3928 
   3929       // Perform name lookup on this name.
   3930       TypoCorrection &Candidate = I->second.front();
   3931       IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
   3932       LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
   3933                                 EnteringContext, CCC.IsObjCIvarLookup);
   3934 
   3935       switch (TmpRes.getResultKind()) {
   3936       case LookupResult::NotFound:
   3937       case LookupResult::NotFoundInCurrentInstantiation:
   3938       case LookupResult::FoundUnresolvedValue:
   3939         QualifiedResults.push_back(Candidate);
   3940         // We didn't find this name in our scope, or didn't like what we found;
   3941         // ignore it.
   3942         {
   3943           TypoCorrectionConsumer::result_iterator Next = I;
   3944           ++Next;
   3945           DI->second.erase(I);
   3946           I = Next;
   3947         }
   3948         break;
   3949 
   3950       case LookupResult::Ambiguous:
   3951         // We don't deal with ambiguities.
   3952         return TypoCorrection();
   3953 
   3954       case LookupResult::FoundOverloaded: {
   3955         TypoCorrectionConsumer::result_iterator Prev = I;
   3956         // Store all of the Decls for overloaded symbols
   3957         for (LookupResult::iterator TRD = TmpRes.begin(),
   3958                                  TRDEnd = TmpRes.end();
   3959              TRD != TRDEnd; ++TRD)
   3960           Candidate.addCorrectionDecl(*TRD);
   3961         ++I;
   3962         if (!isCandidateViable(CCC, Candidate))
   3963           DI->second.erase(Prev);
   3964         break;
   3965       }
   3966 
   3967       case LookupResult::Found: {
   3968         TypoCorrectionConsumer::result_iterator Prev = I;
   3969         Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
   3970         ++I;
   3971         if (!isCandidateViable(CCC, Candidate))
   3972           DI->second.erase(Prev);
   3973         break;
   3974       }
   3975 
   3976       }
   3977     }
   3978 
   3979     if (DI->second.empty())
   3980       Consumer.erase(DI);
   3981     else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
   3982       // If there are results in the closest possible bucket, stop
   3983       break;
   3984 
   3985     // Only perform the qualified lookups for C++
   3986     if (SearchNamespaces) {
   3987       TmpRes.suppressDiagnostics();
   3988       for (SmallVector<TypoCorrection,
   3989                        16>::iterator QRI = QualifiedResults.begin(),
   3990                                   QRIEnd = QualifiedResults.end();
   3991            QRI != QRIEnd; ++QRI) {
   3992         for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
   3993                                           NIEnd = Namespaces.end();
   3994              NI != NIEnd; ++NI) {
   3995           DeclContext *Ctx = NI->DeclCtx;
   3996 
   3997           // FIXME: Stop searching once the namespaces are too far away to create
   3998           // acceptable corrections for this identifier (since the namespaces
   3999           // are sorted in ascending order by edit distance).
   4000 
   4001           TmpRes.clear();
   4002           TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
   4003           if (!LookupQualifiedName(TmpRes, Ctx)) continue;
   4004 
   4005           // Any corrections added below will be validated in subsequent
   4006           // iterations of the main while() loop over the Consumer's contents.
   4007           switch (TmpRes.getResultKind()) {
   4008           case LookupResult::Found: {
   4009             TypoCorrection TC(*QRI);
   4010             TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
   4011             TC.setCorrectionSpecifier(NI->NameSpecifier);
   4012             TC.setQualifierDistance(NI->EditDistance);
   4013             Consumer.addCorrection(TC);
   4014             break;
   4015           }
   4016           case LookupResult::FoundOverloaded: {
   4017             TypoCorrection TC(*QRI);
   4018             TC.setCorrectionSpecifier(NI->NameSpecifier);
   4019             TC.setQualifierDistance(NI->EditDistance);
   4020             for (LookupResult::iterator TRD = TmpRes.begin(),
   4021                                      TRDEnd = TmpRes.end();
   4022                  TRD != TRDEnd; ++TRD)
   4023               TC.addCorrectionDecl(*TRD);
   4024             Consumer.addCorrection(TC);
   4025             break;
   4026           }
   4027           case LookupResult::NotFound:
   4028           case LookupResult::NotFoundInCurrentInstantiation:
   4029           case LookupResult::Ambiguous:
   4030           case LookupResult::FoundUnresolvedValue:
   4031             break;
   4032           }
   4033         }
   4034       }
   4035     }
   4036 
   4037     QualifiedResults.clear();
   4038   }
   4039 
   4040   // No corrections remain...
   4041   if (Consumer.empty()) return TypoCorrection();
   4042 
   4043   TypoResultsMap &BestResults = Consumer.getBestResults();
   4044   ED = Consumer.getBestEditDistance(true);
   4045 
   4046   if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
   4047     // If this was an unqualified lookup and we believe the callback
   4048     // object wouldn't have filtered out possible corrections, note
   4049     // that no correction was found.
   4050     if (IsUnqualifiedLookup && !ValidatingCallback)
   4051       (void)UnqualifiedTyposCorrected[Typo];
   4052 
   4053     return TypoCorrection();
   4054   }
   4055 
   4056   // If only a single name remains, return that result.
   4057   if (BestResults.size() == 1) {
   4058     const TypoResultList &CorrectionList = BestResults.begin()->second;
   4059     const TypoCorrection &Result = CorrectionList.front();
   4060     if (CorrectionList.size() != 1) return TypoCorrection();
   4061 
   4062     // Don't correct to a keyword that's the same as the typo; the keyword
   4063     // wasn't actually in scope.
   4064     if (ED == 0 && Result.isKeyword()) return TypoCorrection();
   4065 
   4066     // Record the correction for unqualified lookup.
   4067     if (IsUnqualifiedLookup)
   4068       UnqualifiedTyposCorrected[Typo] = Result;
   4069 
   4070     TypoCorrection TC = Result;
   4071     TC.setCorrectionRange(SS, TypoName);
   4072     return TC;
   4073   }
   4074   else if (BestResults.size() > 1
   4075            // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
   4076            // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
   4077            // some instances of CTC_Unknown, while WantRemainingKeywords is true
   4078            // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
   4079            && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
   4080            && BestResults["super"].front().isKeyword()) {
   4081     // Prefer 'super' when we're completing in a message-receiver
   4082     // context.
   4083 
   4084     // Don't correct to a keyword that's the same as the typo; the keyword
   4085     // wasn't actually in scope.
   4086     if (ED == 0) return TypoCorrection();
   4087 
   4088     // Record the correction for unqualified lookup.
   4089     if (IsUnqualifiedLookup)
   4090       UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
   4091 
   4092     TypoCorrection TC = BestResults["super"].front();
   4093     TC.setCorrectionRange(SS, TypoName);
   4094     return TC;
   4095   }
   4096 
   4097   // If this was an unqualified lookup and we believe the callback object did
   4098   // not filter out possible corrections, note that no correction was found.
   4099   if (IsUnqualifiedLookup && !ValidatingCallback)
   4100     (void)UnqualifiedTyposCorrected[Typo];
   4101 
   4102   return TypoCorrection();
   4103 }
   4104 
   4105 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
   4106   if (!CDecl) return;
   4107 
   4108   if (isKeyword())
   4109     CorrectionDecls.clear();
   4110 
   4111   CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
   4112 
   4113   if (!CorrectionName)
   4114     CorrectionName = CDecl->getDeclName();
   4115 }
   4116 
   4117 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
   4118   if (CorrectionNameSpec) {
   4119     std::string tmpBuffer;
   4120     llvm::raw_string_ostream PrefixOStream(tmpBuffer);
   4121     CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
   4122     CorrectionName.printName(PrefixOStream);
   4123     return PrefixOStream.str();
   4124   }
   4125 
   4126   return CorrectionName.getAsString();
   4127 }
   4128