blob: 6a1aae62413472b79b41d05d43bba9e12295f7db [file] [log] [blame]
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
Douglas Gregor34074322009-01-14 22:20:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Hans Wennborgdcfba332015-10-06 23:40:43 +000014
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.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
50using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000051using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053namespace {
54 class UnqualUsingEntry {
55 const DeclContext *Nominated;
56 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 public:
59 UnqualUsingEntry(const DeclContext *Nominated,
60 const DeclContext *CommonAncestor)
61 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 const DeclContext *getCommonAncestor() const {
65 return CommonAncestor;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 const DeclContext *getNominatedNamespace() const {
69 return Nominated;
70 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 // Sort by the pointer value of the common ancestor.
73 struct Comparator {
74 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
75 return L.getCommonAncestor() < R.getCommonAncestor();
76 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
79 return E.getCommonAncestor() < DC;
80 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
83 return DC < E.getCommonAncestor();
84 }
85 };
86 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 /// A collection of using directives, as used by C++ unqualified
89 /// lookup.
90 class UnqualUsingDirectiveSet {
Richard Smithb920f852017-10-11 01:19:11 +000091 Sema &SemaRef;
92
Chris Lattner0e62c1c2011-07-23 10:55:15 +000093 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 ListTy list;
96 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 public:
Richard Smithb920f852017-10-11 01:19:11 +000099 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000100
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 // During unqualified name lookup, the names appear as if they
104 // were declared in the nearest enclosing namespace which contains
105 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000108
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000113 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000117 for (auto *I : S->using_directives())
Richard Smithb920f852017-10-11 01:19:11 +0000118 if (SemaRef.isVisible(I))
119 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000120 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000121 }
122 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000123
124 // Visits a context and collect all of its using directives
125 // recursively. Treats all using directives as if they were
126 // declared in the context.
127 //
128 // A given context is only every visited once, so it is important
129 // that contexts be visited from the inside out in order to get
130 // the effective DCs right.
131 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000132 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000133 return;
134
135 addUsingDirectives(DC, EffectiveDC);
136 }
137
138 // Visits a using directive and collects all of its using
139 // directives recursively. Treats all using directives as if they
140 // were declared in the effective DC.
141 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
142 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000143 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000144 return;
145
146 addUsingDirective(UD, EffectiveDC);
147 addUsingDirectives(NS, EffectiveDC);
148 }
149
150 // Adds all the using directives in a context (and those nominated
151 // by its using directives, transitively) as if they appeared in
152 // the given effective context.
153 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Nick Lewycky4b81fc872015-10-18 20:32:12 +0000154 SmallVector<DeclContext*, 4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000155 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000156 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000157 DeclContext *NS = UD->getNominatedNamespace();
Richard Smitha544c512017-10-30 22:38:20 +0000158 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000159 addUsingDirective(UD, EffectiveDC);
160 queue.push_back(NS);
161 }
162 }
163
164 if (queue.empty())
165 return;
166
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000167 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000168 }
169 }
170
171 // Add a using directive as if it had been declared in the given
172 // context. This helps implement C++ [namespace.udir]p3:
173 // The using-directive is transitive: if a scope contains a
174 // using-directive that nominates a second namespace that itself
175 // contains using-directives, the effect is as if the
176 // using-directives from the second namespace also appeared in
177 // the first.
178 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179 // Find the common ancestor between the effective context and
180 // the nominated namespace.
181 DeclContext *Common = UD->getNominatedNamespace();
182 while (!Common->Encloses(EffectiveDC))
183 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000184 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000185
John McCallf6c8a4e2009-11-10 07:01:13 +0000186 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187 }
188
Fangrui Song55fab262018-09-26 22:16:28 +0000189 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
John McCallf6c8a4e2009-11-10 07:01:13 +0000190
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000192
John McCallf6c8a4e2009-11-10 07:01:13 +0000193 const_iterator begin() const { return list.begin(); }
194 const_iterator end() const { return list.end(); }
195
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000196 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000197 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000198 return llvm::make_range(std::equal_range(begin(), end(),
199 DC->getPrimaryContext(),
200 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000201 }
202 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000203} // end anonymous namespace
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205// Retrieve the set of identifier namespaces that correspond to a
206// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000207static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
208 bool CPlusPlus,
209 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 unsigned IDNS = 0;
211 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000212 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000213 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000214 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000215 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000217 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000219 if (Redeclaration)
220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000221 }
Richard Smith541b38b2013-09-20 01:15:31 +0000222 if (Redeclaration)
223 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000224 break;
225
John McCallb9467b62010-04-24 01:30:58 +0000226 case Sema::LookupOperatorName:
227 // Operator lookup is its own crazy thing; it is not the same
228 // as (e.g.) looking up an operator name for redeclaration.
229 assert(!Redeclaration && "cannot do redeclaration operator lookup");
230 IDNS = Decl::IDNS_NonMemberOperator;
231 break;
232
Douglas Gregor889ceb72009-02-03 19:21:40 +0000233 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000234 if (CPlusPlus) {
235 IDNS = Decl::IDNS_Type;
236
237 // When looking for a redeclaration of a tag name, we add:
238 // 1) TagFriend to find undeclared friend decls
239 // 2) Namespace because they can't "overload" with tag decls.
240 // 3) Tag because it includes class templates, which can't
241 // "overload" with tag decls.
242 if (Redeclaration)
243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
244 } else {
245 IDNS = Decl::IDNS_Tag;
246 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000247 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000248
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000249 case Sema::LookupLabel:
250 IDNS = Decl::IDNS_Label;
251 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000252
Douglas Gregor889ceb72009-02-03 19:21:40 +0000253 case Sema::LookupMemberName:
254 IDNS = Decl::IDNS_Member;
255 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000256 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 break;
258
259 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000260 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
261 break;
262
Douglas Gregor889ceb72009-02-03 19:21:40 +0000263 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000264 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000265 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000266
John McCall84d87672009-12-10 09:41:52 +0000267 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000268 assert(Redeclaration && "should only be used for redecl lookup");
269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
270 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
271 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000272 break;
273
Douglas Gregor79947a22009-04-24 00:11:27 +0000274 case Sema::LookupObjCProtocolName:
275 IDNS = Decl::IDNS_ObjCProtocol;
276 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000278 case Sema::LookupOMPReductionName:
279 IDNS = Decl::IDNS_OMPReduction;
280 break;
281
Douglas Gregor39982192010-08-15 06:18:01 +0000282 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000284 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
285 | Decl::IDNS_Type;
286 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000287 }
288 return IDNS;
289}
290
John McCallea305ed2009-12-18 10:40:03 +0000291void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000292 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000293 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000294
Richard Smithbdd14642014-02-04 01:14:30 +0000295 // If we're looking for one of the allocation or deallocation
296 // operators, make sure that the implicitly-declared new and delete
297 // operators can be found.
298 switch (NameInfo.getName().getCXXOverloadedOperator()) {
299 case OO_New:
300 case OO_Delete:
301 case OO_Array_New:
302 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000303 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000304 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000305
Richard Smithbdd14642014-02-04 01:14:30 +0000306 default:
307 break;
308 }
Douglas Gregor15197662013-04-03 23:06:26 +0000309
Richard Smithbdd14642014-02-04 01:14:30 +0000310 // Compiler builtins are always visible, regardless of where they end
311 // up being declared.
312 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
313 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000314 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000315 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000316 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000317 }
John McCallea305ed2009-12-18 10:40:03 +0000318}
319
Alp Tokerc1086762013-12-07 13:51:35 +0000320bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000321 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000322 assert(ResultKind != NotFound || Decls.size() == 0);
323 assert(ResultKind != Found || Decls.size() == 1);
324 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
325 (Decls.size() == 1 &&
326 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
327 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
328 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000329 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
330 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000331 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
332 (Ambiguity == AmbiguousBaseSubobjectTypes ||
333 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000334 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000335}
John McCall19c1bfd2010-08-25 05:32:35 +0000336
John McCall9f3059a2009-10-09 21:13:30 +0000337// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000338void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000339 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000340}
341
Richard Smith3876cc82013-10-30 01:02:04 +0000342/// Get a representative context for a declaration such that two declarations
343/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000344static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000345 // For function-local declarations, use that function as the context. This
346 // doesn't account for scopes within the function; the caller must deal with
347 // those.
348 DeclContext *DC = D->getLexicalDeclContext();
349 if (DC->isFunctionOrMethod())
350 return DC;
351
352 // Otherwise, look at the semantic context of the declaration. The
353 // declaration must have been found there.
354 return D->getDeclContext()->getRedeclContext();
355}
356
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000357/// Determine whether \p D is a better lookup result than \p Existing,
Richard Smith826711d2015-07-29 23:38:25 +0000358/// given that they declare the same entity.
Richard Smithcd31b852015-08-22 21:37:34 +0000359static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
Richard Smith826711d2015-07-29 23:38:25 +0000360 NamedDecl *D, NamedDecl *Existing) {
361 // When looking up redeclarations of a using declaration, prefer a using
362 // shadow declaration over any other declaration of the same entity.
363 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
364 !isa<UsingShadowDecl>(Existing))
365 return true;
366
367 auto *DUnderlying = D->getUnderlyingDecl();
368 auto *EUnderlying = Existing->getUnderlyingDecl();
369
Richard Smith990668b2015-11-12 22:04:34 +0000370 // If they have different underlying declarations, prefer a typedef over the
371 // original type (this happens when two type declarations denote the same
372 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
373 // might carry additional semantic information, such as an alignment override.
374 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
375 // declaration over a typedef.
Richard Smith826711d2015-07-29 23:38:25 +0000376 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
377 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
Richard Smith990668b2015-11-12 22:04:34 +0000378 bool HaveTag = isa<TagDecl>(EUnderlying);
379 bool WantTag = Kind == Sema::LookupTagName;
380 return HaveTag != WantTag;
Richard Smith826711d2015-07-29 23:38:25 +0000381 }
382
Richard Smithcd31b852015-08-22 21:37:34 +0000383 // Pick the function with more default arguments.
384 // FIXME: In the presence of ambiguous default arguments, we should keep both,
385 // so we can diagnose the ambiguity if the default argument is needed.
386 // See C++ [over.match.best]p3.
387 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
388 auto *EFD = cast<FunctionDecl>(EUnderlying);
389 unsigned DMin = DFD->getMinRequiredArguments();
390 unsigned EMin = EFD->getMinRequiredArguments();
391 // If D has more default arguments, it is preferred.
392 if (DMin != EMin)
393 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000394 // FIXME: When we track visibility for default function arguments, check
395 // that we pick the declaration with more visible default arguments.
Richard Smithcd31b852015-08-22 21:37:34 +0000396 }
397
398 // Pick the template with more default template arguments.
399 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
400 auto *ETD = cast<TemplateDecl>(EUnderlying);
401 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
402 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
Richard Smith535ff802015-09-11 22:39:35 +0000403 // If D has more default arguments, it is preferred. Note that default
404 // arguments (and their visibility) is monotonically increasing across the
405 // redeclaration chain, so this is a quick proxy for "is more recent".
Richard Smithcd31b852015-08-22 21:37:34 +0000406 if (DMin != EMin)
407 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000408 // If D has more *visible* default arguments, it is preferred. Note, an
409 // earlier default argument being visible does not imply that a later
410 // default argument is visible, so we can't just check the first one.
411 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
412 I != N; ++I) {
413 if (!S.hasVisibleDefaultArgument(
414 ETD->getTemplateParameters()->getParam(I)) &&
415 S.hasVisibleDefaultArgument(
416 DTD->getTemplateParameters()->getParam(I)))
417 return true;
418 }
Richard Smithcd31b852015-08-22 21:37:34 +0000419 }
420
Vassil Vassilev4d75e8d2016-02-28 19:08:24 +0000421 // VarDecl can have incomplete array types, prefer the one with more complete
422 // array type.
423 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
424 VarDecl *EVD = cast<VarDecl>(EUnderlying);
425 if (EVD->getType()->isIncompleteType() &&
426 !DVD->getType()->isIncompleteType()) {
427 // Prefer the decl with a more complete type if visible.
428 return S.isVisible(DVD);
429 }
430 return false; // Avoid picking up a newer decl, just because it was newer.
431 }
432
Richard Smithcd31b852015-08-22 21:37:34 +0000433 // For most kinds of declaration, it doesn't really matter which one we pick.
434 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
435 // If the existing declaration is hidden, prefer the new one. Otherwise,
436 // keep what we've got.
437 return !S.isVisible(Existing);
438 }
439
440 // Pick the newer declaration; it might have a more precise type.
Richard Smith826711d2015-07-29 23:38:25 +0000441 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
442 Prev = Prev->getPreviousDecl())
443 if (Prev == EUnderlying)
444 return true;
Richard Smith826711d2015-07-29 23:38:25 +0000445 return false;
446}
447
Richard Smith990668b2015-11-12 22:04:34 +0000448/// Determine whether \p D can hide a tag declaration.
449static bool canHideTag(NamedDecl *D) {
450 // C++ [basic.scope.declarative]p4:
451 // Given a set of declarations in a single declarative region [...]
452 // exactly one declaration shall declare a class name or enumeration name
453 // that is not a typedef name and the other declarations shall all refer to
Richard Smith4eeaec42016-12-18 22:01:46 +0000454 // the same variable, non-static data member, or enumerator, or all refer
455 // to functions and function templates; in this case the class name or
456 // enumeration name is hidden.
Richard Smith990668b2015-11-12 22:04:34 +0000457 // C++ [basic.scope.hiding]p2:
458 // A class name or enumeration name can be hidden by the name of a
459 // variable, data member, function, or enumerator declared in the same
460 // scope.
Richard Smith4eeaec42016-12-18 22:01:46 +0000461 // An UnresolvedUsingValueDecl always instantiates to one of these.
Richard Smith990668b2015-11-12 22:04:34 +0000462 D = D->getUnderlyingDecl();
463 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
Richard Smith4eeaec42016-12-18 22:01:46 +0000464 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
465 isa<UnresolvedUsingValueDecl>(D);
Richard Smith990668b2015-11-12 22:04:34 +0000466}
467
John McCall283b9012009-11-22 00:44:51 +0000468/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000469void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000470 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000471
John McCall9f3059a2009-10-09 21:13:30 +0000472 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000473 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000474 assert(ResultKind == NotFound ||
475 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000476 return;
477 }
478
John McCall283b9012009-11-22 00:44:51 +0000479 // If there's a single decl, we need to examine it to decide what
480 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000481 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000482 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
483 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000484 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000485 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000486 ResultKind = FoundUnresolvedValue;
487 return;
488 }
John McCall9f3059a2009-10-09 21:13:30 +0000489
John McCall6538c932009-10-10 05:48:19 +0000490 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000491 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000492
Richard Smitha534a312015-07-21 23:54:07 +0000493 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000494 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000495
John McCall9f3059a2009-10-09 21:13:30 +0000496 bool Ambiguous = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000497 bool HasTag = false, HasFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000498 bool HasFunctionTemplate = false, HasUnresolved = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000499 NamedDecl *HasNonFunction = nullptr;
500
501 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
John McCall9f3059a2009-10-09 21:13:30 +0000502
503 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000504
John McCall9f3059a2009-10-09 21:13:30 +0000505 unsigned I = 0;
506 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000507 NamedDecl *D = Decls[I]->getUnderlyingDecl();
508 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000509
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000510 // Ignore an invalid declaration unless it's the only one left.
Richard Smith5cd86f82015-11-03 03:13:11 +0000511 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000512 Decls[I] = Decls[--N];
513 continue;
514 }
515
Richard Smith826711d2015-07-29 23:38:25 +0000516 llvm::Optional<unsigned> ExistingI;
517
Douglas Gregor13e65872010-08-11 14:45:53 +0000518 // Redeclarations of types via typedef can occur both within a scope
519 // and, through using declarations and directives, across scopes. There is
520 // no ambiguity if they all refer to the same type, so unique based on the
521 // canonical type.
522 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith990668b2015-11-12 22:04:34 +0000523 QualType T = getSema().Context.getTypeDeclType(TD);
524 auto UniqueResult = UniqueTypes.insert(
525 std::make_pair(getSema().Context.getCanonicalType(T), I));
526 if (!UniqueResult.second) {
527 // The type is not unique.
528 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000529 }
530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531
Richard Smith826711d2015-07-29 23:38:25 +0000532 // For non-type declarations, check for a prior lookup result naming this
533 // canonical declaration.
534 if (!ExistingI) {
535 auto UniqueResult = Unique.insert(std::make_pair(D, I));
536 if (!UniqueResult.second) {
537 // We've seen this entity before.
538 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000539 }
Richard Smith826711d2015-07-29 23:38:25 +0000540 }
541
542 if (ExistingI) {
543 // This is not a unique lookup result. Pick one of the results and
544 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000545 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000546 Decls[*ExistingI]))
547 Decls[*ExistingI] = Decls[I];
548 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000549 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 }
551
Douglas Gregor13e65872010-08-11 14:45:53 +0000552 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000553
Douglas Gregor13e65872010-08-11 14:45:53 +0000554 if (isa<UnresolvedUsingValueDecl>(D)) {
555 HasUnresolved = true;
556 } else if (isa<TagDecl>(D)) {
557 if (HasTag)
558 Ambiguous = true;
559 UniqueTagIndex = I;
560 HasTag = true;
561 } else if (isa<FunctionTemplateDecl>(D)) {
562 HasFunction = true;
563 HasFunctionTemplate = true;
564 } else if (isa<FunctionDecl>(D)) {
565 HasFunction = true;
566 } else {
Richard Smith2dbe4042015-11-04 19:26:32 +0000567 if (HasNonFunction) {
568 // If we're about to create an ambiguity between two declarations that
569 // are equivalent, but one is an internal linkage declaration from one
570 // module and the other is an internal linkage declaration from another
571 // module, just skip it.
572 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
573 D)) {
574 EquivalentNonFunctions.push_back(D);
575 Decls[I] = Decls[--N];
576 continue;
577 }
578
Douglas Gregor13e65872010-08-11 14:45:53 +0000579 Ambiguous = true;
Richard Smith2dbe4042015-11-04 19:26:32 +0000580 }
581 HasNonFunction = D;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000582 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000583 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000584 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000585
John McCall9f3059a2009-10-09 21:13:30 +0000586 // C++ [basic.scope.hiding]p2:
587 // A class name or enumeration name can be hidden by the name of
588 // an object, function, or enumerator declared in the same
589 // scope. If a class or enumeration name and an object, function,
590 // or enumerator are declared in the same scope (in any order)
591 // with the same name, the class or enumeration name is hidden
592 // wherever the object, function, or enumerator name is visible.
593 // But it's still an error if there are distinct tag types found,
594 // even if they're not visible. (ref?)
Richard Smith990668b2015-11-12 22:04:34 +0000595 if (N > 1 && HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000596 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith990668b2015-11-12 22:04:34 +0000597 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
598 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
599 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
600 getContextForScopeMatching(OtherDecl)) &&
601 canHideTag(OtherDecl))
Douglas Gregore63d0872010-10-23 16:06:17 +0000602 Decls[UniqueTagIndex] = Decls[--N];
603 else
604 Ambiguous = true;
605 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000606
Richard Smith2dbe4042015-11-04 19:26:32 +0000607 // FIXME: This diagnostic should really be delayed until we're done with
608 // the lookup result, in case the ambiguity is resolved by the caller.
609 if (!EquivalentNonFunctions.empty() && !Ambiguous)
610 getSema().diagnoseEquivalentInternalLinkageDeclarations(
611 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
612
John McCall9f3059a2009-10-09 21:13:30 +0000613 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000614
John McCall80053822009-12-03 00:58:24 +0000615 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000616 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000617
John McCall9f3059a2009-10-09 21:13:30 +0000618 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000619 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000620 else if (HasUnresolved)
621 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000622 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000623 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000624 else
John McCall27b18f82009-11-17 02:14:36 +0000625 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000626}
627
John McCall5cebab12009-11-18 07:57:50 +0000628void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000629 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000630 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000631 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
632 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000633 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000634}
635
John McCall5cebab12009-11-18 07:57:50 +0000636void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000637 Paths = new CXXBasePaths;
638 Paths->swap(P);
639 addDeclsFromBasePaths(*Paths);
640 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000641 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000642}
643
John McCall5cebab12009-11-18 07:57:50 +0000644void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000645 Paths = new CXXBasePaths;
646 Paths->swap(P);
647 addDeclsFromBasePaths(*Paths);
648 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000649 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000650}
651
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000652void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000653 Out << Decls.size() << " result(s)";
654 if (isAmbiguous()) Out << ", ambiguous";
655 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
John McCall9f3059a2009-10-09 21:13:30 +0000657 for (iterator I = begin(), E = end(); I != E; ++I) {
658 Out << "\n";
659 (*I)->print(Out, 2);
660 }
661}
662
Richard Smithba3a4f92016-01-12 21:59:26 +0000663LLVM_DUMP_METHOD void LookupResult::dump() {
664 llvm::errs() << "lookup results for " << getLookupName().getAsString()
665 << ":\n";
666 for (NamedDecl *D : *this)
667 D->dump();
668}
669
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000670/// Lookup a builtin function, when name lookup would otherwise
Douglas Gregord3a59182010-02-12 05:48:04 +0000671/// fail.
672static bool LookupBuiltin(Sema &S, LookupResult &R) {
673 Sema::LookupNameKind NameKind = R.getLookupKind();
674
675 // If we didn't find a use of this identifier, and if the identifier
676 // corresponds to a compiler builtin, create the decl object for the builtin
677 // now, injecting it into translation unit scope, and return it.
678 if (NameKind == Sema::LookupOrdinaryName ||
679 NameKind == Sema::LookupRedeclarationWithLinkage) {
680 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
681 if (II) {
Eric Fiselier6ad68552016-07-01 01:24:09 +0000682 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
683 if (II == S.getASTContext().getMakeIntegerSeqName()) {
684 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
685 return true;
686 } else if (II == S.getASTContext().getTypePackElementName()) {
687 R.addDecl(S.getASTContext().getTypePackElementDecl());
688 return true;
689 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000690 }
Nico Webere1687c52013-06-20 21:44:55 +0000691
Douglas Gregord3a59182010-02-12 05:48:04 +0000692 // If this is a builtin on this (or all) targets, create the decl.
693 if (unsigned BuiltinID = II->getBuiltinID()) {
Anastasia Stulovab607e0f2016-02-02 11:29:43 +0000694 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
695 // library functions like 'malloc'. Instead, we'll just error.
696 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000697 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
698 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
700 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
701 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000702 R.isForRedeclaration(),
703 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000704 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000705 return true;
706 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000707 }
708 }
709 }
710
711 return false;
712}
713
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000714/// Determine whether we can declare a special member function within
Douglas Gregor7454c562010-07-02 20:37:36 +0000715/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000716static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000717 // We need to have a definition for the class.
718 if (!Class->getDefinition() || Class->isDependentContext())
719 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000720
Douglas Gregor7454c562010-07-02 20:37:36 +0000721 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000722 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000723}
724
725void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000726 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000727 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000728
729 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000730 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000731 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000732
Douglas Gregora6d69502010-07-02 23:41:54 +0000733 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000734 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000735 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000737 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000738 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000739 DeclareImplicitCopyAssignment(Class);
740
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000741 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000742 // If the move constructor has not yet been declared, do so now.
743 if (Class->needsImplicitMoveConstructor())
Richard Smitha87b7662016-05-13 18:48:05 +0000744 DeclareImplicitMoveConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000745
746 // If the move assignment operator has not yet been declared, do so now.
747 if (Class->needsImplicitMoveAssignment())
Richard Smitha87b7662016-05-13 18:48:05 +0000748 DeclareImplicitMoveAssignment(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000749 }
750
Douglas Gregor7454c562010-07-02 20:37:36 +0000751 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000752 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000753 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000754}
755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000756/// Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000757/// special member function.
758static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
759 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000760 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000761 case DeclarationName::CXXDestructorName:
762 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000763
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000764 case DeclarationName::CXXOperatorName:
765 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000766
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000767 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000770
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000771 return false;
772}
773
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000774/// If there are any implicit member functions with the given name
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000775/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000776static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000777 DeclarationName Name,
Richard Smith32918772017-02-14 00:25:28 +0000778 SourceLocation Loc,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000779 const DeclContext *DC) {
780 if (!DC)
781 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000783 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000784 case DeclarationName::CXXConstructorName:
785 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000786 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000787 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000788 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000789 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000790 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000791 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000792 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000793 Record->needsImplicitMoveConstructor())
794 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000795 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000796 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000798 case DeclarationName::CXXDestructorName:
799 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000800 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000801 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000802 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000803 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000805 case DeclarationName::CXXOperatorName:
806 if (Name.getCXXOverloadedOperator() != OO_Equal)
807 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808
Sebastian Redl22653ba2011-08-30 19:58:05 +0000809 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000810 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000811 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000812 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000813 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000814 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000815 Record->needsImplicitMoveAssignment())
816 S.DeclareImplicitMoveAssignment(Class);
817 }
818 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000819 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Richard Smith32918772017-02-14 00:25:28 +0000821 case DeclarationName::CXXDeductionGuideName:
822 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
823 break;
824
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000825 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000827 }
828}
Douglas Gregor7454c562010-07-02 20:37:36 +0000829
John McCall9f3059a2009-10-09 21:13:30 +0000830// Adds all qualifying matches for a name within a decl context to the
831// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000832static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000833 bool Found = false;
834
Douglas Gregor7454c562010-07-02 20:37:36 +0000835 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000836 if (S.getLangOpts().CPlusPlus)
Richard Smith32918772017-02-14 00:25:28 +0000837 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
838 DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor7454c562010-07-02 20:37:36 +0000840 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000841 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
Yaron Keren31bde582017-04-12 10:05:48 +0000842 for (NamedDecl *D : DR) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000843 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000844 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000845 Found = true;
846 }
847 }
John McCall9f3059a2009-10-09 21:13:30 +0000848
Douglas Gregord3a59182010-02-12 05:48:04 +0000849 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
850 return true;
851
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000852 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000853 != DeclarationName::CXXConversionFunctionName ||
854 R.getLookupName().getCXXNameType()->isDependentType() ||
855 !isa<CXXRecordDecl>(DC))
856 return Found;
857
858 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000860 // name lookup. Instead, any conversion function templates visible in the
861 // context of the use are considered. [...]
862 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000863 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000864 return Found;
865
Erich Keanec9cb1c12017-06-20 17:38:07 +0000866 // For conversion operators, 'operator auto' should only match
867 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
868 // as a candidate for template substitution.
869 auto *ContainedDeducedType =
870 R.getLookupName().getCXXNameType()->getContainedDeducedType();
871 if (R.getLookupName().getNameKind() ==
872 DeclarationName::CXXConversionFunctionName &&
873 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
874 return Found;
875
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000876 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
877 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000878 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
879 if (!ConvTemplate)
880 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881
Chandler Carruth3a693b72010-01-31 11:44:02 +0000882 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000883 // add the conversion function template. When we deduce template
884 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000885 // type of the new declaration with the type of the function template.
886 if (R.isForRedeclaration()) {
887 R.addDecl(ConvTemplate);
888 Found = true;
889 continue;
890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000891
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000892 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000893 // [...] For each such operator, if argument deduction succeeds
894 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000895 // name lookup.
896 //
897 // When referencing a conversion function for any purpose other than
898 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000899 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000900 // specialization into the result set. We do this to avoid forcing all
901 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000902 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000903 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000904
905 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000906 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
907 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000908
Chandler Carruth3a693b72010-01-31 11:44:02 +0000909 // Compute the type of the function that we would expect the conversion
910 // function to have, if it were to match the name given.
911 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000912 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000913 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000914 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000915 QualType ExpectedType
916 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000917 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
Chandler Carruth3a693b72010-01-31 11:44:02 +0000919 // Perform template argument deduction against the type that we would
920 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000921 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000922 Specialization, Info)
923 == Sema::TDK_Success) {
924 R.addDecl(Specialization);
925 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000926 }
927 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000928
John McCall9f3059a2009-10-09 21:13:30 +0000929 return Found;
930}
931
John McCallf6c8a4e2009-11-10 07:01:13 +0000932// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000933static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000935 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000936
937 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
938
John McCallf6c8a4e2009-11-10 07:01:13 +0000939 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000940 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000941
John McCallf6c8a4e2009-11-10 07:01:13 +0000942 // Perform direct name lookup into the namespaces nominated by the
943 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000944 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
945 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000946 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000947
948 R.resolveKind();
949
950 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000951}
952
953static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000954 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000955 return Ctx->isFileContext();
956 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000957}
Douglas Gregored8f2882009-01-30 01:04:22 +0000958
Douglas Gregor66230062010-03-15 14:33:29 +0000959// Find the next outer declaration context from this scope. This
960// routine actually returns the semantic outer context, which may
961// differ from the lexical context (encoded directly in the Scope
962// stack) when we are parsing a member of a class template. In this
963// case, the second element of the pair will be true, to indicate that
964// name lookup should continue searching in this semantic context when
965// it leaves the current template parameter scope.
966static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000967 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000968 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000970 OuterS = OuterS->getParent()) {
971 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000972 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000973 break;
974 }
975 }
976
977 // C++ [temp.local]p8:
978 // In the definition of a member of a class template that appears
979 // outside of the namespace containing the class template
980 // definition, the name of a template-parameter hides the name of
981 // a member of this namespace.
982 //
983 // Example:
984 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985 // namespace N {
986 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000987 //
988 // template<class T> class B {
989 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000990 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000991 // }
992 //
993 // template<class C> void N::B<C>::f(C) {
994 // C b; // C is the template parameter, not N::C
995 // }
996 //
997 // In this example, the lexical context we return is the
998 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +00001000 !S->getParent()->isTemplateParamScope())
1001 return std::make_pair(Lexical, false);
1002
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001003 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +00001004 // For the example, this is the scope for the template parameters of
1005 // template<class C>.
1006 Scope *OutermostTemplateScope = S->getParent();
1007 while (OutermostTemplateScope->getParent() &&
1008 OutermostTemplateScope->getParent()->isTemplateParamScope())
1009 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Douglas Gregor66230062010-03-15 14:33:29 +00001011 // Find the namespace context in which the original scope occurs. In
1012 // the example, this is namespace N.
1013 DeclContext *Semantic = DC;
1014 while (!Semantic->isFileContext())
1015 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001016
Douglas Gregor66230062010-03-15 14:33:29 +00001017 // Find the declaration context just outside of the template
1018 // parameter scope. This is the context in which the template is
1019 // being lexically declaration (a namespace context). In the
1020 // example, this is the global scope.
1021 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1022 Lexical->Encloses(Semantic))
1023 return std::make_pair(Semantic, true);
1024
1025 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +00001026}
1027
Richard Smith541b38b2013-09-20 01:15:31 +00001028namespace {
1029/// An RAII object to specify that we want to find block scope extern
1030/// declarations.
1031struct FindLocalExternScope {
1032 FindLocalExternScope(LookupResult &R)
1033 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1034 Decl::IDNS_LocalExtern) {
Eric Fiselier5485cc12017-07-31 00:24:28 +00001035 R.setFindLocalExtern(R.getIdentifierNamespace() &
1036 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
Richard Smith541b38b2013-09-20 01:15:31 +00001037 }
1038 void restore() {
1039 R.setFindLocalExtern(OldFindLocalExtern);
1040 }
1041 ~FindLocalExternScope() {
1042 restore();
1043 }
1044 LookupResult &R;
1045 bool OldFindLocalExtern;
1046};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001047} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +00001048
John McCall27b18f82009-11-17 02:14:36 +00001049bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001050 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +00001051
1052 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +00001053 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +00001054
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001055 // If this is the name of an implicitly-declared special member function,
1056 // go through the scope stack to implicitly declare
1057 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1058 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00001059 if (DeclContext *DC = PreS->getEntity())
Richard Smith32918772017-02-14 00:25:28 +00001060 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001063 // Implicitly declare member functions with the name we're looking for, if in
1064 // fact we are in a scope where it matters.
1065
Douglas Gregor889ceb72009-02-03 19:21:40 +00001066 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +00001067 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +00001068 I = IdResolver.begin(Name),
1069 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001070
Douglas Gregor889ceb72009-02-03 19:21:40 +00001071 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001072 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +00001073 // ...During unqualified name lookup (3.4.1), the names appear as if
1074 // they were declared in the nearest enclosing namespace which contains
1075 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001076 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001077 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001078 //
1079 // For example:
1080 // namespace A { int i; }
1081 // void foo() {
1082 // int i;
1083 // {
1084 // using namespace A;
1085 // ++i; // finds local 'i', A::i appears at global scope
1086 // }
1087 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001088 //
Richard Smithb920f852017-10-11 01:19:11 +00001089 UnqualUsingDirectiveSet UDirs(*this);
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001090 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001091 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001092 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001093
1094 // When performing a scope lookup, we want to find local extern decls.
1095 FindLocalExternScope FindLocals(R);
1096
Douglas Gregor700792c2009-02-05 19:25:20 +00001097 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001098 DeclContext *Ctx = S->getEntity();
Olivier Goffart12b221982016-06-16 21:39:46 +00001099 bool SearchNamespaceScope = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +00001100 // Check whether the IdResolver has anything in this scope.
John McCall48871652010-08-21 09:40:31 +00001101 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001102 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Olivier Goffart12b221982016-06-16 21:39:46 +00001103 if (NameKind == LookupRedeclarationWithLinkage &&
1104 !(*I)->isTemplateParameter()) {
1105 // If it's a template parameter, we still find it, so we can diagnose
1106 // the invalid redeclaration.
1107
Richard Smith1c34fb72013-08-13 18:18:50 +00001108 // Determine whether this (or a previous) declaration is
1109 // out-of-scope.
1110 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1111 LeftStartingScope = true;
1112
1113 // If we found something outside of our starting scope that
Olivier Goffart12b221982016-06-16 21:39:46 +00001114 // does not have linkage, skip it.
1115 if (LeftStartingScope && !((*I)->hasLinkage())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001116 R.setShadowed();
1117 continue;
1118 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001119 } else {
1120 // We found something in this scope, we should not look at the
1121 // namespace scope
1122 SearchNamespaceScope = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001123 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001124 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001125 }
1126 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001127 if (!SearchNamespaceScope) {
John McCall9f3059a2009-10-09 21:13:30 +00001128 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001129 if (S->isClassScope())
1130 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1131 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001132 return true;
1133 }
1134
Richard Smith1c34fb72013-08-13 18:18:50 +00001135 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001136 // C++11 [class.friend]p11:
1137 // If a friend declaration appears in a local class and the name
1138 // specified is an unqualified name, a prior declaration is
1139 // looked up without considering scopes that are outside the
1140 // innermost enclosing non-class scope.
1141 return false;
1142 }
1143
Douglas Gregor66230062010-03-15 14:33:29 +00001144 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1145 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1146 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001147 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001148 // lexical and semantic declaration contexts returned by
1149 // findOuterContext(). This implements the name lookup behavior
1150 // of C++ [temp.local]p8.
1151 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001152 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001153 }
1154
1155 if (Ctx) {
1156 DeclContext *OuterCtx;
1157 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001158 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001159 if (SearchAfterTemplateScope)
1160 OutsideOfTemplateParamDC = OuterCtx;
1161
Douglas Gregorea166062010-03-15 15:26:48 +00001162 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001163 // We do not directly look into transparent contexts, since
1164 // those entities will be found in the nearest enclosing
1165 // non-transparent context.
1166 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001167 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001168
1169 // We do not look directly into function or method contexts,
1170 // since all of the local variables and parameters of the
1171 // function/method are present within the Scope.
1172 if (Ctx->isFunctionOrMethod()) {
1173 // If we have an Objective-C instance method, look for ivars
1174 // in the corresponding interface.
1175 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1176 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1177 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1178 ObjCInterfaceDecl *ClassDeclared;
1179 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001180 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001181 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001182 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1183 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001184 R.resolveKind();
1185 return true;
1186 }
1187 }
1188 }
1189 }
1190
1191 continue;
1192 }
1193
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001194 // If this is a file context, we need to perform unqualified name
1195 // lookup considering using directives.
1196 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001197 // If we haven't handled using directives yet, do so now.
1198 if (!VisitedUsingDirectives) {
1199 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001200 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1201 if (UCtx->isTransparentContext())
1202 continue;
1203
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001204 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001205 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001206
1207 // Find the innermost file scope, so we can add using directives
1208 // from local scopes.
1209 Scope *InnermostFileScope = S;
1210 while (InnermostFileScope &&
1211 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1212 InnermostFileScope = InnermostFileScope->getParent();
1213 UDirs.visitScopeChain(Initial, InnermostFileScope);
1214
1215 UDirs.done();
1216
1217 VisitedUsingDirectives = true;
1218 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001219
1220 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1221 R.resolveKind();
1222 return true;
1223 }
1224
1225 continue;
1226 }
1227
Douglas Gregor7f737c02009-09-10 16:57:35 +00001228 // Perform qualified name lookup into this context.
1229 // FIXME: In some cases, we know that every name that could be found by
1230 // this qualified name lookup will also be on the identifier chain. For
1231 // example, inside a class without any base classes, we never need to
1232 // perform qualified lookup because all of the members are on top of the
1233 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001234 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001235 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001236 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001237 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001238 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001239
John McCallf6c8a4e2009-11-10 07:01:13 +00001240 // Stop if we ran out of scopes.
1241 // FIXME: This really, really shouldn't be happening.
1242 if (!S) return false;
1243
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001244 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001245 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001246 return false;
1247
Douglas Gregor700792c2009-02-05 19:25:20 +00001248 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001249 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001250 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001251 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1252 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001253 if (!VisitedUsingDirectives) {
1254 UDirs.visitScopeChain(Initial, S);
1255 UDirs.done();
1256 }
Richard Smith541b38b2013-09-20 01:15:31 +00001257
1258 // If we're not performing redeclaration lookup, do not look for local
1259 // extern declarations outside of a function scope.
1260 if (!R.isForRedeclaration())
1261 FindLocals.restore();
1262
Douglas Gregor700792c2009-02-05 19:25:20 +00001263 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001264 // Unqualified name lookup in C++ requires looking into scopes
1265 // that aren't strictly lexical, and therefore we walk through the
1266 // context as well as walking through the scopes.
1267 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001268 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001269 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001270 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001271 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001272 // We found something. Look for anything else in our scope
1273 // with this same name and in an acceptable identifier
1274 // namespace, so that we can construct an overload set if we
1275 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001276 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001277 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001278 }
1279 }
1280
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001281 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001282 R.resolveKind();
1283 return true;
1284 }
1285
Ted Kremenekc37877d2013-10-08 17:08:03 +00001286 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001287 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1288 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1289 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001290 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001291 // lexical and semantic declaration contexts returned by
1292 // findOuterContext(). This implements the name lookup behavior
1293 // of C++ [temp.local]p8.
1294 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001295 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001296 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001298 if (Ctx) {
1299 DeclContext *OuterCtx;
1300 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001301 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001302 if (SearchAfterTemplateScope)
1303 OutsideOfTemplateParamDC = OuterCtx;
1304
1305 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1306 // We do not directly look into transparent contexts, since
1307 // those entities will be found in the nearest enclosing
1308 // non-transparent context.
1309 if (Ctx->isTransparentContext())
1310 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001311
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001312 // If we have a context, and it's not a context stashed in the
1313 // template parameter scope for an out-of-line definition, also
1314 // look into that context.
Chandler Carruth6232e4d2016-11-04 06:16:09 +00001315 if (!(Found && S->isTemplateParamScope())) {
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001316 assert(Ctx->isFileContext() &&
1317 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001318
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001319 // Look into context considering using-directives.
1320 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1321 Found = true;
1322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001323
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001324 if (Found) {
1325 R.resolveKind();
1326 return true;
1327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001329 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1330 return false;
1331 }
1332 }
1333
Douglas Gregor3ce74932010-02-05 07:07:10 +00001334 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001335 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001336 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001337
John McCall9f3059a2009-10-09 21:13:30 +00001338 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001339}
1340
Richard Smith858e0e02017-05-11 23:11:16 +00001341void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1342 if (auto *M = getCurrentModule())
Richard Smith87bb5692015-06-09 00:35:49 +00001343 Context.mergeDefinitionIntoModule(ND, M);
1344 else
1345 // We're not building a module; just make the definition visible.
Richard Smith90dc5252017-06-23 01:04:34 +00001346 ND->setVisibleDespiteOwningModule();
Richard Smith63e09bf2015-06-17 20:39:41 +00001347
1348 // If ND is a template declaration, make the template parameters
1349 // visible too. They're not (necessarily) within a mergeable DeclContext.
1350 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1351 for (auto *Param : *TD->getTemplateParameters())
Richard Smith858e0e02017-05-11 23:11:16 +00001352 makeMergedDefinitionVisible(Param);
Richard Smithd9ba2242015-05-07 03:54:19 +00001353}
1354
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001355/// Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001356static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001357 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1358 // If this function was instantiated from a template, the defining module is
1359 // the module containing the pattern.
1360 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1361 Entity = Pattern;
1362 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001363 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1364 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001365 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
Richard Smith2195ec92017-04-21 01:15:13 +00001366 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1367 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001368 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
Richard Smith2195ec92017-04-21 01:15:13 +00001369 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1370 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001371 }
1372
Chandler Carruthbd186c02017-04-19 05:25:13 +00001373 // Walk up to the containing context. That might also have been instantiated
1374 // from a template.
Richard Smith17ad3ac2017-10-18 01:41:38 +00001375 DeclContext *Context = Entity->getLexicalDeclContext();
Chandler Carruthbd186c02017-04-19 05:25:13 +00001376 if (Context->isFileContext())
1377 return S.getOwningModule(Entity);
1378 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001379}
1380
1381llvm::DenseSet<Module*> &Sema::getLookupModules() {
Richard Smith696e3122017-02-23 01:43:54 +00001382 unsigned N = CodeSynthesisContexts.size();
1383 for (unsigned I = CodeSynthesisContextLookupModules.size();
Richard Smith0e5d7b82013-07-25 23:08:39 +00001384 I != N; ++I) {
Richard Smith696e3122017-02-23 01:43:54 +00001385 Module *M = getDefiningModule(*this, CodeSynthesisContexts[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001386 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001387 M = nullptr;
Richard Smith696e3122017-02-23 01:43:54 +00001388 CodeSynthesisContextLookupModules.push_back(M);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001389 }
1390 return LookupModulesCache;
1391}
1392
Richard Smithc4577662018-09-12 02:13:47 +00001393/// Determine whether the module M is part of the current module from the
1394/// perspective of a module-private visibility check.
1395static bool isInCurrentModule(const Module *M, const LangOptions &LangOpts) {
1396 // If M is the global module fragment of a module that we've not yet finished
1397 // parsing, then it must be part of the current module.
1398 return M->getTopLevelModuleName() == LangOpts.CurrentModule ||
1399 (M->Kind == Module::GlobalModuleFragment && !M->Parent);
1400}
1401
Richard Smith42413142015-05-15 20:05:43 +00001402bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
Richard Smithc4577662018-09-12 02:13:47 +00001403 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
Richard Smith42413142015-05-15 20:05:43 +00001404 if (isModuleVisible(Merged))
1405 return true;
1406 return false;
1407}
1408
Richard Smithe03a6542017-07-05 01:42:07 +00001409bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
Richard Smithc4577662018-09-12 02:13:47 +00001410 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1411 if (isInCurrentModule(Merged, getLangOpts()))
Richard Smithe03a6542017-07-05 01:42:07 +00001412 return true;
1413 return false;
1414}
1415
Richard Smithe7bd6de2015-06-10 20:30:23 +00001416template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001417static bool
1418hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1419 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001420 if (!D->hasDefaultArgument())
1421 return false;
1422
1423 while (D) {
1424 auto &DefaultArg = D->getDefaultArgStorage();
1425 if (!DefaultArg.isInherited() && S.isVisible(D))
1426 return true;
1427
Richard Smith63e09bf2015-06-17 20:39:41 +00001428 if (!DefaultArg.isInherited() && Modules) {
1429 auto *NonConstD = const_cast<ParmDecl*>(D);
1430 Modules->push_back(S.getOwningModule(NonConstD));
Richard Smith63e09bf2015-06-17 20:39:41 +00001431 }
Richard Smith35c1df52015-06-17 20:16:32 +00001432
Richard Smithe7bd6de2015-06-10 20:30:23 +00001433 // If there was a previous default argument, maybe its parameter is visible.
1434 D = DefaultArg.getInheritedFrom();
1435 }
1436 return false;
1437}
1438
Richard Smith35c1df52015-06-17 20:16:32 +00001439bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1440 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001441 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001442 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001443 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001444 return ::hasVisibleDefaultArgument(*this, P, Modules);
1445 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1446 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001447}
1448
Richard Smith54f04402017-05-18 02:29:20 +00001449template<typename Filter>
1450static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
1451 llvm::SmallVectorImpl<Module *> *Modules,
1452 Filter F) {
Richard Trieu81536282018-06-07 03:20:30 +00001453 bool HasFilteredRedecls = false;
1454
Richard Smith54f04402017-05-18 02:29:20 +00001455 for (auto *Redecl : D->redecls()) {
1456 auto *R = cast<NamedDecl>(Redecl);
1457 if (!F(R))
1458 continue;
1459
1460 if (S.isVisible(R))
1461 return true;
1462
Richard Trieu81536282018-06-07 03:20:30 +00001463 HasFilteredRedecls = true;
1464
Richard Smithc4577662018-09-12 02:13:47 +00001465 if (Modules)
Richard Smith54f04402017-05-18 02:29:20 +00001466 Modules->push_back(R->getOwningModule());
Richard Smith54f04402017-05-18 02:29:20 +00001467 }
1468
Richard Trieu81536282018-06-07 03:20:30 +00001469 // Only return false if there is at least one redecl that is not filtered out.
1470 if (HasFilteredRedecls)
1471 return false;
1472
1473 return true;
Richard Smith54f04402017-05-18 02:29:20 +00001474}
1475
1476bool Sema::hasVisibleExplicitSpecialization(
1477 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1478 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1479 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1480 return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1481 if (auto *FD = dyn_cast<FunctionDecl>(D))
1482 return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1483 if (auto *VD = dyn_cast<VarDecl>(D))
1484 return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1485 llvm_unreachable("unknown explicit specialization kind");
1486 });
1487}
1488
Richard Smith6739a102016-05-05 00:56:12 +00001489bool Sema::hasVisibleMemberSpecialization(
1490 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1491 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1492 "not a member specialization");
Richard Smith54f04402017-05-18 02:29:20 +00001493 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
Richard Smith6739a102016-05-05 00:56:12 +00001494 // If the specialization is declared at namespace scope, then it's a member
1495 // specialization declaration. If it's lexically inside the class
1496 // definition then it was instantiated.
1497 //
1498 // FIXME: This is a hack. There should be a better way to determine this.
1499 // FIXME: What about MS-style explicit specializations declared within a
1500 // class definition?
Richard Smith54f04402017-05-18 02:29:20 +00001501 return D->getLexicalDeclContext()->isFileContext();
1502 });
Richard Smith6739a102016-05-05 00:56:12 +00001503}
1504
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001505/// Determine whether a declaration is visible to name lookup.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001506///
1507/// This routine determines whether the declaration D is visible in the current
1508/// lookup context, taking into account the current template instantiation
1509/// stack. During template instantiation, a declaration is visible if it is
1510/// visible from a module containing any entity on the template instantiation
1511/// path (by instantiating a template, you allow it to see the declarations that
1512/// your module can see, including those later on in your module).
1513bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001514 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001515
Richard Smith54f04402017-05-18 02:29:20 +00001516 Module *DeclModule = SemaRef.getOwningModule(D);
Richard Smithc4577662018-09-12 02:13:47 +00001517 assert(DeclModule && "hidden decl has no owning module");
1518
1519 // If the owning module is visible, the decl is visible.
1520 if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
1521 return true;
Richard Smith54f04402017-05-18 02:29:20 +00001522
Richard Smithd19389a2017-07-05 07:47:11 +00001523 // Determine whether a decl context is a file context for the purpose of
1524 // visibility. This looks through some (export and linkage spec) transparent
1525 // contexts, but not others (enums).
1526 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1527 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1528 isa<ExportDecl>(DC);
1529 };
Richard Smith0e5d7b82013-07-25 23:08:39 +00001530
Richard Smithd19389a2017-07-05 07:47:11 +00001531 // If this declaration is not at namespace scope
Richard Smithbe3980b2015-03-27 00:41:57 +00001532 // then it is visible if its lexical parent has a visible definition.
1533 DeclContext *DC = D->getLexicalDeclContext();
Richard Smithd19389a2017-07-05 07:47:11 +00001534 if (DC && !IsEffectivelyFileContext(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001535 // For a parameter, check whether our current template declaration's
1536 // lexical context is visible, not whether there's some other visible
1537 // definition of it, because parameters aren't "within" the definition.
Vassil Vassilev714b81c2016-09-08 20:34:41 +00001538 //
1539 // In C++ we need to check for a visible definition due to ODR merging,
1540 // and in C we must not because each declaration of a function gets its own
1541 // set of declarations for tags in prototype scope.
Richard Smithd19389a2017-07-05 07:47:11 +00001542 bool VisibleWithinParent;
1543 if (D->isTemplateParameter() || isa<ParmVarDecl>(D) ||
1544 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1545 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1546 else if (D->isModulePrivate()) {
1547 // A module-private declaration is only visible if an enclosing lexical
1548 // parent was merged with another definition in the current module.
1549 VisibleWithinParent = false;
1550 do {
1551 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1552 VisibleWithinParent = true;
1553 break;
1554 }
1555 DC = DC->getLexicalParent();
1556 } while (!IsEffectivelyFileContext(DC));
1557 } else {
1558 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
Richard Smithbe3980b2015-03-27 00:41:57 +00001559 }
Richard Smithd19389a2017-07-05 07:47:11 +00001560
1561 if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1562 // FIXME: Do something better in this case.
1563 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1564 // Cache the fact that this declaration is implicitly visible because
1565 // its parent has a visible definition.
1566 D->setVisibleDespiteOwningModule();
1567 }
1568 return VisibleWithinParent;
Richard Smithbe3980b2015-03-27 00:41:57 +00001569 }
1570
Richard Smithc4577662018-09-12 02:13:47 +00001571 return false;
1572}
1573
1574bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1575 // The module might be ordinarily visible. For a module-private query, that
1576 // means it is part of the current module. For any other query, that means it
1577 // is in our visible module set.
1578 if (ModulePrivate) {
1579 if (isInCurrentModule(M, getLangOpts()))
1580 return true;
1581 } else {
1582 if (VisibleModules.isVisible(M))
1583 return true;
1584 }
1585
1586 // Otherwise, it might be visible by virtue of the query being within a
1587 // template instantiation or similar that is permitted to look inside M.
Richard Smithd19389a2017-07-05 07:47:11 +00001588
Richard Smith0e5d7b82013-07-25 23:08:39 +00001589 // Find the extra places where we need to look.
Richard Smithc4577662018-09-12 02:13:47 +00001590 const auto &LookupModules = getLookupModules();
Richard Smith0e5d7b82013-07-25 23:08:39 +00001591 if (LookupModules.empty())
1592 return false;
1593
Richard Smithc4577662018-09-12 02:13:47 +00001594 // If our lookup set contains the module, it's visible.
1595 if (LookupModules.count(M))
Richard Smith0e5d7b82013-07-25 23:08:39 +00001596 return true;
1597
Richard Smithc4577662018-09-12 02:13:47 +00001598 // For a module-private query, that's everywhere we get to look.
1599 if (ModulePrivate)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001600 return false;
1601
Richard Smithc4577662018-09-12 02:13:47 +00001602 // Check whether M is transitively exported to an import of the lookup set.
Yaron Keren941ad902015-11-23 19:28:42 +00001603 return std::any_of(LookupModules.begin(), LookupModules.end(),
Richard Smithc4577662018-09-12 02:13:47 +00001604 [&](const Module *LookupM) {
1605 return LookupM->isModuleVisible(M); });
Richard Smith0e5d7b82013-07-25 23:08:39 +00001606}
1607
Richard Smith42413142015-05-15 20:05:43 +00001608bool Sema::isVisibleSlow(const NamedDecl *D) {
1609 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1610}
1611
Richard Smith10568d82015-11-17 03:02:41 +00001612bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
Richard Smithbecb92d2017-10-10 22:33:17 +00001613 // FIXME: If there are both visible and hidden declarations, we need to take
1614 // into account whether redeclaration is possible. Example:
Fangrui Song6907ce22018-07-30 19:24:48 +00001615 //
Richard Smithbecb92d2017-10-10 22:33:17 +00001616 // Non-imported module:
1617 // int f(T); // #1
1618 // Some TU:
1619 // static int f(U); // #2, not a redeclaration of #1
1620 // int f(T); // #3, finds both, should link with #1 if T != U, but
1621 // // with #2 if T == U; neither should be ambiguous.
Richard Smith10568d82015-11-17 03:02:41 +00001622 for (auto *D : R) {
1623 if (isVisible(D))
1624 return true;
Richard Smithbecb92d2017-10-10 22:33:17 +00001625 assert(D->isExternallyDeclarable() &&
1626 "should not have hidden, non-externally-declarable result here");
Richard Smith10568d82015-11-17 03:02:41 +00001627 }
Richard Smithbecb92d2017-10-10 22:33:17 +00001628
1629 // This function is called once "New" is essentially complete, but before a
1630 // previous declaration is attached. We can't query the linkage of "New" in
1631 // general, because attaching the previous declaration can change the
1632 // linkage of New to match the previous declaration.
1633 //
1634 // However, because we've just determined that there is no *visible* prior
1635 // declaration, we can compute the linkage here. There are two possibilities:
1636 //
1637 // * This is not a redeclaration; it's safe to compute the linkage now.
1638 //
1639 // * This is a redeclaration of a prior declaration that is externally
1640 // redeclarable. In that case, the linkage of the declaration is not
1641 // changed by attaching the prior declaration, because both are externally
1642 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
1643 //
1644 // FIXME: This is subtle and fragile.
1645 return New->isExternallyDeclarable();
Richard Smith10568d82015-11-17 03:02:41 +00001646}
1647
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001648/// Retrieve the visible declaration corresponding to D, if any.
Douglas Gregor4a814562011-12-14 16:03:29 +00001649///
1650/// This routine determines whether the declaration D is visible in the current
1651/// module, with the current imports. If not, it checks whether any
1652/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001653///
Douglas Gregor4a814562011-12-14 16:03:29 +00001654/// \returns D, or a visible previous declaration of D, whichever is more recent
1655/// and visible. If no declaration of D is visible, returns null.
Richard Smith041740f2018-01-06 00:09:23 +00001656static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
1657 unsigned IDNS) {
Richard Smithe156254d2013-08-20 20:35:18 +00001658 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001659
Aaron Ballman86c93902014-03-06 23:45:36 +00001660 for (auto RD : D->redecls()) {
Richard Smith4083e032016-02-17 21:52:44 +00001661 // Don't bother with extra checks if we already know this one isn't visible.
1662 if (RD == D)
1663 continue;
1664
Richard Smith6739a102016-05-05 00:56:12 +00001665 auto ND = cast<NamedDecl>(RD);
1666 // FIXME: This is wrong in the case where the previous declaration is not
1667 // visible in the same scope as D. This needs to be done much more
1668 // carefully.
Richard Smith041740f2018-01-06 00:09:23 +00001669 if (ND->isInIdentifierNamespace(IDNS) &&
1670 LookupResult::isVisible(SemaRef, ND))
Richard Smith6739a102016-05-05 00:56:12 +00001671 return ND;
Douglas Gregor4a814562011-12-14 16:03:29 +00001672 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001673
Craig Topperc3ec1492014-05-26 06:22:03 +00001674 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001675}
1676
Richard Smith6739a102016-05-05 00:56:12 +00001677bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1678 llvm::SmallVectorImpl<Module *> *Modules) {
1679 assert(!isVisible(D) && "not in slow case");
Richard Smith54f04402017-05-18 02:29:20 +00001680 return hasVisibleDeclarationImpl(*this, D, Modules,
1681 [](const NamedDecl *) { return true; });
Richard Smith6739a102016-05-05 00:56:12 +00001682}
1683
Richard Smithe156254d2013-08-20 20:35:18 +00001684NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Richard Smith4083e032016-02-17 21:52:44 +00001685 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1686 // Namespaces are a bit of a special case: we expect there to be a lot of
1687 // redeclarations of some namespaces, all declarations of a namespace are
1688 // essentially interchangeable, all declarations are found by name lookup
1689 // if any is, and namespaces are never looked up during template
1690 // instantiation. So we benefit from caching the check in this case, and
1691 // it is correct to do so.
1692 auto *Key = ND->getCanonicalDecl();
1693 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1694 return Acceptable;
Richard Smith041740f2018-01-06 00:09:23 +00001695 auto *Acceptable = isVisible(getSema(), Key)
1696 ? Key
1697 : findAcceptableDecl(getSema(), Key, IDNS);
Richard Smith4083e032016-02-17 21:52:44 +00001698 if (Acceptable)
1699 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1700 return Acceptable;
1701 }
1702
Richard Smith041740f2018-01-06 00:09:23 +00001703 return findAcceptableDecl(getSema(), D, IDNS);
Richard Smithe156254d2013-08-20 20:35:18 +00001704}
1705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001706/// Perform unqualified name lookup starting from a given
Douglas Gregor34074322009-01-14 22:20:51 +00001707/// scope.
1708///
1709/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1710/// used to find names within the current scope. For example, 'x' in
1711/// @code
1712/// int x;
1713/// int f() {
1714/// return x; // unqualified name look finds 'x' in the global scope
1715/// }
1716/// @endcode
1717///
1718/// Different lookup criteria can find different names. For example, a
1719/// particular scope can have both a struct and a function of the same
1720/// name, and each can be found by certain lookup criteria. For more
1721/// information about lookup criteria, see the documentation for the
1722/// class LookupCriteria.
1723///
1724/// @param S The scope from which unqualified name lookup will
1725/// begin. If the lookup criteria permits, name lookup may also search
1726/// in the parent scopes.
1727///
James Dennett91738ff2012-06-22 10:32:46 +00001728/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1729/// look up and the lookup kind), and is updated with the results of lookup
1730/// including zero or more declarations and possibly additional information
1731/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001732///
James Dennett91738ff2012-06-22 10:32:46 +00001733/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001734bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1735 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001736 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001737
John McCall27b18f82009-11-17 02:14:36 +00001738 LookupNameKind NameKind = R.getLookupKind();
1739
David Blaikiebbafb8a2012-03-11 07:00:24 +00001740 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001741 // Unqualified name lookup in C/Objective-C is purely lexical, so
1742 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001743 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001744 // Find the nearest non-transparent declaration scope.
1745 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001746 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001747 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001748 }
1749
Richard Smith541b38b2013-09-20 01:15:31 +00001750 // When performing a scope lookup, we want to find local extern decls.
1751 FindLocalExternScope FindLocals(R);
1752
Douglas Gregor34074322009-01-14 22:20:51 +00001753 // Scan up the scope chain looking for a decl that matches this
1754 // identifier that is in the appropriate namespace. This search
1755 // should not take long, as shadowing of names is uncommon, and
1756 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001757 bool LeftStartingScope = false;
1758
Douglas Gregored8f2882009-01-30 01:04:22 +00001759 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001760 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001761 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001762 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001763 if (NameKind == LookupRedeclarationWithLinkage) {
1764 // Determine whether this (or a previous) declaration is
1765 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001766 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001767 LeftStartingScope = true;
1768
1769 // If we found something outside of our starting scope that
1770 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001771 if (LeftStartingScope && !((*I)->hasLinkage())) {
1772 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001773 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001774 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001775 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001776 else if (NameKind == LookupObjCImplicitSelfParam &&
1777 !isa<ImplicitParamDecl>(*I))
1778 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001779
Douglas Gregor4a814562011-12-14 16:03:29 +00001780 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001781
Douglas Gregorb59643b2012-01-03 23:26:26 +00001782 // Check whether there are any other declarations with the same name
1783 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001784 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001785 // Find the scope in which this declaration was declared (if it
1786 // actually exists in a Scope).
1787 while (S && !S->isDeclScope(D))
1788 S = S->getParent();
Fangrui Song6907ce22018-07-30 19:24:48 +00001789
Douglas Gregor81bd0382012-01-13 23:06:53 +00001790 // If the scope containing the declaration is the translation unit,
1791 // then we'll need to perform our checks based on the matching
1792 // DeclContexts rather than matching scopes.
1793 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001794 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001795
1796 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001797 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001798 if (!S)
1799 DC = (*I)->getDeclContext()->getRedeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00001800
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001801 IdentifierResolver::iterator LastI = I;
1802 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001803 if (S) {
1804 // Match based on scope.
1805 if (!S->isDeclScope(*LastI))
1806 break;
1807 } else {
1808 // Match based on DeclContext.
Fangrui Song6907ce22018-07-30 19:24:48 +00001809 DeclContext *LastDC
Douglas Gregor81bd0382012-01-13 23:06:53 +00001810 = (*LastI)->getDeclContext()->getRedeclContext();
1811 if (!LastDC->Equals(DC))
1812 break;
1813 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001814
1815 // If the declaration is in the right namespace and visible, add it.
1816 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1817 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001818 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001819
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001820 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001821 }
Richard Smith541b38b2013-09-20 01:15:31 +00001822
John McCall9f3059a2009-10-09 21:13:30 +00001823 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001824 }
Douglas Gregor34074322009-01-14 22:20:51 +00001825 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001826 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001827 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001828 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001829 }
1830
1831 // If we didn't find a use of this identifier, and if the identifier
1832 // corresponds to a compiler builtin, create the decl object for the builtin
1833 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001834 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1835 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001836
Fangrui Song6907ce22018-07-30 19:24:48 +00001837 // If we didn't find a use of this identifier, the ExternalSource
1838 // may be able to handle the situation.
Axel Naumann016538a2011-02-24 16:47:47 +00001839 // Note: some lookup failures are expected!
1840 // See e.g. R.isForRedeclaration().
1841 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001842}
1843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001844/// Perform qualified name lookup in the namespaces nominated by
John McCall6538c932009-10-10 05:48:19 +00001845/// using directives by the given context.
1846///
1847/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001848/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001849/// (where X is the global namespace), let S be the set of all
1850/// declarations of m in X and in the transitive closure of all
1851/// namespaces nominated by using-directives in X and its used
1852/// namespaces, except that using-directives are ignored in any
1853/// namespace, including X, directly containing one or more
1854/// declarations of m. No namespace is searched more than once in
1855/// the lookup of a name. If S is the empty set, the program is
1856/// ill-formed. Otherwise, if S has exactly one member, or if the
1857/// context of the reference is a using-declaration
1858/// (namespace.udecl), S is the required set of declarations of
1859/// m. Otherwise if the use of m is not one that allows a unique
1860/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001861///
John McCall6538c932009-10-10 05:48:19 +00001862/// C++98 [namespace.qual]p5:
1863/// During the lookup of a qualified namespace member name, if the
1864/// lookup finds more than one declaration of the member, and if one
1865/// declaration introduces a class name or enumeration name and the
1866/// other declarations either introduce the same object, the same
1867/// enumerator or a set of functions, the non-type name hides the
1868/// class or enumeration name if and only if the declarations are
1869/// from the same namespace; otherwise (the declarations are from
1870/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001871static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001872 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001873 assert(StartDC->isFileContext() && "start context is not a file context");
1874
Richard Smithb920f852017-10-11 01:19:11 +00001875 // We have not yet looked into these namespaces, much less added
1876 // their "using-children" to the queue.
1877 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001878
1879 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001880 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001881 Visited.insert(StartDC);
1882
John McCall6538c932009-10-10 05:48:19 +00001883 // We have already looked into the initial namespace; seed the queue
1884 // with its using-children.
Richard Smithb920f852017-10-11 01:19:11 +00001885 for (auto *I : StartDC->using_directives()) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001886 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Richard Smitha544c512017-10-30 22:38:20 +00001887 if (S.isVisible(I) && Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001888 Queue.push_back(ND);
1889 }
1890
1891 // The easiest way to implement the restriction in [namespace.qual]p5
1892 // is to check whether any of the individual results found a tag
1893 // and, if so, to declare an ambiguity if the final result is not
1894 // a tag.
1895 bool FoundTag = false;
1896 bool FoundNonTag = false;
1897
John McCall5cebab12009-11-18 07:57:50 +00001898 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001899
1900 bool Found = false;
1901 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001902 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001903
1904 // We go through some convolutions here to avoid copying results
1905 // between LookupResults.
1906 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001907 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001908 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001909
1910 if (FoundDirect) {
1911 // First do any local hiding.
1912 DirectR.resolveKind();
1913
1914 // If the local result is a tag, remember that.
1915 if (DirectR.isSingleTagDecl())
1916 FoundTag = true;
1917 else
1918 FoundNonTag = true;
1919
1920 // Append the local results to the total results if necessary.
1921 if (UseLocal) {
1922 R.addAllDecls(LocalR);
1923 LocalR.clear();
1924 }
1925 }
1926
1927 // If we find names in this namespace, ignore its using directives.
1928 if (FoundDirect) {
1929 Found = true;
1930 continue;
1931 }
1932
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001933 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001934 NamespaceDecl *Nom = I->getNominatedNamespace();
Richard Smitha544c512017-10-30 22:38:20 +00001935 if (S.isVisible(I) && Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001936 Queue.push_back(Nom);
1937 }
1938 }
1939
1940 if (Found) {
1941 if (FoundTag && FoundNonTag)
1942 R.setAmbiguousQualifiedTagHiding();
1943 else
1944 R.resolveKind();
1945 }
1946
1947 return Found;
1948}
1949
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001950/// Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001952 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001953 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001955 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001956 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001957}
1958
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001959/// Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001960/// static members, nested types, and enumerators.
1961template<typename InputIterator>
1962static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1963 Decl *D = (*First)->getUnderlyingDecl();
1964 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1965 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966
Douglas Gregorc0d24902010-10-22 22:08:47 +00001967 if (isa<CXXMethodDecl>(D)) {
1968 // Determine whether all of the methods are static.
1969 bool AllMethodsAreStatic = true;
1970 for(; First != Last; ++First) {
1971 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972
Douglas Gregorc0d24902010-10-22 22:08:47 +00001973 if (!isa<CXXMethodDecl>(D)) {
1974 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1975 break;
1976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977
Douglas Gregorc0d24902010-10-22 22:08:47 +00001978 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1979 AllMethodsAreStatic = false;
1980 break;
1981 }
1982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001983
Douglas Gregorc0d24902010-10-22 22:08:47 +00001984 if (AllMethodsAreStatic)
1985 return true;
1986 }
1987
1988 return false;
1989}
1990
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001991/// Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001992///
1993/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1994/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001995/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001996///
1997/// Different lookup criteria can find different names. For example, a
1998/// particular scope can have both a struct and a function of the same
1999/// name, and each can be found by certain lookup criteria. For more
2000/// information about lookup criteria, see the documentation for the
2001/// class LookupCriteria.
2002///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002003/// \param R captures both the lookup criteria and any lookup results found.
2004///
2005/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00002006/// search. If the lookup criteria permits, name lookup may also search
2007/// in the parent contexts or (for C++ classes) base classes.
2008///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002010/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00002011///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002012/// \returns true if lookup succeeded, false if it failed.
2013bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2014 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00002015 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00002016
John McCall27b18f82009-11-17 02:14:36 +00002017 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00002018 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002019
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002020 // Make sure that the declaration context is complete.
2021 assert((!isa<TagDecl>(LookupCtx) ||
2022 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00002023 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00002024 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002025 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00002026
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002027 struct QualifiedLookupInScope {
2028 bool oldVal;
2029 DeclContext *Context;
2030 // Set flag in DeclContext informing debugger that we're looking for qualified name
Fangrui Song6907ce22018-07-30 19:24:48 +00002031 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2032 oldVal = ctx->setUseQualifiedLookup();
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002033 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002034 ~QualifiedLookupInScope() {
2035 Context->setUseQualifiedLookup(oldVal);
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002036 }
2037 } QL(LookupCtx);
2038
Douglas Gregord3a59182010-02-12 05:48:04 +00002039 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00002040 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00002041 if (isa<CXXRecordDecl>(LookupCtx))
2042 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00002043 return true;
2044 }
Douglas Gregor34074322009-01-14 22:20:51 +00002045
John McCall6538c932009-10-10 05:48:19 +00002046 // Don't descend into implied contexts for redeclarations.
2047 // C++98 [namespace.qual]p6:
2048 // In a declaration for a namespace member in which the
2049 // declarator-id is a qualified-id, given that the qualified-id
2050 // for the namespace member has the form
2051 // nested-name-specifier unqualified-id
2052 // the unqualified-id shall name a member of the namespace
2053 // designated by the nested-name-specifier.
2054 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00002055 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00002056 return false;
2057
John McCall27b18f82009-11-17 02:14:36 +00002058 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00002059 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00002060 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00002061
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002062 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00002063 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002064 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00002065 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00002066 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002067
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002068 // If we're performing qualified name lookup into a dependent class,
2069 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002070 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002071 // template instantiation time (at which point all bases will be available)
2072 // or we have to fail.
2073 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2074 LookupRec->hasAnyDependentBases()) {
2075 R.setNotFoundInCurrentInstantiation();
2076 return false;
2077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002079 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002080 CXXBasePaths Paths;
2081 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002082
2083 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002084 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2085 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00002086 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002087 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002088 case LookupOrdinaryName:
2089 case LookupMemberName:
2090 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00002091 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002092 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2093 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094
Douglas Gregor36d1b142009-10-06 17:59:45 +00002095 case LookupTagName:
2096 BaseCallback = &CXXRecordDecl::FindTagMember;
2097 break;
John McCall84d87672009-12-10 09:41:52 +00002098
Douglas Gregor39982192010-08-15 06:18:01 +00002099 case LookupAnyName:
2100 BaseCallback = &LookupAnyMember;
2101 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002102
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002103 case LookupOMPReductionName:
2104 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2105 break;
2106
John McCall84d87672009-12-10 09:41:52 +00002107 case LookupUsingDeclName:
2108 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
Douglas Gregor36d1b142009-10-06 17:59:45 +00002110 case LookupOperatorName:
2111 case LookupNamespaceName:
2112 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002113 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002114 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00002115 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002116
Douglas Gregor36d1b142009-10-06 17:59:45 +00002117 case LookupNestedNameSpecifierName:
2118 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2119 break;
2120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002122 DeclarationName Name = R.getLookupName();
2123 if (!LookupRec->lookupInBases(
2124 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2125 return BaseCallback(Specifier, Path, Name);
2126 },
2127 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00002128 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002129
John McCall553c0792010-01-23 00:46:32 +00002130 R.setNamingClass(LookupRec);
2131
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002132 // C++ [class.member.lookup]p2:
2133 // [...] If the resulting set of declarations are not all from
2134 // sub-objects of the same type, or the set has a nonstatic member
2135 // and includes members from distinct sub-objects, there is an
2136 // ambiguity and the program is ill-formed. Otherwise that set is
2137 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002138 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002139 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00002140 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141
Douglas Gregor36d1b142009-10-06 17:59:45 +00002142 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002143 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002144 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002145
John McCall401982f2010-01-20 21:53:11 +00002146 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2147 // across all paths.
2148 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002150 // Determine whether we're looking at a distinct sub-object or not.
2151 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00002152 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002153 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2154 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00002155 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156 }
2157
Douglas Gregorc0d24902010-10-22 22:08:47 +00002158 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002159 != Context.getCanonicalType(PathElement.Base->getType())) {
2160 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002161 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002162 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002163 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002164 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002165 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2166 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167
David Blaikieff7d47a2012-12-19 00:45:41 +00002168 while (FirstD != FirstPath->Decls.end() &&
2169 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002170 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2171 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2172 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173
Douglas Gregorc0d24902010-10-22 22:08:47 +00002174 ++FirstD;
2175 ++CurrentD;
2176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177
David Blaikieff7d47a2012-12-19 00:45:41 +00002178 if (FirstD == FirstPath->Decls.end() &&
2179 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002180 continue;
2181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
John McCall9f3059a2009-10-09 21:13:30 +00002183 R.setAmbiguousBaseSubobjectTypes(Paths);
2184 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002185 }
2186
Douglas Gregorc0d24902010-10-22 22:08:47 +00002187 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002188 // We have a different subobject of the same type.
2189
2190 // C++ [class.member.lookup]p5:
2191 // A static member, a nested type or an enumerator defined in
2192 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002193 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002194 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002195 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002197 // We have found a nonstatic member name in multiple, distinct
2198 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002199 R.setAmbiguousBaseSubobjects(Paths);
2200 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002201 }
2202 }
2203
2204 // Lookup in a base class succeeded; return these results.
2205
Aaron Ballman1e606f42014-07-15 22:03:49 +00002206 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002207 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2208 D->getAccess());
2209 R.addDecl(D, AS);
2210 }
John McCall9f3059a2009-10-09 21:13:30 +00002211 R.resolveKind();
2212 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002213}
2214
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002215/// Performs qualified name lookup or special type of lookup for
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002216/// "__super::" scope specifier.
2217///
2218/// This routine is a convenience overload meant to be called from contexts
2219/// that need to perform a qualified name lookup with an optional C++ scope
2220/// specifier that might require special kind of lookup.
2221///
2222/// \param R captures both the lookup criteria and any lookup results found.
2223///
2224/// \param LookupCtx The context in which qualified name lookup will
2225/// search.
2226///
2227/// \param SS An optional C++ scope-specifier.
2228///
2229/// \returns true if lookup succeeded, false if it failed.
2230bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2231 CXXScopeSpec &SS) {
2232 auto *NNS = SS.getScopeRep();
2233 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2234 return LookupInSuper(R, NNS->getAsRecordDecl());
2235 else
2236
2237 return LookupQualifiedName(R, LookupCtx);
2238}
2239
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002240/// Performs name lookup for a name that was parsed in the
Douglas Gregor34074322009-01-14 22:20:51 +00002241/// source code, and may contain a C++ scope specifier.
2242///
2243/// This routine is a convenience routine meant to be called from
2244/// contexts that receive a name and an optional C++ scope specifier
2245/// (e.g., "N::M::x"). It will then perform either qualified or
2246/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002247/// respectively) on the given name and return those results. It will
2248/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002249///
2250/// @param S The scope from which unqualified name lookup will
2251/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002252///
Douglas Gregore861bac2009-08-25 22:51:20 +00002253/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002254///
Douglas Gregore861bac2009-08-25 22:51:20 +00002255/// @param EnteringContext Indicates whether we are going to enter the
2256/// context of the scope-specifier SS (if present).
2257///
John McCall9f3059a2009-10-09 21:13:30 +00002258/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002259bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002260 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002261 if (SS && SS->isInvalid()) {
2262 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002263 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002264 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002265 }
Mike Stump11289f42009-09-09 15:08:12 +00002266
Douglas Gregore861bac2009-08-25 22:51:20 +00002267 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002268 NestedNameSpecifier *NNS = SS->getScopeRep();
2269 if (NNS->getKind() == NestedNameSpecifier::Super)
2270 return LookupInSuper(R, NNS->getAsRecordDecl());
2271
Douglas Gregore861bac2009-08-25 22:51:20 +00002272 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002273 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002274 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002275 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002276 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002277
John McCall27b18f82009-11-17 02:14:36 +00002278 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002279 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002280 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002281
Douglas Gregore861bac2009-08-25 22:51:20 +00002282 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002283 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002284 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002285 R.setNotFoundInCurrentInstantiation();
2286 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002287 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002288 }
2289
Mike Stump11289f42009-09-09 15:08:12 +00002290 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002291 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002292}
2293
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002294/// Perform qualified name lookup into all base classes of the given
Nikola Smiljanic67860242014-09-26 00:28:20 +00002295/// class.
2296///
2297/// \param R captures both the lookup criteria and any lookup results found.
2298///
2299/// \param Class The context in which qualified name lookup will
2300/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002301///
2302/// @returns True if any decls were found (but possibly ambiguous)
2303bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002304 // The access-control rules we use here are essentially the rules for
2305 // doing a lookup in Class that just magically skipped the direct
2306 // members of Class itself. That is, the naming class is Class, and the
2307 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002308 for (const auto &BaseSpec : Class->bases()) {
2309 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2310 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2311 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
Fangrui Song99337e22018-07-20 08:19:20 +00002312 Result.setBaseObjectType(Context.getRecordType(Class));
Nikola Smiljanic67860242014-09-26 00:28:20 +00002313 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002314
2315 // Copy the lookup results into the target, merging the base's access into
2316 // the path access.
2317 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2318 R.addDecl(I.getDecl(),
2319 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2320 I.getAccess()));
2321 }
2322
2323 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002324 }
2325
2326 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002327 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002328
2329 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002330}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002331
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002332/// Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002333/// from name lookup.
2334///
James Dennett41725122012-06-22 10:16:05 +00002335/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002336void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002337 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2338
John McCall27b18f82009-11-17 02:14:36 +00002339 DeclarationName Name = Result.getLookupName();
2340 SourceLocation NameLoc = Result.getNameLoc();
2341 SourceRange LookupRange = Result.getContextRange();
2342
John McCall6538c932009-10-10 05:48:19 +00002343 switch (Result.getAmbiguityKind()) {
2344 case LookupResult::AmbiguousBaseSubobjects: {
2345 CXXBasePaths *Paths = Result.getBasePaths();
2346 QualType SubobjectType = Paths->front().back().Base->getType();
2347 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2348 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2349 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002350
David Blaikieff7d47a2012-12-19 00:45:41 +00002351 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002352 while (isa<CXXMethodDecl>(*Found) &&
2353 cast<CXXMethodDecl>(*Found)->isStatic())
2354 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002355
John McCall6538c932009-10-10 05:48:19 +00002356 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002357 break;
John McCall6538c932009-10-10 05:48:19 +00002358 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002359
John McCall6538c932009-10-10 05:48:19 +00002360 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002361 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2362 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002363
John McCall6538c932009-10-10 05:48:19 +00002364 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002365 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002366 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2367 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002368 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002369 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002370 if (DeclsPrinted.insert(D).second)
2371 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2372 }
Serge Pavlov99292092013-08-29 07:23:24 +00002373 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002374 }
2375
John McCall6538c932009-10-10 05:48:19 +00002376 case LookupResult::AmbiguousTagHiding: {
2377 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002378
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002379 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002380
Aaron Ballman1e606f42014-07-15 22:03:49 +00002381 for (auto *D : Result)
2382 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002383 TagDecls.insert(TD);
2384 Diag(TD->getLocation(), diag::note_hidden_tag);
2385 }
2386
Aaron Ballman1e606f42014-07-15 22:03:49 +00002387 for (auto *D : Result)
2388 if (!isa<TagDecl>(D))
2389 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002390
2391 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002392 LookupResult::Filter F = Result.makeFilter();
2393 while (F.hasNext()) {
2394 if (TagDecls.count(F.next()))
2395 F.erase();
2396 }
2397 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002398 break;
John McCall6538c932009-10-10 05:48:19 +00002399 }
2400
2401 case LookupResult::AmbiguousReference: {
2402 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002403
Aaron Ballman1e606f42014-07-15 22:03:49 +00002404 for (auto *D : Result)
2405 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002406 break;
John McCall6538c932009-10-10 05:48:19 +00002407 }
Serge Pavlov99292092013-08-29 07:23:24 +00002408 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002409}
Douglas Gregore254f902009-02-04 00:32:51 +00002410
John McCallf24d7bb2010-05-28 18:45:08 +00002411namespace {
2412 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002413 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002414 Sema::AssociatedNamespaceSet &Namespaces,
2415 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002416 : S(S), Namespaces(Namespaces), Classes(Classes),
2417 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002418 }
2419
2420 Sema &S;
2421 Sema::AssociatedNamespaceSet &Namespaces;
2422 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002423 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002424 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002425} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002426
Mike Stump11289f42009-09-09 15:08:12 +00002427static void
John McCallf24d7bb2010-05-28 18:45:08 +00002428addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002429
Douglas Gregor8b895222010-04-30 07:08:38 +00002430static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2431 DeclContext *Ctx) {
2432 // Add the associated namespace for this class.
2433
2434 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2435 // be a locally scoped record.
2436
Sebastian Redlbd595762010-08-31 20:53:31 +00002437 // We skip out of inline namespaces. The innermost non-inline namespace
2438 // contains all names of all its nested inline namespaces anyway, so we can
2439 // replace the entire inline namespace tree with its root.
2440 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2441 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002442 Ctx = Ctx->getParent();
2443
John McCallc7e8e792009-08-07 22:18:02 +00002444 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002445 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002446}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002447
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002448// Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002449// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002450static void
John McCallf24d7bb2010-05-28 18:45:08 +00002451addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2452 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002453 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002454 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002455 switch (Arg.getKind()) {
2456 case TemplateArgument::Null:
2457 break;
Mike Stump11289f42009-09-09 15:08:12 +00002458
Douglas Gregor197e5f72009-07-08 07:51:57 +00002459 case TemplateArgument::Type:
2460 // [...] the namespaces and classes associated with the types of the
2461 // template arguments provided for template type parameters (excluding
2462 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002463 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002464 break;
Mike Stump11289f42009-09-09 15:08:12 +00002465
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002466 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002467 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002468 // [...] the namespaces in which any template template arguments are
2469 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002470 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002471 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002472 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002473 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002474 DeclContext *Ctx = ClassTemplate->getDeclContext();
2475 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002476 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002477 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002478 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002479 }
2480 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002482
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002483 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002484 case TemplateArgument::Integral:
2485 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002486 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002487 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002488 // associated namespaces. ]
2489 break;
Mike Stump11289f42009-09-09 15:08:12 +00002490
Douglas Gregor197e5f72009-07-08 07:51:57 +00002491 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002492 for (const auto &P : Arg.pack_elements())
2493 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002494 break;
2495 }
2496}
2497
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002498// Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002499// argument-dependent lookup with an argument of class type
2500// (C++ [basic.lookup.koenig]p2).
2501static void
John McCallf24d7bb2010-05-28 18:45:08 +00002502addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2503 CXXRecordDecl *Class) {
2504
2505 // Just silently ignore anything whose name is __va_list_tag.
2506 if (Class->getDeclName() == Result.S.VAListTagName)
2507 return;
2508
Douglas Gregore254f902009-02-04 00:32:51 +00002509 // C++ [basic.lookup.koenig]p2:
2510 // [...]
2511 // -- If T is a class type (including unions), its associated
2512 // classes are: the class itself; the class of which it is a
2513 // member, if any; and its direct and indirect base
2514 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002515 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002516
2517 // Add the class of which it is a member, if any.
2518 DeclContext *Ctx = Class->getDeclContext();
2519 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002520 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002521 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002522 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregore254f902009-02-04 00:32:51 +00002524 // Add the class itself. If we've already seen this class, we don't
2525 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002526 //
2527 // FIXME: That's not correct, we may have added this class only because it
2528 // was the enclosing class of another class, and in that case we won't have
2529 // added its base classes yet.
Richard Smith6642bb32016-03-24 19:12:22 +00002530 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002531 return;
2532
Mike Stump11289f42009-09-09 15:08:12 +00002533 // -- If T is a template-id, its associated namespaces and classes are
2534 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002535 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002536 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002537 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002538 // namespaces in which any template template arguments are defined; and
2539 // the classes in which any member templates used as template template
2540 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002541 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002542 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002543 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2544 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2545 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002546 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002547 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002548 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002549
Douglas Gregor197e5f72009-07-08 07:51:57 +00002550 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2551 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002552 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002553 }
Mike Stump11289f42009-09-09 15:08:12 +00002554
John McCall67da35c2010-02-04 22:26:26 +00002555 // Only recurse into base classes for complete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00002556 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2557 Result.S.Context.getRecordType(Class)))
Richard Smith594461f2014-03-14 22:07:27 +00002558 return;
John McCall67da35c2010-02-04 22:26:26 +00002559
Douglas Gregore254f902009-02-04 00:32:51 +00002560 // Add direct and indirect base classes along with their associated
2561 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002562 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002563 Bases.push_back(Class);
2564 while (!Bases.empty()) {
2565 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002566 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002567
2568 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002569 for (const auto &Base : Class->bases()) {
2570 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002571 // In dependent contexts, we do ADL twice, and the first time around,
2572 // the base type might be a dependent TemplateSpecializationType, or a
2573 // TemplateTypeParmType. If that happens, simply ignore it.
2574 // FIXME: If we want to support export, we probably need to add the
2575 // namespace of the template in a TemplateSpecializationType, or even
2576 // the classes and namespaces of known non-dependent arguments.
2577 if (!BaseType)
2578 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002579 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6642bb32016-03-24 19:12:22 +00002580 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002581 // Find the associated namespace for this base class.
2582 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002583 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002584
2585 // Make sure we visit the bases of this base class.
2586 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2587 Bases.push_back(BaseDecl);
2588 }
2589 }
2590 }
2591}
2592
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002593// Add the associated classes and namespaces for
Douglas Gregore254f902009-02-04 00:32:51 +00002594// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002595// (C++ [basic.lookup.koenig]p2).
2596static void
John McCallf24d7bb2010-05-28 18:45:08 +00002597addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002598 // C++ [basic.lookup.koenig]p2:
2599 //
2600 // For each argument type T in the function call, there is a set
2601 // of zero or more associated namespaces and a set of zero or more
2602 // associated classes to be considered. The sets of namespaces and
2603 // classes is determined entirely by the types of the function
2604 // arguments (and the namespace of any template template
2605 // argument). Typedef names and using-declarations used to specify
2606 // the types do not contribute to this set. The sets of namespaces
2607 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002608
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002609 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002610 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2611
Douglas Gregore254f902009-02-04 00:32:51 +00002612 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002613 switch (T->getTypeClass()) {
2614
2615#define TYPE(Class, Base)
2616#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2617#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2618#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2619#define ABSTRACT_TYPE(Class, Base)
2620#include "clang/AST/TypeNodes.def"
2621 // T is canonical. We can also ignore dependent types because
2622 // we don't need to do ADL at the definition point, but if we
2623 // wanted to implement template export (or if we find some other
2624 // use for associated classes and namespaces...) this would be
2625 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002626 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002627
John McCall0af3d3b2010-05-28 06:08:54 +00002628 // -- If T is a pointer to U or an array of U, its associated
2629 // namespaces and classes are those associated with U.
2630 case Type::Pointer:
2631 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2632 continue;
2633 case Type::ConstantArray:
2634 case Type::IncompleteArray:
2635 case Type::VariableArray:
2636 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2637 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002638
John McCall0af3d3b2010-05-28 06:08:54 +00002639 // -- If T is a fundamental type, its associated sets of
2640 // namespaces and classes are both empty.
2641 case Type::Builtin:
2642 break;
2643
2644 // -- If T is a class type (including unions), its associated
2645 // classes are: the class itself; the class of which it is a
2646 // member, if any; and its direct and indirect base
2647 // classes. Its associated namespaces are the namespaces in
2648 // which its associated classes are defined.
2649 case Type::Record: {
Richard Smith82b8d4e2015-12-18 22:19:11 +00002650 CXXRecordDecl *Class =
2651 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002652 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002653 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002654 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002655
John McCall0af3d3b2010-05-28 06:08:54 +00002656 // -- If T is an enumeration type, its associated namespace is
2657 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002658 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002659 // it has no associated class.
2660 case Type::Enum: {
2661 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002662
John McCall0af3d3b2010-05-28 06:08:54 +00002663 DeclContext *Ctx = Enum->getDeclContext();
2664 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002665 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002666
John McCall0af3d3b2010-05-28 06:08:54 +00002667 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002668 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002669
John McCall0af3d3b2010-05-28 06:08:54 +00002670 break;
2671 }
2672
2673 // -- If T is a function type, its associated namespaces and
2674 // classes are those associated with the function parameter
2675 // types and those associated with the return type.
2676 case Type::FunctionProto: {
2677 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002678 for (const auto &Arg : Proto->param_types())
2679 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002680 // fallthrough
Galina Kistanova33399112017-06-03 06:35:06 +00002681 LLVM_FALLTHROUGH;
John McCall0af3d3b2010-05-28 06:08:54 +00002682 }
2683 case Type::FunctionNoProto: {
2684 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002685 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002686 continue;
2687 }
2688
2689 // -- If T is a pointer to a member function of a class X, its
2690 // associated namespaces and classes are those associated
2691 // with the function parameter types and return type,
2692 // together with those associated with X.
2693 //
2694 // -- If T is a pointer to a data member of class X, its
2695 // associated namespaces and classes are those associated
2696 // with the member type together with those associated with
2697 // X.
2698 case Type::MemberPointer: {
2699 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2700
2701 // Queue up the class type into which this points.
2702 Queue.push_back(MemberPtr->getClass());
2703
2704 // And directly continue with the pointee type.
2705 T = MemberPtr->getPointeeType().getTypePtr();
2706 continue;
2707 }
2708
2709 // As an extension, treat this like a normal pointer.
2710 case Type::BlockPointer:
2711 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2712 continue;
2713
2714 // References aren't covered by the standard, but that's such an
2715 // obvious defect that we cover them anyway.
2716 case Type::LValueReference:
2717 case Type::RValueReference:
2718 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2719 continue;
2720
2721 // These are fundamental types.
2722 case Type::Vector:
2723 case Type::ExtVector:
2724 case Type::Complex:
2725 break;
2726
Richard Smith27d807c2013-04-30 13:56:41 +00002727 // Non-deduced auto types only get here for error cases.
2728 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002729 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00002730 break;
2731
Fangrui Song6907ce22018-07-30 19:24:48 +00002732 // If T is an Objective-C object or interface type, or a pointer to an
Douglas Gregor8e936662011-04-12 01:02:45 +00002733 // object or interface type, the associated namespace is the global
2734 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002735 case Type::ObjCObject:
2736 case Type::ObjCInterface:
2737 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002738 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002739 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002740
2741 // Atomic types are just wrappers; use the associations of the
2742 // contained type.
2743 case Type::Atomic:
2744 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2745 continue;
Xiuli Pan9c14e282016-01-09 12:53:17 +00002746 case Type::Pipe:
2747 T = cast<PipeType>(T)->getElementType().getTypePtr();
2748 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002749 }
2750
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002751 if (Queue.empty())
2752 break;
2753 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002754 }
Douglas Gregore254f902009-02-04 00:32:51 +00002755}
2756
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002757/// Find the associated classes and namespaces for
Douglas Gregore254f902009-02-04 00:32:51 +00002758/// argument-dependent lookup for a call with the given set of
2759/// arguments.
2760///
2761/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002762/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002763/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002764void Sema::FindAssociatedClassesAndNamespaces(
2765 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2766 AssociatedNamespaceSet &AssociatedNamespaces,
2767 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002768 AssociatedNamespaces.clear();
2769 AssociatedClasses.clear();
2770
John McCall7d8b0412012-08-24 20:38:34 +00002771 AssociatedLookup Result(*this, InstantiationLoc,
2772 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002773
Douglas Gregore254f902009-02-04 00:32:51 +00002774 // C++ [basic.lookup.koenig]p2:
2775 // For each argument type T in the function call, there is a set
2776 // of zero or more associated namespaces and a set of zero or more
2777 // associated classes to be considered. The sets of namespaces and
2778 // classes is determined entirely by the types of the function
2779 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002780 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002781 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002782 Expr *Arg = Args[ArgIdx];
2783
2784 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002785 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002786 continue;
2787 }
2788
2789 // [...] In addition, if the argument is the name or address of a
2790 // set of overloaded functions and/or function templates, its
2791 // associated classes and namespaces are the union of those
2792 // associated with each of the members of the set: the namespace
2793 // in which the function or function template is defined and the
2794 // classes and namespaces associated with its (non-dependent)
2795 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002796 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002797 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002798 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002799 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002800
John McCallf24d7bb2010-05-28 18:45:08 +00002801 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2802 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002803
Aaron Ballman1e606f42014-07-15 22:03:49 +00002804 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002805 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002806 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002807
2808 // Add the classes and namespaces associated with the parameter
2809 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002810 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002811 }
2812 }
2813}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002814
John McCall5cebab12009-11-18 07:57:50 +00002815NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002816 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002817 LookupNameKind NameKind,
2818 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002819 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002820 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002821 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002822}
2823
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002824/// Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002826 SourceLocation IdLoc,
2827 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002828 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002829 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002830 return cast_or_null<ObjCProtocolDecl>(D);
2831}
2832
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002833void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002834 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002835 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002836 // C++ [over.match.oper]p3:
2837 // -- The set of non-member candidates is the result of the
2838 // unqualified lookup of operator@ in the context of the
2839 // expression according to the usual rules for name lookup in
2840 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002841 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002842 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002843 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2844 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002845
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002846 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002847 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002848}
2849
Richard Smith8bae1be2017-02-24 02:07:20 +00002850Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
2851 CXXSpecialMember SM,
2852 bool ConstArg,
2853 bool VolatileArg,
2854 bool RValueThis,
2855 bool ConstThis,
2856 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002857 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002858 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002859 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002860 if (RValueThis || ConstThis || VolatileThis)
2861 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2862 "constructors and destructors always have unqualified lvalue this");
2863 if (ConstArg || VolatileArg)
2864 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2865 "parameter-less special members can't have qualified arguments");
2866
Richard Smith171e4b52017-02-15 04:18:23 +00002867 // FIXME: Get the caller to pass in a location for the lookup.
2868 SourceLocation LookupLoc = RD->getLocation();
2869
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002870 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002871 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002872 ID.AddInteger(SM);
2873 ID.AddInteger(ConstArg);
2874 ID.AddInteger(VolatileArg);
2875 ID.AddInteger(RValueThis);
2876 ID.AddInteger(ConstThis);
2877 ID.AddInteger(VolatileThis);
2878
2879 void *InsertPoint;
Richard Smith8bae1be2017-02-24 02:07:20 +00002880 SpecialMemberOverloadResultEntry *Result =
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002881 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2882
2883 // This was already cached
2884 if (Result)
Richard Smith8bae1be2017-02-24 02:07:20 +00002885 return *Result;
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002886
Richard Smith8bae1be2017-02-24 02:07:20 +00002887 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
2888 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002889 SpecialMemberCache.InsertNode(Result, InsertPoint);
2890
2891 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002892 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002893 DeclareImplicitDestructor(RD);
2894 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002895 assert(DD && "record without a destructor");
2896 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002897 Result->setKind(DD->isDeleted() ?
2898 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002899 SpecialMemberOverloadResult::Success);
Richard Smith8bae1be2017-02-24 02:07:20 +00002900 return *Result;
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002901 }
2902
Alexis Hunteef8ee02011-06-10 03:50:41 +00002903 // Prepare for overload resolution. Here we construct a synthetic argument
2904 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002905 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002906 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002907 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002908 unsigned NumArgs;
2909
Richard Smith83c478d2012-04-20 18:46:14 +00002910 QualType ArgType = CanTy;
2911 ExprValueKind VK = VK_LValue;
2912
Alexis Hunteef8ee02011-06-10 03:50:41 +00002913 if (SM == CXXDefaultConstructor) {
2914 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2915 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002916 if (RD->needsImplicitDefaultConstructor())
2917 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002918 } else {
2919 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2920 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002921 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002922 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002923 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002924 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002925 } else {
2926 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002927 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002928 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002929 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002930 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002931 }
2932
Alexis Hunteef8ee02011-06-10 03:50:41 +00002933 if (ConstArg)
2934 ArgType.addConst();
2935 if (VolatileArg)
2936 ArgType.addVolatile();
2937
2938 // This isn't /really/ specified by the standard, but it's implied
2939 // we should be working from an RValue in the case of move to ensure
2940 // that we prefer to bind to rvalue references, and an LValue in the
2941 // case of copy to ensure we don't bind to rvalue references.
2942 // Possibly an XValue is actually correct in the case of move, but
2943 // there is no semantic difference for class types in this restricted
2944 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002945 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002946 VK = VK_LValue;
2947 else
2948 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002949 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002950
Richard Smith171e4b52017-02-15 04:18:23 +00002951 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
Richard Smith83c478d2012-04-20 18:46:14 +00002952
2953 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002954 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002955 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002956 }
2957
2958 // Create the object argument
2959 QualType ThisTy = CanTy;
2960 if (ConstThis)
2961 ThisTy.addConst();
2962 if (VolatileThis)
2963 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002964 Expr::Classification Classification =
Richard Smith171e4b52017-02-15 04:18:23 +00002965 OpaqueValueExpr(LookupLoc, ThisTy,
Richard Smith83c478d2012-04-20 18:46:14 +00002966 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002967
2968 // Now we perform lookup on the name we computed earlier and do overload
2969 // resolution. Lookup is only performed directly into the class since there
2970 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith171e4b52017-02-15 04:18:23 +00002971 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002972 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002973
2974 if (R.empty()) {
2975 // We might have no default constructor because we have a lambda's closure
2976 // type, rather than because there's some other declared constructor.
2977 // Every class has a copy/move constructor, copy/move assignment, and
2978 // destructor.
2979 assert(SM == CXXDefaultConstructor &&
2980 "lookup for a constructor or assignment operator was empty");
2981 Result->setMethod(nullptr);
2982 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Richard Smith8bae1be2017-02-24 02:07:20 +00002983 return *Result;
Richard Smith8c37ab52015-02-11 01:48:47 +00002984 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002985
2986 // Copy the candidates as our processing of them may load new declarations
2987 // from an external source and invalidate lookup_result.
2988 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2989
Richard Smith5179eb72016-06-28 19:03:57 +00002990 for (NamedDecl *CandDecl : Candidates) {
2991 if (CandDecl->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002992 continue;
2993
Richard Smith5179eb72016-06-28 19:03:57 +00002994 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
2995 auto CtorInfo = getConstructorInfo(Cand);
2996 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002997 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Richard Smith5179eb72016-06-28 19:03:57 +00002998 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
2999 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3000 else if (CtorInfo)
3001 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003002 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00003003 else
Richard Smith5179eb72016-06-28 19:03:57 +00003004 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3005 true);
3006 } else if (FunctionTemplateDecl *Tmpl =
3007 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3008 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3009 AddMethodTemplateCandidate(
3010 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
George Burgess IVce6284b2017-01-28 02:19:40 +00003011 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Richard Smith5179eb72016-06-28 19:03:57 +00003012 else if (CtorInfo)
3013 AddTemplateOverloadCandidate(
3014 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3015 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3016 else
3017 AddTemplateOverloadCandidate(
3018 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00003019 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00003020 assert(isa<UsingDecl>(Cand.getDecl()) &&
3021 "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00003022 }
3023 }
3024
3025 OverloadCandidateSet::iterator Best;
Richard Smith171e4b52017-02-15 04:18:23 +00003026 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003027 case OR_Success:
3028 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00003029 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003030 break;
3031
3032 case OR_Deleted:
3033 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00003034 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003035 break;
3036
3037 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00003038 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003039 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3040 break;
3041
Alexis Hunteef8ee02011-06-10 03:50:41 +00003042 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00003043 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003044 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003045 break;
3046 }
3047
Richard Smith8bae1be2017-02-24 02:07:20 +00003048 return *Result;
Alexis Hunteef8ee02011-06-10 03:50:41 +00003049}
3050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003051/// Look up the default constructor for the given class.
Alexis Hunteef8ee02011-06-10 03:50:41 +00003052CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Richard Smith8bae1be2017-02-24 02:07:20 +00003053 SpecialMemberOverloadResult Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00003054 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3055 false, false);
3056
Richard Smith8bae1be2017-02-24 02:07:20 +00003057 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003058}
3059
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003060/// Look up the copying constructor for the given class.
Alexis Hunt491ec602011-06-21 23:42:56 +00003061CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00003062 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003063 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3064 "non-const, non-volatile qualifiers for copy ctor arg");
Richard Smith8bae1be2017-02-24 02:07:20 +00003065 SpecialMemberOverloadResult Result =
Alexis Hunt899bd442011-06-10 04:44:37 +00003066 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3067 Quals & Qualifiers::Volatile, false, false, false);
3068
Richard Smith8bae1be2017-02-24 02:07:20 +00003069 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Alexis Hunt899bd442011-06-10 04:44:37 +00003070}
3071
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003072/// Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00003073CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3074 unsigned Quals) {
Richard Smith8bae1be2017-02-24 02:07:20 +00003075 SpecialMemberOverloadResult Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003076 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3077 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003078
Richard Smith8bae1be2017-02-24 02:07:20 +00003079 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003080}
3081
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003082/// Look up the constructors for the given class.
Douglas Gregor52b72822010-07-02 23:12:18 +00003083DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003084 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00003085 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00003086 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003087 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00003088 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003089 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003090 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003091 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00003092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003093
Douglas Gregor52b72822010-07-02 23:12:18 +00003094 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3095 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3096 return Class->lookup(Name);
3097}
3098
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003099/// Look up the copying assignment operator for the given class.
Alexis Hunt491ec602011-06-21 23:42:56 +00003100CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3101 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00003102 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00003103 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3104 "non-const, non-volatile qualifiers for copy assignment arg");
3105 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3106 "non-const, non-volatile qualifiers for copy assignment this");
Richard Smith8bae1be2017-02-24 02:07:20 +00003107 SpecialMemberOverloadResult Result =
Alexis Hunt491ec602011-06-21 23:42:56 +00003108 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3109 Quals & Qualifiers::Volatile, RValueThis,
3110 ThisQuals & Qualifiers::Const,
3111 ThisQuals & Qualifiers::Volatile);
3112
Richard Smith8bae1be2017-02-24 02:07:20 +00003113 return Result.getMethod();
Alexis Hunt491ec602011-06-21 23:42:56 +00003114}
3115
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003116/// Look up the moving assignment operator for the given class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00003117CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00003118 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003119 bool RValueThis,
3120 unsigned ThisQuals) {
3121 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3122 "non-const, non-volatile qualifiers for copy assignment this");
Richard Smith8bae1be2017-02-24 02:07:20 +00003123 SpecialMemberOverloadResult Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003124 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3125 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003126 ThisQuals & Qualifiers::Const,
3127 ThisQuals & Qualifiers::Volatile);
3128
Richard Smith8bae1be2017-02-24 02:07:20 +00003129 return Result.getMethod();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003130}
3131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003132/// Look for the destructor of the given class.
Douglas Gregore71edda2010-07-01 22:47:18 +00003133///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00003134/// During semantic analysis, this routine should be used in lieu of
3135/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00003136///
3137/// \returns The destructor for this class.
3138CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003139 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3140 false, false, false,
Richard Smith8bae1be2017-02-24 02:07:20 +00003141 false, false).getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00003142}
3143
Richard Smithbcc22fc2012-03-09 08:00:36 +00003144/// LookupLiteralOperator - Determine which literal operator should be used for
3145/// a user-defined literal, per C++11 [lex.ext].
3146///
3147/// Normal overload resolution is not used to select which literal operator to
3148/// call for a user-defined literal. Look up the provided literal operator name,
3149/// and filter the results to the appropriate set for the given argument types.
3150Sema::LiteralOperatorLookupResult
3151Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3152 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00003153 bool AllowRaw, bool AllowTemplate,
Tim Northover97103382017-08-09 14:56:48 +00003154 bool AllowStringTemplate, bool DiagnoseMissing) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003155 LookupName(R, S);
3156 assert(R.getResultKind() != LookupResult::Ambiguous &&
3157 "literal operator lookup can't be ambiguous");
3158
3159 // Filter the lookup results appropriately.
3160 LookupResult::Filter F = R.makeFilter();
3161
Richard Smithbcc22fc2012-03-09 08:00:36 +00003162 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00003163 bool FoundTemplate = false;
3164 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003165 bool FoundExactMatch = false;
3166
3167 while (F.hasNext()) {
3168 Decl *D = F.next();
3169 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3170 D = USD->getTargetDecl();
3171
Douglas Gregorc1970572013-04-10 05:18:00 +00003172 // If the declaration we found is invalid, skip it.
3173 if (D->isInvalidDecl()) {
3174 F.erase();
3175 continue;
3176 }
3177
Richard Smithb8b41d32013-10-07 19:57:58 +00003178 bool IsRaw = false;
3179 bool IsTemplate = false;
3180 bool IsStringTemplate = false;
3181 bool IsExactMatch = false;
3182
Richard Smithbcc22fc2012-03-09 08:00:36 +00003183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3184 if (FD->getNumParams() == 1 &&
3185 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3186 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003187 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003188 IsExactMatch = true;
3189 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3190 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3191 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3192 IsExactMatch = false;
3193 break;
3194 }
3195 }
3196 }
3197 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003198 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3199 TemplateParameterList *Params = FD->getTemplateParameters();
3200 if (Params->size() == 1)
3201 IsTemplate = true;
3202 else
3203 IsStringTemplate = true;
3204 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003205
3206 if (IsExactMatch) {
3207 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003208 AllowRaw = false;
3209 AllowTemplate = false;
3210 AllowStringTemplate = false;
3211 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003212 // Go through again and remove the raw and template decls we've
3213 // already found.
3214 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003215 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003216 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003217 } else if (AllowRaw && IsRaw) {
3218 FoundRaw = true;
3219 } else if (AllowTemplate && IsTemplate) {
3220 FoundTemplate = true;
3221 } else if (AllowStringTemplate && IsStringTemplate) {
3222 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003223 } else {
3224 F.erase();
3225 }
3226 }
3227
3228 F.done();
3229
3230 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3231 // parameter type, that is used in preference to a raw literal operator
3232 // or literal operator template.
3233 if (FoundExactMatch)
3234 return LOLR_Cooked;
3235
3236 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3237 // operator template, but not both.
3238 if (FoundRaw && FoundTemplate) {
3239 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003240 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
Richard Smithc2bebe92016-05-11 20:37:46 +00003241 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003242 return LOLR_Error;
3243 }
3244
3245 if (FoundRaw)
3246 return LOLR_Raw;
3247
3248 if (FoundTemplate)
3249 return LOLR_Template;
3250
Richard Smithb8b41d32013-10-07 19:57:58 +00003251 if (FoundStringTemplate)
3252 return LOLR_StringTemplate;
3253
Richard Smithbcc22fc2012-03-09 08:00:36 +00003254 // Didn't find anything we could use.
Tim Northover97103382017-08-09 14:56:48 +00003255 if (DiagnoseMissing) {
3256 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3257 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3258 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3259 << (AllowTemplate || AllowStringTemplate);
3260 return LOLR_Error;
3261 }
3262
3263 return LOLR_ErrorNoDiagnostic;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003264}
3265
John McCall8fe68082010-01-26 07:16:45 +00003266void ADLResult::insert(NamedDecl *New) {
3267 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3268
3269 // If we haven't yet seen a decl for this key, or the last decl
3270 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003271 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003272 Old = New;
3273 return;
3274 }
3275
3276 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003277 FunctionDecl *OldFD = Old->getAsFunction();
3278 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003279
3280 FunctionDecl *Cursor = NewFD;
3281 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003282 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003283
3284 // If we got to the end without finding OldFD, OldFD is the newer
3285 // declaration; leave things as they are.
3286 if (!Cursor) return;
3287
3288 // If we do find OldFD, then NewFD is newer.
3289 if (Cursor == OldFD) break;
3290
3291 // Otherwise, keep looking.
3292 }
3293
3294 Old = New;
3295}
3296
Richard Smith100b24a2014-04-17 01:52:14 +00003297void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3298 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003299 // Find all of the associated namespaces and classes based on the
3300 // arguments we have.
3301 AssociatedNamespaceSet AssociatedNamespaces;
3302 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003303 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003304 AssociatedNamespaces,
3305 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003306
3307 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003308 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3309 // and let Y be the lookup set produced by argument dependent
3310 // lookup (defined as follows). If X contains [...] then Y is
3311 // empty. Otherwise Y is the set of declarations found in the
3312 // namespaces associated with the argument types as described
3313 // below. The set of declarations found by the lookup of the name
3314 // is the union of X and Y.
3315 //
3316 // Here, we compute Y and add its members to the overloaded
3317 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003318 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003319 // When considering an associated namespace, the lookup is the
3320 // same as the lookup performed when the associated namespace is
3321 // used as a qualifier (3.4.3.2) except that:
3322 //
3323 // -- Any using-directives in the associated namespace are
3324 // ignored.
3325 //
John McCallc7e8e792009-08-07 22:18:02 +00003326 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003327 // associated classes are visible within their respective
3328 // namespaces even if they are not visible during an ordinary
3329 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003330 DeclContext::lookup_result R = NS->lookup(Name);
3331 for (auto *D : R) {
Richard Smith041740f2018-01-06 00:09:23 +00003332 auto *Underlying = D;
3333 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3334 Underlying = USD->getTargetDecl();
3335
3336 if (!isa<FunctionDecl>(Underlying) &&
3337 !isa<FunctionTemplateDecl>(Underlying))
3338 continue;
3339
3340 if (!isVisible(D)) {
3341 D = findAcceptableDecl(
3342 *this, D, (Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend));
3343 if (!D)
3344 continue;
3345 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3346 Underlying = USD->getTargetDecl();
3347 }
3348
John McCallaa74a0c2009-08-28 07:59:38 +00003349 // If the only declaration here is an ordinary friend, consider
3350 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003351 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3352 // If it's neither ordinarily visible nor a friend, we can't find it.
3353 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3354 continue;
3355
Richard Smith64017682013-07-17 23:53:16 +00003356 bool DeclaredInAssociatedClass = false;
3357 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3358 DeclContext *LexDC = DI->getLexicalDeclContext();
3359 if (isa<CXXRecordDecl>(LexDC) &&
Richard Smith82b8d4e2015-12-18 22:19:11 +00003360 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) &&
3361 isVisible(cast<NamedDecl>(DI))) {
Richard Smith64017682013-07-17 23:53:16 +00003362 DeclaredInAssociatedClass = true;
3363 break;
3364 }
3365 }
3366 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003367 continue;
3368 }
Mike Stump11289f42009-09-09 15:08:12 +00003369
Richard Smith197f68d2017-10-11 01:49:57 +00003370 // FIXME: Preserve D as the FoundDecl.
3371 Result.insert(Underlying);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003372 }
3373 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003374}
Douglas Gregor2d435302009-12-30 17:04:44 +00003375
3376//----------------------------------------------------------------------------
3377// Search for all visible declarations.
3378//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003379VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003380
Richard Smithe156254d2013-08-20 20:35:18 +00003381bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3382
Douglas Gregor2d435302009-12-30 17:04:44 +00003383namespace {
3384
3385class ShadowContextRAII;
3386
3387class VisibleDeclsRecord {
3388public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003389 /// An entry in the shadow map, which is optimized to store a
Douglas Gregor2d435302009-12-30 17:04:44 +00003390 /// single declaration (the common case) but can also store a list
3391 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003392 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003393
3394private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003395 /// A mapping from declaration names to the declarations that have
Douglas Gregor2d435302009-12-30 17:04:44 +00003396 /// this name within a particular scope.
3397 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003399 /// A list of shadow maps, which is used to model name hiding.
Douglas Gregor2d435302009-12-30 17:04:44 +00003400 std::list<ShadowMap> ShadowMaps;
3401
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003402 /// The declaration contexts we have already visited.
Douglas Gregor2d435302009-12-30 17:04:44 +00003403 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3404
3405 friend class ShadowContextRAII;
3406
3407public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003408 /// Determine whether we have already visited this context
Douglas Gregor2d435302009-12-30 17:04:44 +00003409 /// (and, if not, note that we are going to visit that context now).
3410 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003411 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003412 }
3413
Douglas Gregor39982192010-08-15 06:18:01 +00003414 bool alreadyVisitedContext(DeclContext *Ctx) {
3415 return VisitedContexts.count(Ctx);
3416 }
3417
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003418 /// Determine whether the given declaration is hidden in the
Douglas Gregor2d435302009-12-30 17:04:44 +00003419 /// current scope.
3420 ///
3421 /// \returns the declaration that hides the given declaration, or
3422 /// NULL if no such declaration exists.
3423 NamedDecl *checkHidden(NamedDecl *ND);
3424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003425 /// Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003426 void add(NamedDecl *ND) {
3427 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3428 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003429};
3430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003431/// RAII object that records when we've entered a shadow context.
Douglas Gregor2d435302009-12-30 17:04:44 +00003432class ShadowContextRAII {
3433 VisibleDeclsRecord &Visible;
3434
3435 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3436
3437public:
3438 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003439 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003440 }
3441
3442 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003443 Visible.ShadowMaps.pop_back();
3444 }
3445};
3446
3447} // end anonymous namespace
3448
Douglas Gregor2d435302009-12-30 17:04:44 +00003449NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3450 unsigned IDNS = ND->getIdentifierNamespace();
3451 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3452 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3453 SM != SMEnd; ++SM) {
3454 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3455 if (Pos == SM->end())
3456 continue;
3457
Aaron Ballman1e606f42014-07-15 22:03:49 +00003458 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003459 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003460 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003462 Decl::IDNS_ObjCProtocol)))
3463 continue;
3464
3465 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003466 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003467 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003468 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003469 continue;
3470
Douglas Gregor09bbc652010-01-14 15:47:35 +00003471 // Functions and function templates in the same scope overload
3472 // rather than hide. FIXME: Look for hiding based on function
3473 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003474 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003475 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003476 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003477 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478
Alex Lorenze7e8f802017-01-23 17:23:23 +00003479 // A shadow declaration that's created by a resolved using declaration
3480 // is not hidden by the same using declaration.
3481 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3482 cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3483 continue;
3484
Douglas Gregor2d435302009-12-30 17:04:44 +00003485 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003486 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003487 }
3488 }
3489
Craig Topperc3ec1492014-05-26 06:22:03 +00003490 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003491}
3492
3493static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3494 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003495 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003496 VisibleDeclConsumer &Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003497 VisibleDeclsRecord &Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003498 bool IncludeDependentBases,
3499 bool LoadExternal) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003500 if (!Ctx)
3501 return;
3502
Douglas Gregor2d435302009-12-30 17:04:44 +00003503 // Make sure we don't visit the same context twice.
3504 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3505 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Haojian Wu10d95c52018-01-17 14:29:25 +00003507 Consumer.EnteredContext(Ctx);
3508
Richard Smith9e2341d2015-03-23 03:25:59 +00003509 // Outside C++, lookup results for the TU live on identifiers.
3510 if (isa<TranslationUnitDecl>(Ctx) &&
3511 !Result.getSema().getLangOpts().CPlusPlus) {
3512 auto &S = Result.getSema();
3513 auto &Idents = S.Context.Idents;
3514
3515 // Ensure all external identifiers are in the identifier table.
Sam McCallbb2cf632018-01-12 14:51:47 +00003516 if (LoadExternal)
3517 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3518 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3519 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3520 Idents.get(Name);
3521 }
Richard Smith9e2341d2015-03-23 03:25:59 +00003522
3523 // Walk all lookup results in the TU for each identifier.
3524 for (const auto &Ident : Idents) {
3525 for (auto I = S.IdResolver.begin(Ident.getValue()),
3526 E = S.IdResolver.end();
3527 I != E; ++I) {
3528 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3529 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3530 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3531 Visited.add(ND);
3532 }
3533 }
3534 }
3535 }
3536
3537 return;
3538 }
3539
Douglas Gregor7454c562010-07-02 20:37:36 +00003540 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3541 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3542
Sam McCallabdcc612018-01-24 17:50:20 +00003543 // We sometimes skip loading namespace-level results (they tend to be huge).
3544 bool Load = LoadExternal ||
3545 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
Douglas Gregor2d435302009-12-30 17:04:44 +00003546 // Enumerate all of the results in this context.
Sam McCallbb2cf632018-01-12 14:51:47 +00003547 for (DeclContextLookupResult R :
Sam McCallabdcc612018-01-24 17:50:20 +00003548 Load ? Ctx->lookups()
3549 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003550 for (auto *D : R) {
3551 if (auto *ND = Result.getAcceptableDecl(D)) {
3552 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3553 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003554 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003555 }
3556 }
3557
3558 // Traverse using directives for qualified name lookup.
3559 if (QualifiedNameLookup) {
3560 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003561 for (auto I : Ctx->using_directives()) {
Richard Smithb920f852017-10-11 01:19:11 +00003562 if (!Result.getSema().isVisible(I))
3563 continue;
Aaron Ballman63ab7602014-03-07 13:44:44 +00003564 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Alex Lorenze6afa392017-05-11 13:48:57 +00003565 QualifiedNameLookup, InBaseClass, Consumer, Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003566 IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003567 }
3568 }
3569
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003570 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003571 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003572 if (!Record->hasDefinition())
3573 return;
3574
Aaron Ballman574705e2014-03-13 15:41:46 +00003575 for (const auto &B : Record->bases()) {
3576 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577
Alex Lorenze6afa392017-05-11 13:48:57 +00003578 RecordDecl *RD;
3579 if (BaseType->isDependentType()) {
3580 if (!IncludeDependentBases) {
3581 // Don't look into dependent bases, because name lookup can't look
3582 // there anyway.
3583 continue;
3584 }
3585 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3586 if (!TST)
3587 continue;
3588 TemplateName TN = TST->getTemplateName();
3589 const auto *TD =
3590 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3591 if (!TD)
3592 continue;
3593 RD = TD->getTemplatedDecl();
3594 } else {
3595 const auto *Record = BaseType->getAs<RecordType>();
3596 if (!Record)
3597 continue;
3598 RD = Record->getDecl();
3599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregor2d435302009-12-30 17:04:44 +00003601 // FIXME: It would be nice to be able to determine whether referencing
3602 // a particular member would be ambiguous. For example, given
3603 //
3604 // struct A { int member; };
3605 // struct B { int member; };
3606 // struct C : A, B { };
3607 //
3608 // void f(C *c) { c->### }
3609 //
3610 // accessing 'member' would result in an ambiguity. However, we
3611 // could be smart enough to qualify the member with the base
3612 // class, e.g.,
3613 //
3614 // c->B::member
3615 //
3616 // or
3617 //
3618 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619
Douglas Gregor2d435302009-12-30 17:04:44 +00003620 // Find results in this base class (and its bases).
3621 ShadowContextRAII Shadow(Visited);
Alex Lorenze6afa392017-05-11 13:48:57 +00003622 LookupVisibleDecls(RD, Result, QualifiedNameLookup, true, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003623 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003624 }
3625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003627 // Traverse the contexts of Objective-C classes.
3628 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3629 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003630 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003631 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003632 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, Consumer,
3633 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003634 }
3635
3636 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003637 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003638 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003639 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003640 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003641 }
3642
3643 // Traverse the superclass.
3644 if (IFace->getSuperClass()) {
3645 ShadowContextRAII Shadow(Visited);
3646 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Sam McCallbb2cf632018-01-12 14:51:47 +00003647 true, Consumer, Visited, IncludeDependentBases,
3648 LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003650
Douglas Gregor0b59e802010-04-19 18:02:19 +00003651 // If there is an implementation, traverse it. We do this to find
3652 // synthesized ivars.
3653 if (IFace->getImplementation()) {
3654 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655 LookupVisibleDecls(IFace->getImplementation(), Result,
Sam McCallbb2cf632018-01-12 14:51:47 +00003656 QualifiedNameLookup, InBaseClass, Consumer, Visited,
3657 IncludeDependentBases, LoadExternal);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003658 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003659 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003660 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003661 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003662 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003663 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003664 }
3665 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003666 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003667 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003668 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003669 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregor0b59e802010-04-19 18:02:19 +00003672 // If there is an implementation, traverse it.
3673 if (Category->getImplementation()) {
3674 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675 LookupVisibleDecls(Category->getImplementation(), Result,
Sam McCallbb2cf632018-01-12 14:51:47 +00003676 QualifiedNameLookup, true, Consumer, Visited,
3677 IncludeDependentBases, LoadExternal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003679 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003680}
3681
3682static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3683 UnqualUsingDirectiveSet &UDirs,
3684 VisibleDeclConsumer &Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003685 VisibleDeclsRecord &Visited,
3686 bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003687 if (!S)
3688 return;
3689
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003690 if (!S->getEntity() ||
3691 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003692 !Visited.alreadyVisitedContext(S->getEntity())) ||
3693 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003694 FindLocalExternScope FindLocals(Result);
Benjamin Kramer17ba6692017-10-13 22:14:34 +00003695 // Walk through the declarations in this Scope. The consumer might add new
3696 // decls to the scope as part of deserialization, so make a copy first.
3697 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
3698 for (Decl *D : ScopeDecls) {
Aaron Ballman35c54952014-03-17 16:55:25 +00003699 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003700 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003701 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003702 Visited.add(ND);
3703 }
3704 }
3705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706
Douglas Gregor66230062010-03-15 14:33:29 +00003707 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003708 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003709 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003710 // Look into this scope's declaration context, along with any of its
3711 // parent lookup contexts (e.g., enclosing classes), up to the point
3712 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003713 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003714 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715
Douglas Gregorea166062010-03-15 15:26:48 +00003716 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003717 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003718 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3719 if (Method->isInstanceMethod()) {
3720 // For instance methods, look for ivars in the method's interface.
3721 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3722 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003723 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003725 /*InBaseClass=*/false, Consumer, Visited,
3726 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003727 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003728 }
3729
3730 // We've already performed all of the name lookup that we need
3731 // to for Objective-C methods; the next context will be the
3732 // outer scope.
3733 break;
3734 }
3735
Douglas Gregor2d435302009-12-30 17:04:44 +00003736 if (Ctx->isFunctionOrMethod())
3737 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738
3739 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003740 /*InBaseClass=*/false, Consumer, Visited,
3741 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003742 }
3743 } else if (!S->getParent()) {
3744 // Look into the translation unit scope. We walk through the translation
3745 // unit's declaration context, because the Scope itself won't have all of
3746 // the declarations if we loaded a precompiled header.
3747 // FIXME: We would like the translation unit's Scope object to point to the
3748 // translation unit, so we don't need this special "if" branch. However,
3749 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003751 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003752 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003753 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003755 /*InBaseClass=*/false, Consumer, Visited,
3756 /*IncludeDependentBases=*/false, LoadExternal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 }
3758
Douglas Gregor2d435302009-12-30 17:04:44 +00003759 if (Entity) {
3760 // Lookup visible declarations in any namespaces found by using
3761 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003762 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3763 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764 Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003765 /*InBaseClass=*/false, Consumer, Visited,
3766 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003767 }
3768
3769 // Lookup names in the parent scope.
3770 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003771 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited,
3772 LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003773}
3774
3775void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003776 VisibleDeclConsumer &Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003777 bool IncludeGlobalScope, bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003778 // Determine the set of using directives available during
3779 // unqualified name lookup.
3780 Scope *Initial = S;
Richard Smithb920f852017-10-11 01:19:11 +00003781 UnqualUsingDirectiveSet UDirs(*this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003782 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003783 // Find the first namespace or translation-unit scope.
3784 while (S && !isNamespaceOrTranslationUnitScope(S))
3785 S = S->getParent();
3786
3787 UDirs.visitScopeChain(Initial, S);
3788 }
3789 UDirs.done();
3790
3791 // Look for visible declarations.
3792 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003793 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003794 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003795 if (!IncludeGlobalScope)
3796 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003797 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003798 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003799}
3800
3801void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003802 VisibleDeclConsumer &Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003803 bool IncludeGlobalScope,
Sam McCallbb2cf632018-01-12 14:51:47 +00003804 bool IncludeDependentBases, bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003805 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003806 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003807 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003808 if (!IncludeGlobalScope)
3809 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003810 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003811 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Alex Lorenze6afa392017-05-11 13:48:57 +00003812 /*InBaseClass=*/false, Consumer, Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003813 IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003814}
3815
Chris Lattner43e7f312011-02-18 02:08:43 +00003816/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003817/// If GnuLabelLoc is a valid source location, then this is a definition
3818/// of an __label__ label name, otherwise it is a normal label definition
3819/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003820LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003821 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003822 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003823 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003824
3825 if (GnuLabelLoc.isValid()) {
3826 // Local label definitions always shadow existing labels.
3827 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3828 Scope *S = CurScope;
3829 PushOnScopeChains(Res, S, true);
3830 return cast<LabelDecl>(Res);
3831 }
3832
3833 // Not a GNU local label.
3834 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3835 // If we found a label, check to see if it is in the same context as us.
3836 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003837 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003838 Res = nullptr;
3839 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003840 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003841 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3842 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003843 assert(S && "Not in a function?");
3844 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003845 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003846 return cast<LabelDecl>(Res);
3847}
3848
3849//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003850// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003851//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003852
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003853static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3854 TypoCorrection &Candidate) {
3855 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3856 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3857}
3858
3859static void LookupPotentialTypoResult(Sema &SemaRef,
3860 LookupResult &Res,
3861 IdentifierInfo *Name,
3862 Scope *S, CXXScopeSpec *SS,
3863 DeclContext *MemberContext,
3864 bool EnteringContext,
3865 bool isObjCIvarLookup,
3866 bool FindHidden);
3867
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003868/// Check whether the declarations found for a typo correction are
Richard Smith3092d722017-06-05 22:29:36 +00003869/// visible. Set the correction's RequiresImport flag to true if none of the
3870/// declarations are visible, false otherwise.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003871static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003872 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3873
3874 for (/**/; DI != DE; ++DI)
3875 if (!LookupResult::isVisible(SemaRef, *DI))
3876 break;
Richard Smith3092d722017-06-05 22:29:36 +00003877 // No filtering needed if all decls are visible.
3878 if (DI == DE) {
3879 TC.setRequiresImport(false);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003880 return;
Richard Smith3092d722017-06-05 22:29:36 +00003881 }
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003882
3883 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3884 bool AnyVisibleDecls = !NewDecls.empty();
3885
3886 for (/**/; DI != DE; ++DI) {
Richard Smith041740f2018-01-06 00:09:23 +00003887 if (LookupResult::isVisible(SemaRef, *DI)) {
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003888 if (!AnyVisibleDecls) {
3889 // Found a visible decl, discard all hidden ones.
3890 AnyVisibleDecls = true;
3891 NewDecls.clear();
3892 }
Richard Smith041740f2018-01-06 00:09:23 +00003893 NewDecls.push_back(*DI);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003894 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3895 NewDecls.push_back(*DI);
3896 }
3897
3898 if (NewDecls.empty())
3899 TC = TypoCorrection();
3900 else {
3901 TC.setCorrectionDecls(NewDecls);
3902 TC.setRequiresImport(!AnyVisibleDecls);
3903 }
3904}
3905
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003906// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3907// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3908// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3909static void getNestedNameSpecifierIdentifiers(
3910 NestedNameSpecifier *NNS,
3911 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3912 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3913 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3914 else
3915 Identifiers.clear();
3916
3917 const IdentifierInfo *II = nullptr;
3918
3919 switch (NNS->getKind()) {
3920 case NestedNameSpecifier::Identifier:
3921 II = NNS->getAsIdentifier();
3922 break;
3923
3924 case NestedNameSpecifier::Namespace:
3925 if (NNS->getAsNamespace()->isAnonymousNamespace())
3926 return;
3927 II = NNS->getAsNamespace()->getIdentifier();
3928 break;
3929
3930 case NestedNameSpecifier::NamespaceAlias:
3931 II = NNS->getAsNamespaceAlias()->getIdentifier();
3932 break;
3933
3934 case NestedNameSpecifier::TypeSpecWithTemplate:
3935 case NestedNameSpecifier::TypeSpec:
3936 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3937 break;
3938
3939 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003940 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003941 return;
3942 }
3943
3944 if (II)
3945 Identifiers.push_back(II);
3946}
3947
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003949 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003950 // Don't consider hidden names for typo correction.
3951 if (Hiding)
3952 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953
Douglas Gregor2d435302009-12-30 17:04:44 +00003954 // Only consider entities with identifiers for names, ignoring
3955 // special names (constructors, overloaded operators, selectors,
3956 // etc.).
3957 IdentifierInfo *Name = ND->getIdentifier();
3958 if (!Name)
3959 return;
3960
Richard Smithe156254d2013-08-20 20:35:18 +00003961 // Only consider visible declarations and declarations from modules with
3962 // names that exactly match.
Richard Smith041740f2018-01-06 00:09:23 +00003963 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
Richard Smithe156254d2013-08-20 20:35:18 +00003964 return;
3965
Douglas Gregor57756ea2010-10-14 22:11:03 +00003966 FoundName(Name->getName());
3967}
3968
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003969void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003970 // Compute the edit distance between the typo and the name of this
3971 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003972 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003973}
3974
3975void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3976 // Compute the edit distance between the typo and this keyword,
3977 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003978 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003979}
3980
3981void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3982 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003983 // Use a simple length-based heuristic to determine the minimum possible
3984 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003985 StringRef TypoStr = Typo->getName();
3986 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3987 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003988 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003990 // Compute an upper bound on the allowable edit distance, so that the
3991 // edit-distance algorithm can short-circuit.
Fangrui Songaadc93c2018-09-09 17:20:03 +00003992 unsigned UpperBound = (TypoStr.size() + 2) / 3;
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003993 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Fangrui Songaadc93c2018-09-09 17:20:03 +00003994 if (ED > UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003995
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003996 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003997 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003998 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003999 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004000}
4001
Kaelyn Takatad2287c32014-10-27 18:07:13 +00004002static const unsigned MaxTypoDistanceResultSets = 5;
4003
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004004void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004005 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004006 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004007
4008 // For very short typos, ignore potential corrections that have a different
4009 // base identifier from the typo or which have a normalized edit distance
4010 // longer than the typo itself.
4011 if (TypoStr.size() < 3 &&
4012 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4013 return;
4014
4015 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004016 if (Correction.isResolved()) {
4017 checkCorrectionVisibility(SemaRef, Correction);
4018 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4019 return;
4020 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004021
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004022 TypoResultList &CList =
4023 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00004024
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004025 if (!CList.empty() && !CList.back().isResolved())
4026 CList.pop_back();
4027 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4028 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
4029 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
4030 RI != RIEnd; ++RI) {
4031 // If the Correction refers to a decl already in the result list,
4032 // replace the existing result if the string representation of Correction
4033 // comes before the current result alphabetically, then stop as there is
4034 // nothing more to be done to add Correction to the candidate set.
4035 if (RI->getCorrectionDecl() == NewND) {
4036 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
4037 *RI = Correction;
4038 return;
4039 }
4040 }
4041 }
4042 if (CList.empty() || Correction.isResolved())
4043 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004044
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004045 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004046 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4047}
4048
4049void TypoCorrectionConsumer::addNamespaces(
4050 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4051 SearchNamespaces = true;
4052
4053 for (auto KNPair : KnownNamespaces)
4054 Namespaces.addNameSpecifier(KNPair.first);
4055
4056 bool SSIsTemplate = false;
4057 if (NestedNameSpecifier *NNS =
4058 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4059 if (const Type *T = NNS->getAsType())
4060 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4061 }
Richard Smith2a40fb72015-11-18 01:19:02 +00004062 // Do not transform this into an iterator-based loop. The loop body can
4063 // trigger the creation of further types (through lazy deserialization) and
4064 // invalide iterators into this list.
4065 auto &Types = SemaRef.getASTContext().getTypes();
4066 for (unsigned I = 0; I != Types.size(); ++I) {
4067 const auto *TI = Types[I];
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004068 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4069 CD = CD->getCanonicalDecl();
4070 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4071 !CD->isUnion() && CD->getIdentifier() &&
4072 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4073 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4074 Namespaces.addNameSpecifier(CD);
4075 }
4076 }
4077}
4078
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004079const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4080 if (++CurrentTCIndex < ValidatedCorrections.size())
4081 return ValidatedCorrections[CurrentTCIndex];
4082
4083 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004084 while (!CorrectionResults.empty()) {
4085 auto DI = CorrectionResults.begin();
4086 if (DI->second.empty()) {
4087 CorrectionResults.erase(DI);
4088 continue;
4089 }
4090
4091 auto RI = DI->second.begin();
4092 if (RI->second.empty()) {
4093 DI->second.erase(RI);
4094 performQualifiedLookups();
4095 continue;
4096 }
4097
4098 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004099 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004100 ValidatedCorrections.push_back(TC);
4101 return ValidatedCorrections[CurrentTCIndex];
4102 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004103 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004104 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004105}
4106
4107bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4108 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4109 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004110 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004111retry_lookup:
4112 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4113 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004114 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004115 Name == Typo && !Candidate.WillReplaceSpecifier());
4116 switch (Result.getResultKind()) {
4117 case LookupResult::NotFound:
4118 case LookupResult::NotFoundInCurrentInstantiation:
4119 case LookupResult::FoundUnresolvedValue:
4120 if (TempSS) {
4121 // Immediately retry the lookup without the given CXXScopeSpec
4122 TempSS = nullptr;
4123 Candidate.WillReplaceSpecifier(true);
4124 goto retry_lookup;
4125 }
4126 if (TempMemberContext) {
4127 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004128 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004129 TempMemberContext = nullptr;
4130 goto retry_lookup;
4131 }
4132 if (SearchNamespaces)
4133 QualifiedResults.push_back(Candidate);
4134 break;
4135
4136 case LookupResult::Ambiguous:
4137 // We don't deal with ambiguities.
4138 break;
4139
4140 case LookupResult::Found:
4141 case LookupResult::FoundOverloaded:
4142 // Store all of the Decls for overloaded symbols
4143 for (auto *TRD : Result)
4144 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004145 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004146 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004147 if (SearchNamespaces)
4148 QualifiedResults.push_back(Candidate);
4149 break;
4150 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00004151 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004152 return true;
4153 }
4154 return false;
4155}
4156
4157void TypoCorrectionConsumer::performQualifiedLookups() {
4158 unsigned TypoLen = Typo->getName().size();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00004159 for (const TypoCorrection &QR : QualifiedResults) {
4160 for (const auto &NSI : Namespaces) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004161 DeclContext *Ctx = NSI.DeclCtx;
4162 const Type *NSType = NSI.NameSpecifier->getAsType();
4163
4164 // If the current NestedNameSpecifier refers to a class and the
4165 // current correction candidate is the name of that class, then skip
4166 // it as it is unlikely a qualified version of the class' constructor
4167 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00004168 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4169 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004170 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4171 continue;
4172 }
4173
4174 TypoCorrection TC(QR);
4175 TC.ClearCorrectionDecls();
4176 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4177 TC.setQualifierDistance(NSI.EditDistance);
4178 TC.setCallbackDistance(0); // Reset the callback distance
4179
4180 // If the current correction candidate and namespace combination are
4181 // too far away from the original typo based on the normalized edit
4182 // distance, then skip performing a qualified name lookup.
4183 unsigned TmpED = TC.getEditDistance(true);
4184 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4185 TypoLen / TmpED < 3)
4186 continue;
4187
4188 Result.clear();
4189 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4190 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4191 continue;
4192
4193 // Any corrections added below will be validated in subsequent
4194 // iterations of the main while() loop over the Consumer's contents.
4195 switch (Result.getResultKind()) {
4196 case LookupResult::Found:
4197 case LookupResult::FoundOverloaded: {
4198 if (SS && SS->isValid()) {
4199 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4200 std::string OldQualified;
4201 llvm::raw_string_ostream OldOStream(OldQualified);
4202 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4203 OldOStream << Typo->getName();
4204 // If correction candidate would be an identical written qualified
4205 // identifer, then the existing CXXScopeSpec probably included a
4206 // typedef that didn't get accounted for properly.
4207 if (OldOStream.str() == NewQualified)
4208 break;
4209 }
4210 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4211 TRD != TRDEnd; ++TRD) {
4212 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4213 NSType ? NSType->getAsCXXRecordDecl()
4214 : nullptr,
4215 TRD.getPair()) == Sema::AR_accessible)
4216 TC.addCorrectionDecl(*TRD);
4217 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004218 if (TC.isResolved()) {
4219 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004220 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004221 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004222 break;
4223 }
4224 case LookupResult::NotFound:
4225 case LookupResult::NotFoundInCurrentInstantiation:
4226 case LookupResult::Ambiguous:
4227 case LookupResult::FoundUnresolvedValue:
4228 break;
4229 }
4230 }
4231 }
4232 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004233}
4234
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004235TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4236 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004237 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004238 if (NestedNameSpecifier *NNS =
4239 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4240 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4241 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4242
4243 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4244 }
4245 // Build the list of identifiers that would be used for an absolute
4246 // (from the global context) NestedNameSpecifier referring to the current
4247 // context.
David Majnemerf7e36092016-06-23 00:15:04 +00004248 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4249 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004250 CurContextIdentifiers.push_back(ND->getIdentifier());
4251 }
4252
4253 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004254 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4255 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4256 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004257}
4258
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004259auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4260 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004261 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004262 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004263 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004264 DC = DC->getLookupParent()) {
4265 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4266 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4267 !(ND && ND->isAnonymousNamespace()))
4268 Chain.push_back(DC->getPrimaryContext());
4269 }
4270 return Chain;
4271}
4272
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004273unsigned
4274TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4275 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004276 unsigned NumSpecifiers = 0;
David Majnemerf7e36092016-06-23 00:15:04 +00004277 for (DeclContext *C : llvm::reverse(DeclChain)) {
4278 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004279 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4280 ++NumSpecifiers;
David Majnemerf7e36092016-06-23 00:15:04 +00004281 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004282 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4283 RD->getTypeForDecl());
4284 ++NumSpecifiers;
4285 }
4286 }
4287 return NumSpecifiers;
4288}
4289
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004290void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4291 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004292 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004293 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004294 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004295 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4296
4297 // Eliminate common elements from the two DeclContext chains.
David Majnemerf7e36092016-06-23 00:15:04 +00004298 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4299 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4300 break;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004301 NamespaceDeclChain.pop_back();
4302 }
4303
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004304 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004305 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004306
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004307 // Add an explicit leading '::' specifier if needed.
4308 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004309 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004310 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004311 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004312 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004313 } else if (NamedDecl *ND =
4314 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004315 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004316 bool SameNameSpecifier = false;
4317 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004318 CurNameSpecifierIdentifiers.end(),
4319 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004320 std::string NewNameSpecifier;
4321 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4322 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4323 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4324 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4325 SpecifierOStream.flush();
4326 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004327 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004328 if (SameNameSpecifier ||
4329 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4330 Name) != CurContextIdentifiers.end()) {
4331 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4332 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4333 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004334 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004335 }
4336 }
4337
4338 // If the built NestedNameSpecifier would be replacing an existing
4339 // NestedNameSpecifier, use the number of component identifiers that
4340 // would need to be changed as the edit distance instead of the number
4341 // of components in the built NestedNameSpecifier.
4342 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4343 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4344 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4345 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004346 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4347 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004348 }
4349
Hans Wennborg66010132014-06-11 21:24:13 +00004350 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4351 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004352}
4353
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004354/// Perform name lookup for a possible result for typo correction.
Douglas Gregord507d772010-10-20 03:06:34 +00004355static void LookupPotentialTypoResult(Sema &SemaRef,
4356 LookupResult &Res,
4357 IdentifierInfo *Name,
4358 Scope *S, CXXScopeSpec *SS,
4359 DeclContext *MemberContext,
4360 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004361 bool isObjCIvarLookup,
4362 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004363 Res.suppressDiagnostics();
4364 Res.clear();
4365 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004366 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004368 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004369 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004370 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4371 Res.addDecl(Ivar);
4372 Res.resolveKind();
4373 return;
4374 }
4375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004376
Manman Ren5b786402016-01-28 18:49:28 +00004377 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4378 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregord507d772010-10-20 03:06:34 +00004379 Res.addDecl(Prop);
4380 Res.resolveKind();
4381 return;
4382 }
4383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384
Douglas Gregord507d772010-10-20 03:06:34 +00004385 SemaRef.LookupQualifiedName(Res, MemberContext);
4386 return;
4387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388
4389 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004390 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391
Douglas Gregord507d772010-10-20 03:06:34 +00004392 // Fake ivar lookup; this should really be part of
4393 // LookupParsedName.
4394 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4395 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004397 (Res.isSingleResult() &&
4398 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004400 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4401 Res.addDecl(IV);
4402 Res.resolveKind();
4403 }
4404 }
4405 }
4406}
4407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004408/// Add keywords to the consumer as possible typo corrections.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004409static void AddKeywordsToConsumer(Sema &SemaRef,
4410 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004411 Scope *S, CorrectionCandidateCallback &CCC,
4412 bool AfterNestedNameSpecifier) {
4413 if (AfterNestedNameSpecifier) {
4414 // For 'X::', we know exactly which keywords can appear next.
4415 Consumer.addKeywordResult("template");
4416 if (CCC.WantExpressionKeywords)
4417 Consumer.addKeywordResult("operator");
4418 return;
4419 }
4420
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004421 if (CCC.WantObjCSuper)
4422 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004423
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004424 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004425 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004426 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004427 "char", "const", "double", "enum", "float", "int", "long", "short",
Fangrui Song6907ce22018-07-30 19:24:48 +00004428 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004429 "_Complex", "_Imaginary",
4430 // storage-specifiers as well
4431 "extern", "inline", "static", "typedef"
4432 };
4433
Craig Toppere5ce8312013-07-15 03:38:40 +00004434 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004435 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4436 Consumer.addKeywordResult(CTypeSpecs[I]);
4437
David Blaikiebbafb8a2012-03-11 07:00:24 +00004438 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004439 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004440 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004441 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004442 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004443 Consumer.addKeywordResult("_Bool");
Fangrui Song6907ce22018-07-30 19:24:48 +00004444
David Blaikiebbafb8a2012-03-11 07:00:24 +00004445 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004446 Consumer.addKeywordResult("class");
4447 Consumer.addKeywordResult("typename");
4448 Consumer.addKeywordResult("wchar_t");
4449
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004450 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004451 Consumer.addKeywordResult("char16_t");
4452 Consumer.addKeywordResult("char32_t");
4453 Consumer.addKeywordResult("constexpr");
4454 Consumer.addKeywordResult("decltype");
4455 Consumer.addKeywordResult("thread_local");
4456 }
4457 }
4458
Richard Smith7b301e22018-05-24 21:51:52 +00004459 if (SemaRef.getLangOpts().GNUKeywords)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004460 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004461 } else if (CCC.WantFunctionLikeCasts) {
4462 static const char *const CastableTypeSpecs[] = {
4463 "char", "double", "float", "int", "long", "short",
4464 "signed", "unsigned", "void"
4465 };
4466 for (auto *kw : CastableTypeSpecs)
4467 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004468 }
4469
David Blaikiebbafb8a2012-03-11 07:00:24 +00004470 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004471 Consumer.addKeywordResult("const_cast");
4472 Consumer.addKeywordResult("dynamic_cast");
4473 Consumer.addKeywordResult("reinterpret_cast");
4474 Consumer.addKeywordResult("static_cast");
4475 }
4476
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004477 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004478 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004479 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004480 Consumer.addKeywordResult("false");
4481 Consumer.addKeywordResult("true");
4482 }
4483
David Blaikiebbafb8a2012-03-11 07:00:24 +00004484 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004485 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004486 "delete", "new", "operator", "throw", "typeid"
4487 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004488 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004489 for (unsigned I = 0; I != NumCXXExprs; ++I)
4490 Consumer.addKeywordResult(CXXExprs[I]);
4491
4492 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4493 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4494 Consumer.addKeywordResult("this");
4495
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004496 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004497 Consumer.addKeywordResult("alignof");
4498 Consumer.addKeywordResult("nullptr");
4499 }
4500 }
Jordan Rose58d54722012-06-30 21:33:57 +00004501
4502 if (SemaRef.getLangOpts().C11) {
4503 // FIXME: We should not suggest _Alignof if the alignof macro
4504 // is present.
4505 Consumer.addKeywordResult("_Alignof");
4506 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004507 }
4508
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004509 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004510 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4511 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004512 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004513 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004514 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004515 for (unsigned I = 0; I != NumCStmts; ++I)
4516 Consumer.addKeywordResult(CStmts[I]);
4517
David Blaikiebbafb8a2012-03-11 07:00:24 +00004518 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004519 Consumer.addKeywordResult("catch");
4520 Consumer.addKeywordResult("try");
4521 }
4522
4523 if (S && S->getBreakParent())
4524 Consumer.addKeywordResult("break");
4525
4526 if (S && S->getContinueParent())
4527 Consumer.addKeywordResult("continue");
4528
Reid Kleckner87a31802018-03-12 21:43:02 +00004529 if (SemaRef.getCurFunction() &&
4530 !SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004531 Consumer.addKeywordResult("case");
4532 Consumer.addKeywordResult("default");
4533 }
4534 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004535 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004536 Consumer.addKeywordResult("namespace");
4537 Consumer.addKeywordResult("template");
4538 }
4539
4540 if (S && S->isClassScope()) {
4541 Consumer.addKeywordResult("explicit");
4542 Consumer.addKeywordResult("friend");
4543 Consumer.addKeywordResult("mutable");
4544 Consumer.addKeywordResult("private");
4545 Consumer.addKeywordResult("protected");
4546 Consumer.addKeywordResult("public");
4547 Consumer.addKeywordResult("virtual");
4548 }
4549 }
4550
David Blaikiebbafb8a2012-03-11 07:00:24 +00004551 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004552 Consumer.addKeywordResult("using");
4553
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004554 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004555 Consumer.addKeywordResult("static_assert");
4556 }
4557 }
4558}
4559
Kaelyn Takata6c759512014-10-27 18:07:37 +00004560std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4561 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4562 Scope *S, CXXScopeSpec *SS,
4563 std::unique_ptr<CorrectionCandidateCallback> CCC,
4564 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004565 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004566
4567 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4568 DisableTypoCorrection)
4569 return nullptr;
4570
4571 // In Microsoft mode, don't perform typo correction in a template member
4572 // function dependent context because it interferes with the "lookup into
4573 // dependent bases of class templates" feature.
4574 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4575 isa<CXXMethodDecl>(CurContext))
4576 return nullptr;
4577
4578 // We only attempt to correct typos for identifiers.
4579 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4580 if (!Typo)
4581 return nullptr;
4582
4583 // If the scope specifier itself was invalid, don't try to correct
4584 // typos.
4585 if (SS && SS->isInvalid())
4586 return nullptr;
4587
Richard Smith696e3122017-02-23 01:43:54 +00004588 // Never try to correct typos during any kind of code synthesis.
4589 if (!CodeSynthesisContexts.empty())
Kaelyn Takata6c759512014-10-27 18:07:37 +00004590 return nullptr;
4591
4592 // Don't try to correct 'super'.
4593 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4594 return nullptr;
4595
4596 // Abort if typo correction already failed for this specific typo.
4597 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4598 if (locs != TypoCorrectionFailures.end() &&
4599 locs->second.count(TypoName.getLoc()))
4600 return nullptr;
4601
4602 // Don't try to correct the identifier "vector" when in AltiVec mode.
4603 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4604 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004605 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004606 return nullptr;
4607
Nick Lewycky24653262014-12-16 21:39:02 +00004608 // Provide a stop gap for files that are just seriously broken. Trying
4609 // to correct all typos can turn into a HUGE performance penalty, causing
4610 // some files to take minutes to get rejected by the parser.
4611 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4612 if (Limit && TyposCorrected >= Limit)
4613 return nullptr;
4614 ++TyposCorrected;
4615
Kaelyn Takata6c759512014-10-27 18:07:37 +00004616 // If we're handling a missing symbol error, using modules, and the
4617 // special search all modules option is used, look for a missing import.
4618 if (ErrorRecovery && getLangOpts().Modules &&
4619 getLangOpts().ModulesSearchAll) {
4620 // The following has the side effect of loading the missing module.
4621 getModuleLoader().lookupMissingImports(Typo->getName(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004622 TypoName.getBeginLoc());
Kaelyn Takata6c759512014-10-27 18:07:37 +00004623 }
4624
4625 CorrectionCandidateCallback &CCCRef = *CCC;
4626 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4627 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4628 EnteringContext);
4629
Kaelyn Takata6c759512014-10-27 18:07:37 +00004630 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004631 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004632 DeclContext *QualifiedDC = MemberContext;
4633 if (MemberContext) {
4634 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4635
4636 // Look in qualified interfaces.
4637 if (OPT) {
4638 for (auto *I : OPT->quals())
4639 LookupVisibleDecls(I, LookupKind, *Consumer);
4640 }
4641 } else if (SS && SS->isSet()) {
4642 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4643 if (!QualifiedDC)
4644 return nullptr;
4645
Kaelyn Takata6c759512014-10-27 18:07:37 +00004646 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4647 } else {
4648 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004649 }
4650
4651 // Determine whether we are going to search in the various namespaces for
4652 // corrections.
4653 bool SearchNamespaces
4654 = getLangOpts().CPlusPlus &&
4655 (IsUnqualifiedLookup || (SS && SS->isSet()));
4656
4657 if (IsUnqualifiedLookup || SearchNamespaces) {
4658 // For unqualified lookup, look through all of the names that we have
4659 // seen in this translation unit.
4660 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4661 for (const auto &I : Context.Idents)
4662 Consumer->FoundName(I.getKey());
4663
4664 // Walk through identifiers in external identifier sources.
4665 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4666 if (IdentifierInfoLookup *External
4667 = Context.Idents.getExternalIdentifierLookup()) {
4668 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4669 do {
4670 StringRef Name = Iter->Next();
4671 if (Name.empty())
4672 break;
4673
4674 Consumer->FoundName(Name);
4675 } while (true);
4676 }
4677 }
4678
4679 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4680
4681 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4682 // to search those namespaces.
4683 if (SearchNamespaces) {
4684 // Load any externally-known namespaces.
4685 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4686 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4687 LoadedExternalKnownNamespaces = true;
4688 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4689 for (auto *N : ExternalKnownNamespaces)
4690 KnownNamespaces[N] = true;
4691 }
4692
4693 Consumer->addNamespaces(KnownNamespaces);
4694 }
4695
4696 return Consumer;
4697}
4698
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004699/// Try to "correct" a typo in the source code by finding
Douglas Gregor2d435302009-12-30 17:04:44 +00004700/// visible declarations whose names are similar to the name that was
4701/// present in the source code.
4702///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004703/// \param TypoName the \c DeclarationNameInfo structure that contains
4704/// the name that was present in the source code along with its location.
4705///
4706/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004707///
4708/// \param S the scope in which name lookup occurs.
4709///
4710/// \param SS the nested-name-specifier that precedes the name we're
4711/// looking for, if present.
4712///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004713/// \param CCC A CorrectionCandidateCallback object that provides further
4714/// validation of typo correction candidates. It also provides flags for
4715/// determining the set of keywords permitted.
4716///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004717/// \param MemberContext if non-NULL, the context in which to look for
4718/// a member access expression.
4719///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004721/// the nested-name-specifier SS.
4722///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004723/// \param OPT when non-NULL, the search for visible declarations will
4724/// also walk the protocols in the qualified interfaces of \p OPT.
4725///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004726/// \returns a \c TypoCorrection containing the corrected name if the typo
4727/// along with information such as the \c NamedDecl where the corrected name
4728/// was declared, and any additional \c NestedNameSpecifier needed to access
4729/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4730TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4731 Sema::LookupNameKind LookupKind,
4732 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004733 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004734 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004735 DeclContext *MemberContext,
4736 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004737 const ObjCObjectPointerType *OPT,
4738 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004739 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4740
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004741 // Always let the ExternalSource have the first chance at correction, even
4742 // if we would otherwise have given up.
4743 if (ExternalSource) {
4744 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004745 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004746 return Correction;
4747 }
4748
Kaelyn Takata6c759512014-10-27 18:07:37 +00004749 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4750 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4751 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4752 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4753 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754
Kaelyn Takata6c759512014-10-27 18:07:37 +00004755 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004756 auto Consumer = makeTypoCorrectionConsumer(
4757 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004758 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004759
Kaelyn Takata6c759512014-10-27 18:07:37 +00004760 if (!Consumer)
4761 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004762
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004763 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004764 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004765 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004766
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004767 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4768 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004769 unsigned ED = Consumer->getBestEditDistance(true);
4770 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004771 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004772 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004773
Kaelyn Takata6c759512014-10-27 18:07:37 +00004774 TypoCorrection BestTC = Consumer->getNextCorrection();
4775 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004776 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004777 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004778
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004779 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004780
Kaelyn Takata6c759512014-10-27 18:07:37 +00004781 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004782 // If this was an unqualified lookup and we believe the callback
4783 // object wouldn't have filtered out possible corrections, note
4784 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004785 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004786 }
4787
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004788 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004789 if (!SecondBestTC ||
4790 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4791 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004792
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004793 // Don't correct to a keyword that's the same as the typo; the keyword
4794 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004795 if (ED == 0 && Result.isKeyword())
4796 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004797
David Blaikie04ea41c2012-10-12 20:00:44 +00004798 TypoCorrection TC = Result;
4799 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004800 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004801 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004802 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004803 // Prefer 'super' when we're completing in a message-receiver
4804 // context.
4805
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004806 if (BestTC.getCorrection().getAsString() != "super") {
4807 if (SecondBestTC.getCorrection().getAsString() == "super")
4808 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004809 else if ((*Consumer)["super"].front().isKeyword())
4810 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004811 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004812 // Don't correct to a keyword that's the same as the typo; the keyword
4813 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004814 if (BestTC.getEditDistance() == 0 ||
4815 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004816 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004818 BestTC.setCorrectionRange(SS, TypoName);
4819 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004822 // Record the failure's location if needed and return an empty correction. If
4823 // this was an unqualified lookup and we believe the callback object did not
4824 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004825 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004826}
4827
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004828/// Try to "correct" a typo in the source code by finding
Kaelyn Takata6c759512014-10-27 18:07:37 +00004829/// visible declarations whose names are similar to the name that was
4830/// present in the source code.
4831///
4832/// \param TypoName the \c DeclarationNameInfo structure that contains
4833/// the name that was present in the source code along with its location.
4834///
4835/// \param LookupKind the name-lookup criteria used to search for the name.
4836///
4837/// \param S the scope in which name lookup occurs.
4838///
4839/// \param SS the nested-name-specifier that precedes the name we're
4840/// looking for, if present.
4841///
4842/// \param CCC A CorrectionCandidateCallback object that provides further
4843/// validation of typo correction candidates. It also provides flags for
4844/// determining the set of keywords permitted.
4845///
4846/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4847/// diagnostics when the actual typo correction is attempted.
4848///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004849/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4850/// Expr from a typo correction candidate.
4851///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004852/// \param MemberContext if non-NULL, the context in which to look for
4853/// a member access expression.
4854///
4855/// \param EnteringContext whether we're entering the context described by
4856/// the nested-name-specifier SS.
4857///
4858/// \param OPT when non-NULL, the search for visible declarations will
4859/// also walk the protocols in the qualified interfaces of \p OPT.
4860///
4861/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4862/// Expr representing the result of performing typo correction, or nullptr if
4863/// typo correction is not possible. If nullptr is returned, no diagnostics will
4864/// be emitted and it is the responsibility of the caller to emit any that are
4865/// needed.
4866TypoExpr *Sema::CorrectTypoDelayed(
4867 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4868 Scope *S, CXXScopeSpec *SS,
4869 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004870 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004871 DeclContext *MemberContext, bool EnteringContext,
4872 const ObjCObjectPointerType *OPT) {
4873 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4874
Kaelyn Takata6c759512014-10-27 18:07:37 +00004875 auto Consumer = makeTypoCorrectionConsumer(
4876 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004877 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004878
Benjamin Kramerb8727332016-05-19 10:46:10 +00004879 // Give the external sema source a chance to correct the typo.
4880 TypoCorrection ExternalTypo;
4881 if (ExternalSource && Consumer) {
4882 ExternalTypo = ExternalSource->CorrectTypo(
Benjamin Kramer97d7a662016-05-19 21:53:33 +00004883 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
4884 MemberContext, EnteringContext, OPT);
Benjamin Kramerb8727332016-05-19 10:46:10 +00004885 if (ExternalTypo)
4886 Consumer->addCorrection(ExternalTypo);
4887 }
4888
Kaelyn Takata6c759512014-10-27 18:07:37 +00004889 if (!Consumer || Consumer->empty())
4890 return nullptr;
4891
4892 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4893 // is not more that about a third of the length of the typo's identifier.
4894 unsigned ED = Consumer->getBestEditDistance(true);
4895 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Benjamin Kramerb8727332016-05-19 10:46:10 +00004896 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004897 return nullptr;
4898
4899 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004900 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004901}
4902
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004903void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4904 if (!CDecl) return;
4905
4906 if (isKeyword())
4907 CorrectionDecls.clear();
4908
Richard Smithde6d6c42015-12-29 19:43:10 +00004909 CorrectionDecls.push_back(CDecl);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004910
4911 if (!CorrectionName)
4912 CorrectionName = CDecl->getDeclName();
4913}
4914
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004915std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4916 if (CorrectionNameSpec) {
4917 std::string tmpBuffer;
4918 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4919 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004920 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004921 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004922 }
4923
4924 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004925}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004926
Nico Weberb58e51c2014-11-19 05:21:39 +00004927bool CorrectionCandidateCallback::ValidateCandidate(
4928 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004929 if (!candidate.isResolved())
4930 return true;
4931
4932 if (candidate.isKeyword())
4933 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4934 WantRemainingKeywords || WantObjCSuper;
4935
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004936 bool HasNonType = false;
4937 bool HasStaticMethod = false;
4938 bool HasNonStaticMethod = false;
4939 for (Decl *D : candidate) {
4940 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4941 D = FTD->getTemplatedDecl();
4942 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4943 if (Method->isStatic())
4944 HasStaticMethod = true;
4945 else
4946 HasNonStaticMethod = true;
4947 }
4948 if (!isa<TypeDecl>(D))
4949 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004950 }
4951
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004952 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4953 !candidate.getCorrectionSpecifier())
4954 return false;
4955
4956 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004957}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004958
4959FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004960 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004961 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004962 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004963 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004964 WantTypeSpecifiers = false;
4965 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004966 WantRemainingKeywords = false;
4967}
4968
4969bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4970 if (!candidate.getCorrectionDecl())
4971 return candidate.isKeyword();
4972
Aaron Ballman1e606f42014-07-15 22:03:49 +00004973 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004974 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004975 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004976 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4977 FD = FTD->getTemplatedDecl();
4978 if (!HasExplicitTemplateArgs && !FD) {
4979 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4980 // If the Decl is neither a function nor a template function,
4981 // determine if it is a pointer or reference to a function. If so,
4982 // check against the number of arguments expected for the pointee.
4983 QualType ValType = cast<ValueDecl>(ND)->getType();
Erik Pilkington1c5ae9b2018-07-10 02:15:07 +00004984 if (ValType.isNull())
4985 continue;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004986 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4987 ValType = ValType->getPointeeType();
4988 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004989 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004990 return true;
4991 }
4992 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004993
4994 // Skip the current candidate if it is not a FunctionDecl or does not accept
4995 // the current number of arguments.
4996 if (!FD || !(FD->getNumParams() >= NumArgs &&
4997 FD->getMinRequiredArguments() <= NumArgs))
4998 continue;
4999
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005000 // If the current candidate is a non-static C++ method, skip the candidate
5001 // unless the method being corrected--or the current DeclContext, if the
5002 // function being corrected is not a method--is a method in the same class
5003 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005004 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005005 if (MemberFn || !MD->isStatic()) {
5006 CXXMethodDecl *CurMD =
5007 MemberFn
5008 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5009 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005010 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00005011 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005012 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5013 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5014 continue;
5015 }
5016 }
5017 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005018 }
5019 return false;
5020}
Richard Smithf9b15102013-08-17 00:46:16 +00005021
5022void Sema::diagnoseTypo(const TypoCorrection &Correction,
5023 const PartialDiagnostic &TypoDiag,
5024 bool ErrorRecovery) {
5025 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5026 ErrorRecovery);
5027}
5028
Richard Smithe156254d2013-08-20 20:35:18 +00005029/// Find which declaration we should import to provide the definition of
5030/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00005031static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5032 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005033 return VD->getDefinition();
Yaron Keren18c3d062016-07-13 19:04:51 +00005034 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5035 return FD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005036 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005037 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005038 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005039 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005040 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005041 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005042 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005043 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005044 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00005045}
5046
Richard Smithf2b1eb92015-06-15 20:15:48 +00005047void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005048 MissingImportKind MIK, bool Recover) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005049 // Suggest importing a module providing the definition of this entity, if
5050 // possible.
5051 NamedDecl *Def = getDefinitionToImport(Decl);
5052 if (!Def)
5053 Def = Decl;
5054
Richard Smithc4577662018-09-12 02:13:47 +00005055 Module *Owner = getOwningModule(Def);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005056 assert(Owner && "definition of hidden declaration is not in a module");
5057
Richard Smith35c1df52015-06-17 20:16:32 +00005058 llvm::SmallVector<Module*, 8> OwningModules;
5059 OwningModules.push_back(Owner);
Richard Smithc4577662018-09-12 02:13:47 +00005060 auto Merged = Context.getModulesWithMergedDefinition(Def);
Richard Smith35c1df52015-06-17 20:16:32 +00005061 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5062
Richard Smith6739a102016-05-05 00:56:12 +00005063 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
Richard Smith35c1df52015-06-17 20:16:32 +00005064 Recover);
5065}
5066
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005067/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
Richard Smith4eb83932016-04-27 21:57:05 +00005068/// suggesting the addition of a #include of the specified file.
5069static std::string getIncludeStringForHeader(Preprocessor &PP,
5070 const FileEntry *E) {
5071 bool IsSystem;
5072 auto Path =
5073 PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem);
5074 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5075}
5076
Richard Smith35c1df52015-06-17 20:16:32 +00005077void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5078 SourceLocation DeclLoc,
5079 ArrayRef<Module *> Modules,
5080 MissingImportKind MIK, bool Recover) {
5081 assert(!Modules.empty());
5082
Richard Smith54f04402017-05-18 02:29:20 +00005083 // Weed out duplicates from module list.
5084 llvm::SmallVector<Module*, 8> UniqueModules;
5085 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5086 for (auto *M : Modules)
5087 if (UniqueModuleSet.insert(M).second)
5088 UniqueModules.push_back(M);
5089 Modules = UniqueModules;
5090
Richard Smith35c1df52015-06-17 20:16:32 +00005091 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005092 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00005093 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00005094 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005095 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00005096 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005097 ModuleList += "[...]";
5098 break;
5099 }
5100 ModuleList += M->getFullModuleName();
5101 }
5102
Richard Smith35c1df52015-06-17 20:16:32 +00005103 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5104 << (int)MIK << Decl << ModuleList;
Richard Smithcbf7d8a2017-05-19 23:49:00 +00005105 } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics(
5106 UseLoc, Modules[0], DeclLoc)) {
Richard Smith4eb83932016-04-27 21:57:05 +00005107 // The right way to make the declaration visible is to include a header;
5108 // suggest doing so.
5109 //
5110 // FIXME: Find a smart place to suggest inserting a #include, and add
5111 // a FixItHint there.
5112 Diag(UseLoc, diag::err_module_unimported_use_header)
5113 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5114 << getIncludeStringForHeader(PP, E);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005115 } else {
Richard Smithacef17a2016-05-05 02:14:06 +00005116 // FIXME: Add a FixItHint that imports the corresponding module.
Richard Smith35c1df52015-06-17 20:16:32 +00005117 Diag(UseLoc, diag::err_module_unimported_use)
5118 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00005119 }
Richard Smith35c1df52015-06-17 20:16:32 +00005120
5121 unsigned DiagID;
5122 switch (MIK) {
5123 case MissingImportKind::Declaration:
5124 DiagID = diag::note_previous_declaration;
5125 break;
5126 case MissingImportKind::Definition:
5127 DiagID = diag::note_previous_definition;
5128 break;
5129 case MissingImportKind::DefaultArgument:
5130 DiagID = diag::note_default_argument_declared_here;
5131 break;
Richard Smith6739a102016-05-05 00:56:12 +00005132 case MissingImportKind::ExplicitSpecialization:
5133 DiagID = diag::note_explicit_specialization_declared_here;
5134 break;
5135 case MissingImportKind::PartialSpecialization:
5136 DiagID = diag::note_partial_specialization_declared_here;
5137 break;
Richard Smith35c1df52015-06-17 20:16:32 +00005138 }
5139 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005140
5141 // Try to recover by implicitly importing this module.
5142 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00005143 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005144}
5145
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005146/// Diagnose a successfully-corrected typo. Separated from the correction
Richard Smithf9b15102013-08-17 00:46:16 +00005147/// itself to allow external validation of the result, etc.
5148///
5149/// \param Correction The result of performing typo correction.
5150/// \param TypoDiag The diagnostic to produce. This will have the corrected
5151/// string added to it (and usually also a fixit).
5152/// \param PrevNote A note to use when indicating the location of the entity to
5153/// which we are correcting. Will have the correction string added to it.
5154/// \param ErrorRecovery If \c true (the default), the caller is going to
5155/// recover from the typo as if the corrected string had been typed.
5156/// In this case, \c PDiag must be an error, and we will attach a fixit
5157/// to it.
5158void Sema::diagnoseTypo(const TypoCorrection &Correction,
5159 const PartialDiagnostic &TypoDiag,
5160 const PartialDiagnostic &PrevNote,
5161 bool ErrorRecovery) {
5162 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5163 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5164 FixItHint FixTypo = FixItHint::CreateReplacement(
5165 Correction.getCorrectionRange(), CorrectedStr);
5166
Richard Smithe156254d2013-08-20 20:35:18 +00005167 // Maybe we're just missing a module import.
5168 if (Correction.requiresImport()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00005169 NamedDecl *Decl = Correction.getFoundDecl();
Richard Smithe156254d2013-08-20 20:35:18 +00005170 assert(Decl && "import required but no declaration to import");
5171
Richard Smithf2b1eb92015-06-15 20:15:48 +00005172 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005173 MissingImportKind::Declaration, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00005174 return;
5175 }
5176
Richard Smithf9b15102013-08-17 00:46:16 +00005177 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5178 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5179
5180 NamedDecl *ChosenDecl =
Richard Smithde6d6c42015-12-29 19:43:10 +00005181 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00005182 if (PrevNote.getDiagID() && ChosenDecl)
5183 Diag(ChosenDecl->getLocation(), PrevNote)
5184 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
Benjamin Kramer7de99692016-11-16 18:15:26 +00005185
5186 // Add any extra diagnostics.
5187 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5188 Diag(Correction.getCorrectionRange().getBegin(), PD);
Richard Smithf9b15102013-08-17 00:46:16 +00005189}
Kaelyn Takata6c759512014-10-27 18:07:37 +00005190
Kaelyn Takata8363f042014-10-27 18:07:42 +00005191TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5192 TypoDiagnosticGenerator TDG,
5193 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00005194 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5195 auto TE = new (Context) TypoExpr(Context.DependentTy);
5196 auto &State = DelayedTypos[TE];
5197 State.Consumer = std::move(TCC);
5198 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00005199 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00005200 return TE;
5201}
5202
5203const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5204 auto Entry = DelayedTypos.find(TE);
5205 assert(Entry != DelayedTypos.end() &&
5206 "Failed to get the state for a TypoExpr!");
5207 return Entry->second;
5208}
5209
5210void Sema::clearDelayedTypo(TypoExpr *TE) {
5211 DelayedTypos.erase(TE);
5212}
Richard Smithba3a4f92016-01-12 21:59:26 +00005213
5214void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5215 DeclarationNameInfo Name(II, IILoc);
5216 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5217 R.suppressDiagnostics();
5218 R.setHideTags(false);
5219 LookupName(R, S);
5220 R.dump();
5221}