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