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