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