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