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