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