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