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