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