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