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