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