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