blob: 8a24dd884a76ab9d3128fbd8a5b0f9db5816e419 [file] [log] [blame]
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
Douglas Gregor34074322009-01-14 22:20:51 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregor34074322009-01-14 22:20:51 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements name lookup for C, C++, Objective-C, and
10// Objective-C++.
11//
12//===----------------------------------------------------------------------===//
Hans Wennborgdcfba332015-10-06 23:40:43 +000013
Douglas Gregor960b5bc2009-01-15 00:26:24 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000015#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000016#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000018#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000020#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000021#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +000024#include "clang/Basic/FileManager.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Richard Smith42413142015-05-15 20:05:43 +000026#include "clang/Lex/HeaderSearch.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000027#include "clang/Lex/ModuleLoader.h"
Richard Smith4caa4492015-05-15 02:34:32 +000028#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Sema/DeclSpec.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000030#include "clang/Sema/Lookup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Overload.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "clang/Sema/SemaInternal.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000038#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000040#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000041#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000042#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000043#include <algorithm>
44#include <iterator>
Douglas Gregor2d435302009-12-30 17:04:44 +000045#include <list>
Nick Lewycky13668f22012-04-03 20:26:45 +000046#include <set>
47#include <utility>
48#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000049
Sven van Haastregt9d819152019-06-17 10:06:34 +000050#include "OpenCLBuiltins.inc"
Sven van Haastregt79a222f2019-06-03 09:39:11 +000051
Douglas Gregor34074322009-01-14 22:20:51 +000052using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000053using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000054
John McCallf6c8a4e2009-11-10 07:01:13 +000055namespace {
56 class UnqualUsingEntry {
57 const DeclContext *Nominated;
58 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000059
John McCallf6c8a4e2009-11-10 07:01:13 +000060 public:
61 UnqualUsingEntry(const DeclContext *Nominated,
62 const DeclContext *CommonAncestor)
63 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-11-10 07:01:13 +000066 const DeclContext *getCommonAncestor() const {
67 return CommonAncestor;
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 const DeclContext *getNominatedNamespace() const {
71 return Nominated;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 // Sort by the pointer value of the common ancestor.
75 struct Comparator {
76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
77 return L.getCommonAncestor() < R.getCommonAncestor();
78 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
81 return E.getCommonAncestor() < DC;
82 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
85 return DC < E.getCommonAncestor();
86 }
87 };
88 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000089
John McCallf6c8a4e2009-11-10 07:01:13 +000090 /// A collection of using directives, as used by C++ unqualified
91 /// lookup.
92 class UnqualUsingDirectiveSet {
Richard Smithb920f852017-10-11 01:19:11 +000093 Sema &SemaRef;
94
Chris Lattner0e62c1c2011-07-23 10:55:15 +000095 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000096
John McCallf6c8a4e2009-11-10 07:01:13 +000097 ListTy list;
98 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000099
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 public:
Richard Smithb920f852017-10-11 01:19:11 +0000101 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000102
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000104 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000105 // During unqualified name lookup, the names appear as if they
106 // were declared in the nearest enclosing namespace which contains
107 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000108 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000110
John McCallf6c8a4e2009-11-10 07:01:13 +0000111 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000112 // C++ [namespace.udir]p1:
113 // A using-directive shall not appear in class scope, but may
114 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000115 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000116 if (Ctx && Ctx->isFileContext()) {
117 visit(Ctx, Ctx);
118 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000119 for (auto *I : S->using_directives())
Richard Smithb920f852017-10-11 01:19:11 +0000120 if (SemaRef.isVisible(I))
121 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000122 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000123 }
124 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000125
126 // Visits a context and collect all of its using directives
127 // recursively. Treats all using directives as if they were
128 // declared in the context.
129 //
130 // A given context is only every visited once, so it is important
131 // that contexts be visited from the inside out in order to get
132 // the effective DCs right.
133 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000134 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000135 return;
136
137 addUsingDirectives(DC, EffectiveDC);
138 }
139
140 // Visits a using directive and collects all of its using
141 // directives recursively. Treats all using directives as if they
142 // were declared in the effective DC.
143 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
144 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000145 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000146 return;
147
148 addUsingDirective(UD, EffectiveDC);
149 addUsingDirectives(NS, EffectiveDC);
150 }
151
152 // Adds all the using directives in a context (and those nominated
153 // by its using directives, transitively) as if they appeared in
154 // the given effective context.
155 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Nick Lewycky4b81fc872015-10-18 20:32:12 +0000156 SmallVector<DeclContext*, 4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000157 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000158 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000159 DeclContext *NS = UD->getNominatedNamespace();
Richard Smitha544c512017-10-30 22:38:20 +0000160 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000161 addUsingDirective(UD, EffectiveDC);
162 queue.push_back(NS);
163 }
164 }
165
166 if (queue.empty())
167 return;
168
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000169 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000170 }
171 }
172
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
179 // the first.
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000186 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187
John McCallf6c8a4e2009-11-10 07:01:13 +0000188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
189 }
190
Fangrui Song55fab262018-09-26 22:16:28 +0000191 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
John McCallf6c8a4e2009-11-10 07:01:13 +0000192
John McCallf6c8a4e2009-11-10 07:01:13 +0000193 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000194
John McCallf6c8a4e2009-11-10 07:01:13 +0000195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000198 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000199 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000200 return llvm::make_range(std::equal_range(begin(), end(),
201 DC->getPrimaryContext(),
202 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000203 }
204 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000205} // end anonymous namespace
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207// Retrieve the set of identifier namespaces that correspond to a
208// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000209static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
210 bool CPlusPlus,
211 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 unsigned IDNS = 0;
213 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000214 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000216 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000217 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000219 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000220 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000223 }
Richard Smith541b38b2013-09-20 01:15:31 +0000224 if (Redeclaration)
225 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000226 break;
227
John McCallb9467b62010-04-24 01:30:58 +0000228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup");
232 IDNS = Decl::IDNS_NonMemberOperator;
233 break;
234
Douglas Gregor889ceb72009-02-03 19:21:40 +0000235 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000236 if (CPlusPlus) {
237 IDNS = Decl::IDNS_Type;
238
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
244 if (Redeclaration)
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
246 } else {
247 IDNS = Decl::IDNS_Tag;
248 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000249 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000250
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
253 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000254
Douglas Gregor889ceb72009-02-03 19:21:40 +0000255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
257 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000259 break;
260
261 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
263 break;
264
Douglas Gregor889ceb72009-02-03 19:21:40 +0000265 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000266 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000267 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000268
John McCall84d87672009-12-10 09:41:52 +0000269 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000270 assert(Redeclaration && "should only be used for redecl lookup");
271 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
272 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
273 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000274 break;
275
Douglas Gregor79947a22009-04-24 00:11:27 +0000276 case Sema::LookupObjCProtocolName:
277 IDNS = Decl::IDNS_ObjCProtocol;
278 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000280 case Sema::LookupOMPReductionName:
281 IDNS = Decl::IDNS_OMPReduction;
282 break;
283
Michael Kruse251e1482019-02-01 20:25:04 +0000284 case Sema::LookupOMPMapperName:
285 IDNS = Decl::IDNS_OMPMapper;
286 break;
287
Douglas Gregor39982192010-08-15 06:18:01 +0000288 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000290 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
291 | Decl::IDNS_Type;
292 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000293 }
294 return IDNS;
295}
296
John McCallea305ed2009-12-18 10:40:03 +0000297void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000298 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000299 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000300
Richard Smithbdd14642014-02-04 01:14:30 +0000301 // If we're looking for one of the allocation or deallocation
302 // operators, make sure that the implicitly-declared new and delete
303 // operators can be found.
304 switch (NameInfo.getName().getCXXOverloadedOperator()) {
305 case OO_New:
306 case OO_Delete:
307 case OO_Array_New:
308 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000309 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000310 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000311
Richard Smithbdd14642014-02-04 01:14:30 +0000312 default:
313 break;
314 }
Douglas Gregor15197662013-04-03 23:06:26 +0000315
Richard Smithbdd14642014-02-04 01:14:30 +0000316 // Compiler builtins are always visible, regardless of where they end
317 // up being declared.
318 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
319 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000320 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000321 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000322 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000323 }
John McCallea305ed2009-12-18 10:40:03 +0000324}
325
Alp Tokerc1086762013-12-07 13:51:35 +0000326bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000327 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000328 assert(ResultKind != NotFound || Decls.size() == 0);
329 assert(ResultKind != Found || Decls.size() == 1);
330 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
331 (Decls.size() == 1 &&
332 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
333 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
334 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000335 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
336 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000337 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
338 (Ambiguity == AmbiguousBaseSubobjectTypes ||
339 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000340 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000341}
John McCall19c1bfd2010-08-25 05:32:35 +0000342
John McCall9f3059a2009-10-09 21:13:30 +0000343// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000344void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000345 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000346}
347
Richard Smith3876cc82013-10-30 01:02:04 +0000348/// Get a representative context for a declaration such that two declarations
349/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000350static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000351 // For function-local declarations, use that function as the context. This
352 // doesn't account for scopes within the function; the caller must deal with
353 // those.
354 DeclContext *DC = D->getLexicalDeclContext();
355 if (DC->isFunctionOrMethod())
356 return DC;
357
358 // Otherwise, look at the semantic context of the declaration. The
359 // declaration must have been found there.
360 return D->getDeclContext()->getRedeclContext();
361}
362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000363/// Determine whether \p D is a better lookup result than \p Existing,
Richard Smith826711d2015-07-29 23:38:25 +0000364/// given that they declare the same entity.
Richard Smithcd31b852015-08-22 21:37:34 +0000365static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
Richard Smith826711d2015-07-29 23:38:25 +0000366 NamedDecl *D, NamedDecl *Existing) {
367 // When looking up redeclarations of a using declaration, prefer a using
368 // shadow declaration over any other declaration of the same entity.
369 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
370 !isa<UsingShadowDecl>(Existing))
371 return true;
372
373 auto *DUnderlying = D->getUnderlyingDecl();
374 auto *EUnderlying = Existing->getUnderlyingDecl();
375
Richard Smith990668b2015-11-12 22:04:34 +0000376 // If they have different underlying declarations, prefer a typedef over the
377 // original type (this happens when two type declarations denote the same
378 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
379 // might carry additional semantic information, such as an alignment override.
380 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
381 // declaration over a typedef.
Richard Smith826711d2015-07-29 23:38:25 +0000382 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
383 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
Richard Smith990668b2015-11-12 22:04:34 +0000384 bool HaveTag = isa<TagDecl>(EUnderlying);
385 bool WantTag = Kind == Sema::LookupTagName;
386 return HaveTag != WantTag;
Richard Smith826711d2015-07-29 23:38:25 +0000387 }
388
Richard Smithcd31b852015-08-22 21:37:34 +0000389 // Pick the function with more default arguments.
390 // FIXME: In the presence of ambiguous default arguments, we should keep both,
391 // so we can diagnose the ambiguity if the default argument is needed.
392 // See C++ [over.match.best]p3.
393 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
394 auto *EFD = cast<FunctionDecl>(EUnderlying);
395 unsigned DMin = DFD->getMinRequiredArguments();
396 unsigned EMin = EFD->getMinRequiredArguments();
397 // If D has more default arguments, it is preferred.
398 if (DMin != EMin)
399 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000400 // FIXME: When we track visibility for default function arguments, check
401 // that we pick the declaration with more visible default arguments.
Richard Smithcd31b852015-08-22 21:37:34 +0000402 }
403
404 // Pick the template with more default template arguments.
405 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
406 auto *ETD = cast<TemplateDecl>(EUnderlying);
407 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
408 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
Richard Smith535ff802015-09-11 22:39:35 +0000409 // If D has more default arguments, it is preferred. Note that default
410 // arguments (and their visibility) is monotonically increasing across the
411 // redeclaration chain, so this is a quick proxy for "is more recent".
Richard Smithcd31b852015-08-22 21:37:34 +0000412 if (DMin != EMin)
413 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000414 // If D has more *visible* default arguments, it is preferred. Note, an
415 // earlier default argument being visible does not imply that a later
416 // default argument is visible, so we can't just check the first one.
417 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
418 I != N; ++I) {
419 if (!S.hasVisibleDefaultArgument(
420 ETD->getTemplateParameters()->getParam(I)) &&
421 S.hasVisibleDefaultArgument(
422 DTD->getTemplateParameters()->getParam(I)))
423 return true;
424 }
Richard Smithcd31b852015-08-22 21:37:34 +0000425 }
426
Vassil Vassilev4d75e8d2016-02-28 19:08:24 +0000427 // VarDecl can have incomplete array types, prefer the one with more complete
428 // array type.
429 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
430 VarDecl *EVD = cast<VarDecl>(EUnderlying);
431 if (EVD->getType()->isIncompleteType() &&
432 !DVD->getType()->isIncompleteType()) {
433 // Prefer the decl with a more complete type if visible.
434 return S.isVisible(DVD);
435 }
436 return false; // Avoid picking up a newer decl, just because it was newer.
437 }
438
Richard Smithcd31b852015-08-22 21:37:34 +0000439 // For most kinds of declaration, it doesn't really matter which one we pick.
440 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
441 // If the existing declaration is hidden, prefer the new one. Otherwise,
442 // keep what we've got.
443 return !S.isVisible(Existing);
444 }
445
446 // Pick the newer declaration; it might have a more precise type.
Richard Smith826711d2015-07-29 23:38:25 +0000447 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
448 Prev = Prev->getPreviousDecl())
449 if (Prev == EUnderlying)
450 return true;
Richard Smith826711d2015-07-29 23:38:25 +0000451 return false;
452}
453
Richard Smith990668b2015-11-12 22:04:34 +0000454/// Determine whether \p D can hide a tag declaration.
455static bool canHideTag(NamedDecl *D) {
456 // C++ [basic.scope.declarative]p4:
457 // Given a set of declarations in a single declarative region [...]
458 // exactly one declaration shall declare a class name or enumeration name
459 // that is not a typedef name and the other declarations shall all refer to
Richard Smith4eeaec42016-12-18 22:01:46 +0000460 // the same variable, non-static data member, or enumerator, or all refer
461 // to functions and function templates; in this case the class name or
462 // enumeration name is hidden.
Richard Smith990668b2015-11-12 22:04:34 +0000463 // C++ [basic.scope.hiding]p2:
464 // A class name or enumeration name can be hidden by the name of a
465 // variable, data member, function, or enumerator declared in the same
466 // scope.
Richard Smith4eeaec42016-12-18 22:01:46 +0000467 // An UnresolvedUsingValueDecl always instantiates to one of these.
Richard Smith990668b2015-11-12 22:04:34 +0000468 D = D->getUnderlyingDecl();
469 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
Richard Smith4eeaec42016-12-18 22:01:46 +0000470 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
471 isa<UnresolvedUsingValueDecl>(D);
Richard Smith990668b2015-11-12 22:04:34 +0000472}
473
John McCall283b9012009-11-22 00:44:51 +0000474/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000475void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000476 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000477
John McCall9f3059a2009-10-09 21:13:30 +0000478 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000479 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000480 assert(ResultKind == NotFound ||
481 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000482 return;
483 }
484
John McCall283b9012009-11-22 00:44:51 +0000485 // If there's a single decl, we need to examine it to decide what
486 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000487 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000488 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
489 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000490 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000491 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000492 ResultKind = FoundUnresolvedValue;
493 return;
494 }
John McCall9f3059a2009-10-09 21:13:30 +0000495
John McCall6538c932009-10-10 05:48:19 +0000496 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000497 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000498
Richard Smitha534a312015-07-21 23:54:07 +0000499 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000500 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501
John McCall9f3059a2009-10-09 21:13:30 +0000502 bool Ambiguous = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000503 bool HasTag = false, HasFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000504 bool HasFunctionTemplate = false, HasUnresolved = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000505 NamedDecl *HasNonFunction = nullptr;
506
507 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
John McCall9f3059a2009-10-09 21:13:30 +0000508
509 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510
John McCall9f3059a2009-10-09 21:13:30 +0000511 unsigned I = 0;
512 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000513 NamedDecl *D = Decls[I]->getUnderlyingDecl();
514 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000515
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000516 // Ignore an invalid declaration unless it's the only one left.
Richard Smith5cd86f82015-11-03 03:13:11 +0000517 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000518 Decls[I] = Decls[--N];
519 continue;
520 }
521
Richard Smith826711d2015-07-29 23:38:25 +0000522 llvm::Optional<unsigned> ExistingI;
523
Douglas Gregor13e65872010-08-11 14:45:53 +0000524 // Redeclarations of types via typedef can occur both within a scope
525 // and, through using declarations and directives, across scopes. There is
526 // no ambiguity if they all refer to the same type, so unique based on the
527 // canonical type.
528 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith990668b2015-11-12 22:04:34 +0000529 QualType T = getSema().Context.getTypeDeclType(TD);
530 auto UniqueResult = UniqueTypes.insert(
531 std::make_pair(getSema().Context.getCanonicalType(T), I));
532 if (!UniqueResult.second) {
533 // The type is not unique.
534 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000535 }
536 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000537
Richard Smith826711d2015-07-29 23:38:25 +0000538 // For non-type declarations, check for a prior lookup result naming this
539 // canonical declaration.
540 if (!ExistingI) {
541 auto UniqueResult = Unique.insert(std::make_pair(D, I));
542 if (!UniqueResult.second) {
543 // We've seen this entity before.
544 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000545 }
Richard Smith826711d2015-07-29 23:38:25 +0000546 }
547
548 if (ExistingI) {
549 // This is not a unique lookup result. Pick one of the results and
550 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000551 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000552 Decls[*ExistingI]))
553 Decls[*ExistingI] = Decls[I];
554 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000555 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556 }
557
Douglas Gregor13e65872010-08-11 14:45:53 +0000558 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000559
Douglas Gregor13e65872010-08-11 14:45:53 +0000560 if (isa<UnresolvedUsingValueDecl>(D)) {
561 HasUnresolved = true;
562 } else if (isa<TagDecl>(D)) {
563 if (HasTag)
564 Ambiguous = true;
565 UniqueTagIndex = I;
566 HasTag = true;
567 } else if (isa<FunctionTemplateDecl>(D)) {
568 HasFunction = true;
569 HasFunctionTemplate = true;
570 } else if (isa<FunctionDecl>(D)) {
571 HasFunction = true;
572 } else {
Richard Smith2dbe4042015-11-04 19:26:32 +0000573 if (HasNonFunction) {
574 // If we're about to create an ambiguity between two declarations that
575 // are equivalent, but one is an internal linkage declaration from one
576 // module and the other is an internal linkage declaration from another
577 // module, just skip it.
578 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
579 D)) {
580 EquivalentNonFunctions.push_back(D);
581 Decls[I] = Decls[--N];
582 continue;
583 }
584
Douglas Gregor13e65872010-08-11 14:45:53 +0000585 Ambiguous = true;
Richard Smith2dbe4042015-11-04 19:26:32 +0000586 }
587 HasNonFunction = D;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000588 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000589 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000590 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000591
John McCall9f3059a2009-10-09 21:13:30 +0000592 // C++ [basic.scope.hiding]p2:
593 // A class name or enumeration name can be hidden by the name of
594 // an object, function, or enumerator declared in the same
595 // scope. If a class or enumeration name and an object, function,
596 // or enumerator are declared in the same scope (in any order)
597 // with the same name, the class or enumeration name is hidden
598 // wherever the object, function, or enumerator name is visible.
599 // But it's still an error if there are distinct tag types found,
600 // even if they're not visible. (ref?)
Richard Smith990668b2015-11-12 22:04:34 +0000601 if (N > 1 && HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000602 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith990668b2015-11-12 22:04:34 +0000603 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
604 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
605 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
606 getContextForScopeMatching(OtherDecl)) &&
607 canHideTag(OtherDecl))
Douglas Gregore63d0872010-10-23 16:06:17 +0000608 Decls[UniqueTagIndex] = Decls[--N];
609 else
610 Ambiguous = true;
611 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000612
Richard Smith2dbe4042015-11-04 19:26:32 +0000613 // FIXME: This diagnostic should really be delayed until we're done with
614 // the lookup result, in case the ambiguity is resolved by the caller.
615 if (!EquivalentNonFunctions.empty() && !Ambiguous)
616 getSema().diagnoseEquivalentInternalLinkageDeclarations(
617 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
618
John McCall9f3059a2009-10-09 21:13:30 +0000619 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000620
John McCall80053822009-12-03 00:58:24 +0000621 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000622 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000623
John McCall9f3059a2009-10-09 21:13:30 +0000624 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000625 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000626 else if (HasUnresolved)
627 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000628 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000629 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000630 else
John McCall27b18f82009-11-17 02:14:36 +0000631 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000632}
633
John McCall5cebab12009-11-18 07:57:50 +0000634void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000635 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000636 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000637 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
638 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000639 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000640}
641
John McCall5cebab12009-11-18 07:57:50 +0000642void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000643 Paths = new CXXBasePaths;
644 Paths->swap(P);
645 addDeclsFromBasePaths(*Paths);
646 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000647 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000648}
649
John McCall5cebab12009-11-18 07:57:50 +0000650void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000651 Paths = new CXXBasePaths;
652 Paths->swap(P);
653 addDeclsFromBasePaths(*Paths);
654 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000655 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000656}
657
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000658void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000659 Out << Decls.size() << " result(s)";
660 if (isAmbiguous()) Out << ", ambiguous";
661 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
John McCall9f3059a2009-10-09 21:13:30 +0000663 for (iterator I = begin(), E = end(); I != E; ++I) {
664 Out << "\n";
665 (*I)->print(Out, 2);
666 }
667}
668
Richard Smithba3a4f92016-01-12 21:59:26 +0000669LLVM_DUMP_METHOD void LookupResult::dump() {
670 llvm::errs() << "lookup results for " << getLookupName().getAsString()
671 << ":\n";
672 for (NamedDecl *D : *this)
673 D->dump();
674}
675
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000676/// When trying to resolve a function name, if the isOpenCLBuiltin function
677/// defined in "OpenCLBuiltins.inc" returns a non-null <Index, Len>, then the
678/// identifier is referencing an OpenCL builtin function. Thus, all its
679/// prototypes are added to the LookUpResult.
680///
681/// \param S The Sema instance
682/// \param LR The LookupResult instance
683/// \param II The identifier being resolved
684/// \param Index The list of prototypes starts at Index in OpenCLBuiltins[]
685/// \param Len The list of prototypes has Len elements
686static void InsertOCLBuiltinDeclarations(Sema &S, LookupResult &LR,
687 IdentifierInfo *II, unsigned Index,
688 unsigned Len) {
689
690 for (unsigned i = 0; i < Len; ++i) {
Tom Stellard4422cc42019-07-15 22:34:19 +0000691 const OpenCLBuiltinDecl &Decl = OpenCLBuiltins[Index - 1 + i];
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000692 ASTContext &Context = S.Context;
693
694 // Ignore this BIF if the version is incorrect.
695 if (Context.getLangOpts().OpenCLVersion < Decl.Version)
696 continue;
697
698 FunctionProtoType::ExtProtoInfo PI;
699 PI.Variadic = false;
700
701 // Defined in "OpenCLBuiltins.inc"
702 QualType RT = OCL2Qual(Context, OpenCLSignature[Decl.ArgTableIndex]);
703
704 SmallVector<QualType, 5> ArgTypes;
705 for (unsigned I = 1; I < Decl.NumArgs; I++) {
706 QualType Ty = OCL2Qual(Context, OpenCLSignature[Decl.ArgTableIndex + I]);
707 ArgTypes.push_back(Ty);
708 }
709
710 QualType R = Context.getFunctionType(RT, ArgTypes, PI);
711 SourceLocation Loc = LR.getNameLoc();
712
713 // TODO: This part is taken from Sema::LazilyCreateBuiltin,
714 // maybe refactor it.
715 DeclContext *Parent = Context.getTranslationUnitDecl();
716 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, R,
717 /*TInfo=*/nullptr, SC_Extern,
718 false, R->isFunctionProtoType());
719 New->setImplicit();
720
721 // Create Decl objects for each parameter, adding them to the
722 // FunctionDecl.
723 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
724 SmallVector<ParmVarDecl *, 16> Params;
725 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
726 ParmVarDecl *Parm =
727 ParmVarDecl::Create(Context, New, SourceLocation(),
728 SourceLocation(), nullptr, FT->getParamType(i),
729 /*TInfo=*/nullptr, SC_None, nullptr);
730 Parm->setScopeInfo(0, i);
731 Params.push_back(Parm);
732 }
733 New->setParams(Params);
734 }
735
736 New->addAttr(OverloadableAttr::CreateImplicit(Context));
737
738 if (strlen(Decl.Extension))
739 S.setOpenCLExtensionForDecl(New, Decl.Extension);
740
741 LR.addDecl(New);
742 }
743
744 // If we added overloads, need to resolve the lookup result.
745 if (Len > 1)
746 LR.resolveKind();
747}
748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000749/// Lookup a builtin function, when name lookup would otherwise
Douglas Gregord3a59182010-02-12 05:48:04 +0000750/// fail.
751static bool LookupBuiltin(Sema &S, LookupResult &R) {
752 Sema::LookupNameKind NameKind = R.getLookupKind();
753
754 // If we didn't find a use of this identifier, and if the identifier
755 // corresponds to a compiler builtin, create the decl object for the builtin
756 // now, injecting it into translation unit scope, and return it.
757 if (NameKind == Sema::LookupOrdinaryName ||
758 NameKind == Sema::LookupRedeclarationWithLinkage) {
759 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
760 if (II) {
Eric Fiselier6ad68552016-07-01 01:24:09 +0000761 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
762 if (II == S.getASTContext().getMakeIntegerSeqName()) {
763 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
764 return true;
765 } else if (II == S.getASTContext().getTypePackElementName()) {
766 R.addDecl(S.getASTContext().getTypePackElementDecl());
767 return true;
768 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000769 }
Nico Webere1687c52013-06-20 21:44:55 +0000770
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000771 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
772 if (S.getLangOpts().OpenCL && S.getLangOpts().DeclareOpenCLBuiltins) {
773 auto Index = isOpenCLBuiltin(II->getName());
774 if (Index.first) {
775 InsertOCLBuiltinDeclarations(S, R, II, Index.first, Index.second);
776 return true;
777 }
778 }
779
Douglas Gregord3a59182010-02-12 05:48:04 +0000780 // If this is a builtin on this (or all) targets, create the decl.
781 if (unsigned BuiltinID = II->getBuiltinID()) {
Anastasia Stulovab607e0f2016-02-02 11:29:43 +0000782 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
783 // library functions like 'malloc'. Instead, we'll just error.
784 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000785 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
786 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
788 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
789 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000790 R.isForRedeclaration(),
791 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000792 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000793 return true;
794 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000795 }
796 }
797 }
798
799 return false;
800}
801
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000802/// Determine whether we can declare a special member function within
Douglas Gregor7454c562010-07-02 20:37:36 +0000803/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000804static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000805 // We need to have a definition for the class.
806 if (!Class->getDefinition() || Class->isDependentContext())
807 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808
Douglas Gregor7454c562010-07-02 20:37:36 +0000809 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000810 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000811}
812
813void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000814 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000815 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000816
817 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000818 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000819 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregora6d69502010-07-02 23:41:54 +0000821 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000822 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000823 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000825 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000826 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000827 DeclareImplicitCopyAssignment(Class);
828
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000829 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000830 // If the move constructor has not yet been declared, do so now.
831 if (Class->needsImplicitMoveConstructor())
Richard Smitha87b7662016-05-13 18:48:05 +0000832 DeclareImplicitMoveConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000833
834 // If the move assignment operator has not yet been declared, do so now.
835 if (Class->needsImplicitMoveAssignment())
Richard Smitha87b7662016-05-13 18:48:05 +0000836 DeclareImplicitMoveAssignment(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000837 }
838
Douglas Gregor7454c562010-07-02 20:37:36 +0000839 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000840 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000842}
843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000844/// Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000845/// special member function.
846static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
847 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000848 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000849 case DeclarationName::CXXDestructorName:
850 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000852 case DeclarationName::CXXOperatorName:
853 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000854
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000855 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000858
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000859 return false;
860}
861
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000862/// If there are any implicit member functions with the given name
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000863/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000864static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000865 DeclarationName Name,
Richard Smith32918772017-02-14 00:25:28 +0000866 SourceLocation Loc,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000867 const DeclContext *DC) {
868 if (!DC)
869 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000871 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000872 case DeclarationName::CXXConstructorName:
873 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000874 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000875 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000876 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000877 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000878 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000879 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000880 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000881 Record->needsImplicitMoveConstructor())
882 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000883 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000884 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000886 case DeclarationName::CXXDestructorName:
887 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000888 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000889 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000890 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000891 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000893 case DeclarationName::CXXOperatorName:
894 if (Name.getCXXOverloadedOperator() != OO_Equal)
895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896
Sebastian Redl22653ba2011-08-30 19:58:05 +0000897 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000898 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000899 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000900 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000901 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000902 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000903 Record->needsImplicitMoveAssignment())
904 S.DeclareImplicitMoveAssignment(Class);
905 }
906 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000907 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000908
Richard Smith32918772017-02-14 00:25:28 +0000909 case DeclarationName::CXXDeductionGuideName:
910 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
911 break;
912
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000913 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000915 }
916}
Douglas Gregor7454c562010-07-02 20:37:36 +0000917
John McCall9f3059a2009-10-09 21:13:30 +0000918// Adds all qualifying matches for a name within a decl context to the
919// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000920static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000921 bool Found = false;
922
Douglas Gregor7454c562010-07-02 20:37:36 +0000923 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000924 if (S.getLangOpts().CPlusPlus)
Richard Smith32918772017-02-14 00:25:28 +0000925 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
926 DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927
Douglas Gregor7454c562010-07-02 20:37:36 +0000928 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000929 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
Yaron Keren31bde582017-04-12 10:05:48 +0000930 for (NamedDecl *D : DR) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000931 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000932 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000933 Found = true;
934 }
935 }
John McCall9f3059a2009-10-09 21:13:30 +0000936
Douglas Gregord3a59182010-02-12 05:48:04 +0000937 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
938 return true;
939
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000940 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000941 != DeclarationName::CXXConversionFunctionName ||
942 R.getLookupName().getCXXNameType()->isDependentType() ||
943 !isa<CXXRecordDecl>(DC))
944 return Found;
945
946 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000947 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000948 // name lookup. Instead, any conversion function templates visible in the
949 // context of the use are considered. [...]
950 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000951 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000952 return Found;
953
Erich Keanec9cb1c12017-06-20 17:38:07 +0000954 // For conversion operators, 'operator auto' should only match
955 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
956 // as a candidate for template substitution.
957 auto *ContainedDeducedType =
958 R.getLookupName().getCXXNameType()->getContainedDeducedType();
959 if (R.getLookupName().getNameKind() ==
960 DeclarationName::CXXConversionFunctionName &&
961 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
962 return Found;
963
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000964 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
965 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000966 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
967 if (!ConvTemplate)
968 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Chandler Carruth3a693b72010-01-31 11:44:02 +0000970 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000971 // add the conversion function template. When we deduce template
972 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000973 // type of the new declaration with the type of the function template.
974 if (R.isForRedeclaration()) {
975 R.addDecl(ConvTemplate);
976 Found = true;
977 continue;
978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000979
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000980 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000981 // [...] For each such operator, if argument deduction succeeds
982 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000983 // name lookup.
984 //
985 // When referencing a conversion function for any purpose other than
986 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000988 // specialization into the result set. We do this to avoid forcing all
989 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000990 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000991 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992
993 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000994 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
995 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000996
Chandler Carruth3a693b72010-01-31 11:44:02 +0000997 // Compute the type of the function that we would expect the conversion
998 // function to have, if it were to match the name given.
999 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +00001000 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +00001001 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +00001002 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +00001003 QualType ExpectedType
1004 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001005 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Chandler Carruth3a693b72010-01-31 11:44:02 +00001007 // Perform template argument deduction against the type that we would
1008 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +00001009 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +00001010 Specialization, Info)
1011 == Sema::TDK_Success) {
1012 R.addDecl(Specialization);
1013 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001014 }
1015 }
Chandler Carruth3a693b72010-01-31 11:44:02 +00001016
John McCall9f3059a2009-10-09 21:13:30 +00001017 return Found;
1018}
1019
John McCallf6c8a4e2009-11-10 07:01:13 +00001020// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +00001021static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001022CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +00001023 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +00001024
1025 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1026
John McCallf6c8a4e2009-11-10 07:01:13 +00001027 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001028 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +00001029
John McCallf6c8a4e2009-11-10 07:01:13 +00001030 // Perform direct name lookup into the namespaces nominated by the
1031 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00001032 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
1033 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +00001034 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +00001035
1036 R.resolveKind();
1037
1038 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +00001039}
1040
1041static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001042 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +00001043 return Ctx->isFileContext();
1044 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +00001045}
Douglas Gregored8f2882009-01-30 01:04:22 +00001046
Douglas Gregor66230062010-03-15 14:33:29 +00001047// Find the next outer declaration context from this scope. This
1048// routine actually returns the semantic outer context, which may
1049// differ from the lexical context (encoded directly in the Scope
1050// stack) when we are parsing a member of a class template. In this
1051// case, the second element of the pair will be true, to indicate that
1052// name lookup should continue searching in this semantic context when
1053// it leaves the current template parameter scope.
1054static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001055 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +00001056 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001057 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +00001058 OuterS = OuterS->getParent()) {
1059 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001060 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00001061 break;
1062 }
1063 }
1064
1065 // C++ [temp.local]p8:
1066 // In the definition of a member of a class template that appears
1067 // outside of the namespace containing the class template
1068 // definition, the name of a template-parameter hides the name of
1069 // a member of this namespace.
1070 //
1071 // Example:
1072 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001073 // namespace N {
1074 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +00001075 //
1076 // template<class T> class B {
1077 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078 // };
Douglas Gregor66230062010-03-15 14:33:29 +00001079 // }
1080 //
1081 // template<class C> void N::B<C>::f(C) {
1082 // C b; // C is the template parameter, not N::C
1083 // }
1084 //
1085 // In this example, the lexical context we return is the
1086 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +00001088 !S->getParent()->isTemplateParamScope())
1089 return std::make_pair(Lexical, false);
1090
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +00001092 // For the example, this is the scope for the template parameters of
1093 // template<class C>.
1094 Scope *OutermostTemplateScope = S->getParent();
1095 while (OutermostTemplateScope->getParent() &&
1096 OutermostTemplateScope->getParent()->isTemplateParamScope())
1097 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098
Douglas Gregor66230062010-03-15 14:33:29 +00001099 // Find the namespace context in which the original scope occurs. In
1100 // the example, this is namespace N.
1101 DeclContext *Semantic = DC;
1102 while (!Semantic->isFileContext())
1103 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
Douglas Gregor66230062010-03-15 14:33:29 +00001105 // Find the declaration context just outside of the template
1106 // parameter scope. This is the context in which the template is
1107 // being lexically declaration (a namespace context). In the
1108 // example, this is the global scope.
1109 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1110 Lexical->Encloses(Semantic))
1111 return std::make_pair(Semantic, true);
1112
1113 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +00001114}
1115
Richard Smith541b38b2013-09-20 01:15:31 +00001116namespace {
1117/// An RAII object to specify that we want to find block scope extern
1118/// declarations.
1119struct FindLocalExternScope {
1120 FindLocalExternScope(LookupResult &R)
1121 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1122 Decl::IDNS_LocalExtern) {
Eric Fiselier5485cc12017-07-31 00:24:28 +00001123 R.setFindLocalExtern(R.getIdentifierNamespace() &
1124 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
Richard Smith541b38b2013-09-20 01:15:31 +00001125 }
1126 void restore() {
1127 R.setFindLocalExtern(OldFindLocalExtern);
1128 }
1129 ~FindLocalExternScope() {
1130 restore();
1131 }
1132 LookupResult &R;
1133 bool OldFindLocalExtern;
1134};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001135} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +00001136
John McCall27b18f82009-11-17 02:14:36 +00001137bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001138 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +00001139
1140 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +00001141 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +00001142
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001143 // If this is the name of an implicitly-declared special member function,
1144 // go through the scope stack to implicitly declare
1145 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1146 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00001147 if (DeclContext *DC = PreS->getEntity())
Richard Smith32918772017-02-14 00:25:28 +00001148 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001150
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001151 // Implicitly declare member functions with the name we're looking for, if in
1152 // fact we are in a scope where it matters.
1153
Douglas Gregor889ceb72009-02-03 19:21:40 +00001154 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +00001155 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +00001156 I = IdResolver.begin(Name),
1157 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001158
Douglas Gregor889ceb72009-02-03 19:21:40 +00001159 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001160 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +00001161 // ...During unqualified name lookup (3.4.1), the names appear as if
1162 // they were declared in the nearest enclosing namespace which contains
1163 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001164 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001165 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001166 //
1167 // For example:
1168 // namespace A { int i; }
1169 // void foo() {
1170 // int i;
1171 // {
1172 // using namespace A;
1173 // ++i; // finds local 'i', A::i appears at global scope
1174 // }
1175 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001176 //
Richard Smithb920f852017-10-11 01:19:11 +00001177 UnqualUsingDirectiveSet UDirs(*this);
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001178 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001179 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001180 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001181
1182 // When performing a scope lookup, we want to find local extern decls.
1183 FindLocalExternScope FindLocals(R);
1184
Douglas Gregor700792c2009-02-05 19:25:20 +00001185 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001186 DeclContext *Ctx = S->getEntity();
Olivier Goffart12b221982016-06-16 21:39:46 +00001187 bool SearchNamespaceScope = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +00001188 // Check whether the IdResolver has anything in this scope.
John McCall48871652010-08-21 09:40:31 +00001189 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001190 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Olivier Goffart12b221982016-06-16 21:39:46 +00001191 if (NameKind == LookupRedeclarationWithLinkage &&
1192 !(*I)->isTemplateParameter()) {
1193 // If it's a template parameter, we still find it, so we can diagnose
1194 // the invalid redeclaration.
1195
Richard Smith1c34fb72013-08-13 18:18:50 +00001196 // Determine whether this (or a previous) declaration is
1197 // out-of-scope.
1198 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1199 LeftStartingScope = true;
1200
1201 // If we found something outside of our starting scope that
Olivier Goffart12b221982016-06-16 21:39:46 +00001202 // does not have linkage, skip it.
1203 if (LeftStartingScope && !((*I)->hasLinkage())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001204 R.setShadowed();
1205 continue;
1206 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001207 } else {
1208 // We found something in this scope, we should not look at the
1209 // namespace scope
1210 SearchNamespaceScope = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001211 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001212 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001213 }
1214 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001215 if (!SearchNamespaceScope) {
John McCall9f3059a2009-10-09 21:13:30 +00001216 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001217 if (S->isClassScope())
1218 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1219 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001220 return true;
1221 }
1222
Richard Smith1c34fb72013-08-13 18:18:50 +00001223 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001224 // C++11 [class.friend]p11:
1225 // If a friend declaration appears in a local class and the name
1226 // specified is an unqualified name, a prior declaration is
1227 // looked up without considering scopes that are outside the
1228 // innermost enclosing non-class scope.
1229 return false;
1230 }
1231
Douglas Gregor66230062010-03-15 14:33:29 +00001232 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1233 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1234 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001235 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001236 // lexical and semantic declaration contexts returned by
1237 // findOuterContext(). This implements the name lookup behavior
1238 // of C++ [temp.local]p8.
1239 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001240 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001241 }
1242
1243 if (Ctx) {
1244 DeclContext *OuterCtx;
1245 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001246 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001247 if (SearchAfterTemplateScope)
1248 OutsideOfTemplateParamDC = OuterCtx;
1249
Douglas Gregorea166062010-03-15 15:26:48 +00001250 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001251 // We do not directly look into transparent contexts, since
1252 // those entities will be found in the nearest enclosing
1253 // non-transparent context.
1254 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001255 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001256
1257 // We do not look directly into function or method contexts,
1258 // since all of the local variables and parameters of the
1259 // function/method are present within the Scope.
1260 if (Ctx->isFunctionOrMethod()) {
1261 // If we have an Objective-C instance method, look for ivars
1262 // in the corresponding interface.
1263 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1264 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1265 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1266 ObjCInterfaceDecl *ClassDeclared;
1267 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001269 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001270 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1271 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001272 R.resolveKind();
1273 return true;
1274 }
1275 }
1276 }
1277 }
1278
1279 continue;
1280 }
1281
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001282 // If this is a file context, we need to perform unqualified name
1283 // lookup considering using directives.
1284 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001285 // If we haven't handled using directives yet, do so now.
1286 if (!VisitedUsingDirectives) {
1287 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001288 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1289 if (UCtx->isTransparentContext())
1290 continue;
1291
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001292 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001293 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001294
1295 // Find the innermost file scope, so we can add using directives
1296 // from local scopes.
1297 Scope *InnermostFileScope = S;
1298 while (InnermostFileScope &&
1299 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1300 InnermostFileScope = InnermostFileScope->getParent();
1301 UDirs.visitScopeChain(Initial, InnermostFileScope);
1302
1303 UDirs.done();
1304
1305 VisitedUsingDirectives = true;
1306 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001307
1308 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1309 R.resolveKind();
1310 return true;
1311 }
1312
1313 continue;
1314 }
1315
Douglas Gregor7f737c02009-09-10 16:57:35 +00001316 // Perform qualified name lookup into this context.
1317 // FIXME: In some cases, we know that every name that could be found by
1318 // this qualified name lookup will also be on the identifier chain. For
1319 // example, inside a class without any base classes, we never need to
1320 // perform qualified lookup because all of the members are on top of the
1321 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001322 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001323 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001324 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001325 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001326 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001327
John McCallf6c8a4e2009-11-10 07:01:13 +00001328 // Stop if we ran out of scopes.
1329 // FIXME: This really, really shouldn't be happening.
1330 if (!S) return false;
1331
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001332 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001333 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001334 return false;
1335
Douglas Gregor700792c2009-02-05 19:25:20 +00001336 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001337 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001338 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001339 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1340 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001341 if (!VisitedUsingDirectives) {
1342 UDirs.visitScopeChain(Initial, S);
1343 UDirs.done();
1344 }
Richard Smith541b38b2013-09-20 01:15:31 +00001345
1346 // If we're not performing redeclaration lookup, do not look for local
1347 // extern declarations outside of a function scope.
1348 if (!R.isForRedeclaration())
1349 FindLocals.restore();
1350
Douglas Gregor700792c2009-02-05 19:25:20 +00001351 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001352 // Unqualified name lookup in C++ requires looking into scopes
1353 // that aren't strictly lexical, and therefore we walk through the
1354 // context as well as walking through the scopes.
1355 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001356 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001357 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001358 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001359 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001360 // We found something. Look for anything else in our scope
1361 // with this same name and in an acceptable identifier
1362 // namespace, so that we can construct an overload set if we
1363 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001364 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001365 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001366 }
1367 }
1368
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001369 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001370 R.resolveKind();
1371 return true;
1372 }
1373
Ted Kremenekc37877d2013-10-08 17:08:03 +00001374 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001375 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1376 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1377 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001378 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001379 // lexical and semantic declaration contexts returned by
1380 // findOuterContext(). This implements the name lookup behavior
1381 // of C++ [temp.local]p8.
1382 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001383 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001386 if (Ctx) {
1387 DeclContext *OuterCtx;
1388 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001389 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001390 if (SearchAfterTemplateScope)
1391 OutsideOfTemplateParamDC = OuterCtx;
1392
1393 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1394 // We do not directly look into transparent contexts, since
1395 // those entities will be found in the nearest enclosing
1396 // non-transparent context.
1397 if (Ctx->isTransparentContext())
1398 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001400 // If we have a context, and it's not a context stashed in the
1401 // template parameter scope for an out-of-line definition, also
1402 // look into that context.
Chandler Carruth6232e4d2016-11-04 06:16:09 +00001403 if (!(Found && S->isTemplateParamScope())) {
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001404 assert(Ctx->isFileContext() &&
1405 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001407 // Look into context considering using-directives.
1408 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1409 Found = true;
1410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001411
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001412 if (Found) {
1413 R.resolveKind();
1414 return true;
1415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001416
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001417 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1418 return false;
1419 }
1420 }
1421
Douglas Gregor3ce74932010-02-05 07:07:10 +00001422 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001423 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001424 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001425
John McCall9f3059a2009-10-09 21:13:30 +00001426 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001427}
1428
Richard Smith858e0e02017-05-11 23:11:16 +00001429void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1430 if (auto *M = getCurrentModule())
Richard Smith87bb5692015-06-09 00:35:49 +00001431 Context.mergeDefinitionIntoModule(ND, M);
1432 else
1433 // We're not building a module; just make the definition visible.
Richard Smith90dc5252017-06-23 01:04:34 +00001434 ND->setVisibleDespiteOwningModule();
Richard Smith63e09bf2015-06-17 20:39:41 +00001435
1436 // If ND is a template declaration, make the template parameters
1437 // visible too. They're not (necessarily) within a mergeable DeclContext.
1438 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1439 for (auto *Param : *TD->getTemplateParameters())
Richard Smith858e0e02017-05-11 23:11:16 +00001440 makeMergedDefinitionVisible(Param);
Richard Smithd9ba2242015-05-07 03:54:19 +00001441}
1442
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001443/// Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001444static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001445 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1446 // If this function was instantiated from a template, the defining module is
1447 // the module containing the pattern.
1448 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1449 Entity = Pattern;
1450 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001451 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1452 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001453 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
Richard Smith2195ec92017-04-21 01:15:13 +00001454 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1455 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001456 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
Richard Smith2195ec92017-04-21 01:15:13 +00001457 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1458 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001459 }
1460
Chandler Carruthbd186c02017-04-19 05:25:13 +00001461 // Walk up to the containing context. That might also have been instantiated
1462 // from a template.
Richard Smith17ad3ac2017-10-18 01:41:38 +00001463 DeclContext *Context = Entity->getLexicalDeclContext();
Chandler Carruthbd186c02017-04-19 05:25:13 +00001464 if (Context->isFileContext())
1465 return S.getOwningModule(Entity);
1466 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001467}
1468
1469llvm::DenseSet<Module*> &Sema::getLookupModules() {
Richard Smith696e3122017-02-23 01:43:54 +00001470 unsigned N = CodeSynthesisContexts.size();
1471 for (unsigned I = CodeSynthesisContextLookupModules.size();
Richard Smith0e5d7b82013-07-25 23:08:39 +00001472 I != N; ++I) {
Richard Smith696e3122017-02-23 01:43:54 +00001473 Module *M = getDefiningModule(*this, CodeSynthesisContexts[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001474 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001475 M = nullptr;
Richard Smith696e3122017-02-23 01:43:54 +00001476 CodeSynthesisContextLookupModules.push_back(M);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001477 }
1478 return LookupModulesCache;
1479}
1480
Richard Smithc4577662018-09-12 02:13:47 +00001481/// Determine whether the module M is part of the current module from the
1482/// perspective of a module-private visibility check.
1483static bool isInCurrentModule(const Module *M, const LangOptions &LangOpts) {
1484 // If M is the global module fragment of a module that we've not yet finished
1485 // parsing, then it must be part of the current module.
1486 return M->getTopLevelModuleName() == LangOpts.CurrentModule ||
1487 (M->Kind == Module::GlobalModuleFragment && !M->Parent);
1488}
1489
Richard Smith42413142015-05-15 20:05:43 +00001490bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
Richard Smithc4577662018-09-12 02:13:47 +00001491 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
Richard Smith42413142015-05-15 20:05:43 +00001492 if (isModuleVisible(Merged))
1493 return true;
1494 return false;
1495}
1496
Richard Smithe03a6542017-07-05 01:42:07 +00001497bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
Richard Smithc4577662018-09-12 02:13:47 +00001498 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1499 if (isInCurrentModule(Merged, getLangOpts()))
Richard Smithe03a6542017-07-05 01:42:07 +00001500 return true;
1501 return false;
1502}
1503
Richard Smithe7bd6de2015-06-10 20:30:23 +00001504template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001505static bool
1506hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1507 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001508 if (!D->hasDefaultArgument())
1509 return false;
1510
1511 while (D) {
1512 auto &DefaultArg = D->getDefaultArgStorage();
1513 if (!DefaultArg.isInherited() && S.isVisible(D))
1514 return true;
1515
Richard Smith63e09bf2015-06-17 20:39:41 +00001516 if (!DefaultArg.isInherited() && Modules) {
1517 auto *NonConstD = const_cast<ParmDecl*>(D);
1518 Modules->push_back(S.getOwningModule(NonConstD));
Richard Smith63e09bf2015-06-17 20:39:41 +00001519 }
Richard Smith35c1df52015-06-17 20:16:32 +00001520
Richard Smithe7bd6de2015-06-10 20:30:23 +00001521 // If there was a previous default argument, maybe its parameter is visible.
1522 D = DefaultArg.getInheritedFrom();
1523 }
1524 return false;
1525}
1526
Richard Smith35c1df52015-06-17 20:16:32 +00001527bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1528 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001529 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001530 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001531 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001532 return ::hasVisibleDefaultArgument(*this, P, Modules);
1533 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1534 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001535}
1536
Richard Smith54f04402017-05-18 02:29:20 +00001537template<typename Filter>
1538static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
1539 llvm::SmallVectorImpl<Module *> *Modules,
1540 Filter F) {
Richard Trieu81536282018-06-07 03:20:30 +00001541 bool HasFilteredRedecls = false;
1542
Richard Smith54f04402017-05-18 02:29:20 +00001543 for (auto *Redecl : D->redecls()) {
1544 auto *R = cast<NamedDecl>(Redecl);
1545 if (!F(R))
1546 continue;
1547
1548 if (S.isVisible(R))
1549 return true;
1550
Richard Trieu81536282018-06-07 03:20:30 +00001551 HasFilteredRedecls = true;
1552
Richard Smithc4577662018-09-12 02:13:47 +00001553 if (Modules)
Richard Smith54f04402017-05-18 02:29:20 +00001554 Modules->push_back(R->getOwningModule());
Richard Smith54f04402017-05-18 02:29:20 +00001555 }
1556
Richard Trieu81536282018-06-07 03:20:30 +00001557 // Only return false if there is at least one redecl that is not filtered out.
1558 if (HasFilteredRedecls)
1559 return false;
1560
1561 return true;
Richard Smith54f04402017-05-18 02:29:20 +00001562}
1563
1564bool Sema::hasVisibleExplicitSpecialization(
1565 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1566 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1567 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1568 return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1569 if (auto *FD = dyn_cast<FunctionDecl>(D))
1570 return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1571 if (auto *VD = dyn_cast<VarDecl>(D))
1572 return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1573 llvm_unreachable("unknown explicit specialization kind");
1574 });
1575}
1576
Richard Smith6739a102016-05-05 00:56:12 +00001577bool Sema::hasVisibleMemberSpecialization(
1578 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1579 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1580 "not a member specialization");
Richard Smith54f04402017-05-18 02:29:20 +00001581 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
Richard Smith6739a102016-05-05 00:56:12 +00001582 // If the specialization is declared at namespace scope, then it's a member
1583 // specialization declaration. If it's lexically inside the class
1584 // definition then it was instantiated.
1585 //
1586 // FIXME: This is a hack. There should be a better way to determine this.
1587 // FIXME: What about MS-style explicit specializations declared within a
1588 // class definition?
Richard Smith54f04402017-05-18 02:29:20 +00001589 return D->getLexicalDeclContext()->isFileContext();
1590 });
Richard Smith6739a102016-05-05 00:56:12 +00001591}
1592
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001593/// Determine whether a declaration is visible to name lookup.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001594///
1595/// This routine determines whether the declaration D is visible in the current
1596/// lookup context, taking into account the current template instantiation
1597/// stack. During template instantiation, a declaration is visible if it is
1598/// visible from a module containing any entity on the template instantiation
1599/// path (by instantiating a template, you allow it to see the declarations that
1600/// your module can see, including those later on in your module).
1601bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001602 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001603
Richard Smith54f04402017-05-18 02:29:20 +00001604 Module *DeclModule = SemaRef.getOwningModule(D);
Richard Smithc4577662018-09-12 02:13:47 +00001605 assert(DeclModule && "hidden decl has no owning module");
1606
1607 // If the owning module is visible, the decl is visible.
1608 if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
1609 return true;
Richard Smith54f04402017-05-18 02:29:20 +00001610
Richard Smithd19389a2017-07-05 07:47:11 +00001611 // Determine whether a decl context is a file context for the purpose of
1612 // visibility. This looks through some (export and linkage spec) transparent
1613 // contexts, but not others (enums).
1614 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1615 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1616 isa<ExportDecl>(DC);
1617 };
Richard Smith0e5d7b82013-07-25 23:08:39 +00001618
Richard Smithd19389a2017-07-05 07:47:11 +00001619 // If this declaration is not at namespace scope
Richard Smithbe3980b2015-03-27 00:41:57 +00001620 // then it is visible if its lexical parent has a visible definition.
1621 DeclContext *DC = D->getLexicalDeclContext();
Richard Smithd19389a2017-07-05 07:47:11 +00001622 if (DC && !IsEffectivelyFileContext(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001623 // For a parameter, check whether our current template declaration's
1624 // lexical context is visible, not whether there's some other visible
1625 // definition of it, because parameters aren't "within" the definition.
Vassil Vassilev714b81c2016-09-08 20:34:41 +00001626 //
1627 // In C++ we need to check for a visible definition due to ODR merging,
1628 // and in C we must not because each declaration of a function gets its own
1629 // set of declarations for tags in prototype scope.
Richard Smithd19389a2017-07-05 07:47:11 +00001630 bool VisibleWithinParent;
David Blaikieaa3bf6c2019-04-19 23:02:30 +00001631 if (D->isTemplateParameter()) {
1632 bool SearchDefinitions = true;
1633 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1634 if (const auto *TD = DCD->getDescribedTemplate()) {
1635 TemplateParameterList *TPL = TD->getTemplateParameters();
1636 auto Index = getDepthAndIndex(D).second;
1637 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1638 }
1639 }
1640 if (SearchDefinitions)
1641 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
1642 else
1643 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1644 } else if (isa<ParmVarDecl>(D) ||
1645 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
Richard Smithd19389a2017-07-05 07:47:11 +00001646 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1647 else if (D->isModulePrivate()) {
1648 // A module-private declaration is only visible if an enclosing lexical
1649 // parent was merged with another definition in the current module.
1650 VisibleWithinParent = false;
1651 do {
1652 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1653 VisibleWithinParent = true;
1654 break;
1655 }
1656 DC = DC->getLexicalParent();
1657 } while (!IsEffectivelyFileContext(DC));
1658 } else {
1659 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
Richard Smithbe3980b2015-03-27 00:41:57 +00001660 }
Richard Smithd19389a2017-07-05 07:47:11 +00001661
1662 if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1663 // FIXME: Do something better in this case.
1664 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1665 // Cache the fact that this declaration is implicitly visible because
1666 // its parent has a visible definition.
1667 D->setVisibleDespiteOwningModule();
1668 }
1669 return VisibleWithinParent;
Richard Smithbe3980b2015-03-27 00:41:57 +00001670 }
1671
Richard Smithc4577662018-09-12 02:13:47 +00001672 return false;
1673}
1674
1675bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1676 // The module might be ordinarily visible. For a module-private query, that
1677 // means it is part of the current module. For any other query, that means it
1678 // is in our visible module set.
1679 if (ModulePrivate) {
1680 if (isInCurrentModule(M, getLangOpts()))
1681 return true;
1682 } else {
1683 if (VisibleModules.isVisible(M))
1684 return true;
1685 }
1686
1687 // Otherwise, it might be visible by virtue of the query being within a
1688 // template instantiation or similar that is permitted to look inside M.
Richard Smithd19389a2017-07-05 07:47:11 +00001689
Richard Smith0e5d7b82013-07-25 23:08:39 +00001690 // Find the extra places where we need to look.
Richard Smithc4577662018-09-12 02:13:47 +00001691 const auto &LookupModules = getLookupModules();
Richard Smith0e5d7b82013-07-25 23:08:39 +00001692 if (LookupModules.empty())
1693 return false;
1694
Richard Smithc4577662018-09-12 02:13:47 +00001695 // If our lookup set contains the module, it's visible.
1696 if (LookupModules.count(M))
Richard Smith0e5d7b82013-07-25 23:08:39 +00001697 return true;
1698
Richard Smithc4577662018-09-12 02:13:47 +00001699 // For a module-private query, that's everywhere we get to look.
1700 if (ModulePrivate)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001701 return false;
1702
Richard Smithc4577662018-09-12 02:13:47 +00001703 // Check whether M is transitively exported to an import of the lookup set.
Fangrui Song3117b172018-10-20 17:53:42 +00001704 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1705 return LookupM->isModuleVisible(M);
1706 });
Richard Smith0e5d7b82013-07-25 23:08:39 +00001707}
1708
Richard Smith42413142015-05-15 20:05:43 +00001709bool Sema::isVisibleSlow(const NamedDecl *D) {
1710 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1711}
1712
Richard Smith10568d82015-11-17 03:02:41 +00001713bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
Richard Smithbecb92d2017-10-10 22:33:17 +00001714 // FIXME: If there are both visible and hidden declarations, we need to take
1715 // into account whether redeclaration is possible. Example:
Fangrui Song6907ce22018-07-30 19:24:48 +00001716 //
Richard Smithbecb92d2017-10-10 22:33:17 +00001717 // Non-imported module:
1718 // int f(T); // #1
1719 // Some TU:
1720 // static int f(U); // #2, not a redeclaration of #1
1721 // int f(T); // #3, finds both, should link with #1 if T != U, but
1722 // // with #2 if T == U; neither should be ambiguous.
Richard Smith10568d82015-11-17 03:02:41 +00001723 for (auto *D : R) {
1724 if (isVisible(D))
1725 return true;
Richard Smithbecb92d2017-10-10 22:33:17 +00001726 assert(D->isExternallyDeclarable() &&
1727 "should not have hidden, non-externally-declarable result here");
Richard Smith10568d82015-11-17 03:02:41 +00001728 }
Richard Smithbecb92d2017-10-10 22:33:17 +00001729
1730 // This function is called once "New" is essentially complete, but before a
1731 // previous declaration is attached. We can't query the linkage of "New" in
1732 // general, because attaching the previous declaration can change the
1733 // linkage of New to match the previous declaration.
1734 //
1735 // However, because we've just determined that there is no *visible* prior
1736 // declaration, we can compute the linkage here. There are two possibilities:
1737 //
1738 // * This is not a redeclaration; it's safe to compute the linkage now.
1739 //
1740 // * This is a redeclaration of a prior declaration that is externally
1741 // redeclarable. In that case, the linkage of the declaration is not
1742 // changed by attaching the prior declaration, because both are externally
1743 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
1744 //
1745 // FIXME: This is subtle and fragile.
1746 return New->isExternallyDeclarable();
Richard Smith10568d82015-11-17 03:02:41 +00001747}
1748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001749/// Retrieve the visible declaration corresponding to D, if any.
Douglas Gregor4a814562011-12-14 16:03:29 +00001750///
1751/// This routine determines whether the declaration D is visible in the current
1752/// module, with the current imports. If not, it checks whether any
1753/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001754///
Douglas Gregor4a814562011-12-14 16:03:29 +00001755/// \returns D, or a visible previous declaration of D, whichever is more recent
1756/// and visible. If no declaration of D is visible, returns null.
Richard Smith041740f2018-01-06 00:09:23 +00001757static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
1758 unsigned IDNS) {
Richard Smithe156254d2013-08-20 20:35:18 +00001759 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001760
Aaron Ballman86c93902014-03-06 23:45:36 +00001761 for (auto RD : D->redecls()) {
Richard Smith4083e032016-02-17 21:52:44 +00001762 // Don't bother with extra checks if we already know this one isn't visible.
1763 if (RD == D)
1764 continue;
1765
Richard Smith6739a102016-05-05 00:56:12 +00001766 auto ND = cast<NamedDecl>(RD);
1767 // FIXME: This is wrong in the case where the previous declaration is not
1768 // visible in the same scope as D. This needs to be done much more
1769 // carefully.
Richard Smith041740f2018-01-06 00:09:23 +00001770 if (ND->isInIdentifierNamespace(IDNS) &&
1771 LookupResult::isVisible(SemaRef, ND))
Richard Smith6739a102016-05-05 00:56:12 +00001772 return ND;
Douglas Gregor4a814562011-12-14 16:03:29 +00001773 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001774
Craig Topperc3ec1492014-05-26 06:22:03 +00001775 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001776}
1777
Richard Smith6739a102016-05-05 00:56:12 +00001778bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1779 llvm::SmallVectorImpl<Module *> *Modules) {
1780 assert(!isVisible(D) && "not in slow case");
Richard Smith54f04402017-05-18 02:29:20 +00001781 return hasVisibleDeclarationImpl(*this, D, Modules,
1782 [](const NamedDecl *) { return true; });
Richard Smith6739a102016-05-05 00:56:12 +00001783}
1784
Richard Smithe156254d2013-08-20 20:35:18 +00001785NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Richard Smith4083e032016-02-17 21:52:44 +00001786 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1787 // Namespaces are a bit of a special case: we expect there to be a lot of
1788 // redeclarations of some namespaces, all declarations of a namespace are
1789 // essentially interchangeable, all declarations are found by name lookup
1790 // if any is, and namespaces are never looked up during template
1791 // instantiation. So we benefit from caching the check in this case, and
1792 // it is correct to do so.
1793 auto *Key = ND->getCanonicalDecl();
1794 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1795 return Acceptable;
Richard Smith041740f2018-01-06 00:09:23 +00001796 auto *Acceptable = isVisible(getSema(), Key)
1797 ? Key
1798 : findAcceptableDecl(getSema(), Key, IDNS);
Richard Smith4083e032016-02-17 21:52:44 +00001799 if (Acceptable)
1800 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1801 return Acceptable;
1802 }
1803
Richard Smith041740f2018-01-06 00:09:23 +00001804 return findAcceptableDecl(getSema(), D, IDNS);
Richard Smithe156254d2013-08-20 20:35:18 +00001805}
1806
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001807/// Perform unqualified name lookup starting from a given
Douglas Gregor34074322009-01-14 22:20:51 +00001808/// scope.
1809///
1810/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1811/// used to find names within the current scope. For example, 'x' in
1812/// @code
1813/// int x;
1814/// int f() {
1815/// return x; // unqualified name look finds 'x' in the global scope
1816/// }
1817/// @endcode
1818///
1819/// Different lookup criteria can find different names. For example, a
1820/// particular scope can have both a struct and a function of the same
1821/// name, and each can be found by certain lookup criteria. For more
1822/// information about lookup criteria, see the documentation for the
1823/// class LookupCriteria.
1824///
1825/// @param S The scope from which unqualified name lookup will
1826/// begin. If the lookup criteria permits, name lookup may also search
1827/// in the parent scopes.
1828///
James Dennett91738ff2012-06-22 10:32:46 +00001829/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1830/// look up and the lookup kind), and is updated with the results of lookup
1831/// including zero or more declarations and possibly additional information
1832/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001833///
James Dennett91738ff2012-06-22 10:32:46 +00001834/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001835bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1836 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001837 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001838
John McCall27b18f82009-11-17 02:14:36 +00001839 LookupNameKind NameKind = R.getLookupKind();
1840
David Blaikiebbafb8a2012-03-11 07:00:24 +00001841 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001842 // Unqualified name lookup in C/Objective-C is purely lexical, so
1843 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001844 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001845 // Find the nearest non-transparent declaration scope.
1846 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001847 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001848 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001849 }
1850
Richard Smith541b38b2013-09-20 01:15:31 +00001851 // When performing a scope lookup, we want to find local extern decls.
1852 FindLocalExternScope FindLocals(R);
1853
Douglas Gregor34074322009-01-14 22:20:51 +00001854 // Scan up the scope chain looking for a decl that matches this
1855 // identifier that is in the appropriate namespace. This search
1856 // should not take long, as shadowing of names is uncommon, and
1857 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001858 bool LeftStartingScope = false;
1859
Douglas Gregored8f2882009-01-30 01:04:22 +00001860 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001861 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001862 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001863 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001864 if (NameKind == LookupRedeclarationWithLinkage) {
1865 // Determine whether this (or a previous) declaration is
1866 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001867 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001868 LeftStartingScope = true;
1869
1870 // If we found something outside of our starting scope that
1871 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001872 if (LeftStartingScope && !((*I)->hasLinkage())) {
1873 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001874 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001875 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001876 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001877 else if (NameKind == LookupObjCImplicitSelfParam &&
1878 !isa<ImplicitParamDecl>(*I))
1879 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001880
Douglas Gregor4a814562011-12-14 16:03:29 +00001881 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001882
Douglas Gregorb59643b2012-01-03 23:26:26 +00001883 // Check whether there are any other declarations with the same name
1884 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001885 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001886 // Find the scope in which this declaration was declared (if it
1887 // actually exists in a Scope).
1888 while (S && !S->isDeclScope(D))
1889 S = S->getParent();
Fangrui Song6907ce22018-07-30 19:24:48 +00001890
Douglas Gregor81bd0382012-01-13 23:06:53 +00001891 // If the scope containing the declaration is the translation unit,
1892 // then we'll need to perform our checks based on the matching
1893 // DeclContexts rather than matching scopes.
1894 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001895 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001896
1897 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001898 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001899 if (!S)
1900 DC = (*I)->getDeclContext()->getRedeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00001901
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001902 IdentifierResolver::iterator LastI = I;
1903 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001904 if (S) {
1905 // Match based on scope.
1906 if (!S->isDeclScope(*LastI))
1907 break;
1908 } else {
1909 // Match based on DeclContext.
Fangrui Song6907ce22018-07-30 19:24:48 +00001910 DeclContext *LastDC
Douglas Gregor81bd0382012-01-13 23:06:53 +00001911 = (*LastI)->getDeclContext()->getRedeclContext();
1912 if (!LastDC->Equals(DC))
1913 break;
1914 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001915
1916 // If the declaration is in the right namespace and visible, add it.
1917 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1918 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001919 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001920
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001921 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001922 }
Richard Smith541b38b2013-09-20 01:15:31 +00001923
John McCall9f3059a2009-10-09 21:13:30 +00001924 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001925 }
Douglas Gregor34074322009-01-14 22:20:51 +00001926 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001927 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001928 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001929 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001930 }
1931
1932 // If we didn't find a use of this identifier, and if the identifier
1933 // corresponds to a compiler builtin, create the decl object for the builtin
1934 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001935 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1936 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001937
Fangrui Song6907ce22018-07-30 19:24:48 +00001938 // If we didn't find a use of this identifier, the ExternalSource
1939 // may be able to handle the situation.
Axel Naumann016538a2011-02-24 16:47:47 +00001940 // Note: some lookup failures are expected!
1941 // See e.g. R.isForRedeclaration().
1942 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001943}
1944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001945/// Perform qualified name lookup in the namespaces nominated by
John McCall6538c932009-10-10 05:48:19 +00001946/// using directives by the given context.
1947///
1948/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001949/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001950/// (where X is the global namespace), let S be the set of all
1951/// declarations of m in X and in the transitive closure of all
1952/// namespaces nominated by using-directives in X and its used
1953/// namespaces, except that using-directives are ignored in any
1954/// namespace, including X, directly containing one or more
1955/// declarations of m. No namespace is searched more than once in
1956/// the lookup of a name. If S is the empty set, the program is
1957/// ill-formed. Otherwise, if S has exactly one member, or if the
1958/// context of the reference is a using-declaration
1959/// (namespace.udecl), S is the required set of declarations of
1960/// m. Otherwise if the use of m is not one that allows a unique
1961/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001962///
John McCall6538c932009-10-10 05:48:19 +00001963/// C++98 [namespace.qual]p5:
1964/// During the lookup of a qualified namespace member name, if the
1965/// lookup finds more than one declaration of the member, and if one
1966/// declaration introduces a class name or enumeration name and the
1967/// other declarations either introduce the same object, the same
1968/// enumerator or a set of functions, the non-type name hides the
1969/// class or enumeration name if and only if the declarations are
1970/// from the same namespace; otherwise (the declarations are from
1971/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001972static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001973 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001974 assert(StartDC->isFileContext() && "start context is not a file context");
1975
Richard Smithb920f852017-10-11 01:19:11 +00001976 // We have not yet looked into these namespaces, much less added
1977 // their "using-children" to the queue.
1978 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001979
1980 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001981 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001982 Visited.insert(StartDC);
1983
John McCall6538c932009-10-10 05:48:19 +00001984 // We have already looked into the initial namespace; seed the queue
1985 // with its using-children.
Richard Smithb920f852017-10-11 01:19:11 +00001986 for (auto *I : StartDC->using_directives()) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001987 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Richard Smitha544c512017-10-30 22:38:20 +00001988 if (S.isVisible(I) && Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001989 Queue.push_back(ND);
1990 }
1991
1992 // The easiest way to implement the restriction in [namespace.qual]p5
1993 // is to check whether any of the individual results found a tag
1994 // and, if so, to declare an ambiguity if the final result is not
1995 // a tag.
1996 bool FoundTag = false;
1997 bool FoundNonTag = false;
1998
John McCall5cebab12009-11-18 07:57:50 +00001999 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00002000
2001 bool Found = false;
2002 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002003 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00002004
2005 // We go through some convolutions here to avoid copying results
2006 // between LookupResults.
2007 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00002008 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00002009 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00002010
2011 if (FoundDirect) {
2012 // First do any local hiding.
2013 DirectR.resolveKind();
2014
2015 // If the local result is a tag, remember that.
2016 if (DirectR.isSingleTagDecl())
2017 FoundTag = true;
2018 else
2019 FoundNonTag = true;
2020
2021 // Append the local results to the total results if necessary.
2022 if (UseLocal) {
2023 R.addAllDecls(LocalR);
2024 LocalR.clear();
2025 }
2026 }
2027
2028 // If we find names in this namespace, ignore its using directives.
2029 if (FoundDirect) {
2030 Found = true;
2031 continue;
2032 }
2033
Aaron Ballman804a7fb2014-03-17 17:14:12 +00002034 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00002035 NamespaceDecl *Nom = I->getNominatedNamespace();
Richard Smitha544c512017-10-30 22:38:20 +00002036 if (S.isVisible(I) && Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00002037 Queue.push_back(Nom);
2038 }
2039 }
2040
2041 if (Found) {
2042 if (FoundTag && FoundNonTag)
2043 R.setAmbiguousQualifiedTagHiding();
2044 else
2045 R.resolveKind();
2046 }
2047
2048 return Found;
2049}
2050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002051/// Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002053 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00002054 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002055
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002056 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002057 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00002058}
2059
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002060/// Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00002061/// static members, nested types, and enumerators.
2062template<typename InputIterator>
2063static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
2064 Decl *D = (*First)->getUnderlyingDecl();
2065 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
2066 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002067
Douglas Gregorc0d24902010-10-22 22:08:47 +00002068 if (isa<CXXMethodDecl>(D)) {
2069 // Determine whether all of the methods are static.
2070 bool AllMethodsAreStatic = true;
2071 for(; First != Last; ++First) {
2072 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002073
Douglas Gregorc0d24902010-10-22 22:08:47 +00002074 if (!isa<CXXMethodDecl>(D)) {
2075 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
2076 break;
2077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
Douglas Gregorc0d24902010-10-22 22:08:47 +00002079 if (!cast<CXXMethodDecl>(D)->isStatic()) {
2080 AllMethodsAreStatic = false;
2081 break;
2082 }
2083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002084
Douglas Gregorc0d24902010-10-22 22:08:47 +00002085 if (AllMethodsAreStatic)
2086 return true;
2087 }
2088
2089 return false;
2090}
2091
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002092/// Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00002093///
2094/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2095/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002096/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00002097///
2098/// Different lookup criteria can find different names. For example, a
2099/// particular scope can have both a struct and a function of the same
2100/// name, and each can be found by certain lookup criteria. For more
2101/// information about lookup criteria, see the documentation for the
2102/// class LookupCriteria.
2103///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002104/// \param R captures both the lookup criteria and any lookup results found.
2105///
2106/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00002107/// search. If the lookup criteria permits, name lookup may also search
2108/// in the parent contexts or (for C++ classes) base classes.
2109///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002110/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002111/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00002112///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002113/// \returns true if lookup succeeded, false if it failed.
2114bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2115 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00002116 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00002117
John McCall27b18f82009-11-17 02:14:36 +00002118 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00002119 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002120
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002121 // Make sure that the declaration context is complete.
2122 assert((!isa<TagDecl>(LookupCtx) ||
2123 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00002124 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00002125 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002126 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00002127
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002128 struct QualifiedLookupInScope {
2129 bool oldVal;
2130 DeclContext *Context;
2131 // Set flag in DeclContext informing debugger that we're looking for qualified name
Fangrui Song6907ce22018-07-30 19:24:48 +00002132 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2133 oldVal = ctx->setUseQualifiedLookup();
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002134 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002135 ~QualifiedLookupInScope() {
2136 Context->setUseQualifiedLookup(oldVal);
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002137 }
2138 } QL(LookupCtx);
2139
Douglas Gregord3a59182010-02-12 05:48:04 +00002140 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00002141 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00002142 if (isa<CXXRecordDecl>(LookupCtx))
2143 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00002144 return true;
2145 }
Douglas Gregor34074322009-01-14 22:20:51 +00002146
John McCall6538c932009-10-10 05:48:19 +00002147 // Don't descend into implied contexts for redeclarations.
2148 // C++98 [namespace.qual]p6:
2149 // In a declaration for a namespace member in which the
2150 // declarator-id is a qualified-id, given that the qualified-id
2151 // for the namespace member has the form
2152 // nested-name-specifier unqualified-id
2153 // the unqualified-id shall name a member of the namespace
2154 // designated by the nested-name-specifier.
2155 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00002156 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00002157 return false;
2158
John McCall27b18f82009-11-17 02:14:36 +00002159 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00002160 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00002161 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00002162
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002163 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00002164 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002165 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00002166 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00002167 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002168
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002169 // If we're performing qualified name lookup into a dependent class,
2170 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002172 // template instantiation time (at which point all bases will be available)
2173 // or we have to fail.
2174 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2175 LookupRec->hasAnyDependentBases()) {
2176 R.setNotFoundInCurrentInstantiation();
2177 return false;
2178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002180 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002181 CXXBasePaths Paths;
2182 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002183
2184 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002185 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2186 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00002187 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002188 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002189 case LookupOrdinaryName:
2190 case LookupMemberName:
2191 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00002192 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002193 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2194 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002195
Douglas Gregor36d1b142009-10-06 17:59:45 +00002196 case LookupTagName:
2197 BaseCallback = &CXXRecordDecl::FindTagMember;
2198 break;
John McCall84d87672009-12-10 09:41:52 +00002199
Douglas Gregor39982192010-08-15 06:18:01 +00002200 case LookupAnyName:
2201 BaseCallback = &LookupAnyMember;
2202 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002204 case LookupOMPReductionName:
2205 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2206 break;
2207
Michael Kruse251e1482019-02-01 20:25:04 +00002208 case LookupOMPMapperName:
2209 BaseCallback = &CXXRecordDecl::FindOMPMapperMember;
2210 break;
2211
John McCall84d87672009-12-10 09:41:52 +00002212 case LookupUsingDeclName:
2213 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002214
Douglas Gregor36d1b142009-10-06 17:59:45 +00002215 case LookupOperatorName:
2216 case LookupNamespaceName:
2217 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002218 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002219 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00002220 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002221
Douglas Gregor36d1b142009-10-06 17:59:45 +00002222 case LookupNestedNameSpecifierName:
2223 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2224 break;
2225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002226
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002227 DeclarationName Name = R.getLookupName();
2228 if (!LookupRec->lookupInBases(
2229 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2230 return BaseCallback(Specifier, Path, Name);
2231 },
2232 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00002233 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002234
John McCall553c0792010-01-23 00:46:32 +00002235 R.setNamingClass(LookupRec);
2236
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002237 // C++ [class.member.lookup]p2:
2238 // [...] If the resulting set of declarations are not all from
2239 // sub-objects of the same type, or the set has a nonstatic member
2240 // and includes members from distinct sub-objects, there is an
2241 // ambiguity and the program is ill-formed. Otherwise that set is
2242 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002243 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002244 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00002245 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002246
Douglas Gregor36d1b142009-10-06 17:59:45 +00002247 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002248 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002249 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002250
John McCall401982f2010-01-20 21:53:11 +00002251 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2252 // across all paths.
2253 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002254
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002255 // Determine whether we're looking at a distinct sub-object or not.
2256 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00002257 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002258 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2259 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00002260 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002261 }
2262
Douglas Gregorc0d24902010-10-22 22:08:47 +00002263 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002264 != Context.getCanonicalType(PathElement.Base->getType())) {
2265 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002266 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002267 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002268 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002269 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002270 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2271 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002272
Richard Smithafcfb6b2019-02-15 21:53:07 +00002273 // Get the decl that we should use for deduplicating this lookup.
2274 auto GetRepresentativeDecl = [&](NamedDecl *D) -> Decl * {
2275 // C++ [temp.local]p3:
2276 // A lookup that finds an injected-class-name (10.2) can result in
2277 // an ambiguity in certain cases (for example, if it is found in
2278 // more than one base class). If all of the injected-class-names
2279 // that are found refer to specializations of the same class
2280 // template, and if the name is used as a template-name, the
2281 // reference refers to the class template itself and not a
2282 // specialization thereof, and is not ambiguous.
2283 if (R.isTemplateNameLookup())
2284 if (auto *TD = getAsTemplateNameDecl(D))
2285 D = TD;
2286 return D->getUnderlyingDecl()->getCanonicalDecl();
2287 };
2288
David Blaikieff7d47a2012-12-19 00:45:41 +00002289 while (FirstD != FirstPath->Decls.end() &&
2290 CurrentD != Path->Decls.end()) {
Richard Smithafcfb6b2019-02-15 21:53:07 +00002291 if (GetRepresentativeDecl(*FirstD) !=
2292 GetRepresentativeDecl(*CurrentD))
2293 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002294
Douglas Gregorc0d24902010-10-22 22:08:47 +00002295 ++FirstD;
2296 ++CurrentD;
2297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298
David Blaikieff7d47a2012-12-19 00:45:41 +00002299 if (FirstD == FirstPath->Decls.end() &&
2300 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002301 continue;
2302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002303
John McCall9f3059a2009-10-09 21:13:30 +00002304 R.setAmbiguousBaseSubobjectTypes(Paths);
2305 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002306 }
2307
Douglas Gregorc0d24902010-10-22 22:08:47 +00002308 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002309 // We have a different subobject of the same type.
2310
2311 // C++ [class.member.lookup]p5:
2312 // A static member, a nested type or an enumerator defined in
2313 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002314 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002315 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002316 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002317
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002318 // We have found a nonstatic member name in multiple, distinct
2319 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002320 R.setAmbiguousBaseSubobjects(Paths);
2321 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002322 }
2323 }
2324
2325 // Lookup in a base class succeeded; return these results.
2326
Aaron Ballman1e606f42014-07-15 22:03:49 +00002327 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002328 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2329 D->getAccess());
2330 R.addDecl(D, AS);
2331 }
John McCall9f3059a2009-10-09 21:13:30 +00002332 R.resolveKind();
2333 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002334}
2335
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002336/// Performs qualified name lookup or special type of lookup for
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002337/// "__super::" scope specifier.
2338///
2339/// This routine is a convenience overload meant to be called from contexts
2340/// that need to perform a qualified name lookup with an optional C++ scope
2341/// specifier that might require special kind of lookup.
2342///
2343/// \param R captures both the lookup criteria and any lookup results found.
2344///
2345/// \param LookupCtx The context in which qualified name lookup will
2346/// search.
2347///
2348/// \param SS An optional C++ scope-specifier.
2349///
2350/// \returns true if lookup succeeded, false if it failed.
2351bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2352 CXXScopeSpec &SS) {
2353 auto *NNS = SS.getScopeRep();
2354 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2355 return LookupInSuper(R, NNS->getAsRecordDecl());
2356 else
2357
2358 return LookupQualifiedName(R, LookupCtx);
2359}
2360
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002361/// Performs name lookup for a name that was parsed in the
Douglas Gregor34074322009-01-14 22:20:51 +00002362/// source code, and may contain a C++ scope specifier.
2363///
2364/// This routine is a convenience routine meant to be called from
2365/// contexts that receive a name and an optional C++ scope specifier
2366/// (e.g., "N::M::x"). It will then perform either qualified or
2367/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002368/// respectively) on the given name and return those results. It will
2369/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002370///
2371/// @param S The scope from which unqualified name lookup will
2372/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002373///
Douglas Gregore861bac2009-08-25 22:51:20 +00002374/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002375///
Douglas Gregore861bac2009-08-25 22:51:20 +00002376/// @param EnteringContext Indicates whether we are going to enter the
2377/// context of the scope-specifier SS (if present).
2378///
John McCall9f3059a2009-10-09 21:13:30 +00002379/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002380bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002381 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002382 if (SS && SS->isInvalid()) {
2383 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002384 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002385 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387
Douglas Gregore861bac2009-08-25 22:51:20 +00002388 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002389 NestedNameSpecifier *NNS = SS->getScopeRep();
2390 if (NNS->getKind() == NestedNameSpecifier::Super)
2391 return LookupInSuper(R, NNS->getAsRecordDecl());
2392
Douglas Gregore861bac2009-08-25 22:51:20 +00002393 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002394 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002395 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002396 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002397 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002398
John McCall27b18f82009-11-17 02:14:36 +00002399 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002400 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002401 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002402
Douglas Gregore861bac2009-08-25 22:51:20 +00002403 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002404 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002405 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002406 R.setNotFoundInCurrentInstantiation();
2407 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002408 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002409 }
2410
Mike Stump11289f42009-09-09 15:08:12 +00002411 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002412 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002413}
2414
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002415/// Perform qualified name lookup into all base classes of the given
Nikola Smiljanic67860242014-09-26 00:28:20 +00002416/// class.
2417///
2418/// \param R captures both the lookup criteria and any lookup results found.
2419///
2420/// \param Class The context in which qualified name lookup will
2421/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002422///
2423/// @returns True if any decls were found (but possibly ambiguous)
2424bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002425 // The access-control rules we use here are essentially the rules for
2426 // doing a lookup in Class that just magically skipped the direct
2427 // members of Class itself. That is, the naming class is Class, and the
2428 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002429 for (const auto &BaseSpec : Class->bases()) {
2430 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2431 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2432 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
Fangrui Song99337e22018-07-20 08:19:20 +00002433 Result.setBaseObjectType(Context.getRecordType(Class));
Nikola Smiljanic67860242014-09-26 00:28:20 +00002434 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002435
2436 // Copy the lookup results into the target, merging the base's access into
2437 // the path access.
2438 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2439 R.addDecl(I.getDecl(),
2440 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2441 I.getAccess()));
2442 }
2443
2444 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002445 }
2446
2447 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002448 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002449
2450 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002451}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002452
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002453/// Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002454/// from name lookup.
2455///
James Dennett41725122012-06-22 10:16:05 +00002456/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002457void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002458 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2459
John McCall27b18f82009-11-17 02:14:36 +00002460 DeclarationName Name = Result.getLookupName();
2461 SourceLocation NameLoc = Result.getNameLoc();
2462 SourceRange LookupRange = Result.getContextRange();
2463
John McCall6538c932009-10-10 05:48:19 +00002464 switch (Result.getAmbiguityKind()) {
2465 case LookupResult::AmbiguousBaseSubobjects: {
2466 CXXBasePaths *Paths = Result.getBasePaths();
2467 QualType SubobjectType = Paths->front().back().Base->getType();
2468 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2469 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2470 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002471
David Blaikieff7d47a2012-12-19 00:45:41 +00002472 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002473 while (isa<CXXMethodDecl>(*Found) &&
2474 cast<CXXMethodDecl>(*Found)->isStatic())
2475 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002476
John McCall6538c932009-10-10 05:48:19 +00002477 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002478 break;
John McCall6538c932009-10-10 05:48:19 +00002479 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002480
John McCall6538c932009-10-10 05:48:19 +00002481 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002482 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2483 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002484
John McCall6538c932009-10-10 05:48:19 +00002485 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002486 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002487 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2488 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002489 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002490 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002491 if (DeclsPrinted.insert(D).second)
2492 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2493 }
Serge Pavlov99292092013-08-29 07:23:24 +00002494 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002495 }
2496
John McCall6538c932009-10-10 05:48:19 +00002497 case LookupResult::AmbiguousTagHiding: {
2498 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002499
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002500 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002501
Aaron Ballman1e606f42014-07-15 22:03:49 +00002502 for (auto *D : Result)
2503 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002504 TagDecls.insert(TD);
2505 Diag(TD->getLocation(), diag::note_hidden_tag);
2506 }
2507
Aaron Ballman1e606f42014-07-15 22:03:49 +00002508 for (auto *D : Result)
2509 if (!isa<TagDecl>(D))
2510 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002511
2512 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002513 LookupResult::Filter F = Result.makeFilter();
2514 while (F.hasNext()) {
2515 if (TagDecls.count(F.next()))
2516 F.erase();
2517 }
2518 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002519 break;
John McCall6538c932009-10-10 05:48:19 +00002520 }
2521
2522 case LookupResult::AmbiguousReference: {
2523 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524
Aaron Ballman1e606f42014-07-15 22:03:49 +00002525 for (auto *D : Result)
2526 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002527 break;
John McCall6538c932009-10-10 05:48:19 +00002528 }
Serge Pavlov99292092013-08-29 07:23:24 +00002529 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002530}
Douglas Gregore254f902009-02-04 00:32:51 +00002531
John McCallf24d7bb2010-05-28 18:45:08 +00002532namespace {
2533 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002534 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002535 Sema::AssociatedNamespaceSet &Namespaces,
2536 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002537 : S(S), Namespaces(Namespaces), Classes(Classes),
2538 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002539 }
2540
Richard Smith58bd01f2019-01-16 22:01:39 +00002541 bool addClassTransitive(CXXRecordDecl *RD) {
2542 Classes.insert(RD);
2543 return ClassesTransitive.insert(RD);
2544 }
2545
John McCallf24d7bb2010-05-28 18:45:08 +00002546 Sema &S;
2547 Sema::AssociatedNamespaceSet &Namespaces;
2548 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002549 SourceLocation InstantiationLoc;
Richard Smith58bd01f2019-01-16 22:01:39 +00002550
2551 private:
2552 Sema::AssociatedClassSet ClassesTransitive;
John McCallf24d7bb2010-05-28 18:45:08 +00002553 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002554} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002555
Mike Stump11289f42009-09-09 15:08:12 +00002556static void
John McCallf24d7bb2010-05-28 18:45:08 +00002557addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002558
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002559// Given the declaration context \param Ctx of a class, class template or
2560// enumeration, add the associated namespaces to \param Namespaces as described
2561// in [basic.lookup.argdep]p2.
Douglas Gregor8b895222010-04-30 07:08:38 +00002562static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2563 DeclContext *Ctx) {
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002564 // The exact wording has been changed in C++14 as a result of
2565 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2566 // to all language versions since it is possible to return a local type
2567 // from a lambda in C++11.
2568 //
2569 // C++14 [basic.lookup.argdep]p2:
2570 // If T is a class type [...]. Its associated namespaces are the innermost
2571 // enclosing namespaces of its associated classes. [...]
2572 //
2573 // If T is an enumeration type, its associated namespace is the innermost
2574 // enclosing namespace of its declaration. [...]
Douglas Gregor8b895222010-04-30 07:08:38 +00002575
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002576 // We additionally skip inline namespaces. The innermost non-inline namespace
Sebastian Redlbd595762010-08-31 20:53:31 +00002577 // contains all names of all its nested inline namespaces anyway, so we can
2578 // replace the entire inline namespace tree with its root.
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002579 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002580 Ctx = Ctx->getParent();
2581
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002582 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002583}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002584
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002585// Add the associated classes and namespaces for argument-dependent
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002586// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002587static void
John McCallf24d7bb2010-05-28 18:45:08 +00002588addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2589 const TemplateArgument &Arg) {
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002590 // C++ [basic.lookup.argdep]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002591 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002592 switch (Arg.getKind()) {
2593 case TemplateArgument::Null:
2594 break;
Mike Stump11289f42009-09-09 15:08:12 +00002595
Douglas Gregor197e5f72009-07-08 07:51:57 +00002596 case TemplateArgument::Type:
2597 // [...] the namespaces and classes associated with the types of the
2598 // template arguments provided for template type parameters (excluding
2599 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002600 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002601 break;
Mike Stump11289f42009-09-09 15:08:12 +00002602
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002603 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002604 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002605 // [...] the namespaces in which any template template arguments are
2606 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002607 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002608 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002609 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002610 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002611 DeclContext *Ctx = ClassTemplate->getDeclContext();
2612 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002613 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002614 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002615 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002616 }
2617 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002619
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002620 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002621 case TemplateArgument::Integral:
2622 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002623 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002624 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002625 // associated namespaces. ]
2626 break;
Mike Stump11289f42009-09-09 15:08:12 +00002627
Douglas Gregor197e5f72009-07-08 07:51:57 +00002628 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002629 for (const auto &P : Arg.pack_elements())
2630 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002631 break;
2632 }
2633}
2634
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002635// Add the associated classes and namespaces for argument-dependent lookup
2636// with an argument of class type (C++ [basic.lookup.argdep]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002637static void
John McCallf24d7bb2010-05-28 18:45:08 +00002638addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2639 CXXRecordDecl *Class) {
2640
2641 // Just silently ignore anything whose name is __va_list_tag.
2642 if (Class->getDeclName() == Result.S.VAListTagName)
2643 return;
2644
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002645 // C++ [basic.lookup.argdep]p2:
Douglas Gregore254f902009-02-04 00:32:51 +00002646 // [...]
2647 // -- If T is a class type (including unions), its associated
2648 // classes are: the class itself; the class of which it is a
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002649 // member, if any; and its direct and indirect base classes.
2650 // Its associated namespaces are the innermost enclosing
2651 // namespaces of its associated classes.
Douglas Gregore254f902009-02-04 00:32:51 +00002652
2653 // Add the class of which it is a member, if any.
2654 DeclContext *Ctx = Class->getDeclContext();
2655 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002656 Result.Classes.insert(EnclosingClass);
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002657
Douglas Gregore254f902009-02-04 00:32:51 +00002658 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002659 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002660
Mike Stump11289f42009-09-09 15:08:12 +00002661 // -- If T is a template-id, its associated namespaces and classes are
2662 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002663 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002664 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002665 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002666 // namespaces in which any template template arguments are defined; and
2667 // the classes in which any member templates used as template template
2668 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002669 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002670 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002671 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2672 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2673 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002674 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002675 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002676 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002677
Douglas Gregor197e5f72009-07-08 07:51:57 +00002678 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2679 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002680 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002681 }
Mike Stump11289f42009-09-09 15:08:12 +00002682
Richard Smith58bd01f2019-01-16 22:01:39 +00002683 // Add the class itself. If we've already transitively visited this class,
2684 // we don't need to visit base classes.
2685 if (!Result.addClassTransitive(Class))
2686 return;
2687
John McCall67da35c2010-02-04 22:26:26 +00002688 // Only recurse into base classes for complete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00002689 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2690 Result.S.Context.getRecordType(Class)))
Richard Smith594461f2014-03-14 22:07:27 +00002691 return;
John McCall67da35c2010-02-04 22:26:26 +00002692
Douglas Gregore254f902009-02-04 00:32:51 +00002693 // Add direct and indirect base classes along with their associated
2694 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002695 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002696 Bases.push_back(Class);
2697 while (!Bases.empty()) {
2698 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002699 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002700
2701 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002702 for (const auto &Base : Class->bases()) {
2703 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002704 // In dependent contexts, we do ADL twice, and the first time around,
2705 // the base type might be a dependent TemplateSpecializationType, or a
2706 // TemplateTypeParmType. If that happens, simply ignore it.
2707 // FIXME: If we want to support export, we probably need to add the
2708 // namespace of the template in a TemplateSpecializationType, or even
2709 // the classes and namespaces of known non-dependent arguments.
2710 if (!BaseType)
2711 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002712 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith58bd01f2019-01-16 22:01:39 +00002713 if (Result.addClassTransitive(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002714 // Find the associated namespace for this base class.
2715 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002716 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002717
2718 // Make sure we visit the bases of this base class.
2719 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2720 Bases.push_back(BaseDecl);
2721 }
2722 }
2723 }
2724}
2725
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002726// Add the associated classes and namespaces for
Douglas Gregore254f902009-02-04 00:32:51 +00002727// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002728// (C++ [basic.lookup.koenig]p2).
2729static void
John McCallf24d7bb2010-05-28 18:45:08 +00002730addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002731 // C++ [basic.lookup.koenig]p2:
2732 //
2733 // For each argument type T in the function call, there is a set
2734 // of zero or more associated namespaces and a set of zero or more
2735 // associated classes to be considered. The sets of namespaces and
2736 // classes is determined entirely by the types of the function
2737 // arguments (and the namespace of any template template
2738 // argument). Typedef names and using-declarations used to specify
2739 // the types do not contribute to this set. The sets of namespaces
2740 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002741
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002742 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002743 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2744
Douglas Gregore254f902009-02-04 00:32:51 +00002745 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002746 switch (T->getTypeClass()) {
2747
2748#define TYPE(Class, Base)
2749#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2750#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2751#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2752#define ABSTRACT_TYPE(Class, Base)
2753#include "clang/AST/TypeNodes.def"
2754 // T is canonical. We can also ignore dependent types because
2755 // we don't need to do ADL at the definition point, but if we
2756 // wanted to implement template export (or if we find some other
2757 // use for associated classes and namespaces...) this would be
2758 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002759 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002760
John McCall0af3d3b2010-05-28 06:08:54 +00002761 // -- If T is a pointer to U or an array of U, its associated
2762 // namespaces and classes are those associated with U.
2763 case Type::Pointer:
2764 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2765 continue;
2766 case Type::ConstantArray:
2767 case Type::IncompleteArray:
2768 case Type::VariableArray:
2769 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2770 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002771
John McCall0af3d3b2010-05-28 06:08:54 +00002772 // -- If T is a fundamental type, its associated sets of
2773 // namespaces and classes are both empty.
2774 case Type::Builtin:
2775 break;
2776
2777 // -- If T is a class type (including unions), its associated
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002778 // classes are: the class itself; the class of which it is
2779 // a member, if any; and its direct and indirect base classes.
2780 // Its associated namespaces are the innermost enclosing
2781 // namespaces of its associated classes.
John McCall0af3d3b2010-05-28 06:08:54 +00002782 case Type::Record: {
Richard Smith82b8d4e2015-12-18 22:19:11 +00002783 CXXRecordDecl *Class =
2784 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002785 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002786 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002787 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002788
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002789 // -- If T is an enumeration type, its associated namespace
2790 // is the innermost enclosing namespace of its declaration.
2791 // If it is a class member, its associated class is the
2792 // member’s class; else it has no associated class.
John McCall0af3d3b2010-05-28 06:08:54 +00002793 case Type::Enum: {
2794 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002795
John McCall0af3d3b2010-05-28 06:08:54 +00002796 DeclContext *Ctx = Enum->getDeclContext();
2797 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002798 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002799
Bruno Ricciaf3e50a2019-04-22 12:19:00 +00002800 // Add the associated namespace for this enumeration.
John McCallf24d7bb2010-05-28 18:45:08 +00002801 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002802
John McCall0af3d3b2010-05-28 06:08:54 +00002803 break;
2804 }
2805
2806 // -- If T is a function type, its associated namespaces and
2807 // classes are those associated with the function parameter
2808 // types and those associated with the return type.
2809 case Type::FunctionProto: {
2810 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002811 for (const auto &Arg : Proto->param_types())
2812 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002813 // fallthrough
Galina Kistanova33399112017-06-03 06:35:06 +00002814 LLVM_FALLTHROUGH;
John McCall0af3d3b2010-05-28 06:08:54 +00002815 }
2816 case Type::FunctionNoProto: {
2817 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002818 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002819 continue;
2820 }
2821
2822 // -- If T is a pointer to a member function of a class X, its
2823 // associated namespaces and classes are those associated
2824 // with the function parameter types and return type,
2825 // together with those associated with X.
2826 //
2827 // -- If T is a pointer to a data member of class X, its
2828 // associated namespaces and classes are those associated
2829 // with the member type together with those associated with
2830 // X.
2831 case Type::MemberPointer: {
2832 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2833
2834 // Queue up the class type into which this points.
2835 Queue.push_back(MemberPtr->getClass());
2836
2837 // And directly continue with the pointee type.
2838 T = MemberPtr->getPointeeType().getTypePtr();
2839 continue;
2840 }
2841
2842 // As an extension, treat this like a normal pointer.
2843 case Type::BlockPointer:
2844 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2845 continue;
2846
2847 // References aren't covered by the standard, but that's such an
2848 // obvious defect that we cover them anyway.
2849 case Type::LValueReference:
2850 case Type::RValueReference:
2851 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2852 continue;
2853
2854 // These are fundamental types.
2855 case Type::Vector:
2856 case Type::ExtVector:
2857 case Type::Complex:
2858 break;
2859
Richard Smith27d807c2013-04-30 13:56:41 +00002860 // Non-deduced auto types only get here for error cases.
2861 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002862 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00002863 break;
2864
Fangrui Song6907ce22018-07-30 19:24:48 +00002865 // If T is an Objective-C object or interface type, or a pointer to an
Douglas Gregor8e936662011-04-12 01:02:45 +00002866 // object or interface type, the associated namespace is the global
2867 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002868 case Type::ObjCObject:
2869 case Type::ObjCInterface:
2870 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002871 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002872 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002873
2874 // Atomic types are just wrappers; use the associations of the
2875 // contained type.
2876 case Type::Atomic:
2877 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2878 continue;
Xiuli Pan9c14e282016-01-09 12:53:17 +00002879 case Type::Pipe:
2880 T = cast<PipeType>(T)->getElementType().getTypePtr();
2881 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002882 }
2883
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002884 if (Queue.empty())
2885 break;
2886 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002887 }
Douglas Gregore254f902009-02-04 00:32:51 +00002888}
2889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002890/// Find the associated classes and namespaces for
Douglas Gregore254f902009-02-04 00:32:51 +00002891/// argument-dependent lookup for a call with the given set of
2892/// arguments.
2893///
2894/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002895/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002896/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002897void Sema::FindAssociatedClassesAndNamespaces(
2898 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2899 AssociatedNamespaceSet &AssociatedNamespaces,
2900 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002901 AssociatedNamespaces.clear();
2902 AssociatedClasses.clear();
2903
John McCall7d8b0412012-08-24 20:38:34 +00002904 AssociatedLookup Result(*this, InstantiationLoc,
2905 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002906
Douglas Gregore254f902009-02-04 00:32:51 +00002907 // C++ [basic.lookup.koenig]p2:
2908 // For each argument type T in the function call, there is a set
2909 // of zero or more associated namespaces and a set of zero or more
2910 // associated classes to be considered. The sets of namespaces and
2911 // classes is determined entirely by the types of the function
2912 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002913 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002914 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002915 Expr *Arg = Args[ArgIdx];
2916
2917 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002918 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002919 continue;
2920 }
2921
2922 // [...] In addition, if the argument is the name or address of a
2923 // set of overloaded functions and/or function templates, its
2924 // associated classes and namespaces are the union of those
2925 // associated with each of the members of the set: the namespace
2926 // in which the function or function template is defined and the
2927 // classes and namespaces associated with its (non-dependent)
2928 // parameter types and return type.
Richard Smith58bd01f2019-01-16 22:01:39 +00002929 OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
Mike Stump11289f42009-09-09 15:08:12 +00002930
Richard Smith58bd01f2019-01-16 22:01:39 +00002931 for (const NamedDecl *D : OE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002932 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002933 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002934
2935 // Add the classes and namespaces associated with the parameter
2936 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002937 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002938 }
2939 }
2940}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002941
John McCall5cebab12009-11-18 07:57:50 +00002942NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002943 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002944 LookupNameKind NameKind,
2945 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002946 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002947 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002948 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002949}
2950
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002951/// Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002953 SourceLocation IdLoc,
2954 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002955 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002956 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002957 return cast_or_null<ObjCProtocolDecl>(D);
2958}
2959
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002960void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002961 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002962 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002963 // C++ [over.match.oper]p3:
2964 // -- The set of non-member candidates is the result of the
2965 // unqualified lookup of operator@ in the context of the
2966 // expression according to the usual rules for name lookup in
2967 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002968 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002969 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002970 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2971 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002972
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002973 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002974 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002975}
2976
Richard Smith8bae1be2017-02-24 02:07:20 +00002977Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
2978 CXXSpecialMember SM,
2979 bool ConstArg,
2980 bool VolatileArg,
2981 bool RValueThis,
2982 bool ConstThis,
2983 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002984 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002985 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002986 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002987 if (RValueThis || ConstThis || VolatileThis)
2988 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2989 "constructors and destructors always have unqualified lvalue this");
2990 if (ConstArg || VolatileArg)
2991 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2992 "parameter-less special members can't have qualified arguments");
2993
Richard Smith171e4b52017-02-15 04:18:23 +00002994 // FIXME: Get the caller to pass in a location for the lookup.
2995 SourceLocation LookupLoc = RD->getLocation();
2996
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002997 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002998 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002999 ID.AddInteger(SM);
3000 ID.AddInteger(ConstArg);
3001 ID.AddInteger(VolatileArg);
3002 ID.AddInteger(RValueThis);
3003 ID.AddInteger(ConstThis);
3004 ID.AddInteger(VolatileThis);
3005
3006 void *InsertPoint;
Richard Smith8bae1be2017-02-24 02:07:20 +00003007 SpecialMemberOverloadResultEntry *Result =
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003008 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3009
3010 // This was already cached
3011 if (Result)
Richard Smith8bae1be2017-02-24 02:07:20 +00003012 return *Result;
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003013
Richard Smith8bae1be2017-02-24 02:07:20 +00003014 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
3015 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003016 SpecialMemberCache.InsertNode(Result, InsertPoint);
3017
3018 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00003019 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00003020 DeclareImplicitDestructor(RD);
3021 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003022 assert(DD && "record without a destructor");
3023 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00003024 Result->setKind(DD->isDeleted() ?
3025 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00003026 SpecialMemberOverloadResult::Success);
Richard Smith8bae1be2017-02-24 02:07:20 +00003027 return *Result;
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003028 }
3029
Alexis Hunteef8ee02011-06-10 03:50:41 +00003030 // Prepare for overload resolution. Here we construct a synthetic argument
3031 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00003032 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00003033 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00003034 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00003035 unsigned NumArgs;
3036
Richard Smith83c478d2012-04-20 18:46:14 +00003037 QualType ArgType = CanTy;
3038 ExprValueKind VK = VK_LValue;
3039
Alexis Hunteef8ee02011-06-10 03:50:41 +00003040 if (SM == CXXDefaultConstructor) {
3041 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3042 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00003043 if (RD->needsImplicitDefaultConstructor())
3044 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003045 } else {
3046 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
3047 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00003048 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00003049 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003050 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003051 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003052 } else {
3053 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00003054 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00003055 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003056 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003057 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003058 }
3059
Alexis Hunteef8ee02011-06-10 03:50:41 +00003060 if (ConstArg)
3061 ArgType.addConst();
3062 if (VolatileArg)
3063 ArgType.addVolatile();
3064
3065 // This isn't /really/ specified by the standard, but it's implied
3066 // we should be working from an RValue in the case of move to ensure
3067 // that we prefer to bind to rvalue references, and an LValue in the
3068 // case of copy to ensure we don't bind to rvalue references.
3069 // Possibly an XValue is actually correct in the case of move, but
3070 // there is no semantic difference for class types in this restricted
3071 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00003072 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00003073 VK = VK_LValue;
3074 else
3075 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00003076 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00003077
Richard Smith171e4b52017-02-15 04:18:23 +00003078 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
Richard Smith83c478d2012-04-20 18:46:14 +00003079
3080 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003081 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00003082 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00003083 }
3084
3085 // Create the object argument
3086 QualType ThisTy = CanTy;
3087 if (ConstThis)
3088 ThisTy.addConst();
3089 if (VolatileThis)
3090 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00003091 Expr::Classification Classification =
Richard Smith171e4b52017-02-15 04:18:23 +00003092 OpaqueValueExpr(LookupLoc, ThisTy,
Richard Smith83c478d2012-04-20 18:46:14 +00003093 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003094
3095 // Now we perform lookup on the name we computed earlier and do overload
3096 // resolution. Lookup is only performed directly into the class since there
3097 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith171e4b52017-02-15 04:18:23 +00003098 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00003099 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00003100
3101 if (R.empty()) {
3102 // We might have no default constructor because we have a lambda's closure
3103 // type, rather than because there's some other declared constructor.
3104 // Every class has a copy/move constructor, copy/move assignment, and
3105 // destructor.
3106 assert(SM == CXXDefaultConstructor &&
3107 "lookup for a constructor or assignment operator was empty");
3108 Result->setMethod(nullptr);
3109 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Richard Smith8bae1be2017-02-24 02:07:20 +00003110 return *Result;
Richard Smith8c37ab52015-02-11 01:48:47 +00003111 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00003112
3113 // Copy the candidates as our processing of them may load new declarations
3114 // from an external source and invalidate lookup_result.
3115 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3116
Richard Smith5179eb72016-06-28 19:03:57 +00003117 for (NamedDecl *CandDecl : Candidates) {
3118 if (CandDecl->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00003119 continue;
3120
Richard Smith5179eb72016-06-28 19:03:57 +00003121 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
3122 auto CtorInfo = getConstructorInfo(Cand);
3123 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
Alexis Hunt080709f2011-06-23 00:26:20 +00003124 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Richard Smith5179eb72016-06-28 19:03:57 +00003125 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3126 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3127 else if (CtorInfo)
3128 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
Richard Smith76b90272019-05-09 03:59:21 +00003129 llvm::makeArrayRef(&Arg, NumArgs), OCS,
3130 /*SuppressUserConversions*/ true);
Alexis Hunt080709f2011-06-23 00:26:20 +00003131 else
Richard Smith5179eb72016-06-28 19:03:57 +00003132 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
Richard Smith76b90272019-05-09 03:59:21 +00003133 /*SuppressUserConversions*/ true);
Richard Smith5179eb72016-06-28 19:03:57 +00003134 } else if (FunctionTemplateDecl *Tmpl =
3135 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3136 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3137 AddMethodTemplateCandidate(
3138 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
George Burgess IVce6284b2017-01-28 02:19:40 +00003139 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Richard Smith5179eb72016-06-28 19:03:57 +00003140 else if (CtorInfo)
3141 AddTemplateOverloadCandidate(
3142 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3143 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3144 else
3145 AddTemplateOverloadCandidate(
3146 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00003147 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00003148 assert(isa<UsingDecl>(Cand.getDecl()) &&
3149 "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00003150 }
3151 }
3152
3153 OverloadCandidateSet::iterator Best;
Richard Smith171e4b52017-02-15 04:18:23 +00003154 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003155 case OR_Success:
3156 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00003157 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003158 break;
3159
3160 case OR_Deleted:
3161 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00003162 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003163 break;
3164
3165 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00003166 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003167 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3168 break;
3169
Alexis Hunteef8ee02011-06-10 03:50:41 +00003170 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00003171 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003172 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003173 break;
3174 }
3175
Richard Smith8bae1be2017-02-24 02:07:20 +00003176 return *Result;
Alexis Hunteef8ee02011-06-10 03:50:41 +00003177}
3178
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003179/// Look up the default constructor for the given class.
Alexis Hunteef8ee02011-06-10 03:50:41 +00003180CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Richard Smith8bae1be2017-02-24 02:07:20 +00003181 SpecialMemberOverloadResult Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00003182 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3183 false, false);
3184
Richard Smith8bae1be2017-02-24 02:07:20 +00003185 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003186}
3187
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003188/// Look up the copying constructor for the given class.
Alexis Hunt491ec602011-06-21 23:42:56 +00003189CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00003190 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003191 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3192 "non-const, non-volatile qualifiers for copy ctor arg");
Richard Smith8bae1be2017-02-24 02:07:20 +00003193 SpecialMemberOverloadResult Result =
Alexis Hunt899bd442011-06-10 04:44:37 +00003194 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3195 Quals & Qualifiers::Volatile, false, false, false);
3196
Richard Smith8bae1be2017-02-24 02:07:20 +00003197 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Alexis Hunt899bd442011-06-10 04:44:37 +00003198}
3199
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003200/// Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00003201CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3202 unsigned Quals) {
Richard Smith8bae1be2017-02-24 02:07:20 +00003203 SpecialMemberOverloadResult Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003204 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3205 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003206
Richard Smith8bae1be2017-02-24 02:07:20 +00003207 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003208}
3209
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003210/// Look up the constructors for the given class.
Douglas Gregor52b72822010-07-02 23:12:18 +00003211DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003212 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00003213 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00003214 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003215 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00003216 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003217 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003218 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003219 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00003220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221
Douglas Gregor52b72822010-07-02 23:12:18 +00003222 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3223 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3224 return Class->lookup(Name);
3225}
3226
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003227/// Look up the copying assignment operator for the given class.
Alexis Hunt491ec602011-06-21 23:42:56 +00003228CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3229 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00003230 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00003231 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3232 "non-const, non-volatile qualifiers for copy assignment arg");
3233 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3234 "non-const, non-volatile qualifiers for copy assignment this");
Richard Smith8bae1be2017-02-24 02:07:20 +00003235 SpecialMemberOverloadResult Result =
Alexis Hunt491ec602011-06-21 23:42:56 +00003236 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3237 Quals & Qualifiers::Volatile, RValueThis,
3238 ThisQuals & Qualifiers::Const,
3239 ThisQuals & Qualifiers::Volatile);
3240
Richard Smith8bae1be2017-02-24 02:07:20 +00003241 return Result.getMethod();
Alexis Hunt491ec602011-06-21 23:42:56 +00003242}
3243
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003244/// Look up the moving assignment operator for the given class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00003245CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00003246 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003247 bool RValueThis,
3248 unsigned ThisQuals) {
3249 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3250 "non-const, non-volatile qualifiers for copy assignment this");
Richard Smith8bae1be2017-02-24 02:07:20 +00003251 SpecialMemberOverloadResult Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003252 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3253 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003254 ThisQuals & Qualifiers::Const,
3255 ThisQuals & Qualifiers::Volatile);
3256
Richard Smith8bae1be2017-02-24 02:07:20 +00003257 return Result.getMethod();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003258}
3259
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003260/// Look for the destructor of the given class.
Douglas Gregore71edda2010-07-01 22:47:18 +00003261///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00003262/// During semantic analysis, this routine should be used in lieu of
3263/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00003264///
3265/// \returns The destructor for this class.
3266CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003267 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3268 false, false, false,
Richard Smith8bae1be2017-02-24 02:07:20 +00003269 false, false).getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00003270}
3271
Richard Smithbcc22fc2012-03-09 08:00:36 +00003272/// LookupLiteralOperator - Determine which literal operator should be used for
3273/// a user-defined literal, per C++11 [lex.ext].
3274///
3275/// Normal overload resolution is not used to select which literal operator to
3276/// call for a user-defined literal. Look up the provided literal operator name,
3277/// and filter the results to the appropriate set for the given argument types.
3278Sema::LiteralOperatorLookupResult
3279Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3280 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00003281 bool AllowRaw, bool AllowTemplate,
Tim Northover97103382017-08-09 14:56:48 +00003282 bool AllowStringTemplate, bool DiagnoseMissing) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003283 LookupName(R, S);
3284 assert(R.getResultKind() != LookupResult::Ambiguous &&
3285 "literal operator lookup can't be ambiguous");
3286
3287 // Filter the lookup results appropriately.
3288 LookupResult::Filter F = R.makeFilter();
3289
Richard Smithbcc22fc2012-03-09 08:00:36 +00003290 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00003291 bool FoundTemplate = false;
3292 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003293 bool FoundExactMatch = false;
3294
3295 while (F.hasNext()) {
3296 Decl *D = F.next();
3297 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3298 D = USD->getTargetDecl();
3299
Douglas Gregorc1970572013-04-10 05:18:00 +00003300 // If the declaration we found is invalid, skip it.
3301 if (D->isInvalidDecl()) {
3302 F.erase();
3303 continue;
3304 }
3305
Richard Smithb8b41d32013-10-07 19:57:58 +00003306 bool IsRaw = false;
3307 bool IsTemplate = false;
3308 bool IsStringTemplate = false;
3309 bool IsExactMatch = false;
3310
Richard Smithbcc22fc2012-03-09 08:00:36 +00003311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3312 if (FD->getNumParams() == 1 &&
3313 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3314 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003315 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003316 IsExactMatch = true;
3317 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3318 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3319 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3320 IsExactMatch = false;
3321 break;
3322 }
3323 }
3324 }
3325 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003326 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3327 TemplateParameterList *Params = FD->getTemplateParameters();
3328 if (Params->size() == 1)
3329 IsTemplate = true;
3330 else
3331 IsStringTemplate = true;
3332 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003333
3334 if (IsExactMatch) {
3335 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003336 AllowRaw = false;
3337 AllowTemplate = false;
3338 AllowStringTemplate = false;
3339 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003340 // Go through again and remove the raw and template decls we've
3341 // already found.
3342 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003343 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003344 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003345 } else if (AllowRaw && IsRaw) {
3346 FoundRaw = true;
3347 } else if (AllowTemplate && IsTemplate) {
3348 FoundTemplate = true;
3349 } else if (AllowStringTemplate && IsStringTemplate) {
3350 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003351 } else {
3352 F.erase();
3353 }
3354 }
3355
3356 F.done();
3357
3358 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3359 // parameter type, that is used in preference to a raw literal operator
3360 // or literal operator template.
3361 if (FoundExactMatch)
3362 return LOLR_Cooked;
3363
3364 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3365 // operator template, but not both.
3366 if (FoundRaw && FoundTemplate) {
3367 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003368 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
Richard Smithc2bebe92016-05-11 20:37:46 +00003369 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003370 return LOLR_Error;
3371 }
3372
3373 if (FoundRaw)
3374 return LOLR_Raw;
3375
3376 if (FoundTemplate)
3377 return LOLR_Template;
3378
Richard Smithb8b41d32013-10-07 19:57:58 +00003379 if (FoundStringTemplate)
3380 return LOLR_StringTemplate;
3381
Richard Smithbcc22fc2012-03-09 08:00:36 +00003382 // Didn't find anything we could use.
Tim Northover97103382017-08-09 14:56:48 +00003383 if (DiagnoseMissing) {
3384 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3385 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3386 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3387 << (AllowTemplate || AllowStringTemplate);
3388 return LOLR_Error;
3389 }
3390
3391 return LOLR_ErrorNoDiagnostic;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003392}
3393
John McCall8fe68082010-01-26 07:16:45 +00003394void ADLResult::insert(NamedDecl *New) {
3395 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3396
3397 // If we haven't yet seen a decl for this key, or the last decl
3398 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003399 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003400 Old = New;
3401 return;
3402 }
3403
3404 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003405 FunctionDecl *OldFD = Old->getAsFunction();
3406 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003407
3408 FunctionDecl *Cursor = NewFD;
3409 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003410 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003411
3412 // If we got to the end without finding OldFD, OldFD is the newer
3413 // declaration; leave things as they are.
3414 if (!Cursor) return;
3415
3416 // If we do find OldFD, then NewFD is newer.
3417 if (Cursor == OldFD) break;
3418
3419 // Otherwise, keep looking.
3420 }
3421
3422 Old = New;
3423}
3424
Richard Smith100b24a2014-04-17 01:52:14 +00003425void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3426 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003427 // Find all of the associated namespaces and classes based on the
3428 // arguments we have.
3429 AssociatedNamespaceSet AssociatedNamespaces;
3430 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003431 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003432 AssociatedNamespaces,
3433 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003434
3435 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003436 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3437 // and let Y be the lookup set produced by argument dependent
3438 // lookup (defined as follows). If X contains [...] then Y is
3439 // empty. Otherwise Y is the set of declarations found in the
3440 // namespaces associated with the argument types as described
3441 // below. The set of declarations found by the lookup of the name
3442 // is the union of X and Y.
3443 //
3444 // Here, we compute Y and add its members to the overloaded
3445 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003446 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003447 // When considering an associated namespace, the lookup is the
3448 // same as the lookup performed when the associated namespace is
3449 // used as a qualifier (3.4.3.2) except that:
3450 //
3451 // -- Any using-directives in the associated namespace are
3452 // ignored.
3453 //
John McCallc7e8e792009-08-07 22:18:02 +00003454 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003455 // associated classes are visible within their respective
3456 // namespaces even if they are not visible during an ordinary
3457 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003458 DeclContext::lookup_result R = NS->lookup(Name);
3459 for (auto *D : R) {
Richard Smith041740f2018-01-06 00:09:23 +00003460 auto *Underlying = D;
3461 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3462 Underlying = USD->getTargetDecl();
3463
3464 if (!isa<FunctionDecl>(Underlying) &&
3465 !isa<FunctionTemplateDecl>(Underlying))
3466 continue;
3467
Richard Smith8ce732b2019-01-07 06:00:46 +00003468 // The declaration is visible to argument-dependent lookup if either
3469 // it's ordinarily visible or declared as a friend in an associated
3470 // class.
3471 bool Visible = false;
3472 for (D = D->getMostRecentDecl(); D;
3473 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3474 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3475 if (isVisible(D)) {
3476 Visible = true;
3477 break;
3478 }
3479 } else if (D->getFriendObjectKind()) {
3480 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3481 if (AssociatedClasses.count(RD) && isVisible(D)) {
3482 Visible = true;
Richard Smith64017682013-07-17 23:53:16 +00003483 break;
3484 }
3485 }
John McCalld1e9d832009-08-11 06:59:38 +00003486 }
Mike Stump11289f42009-09-09 15:08:12 +00003487
Richard Smith197f68d2017-10-11 01:49:57 +00003488 // FIXME: Preserve D as the FoundDecl.
Richard Smith8ce732b2019-01-07 06:00:46 +00003489 if (Visible)
3490 Result.insert(Underlying);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003491 }
3492 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003493}
Douglas Gregor2d435302009-12-30 17:04:44 +00003494
3495//----------------------------------------------------------------------------
3496// Search for all visible declarations.
3497//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003498VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003499
Richard Smithe156254d2013-08-20 20:35:18 +00003500bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3501
Douglas Gregor2d435302009-12-30 17:04:44 +00003502namespace {
3503
3504class ShadowContextRAII;
3505
3506class VisibleDeclsRecord {
3507public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003508 /// An entry in the shadow map, which is optimized to store a
Douglas Gregor2d435302009-12-30 17:04:44 +00003509 /// single declaration (the common case) but can also store a list
3510 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003511 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003512
3513private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003514 /// A mapping from declaration names to the declarations that have
Douglas Gregor2d435302009-12-30 17:04:44 +00003515 /// this name within a particular scope.
3516 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3517
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003518 /// A list of shadow maps, which is used to model name hiding.
Douglas Gregor2d435302009-12-30 17:04:44 +00003519 std::list<ShadowMap> ShadowMaps;
3520
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003521 /// The declaration contexts we have already visited.
Douglas Gregor2d435302009-12-30 17:04:44 +00003522 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3523
3524 friend class ShadowContextRAII;
3525
3526public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003527 /// Determine whether we have already visited this context
Douglas Gregor2d435302009-12-30 17:04:44 +00003528 /// (and, if not, note that we are going to visit that context now).
3529 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003530 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003531 }
3532
Douglas Gregor39982192010-08-15 06:18:01 +00003533 bool alreadyVisitedContext(DeclContext *Ctx) {
3534 return VisitedContexts.count(Ctx);
3535 }
3536
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003537 /// Determine whether the given declaration is hidden in the
Douglas Gregor2d435302009-12-30 17:04:44 +00003538 /// current scope.
3539 ///
3540 /// \returns the declaration that hides the given declaration, or
3541 /// NULL if no such declaration exists.
3542 NamedDecl *checkHidden(NamedDecl *ND);
3543
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003544 /// Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003545 void add(NamedDecl *ND) {
3546 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3547 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003548};
3549
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003550/// RAII object that records when we've entered a shadow context.
Douglas Gregor2d435302009-12-30 17:04:44 +00003551class ShadowContextRAII {
3552 VisibleDeclsRecord &Visible;
3553
3554 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3555
3556public:
3557 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003558 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003559 }
3560
3561 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003562 Visible.ShadowMaps.pop_back();
3563 }
3564};
3565
3566} // end anonymous namespace
3567
Douglas Gregor2d435302009-12-30 17:04:44 +00003568NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3569 unsigned IDNS = ND->getIdentifierNamespace();
3570 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3571 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3572 SM != SMEnd; ++SM) {
3573 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3574 if (Pos == SM->end())
3575 continue;
3576
Aaron Ballman1e606f42014-07-15 22:03:49 +00003577 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003578 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003579 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003581 Decl::IDNS_ObjCProtocol)))
3582 continue;
3583
3584 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003585 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003586 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003587 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003588 continue;
3589
Douglas Gregor09bbc652010-01-14 15:47:35 +00003590 // Functions and function templates in the same scope overload
3591 // rather than hide. FIXME: Look for hiding based on function
3592 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003593 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003594 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003595 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003596 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597
Alex Lorenze7e8f802017-01-23 17:23:23 +00003598 // A shadow declaration that's created by a resolved using declaration
3599 // is not hidden by the same using declaration.
3600 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3601 cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3602 continue;
3603
Douglas Gregor2d435302009-12-30 17:04:44 +00003604 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003605 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003606 }
3607 }
3608
Craig Topperc3ec1492014-05-26 06:22:03 +00003609 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003610}
3611
3612static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3613 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003614 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003615 VisibleDeclConsumer &Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003616 VisibleDeclsRecord &Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003617 bool IncludeDependentBases,
3618 bool LoadExternal) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003619 if (!Ctx)
3620 return;
3621
Douglas Gregor2d435302009-12-30 17:04:44 +00003622 // Make sure we don't visit the same context twice.
3623 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3624 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003625
Haojian Wu10d95c52018-01-17 14:29:25 +00003626 Consumer.EnteredContext(Ctx);
3627
Richard Smith9e2341d2015-03-23 03:25:59 +00003628 // Outside C++, lookup results for the TU live on identifiers.
3629 if (isa<TranslationUnitDecl>(Ctx) &&
3630 !Result.getSema().getLangOpts().CPlusPlus) {
3631 auto &S = Result.getSema();
3632 auto &Idents = S.Context.Idents;
3633
3634 // Ensure all external identifiers are in the identifier table.
Sam McCallbb2cf632018-01-12 14:51:47 +00003635 if (LoadExternal)
3636 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3637 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3638 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3639 Idents.get(Name);
3640 }
Richard Smith9e2341d2015-03-23 03:25:59 +00003641
3642 // Walk all lookup results in the TU for each identifier.
3643 for (const auto &Ident : Idents) {
3644 for (auto I = S.IdResolver.begin(Ident.getValue()),
3645 E = S.IdResolver.end();
3646 I != E; ++I) {
3647 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3648 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3649 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3650 Visited.add(ND);
3651 }
3652 }
3653 }
3654 }
3655
3656 return;
3657 }
3658
Douglas Gregor7454c562010-07-02 20:37:36 +00003659 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3660 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3661
Sam McCallabdcc612018-01-24 17:50:20 +00003662 // We sometimes skip loading namespace-level results (they tend to be huge).
3663 bool Load = LoadExternal ||
3664 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
Douglas Gregor2d435302009-12-30 17:04:44 +00003665 // Enumerate all of the results in this context.
Sam McCallbb2cf632018-01-12 14:51:47 +00003666 for (DeclContextLookupResult R :
Sam McCallabdcc612018-01-24 17:50:20 +00003667 Load ? Ctx->lookups()
3668 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003669 for (auto *D : R) {
3670 if (auto *ND = Result.getAcceptableDecl(D)) {
3671 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3672 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003673 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003674 }
3675 }
3676
3677 // Traverse using directives for qualified name lookup.
3678 if (QualifiedNameLookup) {
3679 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003680 for (auto I : Ctx->using_directives()) {
Richard Smithb920f852017-10-11 01:19:11 +00003681 if (!Result.getSema().isVisible(I))
3682 continue;
Aaron Ballman63ab7602014-03-07 13:44:44 +00003683 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Alex Lorenze6afa392017-05-11 13:48:57 +00003684 QualifiedNameLookup, InBaseClass, Consumer, Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003685 IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003686 }
3687 }
3688
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003689 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003690 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003691 if (!Record->hasDefinition())
3692 return;
3693
Aaron Ballman574705e2014-03-13 15:41:46 +00003694 for (const auto &B : Record->bases()) {
3695 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696
Alex Lorenze6afa392017-05-11 13:48:57 +00003697 RecordDecl *RD;
3698 if (BaseType->isDependentType()) {
3699 if (!IncludeDependentBases) {
3700 // Don't look into dependent bases, because name lookup can't look
3701 // there anyway.
3702 continue;
3703 }
3704 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3705 if (!TST)
3706 continue;
3707 TemplateName TN = TST->getTemplateName();
3708 const auto *TD =
3709 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3710 if (!TD)
3711 continue;
3712 RD = TD->getTemplatedDecl();
3713 } else {
3714 const auto *Record = BaseType->getAs<RecordType>();
3715 if (!Record)
3716 continue;
3717 RD = Record->getDecl();
3718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719
Douglas Gregor2d435302009-12-30 17:04:44 +00003720 // FIXME: It would be nice to be able to determine whether referencing
3721 // a particular member would be ambiguous. For example, given
3722 //
3723 // struct A { int member; };
3724 // struct B { int member; };
3725 // struct C : A, B { };
3726 //
3727 // void f(C *c) { c->### }
3728 //
3729 // accessing 'member' would result in an ambiguity. However, we
3730 // could be smart enough to qualify the member with the base
3731 // class, e.g.,
3732 //
3733 // c->B::member
3734 //
3735 // or
3736 //
3737 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738
Douglas Gregor2d435302009-12-30 17:04:44 +00003739 // Find results in this base class (and its bases).
3740 ShadowContextRAII Shadow(Visited);
Eric Liub91e0812018-10-02 10:29:00 +00003741 LookupVisibleDecls(RD, Result, QualifiedNameLookup, /*InBaseClass=*/true,
3742 Consumer, Visited, IncludeDependentBases,
3743 LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003744 }
3745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003747 // Traverse the contexts of Objective-C classes.
3748 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3749 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003750 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003751 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003752 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, Consumer,
3753 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003754 }
3755
3756 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003757 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003758 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003759 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003760 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003761 }
3762
3763 // Traverse the superclass.
3764 if (IFace->getSuperClass()) {
3765 ShadowContextRAII Shadow(Visited);
3766 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Sam McCallbb2cf632018-01-12 14:51:47 +00003767 true, Consumer, Visited, IncludeDependentBases,
3768 LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
Douglas Gregor0b59e802010-04-19 18:02:19 +00003771 // If there is an implementation, traverse it. We do this to find
3772 // synthesized ivars.
3773 if (IFace->getImplementation()) {
3774 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003775 LookupVisibleDecls(IFace->getImplementation(), Result,
Sam McCallbb2cf632018-01-12 14:51:47 +00003776 QualifiedNameLookup, InBaseClass, Consumer, Visited,
3777 IncludeDependentBases, LoadExternal);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003778 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003779 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003780 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003781 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003782 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003783 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003784 }
3785 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003786 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003787 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003788 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003789 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791
Douglas Gregor0b59e802010-04-19 18:02:19 +00003792 // If there is an implementation, traverse it.
3793 if (Category->getImplementation()) {
3794 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795 LookupVisibleDecls(Category->getImplementation(), Result,
Sam McCallbb2cf632018-01-12 14:51:47 +00003796 QualifiedNameLookup, true, Consumer, Visited,
3797 IncludeDependentBases, LoadExternal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003798 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003799 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003800}
3801
3802static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3803 UnqualUsingDirectiveSet &UDirs,
3804 VisibleDeclConsumer &Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003805 VisibleDeclsRecord &Visited,
3806 bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003807 if (!S)
3808 return;
3809
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003810 if (!S->getEntity() ||
3811 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003812 !Visited.alreadyVisitedContext(S->getEntity())) ||
3813 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003814 FindLocalExternScope FindLocals(Result);
Benjamin Kramer17ba6692017-10-13 22:14:34 +00003815 // Walk through the declarations in this Scope. The consumer might add new
3816 // decls to the scope as part of deserialization, so make a copy first.
3817 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
3818 for (Decl *D : ScopeDecls) {
Aaron Ballman35c54952014-03-17 16:55:25 +00003819 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003820 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003821 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003822 Visited.add(ND);
3823 }
3824 }
3825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003826
Douglas Gregor66230062010-03-15 14:33:29 +00003827 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003828 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003829 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003830 // Look into this scope's declaration context, along with any of its
3831 // parent lookup contexts (e.g., enclosing classes), up to the point
3832 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003833 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003834 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835
Douglas Gregorea166062010-03-15 15:26:48 +00003836 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003837 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003838 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3839 if (Method->isInstanceMethod()) {
3840 // For instance methods, look for ivars in the method's interface.
3841 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3842 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003843 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003844 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003845 /*InBaseClass=*/false, Consumer, Visited,
3846 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003847 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003848 }
3849
3850 // We've already performed all of the name lookup that we need
3851 // to for Objective-C methods; the next context will be the
3852 // outer scope.
3853 break;
3854 }
3855
Douglas Gregor2d435302009-12-30 17:04:44 +00003856 if (Ctx->isFunctionOrMethod())
3857 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858
3859 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003860 /*InBaseClass=*/false, Consumer, Visited,
3861 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003862 }
3863 } else if (!S->getParent()) {
3864 // Look into the translation unit scope. We walk through the translation
3865 // unit's declaration context, because the Scope itself won't have all of
3866 // the declarations if we loaded a precompiled header.
3867 // FIXME: We would like the translation unit's Scope object to point to the
3868 // translation unit, so we don't need this special "if" branch. However,
3869 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003871 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003872 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003873 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003875 /*InBaseClass=*/false, Consumer, Visited,
3876 /*IncludeDependentBases=*/false, LoadExternal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003877 }
3878
Douglas Gregor2d435302009-12-30 17:04:44 +00003879 if (Entity) {
3880 // Lookup visible declarations in any namespaces found by using
3881 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003882 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3883 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884 Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003885 /*InBaseClass=*/false, Consumer, Visited,
3886 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003887 }
3888
3889 // Lookup names in the parent scope.
3890 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003891 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited,
3892 LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003893}
3894
3895void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003896 VisibleDeclConsumer &Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003897 bool IncludeGlobalScope, bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003898 // Determine the set of using directives available during
3899 // unqualified name lookup.
3900 Scope *Initial = S;
Richard Smithb920f852017-10-11 01:19:11 +00003901 UnqualUsingDirectiveSet UDirs(*this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003902 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003903 // Find the first namespace or translation-unit scope.
3904 while (S && !isNamespaceOrTranslationUnitScope(S))
3905 S = S->getParent();
3906
3907 UDirs.visitScopeChain(Initial, S);
3908 }
3909 UDirs.done();
3910
3911 // Look for visible declarations.
3912 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003913 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003914 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003915 if (!IncludeGlobalScope)
3916 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003917 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003918 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003919}
3920
3921void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003922 VisibleDeclConsumer &Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003923 bool IncludeGlobalScope,
Sam McCallbb2cf632018-01-12 14:51:47 +00003924 bool IncludeDependentBases, bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003925 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003926 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003927 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003928 if (!IncludeGlobalScope)
3929 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003930 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Alex Lorenze6afa392017-05-11 13:48:57 +00003932 /*InBaseClass=*/false, Consumer, Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003933 IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003934}
3935
Chris Lattner43e7f312011-02-18 02:08:43 +00003936/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003937/// If GnuLabelLoc is a valid source location, then this is a definition
3938/// of an __label__ label name, otherwise it is a normal label definition
3939/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003940LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003941 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003942 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003943 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003944
3945 if (GnuLabelLoc.isValid()) {
3946 // Local label definitions always shadow existing labels.
3947 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3948 Scope *S = CurScope;
3949 PushOnScopeChains(Res, S, true);
3950 return cast<LabelDecl>(Res);
3951 }
3952
3953 // Not a GNU local label.
3954 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3955 // If we found a label, check to see if it is in the same context as us.
3956 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003957 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003958 Res = nullptr;
3959 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003960 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003961 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3962 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003963 assert(S && "Not in a function?");
3964 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003965 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003966 return cast<LabelDecl>(Res);
3967}
3968
3969//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003970// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003971//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003972
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003973static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3974 TypoCorrection &Candidate) {
3975 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3976 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3977}
3978
3979static void LookupPotentialTypoResult(Sema &SemaRef,
3980 LookupResult &Res,
3981 IdentifierInfo *Name,
3982 Scope *S, CXXScopeSpec *SS,
3983 DeclContext *MemberContext,
3984 bool EnteringContext,
3985 bool isObjCIvarLookup,
3986 bool FindHidden);
3987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003988/// Check whether the declarations found for a typo correction are
Richard Smith3092d722017-06-05 22:29:36 +00003989/// visible. Set the correction's RequiresImport flag to true if none of the
3990/// declarations are visible, false otherwise.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003991static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003992 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3993
3994 for (/**/; DI != DE; ++DI)
3995 if (!LookupResult::isVisible(SemaRef, *DI))
3996 break;
Richard Smith3092d722017-06-05 22:29:36 +00003997 // No filtering needed if all decls are visible.
3998 if (DI == DE) {
3999 TC.setRequiresImport(false);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004000 return;
Richard Smith3092d722017-06-05 22:29:36 +00004001 }
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004002
4003 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4004 bool AnyVisibleDecls = !NewDecls.empty();
4005
4006 for (/**/; DI != DE; ++DI) {
Richard Smith041740f2018-01-06 00:09:23 +00004007 if (LookupResult::isVisible(SemaRef, *DI)) {
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004008 if (!AnyVisibleDecls) {
4009 // Found a visible decl, discard all hidden ones.
4010 AnyVisibleDecls = true;
4011 NewDecls.clear();
4012 }
Richard Smith041740f2018-01-06 00:09:23 +00004013 NewDecls.push_back(*DI);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004014 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4015 NewDecls.push_back(*DI);
4016 }
4017
4018 if (NewDecls.empty())
4019 TC = TypoCorrection();
4020 else {
4021 TC.setCorrectionDecls(NewDecls);
4022 TC.setRequiresImport(!AnyVisibleDecls);
4023 }
4024}
4025
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004026// Fill the supplied vector with the IdentifierInfo pointers for each piece of
4027// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4028// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4029static void getNestedNameSpecifierIdentifiers(
4030 NestedNameSpecifier *NNS,
4031 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
4032 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4033 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4034 else
4035 Identifiers.clear();
4036
4037 const IdentifierInfo *II = nullptr;
4038
4039 switch (NNS->getKind()) {
4040 case NestedNameSpecifier::Identifier:
4041 II = NNS->getAsIdentifier();
4042 break;
4043
4044 case NestedNameSpecifier::Namespace:
4045 if (NNS->getAsNamespace()->isAnonymousNamespace())
4046 return;
4047 II = NNS->getAsNamespace()->getIdentifier();
4048 break;
4049
4050 case NestedNameSpecifier::NamespaceAlias:
4051 II = NNS->getAsNamespaceAlias()->getIdentifier();
4052 break;
4053
4054 case NestedNameSpecifier::TypeSpecWithTemplate:
4055 case NestedNameSpecifier::TypeSpec:
4056 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4057 break;
4058
4059 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004060 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004061 return;
4062 }
4063
4064 if (II)
4065 Identifiers.push_back(II);
4066}
4067
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004068void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00004069 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00004070 // Don't consider hidden names for typo correction.
4071 if (Hiding)
4072 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004073
Douglas Gregor2d435302009-12-30 17:04:44 +00004074 // Only consider entities with identifiers for names, ignoring
4075 // special names (constructors, overloaded operators, selectors,
4076 // etc.).
4077 IdentifierInfo *Name = ND->getIdentifier();
4078 if (!Name)
4079 return;
4080
Richard Smithe156254d2013-08-20 20:35:18 +00004081 // Only consider visible declarations and declarations from modules with
4082 // names that exactly match.
Richard Smith041740f2018-01-06 00:09:23 +00004083 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
Richard Smithe156254d2013-08-20 20:35:18 +00004084 return;
4085
Douglas Gregor57756ea2010-10-14 22:11:03 +00004086 FoundName(Name->getName());
4087}
4088
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004089void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004090 // Compute the edit distance between the typo and the name of this
4091 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00004092 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004093}
4094
4095void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4096 // Compute the edit distance between the typo and this keyword,
4097 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00004098 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004099}
4100
4101void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4102 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00004103 // Use a simple length-based heuristic to determine the minimum possible
4104 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004105 StringRef TypoStr = Typo->getName();
4106 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4107 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00004108 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004109
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00004110 // Compute an upper bound on the allowable edit distance, so that the
4111 // edit-distance algorithm can short-circuit.
Fangrui Songaadc93c2018-09-09 17:20:03 +00004112 unsigned UpperBound = (TypoStr.size() + 2) / 3;
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004113 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Fangrui Songaadc93c2018-09-09 17:20:03 +00004114 if (ED > UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004116 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004117 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00004118 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004119 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004120}
4121
Kaelyn Takatad2287c32014-10-27 18:07:13 +00004122static const unsigned MaxTypoDistanceResultSets = 5;
4123
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004124void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004125 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004126 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004127
4128 // For very short typos, ignore potential corrections that have a different
4129 // base identifier from the typo or which have a normalized edit distance
4130 // longer than the typo itself.
4131 if (TypoStr.size() < 3 &&
4132 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4133 return;
4134
4135 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004136 if (Correction.isResolved()) {
4137 checkCorrectionVisibility(SemaRef, Correction);
4138 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4139 return;
4140 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004141
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004142 TypoResultList &CList =
4143 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00004144
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004145 if (!CList.empty() && !CList.back().isResolved())
4146 CList.pop_back();
4147 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4148 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
4149 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
4150 RI != RIEnd; ++RI) {
4151 // If the Correction refers to a decl already in the result list,
4152 // replace the existing result if the string representation of Correction
4153 // comes before the current result alphabetically, then stop as there is
4154 // nothing more to be done to add Correction to the candidate set.
4155 if (RI->getCorrectionDecl() == NewND) {
4156 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
4157 *RI = Correction;
4158 return;
4159 }
4160 }
4161 }
4162 if (CList.empty() || Correction.isResolved())
4163 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004164
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004165 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004166 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4167}
4168
4169void TypoCorrectionConsumer::addNamespaces(
4170 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4171 SearchNamespaces = true;
4172
4173 for (auto KNPair : KnownNamespaces)
4174 Namespaces.addNameSpecifier(KNPair.first);
4175
4176 bool SSIsTemplate = false;
4177 if (NestedNameSpecifier *NNS =
4178 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4179 if (const Type *T = NNS->getAsType())
4180 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4181 }
Richard Smith2a40fb72015-11-18 01:19:02 +00004182 // Do not transform this into an iterator-based loop. The loop body can
4183 // trigger the creation of further types (through lazy deserialization) and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00004184 // invalid iterators into this list.
Richard Smith2a40fb72015-11-18 01:19:02 +00004185 auto &Types = SemaRef.getASTContext().getTypes();
4186 for (unsigned I = 0; I != Types.size(); ++I) {
4187 const auto *TI = Types[I];
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004188 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4189 CD = CD->getCanonicalDecl();
4190 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4191 !CD->isUnion() && CD->getIdentifier() &&
4192 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4193 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4194 Namespaces.addNameSpecifier(CD);
4195 }
4196 }
4197}
4198
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004199const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4200 if (++CurrentTCIndex < ValidatedCorrections.size())
4201 return ValidatedCorrections[CurrentTCIndex];
4202
4203 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004204 while (!CorrectionResults.empty()) {
4205 auto DI = CorrectionResults.begin();
4206 if (DI->second.empty()) {
4207 CorrectionResults.erase(DI);
4208 continue;
4209 }
4210
4211 auto RI = DI->second.begin();
4212 if (RI->second.empty()) {
4213 DI->second.erase(RI);
4214 performQualifiedLookups();
4215 continue;
4216 }
4217
4218 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004219 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004220 ValidatedCorrections.push_back(TC);
4221 return ValidatedCorrections[CurrentTCIndex];
4222 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004223 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004224 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004225}
4226
4227bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4228 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4229 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004230 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004231retry_lookup:
4232 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4233 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004234 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004235 Name == Typo && !Candidate.WillReplaceSpecifier());
4236 switch (Result.getResultKind()) {
4237 case LookupResult::NotFound:
4238 case LookupResult::NotFoundInCurrentInstantiation:
4239 case LookupResult::FoundUnresolvedValue:
4240 if (TempSS) {
4241 // Immediately retry the lookup without the given CXXScopeSpec
4242 TempSS = nullptr;
4243 Candidate.WillReplaceSpecifier(true);
4244 goto retry_lookup;
4245 }
4246 if (TempMemberContext) {
4247 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004248 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004249 TempMemberContext = nullptr;
4250 goto retry_lookup;
4251 }
4252 if (SearchNamespaces)
4253 QualifiedResults.push_back(Candidate);
4254 break;
4255
4256 case LookupResult::Ambiguous:
4257 // We don't deal with ambiguities.
4258 break;
4259
4260 case LookupResult::Found:
4261 case LookupResult::FoundOverloaded:
4262 // Store all of the Decls for overloaded symbols
4263 for (auto *TRD : Result)
4264 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004265 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004266 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004267 if (SearchNamespaces)
4268 QualifiedResults.push_back(Candidate);
4269 break;
4270 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00004271 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004272 return true;
4273 }
4274 return false;
4275}
4276
4277void TypoCorrectionConsumer::performQualifiedLookups() {
4278 unsigned TypoLen = Typo->getName().size();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00004279 for (const TypoCorrection &QR : QualifiedResults) {
4280 for (const auto &NSI : Namespaces) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004281 DeclContext *Ctx = NSI.DeclCtx;
4282 const Type *NSType = NSI.NameSpecifier->getAsType();
4283
4284 // If the current NestedNameSpecifier refers to a class and the
4285 // current correction candidate is the name of that class, then skip
4286 // it as it is unlikely a qualified version of the class' constructor
4287 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00004288 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4289 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004290 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4291 continue;
4292 }
4293
4294 TypoCorrection TC(QR);
4295 TC.ClearCorrectionDecls();
4296 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4297 TC.setQualifierDistance(NSI.EditDistance);
4298 TC.setCallbackDistance(0); // Reset the callback distance
4299
4300 // If the current correction candidate and namespace combination are
4301 // too far away from the original typo based on the normalized edit
4302 // distance, then skip performing a qualified name lookup.
4303 unsigned TmpED = TC.getEditDistance(true);
4304 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4305 TypoLen / TmpED < 3)
4306 continue;
4307
4308 Result.clear();
4309 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4310 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4311 continue;
4312
4313 // Any corrections added below will be validated in subsequent
4314 // iterations of the main while() loop over the Consumer's contents.
4315 switch (Result.getResultKind()) {
4316 case LookupResult::Found:
4317 case LookupResult::FoundOverloaded: {
4318 if (SS && SS->isValid()) {
4319 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4320 std::string OldQualified;
4321 llvm::raw_string_ostream OldOStream(OldQualified);
4322 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4323 OldOStream << Typo->getName();
4324 // If correction candidate would be an identical written qualified
Raphael Isemannb23ccec2018-12-10 12:37:46 +00004325 // identifier, then the existing CXXScopeSpec probably included a
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004326 // typedef that didn't get accounted for properly.
4327 if (OldOStream.str() == NewQualified)
4328 break;
4329 }
4330 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4331 TRD != TRDEnd; ++TRD) {
4332 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4333 NSType ? NSType->getAsCXXRecordDecl()
4334 : nullptr,
4335 TRD.getPair()) == Sema::AR_accessible)
4336 TC.addCorrectionDecl(*TRD);
4337 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004338 if (TC.isResolved()) {
4339 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004340 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004341 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004342 break;
4343 }
4344 case LookupResult::NotFound:
4345 case LookupResult::NotFoundInCurrentInstantiation:
4346 case LookupResult::Ambiguous:
4347 case LookupResult::FoundUnresolvedValue:
4348 break;
4349 }
4350 }
4351 }
4352 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004353}
4354
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004355TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4356 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004357 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004358 if (NestedNameSpecifier *NNS =
4359 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4360 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4361 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4362
4363 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4364 }
4365 // Build the list of identifiers that would be used for an absolute
4366 // (from the global context) NestedNameSpecifier referring to the current
4367 // context.
David Majnemerf7e36092016-06-23 00:15:04 +00004368 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4369 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004370 CurContextIdentifiers.push_back(ND->getIdentifier());
4371 }
4372
4373 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004374 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4375 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4376 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004377}
4378
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004379auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4380 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004381 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004382 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004383 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004384 DC = DC->getLookupParent()) {
4385 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4386 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4387 !(ND && ND->isAnonymousNamespace()))
4388 Chain.push_back(DC->getPrimaryContext());
4389 }
4390 return Chain;
4391}
4392
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004393unsigned
4394TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4395 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004396 unsigned NumSpecifiers = 0;
David Majnemerf7e36092016-06-23 00:15:04 +00004397 for (DeclContext *C : llvm::reverse(DeclChain)) {
4398 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004399 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4400 ++NumSpecifiers;
David Majnemerf7e36092016-06-23 00:15:04 +00004401 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004402 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4403 RD->getTypeForDecl());
4404 ++NumSpecifiers;
4405 }
4406 }
4407 return NumSpecifiers;
4408}
4409
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004410void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4411 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004412 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004413 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004414 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004415 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4416
4417 // Eliminate common elements from the two DeclContext chains.
David Majnemerf7e36092016-06-23 00:15:04 +00004418 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4419 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4420 break;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004421 NamespaceDeclChain.pop_back();
4422 }
4423
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004424 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004425 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004426
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004427 // Add an explicit leading '::' specifier if needed.
4428 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004429 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004430 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004431 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004432 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004433 } else if (NamedDecl *ND =
4434 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004435 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004436 bool SameNameSpecifier = false;
4437 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004438 CurNameSpecifierIdentifiers.end(),
4439 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004440 std::string NewNameSpecifier;
4441 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4442 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4443 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4444 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4445 SpecifierOStream.flush();
4446 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004447 }
Fangrui Song75e74e02019-03-31 08:48:19 +00004448 if (SameNameSpecifier || llvm::find(CurContextIdentifiers, Name) !=
4449 CurContextIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004450 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4451 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4452 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004453 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004454 }
4455 }
4456
4457 // If the built NestedNameSpecifier would be replacing an existing
4458 // NestedNameSpecifier, use the number of component identifiers that
4459 // would need to be changed as the edit distance instead of the number
4460 // of components in the built NestedNameSpecifier.
4461 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4462 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4463 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4464 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004465 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4466 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004467 }
4468
Hans Wennborg66010132014-06-11 21:24:13 +00004469 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4470 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004471}
4472
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004473/// Perform name lookup for a possible result for typo correction.
Douglas Gregord507d772010-10-20 03:06:34 +00004474static void LookupPotentialTypoResult(Sema &SemaRef,
4475 LookupResult &Res,
4476 IdentifierInfo *Name,
4477 Scope *S, CXXScopeSpec *SS,
4478 DeclContext *MemberContext,
4479 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004480 bool isObjCIvarLookup,
4481 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004482 Res.suppressDiagnostics();
4483 Res.clear();
4484 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004485 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004486 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004487 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004488 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004489 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4490 Res.addDecl(Ivar);
4491 Res.resolveKind();
4492 return;
4493 }
4494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004495
Manman Ren5b786402016-01-28 18:49:28 +00004496 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4497 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregord507d772010-10-20 03:06:34 +00004498 Res.addDecl(Prop);
4499 Res.resolveKind();
4500 return;
4501 }
4502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregord507d772010-10-20 03:06:34 +00004504 SemaRef.LookupQualifiedName(Res, MemberContext);
4505 return;
4506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507
4508 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004509 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
Douglas Gregord507d772010-10-20 03:06:34 +00004511 // Fake ivar lookup; this should really be part of
4512 // LookupParsedName.
4513 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4514 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004516 (Res.isSingleResult() &&
4517 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004519 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4520 Res.addDecl(IV);
4521 Res.resolveKind();
4522 }
4523 }
4524 }
4525}
4526
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004527/// Add keywords to the consumer as possible typo corrections.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004528static void AddKeywordsToConsumer(Sema &SemaRef,
4529 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004530 Scope *S, CorrectionCandidateCallback &CCC,
4531 bool AfterNestedNameSpecifier) {
4532 if (AfterNestedNameSpecifier) {
4533 // For 'X::', we know exactly which keywords can appear next.
4534 Consumer.addKeywordResult("template");
4535 if (CCC.WantExpressionKeywords)
4536 Consumer.addKeywordResult("operator");
4537 return;
4538 }
4539
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004540 if (CCC.WantObjCSuper)
4541 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004542
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004543 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004544 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004545 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004546 "char", "const", "double", "enum", "float", "int", "long", "short",
Fangrui Song6907ce22018-07-30 19:24:48 +00004547 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004548 "_Complex", "_Imaginary",
4549 // storage-specifiers as well
4550 "extern", "inline", "static", "typedef"
4551 };
4552
Craig Toppere5ce8312013-07-15 03:38:40 +00004553 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004554 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4555 Consumer.addKeywordResult(CTypeSpecs[I]);
4556
David Blaikiebbafb8a2012-03-11 07:00:24 +00004557 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004558 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004559 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004560 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004561 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004562 Consumer.addKeywordResult("_Bool");
Fangrui Song6907ce22018-07-30 19:24:48 +00004563
David Blaikiebbafb8a2012-03-11 07:00:24 +00004564 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004565 Consumer.addKeywordResult("class");
4566 Consumer.addKeywordResult("typename");
4567 Consumer.addKeywordResult("wchar_t");
4568
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004569 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004570 Consumer.addKeywordResult("char16_t");
4571 Consumer.addKeywordResult("char32_t");
4572 Consumer.addKeywordResult("constexpr");
4573 Consumer.addKeywordResult("decltype");
4574 Consumer.addKeywordResult("thread_local");
4575 }
4576 }
4577
Richard Smith7b301e22018-05-24 21:51:52 +00004578 if (SemaRef.getLangOpts().GNUKeywords)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004579 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004580 } else if (CCC.WantFunctionLikeCasts) {
4581 static const char *const CastableTypeSpecs[] = {
4582 "char", "double", "float", "int", "long", "short",
4583 "signed", "unsigned", "void"
4584 };
4585 for (auto *kw : CastableTypeSpecs)
4586 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004587 }
4588
David Blaikiebbafb8a2012-03-11 07:00:24 +00004589 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004590 Consumer.addKeywordResult("const_cast");
4591 Consumer.addKeywordResult("dynamic_cast");
4592 Consumer.addKeywordResult("reinterpret_cast");
4593 Consumer.addKeywordResult("static_cast");
4594 }
4595
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004596 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004597 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004598 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004599 Consumer.addKeywordResult("false");
4600 Consumer.addKeywordResult("true");
4601 }
4602
David Blaikiebbafb8a2012-03-11 07:00:24 +00004603 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004604 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004605 "delete", "new", "operator", "throw", "typeid"
4606 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004607 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004608 for (unsigned I = 0; I != NumCXXExprs; ++I)
4609 Consumer.addKeywordResult(CXXExprs[I]);
4610
4611 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4612 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4613 Consumer.addKeywordResult("this");
4614
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004615 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004616 Consumer.addKeywordResult("alignof");
4617 Consumer.addKeywordResult("nullptr");
4618 }
4619 }
Jordan Rose58d54722012-06-30 21:33:57 +00004620
4621 if (SemaRef.getLangOpts().C11) {
4622 // FIXME: We should not suggest _Alignof if the alignof macro
4623 // is present.
4624 Consumer.addKeywordResult("_Alignof");
4625 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004626 }
4627
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004628 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004629 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4630 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004631 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004632 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004633 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004634 for (unsigned I = 0; I != NumCStmts; ++I)
4635 Consumer.addKeywordResult(CStmts[I]);
4636
David Blaikiebbafb8a2012-03-11 07:00:24 +00004637 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004638 Consumer.addKeywordResult("catch");
4639 Consumer.addKeywordResult("try");
4640 }
4641
4642 if (S && S->getBreakParent())
4643 Consumer.addKeywordResult("break");
4644
4645 if (S && S->getContinueParent())
4646 Consumer.addKeywordResult("continue");
4647
Reid Kleckner87a31802018-03-12 21:43:02 +00004648 if (SemaRef.getCurFunction() &&
4649 !SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004650 Consumer.addKeywordResult("case");
4651 Consumer.addKeywordResult("default");
4652 }
4653 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004654 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004655 Consumer.addKeywordResult("namespace");
4656 Consumer.addKeywordResult("template");
4657 }
4658
4659 if (S && S->isClassScope()) {
4660 Consumer.addKeywordResult("explicit");
4661 Consumer.addKeywordResult("friend");
4662 Consumer.addKeywordResult("mutable");
4663 Consumer.addKeywordResult("private");
4664 Consumer.addKeywordResult("protected");
4665 Consumer.addKeywordResult("public");
4666 Consumer.addKeywordResult("virtual");
4667 }
4668 }
4669
David Blaikiebbafb8a2012-03-11 07:00:24 +00004670 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004671 Consumer.addKeywordResult("using");
4672
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004673 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004674 Consumer.addKeywordResult("static_assert");
4675 }
4676 }
4677}
4678
Kaelyn Takata6c759512014-10-27 18:07:37 +00004679std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4680 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
Bruno Ricci70ad3962019-03-25 17:08:51 +00004681 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004682 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004683 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004684
4685 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4686 DisableTypoCorrection)
4687 return nullptr;
4688
4689 // In Microsoft mode, don't perform typo correction in a template member
4690 // function dependent context because it interferes with the "lookup into
4691 // dependent bases of class templates" feature.
4692 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4693 isa<CXXMethodDecl>(CurContext))
4694 return nullptr;
4695
4696 // We only attempt to correct typos for identifiers.
4697 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4698 if (!Typo)
4699 return nullptr;
4700
4701 // If the scope specifier itself was invalid, don't try to correct
4702 // typos.
4703 if (SS && SS->isInvalid())
4704 return nullptr;
4705
Richard Smith696e3122017-02-23 01:43:54 +00004706 // Never try to correct typos during any kind of code synthesis.
4707 if (!CodeSynthesisContexts.empty())
Kaelyn Takata6c759512014-10-27 18:07:37 +00004708 return nullptr;
4709
4710 // Don't try to correct 'super'.
4711 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4712 return nullptr;
4713
4714 // Abort if typo correction already failed for this specific typo.
4715 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4716 if (locs != TypoCorrectionFailures.end() &&
4717 locs->second.count(TypoName.getLoc()))
4718 return nullptr;
4719
4720 // Don't try to correct the identifier "vector" when in AltiVec mode.
4721 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4722 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004723 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004724 return nullptr;
4725
Nick Lewycky24653262014-12-16 21:39:02 +00004726 // Provide a stop gap for files that are just seriously broken. Trying
4727 // to correct all typos can turn into a HUGE performance penalty, causing
4728 // some files to take minutes to get rejected by the parser.
4729 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4730 if (Limit && TyposCorrected >= Limit)
4731 return nullptr;
4732 ++TyposCorrected;
4733
Kaelyn Takata6c759512014-10-27 18:07:37 +00004734 // If we're handling a missing symbol error, using modules, and the
4735 // special search all modules option is used, look for a missing import.
4736 if (ErrorRecovery && getLangOpts().Modules &&
4737 getLangOpts().ModulesSearchAll) {
4738 // The following has the side effect of loading the missing module.
4739 getModuleLoader().lookupMissingImports(Typo->getName(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004740 TypoName.getBeginLoc());
Kaelyn Takata6c759512014-10-27 18:07:37 +00004741 }
4742
Bruno Ricci70ad3962019-03-25 17:08:51 +00004743 // Extend the lifetime of the callback. We delayed this until here
4744 // to avoid allocations in the hot path (which is where no typo correction
4745 // occurs). Note that CorrectionCandidateCallback is polymorphic and
4746 // initially stack-allocated.
4747 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004748 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
Bruno Ricci70ad3962019-03-25 17:08:51 +00004749 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004750 EnteringContext);
4751
Kaelyn Takata6c759512014-10-27 18:07:37 +00004752 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004753 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004754 DeclContext *QualifiedDC = MemberContext;
4755 if (MemberContext) {
4756 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4757
4758 // Look in qualified interfaces.
4759 if (OPT) {
4760 for (auto *I : OPT->quals())
4761 LookupVisibleDecls(I, LookupKind, *Consumer);
4762 }
4763 } else if (SS && SS->isSet()) {
4764 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4765 if (!QualifiedDC)
4766 return nullptr;
4767
Kaelyn Takata6c759512014-10-27 18:07:37 +00004768 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4769 } else {
4770 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004771 }
4772
4773 // Determine whether we are going to search in the various namespaces for
4774 // corrections.
4775 bool SearchNamespaces
4776 = getLangOpts().CPlusPlus &&
4777 (IsUnqualifiedLookup || (SS && SS->isSet()));
4778
4779 if (IsUnqualifiedLookup || SearchNamespaces) {
4780 // For unqualified lookup, look through all of the names that we have
4781 // seen in this translation unit.
4782 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4783 for (const auto &I : Context.Idents)
4784 Consumer->FoundName(I.getKey());
4785
4786 // Walk through identifiers in external identifier sources.
4787 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4788 if (IdentifierInfoLookup *External
4789 = Context.Idents.getExternalIdentifierLookup()) {
4790 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4791 do {
4792 StringRef Name = Iter->Next();
4793 if (Name.empty())
4794 break;
4795
4796 Consumer->FoundName(Name);
4797 } while (true);
4798 }
4799 }
4800
Bruno Ricci70ad3962019-03-25 17:08:51 +00004801 AddKeywordsToConsumer(*this, *Consumer, S,
4802 *Consumer->getCorrectionValidator(),
4803 SS && SS->isNotEmpty());
Kaelyn Takata6c759512014-10-27 18:07:37 +00004804
4805 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4806 // to search those namespaces.
4807 if (SearchNamespaces) {
4808 // Load any externally-known namespaces.
4809 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4810 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4811 LoadedExternalKnownNamespaces = true;
4812 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4813 for (auto *N : ExternalKnownNamespaces)
4814 KnownNamespaces[N] = true;
4815 }
4816
4817 Consumer->addNamespaces(KnownNamespaces);
4818 }
4819
4820 return Consumer;
4821}
4822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004823/// Try to "correct" a typo in the source code by finding
Douglas Gregor2d435302009-12-30 17:04:44 +00004824/// visible declarations whose names are similar to the name that was
4825/// present in the source code.
4826///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004827/// \param TypoName the \c DeclarationNameInfo structure that contains
4828/// the name that was present in the source code along with its location.
4829///
4830/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004831///
4832/// \param S the scope in which name lookup occurs.
4833///
4834/// \param SS the nested-name-specifier that precedes the name we're
4835/// looking for, if present.
4836///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004837/// \param CCC A CorrectionCandidateCallback object that provides further
4838/// validation of typo correction candidates. It also provides flags for
4839/// determining the set of keywords permitted.
4840///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004841/// \param MemberContext if non-NULL, the context in which to look for
4842/// a member access expression.
4843///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004845/// the nested-name-specifier SS.
4846///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004847/// \param OPT when non-NULL, the search for visible declarations will
4848/// also walk the protocols in the qualified interfaces of \p OPT.
4849///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004850/// \returns a \c TypoCorrection containing the corrected name if the typo
4851/// along with information such as the \c NamedDecl where the corrected name
4852/// was declared, and any additional \c NestedNameSpecifier needed to access
4853/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4854TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4855 Sema::LookupNameKind LookupKind,
4856 Scope *S, CXXScopeSpec *SS,
Bruno Ricci70ad3962019-03-25 17:08:51 +00004857 CorrectionCandidateCallback &CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004858 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004859 DeclContext *MemberContext,
4860 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004861 const ObjCObjectPointerType *OPT,
4862 bool RecordFailure) {
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004863 // Always let the ExternalSource have the first chance at correction, even
4864 // if we would otherwise have given up.
4865 if (ExternalSource) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00004866 if (TypoCorrection Correction =
4867 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
4868 MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004869 return Correction;
4870 }
4871
Kaelyn Takata6c759512014-10-27 18:07:37 +00004872 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4873 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4874 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4875 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Bruno Ricci70ad3962019-03-25 17:08:51 +00004876 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004877
Kaelyn Takata6c759512014-10-27 18:07:37 +00004878 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Bruno Ricci70ad3962019-03-25 17:08:51 +00004879 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
4880 MemberContext, EnteringContext,
4881 OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004882
Kaelyn Takata6c759512014-10-27 18:07:37 +00004883 if (!Consumer)
4884 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004886 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004887 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004888 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004889
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004890 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4891 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004892 unsigned ED = Consumer->getBestEditDistance(true);
4893 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004894 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004895 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004896
Kaelyn Takata6c759512014-10-27 18:07:37 +00004897 TypoCorrection BestTC = Consumer->getNextCorrection();
4898 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004899 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004900 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004901
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004902 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004903
Kaelyn Takata6c759512014-10-27 18:07:37 +00004904 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004905 // If this was an unqualified lookup and we believe the callback
4906 // object wouldn't have filtered out possible corrections, note
4907 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004908 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004909 }
4910
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004911 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004912 if (!SecondBestTC ||
4913 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4914 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004916 // Don't correct to a keyword that's the same as the typo; the keyword
4917 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004918 if (ED == 0 && Result.isKeyword())
4919 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004920
David Blaikie04ea41c2012-10-12 20:00:44 +00004921 TypoCorrection TC = Result;
4922 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004923 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004924 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004925 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004926 // Prefer 'super' when we're completing in a message-receiver
4927 // context.
4928
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004929 if (BestTC.getCorrection().getAsString() != "super") {
4930 if (SecondBestTC.getCorrection().getAsString() == "super")
4931 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004932 else if ((*Consumer)["super"].front().isKeyword())
4933 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004934 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004935 // Don't correct to a keyword that's the same as the typo; the keyword
4936 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004937 if (BestTC.getEditDistance() == 0 ||
4938 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004939 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004941 BestTC.setCorrectionRange(SS, TypoName);
4942 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004945 // Record the failure's location if needed and return an empty correction. If
4946 // this was an unqualified lookup and we believe the callback object did not
4947 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004948 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004949}
4950
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004951/// Try to "correct" a typo in the source code by finding
Kaelyn Takata6c759512014-10-27 18:07:37 +00004952/// visible declarations whose names are similar to the name that was
4953/// present in the source code.
4954///
4955/// \param TypoName the \c DeclarationNameInfo structure that contains
4956/// the name that was present in the source code along with its location.
4957///
4958/// \param LookupKind the name-lookup criteria used to search for the name.
4959///
4960/// \param S the scope in which name lookup occurs.
4961///
4962/// \param SS the nested-name-specifier that precedes the name we're
4963/// looking for, if present.
4964///
4965/// \param CCC A CorrectionCandidateCallback object that provides further
4966/// validation of typo correction candidates. It also provides flags for
4967/// determining the set of keywords permitted.
4968///
4969/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4970/// diagnostics when the actual typo correction is attempted.
4971///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004972/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4973/// Expr from a typo correction candidate.
4974///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004975/// \param MemberContext if non-NULL, the context in which to look for
4976/// a member access expression.
4977///
4978/// \param EnteringContext whether we're entering the context described by
4979/// the nested-name-specifier SS.
4980///
4981/// \param OPT when non-NULL, the search for visible declarations will
4982/// also walk the protocols in the qualified interfaces of \p OPT.
4983///
4984/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4985/// Expr representing the result of performing typo correction, or nullptr if
4986/// typo correction is not possible. If nullptr is returned, no diagnostics will
4987/// be emitted and it is the responsibility of the caller to emit any that are
4988/// needed.
4989TypoExpr *Sema::CorrectTypoDelayed(
4990 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
Bruno Ricci70ad3962019-03-25 17:08:51 +00004991 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004992 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004993 DeclContext *MemberContext, bool EnteringContext,
4994 const ObjCObjectPointerType *OPT) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00004995 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
4996 MemberContext, EnteringContext,
4997 OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004998
Benjamin Kramerb8727332016-05-19 10:46:10 +00004999 // Give the external sema source a chance to correct the typo.
5000 TypoCorrection ExternalTypo;
5001 if (ExternalSource && Consumer) {
5002 ExternalTypo = ExternalSource->CorrectTypo(
Benjamin Kramer97d7a662016-05-19 21:53:33 +00005003 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5004 MemberContext, EnteringContext, OPT);
Benjamin Kramerb8727332016-05-19 10:46:10 +00005005 if (ExternalTypo)
5006 Consumer->addCorrection(ExternalTypo);
5007 }
5008
Kaelyn Takata6c759512014-10-27 18:07:37 +00005009 if (!Consumer || Consumer->empty())
5010 return nullptr;
5011
5012 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5013 // is not more that about a third of the length of the typo's identifier.
5014 unsigned ED = Consumer->getBestEditDistance(true);
5015 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Benjamin Kramerb8727332016-05-19 10:46:10 +00005016 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
Kaelyn Takata6c759512014-10-27 18:07:37 +00005017 return nullptr;
5018
5019 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00005020 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00005021}
5022
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00005023void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5024 if (!CDecl) return;
5025
5026 if (isKeyword())
5027 CorrectionDecls.clear();
5028
Richard Smithde6d6c42015-12-29 19:43:10 +00005029 CorrectionDecls.push_back(CDecl);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00005030
5031 if (!CorrectionName)
5032 CorrectionName = CDecl->getDeclName();
5033}
5034
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005035std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5036 if (CorrectionNameSpec) {
5037 std::string tmpBuffer;
5038 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5039 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00005040 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00005041 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005042 }
5043
5044 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00005045}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00005046
Nico Weberb58e51c2014-11-19 05:21:39 +00005047bool CorrectionCandidateCallback::ValidateCandidate(
5048 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00005049 if (!candidate.isResolved())
5050 return true;
5051
5052 if (candidate.isKeyword())
5053 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5054 WantRemainingKeywords || WantObjCSuper;
5055
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00005056 bool HasNonType = false;
5057 bool HasStaticMethod = false;
5058 bool HasNonStaticMethod = false;
5059 for (Decl *D : candidate) {
5060 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5061 D = FTD->getTemplatedDecl();
5062 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5063 if (Method->isStatic())
5064 HasStaticMethod = true;
5065 else
5066 HasNonStaticMethod = true;
5067 }
5068 if (!isa<TypeDecl>(D))
5069 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00005070 }
5071
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00005072 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5073 !candidate.getCorrectionSpecifier())
5074 return false;
5075
5076 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00005077}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005078
5079FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005080 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005081 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005082 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005083 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00005084 WantTypeSpecifiers = false;
Richard Smith2194fb62019-05-09 00:57:24 +00005085 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5086 !HasExplicitTemplateArgs && NumArgs == 1;
5087 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005088 WantRemainingKeywords = false;
5089}
5090
5091bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5092 if (!candidate.getCorrectionDecl())
5093 return candidate.isKeyword();
5094
Aaron Ballman1e606f42014-07-15 22:03:49 +00005095 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005096 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00005097 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005098 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5099 FD = FTD->getTemplatedDecl();
5100 if (!HasExplicitTemplateArgs && !FD) {
5101 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5102 // If the Decl is neither a function nor a template function,
5103 // determine if it is a pointer or reference to a function. If so,
5104 // check against the number of arguments expected for the pointee.
5105 QualType ValType = cast<ValueDecl>(ND)->getType();
Erik Pilkington1c5ae9b2018-07-10 02:15:07 +00005106 if (ValType.isNull())
5107 continue;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005108 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5109 ValType = ValType->getPointeeType();
5110 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00005111 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005112 return true;
5113 }
5114 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005115
Richard Smith2194fb62019-05-09 00:57:24 +00005116 // A typo for a function-style cast can look like a function call in C++.
5117 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5118 : isa<TypeDecl>(ND)) &&
5119 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5120 // Only a class or class template can take two or more arguments.
5121 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5122
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005123 // Skip the current candidate if it is not a FunctionDecl or does not accept
5124 // the current number of arguments.
5125 if (!FD || !(FD->getNumParams() >= NumArgs &&
5126 FD->getMinRequiredArguments() <= NumArgs))
5127 continue;
5128
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005129 // If the current candidate is a non-static C++ method, skip the candidate
5130 // unless the method being corrected--or the current DeclContext, if the
5131 // function being corrected is not a method--is a method in the same class
5132 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005133 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005134 if (MemberFn || !MD->isStatic()) {
5135 CXXMethodDecl *CurMD =
5136 MemberFn
5137 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5138 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005139 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00005140 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005141 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5142 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5143 continue;
5144 }
5145 }
5146 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005147 }
5148 return false;
5149}
Richard Smithf9b15102013-08-17 00:46:16 +00005150
5151void Sema::diagnoseTypo(const TypoCorrection &Correction,
5152 const PartialDiagnostic &TypoDiag,
5153 bool ErrorRecovery) {
5154 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5155 ErrorRecovery);
5156}
5157
Richard Smithe156254d2013-08-20 20:35:18 +00005158/// Find which declaration we should import to provide the definition of
5159/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00005160static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5161 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005162 return VD->getDefinition();
Yaron Keren18c3d062016-07-13 19:04:51 +00005163 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5164 return FD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005165 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005166 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005167 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005168 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005169 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005170 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005171 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Saar Razd7aae332019-07-10 21:25:49 +00005172 if (NamedDecl *TTD = TD->getTemplatedDecl())
5173 return getDefinitionToImport(TTD);
Craig Topperc3ec1492014-05-26 06:22:03 +00005174 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00005175}
5176
Richard Smithf2b1eb92015-06-15 20:15:48 +00005177void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005178 MissingImportKind MIK, bool Recover) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005179 // Suggest importing a module providing the definition of this entity, if
5180 // possible.
5181 NamedDecl *Def = getDefinitionToImport(Decl);
5182 if (!Def)
5183 Def = Decl;
5184
Richard Smithc4577662018-09-12 02:13:47 +00005185 Module *Owner = getOwningModule(Def);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005186 assert(Owner && "definition of hidden declaration is not in a module");
5187
Richard Smith35c1df52015-06-17 20:16:32 +00005188 llvm::SmallVector<Module*, 8> OwningModules;
5189 OwningModules.push_back(Owner);
Richard Smithc4577662018-09-12 02:13:47 +00005190 auto Merged = Context.getModulesWithMergedDefinition(Def);
Richard Smith35c1df52015-06-17 20:16:32 +00005191 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5192
Richard Smithe867e982019-04-18 00:56:58 +00005193 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
Richard Smith35c1df52015-06-17 20:16:32 +00005194 Recover);
5195}
5196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005197/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
Richard Smith4eb83932016-04-27 21:57:05 +00005198/// suggesting the addition of a #include of the specified file.
5199static std::string getIncludeStringForHeader(Preprocessor &PP,
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00005200 const FileEntry *E,
5201 llvm::StringRef IncludingFile) {
5202 bool IsSystem = false;
5203 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5204 E, IncludingFile, &IsSystem);
Richard Smith4eb83932016-04-27 21:57:05 +00005205 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5206}
5207
Richard Smith35c1df52015-06-17 20:16:32 +00005208void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5209 SourceLocation DeclLoc,
5210 ArrayRef<Module *> Modules,
5211 MissingImportKind MIK, bool Recover) {
5212 assert(!Modules.empty());
5213
Richard Smithe867e982019-04-18 00:56:58 +00005214 auto NotePrevious = [&] {
5215 unsigned DiagID;
5216 switch (MIK) {
5217 case MissingImportKind::Declaration:
5218 DiagID = diag::note_previous_declaration;
5219 break;
5220 case MissingImportKind::Definition:
5221 DiagID = diag::note_previous_definition;
5222 break;
5223 case MissingImportKind::DefaultArgument:
5224 DiagID = diag::note_default_argument_declared_here;
5225 break;
5226 case MissingImportKind::ExplicitSpecialization:
5227 DiagID = diag::note_explicit_specialization_declared_here;
5228 break;
5229 case MissingImportKind::PartialSpecialization:
5230 DiagID = diag::note_partial_specialization_declared_here;
5231 break;
5232 }
5233 Diag(DeclLoc, DiagID);
5234 };
5235
Richard Smith54f04402017-05-18 02:29:20 +00005236 // Weed out duplicates from module list.
5237 llvm::SmallVector<Module*, 8> UniqueModules;
5238 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
Richard Smithe867e982019-04-18 00:56:58 +00005239 for (auto *M : Modules) {
5240 if (M->Kind == Module::GlobalModuleFragment)
5241 continue;
Richard Smith54f04402017-05-18 02:29:20 +00005242 if (UniqueModuleSet.insert(M).second)
5243 UniqueModules.push_back(M);
Richard Smithe867e982019-04-18 00:56:58 +00005244 }
5245
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00005246 llvm::StringRef IncludingFile;
5247 if (const FileEntry *FE =
5248 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5249 IncludingFile = FE->tryGetRealPathName();
5250
Richard Smithe867e982019-04-18 00:56:58 +00005251 if (UniqueModules.empty()) {
5252 // All candidates were global module fragments. Try to suggest a #include.
5253 const FileEntry *E =
5254 PP.getModuleHeaderToIncludeForDiagnostics(UseLoc, Modules[0], DeclLoc);
5255 // FIXME: Find a smart place to suggest inserting a #include, and add
5256 // a FixItHint there.
5257 Diag(UseLoc, diag::err_module_unimported_use_global_module_fragment)
5258 << (int)MIK << Decl << !!E
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00005259 << (E ? getIncludeStringForHeader(PP, E, IncludingFile) : "");
Richard Smithe867e982019-04-18 00:56:58 +00005260 // Produce a "previous" note if it will point to a header rather than some
5261 // random global module fragment.
5262 // FIXME: Suppress the note backtrace even under
5263 // -fdiagnostics-show-note-include-stack.
5264 if (E)
5265 NotePrevious();
5266 if (Recover)
5267 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5268 return;
5269 }
5270
Richard Smith54f04402017-05-18 02:29:20 +00005271 Modules = UniqueModules;
5272
Richard Smith35c1df52015-06-17 20:16:32 +00005273 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005274 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00005275 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00005276 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005277 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00005278 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005279 ModuleList += "[...]";
5280 break;
5281 }
5282 ModuleList += M->getFullModuleName();
5283 }
5284
Richard Smith35c1df52015-06-17 20:16:32 +00005285 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5286 << (int)MIK << Decl << ModuleList;
Richard Smithcbf7d8a2017-05-19 23:49:00 +00005287 } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics(
5288 UseLoc, Modules[0], DeclLoc)) {
Richard Smith4eb83932016-04-27 21:57:05 +00005289 // The right way to make the declaration visible is to include a header;
5290 // suggest doing so.
5291 //
5292 // FIXME: Find a smart place to suggest inserting a #include, and add
5293 // a FixItHint there.
5294 Diag(UseLoc, diag::err_module_unimported_use_header)
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00005295 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5296 << getIncludeStringForHeader(PP, E, IncludingFile);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005297 } else {
Richard Smithacef17a2016-05-05 02:14:06 +00005298 // FIXME: Add a FixItHint that imports the corresponding module.
Richard Smith35c1df52015-06-17 20:16:32 +00005299 Diag(UseLoc, diag::err_module_unimported_use)
5300 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00005301 }
Richard Smith35c1df52015-06-17 20:16:32 +00005302
Richard Smithe867e982019-04-18 00:56:58 +00005303 NotePrevious();
Richard Smithf2b1eb92015-06-15 20:15:48 +00005304
5305 // Try to recover by implicitly importing this module.
5306 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00005307 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005308}
5309
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005310/// Diagnose a successfully-corrected typo. Separated from the correction
Richard Smithf9b15102013-08-17 00:46:16 +00005311/// itself to allow external validation of the result, etc.
5312///
5313/// \param Correction The result of performing typo correction.
5314/// \param TypoDiag The diagnostic to produce. This will have the corrected
5315/// string added to it (and usually also a fixit).
5316/// \param PrevNote A note to use when indicating the location of the entity to
5317/// which we are correcting. Will have the correction string added to it.
5318/// \param ErrorRecovery If \c true (the default), the caller is going to
5319/// recover from the typo as if the corrected string had been typed.
5320/// In this case, \c PDiag must be an error, and we will attach a fixit
5321/// to it.
5322void Sema::diagnoseTypo(const TypoCorrection &Correction,
5323 const PartialDiagnostic &TypoDiag,
5324 const PartialDiagnostic &PrevNote,
5325 bool ErrorRecovery) {
5326 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5327 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5328 FixItHint FixTypo = FixItHint::CreateReplacement(
5329 Correction.getCorrectionRange(), CorrectedStr);
5330
Richard Smithe156254d2013-08-20 20:35:18 +00005331 // Maybe we're just missing a module import.
5332 if (Correction.requiresImport()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00005333 NamedDecl *Decl = Correction.getFoundDecl();
Richard Smithe156254d2013-08-20 20:35:18 +00005334 assert(Decl && "import required but no declaration to import");
5335
Richard Smithf2b1eb92015-06-15 20:15:48 +00005336 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005337 MissingImportKind::Declaration, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00005338 return;
5339 }
5340
Richard Smithf9b15102013-08-17 00:46:16 +00005341 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5342 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5343
5344 NamedDecl *ChosenDecl =
Richard Smithde6d6c42015-12-29 19:43:10 +00005345 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00005346 if (PrevNote.getDiagID() && ChosenDecl)
5347 Diag(ChosenDecl->getLocation(), PrevNote)
5348 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
Benjamin Kramer7de99692016-11-16 18:15:26 +00005349
5350 // Add any extra diagnostics.
5351 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5352 Diag(Correction.getCorrectionRange().getBegin(), PD);
Richard Smithf9b15102013-08-17 00:46:16 +00005353}
Kaelyn Takata6c759512014-10-27 18:07:37 +00005354
Kaelyn Takata8363f042014-10-27 18:07:42 +00005355TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5356 TypoDiagnosticGenerator TDG,
5357 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00005358 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5359 auto TE = new (Context) TypoExpr(Context.DependentTy);
5360 auto &State = DelayedTypos[TE];
5361 State.Consumer = std::move(TCC);
5362 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00005363 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00005364 return TE;
5365}
5366
5367const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5368 auto Entry = DelayedTypos.find(TE);
5369 assert(Entry != DelayedTypos.end() &&
5370 "Failed to get the state for a TypoExpr!");
5371 return Entry->second;
5372}
5373
5374void Sema::clearDelayedTypo(TypoExpr *TE) {
5375 DelayedTypos.erase(TE);
5376}
Richard Smithba3a4f92016-01-12 21:59:26 +00005377
5378void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5379 DeclarationNameInfo Name(II, IILoc);
5380 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5381 R.suppressDiagnostics();
5382 R.setHideTags(false);
5383 LookupName(R, S);
5384 R.dump();
5385}