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