blob: 86960e0a1dbd5b3464d3c1478b71d1da648768af [file] [log] [blame]
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
Douglas Gregor34074322009-01-14 22:20:51 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregor34074322009-01-14 22:20:51 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements name lookup for C, C++, Objective-C, and
10// Objective-C++.
11//
12//===----------------------------------------------------------------------===//
Hans Wennborgdcfba332015-10-06 23:40:43 +000013
Douglas Gregor960b5bc2009-01-15 00:26:24 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000015#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000016#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000018#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000020#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000021#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/Basic/LangOptions.h"
Richard Smith42413142015-05-15 20:05:43 +000025#include "clang/Lex/HeaderSearch.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000026#include "clang/Lex/ModuleLoader.h"
Richard Smith4caa4492015-05-15 02:34:32 +000027#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Sema/DeclSpec.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000029#include "clang/Sema/Lookup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/Overload.h"
31#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
33#include "clang/Sema/Sema.h"
34#include "clang/Sema/SemaInternal.h"
35#include "clang/Sema/TemplateDeduction.h"
36#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000037#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000038#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregor2d435302009-12-30 17:04:44 +000044#include <list>
Nick Lewycky13668f22012-04-03 20:26:45 +000045#include <set>
46#include <utility>
47#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000048
49using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000050using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000051
John McCallf6c8a4e2009-11-10 07:01:13 +000052namespace {
53 class UnqualUsingEntry {
54 const DeclContext *Nominated;
55 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000056
John McCallf6c8a4e2009-11-10 07:01:13 +000057 public:
58 UnqualUsingEntry(const DeclContext *Nominated,
59 const DeclContext *CommonAncestor)
60 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
61 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 const DeclContext *getCommonAncestor() const {
64 return CommonAncestor;
65 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000066
John McCallf6c8a4e2009-11-10 07:01:13 +000067 const DeclContext *getNominatedNamespace() const {
68 return Nominated;
69 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000070
John McCallf6c8a4e2009-11-10 07:01:13 +000071 // Sort by the pointer value of the common ancestor.
72 struct Comparator {
73 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
74 return L.getCommonAncestor() < R.getCommonAncestor();
75 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000076
John McCallf6c8a4e2009-11-10 07:01:13 +000077 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
78 return E.getCommonAncestor() < DC;
79 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000080
John McCallf6c8a4e2009-11-10 07:01:13 +000081 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
82 return DC < E.getCommonAncestor();
83 }
84 };
85 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000086
John McCallf6c8a4e2009-11-10 07:01:13 +000087 /// A collection of using directives, as used by C++ unqualified
88 /// lookup.
89 class UnqualUsingDirectiveSet {
Richard Smithb920f852017-10-11 01:19:11 +000090 Sema &SemaRef;
91
Chris Lattner0e62c1c2011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000096
John McCallf6c8a4e2009-11-10 07:01:13 +000097 public:
Richard Smithb920f852017-10-11 01:19:11 +000098 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000099
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000105 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000107
John McCallf6c8a4e2009-11-10 07:01:13 +0000108 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000109 // C++ [namespace.udir]p1:
110 // A using-directive shall not appear in class scope, but may
111 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000112 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000113 if (Ctx && Ctx->isFileContext()) {
114 visit(Ctx, Ctx);
115 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000116 for (auto *I : S->using_directives())
Richard Smithb920f852017-10-11 01:19:11 +0000117 if (SemaRef.isVisible(I))
118 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000119 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000120 }
121 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000122
123 // Visits a context and collect all of its using directives
124 // recursively. Treats all using directives as if they were
125 // declared in the context.
126 //
127 // A given context is only every visited once, so it is important
128 // that contexts be visited from the inside out in order to get
129 // the effective DCs right.
130 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000131 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000132 return;
133
134 addUsingDirectives(DC, EffectiveDC);
135 }
136
137 // Visits a using directive and collects all of its using
138 // directives recursively. Treats all using directives as if they
139 // were declared in the effective DC.
140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
141 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000142 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000143 return;
144
145 addUsingDirective(UD, EffectiveDC);
146 addUsingDirectives(NS, EffectiveDC);
147 }
148
149 // Adds all the using directives in a context (and those nominated
150 // by its using directives, transitively) as if they appeared in
151 // the given effective context.
152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Nick Lewycky4b81fc872015-10-18 20:32:12 +0000153 SmallVector<DeclContext*, 4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000154 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000155 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 DeclContext *NS = UD->getNominatedNamespace();
Richard Smitha544c512017-10-30 22:38:20 +0000157 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000158 addUsingDirective(UD, EffectiveDC);
159 queue.push_back(NS);
160 }
161 }
162
163 if (queue.empty())
164 return;
165
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000166 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000167 }
168 }
169
170 // Add a using directive as if it had been declared in the given
171 // context. This helps implement C++ [namespace.udir]p3:
172 // The using-directive is transitive: if a scope contains a
173 // using-directive that nominates a second namespace that itself
174 // contains using-directives, the effect is as if the
175 // using-directives from the second namespace also appeared in
176 // the first.
177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
178 // Find the common ancestor between the effective context and
179 // the nominated namespace.
180 DeclContext *Common = UD->getNominatedNamespace();
181 while (!Common->Encloses(EffectiveDC))
182 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000183 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184
John McCallf6c8a4e2009-11-10 07:01:13 +0000185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
186 }
187
Fangrui Song55fab262018-09-26 22:16:28 +0000188 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
John McCallf6c8a4e2009-11-10 07:01:13 +0000189
John McCallf6c8a4e2009-11-10 07:01:13 +0000190 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000191
John McCallf6c8a4e2009-11-10 07:01:13 +0000192 const_iterator begin() const { return list.begin(); }
193 const_iterator end() const { return list.end(); }
194
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000195 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000197 return llvm::make_range(std::equal_range(begin(), end(),
198 DC->getPrimaryContext(),
199 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000200 }
201 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000202} // end anonymous namespace
Douglas Gregor889ceb72009-02-03 19:21:40 +0000203
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204// Retrieve the set of identifier namespaces that correspond to a
205// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000206static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
207 bool CPlusPlus,
208 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209 unsigned IDNS = 0;
210 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000211 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000213 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000214 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000216 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000218 if (Redeclaration)
219 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000220 }
Richard Smith541b38b2013-09-20 01:15:31 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000223 break;
224
John McCallb9467b62010-04-24 01:30:58 +0000225 case Sema::LookupOperatorName:
226 // Operator lookup is its own crazy thing; it is not the same
227 // as (e.g.) looking up an operator name for redeclaration.
228 assert(!Redeclaration && "cannot do redeclaration operator lookup");
229 IDNS = Decl::IDNS_NonMemberOperator;
230 break;
231
Douglas Gregor889ceb72009-02-03 19:21:40 +0000232 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000233 if (CPlusPlus) {
234 IDNS = Decl::IDNS_Type;
235
236 // When looking for a redeclaration of a tag name, we add:
237 // 1) TagFriend to find undeclared friend decls
238 // 2) Namespace because they can't "overload" with tag decls.
239 // 3) Tag because it includes class templates, which can't
240 // "overload" with tag decls.
241 if (Redeclaration)
242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
243 } else {
244 IDNS = Decl::IDNS_Tag;
245 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000246 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000247
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000248 case Sema::LookupLabel:
249 IDNS = Decl::IDNS_Label;
250 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000251
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 case Sema::LookupMemberName:
253 IDNS = Decl::IDNS_Member;
254 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000255 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000256 break;
257
258 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000259 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
260 break;
261
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000263 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000265
John McCall84d87672009-12-10 09:41:52 +0000266 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000267 assert(Redeclaration && "should only be used for redecl lookup");
268 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
269 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
270 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000271 break;
272
Douglas Gregor79947a22009-04-24 00:11:27 +0000273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
275 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000277 case Sema::LookupOMPReductionName:
278 IDNS = Decl::IDNS_OMPReduction;
279 break;
280
Michael Kruse251e1482019-02-01 20:25:04 +0000281 case Sema::LookupOMPMapperName:
282 IDNS = Decl::IDNS_OMPMapper;
283 break;
284
Douglas Gregor39982192010-08-15 06:18:01 +0000285 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000286 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000287 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
288 | Decl::IDNS_Type;
289 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000290 }
291 return IDNS;
292}
293
John McCallea305ed2009-12-18 10:40:03 +0000294void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000295 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000296 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000297
Richard Smithbdd14642014-02-04 01:14:30 +0000298 // If we're looking for one of the allocation or deallocation
299 // operators, make sure that the implicitly-declared new and delete
300 // operators can be found.
301 switch (NameInfo.getName().getCXXOverloadedOperator()) {
302 case OO_New:
303 case OO_Delete:
304 case OO_Array_New:
305 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000306 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000307 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000308
Richard Smithbdd14642014-02-04 01:14:30 +0000309 default:
310 break;
311 }
Douglas Gregor15197662013-04-03 23:06:26 +0000312
Richard Smithbdd14642014-02-04 01:14:30 +0000313 // Compiler builtins are always visible, regardless of where they end
314 // up being declared.
315 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
316 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000317 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000318 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000319 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000320 }
John McCallea305ed2009-12-18 10:40:03 +0000321}
322
Alp Tokerc1086762013-12-07 13:51:35 +0000323bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000324 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000325 assert(ResultKind != NotFound || Decls.size() == 0);
326 assert(ResultKind != Found || Decls.size() == 1);
327 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
328 (Decls.size() == 1 &&
329 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
330 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
331 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000332 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
333 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000334 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
335 (Ambiguity == AmbiguousBaseSubobjectTypes ||
336 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000337 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000338}
John McCall19c1bfd2010-08-25 05:32:35 +0000339
John McCall9f3059a2009-10-09 21:13:30 +0000340// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000341void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000342 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000343}
344
Richard Smith3876cc82013-10-30 01:02:04 +0000345/// Get a representative context for a declaration such that two declarations
346/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000347static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000348 // For function-local declarations, use that function as the context. This
349 // doesn't account for scopes within the function; the caller must deal with
350 // those.
351 DeclContext *DC = D->getLexicalDeclContext();
352 if (DC->isFunctionOrMethod())
353 return DC;
354
355 // Otherwise, look at the semantic context of the declaration. The
356 // declaration must have been found there.
357 return D->getDeclContext()->getRedeclContext();
358}
359
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000360/// Determine whether \p D is a better lookup result than \p Existing,
Richard Smith826711d2015-07-29 23:38:25 +0000361/// given that they declare the same entity.
Richard Smithcd31b852015-08-22 21:37:34 +0000362static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
Richard Smith826711d2015-07-29 23:38:25 +0000363 NamedDecl *D, NamedDecl *Existing) {
364 // When looking up redeclarations of a using declaration, prefer a using
365 // shadow declaration over any other declaration of the same entity.
366 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
367 !isa<UsingShadowDecl>(Existing))
368 return true;
369
370 auto *DUnderlying = D->getUnderlyingDecl();
371 auto *EUnderlying = Existing->getUnderlyingDecl();
372
Richard Smith990668b2015-11-12 22:04:34 +0000373 // If they have different underlying declarations, prefer a typedef over the
374 // original type (this happens when two type declarations denote the same
375 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
376 // might carry additional semantic information, such as an alignment override.
377 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
378 // declaration over a typedef.
Richard Smith826711d2015-07-29 23:38:25 +0000379 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
380 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
Richard Smith990668b2015-11-12 22:04:34 +0000381 bool HaveTag = isa<TagDecl>(EUnderlying);
382 bool WantTag = Kind == Sema::LookupTagName;
383 return HaveTag != WantTag;
Richard Smith826711d2015-07-29 23:38:25 +0000384 }
385
Richard Smithcd31b852015-08-22 21:37:34 +0000386 // Pick the function with more default arguments.
387 // FIXME: In the presence of ambiguous default arguments, we should keep both,
388 // so we can diagnose the ambiguity if the default argument is needed.
389 // See C++ [over.match.best]p3.
390 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
391 auto *EFD = cast<FunctionDecl>(EUnderlying);
392 unsigned DMin = DFD->getMinRequiredArguments();
393 unsigned EMin = EFD->getMinRequiredArguments();
394 // If D has more default arguments, it is preferred.
395 if (DMin != EMin)
396 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000397 // FIXME: When we track visibility for default function arguments, check
398 // that we pick the declaration with more visible default arguments.
Richard Smithcd31b852015-08-22 21:37:34 +0000399 }
400
401 // Pick the template with more default template arguments.
402 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
403 auto *ETD = cast<TemplateDecl>(EUnderlying);
404 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
405 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
Richard Smith535ff802015-09-11 22:39:35 +0000406 // If D has more default arguments, it is preferred. Note that default
407 // arguments (and their visibility) is monotonically increasing across the
408 // redeclaration chain, so this is a quick proxy for "is more recent".
Richard Smithcd31b852015-08-22 21:37:34 +0000409 if (DMin != EMin)
410 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000411 // If D has more *visible* default arguments, it is preferred. Note, an
412 // earlier default argument being visible does not imply that a later
413 // default argument is visible, so we can't just check the first one.
414 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
415 I != N; ++I) {
416 if (!S.hasVisibleDefaultArgument(
417 ETD->getTemplateParameters()->getParam(I)) &&
418 S.hasVisibleDefaultArgument(
419 DTD->getTemplateParameters()->getParam(I)))
420 return true;
421 }
Richard Smithcd31b852015-08-22 21:37:34 +0000422 }
423
Vassil Vassilev4d75e8d2016-02-28 19:08:24 +0000424 // VarDecl can have incomplete array types, prefer the one with more complete
425 // array type.
426 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
427 VarDecl *EVD = cast<VarDecl>(EUnderlying);
428 if (EVD->getType()->isIncompleteType() &&
429 !DVD->getType()->isIncompleteType()) {
430 // Prefer the decl with a more complete type if visible.
431 return S.isVisible(DVD);
432 }
433 return false; // Avoid picking up a newer decl, just because it was newer.
434 }
435
Richard Smithcd31b852015-08-22 21:37:34 +0000436 // For most kinds of declaration, it doesn't really matter which one we pick.
437 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
438 // If the existing declaration is hidden, prefer the new one. Otherwise,
439 // keep what we've got.
440 return !S.isVisible(Existing);
441 }
442
443 // Pick the newer declaration; it might have a more precise type.
Richard Smith826711d2015-07-29 23:38:25 +0000444 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
445 Prev = Prev->getPreviousDecl())
446 if (Prev == EUnderlying)
447 return true;
Richard Smith826711d2015-07-29 23:38:25 +0000448 return false;
449}
450
Richard Smith990668b2015-11-12 22:04:34 +0000451/// Determine whether \p D can hide a tag declaration.
452static bool canHideTag(NamedDecl *D) {
453 // C++ [basic.scope.declarative]p4:
454 // Given a set of declarations in a single declarative region [...]
455 // exactly one declaration shall declare a class name or enumeration name
456 // that is not a typedef name and the other declarations shall all refer to
Richard Smith4eeaec42016-12-18 22:01:46 +0000457 // the same variable, non-static data member, or enumerator, or all refer
458 // to functions and function templates; in this case the class name or
459 // enumeration name is hidden.
Richard Smith990668b2015-11-12 22:04:34 +0000460 // C++ [basic.scope.hiding]p2:
461 // A class name or enumeration name can be hidden by the name of a
462 // variable, data member, function, or enumerator declared in the same
463 // scope.
Richard Smith4eeaec42016-12-18 22:01:46 +0000464 // An UnresolvedUsingValueDecl always instantiates to one of these.
Richard Smith990668b2015-11-12 22:04:34 +0000465 D = D->getUnderlyingDecl();
466 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
Richard Smith4eeaec42016-12-18 22:01:46 +0000467 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
468 isa<UnresolvedUsingValueDecl>(D);
Richard Smith990668b2015-11-12 22:04:34 +0000469}
470
John McCall283b9012009-11-22 00:44:51 +0000471/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000472void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000473 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000474
John McCall9f3059a2009-10-09 21:13:30 +0000475 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000476 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000477 assert(ResultKind == NotFound ||
478 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000479 return;
480 }
481
John McCall283b9012009-11-22 00:44:51 +0000482 // If there's a single decl, we need to examine it to decide what
483 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000484 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000485 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
486 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000487 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000488 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000489 ResultKind = FoundUnresolvedValue;
490 return;
491 }
John McCall9f3059a2009-10-09 21:13:30 +0000492
John McCall6538c932009-10-10 05:48:19 +0000493 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000494 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000495
Richard Smitha534a312015-07-21 23:54:07 +0000496 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000497 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000498
John McCall9f3059a2009-10-09 21:13:30 +0000499 bool Ambiguous = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000500 bool HasTag = false, HasFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000501 bool HasFunctionTemplate = false, HasUnresolved = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000502 NamedDecl *HasNonFunction = nullptr;
503
504 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
John McCall9f3059a2009-10-09 21:13:30 +0000505
506 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507
John McCall9f3059a2009-10-09 21:13:30 +0000508 unsigned I = 0;
509 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000510 NamedDecl *D = Decls[I]->getUnderlyingDecl();
511 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000512
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000513 // Ignore an invalid declaration unless it's the only one left.
Richard Smith5cd86f82015-11-03 03:13:11 +0000514 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000515 Decls[I] = Decls[--N];
516 continue;
517 }
518
Richard Smith826711d2015-07-29 23:38:25 +0000519 llvm::Optional<unsigned> ExistingI;
520
Douglas Gregor13e65872010-08-11 14:45:53 +0000521 // Redeclarations of types via typedef can occur both within a scope
522 // and, through using declarations and directives, across scopes. There is
523 // no ambiguity if they all refer to the same type, so unique based on the
524 // canonical type.
525 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith990668b2015-11-12 22:04:34 +0000526 QualType T = getSema().Context.getTypeDeclType(TD);
527 auto UniqueResult = UniqueTypes.insert(
528 std::make_pair(getSema().Context.getCanonicalType(T), I));
529 if (!UniqueResult.second) {
530 // The type is not unique.
531 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000532 }
533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
Richard Smith826711d2015-07-29 23:38:25 +0000535 // For non-type declarations, check for a prior lookup result naming this
536 // canonical declaration.
537 if (!ExistingI) {
538 auto UniqueResult = Unique.insert(std::make_pair(D, I));
539 if (!UniqueResult.second) {
540 // We've seen this entity before.
541 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000542 }
Richard Smith826711d2015-07-29 23:38:25 +0000543 }
544
545 if (ExistingI) {
546 // This is not a unique lookup result. Pick one of the results and
547 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000548 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000549 Decls[*ExistingI]))
550 Decls[*ExistingI] = Decls[I];
551 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000552 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553 }
554
Douglas Gregor13e65872010-08-11 14:45:53 +0000555 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000556
Douglas Gregor13e65872010-08-11 14:45:53 +0000557 if (isa<UnresolvedUsingValueDecl>(D)) {
558 HasUnresolved = true;
559 } else if (isa<TagDecl>(D)) {
560 if (HasTag)
561 Ambiguous = true;
562 UniqueTagIndex = I;
563 HasTag = true;
564 } else if (isa<FunctionTemplateDecl>(D)) {
565 HasFunction = true;
566 HasFunctionTemplate = true;
567 } else if (isa<FunctionDecl>(D)) {
568 HasFunction = true;
569 } else {
Richard Smith2dbe4042015-11-04 19:26:32 +0000570 if (HasNonFunction) {
571 // If we're about to create an ambiguity between two declarations that
572 // are equivalent, but one is an internal linkage declaration from one
573 // module and the other is an internal linkage declaration from another
574 // module, just skip it.
575 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
576 D)) {
577 EquivalentNonFunctions.push_back(D);
578 Decls[I] = Decls[--N];
579 continue;
580 }
581
Douglas Gregor13e65872010-08-11 14:45:53 +0000582 Ambiguous = true;
Richard Smith2dbe4042015-11-04 19:26:32 +0000583 }
584 HasNonFunction = D;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000585 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000586 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000587 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000588
John McCall9f3059a2009-10-09 21:13:30 +0000589 // C++ [basic.scope.hiding]p2:
590 // A class name or enumeration name can be hidden by the name of
591 // an object, function, or enumerator declared in the same
592 // scope. If a class or enumeration name and an object, function,
593 // or enumerator are declared in the same scope (in any order)
594 // with the same name, the class or enumeration name is hidden
595 // wherever the object, function, or enumerator name is visible.
596 // But it's still an error if there are distinct tag types found,
597 // even if they're not visible. (ref?)
Richard Smith990668b2015-11-12 22:04:34 +0000598 if (N > 1 && HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000599 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith990668b2015-11-12 22:04:34 +0000600 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
601 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
602 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
603 getContextForScopeMatching(OtherDecl)) &&
604 canHideTag(OtherDecl))
Douglas Gregore63d0872010-10-23 16:06:17 +0000605 Decls[UniqueTagIndex] = Decls[--N];
606 else
607 Ambiguous = true;
608 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000609
Richard Smith2dbe4042015-11-04 19:26:32 +0000610 // FIXME: This diagnostic should really be delayed until we're done with
611 // the lookup result, in case the ambiguity is resolved by the caller.
612 if (!EquivalentNonFunctions.empty() && !Ambiguous)
613 getSema().diagnoseEquivalentInternalLinkageDeclarations(
614 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
615
John McCall9f3059a2009-10-09 21:13:30 +0000616 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000617
John McCall80053822009-12-03 00:58:24 +0000618 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000619 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000620
John McCall9f3059a2009-10-09 21:13:30 +0000621 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000622 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000623 else if (HasUnresolved)
624 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000625 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000626 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000627 else
John McCall27b18f82009-11-17 02:14:36 +0000628 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000629}
630
John McCall5cebab12009-11-18 07:57:50 +0000631void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000632 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000633 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000634 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
635 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000636 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000637}
638
John McCall5cebab12009-11-18 07:57:50 +0000639void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000640 Paths = new CXXBasePaths;
641 Paths->swap(P);
642 addDeclsFromBasePaths(*Paths);
643 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000644 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000645}
646
John McCall5cebab12009-11-18 07:57:50 +0000647void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000648 Paths = new CXXBasePaths;
649 Paths->swap(P);
650 addDeclsFromBasePaths(*Paths);
651 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000652 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000653}
654
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000655void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000656 Out << Decls.size() << " result(s)";
657 if (isAmbiguous()) Out << ", ambiguous";
658 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
John McCall9f3059a2009-10-09 21:13:30 +0000660 for (iterator I = begin(), E = end(); I != E; ++I) {
661 Out << "\n";
662 (*I)->print(Out, 2);
663 }
664}
665
Richard Smithba3a4f92016-01-12 21:59:26 +0000666LLVM_DUMP_METHOD void LookupResult::dump() {
667 llvm::errs() << "lookup results for " << getLookupName().getAsString()
668 << ":\n";
669 for (NamedDecl *D : *this)
670 D->dump();
671}
672
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000673/// Lookup a builtin function, when name lookup would otherwise
Douglas Gregord3a59182010-02-12 05:48:04 +0000674/// fail.
675static bool LookupBuiltin(Sema &S, LookupResult &R) {
676 Sema::LookupNameKind NameKind = R.getLookupKind();
677
678 // If we didn't find a use of this identifier, and if the identifier
679 // corresponds to a compiler builtin, create the decl object for the builtin
680 // now, injecting it into translation unit scope, and return it.
681 if (NameKind == Sema::LookupOrdinaryName ||
682 NameKind == Sema::LookupRedeclarationWithLinkage) {
683 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
684 if (II) {
Eric Fiselier6ad68552016-07-01 01:24:09 +0000685 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
686 if (II == S.getASTContext().getMakeIntegerSeqName()) {
687 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
688 return true;
689 } else if (II == S.getASTContext().getTypePackElementName()) {
690 R.addDecl(S.getASTContext().getTypePackElementDecl());
691 return true;
692 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000693 }
Nico Webere1687c52013-06-20 21:44:55 +0000694
Douglas Gregord3a59182010-02-12 05:48:04 +0000695 // If this is a builtin on this (or all) targets, create the decl.
696 if (unsigned BuiltinID = II->getBuiltinID()) {
Anastasia Stulovab607e0f2016-02-02 11:29:43 +0000697 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
698 // library functions like 'malloc'. Instead, we'll just error.
699 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000700 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
701 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
703 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
704 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000705 R.isForRedeclaration(),
706 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000707 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000708 return true;
709 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000710 }
711 }
712 }
713
714 return false;
715}
716
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000717/// Determine whether we can declare a special member function within
Douglas Gregor7454c562010-07-02 20:37:36 +0000718/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000719static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000720 // We need to have a definition for the class.
721 if (!Class->getDefinition() || Class->isDependentContext())
722 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
Douglas Gregor7454c562010-07-02 20:37:36 +0000724 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000725 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000726}
727
728void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000729 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000730 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000731
732 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000733 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000734 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregora6d69502010-07-02 23:41:54 +0000736 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000737 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000738 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000739
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000740 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000741 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000742 DeclareImplicitCopyAssignment(Class);
743
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000744 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000745 // If the move constructor has not yet been declared, do so now.
746 if (Class->needsImplicitMoveConstructor())
Richard Smitha87b7662016-05-13 18:48:05 +0000747 DeclareImplicitMoveConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000748
749 // If the move assignment operator has not yet been declared, do so now.
750 if (Class->needsImplicitMoveAssignment())
Richard Smitha87b7662016-05-13 18:48:05 +0000751 DeclareImplicitMoveAssignment(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000752 }
753
Douglas Gregor7454c562010-07-02 20:37:36 +0000754 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000755 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000756 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000757}
758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000759/// Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000760/// special member function.
761static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
762 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000763 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000764 case DeclarationName::CXXDestructorName:
765 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000766
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000767 case DeclarationName::CXXOperatorName:
768 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000770 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000774 return false;
775}
776
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000777/// If there are any implicit member functions with the given name
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000778/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000780 DeclarationName Name,
Richard Smith32918772017-02-14 00:25:28 +0000781 SourceLocation Loc,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000782 const DeclContext *DC) {
783 if (!DC)
784 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000785
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000786 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000787 case DeclarationName::CXXConstructorName:
788 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000789 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000790 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000791 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000792 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000793 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000794 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000795 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000796 Record->needsImplicitMoveConstructor())
797 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000798 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000799 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000801 case DeclarationName::CXXDestructorName:
802 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000803 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000804 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000805 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000806 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000808 case DeclarationName::CXXOperatorName:
809 if (Name.getCXXOverloadedOperator() != OO_Equal)
810 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
Sebastian Redl22653ba2011-08-30 19:58:05 +0000812 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000813 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000814 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000815 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000816 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000817 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000818 Record->needsImplicitMoveAssignment())
819 S.DeclareImplicitMoveAssignment(Class);
820 }
821 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000822 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000823
Richard Smith32918772017-02-14 00:25:28 +0000824 case DeclarationName::CXXDeductionGuideName:
825 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
826 break;
827
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000828 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000830 }
831}
Douglas Gregor7454c562010-07-02 20:37:36 +0000832
John McCall9f3059a2009-10-09 21:13:30 +0000833// Adds all qualifying matches for a name within a decl context to the
834// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000835static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000836 bool Found = false;
837
Douglas Gregor7454c562010-07-02 20:37:36 +0000838 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000839 if (S.getLangOpts().CPlusPlus)
Richard Smith32918772017-02-14 00:25:28 +0000840 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
841 DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor7454c562010-07-02 20:37:36 +0000843 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000844 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
Yaron Keren31bde582017-04-12 10:05:48 +0000845 for (NamedDecl *D : DR) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000846 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000847 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000848 Found = true;
849 }
850 }
John McCall9f3059a2009-10-09 21:13:30 +0000851
Douglas Gregord3a59182010-02-12 05:48:04 +0000852 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
853 return true;
854
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000855 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000856 != DeclarationName::CXXConversionFunctionName ||
857 R.getLookupName().getCXXNameType()->isDependentType() ||
858 !isa<CXXRecordDecl>(DC))
859 return Found;
860
861 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000862 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000863 // name lookup. Instead, any conversion function templates visible in the
864 // context of the use are considered. [...]
865 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000866 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000867 return Found;
868
Erich Keanec9cb1c12017-06-20 17:38:07 +0000869 // For conversion operators, 'operator auto' should only match
870 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
871 // as a candidate for template substitution.
872 auto *ContainedDeducedType =
873 R.getLookupName().getCXXNameType()->getContainedDeducedType();
874 if (R.getLookupName().getNameKind() ==
875 DeclarationName::CXXConversionFunctionName &&
876 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
877 return Found;
878
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000879 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
880 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000881 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
882 if (!ConvTemplate)
883 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884
Chandler Carruth3a693b72010-01-31 11:44:02 +0000885 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886 // add the conversion function template. When we deduce template
887 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000888 // type of the new declaration with the type of the function template.
889 if (R.isForRedeclaration()) {
890 R.addDecl(ConvTemplate);
891 Found = true;
892 continue;
893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000895 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896 // [...] For each such operator, if argument deduction succeeds
897 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000898 // name lookup.
899 //
900 // When referencing a conversion function for any purpose other than
901 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000902 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000903 // specialization into the result set. We do this to avoid forcing all
904 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000905 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000906 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000907
908 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000909 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
910 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000911
Chandler Carruth3a693b72010-01-31 11:44:02 +0000912 // Compute the type of the function that we would expect the conversion
913 // function to have, if it were to match the name given.
914 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000915 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000916 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000917 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000918 QualType ExpectedType
919 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000920 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000921
Chandler Carruth3a693b72010-01-31 11:44:02 +0000922 // Perform template argument deduction against the type that we would
923 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000924 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000925 Specialization, Info)
926 == Sema::TDK_Success) {
927 R.addDecl(Specialization);
928 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000929 }
930 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000931
John McCall9f3059a2009-10-09 21:13:30 +0000932 return Found;
933}
934
John McCallf6c8a4e2009-11-10 07:01:13 +0000935// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000936static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000937CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000938 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000939
940 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
941
John McCallf6c8a4e2009-11-10 07:01:13 +0000942 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000943 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000944
John McCallf6c8a4e2009-11-10 07:01:13 +0000945 // Perform direct name lookup into the namespaces nominated by the
946 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000947 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
948 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000949 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000950
951 R.resolveKind();
952
953 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000954}
955
956static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000957 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000958 return Ctx->isFileContext();
959 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000960}
Douglas Gregored8f2882009-01-30 01:04:22 +0000961
Douglas Gregor66230062010-03-15 14:33:29 +0000962// Find the next outer declaration context from this scope. This
963// routine actually returns the semantic outer context, which may
964// differ from the lexical context (encoded directly in the Scope
965// stack) when we are parsing a member of a class template. In this
966// case, the second element of the pair will be true, to indicate that
967// name lookup should continue searching in this semantic context when
968// it leaves the current template parameter scope.
969static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000970 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000971 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000973 OuterS = OuterS->getParent()) {
974 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000975 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000976 break;
977 }
978 }
979
980 // C++ [temp.local]p8:
981 // In the definition of a member of a class template that appears
982 // outside of the namespace containing the class template
983 // definition, the name of a template-parameter hides the name of
984 // a member of this namespace.
985 //
986 // Example:
987 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000988 // namespace N {
989 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000990 //
991 // template<class T> class B {
992 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000994 // }
995 //
996 // template<class C> void N::B<C>::f(C) {
997 // C b; // C is the template parameter, not N::C
998 // }
999 //
1000 // In this example, the lexical context we return is the
1001 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001002 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +00001003 !S->getParent()->isTemplateParamScope())
1004 return std::make_pair(Lexical, false);
1005
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +00001007 // For the example, this is the scope for the template parameters of
1008 // template<class C>.
1009 Scope *OutermostTemplateScope = S->getParent();
1010 while (OutermostTemplateScope->getParent() &&
1011 OutermostTemplateScope->getParent()->isTemplateParamScope())
1012 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001013
Douglas Gregor66230062010-03-15 14:33:29 +00001014 // Find the namespace context in which the original scope occurs. In
1015 // the example, this is namespace N.
1016 DeclContext *Semantic = DC;
1017 while (!Semantic->isFileContext())
1018 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019
Douglas Gregor66230062010-03-15 14:33:29 +00001020 // Find the declaration context just outside of the template
1021 // parameter scope. This is the context in which the template is
1022 // being lexically declaration (a namespace context). In the
1023 // example, this is the global scope.
1024 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1025 Lexical->Encloses(Semantic))
1026 return std::make_pair(Semantic, true);
1027
1028 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +00001029}
1030
Richard Smith541b38b2013-09-20 01:15:31 +00001031namespace {
1032/// An RAII object to specify that we want to find block scope extern
1033/// declarations.
1034struct FindLocalExternScope {
1035 FindLocalExternScope(LookupResult &R)
1036 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1037 Decl::IDNS_LocalExtern) {
Eric Fiselier5485cc12017-07-31 00:24:28 +00001038 R.setFindLocalExtern(R.getIdentifierNamespace() &
1039 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
Richard Smith541b38b2013-09-20 01:15:31 +00001040 }
1041 void restore() {
1042 R.setFindLocalExtern(OldFindLocalExtern);
1043 }
1044 ~FindLocalExternScope() {
1045 restore();
1046 }
1047 LookupResult &R;
1048 bool OldFindLocalExtern;
1049};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001050} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +00001051
John McCall27b18f82009-11-17 02:14:36 +00001052bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001053 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +00001054
1055 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +00001056 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +00001057
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001058 // If this is the name of an implicitly-declared special member function,
1059 // go through the scope stack to implicitly declare
1060 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1061 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00001062 if (DeclContext *DC = PreS->getEntity())
Richard Smith32918772017-02-14 00:25:28 +00001063 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001065
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001066 // Implicitly declare member functions with the name we're looking for, if in
1067 // fact we are in a scope where it matters.
1068
Douglas Gregor889ceb72009-02-03 19:21:40 +00001069 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +00001070 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +00001071 I = IdResolver.begin(Name),
1072 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001073
Douglas Gregor889ceb72009-02-03 19:21:40 +00001074 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001075 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +00001076 // ...During unqualified name lookup (3.4.1), the names appear as if
1077 // they were declared in the nearest enclosing namespace which contains
1078 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001079 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001080 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001081 //
1082 // For example:
1083 // namespace A { int i; }
1084 // void foo() {
1085 // int i;
1086 // {
1087 // using namespace A;
1088 // ++i; // finds local 'i', A::i appears at global scope
1089 // }
1090 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001091 //
Richard Smithb920f852017-10-11 01:19:11 +00001092 UnqualUsingDirectiveSet UDirs(*this);
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001093 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001094 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001095 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001096
1097 // When performing a scope lookup, we want to find local extern decls.
1098 FindLocalExternScope FindLocals(R);
1099
Douglas Gregor700792c2009-02-05 19:25:20 +00001100 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001101 DeclContext *Ctx = S->getEntity();
Olivier Goffart12b221982016-06-16 21:39:46 +00001102 bool SearchNamespaceScope = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +00001103 // Check whether the IdResolver has anything in this scope.
John McCall48871652010-08-21 09:40:31 +00001104 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001105 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Olivier Goffart12b221982016-06-16 21:39:46 +00001106 if (NameKind == LookupRedeclarationWithLinkage &&
1107 !(*I)->isTemplateParameter()) {
1108 // If it's a template parameter, we still find it, so we can diagnose
1109 // the invalid redeclaration.
1110
Richard Smith1c34fb72013-08-13 18:18:50 +00001111 // Determine whether this (or a previous) declaration is
1112 // out-of-scope.
1113 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1114 LeftStartingScope = true;
1115
1116 // If we found something outside of our starting scope that
Olivier Goffart12b221982016-06-16 21:39:46 +00001117 // does not have linkage, skip it.
1118 if (LeftStartingScope && !((*I)->hasLinkage())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001119 R.setShadowed();
1120 continue;
1121 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001122 } else {
1123 // We found something in this scope, we should not look at the
1124 // namespace scope
1125 SearchNamespaceScope = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001126 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001127 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001128 }
1129 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001130 if (!SearchNamespaceScope) {
John McCall9f3059a2009-10-09 21:13:30 +00001131 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001132 if (S->isClassScope())
1133 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1134 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001135 return true;
1136 }
1137
Richard Smith1c34fb72013-08-13 18:18:50 +00001138 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001139 // C++11 [class.friend]p11:
1140 // If a friend declaration appears in a local class and the name
1141 // specified is an unqualified name, a prior declaration is
1142 // looked up without considering scopes that are outside the
1143 // innermost enclosing non-class scope.
1144 return false;
1145 }
1146
Douglas Gregor66230062010-03-15 14:33:29 +00001147 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1148 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1149 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001150 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001151 // lexical and semantic declaration contexts returned by
1152 // findOuterContext(). This implements the name lookup behavior
1153 // of C++ [temp.local]p8.
1154 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001155 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001156 }
1157
1158 if (Ctx) {
1159 DeclContext *OuterCtx;
1160 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001161 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001162 if (SearchAfterTemplateScope)
1163 OutsideOfTemplateParamDC = OuterCtx;
1164
Douglas Gregorea166062010-03-15 15:26:48 +00001165 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001166 // We do not directly look into transparent contexts, since
1167 // those entities will be found in the nearest enclosing
1168 // non-transparent context.
1169 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001170 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001171
1172 // We do not look directly into function or method contexts,
1173 // since all of the local variables and parameters of the
1174 // function/method are present within the Scope.
1175 if (Ctx->isFunctionOrMethod()) {
1176 // If we have an Objective-C instance method, look for ivars
1177 // in the corresponding interface.
1178 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1179 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1180 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1181 ObjCInterfaceDecl *ClassDeclared;
1182 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001184 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001185 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1186 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001187 R.resolveKind();
1188 return true;
1189 }
1190 }
1191 }
1192 }
1193
1194 continue;
1195 }
1196
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001197 // If this is a file context, we need to perform unqualified name
1198 // lookup considering using directives.
1199 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001200 // If we haven't handled using directives yet, do so now.
1201 if (!VisitedUsingDirectives) {
1202 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001203 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1204 if (UCtx->isTransparentContext())
1205 continue;
1206
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001207 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001208 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001209
1210 // Find the innermost file scope, so we can add using directives
1211 // from local scopes.
1212 Scope *InnermostFileScope = S;
1213 while (InnermostFileScope &&
1214 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1215 InnermostFileScope = InnermostFileScope->getParent();
1216 UDirs.visitScopeChain(Initial, InnermostFileScope);
1217
1218 UDirs.done();
1219
1220 VisitedUsingDirectives = true;
1221 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001222
1223 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1224 R.resolveKind();
1225 return true;
1226 }
1227
1228 continue;
1229 }
1230
Douglas Gregor7f737c02009-09-10 16:57:35 +00001231 // Perform qualified name lookup into this context.
1232 // FIXME: In some cases, we know that every name that could be found by
1233 // this qualified name lookup will also be on the identifier chain. For
1234 // example, inside a class without any base classes, we never need to
1235 // perform qualified lookup because all of the members are on top of the
1236 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001237 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001238 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001239 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001240 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001241 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001242
John McCallf6c8a4e2009-11-10 07:01:13 +00001243 // Stop if we ran out of scopes.
1244 // FIXME: This really, really shouldn't be happening.
1245 if (!S) return false;
1246
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001247 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001248 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001249 return false;
1250
Douglas Gregor700792c2009-02-05 19:25:20 +00001251 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001252 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001253 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001254 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1255 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001256 if (!VisitedUsingDirectives) {
1257 UDirs.visitScopeChain(Initial, S);
1258 UDirs.done();
1259 }
Richard Smith541b38b2013-09-20 01:15:31 +00001260
1261 // If we're not performing redeclaration lookup, do not look for local
1262 // extern declarations outside of a function scope.
1263 if (!R.isForRedeclaration())
1264 FindLocals.restore();
1265
Douglas Gregor700792c2009-02-05 19:25:20 +00001266 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001267 // Unqualified name lookup in C++ requires looking into scopes
1268 // that aren't strictly lexical, and therefore we walk through the
1269 // context as well as walking through the scopes.
1270 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001271 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001272 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001273 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001274 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001275 // We found something. Look for anything else in our scope
1276 // with this same name and in an acceptable identifier
1277 // namespace, so that we can construct an overload set if we
1278 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001279 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001280 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001281 }
1282 }
1283
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001284 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001285 R.resolveKind();
1286 return true;
1287 }
1288
Ted Kremenekc37877d2013-10-08 17:08:03 +00001289 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001290 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1291 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1292 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001293 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001294 // lexical and semantic declaration contexts returned by
1295 // findOuterContext(). This implements the name lookup behavior
1296 // of C++ [temp.local]p8.
1297 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001298 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001299 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001300
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001301 if (Ctx) {
1302 DeclContext *OuterCtx;
1303 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001304 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001305 if (SearchAfterTemplateScope)
1306 OutsideOfTemplateParamDC = OuterCtx;
1307
1308 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1309 // We do not directly look into transparent contexts, since
1310 // those entities will be found in the nearest enclosing
1311 // non-transparent context.
1312 if (Ctx->isTransparentContext())
1313 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001314
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001315 // If we have a context, and it's not a context stashed in the
1316 // template parameter scope for an out-of-line definition, also
1317 // look into that context.
Chandler Carruth6232e4d2016-11-04 06:16:09 +00001318 if (!(Found && S->isTemplateParamScope())) {
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001319 assert(Ctx->isFileContext() &&
1320 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001322 // Look into context considering using-directives.
1323 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1324 Found = true;
1325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001326
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001327 if (Found) {
1328 R.resolveKind();
1329 return true;
1330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001331
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001332 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1333 return false;
1334 }
1335 }
1336
Douglas Gregor3ce74932010-02-05 07:07:10 +00001337 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001338 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001339 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001340
John McCall9f3059a2009-10-09 21:13:30 +00001341 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001342}
1343
Richard Smith858e0e02017-05-11 23:11:16 +00001344void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1345 if (auto *M = getCurrentModule())
Richard Smith87bb5692015-06-09 00:35:49 +00001346 Context.mergeDefinitionIntoModule(ND, M);
1347 else
1348 // We're not building a module; just make the definition visible.
Richard Smith90dc5252017-06-23 01:04:34 +00001349 ND->setVisibleDespiteOwningModule();
Richard Smith63e09bf2015-06-17 20:39:41 +00001350
1351 // If ND is a template declaration, make the template parameters
1352 // visible too. They're not (necessarily) within a mergeable DeclContext.
1353 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1354 for (auto *Param : *TD->getTemplateParameters())
Richard Smith858e0e02017-05-11 23:11:16 +00001355 makeMergedDefinitionVisible(Param);
Richard Smithd9ba2242015-05-07 03:54:19 +00001356}
1357
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001358/// Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001359static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001360 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1361 // If this function was instantiated from a template, the defining module is
1362 // the module containing the pattern.
1363 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1364 Entity = Pattern;
1365 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001366 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1367 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001368 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
Richard Smith2195ec92017-04-21 01:15:13 +00001369 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1370 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001371 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
Richard Smith2195ec92017-04-21 01:15:13 +00001372 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1373 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001374 }
1375
Chandler Carruthbd186c02017-04-19 05:25:13 +00001376 // Walk up to the containing context. That might also have been instantiated
1377 // from a template.
Richard Smith17ad3ac2017-10-18 01:41:38 +00001378 DeclContext *Context = Entity->getLexicalDeclContext();
Chandler Carruthbd186c02017-04-19 05:25:13 +00001379 if (Context->isFileContext())
1380 return S.getOwningModule(Entity);
1381 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001382}
1383
1384llvm::DenseSet<Module*> &Sema::getLookupModules() {
Richard Smith696e3122017-02-23 01:43:54 +00001385 unsigned N = CodeSynthesisContexts.size();
1386 for (unsigned I = CodeSynthesisContextLookupModules.size();
Richard Smith0e5d7b82013-07-25 23:08:39 +00001387 I != N; ++I) {
Richard Smith696e3122017-02-23 01:43:54 +00001388 Module *M = getDefiningModule(*this, CodeSynthesisContexts[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001389 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001390 M = nullptr;
Richard Smith696e3122017-02-23 01:43:54 +00001391 CodeSynthesisContextLookupModules.push_back(M);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001392 }
1393 return LookupModulesCache;
1394}
1395
Richard Smithc4577662018-09-12 02:13:47 +00001396/// Determine whether the module M is part of the current module from the
1397/// perspective of a module-private visibility check.
1398static bool isInCurrentModule(const Module *M, const LangOptions &LangOpts) {
1399 // If M is the global module fragment of a module that we've not yet finished
1400 // parsing, then it must be part of the current module.
1401 return M->getTopLevelModuleName() == LangOpts.CurrentModule ||
1402 (M->Kind == Module::GlobalModuleFragment && !M->Parent);
1403}
1404
Richard Smith42413142015-05-15 20:05:43 +00001405bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
Richard Smithc4577662018-09-12 02:13:47 +00001406 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
Richard Smith42413142015-05-15 20:05:43 +00001407 if (isModuleVisible(Merged))
1408 return true;
1409 return false;
1410}
1411
Richard Smithe03a6542017-07-05 01:42:07 +00001412bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
Richard Smithc4577662018-09-12 02:13:47 +00001413 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1414 if (isInCurrentModule(Merged, getLangOpts()))
Richard Smithe03a6542017-07-05 01:42:07 +00001415 return true;
1416 return false;
1417}
1418
Richard Smithe7bd6de2015-06-10 20:30:23 +00001419template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001420static bool
1421hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1422 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001423 if (!D->hasDefaultArgument())
1424 return false;
1425
1426 while (D) {
1427 auto &DefaultArg = D->getDefaultArgStorage();
1428 if (!DefaultArg.isInherited() && S.isVisible(D))
1429 return true;
1430
Richard Smith63e09bf2015-06-17 20:39:41 +00001431 if (!DefaultArg.isInherited() && Modules) {
1432 auto *NonConstD = const_cast<ParmDecl*>(D);
1433 Modules->push_back(S.getOwningModule(NonConstD));
Richard Smith63e09bf2015-06-17 20:39:41 +00001434 }
Richard Smith35c1df52015-06-17 20:16:32 +00001435
Richard Smithe7bd6de2015-06-10 20:30:23 +00001436 // If there was a previous default argument, maybe its parameter is visible.
1437 D = DefaultArg.getInheritedFrom();
1438 }
1439 return false;
1440}
1441
Richard Smith35c1df52015-06-17 20:16:32 +00001442bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1443 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001444 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001445 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001446 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001447 return ::hasVisibleDefaultArgument(*this, P, Modules);
1448 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1449 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001450}
1451
Richard Smith54f04402017-05-18 02:29:20 +00001452template<typename Filter>
1453static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
1454 llvm::SmallVectorImpl<Module *> *Modules,
1455 Filter F) {
Richard Trieu81536282018-06-07 03:20:30 +00001456 bool HasFilteredRedecls = false;
1457
Richard Smith54f04402017-05-18 02:29:20 +00001458 for (auto *Redecl : D->redecls()) {
1459 auto *R = cast<NamedDecl>(Redecl);
1460 if (!F(R))
1461 continue;
1462
1463 if (S.isVisible(R))
1464 return true;
1465
Richard Trieu81536282018-06-07 03:20:30 +00001466 HasFilteredRedecls = true;
1467
Richard Smithc4577662018-09-12 02:13:47 +00001468 if (Modules)
Richard Smith54f04402017-05-18 02:29:20 +00001469 Modules->push_back(R->getOwningModule());
Richard Smith54f04402017-05-18 02:29:20 +00001470 }
1471
Richard Trieu81536282018-06-07 03:20:30 +00001472 // Only return false if there is at least one redecl that is not filtered out.
1473 if (HasFilteredRedecls)
1474 return false;
1475
1476 return true;
Richard Smith54f04402017-05-18 02:29:20 +00001477}
1478
1479bool Sema::hasVisibleExplicitSpecialization(
1480 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1481 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1482 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1483 return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1484 if (auto *FD = dyn_cast<FunctionDecl>(D))
1485 return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1486 if (auto *VD = dyn_cast<VarDecl>(D))
1487 return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1488 llvm_unreachable("unknown explicit specialization kind");
1489 });
1490}
1491
Richard Smith6739a102016-05-05 00:56:12 +00001492bool Sema::hasVisibleMemberSpecialization(
1493 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1494 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1495 "not a member specialization");
Richard Smith54f04402017-05-18 02:29:20 +00001496 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
Richard Smith6739a102016-05-05 00:56:12 +00001497 // If the specialization is declared at namespace scope, then it's a member
1498 // specialization declaration. If it's lexically inside the class
1499 // definition then it was instantiated.
1500 //
1501 // FIXME: This is a hack. There should be a better way to determine this.
1502 // FIXME: What about MS-style explicit specializations declared within a
1503 // class definition?
Richard Smith54f04402017-05-18 02:29:20 +00001504 return D->getLexicalDeclContext()->isFileContext();
1505 });
Richard Smith6739a102016-05-05 00:56:12 +00001506}
1507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001508/// Determine whether a declaration is visible to name lookup.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001509///
1510/// This routine determines whether the declaration D is visible in the current
1511/// lookup context, taking into account the current template instantiation
1512/// stack. During template instantiation, a declaration is visible if it is
1513/// visible from a module containing any entity on the template instantiation
1514/// path (by instantiating a template, you allow it to see the declarations that
1515/// your module can see, including those later on in your module).
1516bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001517 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001518
Richard Smith54f04402017-05-18 02:29:20 +00001519 Module *DeclModule = SemaRef.getOwningModule(D);
Richard Smithc4577662018-09-12 02:13:47 +00001520 assert(DeclModule && "hidden decl has no owning module");
1521
1522 // If the owning module is visible, the decl is visible.
1523 if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
1524 return true;
Richard Smith54f04402017-05-18 02:29:20 +00001525
Richard Smithd19389a2017-07-05 07:47:11 +00001526 // Determine whether a decl context is a file context for the purpose of
1527 // visibility. This looks through some (export and linkage spec) transparent
1528 // contexts, but not others (enums).
1529 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1530 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1531 isa<ExportDecl>(DC);
1532 };
Richard Smith0e5d7b82013-07-25 23:08:39 +00001533
Richard Smithd19389a2017-07-05 07:47:11 +00001534 // If this declaration is not at namespace scope
Richard Smithbe3980b2015-03-27 00:41:57 +00001535 // then it is visible if its lexical parent has a visible definition.
1536 DeclContext *DC = D->getLexicalDeclContext();
Richard Smithd19389a2017-07-05 07:47:11 +00001537 if (DC && !IsEffectivelyFileContext(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001538 // For a parameter, check whether our current template declaration's
1539 // lexical context is visible, not whether there's some other visible
1540 // definition of it, because parameters aren't "within" the definition.
Vassil Vassilev714b81c2016-09-08 20:34:41 +00001541 //
1542 // In C++ we need to check for a visible definition due to ODR merging,
1543 // and in C we must not because each declaration of a function gets its own
1544 // set of declarations for tags in prototype scope.
Richard Smithd19389a2017-07-05 07:47:11 +00001545 bool VisibleWithinParent;
1546 if (D->isTemplateParameter() || isa<ParmVarDecl>(D) ||
1547 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1548 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1549 else if (D->isModulePrivate()) {
1550 // A module-private declaration is only visible if an enclosing lexical
1551 // parent was merged with another definition in the current module.
1552 VisibleWithinParent = false;
1553 do {
1554 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1555 VisibleWithinParent = true;
1556 break;
1557 }
1558 DC = DC->getLexicalParent();
1559 } while (!IsEffectivelyFileContext(DC));
1560 } else {
1561 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
Richard Smithbe3980b2015-03-27 00:41:57 +00001562 }
Richard Smithd19389a2017-07-05 07:47:11 +00001563
1564 if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1565 // FIXME: Do something better in this case.
1566 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1567 // Cache the fact that this declaration is implicitly visible because
1568 // its parent has a visible definition.
1569 D->setVisibleDespiteOwningModule();
1570 }
1571 return VisibleWithinParent;
Richard Smithbe3980b2015-03-27 00:41:57 +00001572 }
1573
Richard Smithc4577662018-09-12 02:13:47 +00001574 return false;
1575}
1576
1577bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1578 // The module might be ordinarily visible. For a module-private query, that
1579 // means it is part of the current module. For any other query, that means it
1580 // is in our visible module set.
1581 if (ModulePrivate) {
1582 if (isInCurrentModule(M, getLangOpts()))
1583 return true;
1584 } else {
1585 if (VisibleModules.isVisible(M))
1586 return true;
1587 }
1588
1589 // Otherwise, it might be visible by virtue of the query being within a
1590 // template instantiation or similar that is permitted to look inside M.
Richard Smithd19389a2017-07-05 07:47:11 +00001591
Richard Smith0e5d7b82013-07-25 23:08:39 +00001592 // Find the extra places where we need to look.
Richard Smithc4577662018-09-12 02:13:47 +00001593 const auto &LookupModules = getLookupModules();
Richard Smith0e5d7b82013-07-25 23:08:39 +00001594 if (LookupModules.empty())
1595 return false;
1596
Richard Smithc4577662018-09-12 02:13:47 +00001597 // If our lookup set contains the module, it's visible.
1598 if (LookupModules.count(M))
Richard Smith0e5d7b82013-07-25 23:08:39 +00001599 return true;
1600
Richard Smithc4577662018-09-12 02:13:47 +00001601 // For a module-private query, that's everywhere we get to look.
1602 if (ModulePrivate)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001603 return false;
1604
Richard Smithc4577662018-09-12 02:13:47 +00001605 // Check whether M is transitively exported to an import of the lookup set.
Fangrui Song3117b172018-10-20 17:53:42 +00001606 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1607 return LookupM->isModuleVisible(M);
1608 });
Richard Smith0e5d7b82013-07-25 23:08:39 +00001609}
1610
Richard Smith42413142015-05-15 20:05:43 +00001611bool Sema::isVisibleSlow(const NamedDecl *D) {
1612 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1613}
1614
Richard Smith10568d82015-11-17 03:02:41 +00001615bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
Richard Smithbecb92d2017-10-10 22:33:17 +00001616 // FIXME: If there are both visible and hidden declarations, we need to take
1617 // into account whether redeclaration is possible. Example:
Fangrui Song6907ce22018-07-30 19:24:48 +00001618 //
Richard Smithbecb92d2017-10-10 22:33:17 +00001619 // Non-imported module:
1620 // int f(T); // #1
1621 // Some TU:
1622 // static int f(U); // #2, not a redeclaration of #1
1623 // int f(T); // #3, finds both, should link with #1 if T != U, but
1624 // // with #2 if T == U; neither should be ambiguous.
Richard Smith10568d82015-11-17 03:02:41 +00001625 for (auto *D : R) {
1626 if (isVisible(D))
1627 return true;
Richard Smithbecb92d2017-10-10 22:33:17 +00001628 assert(D->isExternallyDeclarable() &&
1629 "should not have hidden, non-externally-declarable result here");
Richard Smith10568d82015-11-17 03:02:41 +00001630 }
Richard Smithbecb92d2017-10-10 22:33:17 +00001631
1632 // This function is called once "New" is essentially complete, but before a
1633 // previous declaration is attached. We can't query the linkage of "New" in
1634 // general, because attaching the previous declaration can change the
1635 // linkage of New to match the previous declaration.
1636 //
1637 // However, because we've just determined that there is no *visible* prior
1638 // declaration, we can compute the linkage here. There are two possibilities:
1639 //
1640 // * This is not a redeclaration; it's safe to compute the linkage now.
1641 //
1642 // * This is a redeclaration of a prior declaration that is externally
1643 // redeclarable. In that case, the linkage of the declaration is not
1644 // changed by attaching the prior declaration, because both are externally
1645 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
1646 //
1647 // FIXME: This is subtle and fragile.
1648 return New->isExternallyDeclarable();
Richard Smith10568d82015-11-17 03:02:41 +00001649}
1650
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001651/// Retrieve the visible declaration corresponding to D, if any.
Douglas Gregor4a814562011-12-14 16:03:29 +00001652///
1653/// This routine determines whether the declaration D is visible in the current
1654/// module, with the current imports. If not, it checks whether any
1655/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001656///
Douglas Gregor4a814562011-12-14 16:03:29 +00001657/// \returns D, or a visible previous declaration of D, whichever is more recent
1658/// and visible. If no declaration of D is visible, returns null.
Richard Smith041740f2018-01-06 00:09:23 +00001659static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
1660 unsigned IDNS) {
Richard Smithe156254d2013-08-20 20:35:18 +00001661 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001662
Aaron Ballman86c93902014-03-06 23:45:36 +00001663 for (auto RD : D->redecls()) {
Richard Smith4083e032016-02-17 21:52:44 +00001664 // Don't bother with extra checks if we already know this one isn't visible.
1665 if (RD == D)
1666 continue;
1667
Richard Smith6739a102016-05-05 00:56:12 +00001668 auto ND = cast<NamedDecl>(RD);
1669 // FIXME: This is wrong in the case where the previous declaration is not
1670 // visible in the same scope as D. This needs to be done much more
1671 // carefully.
Richard Smith041740f2018-01-06 00:09:23 +00001672 if (ND->isInIdentifierNamespace(IDNS) &&
1673 LookupResult::isVisible(SemaRef, ND))
Richard Smith6739a102016-05-05 00:56:12 +00001674 return ND;
Douglas Gregor4a814562011-12-14 16:03:29 +00001675 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001676
Craig Topperc3ec1492014-05-26 06:22:03 +00001677 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001678}
1679
Richard Smith6739a102016-05-05 00:56:12 +00001680bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1681 llvm::SmallVectorImpl<Module *> *Modules) {
1682 assert(!isVisible(D) && "not in slow case");
Richard Smith54f04402017-05-18 02:29:20 +00001683 return hasVisibleDeclarationImpl(*this, D, Modules,
1684 [](const NamedDecl *) { return true; });
Richard Smith6739a102016-05-05 00:56:12 +00001685}
1686
Richard Smithe156254d2013-08-20 20:35:18 +00001687NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Richard Smith4083e032016-02-17 21:52:44 +00001688 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1689 // Namespaces are a bit of a special case: we expect there to be a lot of
1690 // redeclarations of some namespaces, all declarations of a namespace are
1691 // essentially interchangeable, all declarations are found by name lookup
1692 // if any is, and namespaces are never looked up during template
1693 // instantiation. So we benefit from caching the check in this case, and
1694 // it is correct to do so.
1695 auto *Key = ND->getCanonicalDecl();
1696 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1697 return Acceptable;
Richard Smith041740f2018-01-06 00:09:23 +00001698 auto *Acceptable = isVisible(getSema(), Key)
1699 ? Key
1700 : findAcceptableDecl(getSema(), Key, IDNS);
Richard Smith4083e032016-02-17 21:52:44 +00001701 if (Acceptable)
1702 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1703 return Acceptable;
1704 }
1705
Richard Smith041740f2018-01-06 00:09:23 +00001706 return findAcceptableDecl(getSema(), D, IDNS);
Richard Smithe156254d2013-08-20 20:35:18 +00001707}
1708
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001709/// Perform unqualified name lookup starting from a given
Douglas Gregor34074322009-01-14 22:20:51 +00001710/// scope.
1711///
1712/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1713/// used to find names within the current scope. For example, 'x' in
1714/// @code
1715/// int x;
1716/// int f() {
1717/// return x; // unqualified name look finds 'x' in the global scope
1718/// }
1719/// @endcode
1720///
1721/// Different lookup criteria can find different names. For example, a
1722/// particular scope can have both a struct and a function of the same
1723/// name, and each can be found by certain lookup criteria. For more
1724/// information about lookup criteria, see the documentation for the
1725/// class LookupCriteria.
1726///
1727/// @param S The scope from which unqualified name lookup will
1728/// begin. If the lookup criteria permits, name lookup may also search
1729/// in the parent scopes.
1730///
James Dennett91738ff2012-06-22 10:32:46 +00001731/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1732/// look up and the lookup kind), and is updated with the results of lookup
1733/// including zero or more declarations and possibly additional information
1734/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001735///
James Dennett91738ff2012-06-22 10:32:46 +00001736/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001737bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1738 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001739 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001740
John McCall27b18f82009-11-17 02:14:36 +00001741 LookupNameKind NameKind = R.getLookupKind();
1742
David Blaikiebbafb8a2012-03-11 07:00:24 +00001743 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001744 // Unqualified name lookup in C/Objective-C is purely lexical, so
1745 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001746 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001747 // Find the nearest non-transparent declaration scope.
1748 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001749 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001750 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001751 }
1752
Richard Smith541b38b2013-09-20 01:15:31 +00001753 // When performing a scope lookup, we want to find local extern decls.
1754 FindLocalExternScope FindLocals(R);
1755
Douglas Gregor34074322009-01-14 22:20:51 +00001756 // Scan up the scope chain looking for a decl that matches this
1757 // identifier that is in the appropriate namespace. This search
1758 // should not take long, as shadowing of names is uncommon, and
1759 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001760 bool LeftStartingScope = false;
1761
Douglas Gregored8f2882009-01-30 01:04:22 +00001762 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001763 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001764 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001765 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001766 if (NameKind == LookupRedeclarationWithLinkage) {
1767 // Determine whether this (or a previous) declaration is
1768 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001769 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001770 LeftStartingScope = true;
1771
1772 // If we found something outside of our starting scope that
1773 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001774 if (LeftStartingScope && !((*I)->hasLinkage())) {
1775 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001776 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001777 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001778 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001779 else if (NameKind == LookupObjCImplicitSelfParam &&
1780 !isa<ImplicitParamDecl>(*I))
1781 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001782
Douglas Gregor4a814562011-12-14 16:03:29 +00001783 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001784
Douglas Gregorb59643b2012-01-03 23:26:26 +00001785 // Check whether there are any other declarations with the same name
1786 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001787 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001788 // Find the scope in which this declaration was declared (if it
1789 // actually exists in a Scope).
1790 while (S && !S->isDeclScope(D))
1791 S = S->getParent();
Fangrui Song6907ce22018-07-30 19:24:48 +00001792
Douglas Gregor81bd0382012-01-13 23:06:53 +00001793 // If the scope containing the declaration is the translation unit,
1794 // then we'll need to perform our checks based on the matching
1795 // DeclContexts rather than matching scopes.
1796 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001797 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001798
1799 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001800 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001801 if (!S)
1802 DC = (*I)->getDeclContext()->getRedeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00001803
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001804 IdentifierResolver::iterator LastI = I;
1805 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001806 if (S) {
1807 // Match based on scope.
1808 if (!S->isDeclScope(*LastI))
1809 break;
1810 } else {
1811 // Match based on DeclContext.
Fangrui Song6907ce22018-07-30 19:24:48 +00001812 DeclContext *LastDC
Douglas Gregor81bd0382012-01-13 23:06:53 +00001813 = (*LastI)->getDeclContext()->getRedeclContext();
1814 if (!LastDC->Equals(DC))
1815 break;
1816 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001817
1818 // If the declaration is in the right namespace and visible, add it.
1819 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1820 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001821 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001822
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001823 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001824 }
Richard Smith541b38b2013-09-20 01:15:31 +00001825
John McCall9f3059a2009-10-09 21:13:30 +00001826 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001827 }
Douglas Gregor34074322009-01-14 22:20:51 +00001828 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001829 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001830 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001831 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001832 }
1833
1834 // If we didn't find a use of this identifier, and if the identifier
1835 // corresponds to a compiler builtin, create the decl object for the builtin
1836 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001837 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1838 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001839
Fangrui Song6907ce22018-07-30 19:24:48 +00001840 // If we didn't find a use of this identifier, the ExternalSource
1841 // may be able to handle the situation.
Axel Naumann016538a2011-02-24 16:47:47 +00001842 // Note: some lookup failures are expected!
1843 // See e.g. R.isForRedeclaration().
1844 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001845}
1846
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001847/// Perform qualified name lookup in the namespaces nominated by
John McCall6538c932009-10-10 05:48:19 +00001848/// using directives by the given context.
1849///
1850/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001851/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001852/// (where X is the global namespace), let S be the set of all
1853/// declarations of m in X and in the transitive closure of all
1854/// namespaces nominated by using-directives in X and its used
1855/// namespaces, except that using-directives are ignored in any
1856/// namespace, including X, directly containing one or more
1857/// declarations of m. No namespace is searched more than once in
1858/// the lookup of a name. If S is the empty set, the program is
1859/// ill-formed. Otherwise, if S has exactly one member, or if the
1860/// context of the reference is a using-declaration
1861/// (namespace.udecl), S is the required set of declarations of
1862/// m. Otherwise if the use of m is not one that allows a unique
1863/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001864///
John McCall6538c932009-10-10 05:48:19 +00001865/// C++98 [namespace.qual]p5:
1866/// During the lookup of a qualified namespace member name, if the
1867/// lookup finds more than one declaration of the member, and if one
1868/// declaration introduces a class name or enumeration name and the
1869/// other declarations either introduce the same object, the same
1870/// enumerator or a set of functions, the non-type name hides the
1871/// class or enumeration name if and only if the declarations are
1872/// from the same namespace; otherwise (the declarations are from
1873/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001874static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001875 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001876 assert(StartDC->isFileContext() && "start context is not a file context");
1877
Richard Smithb920f852017-10-11 01:19:11 +00001878 // We have not yet looked into these namespaces, much less added
1879 // their "using-children" to the queue.
1880 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001881
1882 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001883 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001884 Visited.insert(StartDC);
1885
John McCall6538c932009-10-10 05:48:19 +00001886 // We have already looked into the initial namespace; seed the queue
1887 // with its using-children.
Richard Smithb920f852017-10-11 01:19:11 +00001888 for (auto *I : StartDC->using_directives()) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001889 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Richard Smitha544c512017-10-30 22:38:20 +00001890 if (S.isVisible(I) && Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001891 Queue.push_back(ND);
1892 }
1893
1894 // The easiest way to implement the restriction in [namespace.qual]p5
1895 // is to check whether any of the individual results found a tag
1896 // and, if so, to declare an ambiguity if the final result is not
1897 // a tag.
1898 bool FoundTag = false;
1899 bool FoundNonTag = false;
1900
John McCall5cebab12009-11-18 07:57:50 +00001901 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001902
1903 bool Found = false;
1904 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001905 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001906
1907 // We go through some convolutions here to avoid copying results
1908 // between LookupResults.
1909 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001910 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001911 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001912
1913 if (FoundDirect) {
1914 // First do any local hiding.
1915 DirectR.resolveKind();
1916
1917 // If the local result is a tag, remember that.
1918 if (DirectR.isSingleTagDecl())
1919 FoundTag = true;
1920 else
1921 FoundNonTag = true;
1922
1923 // Append the local results to the total results if necessary.
1924 if (UseLocal) {
1925 R.addAllDecls(LocalR);
1926 LocalR.clear();
1927 }
1928 }
1929
1930 // If we find names in this namespace, ignore its using directives.
1931 if (FoundDirect) {
1932 Found = true;
1933 continue;
1934 }
1935
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001936 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001937 NamespaceDecl *Nom = I->getNominatedNamespace();
Richard Smitha544c512017-10-30 22:38:20 +00001938 if (S.isVisible(I) && Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001939 Queue.push_back(Nom);
1940 }
1941 }
1942
1943 if (Found) {
1944 if (FoundTag && FoundNonTag)
1945 R.setAmbiguousQualifiedTagHiding();
1946 else
1947 R.resolveKind();
1948 }
1949
1950 return Found;
1951}
1952
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001953/// Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001955 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001956 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001958 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001959 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001960}
1961
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001962/// Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001963/// static members, nested types, and enumerators.
1964template<typename InputIterator>
1965static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1966 Decl *D = (*First)->getUnderlyingDecl();
1967 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1968 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969
Douglas Gregorc0d24902010-10-22 22:08:47 +00001970 if (isa<CXXMethodDecl>(D)) {
1971 // Determine whether all of the methods are static.
1972 bool AllMethodsAreStatic = true;
1973 for(; First != Last; ++First) {
1974 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975
Douglas Gregorc0d24902010-10-22 22:08:47 +00001976 if (!isa<CXXMethodDecl>(D)) {
1977 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1978 break;
1979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Douglas Gregorc0d24902010-10-22 22:08:47 +00001981 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1982 AllMethodsAreStatic = false;
1983 break;
1984 }
1985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Douglas Gregorc0d24902010-10-22 22:08:47 +00001987 if (AllMethodsAreStatic)
1988 return true;
1989 }
1990
1991 return false;
1992}
1993
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001994/// Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001995///
1996/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1997/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001998/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001999///
2000/// Different lookup criteria can find different names. For example, a
2001/// particular scope can have both a struct and a function of the same
2002/// name, and each can be found by certain lookup criteria. For more
2003/// information about lookup criteria, see the documentation for the
2004/// class LookupCriteria.
2005///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002006/// \param R captures both the lookup criteria and any lookup results found.
2007///
2008/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00002009/// search. If the lookup criteria permits, name lookup may also search
2010/// in the parent contexts or (for C++ classes) base classes.
2011///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002012/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002013/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00002014///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002015/// \returns true if lookup succeeded, false if it failed.
2016bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2017 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00002018 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00002019
John McCall27b18f82009-11-17 02:14:36 +00002020 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00002021 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002023 // Make sure that the declaration context is complete.
2024 assert((!isa<TagDecl>(LookupCtx) ||
2025 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00002026 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00002027 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002028 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00002029
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002030 struct QualifiedLookupInScope {
2031 bool oldVal;
2032 DeclContext *Context;
2033 // Set flag in DeclContext informing debugger that we're looking for qualified name
Fangrui Song6907ce22018-07-30 19:24:48 +00002034 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2035 oldVal = ctx->setUseQualifiedLookup();
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002036 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002037 ~QualifiedLookupInScope() {
2038 Context->setUseQualifiedLookup(oldVal);
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002039 }
2040 } QL(LookupCtx);
2041
Douglas Gregord3a59182010-02-12 05:48:04 +00002042 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00002043 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00002044 if (isa<CXXRecordDecl>(LookupCtx))
2045 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00002046 return true;
2047 }
Douglas Gregor34074322009-01-14 22:20:51 +00002048
John McCall6538c932009-10-10 05:48:19 +00002049 // Don't descend into implied contexts for redeclarations.
2050 // C++98 [namespace.qual]p6:
2051 // In a declaration for a namespace member in which the
2052 // declarator-id is a qualified-id, given that the qualified-id
2053 // for the namespace member has the form
2054 // nested-name-specifier unqualified-id
2055 // the unqualified-id shall name a member of the namespace
2056 // designated by the nested-name-specifier.
2057 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00002058 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00002059 return false;
2060
John McCall27b18f82009-11-17 02:14:36 +00002061 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00002062 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00002063 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00002064
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002065 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00002066 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002067 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00002068 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00002069 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002070
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002071 // If we're performing qualified name lookup into a dependent class,
2072 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002073 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002074 // template instantiation time (at which point all bases will be available)
2075 // or we have to fail.
2076 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2077 LookupRec->hasAnyDependentBases()) {
2078 R.setNotFoundInCurrentInstantiation();
2079 return false;
2080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002082 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002083 CXXBasePaths Paths;
2084 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002085
2086 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002087 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2088 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00002089 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002090 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002091 case LookupOrdinaryName:
2092 case LookupMemberName:
2093 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00002094 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002095 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2096 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097
Douglas Gregor36d1b142009-10-06 17:59:45 +00002098 case LookupTagName:
2099 BaseCallback = &CXXRecordDecl::FindTagMember;
2100 break;
John McCall84d87672009-12-10 09:41:52 +00002101
Douglas Gregor39982192010-08-15 06:18:01 +00002102 case LookupAnyName:
2103 BaseCallback = &LookupAnyMember;
2104 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002106 case LookupOMPReductionName:
2107 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2108 break;
2109
Michael Kruse251e1482019-02-01 20:25:04 +00002110 case LookupOMPMapperName:
2111 BaseCallback = &CXXRecordDecl::FindOMPMapperMember;
2112 break;
2113
John McCall84d87672009-12-10 09:41:52 +00002114 case LookupUsingDeclName:
2115 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002116
Douglas Gregor36d1b142009-10-06 17:59:45 +00002117 case LookupOperatorName:
2118 case LookupNamespaceName:
2119 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002120 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002121 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00002122 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123
Douglas Gregor36d1b142009-10-06 17:59:45 +00002124 case LookupNestedNameSpecifierName:
2125 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2126 break;
2127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002129 DeclarationName Name = R.getLookupName();
2130 if (!LookupRec->lookupInBases(
2131 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2132 return BaseCallback(Specifier, Path, Name);
2133 },
2134 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00002135 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002136
John McCall553c0792010-01-23 00:46:32 +00002137 R.setNamingClass(LookupRec);
2138
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002139 // C++ [class.member.lookup]p2:
2140 // [...] If the resulting set of declarations are not all from
2141 // sub-objects of the same type, or the set has a nonstatic member
2142 // and includes members from distinct sub-objects, there is an
2143 // ambiguity and the program is ill-formed. Otherwise that set is
2144 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002145 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002146 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00002147 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148
Douglas Gregor36d1b142009-10-06 17:59:45 +00002149 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002150 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002151 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002152
John McCall401982f2010-01-20 21:53:11 +00002153 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2154 // across all paths.
2155 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002157 // Determine whether we're looking at a distinct sub-object or not.
2158 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00002159 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002160 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2161 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00002162 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163 }
2164
Douglas Gregorc0d24902010-10-22 22:08:47 +00002165 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002166 != Context.getCanonicalType(PathElement.Base->getType())) {
2167 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002168 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002169 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002170 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002171 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002172 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2173 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002174
Richard Smithafcfb6b2019-02-15 21:53:07 +00002175 // Get the decl that we should use for deduplicating this lookup.
2176 auto GetRepresentativeDecl = [&](NamedDecl *D) -> Decl * {
2177 // C++ [temp.local]p3:
2178 // A lookup that finds an injected-class-name (10.2) can result in
2179 // an ambiguity in certain cases (for example, if it is found in
2180 // more than one base class). If all of the injected-class-names
2181 // that are found refer to specializations of the same class
2182 // template, and if the name is used as a template-name, the
2183 // reference refers to the class template itself and not a
2184 // specialization thereof, and is not ambiguous.
2185 if (R.isTemplateNameLookup())
2186 if (auto *TD = getAsTemplateNameDecl(D))
2187 D = TD;
2188 return D->getUnderlyingDecl()->getCanonicalDecl();
2189 };
2190
David Blaikieff7d47a2012-12-19 00:45:41 +00002191 while (FirstD != FirstPath->Decls.end() &&
2192 CurrentD != Path->Decls.end()) {
Richard Smithafcfb6b2019-02-15 21:53:07 +00002193 if (GetRepresentativeDecl(*FirstD) !=
2194 GetRepresentativeDecl(*CurrentD))
2195 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196
Douglas Gregorc0d24902010-10-22 22:08:47 +00002197 ++FirstD;
2198 ++CurrentD;
2199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200
David Blaikieff7d47a2012-12-19 00:45:41 +00002201 if (FirstD == FirstPath->Decls.end() &&
2202 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002203 continue;
2204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002205
John McCall9f3059a2009-10-09 21:13:30 +00002206 R.setAmbiguousBaseSubobjectTypes(Paths);
2207 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208 }
2209
Douglas Gregorc0d24902010-10-22 22:08:47 +00002210 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002211 // We have a different subobject of the same type.
2212
2213 // C++ [class.member.lookup]p5:
2214 // A static member, a nested type or an enumerator defined in
2215 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002216 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002217 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002218 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002219
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002220 // We have found a nonstatic member name in multiple, distinct
2221 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002222 R.setAmbiguousBaseSubobjects(Paths);
2223 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002224 }
2225 }
2226
2227 // Lookup in a base class succeeded; return these results.
2228
Aaron Ballman1e606f42014-07-15 22:03:49 +00002229 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002230 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2231 D->getAccess());
2232 R.addDecl(D, AS);
2233 }
John McCall9f3059a2009-10-09 21:13:30 +00002234 R.resolveKind();
2235 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002236}
2237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002238/// Performs qualified name lookup or special type of lookup for
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002239/// "__super::" scope specifier.
2240///
2241/// This routine is a convenience overload meant to be called from contexts
2242/// that need to perform a qualified name lookup with an optional C++ scope
2243/// specifier that might require special kind of lookup.
2244///
2245/// \param R captures both the lookup criteria and any lookup results found.
2246///
2247/// \param LookupCtx The context in which qualified name lookup will
2248/// search.
2249///
2250/// \param SS An optional C++ scope-specifier.
2251///
2252/// \returns true if lookup succeeded, false if it failed.
2253bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2254 CXXScopeSpec &SS) {
2255 auto *NNS = SS.getScopeRep();
2256 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2257 return LookupInSuper(R, NNS->getAsRecordDecl());
2258 else
2259
2260 return LookupQualifiedName(R, LookupCtx);
2261}
2262
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002263/// Performs name lookup for a name that was parsed in the
Douglas Gregor34074322009-01-14 22:20:51 +00002264/// source code, and may contain a C++ scope specifier.
2265///
2266/// This routine is a convenience routine meant to be called from
2267/// contexts that receive a name and an optional C++ scope specifier
2268/// (e.g., "N::M::x"). It will then perform either qualified or
2269/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002270/// respectively) on the given name and return those results. It will
2271/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002272///
2273/// @param S The scope from which unqualified name lookup will
2274/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002275///
Douglas Gregore861bac2009-08-25 22:51:20 +00002276/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002277///
Douglas Gregore861bac2009-08-25 22:51:20 +00002278/// @param EnteringContext Indicates whether we are going to enter the
2279/// context of the scope-specifier SS (if present).
2280///
John McCall9f3059a2009-10-09 21:13:30 +00002281/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002282bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002283 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002284 if (SS && SS->isInvalid()) {
2285 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002286 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002287 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002288 }
Mike Stump11289f42009-09-09 15:08:12 +00002289
Douglas Gregore861bac2009-08-25 22:51:20 +00002290 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002291 NestedNameSpecifier *NNS = SS->getScopeRep();
2292 if (NNS->getKind() == NestedNameSpecifier::Super)
2293 return LookupInSuper(R, NNS->getAsRecordDecl());
2294
Douglas Gregore861bac2009-08-25 22:51:20 +00002295 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002296 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002297 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002298 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002299 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002300
John McCall27b18f82009-11-17 02:14:36 +00002301 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002302 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002303 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002304
Douglas Gregore861bac2009-08-25 22:51:20 +00002305 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002306 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002307 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002308 R.setNotFoundInCurrentInstantiation();
2309 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002310 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002311 }
2312
Mike Stump11289f42009-09-09 15:08:12 +00002313 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002314 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002315}
2316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002317/// Perform qualified name lookup into all base classes of the given
Nikola Smiljanic67860242014-09-26 00:28:20 +00002318/// class.
2319///
2320/// \param R captures both the lookup criteria and any lookup results found.
2321///
2322/// \param Class The context in which qualified name lookup will
2323/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002324///
2325/// @returns True if any decls were found (but possibly ambiguous)
2326bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002327 // The access-control rules we use here are essentially the rules for
2328 // doing a lookup in Class that just magically skipped the direct
2329 // members of Class itself. That is, the naming class is Class, and the
2330 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002331 for (const auto &BaseSpec : Class->bases()) {
2332 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2333 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2334 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
Fangrui Song99337e22018-07-20 08:19:20 +00002335 Result.setBaseObjectType(Context.getRecordType(Class));
Nikola Smiljanic67860242014-09-26 00:28:20 +00002336 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002337
2338 // Copy the lookup results into the target, merging the base's access into
2339 // the path access.
2340 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2341 R.addDecl(I.getDecl(),
2342 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2343 I.getAccess()));
2344 }
2345
2346 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002347 }
2348
2349 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002350 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002351
2352 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002353}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002354
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002355/// Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002356/// from name lookup.
2357///
James Dennett41725122012-06-22 10:16:05 +00002358/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002359void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002360 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2361
John McCall27b18f82009-11-17 02:14:36 +00002362 DeclarationName Name = Result.getLookupName();
2363 SourceLocation NameLoc = Result.getNameLoc();
2364 SourceRange LookupRange = Result.getContextRange();
2365
John McCall6538c932009-10-10 05:48:19 +00002366 switch (Result.getAmbiguityKind()) {
2367 case LookupResult::AmbiguousBaseSubobjects: {
2368 CXXBasePaths *Paths = Result.getBasePaths();
2369 QualType SubobjectType = Paths->front().back().Base->getType();
2370 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2371 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2372 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002373
David Blaikieff7d47a2012-12-19 00:45:41 +00002374 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002375 while (isa<CXXMethodDecl>(*Found) &&
2376 cast<CXXMethodDecl>(*Found)->isStatic())
2377 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002378
John McCall6538c932009-10-10 05:48:19 +00002379 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002380 break;
John McCall6538c932009-10-10 05:48:19 +00002381 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002382
John McCall6538c932009-10-10 05:48:19 +00002383 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002384 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2385 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002386
John McCall6538c932009-10-10 05:48:19 +00002387 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002388 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002389 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2390 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002391 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002392 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002393 if (DeclsPrinted.insert(D).second)
2394 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2395 }
Serge Pavlov99292092013-08-29 07:23:24 +00002396 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002397 }
2398
John McCall6538c932009-10-10 05:48:19 +00002399 case LookupResult::AmbiguousTagHiding: {
2400 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002401
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002402 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002403
Aaron Ballman1e606f42014-07-15 22:03:49 +00002404 for (auto *D : Result)
2405 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002406 TagDecls.insert(TD);
2407 Diag(TD->getLocation(), diag::note_hidden_tag);
2408 }
2409
Aaron Ballman1e606f42014-07-15 22:03:49 +00002410 for (auto *D : Result)
2411 if (!isa<TagDecl>(D))
2412 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002413
2414 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002415 LookupResult::Filter F = Result.makeFilter();
2416 while (F.hasNext()) {
2417 if (TagDecls.count(F.next()))
2418 F.erase();
2419 }
2420 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002421 break;
John McCall6538c932009-10-10 05:48:19 +00002422 }
2423
2424 case LookupResult::AmbiguousReference: {
2425 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002426
Aaron Ballman1e606f42014-07-15 22:03:49 +00002427 for (auto *D : Result)
2428 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002429 break;
John McCall6538c932009-10-10 05:48:19 +00002430 }
Serge Pavlov99292092013-08-29 07:23:24 +00002431 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002432}
Douglas Gregore254f902009-02-04 00:32:51 +00002433
John McCallf24d7bb2010-05-28 18:45:08 +00002434namespace {
2435 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002436 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002437 Sema::AssociatedNamespaceSet &Namespaces,
2438 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002439 : S(S), Namespaces(Namespaces), Classes(Classes),
2440 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002441 }
2442
Richard Smith58bd01f2019-01-16 22:01:39 +00002443 bool addClassTransitive(CXXRecordDecl *RD) {
2444 Classes.insert(RD);
2445 return ClassesTransitive.insert(RD);
2446 }
2447
John McCallf24d7bb2010-05-28 18:45:08 +00002448 Sema &S;
2449 Sema::AssociatedNamespaceSet &Namespaces;
2450 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002451 SourceLocation InstantiationLoc;
Richard Smith58bd01f2019-01-16 22:01:39 +00002452
2453 private:
2454 Sema::AssociatedClassSet ClassesTransitive;
John McCallf24d7bb2010-05-28 18:45:08 +00002455 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002456} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002457
Mike Stump11289f42009-09-09 15:08:12 +00002458static void
John McCallf24d7bb2010-05-28 18:45:08 +00002459addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002460
Douglas Gregor8b895222010-04-30 07:08:38 +00002461static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2462 DeclContext *Ctx) {
2463 // Add the associated namespace for this class.
2464
2465 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2466 // be a locally scoped record.
2467
Sebastian Redlbd595762010-08-31 20:53:31 +00002468 // We skip out of inline namespaces. The innermost non-inline namespace
2469 // contains all names of all its nested inline namespaces anyway, so we can
2470 // replace the entire inline namespace tree with its root.
2471 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2472 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002473 Ctx = Ctx->getParent();
2474
John McCallc7e8e792009-08-07 22:18:02 +00002475 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002476 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002477}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002478
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002479// Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002480// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002481static void
John McCallf24d7bb2010-05-28 18:45:08 +00002482addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2483 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002484 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002485 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002486 switch (Arg.getKind()) {
2487 case TemplateArgument::Null:
2488 break;
Mike Stump11289f42009-09-09 15:08:12 +00002489
Douglas Gregor197e5f72009-07-08 07:51:57 +00002490 case TemplateArgument::Type:
2491 // [...] the namespaces and classes associated with the types of the
2492 // template arguments provided for template type parameters (excluding
2493 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002494 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002495 break;
Mike Stump11289f42009-09-09 15:08:12 +00002496
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002498 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002499 // [...] the namespaces in which any template template arguments are
2500 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002501 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002502 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002503 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002504 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002505 DeclContext *Ctx = ClassTemplate->getDeclContext();
2506 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002507 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002508 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002509 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002510 }
2511 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002513
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002514 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002515 case TemplateArgument::Integral:
2516 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002517 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002518 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002519 // associated namespaces. ]
2520 break;
Mike Stump11289f42009-09-09 15:08:12 +00002521
Douglas Gregor197e5f72009-07-08 07:51:57 +00002522 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002523 for (const auto &P : Arg.pack_elements())
2524 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002525 break;
2526 }
2527}
2528
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002529// Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002530// argument-dependent lookup with an argument of class type
2531// (C++ [basic.lookup.koenig]p2).
2532static void
John McCallf24d7bb2010-05-28 18:45:08 +00002533addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2534 CXXRecordDecl *Class) {
2535
2536 // Just silently ignore anything whose name is __va_list_tag.
2537 if (Class->getDeclName() == Result.S.VAListTagName)
2538 return;
2539
Douglas Gregore254f902009-02-04 00:32:51 +00002540 // C++ [basic.lookup.koenig]p2:
2541 // [...]
2542 // -- If T is a class type (including unions), its associated
2543 // classes are: the class itself; the class of which it is a
2544 // member, if any; and its direct and indirect base
2545 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002546 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002547
2548 // Add the class of which it is a member, if any.
2549 DeclContext *Ctx = Class->getDeclContext();
2550 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002551 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002552 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002553 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002554
Mike Stump11289f42009-09-09 15:08:12 +00002555 // -- If T is a template-id, its associated namespaces and classes are
2556 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002557 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002558 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002559 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002560 // namespaces in which any template template arguments are defined; and
2561 // the classes in which any member templates used as template template
2562 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002563 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002564 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002565 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2566 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2567 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002568 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002569 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002570 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregor197e5f72009-07-08 07:51:57 +00002572 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2573 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002574 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002575 }
Mike Stump11289f42009-09-09 15:08:12 +00002576
Richard Smith58bd01f2019-01-16 22:01:39 +00002577 // Add the class itself. If we've already transitively visited this class,
2578 // we don't need to visit base classes.
2579 if (!Result.addClassTransitive(Class))
2580 return;
2581
John McCall67da35c2010-02-04 22:26:26 +00002582 // Only recurse into base classes for complete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00002583 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2584 Result.S.Context.getRecordType(Class)))
Richard Smith594461f2014-03-14 22:07:27 +00002585 return;
John McCall67da35c2010-02-04 22:26:26 +00002586
Douglas Gregore254f902009-02-04 00:32:51 +00002587 // Add direct and indirect base classes along with their associated
2588 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002589 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002590 Bases.push_back(Class);
2591 while (!Bases.empty()) {
2592 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002593 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002594
2595 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002596 for (const auto &Base : Class->bases()) {
2597 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002598 // In dependent contexts, we do ADL twice, and the first time around,
2599 // the base type might be a dependent TemplateSpecializationType, or a
2600 // TemplateTypeParmType. If that happens, simply ignore it.
2601 // FIXME: If we want to support export, we probably need to add the
2602 // namespace of the template in a TemplateSpecializationType, or even
2603 // the classes and namespaces of known non-dependent arguments.
2604 if (!BaseType)
2605 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002606 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith58bd01f2019-01-16 22:01:39 +00002607 if (Result.addClassTransitive(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002608 // Find the associated namespace for this base class.
2609 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002610 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002611
2612 // Make sure we visit the bases of this base class.
2613 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2614 Bases.push_back(BaseDecl);
2615 }
2616 }
2617 }
2618}
2619
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002620// Add the associated classes and namespaces for
Douglas Gregore254f902009-02-04 00:32:51 +00002621// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002622// (C++ [basic.lookup.koenig]p2).
2623static void
John McCallf24d7bb2010-05-28 18:45:08 +00002624addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002625 // C++ [basic.lookup.koenig]p2:
2626 //
2627 // For each argument type T in the function call, there is a set
2628 // of zero or more associated namespaces and a set of zero or more
2629 // associated classes to be considered. The sets of namespaces and
2630 // classes is determined entirely by the types of the function
2631 // arguments (and the namespace of any template template
2632 // argument). Typedef names and using-declarations used to specify
2633 // the types do not contribute to this set. The sets of namespaces
2634 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002635
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002636 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002637 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2638
Douglas Gregore254f902009-02-04 00:32:51 +00002639 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002640 switch (T->getTypeClass()) {
2641
2642#define TYPE(Class, Base)
2643#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2644#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2645#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2646#define ABSTRACT_TYPE(Class, Base)
2647#include "clang/AST/TypeNodes.def"
2648 // T is canonical. We can also ignore dependent types because
2649 // we don't need to do ADL at the definition point, but if we
2650 // wanted to implement template export (or if we find some other
2651 // use for associated classes and namespaces...) this would be
2652 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002653 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002654
John McCall0af3d3b2010-05-28 06:08:54 +00002655 // -- If T is a pointer to U or an array of U, its associated
2656 // namespaces and classes are those associated with U.
2657 case Type::Pointer:
2658 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2659 continue;
2660 case Type::ConstantArray:
2661 case Type::IncompleteArray:
2662 case Type::VariableArray:
2663 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2664 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002665
John McCall0af3d3b2010-05-28 06:08:54 +00002666 // -- If T is a fundamental type, its associated sets of
2667 // namespaces and classes are both empty.
2668 case Type::Builtin:
2669 break;
2670
2671 // -- If T is a class type (including unions), its associated
2672 // classes are: the class itself; the class of which it is a
2673 // member, if any; and its direct and indirect base
2674 // classes. Its associated namespaces are the namespaces in
2675 // which its associated classes are defined.
2676 case Type::Record: {
Richard Smith82b8d4e2015-12-18 22:19:11 +00002677 CXXRecordDecl *Class =
2678 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002679 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002680 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002681 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002682
John McCall0af3d3b2010-05-28 06:08:54 +00002683 // -- If T is an enumeration type, its associated namespace is
2684 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002685 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002686 // it has no associated class.
2687 case Type::Enum: {
2688 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002689
John McCall0af3d3b2010-05-28 06:08:54 +00002690 DeclContext *Ctx = Enum->getDeclContext();
2691 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002692 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002693
John McCall0af3d3b2010-05-28 06:08:54 +00002694 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002695 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002696
John McCall0af3d3b2010-05-28 06:08:54 +00002697 break;
2698 }
2699
2700 // -- If T is a function type, its associated namespaces and
2701 // classes are those associated with the function parameter
2702 // types and those associated with the return type.
2703 case Type::FunctionProto: {
2704 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002705 for (const auto &Arg : Proto->param_types())
2706 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002707 // fallthrough
Galina Kistanova33399112017-06-03 06:35:06 +00002708 LLVM_FALLTHROUGH;
John McCall0af3d3b2010-05-28 06:08:54 +00002709 }
2710 case Type::FunctionNoProto: {
2711 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002712 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002713 continue;
2714 }
2715
2716 // -- If T is a pointer to a member function of a class X, its
2717 // associated namespaces and classes are those associated
2718 // with the function parameter types and return type,
2719 // together with those associated with X.
2720 //
2721 // -- If T is a pointer to a data member of class X, its
2722 // associated namespaces and classes are those associated
2723 // with the member type together with those associated with
2724 // X.
2725 case Type::MemberPointer: {
2726 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2727
2728 // Queue up the class type into which this points.
2729 Queue.push_back(MemberPtr->getClass());
2730
2731 // And directly continue with the pointee type.
2732 T = MemberPtr->getPointeeType().getTypePtr();
2733 continue;
2734 }
2735
2736 // As an extension, treat this like a normal pointer.
2737 case Type::BlockPointer:
2738 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2739 continue;
2740
2741 // References aren't covered by the standard, but that's such an
2742 // obvious defect that we cover them anyway.
2743 case Type::LValueReference:
2744 case Type::RValueReference:
2745 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2746 continue;
2747
2748 // These are fundamental types.
2749 case Type::Vector:
2750 case Type::ExtVector:
2751 case Type::Complex:
2752 break;
2753
Richard Smith27d807c2013-04-30 13:56:41 +00002754 // Non-deduced auto types only get here for error cases.
2755 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002756 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00002757 break;
2758
Fangrui Song6907ce22018-07-30 19:24:48 +00002759 // If T is an Objective-C object or interface type, or a pointer to an
Douglas Gregor8e936662011-04-12 01:02:45 +00002760 // object or interface type, the associated namespace is the global
2761 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002762 case Type::ObjCObject:
2763 case Type::ObjCInterface:
2764 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002765 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002766 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002767
2768 // Atomic types are just wrappers; use the associations of the
2769 // contained type.
2770 case Type::Atomic:
2771 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2772 continue;
Xiuli Pan9c14e282016-01-09 12:53:17 +00002773 case Type::Pipe:
2774 T = cast<PipeType>(T)->getElementType().getTypePtr();
2775 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002776 }
2777
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002778 if (Queue.empty())
2779 break;
2780 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002781 }
Douglas Gregore254f902009-02-04 00:32:51 +00002782}
2783
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002784/// Find the associated classes and namespaces for
Douglas Gregore254f902009-02-04 00:32:51 +00002785/// argument-dependent lookup for a call with the given set of
2786/// arguments.
2787///
2788/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002789/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002790/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002791void Sema::FindAssociatedClassesAndNamespaces(
2792 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2793 AssociatedNamespaceSet &AssociatedNamespaces,
2794 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002795 AssociatedNamespaces.clear();
2796 AssociatedClasses.clear();
2797
John McCall7d8b0412012-08-24 20:38:34 +00002798 AssociatedLookup Result(*this, InstantiationLoc,
2799 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002800
Douglas Gregore254f902009-02-04 00:32:51 +00002801 // C++ [basic.lookup.koenig]p2:
2802 // For each argument type T in the function call, there is a set
2803 // of zero or more associated namespaces and a set of zero or more
2804 // associated classes to be considered. The sets of namespaces and
2805 // classes is determined entirely by the types of the function
2806 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002807 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002808 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002809 Expr *Arg = Args[ArgIdx];
2810
2811 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002812 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002813 continue;
2814 }
2815
2816 // [...] In addition, if the argument is the name or address of a
2817 // set of overloaded functions and/or function templates, its
2818 // associated classes and namespaces are the union of those
2819 // associated with each of the members of the set: the namespace
2820 // in which the function or function template is defined and the
2821 // classes and namespaces associated with its (non-dependent)
2822 // parameter types and return type.
Richard Smith58bd01f2019-01-16 22:01:39 +00002823 OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
Mike Stump11289f42009-09-09 15:08:12 +00002824
Richard Smith58bd01f2019-01-16 22:01:39 +00002825 for (const NamedDecl *D : OE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002826 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002827 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002828
2829 // Add the classes and namespaces associated with the parameter
2830 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002831 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002832 }
2833 }
2834}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002835
John McCall5cebab12009-11-18 07:57:50 +00002836NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002837 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002838 LookupNameKind NameKind,
2839 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002840 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002841 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002842 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002843}
2844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002845/// Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002846ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002847 SourceLocation IdLoc,
2848 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002849 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002850 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002851 return cast_or_null<ObjCProtocolDecl>(D);
2852}
2853
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002854void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002855 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002856 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002857 // C++ [over.match.oper]p3:
2858 // -- The set of non-member candidates is the result of the
2859 // unqualified lookup of operator@ in the context of the
2860 // expression according to the usual rules for name lookup in
2861 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002862 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002863 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002864 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2865 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002867 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002868 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002869}
2870
Richard Smith8bae1be2017-02-24 02:07:20 +00002871Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
2872 CXXSpecialMember SM,
2873 bool ConstArg,
2874 bool VolatileArg,
2875 bool RValueThis,
2876 bool ConstThis,
2877 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002878 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002879 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002880 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002881 if (RValueThis || ConstThis || VolatileThis)
2882 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2883 "constructors and destructors always have unqualified lvalue this");
2884 if (ConstArg || VolatileArg)
2885 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2886 "parameter-less special members can't have qualified arguments");
2887
Richard Smith171e4b52017-02-15 04:18:23 +00002888 // FIXME: Get the caller to pass in a location for the lookup.
2889 SourceLocation LookupLoc = RD->getLocation();
2890
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002891 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002892 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002893 ID.AddInteger(SM);
2894 ID.AddInteger(ConstArg);
2895 ID.AddInteger(VolatileArg);
2896 ID.AddInteger(RValueThis);
2897 ID.AddInteger(ConstThis);
2898 ID.AddInteger(VolatileThis);
2899
2900 void *InsertPoint;
Richard Smith8bae1be2017-02-24 02:07:20 +00002901 SpecialMemberOverloadResultEntry *Result =
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002902 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2903
2904 // This was already cached
2905 if (Result)
Richard Smith8bae1be2017-02-24 02:07:20 +00002906 return *Result;
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002907
Richard Smith8bae1be2017-02-24 02:07:20 +00002908 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
2909 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002910 SpecialMemberCache.InsertNode(Result, InsertPoint);
2911
2912 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002913 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002914 DeclareImplicitDestructor(RD);
2915 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002916 assert(DD && "record without a destructor");
2917 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002918 Result->setKind(DD->isDeleted() ?
2919 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002920 SpecialMemberOverloadResult::Success);
Richard Smith8bae1be2017-02-24 02:07:20 +00002921 return *Result;
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002922 }
2923
Alexis Hunteef8ee02011-06-10 03:50:41 +00002924 // Prepare for overload resolution. Here we construct a synthetic argument
2925 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002926 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002927 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002928 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002929 unsigned NumArgs;
2930
Richard Smith83c478d2012-04-20 18:46:14 +00002931 QualType ArgType = CanTy;
2932 ExprValueKind VK = VK_LValue;
2933
Alexis Hunteef8ee02011-06-10 03:50:41 +00002934 if (SM == CXXDefaultConstructor) {
2935 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2936 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002937 if (RD->needsImplicitDefaultConstructor())
2938 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002939 } else {
2940 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2941 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002942 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002943 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002944 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002945 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002946 } else {
2947 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002948 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002949 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002950 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002951 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002952 }
2953
Alexis Hunteef8ee02011-06-10 03:50:41 +00002954 if (ConstArg)
2955 ArgType.addConst();
2956 if (VolatileArg)
2957 ArgType.addVolatile();
2958
2959 // This isn't /really/ specified by the standard, but it's implied
2960 // we should be working from an RValue in the case of move to ensure
2961 // that we prefer to bind to rvalue references, and an LValue in the
2962 // case of copy to ensure we don't bind to rvalue references.
2963 // Possibly an XValue is actually correct in the case of move, but
2964 // there is no semantic difference for class types in this restricted
2965 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002966 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002967 VK = VK_LValue;
2968 else
2969 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002970 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002971
Richard Smith171e4b52017-02-15 04:18:23 +00002972 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
Richard Smith83c478d2012-04-20 18:46:14 +00002973
2974 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002975 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002976 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002977 }
2978
2979 // Create the object argument
2980 QualType ThisTy = CanTy;
2981 if (ConstThis)
2982 ThisTy.addConst();
2983 if (VolatileThis)
2984 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002985 Expr::Classification Classification =
Richard Smith171e4b52017-02-15 04:18:23 +00002986 OpaqueValueExpr(LookupLoc, ThisTy,
Richard Smith83c478d2012-04-20 18:46:14 +00002987 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002988
2989 // Now we perform lookup on the name we computed earlier and do overload
2990 // resolution. Lookup is only performed directly into the class since there
2991 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith171e4b52017-02-15 04:18:23 +00002992 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002993 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002994
2995 if (R.empty()) {
2996 // We might have no default constructor because we have a lambda's closure
2997 // type, rather than because there's some other declared constructor.
2998 // Every class has a copy/move constructor, copy/move assignment, and
2999 // destructor.
3000 assert(SM == CXXDefaultConstructor &&
3001 "lookup for a constructor or assignment operator was empty");
3002 Result->setMethod(nullptr);
3003 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Richard Smith8bae1be2017-02-24 02:07:20 +00003004 return *Result;
Richard Smith8c37ab52015-02-11 01:48:47 +00003005 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00003006
3007 // Copy the candidates as our processing of them may load new declarations
3008 // from an external source and invalidate lookup_result.
3009 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3010
Richard Smith5179eb72016-06-28 19:03:57 +00003011 for (NamedDecl *CandDecl : Candidates) {
3012 if (CandDecl->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00003013 continue;
3014
Richard Smith5179eb72016-06-28 19:03:57 +00003015 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
3016 auto CtorInfo = getConstructorInfo(Cand);
3017 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
Alexis Hunt080709f2011-06-23 00:26:20 +00003018 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Richard Smith5179eb72016-06-28 19:03:57 +00003019 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3020 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3021 else if (CtorInfo)
3022 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003023 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00003024 else
Richard Smith5179eb72016-06-28 19:03:57 +00003025 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3026 true);
3027 } else if (FunctionTemplateDecl *Tmpl =
3028 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3029 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3030 AddMethodTemplateCandidate(
3031 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
George Burgess IVce6284b2017-01-28 02:19:40 +00003032 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Richard Smith5179eb72016-06-28 19:03:57 +00003033 else if (CtorInfo)
3034 AddTemplateOverloadCandidate(
3035 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3036 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3037 else
3038 AddTemplateOverloadCandidate(
3039 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00003040 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00003041 assert(isa<UsingDecl>(Cand.getDecl()) &&
3042 "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00003043 }
3044 }
3045
3046 OverloadCandidateSet::iterator Best;
Richard Smith171e4b52017-02-15 04:18:23 +00003047 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003048 case OR_Success:
3049 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00003050 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003051 break;
3052
3053 case OR_Deleted:
3054 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00003055 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003056 break;
3057
3058 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00003059 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003060 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3061 break;
3062
Alexis Hunteef8ee02011-06-10 03:50:41 +00003063 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00003064 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003065 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003066 break;
3067 }
3068
Richard Smith8bae1be2017-02-24 02:07:20 +00003069 return *Result;
Alexis Hunteef8ee02011-06-10 03:50:41 +00003070}
3071
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003072/// Look up the default constructor for the given class.
Alexis Hunteef8ee02011-06-10 03:50:41 +00003073CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Richard Smith8bae1be2017-02-24 02:07:20 +00003074 SpecialMemberOverloadResult Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00003075 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3076 false, false);
3077
Richard Smith8bae1be2017-02-24 02:07:20 +00003078 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003079}
3080
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003081/// Look up the copying constructor for the given class.
Alexis Hunt491ec602011-06-21 23:42:56 +00003082CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00003083 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003084 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3085 "non-const, non-volatile qualifiers for copy ctor arg");
Richard Smith8bae1be2017-02-24 02:07:20 +00003086 SpecialMemberOverloadResult Result =
Alexis Hunt899bd442011-06-10 04:44:37 +00003087 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3088 Quals & Qualifiers::Volatile, false, false, false);
3089
Richard Smith8bae1be2017-02-24 02:07:20 +00003090 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Alexis Hunt899bd442011-06-10 04:44:37 +00003091}
3092
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003093/// Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00003094CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3095 unsigned Quals) {
Richard Smith8bae1be2017-02-24 02:07:20 +00003096 SpecialMemberOverloadResult Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003097 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3098 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003099
Richard Smith8bae1be2017-02-24 02:07:20 +00003100 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003101}
3102
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003103/// Look up the constructors for the given class.
Douglas Gregor52b72822010-07-02 23:12:18 +00003104DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003105 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00003106 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00003107 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003108 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00003109 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003110 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003111 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003112 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00003113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003114
Douglas Gregor52b72822010-07-02 23:12:18 +00003115 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3116 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3117 return Class->lookup(Name);
3118}
3119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003120/// Look up the copying assignment operator for the given class.
Alexis Hunt491ec602011-06-21 23:42:56 +00003121CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3122 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00003123 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00003124 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3125 "non-const, non-volatile qualifiers for copy assignment arg");
3126 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3127 "non-const, non-volatile qualifiers for copy assignment this");
Richard Smith8bae1be2017-02-24 02:07:20 +00003128 SpecialMemberOverloadResult Result =
Alexis Hunt491ec602011-06-21 23:42:56 +00003129 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3130 Quals & Qualifiers::Volatile, RValueThis,
3131 ThisQuals & Qualifiers::Const,
3132 ThisQuals & Qualifiers::Volatile);
3133
Richard Smith8bae1be2017-02-24 02:07:20 +00003134 return Result.getMethod();
Alexis Hunt491ec602011-06-21 23:42:56 +00003135}
3136
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003137/// Look up the moving assignment operator for the given class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00003138CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00003139 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003140 bool RValueThis,
3141 unsigned ThisQuals) {
3142 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3143 "non-const, non-volatile qualifiers for copy assignment this");
Richard Smith8bae1be2017-02-24 02:07:20 +00003144 SpecialMemberOverloadResult Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003145 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3146 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003147 ThisQuals & Qualifiers::Const,
3148 ThisQuals & Qualifiers::Volatile);
3149
Richard Smith8bae1be2017-02-24 02:07:20 +00003150 return Result.getMethod();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003151}
3152
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003153/// Look for the destructor of the given class.
Douglas Gregore71edda2010-07-01 22:47:18 +00003154///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00003155/// During semantic analysis, this routine should be used in lieu of
3156/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00003157///
3158/// \returns The destructor for this class.
3159CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003160 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3161 false, false, false,
Richard Smith8bae1be2017-02-24 02:07:20 +00003162 false, false).getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00003163}
3164
Richard Smithbcc22fc2012-03-09 08:00:36 +00003165/// LookupLiteralOperator - Determine which literal operator should be used for
3166/// a user-defined literal, per C++11 [lex.ext].
3167///
3168/// Normal overload resolution is not used to select which literal operator to
3169/// call for a user-defined literal. Look up the provided literal operator name,
3170/// and filter the results to the appropriate set for the given argument types.
3171Sema::LiteralOperatorLookupResult
3172Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3173 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00003174 bool AllowRaw, bool AllowTemplate,
Tim Northover97103382017-08-09 14:56:48 +00003175 bool AllowStringTemplate, bool DiagnoseMissing) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003176 LookupName(R, S);
3177 assert(R.getResultKind() != LookupResult::Ambiguous &&
3178 "literal operator lookup can't be ambiguous");
3179
3180 // Filter the lookup results appropriately.
3181 LookupResult::Filter F = R.makeFilter();
3182
Richard Smithbcc22fc2012-03-09 08:00:36 +00003183 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00003184 bool FoundTemplate = false;
3185 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003186 bool FoundExactMatch = false;
3187
3188 while (F.hasNext()) {
3189 Decl *D = F.next();
3190 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3191 D = USD->getTargetDecl();
3192
Douglas Gregorc1970572013-04-10 05:18:00 +00003193 // If the declaration we found is invalid, skip it.
3194 if (D->isInvalidDecl()) {
3195 F.erase();
3196 continue;
3197 }
3198
Richard Smithb8b41d32013-10-07 19:57:58 +00003199 bool IsRaw = false;
3200 bool IsTemplate = false;
3201 bool IsStringTemplate = false;
3202 bool IsExactMatch = false;
3203
Richard Smithbcc22fc2012-03-09 08:00:36 +00003204 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3205 if (FD->getNumParams() == 1 &&
3206 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3207 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003208 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003209 IsExactMatch = true;
3210 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3211 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3212 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3213 IsExactMatch = false;
3214 break;
3215 }
3216 }
3217 }
3218 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003219 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3220 TemplateParameterList *Params = FD->getTemplateParameters();
3221 if (Params->size() == 1)
3222 IsTemplate = true;
3223 else
3224 IsStringTemplate = true;
3225 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003226
3227 if (IsExactMatch) {
3228 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003229 AllowRaw = false;
3230 AllowTemplate = false;
3231 AllowStringTemplate = false;
3232 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003233 // Go through again and remove the raw and template decls we've
3234 // already found.
3235 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003236 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003237 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003238 } else if (AllowRaw && IsRaw) {
3239 FoundRaw = true;
3240 } else if (AllowTemplate && IsTemplate) {
3241 FoundTemplate = true;
3242 } else if (AllowStringTemplate && IsStringTemplate) {
3243 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003244 } else {
3245 F.erase();
3246 }
3247 }
3248
3249 F.done();
3250
3251 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3252 // parameter type, that is used in preference to a raw literal operator
3253 // or literal operator template.
3254 if (FoundExactMatch)
3255 return LOLR_Cooked;
3256
3257 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3258 // operator template, but not both.
3259 if (FoundRaw && FoundTemplate) {
3260 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003261 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
Richard Smithc2bebe92016-05-11 20:37:46 +00003262 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003263 return LOLR_Error;
3264 }
3265
3266 if (FoundRaw)
3267 return LOLR_Raw;
3268
3269 if (FoundTemplate)
3270 return LOLR_Template;
3271
Richard Smithb8b41d32013-10-07 19:57:58 +00003272 if (FoundStringTemplate)
3273 return LOLR_StringTemplate;
3274
Richard Smithbcc22fc2012-03-09 08:00:36 +00003275 // Didn't find anything we could use.
Tim Northover97103382017-08-09 14:56:48 +00003276 if (DiagnoseMissing) {
3277 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3278 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3279 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3280 << (AllowTemplate || AllowStringTemplate);
3281 return LOLR_Error;
3282 }
3283
3284 return LOLR_ErrorNoDiagnostic;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003285}
3286
John McCall8fe68082010-01-26 07:16:45 +00003287void ADLResult::insert(NamedDecl *New) {
3288 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3289
3290 // If we haven't yet seen a decl for this key, or the last decl
3291 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003292 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003293 Old = New;
3294 return;
3295 }
3296
3297 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003298 FunctionDecl *OldFD = Old->getAsFunction();
3299 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003300
3301 FunctionDecl *Cursor = NewFD;
3302 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003303 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003304
3305 // If we got to the end without finding OldFD, OldFD is the newer
3306 // declaration; leave things as they are.
3307 if (!Cursor) return;
3308
3309 // If we do find OldFD, then NewFD is newer.
3310 if (Cursor == OldFD) break;
3311
3312 // Otherwise, keep looking.
3313 }
3314
3315 Old = New;
3316}
3317
Richard Smith100b24a2014-04-17 01:52:14 +00003318void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3319 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003320 // Find all of the associated namespaces and classes based on the
3321 // arguments we have.
3322 AssociatedNamespaceSet AssociatedNamespaces;
3323 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003324 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003325 AssociatedNamespaces,
3326 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003327
3328 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003329 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3330 // and let Y be the lookup set produced by argument dependent
3331 // lookup (defined as follows). If X contains [...] then Y is
3332 // empty. Otherwise Y is the set of declarations found in the
3333 // namespaces associated with the argument types as described
3334 // below. The set of declarations found by the lookup of the name
3335 // is the union of X and Y.
3336 //
3337 // Here, we compute Y and add its members to the overloaded
3338 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003339 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003340 // When considering an associated namespace, the lookup is the
3341 // same as the lookup performed when the associated namespace is
3342 // used as a qualifier (3.4.3.2) except that:
3343 //
3344 // -- Any using-directives in the associated namespace are
3345 // ignored.
3346 //
John McCallc7e8e792009-08-07 22:18:02 +00003347 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003348 // associated classes are visible within their respective
3349 // namespaces even if they are not visible during an ordinary
3350 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003351 DeclContext::lookup_result R = NS->lookup(Name);
3352 for (auto *D : R) {
Richard Smith041740f2018-01-06 00:09:23 +00003353 auto *Underlying = D;
3354 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3355 Underlying = USD->getTargetDecl();
3356
3357 if (!isa<FunctionDecl>(Underlying) &&
3358 !isa<FunctionTemplateDecl>(Underlying))
3359 continue;
3360
Richard Smith8ce732b2019-01-07 06:00:46 +00003361 // The declaration is visible to argument-dependent lookup if either
3362 // it's ordinarily visible or declared as a friend in an associated
3363 // class.
3364 bool Visible = false;
3365 for (D = D->getMostRecentDecl(); D;
3366 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3367 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3368 if (isVisible(D)) {
3369 Visible = true;
3370 break;
3371 }
3372 } else if (D->getFriendObjectKind()) {
3373 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3374 if (AssociatedClasses.count(RD) && isVisible(D)) {
3375 Visible = true;
Richard Smith64017682013-07-17 23:53:16 +00003376 break;
3377 }
3378 }
John McCalld1e9d832009-08-11 06:59:38 +00003379 }
Mike Stump11289f42009-09-09 15:08:12 +00003380
Richard Smith197f68d2017-10-11 01:49:57 +00003381 // FIXME: Preserve D as the FoundDecl.
Richard Smith8ce732b2019-01-07 06:00:46 +00003382 if (Visible)
3383 Result.insert(Underlying);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003384 }
3385 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003386}
Douglas Gregor2d435302009-12-30 17:04:44 +00003387
3388//----------------------------------------------------------------------------
3389// Search for all visible declarations.
3390//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003391VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003392
Richard Smithe156254d2013-08-20 20:35:18 +00003393bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3394
Douglas Gregor2d435302009-12-30 17:04:44 +00003395namespace {
3396
3397class ShadowContextRAII;
3398
3399class VisibleDeclsRecord {
3400public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003401 /// An entry in the shadow map, which is optimized to store a
Douglas Gregor2d435302009-12-30 17:04:44 +00003402 /// single declaration (the common case) but can also store a list
3403 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003404 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003405
3406private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003407 /// A mapping from declaration names to the declarations that have
Douglas Gregor2d435302009-12-30 17:04:44 +00003408 /// this name within a particular scope.
3409 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3410
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003411 /// A list of shadow maps, which is used to model name hiding.
Douglas Gregor2d435302009-12-30 17:04:44 +00003412 std::list<ShadowMap> ShadowMaps;
3413
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003414 /// The declaration contexts we have already visited.
Douglas Gregor2d435302009-12-30 17:04:44 +00003415 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3416
3417 friend class ShadowContextRAII;
3418
3419public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003420 /// Determine whether we have already visited this context
Douglas Gregor2d435302009-12-30 17:04:44 +00003421 /// (and, if not, note that we are going to visit that context now).
3422 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003423 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003424 }
3425
Douglas Gregor39982192010-08-15 06:18:01 +00003426 bool alreadyVisitedContext(DeclContext *Ctx) {
3427 return VisitedContexts.count(Ctx);
3428 }
3429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003430 /// Determine whether the given declaration is hidden in the
Douglas Gregor2d435302009-12-30 17:04:44 +00003431 /// current scope.
3432 ///
3433 /// \returns the declaration that hides the given declaration, or
3434 /// NULL if no such declaration exists.
3435 NamedDecl *checkHidden(NamedDecl *ND);
3436
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003437 /// Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003438 void add(NamedDecl *ND) {
3439 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3440 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003441};
3442
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003443/// RAII object that records when we've entered a shadow context.
Douglas Gregor2d435302009-12-30 17:04:44 +00003444class ShadowContextRAII {
3445 VisibleDeclsRecord &Visible;
3446
3447 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3448
3449public:
3450 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003451 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003452 }
3453
3454 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003455 Visible.ShadowMaps.pop_back();
3456 }
3457};
3458
3459} // end anonymous namespace
3460
Douglas Gregor2d435302009-12-30 17:04:44 +00003461NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3462 unsigned IDNS = ND->getIdentifierNamespace();
3463 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3464 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3465 SM != SMEnd; ++SM) {
3466 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3467 if (Pos == SM->end())
3468 continue;
3469
Aaron Ballman1e606f42014-07-15 22:03:49 +00003470 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003471 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003472 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003474 Decl::IDNS_ObjCProtocol)))
3475 continue;
3476
3477 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003478 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003479 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003480 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003481 continue;
3482
Douglas Gregor09bbc652010-01-14 15:47:35 +00003483 // Functions and function templates in the same scope overload
3484 // rather than hide. FIXME: Look for hiding based on function
3485 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003486 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003487 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003488 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003489 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Alex Lorenze7e8f802017-01-23 17:23:23 +00003491 // A shadow declaration that's created by a resolved using declaration
3492 // is not hidden by the same using declaration.
3493 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3494 cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3495 continue;
3496
Douglas Gregor2d435302009-12-30 17:04:44 +00003497 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003498 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003499 }
3500 }
3501
Craig Topperc3ec1492014-05-26 06:22:03 +00003502 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003503}
3504
3505static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3506 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003507 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003508 VisibleDeclConsumer &Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003509 VisibleDeclsRecord &Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003510 bool IncludeDependentBases,
3511 bool LoadExternal) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003512 if (!Ctx)
3513 return;
3514
Douglas Gregor2d435302009-12-30 17:04:44 +00003515 // Make sure we don't visit the same context twice.
3516 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3517 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518
Haojian Wu10d95c52018-01-17 14:29:25 +00003519 Consumer.EnteredContext(Ctx);
3520
Richard Smith9e2341d2015-03-23 03:25:59 +00003521 // Outside C++, lookup results for the TU live on identifiers.
3522 if (isa<TranslationUnitDecl>(Ctx) &&
3523 !Result.getSema().getLangOpts().CPlusPlus) {
3524 auto &S = Result.getSema();
3525 auto &Idents = S.Context.Idents;
3526
3527 // Ensure all external identifiers are in the identifier table.
Sam McCallbb2cf632018-01-12 14:51:47 +00003528 if (LoadExternal)
3529 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3530 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3531 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3532 Idents.get(Name);
3533 }
Richard Smith9e2341d2015-03-23 03:25:59 +00003534
3535 // Walk all lookup results in the TU for each identifier.
3536 for (const auto &Ident : Idents) {
3537 for (auto I = S.IdResolver.begin(Ident.getValue()),
3538 E = S.IdResolver.end();
3539 I != E; ++I) {
3540 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3541 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3542 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3543 Visited.add(ND);
3544 }
3545 }
3546 }
3547 }
3548
3549 return;
3550 }
3551
Douglas Gregor7454c562010-07-02 20:37:36 +00003552 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3553 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3554
Sam McCallabdcc612018-01-24 17:50:20 +00003555 // We sometimes skip loading namespace-level results (they tend to be huge).
3556 bool Load = LoadExternal ||
3557 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
Douglas Gregor2d435302009-12-30 17:04:44 +00003558 // Enumerate all of the results in this context.
Sam McCallbb2cf632018-01-12 14:51:47 +00003559 for (DeclContextLookupResult R :
Sam McCallabdcc612018-01-24 17:50:20 +00003560 Load ? Ctx->lookups()
3561 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003562 for (auto *D : R) {
3563 if (auto *ND = Result.getAcceptableDecl(D)) {
3564 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3565 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003566 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003567 }
3568 }
3569
3570 // Traverse using directives for qualified name lookup.
3571 if (QualifiedNameLookup) {
3572 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003573 for (auto I : Ctx->using_directives()) {
Richard Smithb920f852017-10-11 01:19:11 +00003574 if (!Result.getSema().isVisible(I))
3575 continue;
Aaron Ballman63ab7602014-03-07 13:44:44 +00003576 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Alex Lorenze6afa392017-05-11 13:48:57 +00003577 QualifiedNameLookup, InBaseClass, Consumer, Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003578 IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003579 }
3580 }
3581
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003582 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003583 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003584 if (!Record->hasDefinition())
3585 return;
3586
Aaron Ballman574705e2014-03-13 15:41:46 +00003587 for (const auto &B : Record->bases()) {
3588 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589
Alex Lorenze6afa392017-05-11 13:48:57 +00003590 RecordDecl *RD;
3591 if (BaseType->isDependentType()) {
3592 if (!IncludeDependentBases) {
3593 // Don't look into dependent bases, because name lookup can't look
3594 // there anyway.
3595 continue;
3596 }
3597 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3598 if (!TST)
3599 continue;
3600 TemplateName TN = TST->getTemplateName();
3601 const auto *TD =
3602 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3603 if (!TD)
3604 continue;
3605 RD = TD->getTemplatedDecl();
3606 } else {
3607 const auto *Record = BaseType->getAs<RecordType>();
3608 if (!Record)
3609 continue;
3610 RD = Record->getDecl();
3611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612
Douglas Gregor2d435302009-12-30 17:04:44 +00003613 // FIXME: It would be nice to be able to determine whether referencing
3614 // a particular member would be ambiguous. For example, given
3615 //
3616 // struct A { int member; };
3617 // struct B { int member; };
3618 // struct C : A, B { };
3619 //
3620 // void f(C *c) { c->### }
3621 //
3622 // accessing 'member' would result in an ambiguity. However, we
3623 // could be smart enough to qualify the member with the base
3624 // class, e.g.,
3625 //
3626 // c->B::member
3627 //
3628 // or
3629 //
3630 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631
Douglas Gregor2d435302009-12-30 17:04:44 +00003632 // Find results in this base class (and its bases).
3633 ShadowContextRAII Shadow(Visited);
Eric Liub91e0812018-10-02 10:29:00 +00003634 LookupVisibleDecls(RD, Result, QualifiedNameLookup, /*InBaseClass=*/true,
3635 Consumer, Visited, IncludeDependentBases,
3636 LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003637 }
3638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003640 // Traverse the contexts of Objective-C classes.
3641 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3642 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003643 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003644 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003645 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, Consumer,
3646 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003647 }
3648
3649 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003650 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003651 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003652 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003653 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003654 }
3655
3656 // Traverse the superclass.
3657 if (IFace->getSuperClass()) {
3658 ShadowContextRAII Shadow(Visited);
3659 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Sam McCallbb2cf632018-01-12 14:51:47 +00003660 true, Consumer, Visited, IncludeDependentBases,
3661 LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663
Douglas Gregor0b59e802010-04-19 18:02:19 +00003664 // If there is an implementation, traverse it. We do this to find
3665 // synthesized ivars.
3666 if (IFace->getImplementation()) {
3667 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668 LookupVisibleDecls(IFace->getImplementation(), Result,
Sam McCallbb2cf632018-01-12 14:51:47 +00003669 QualifiedNameLookup, InBaseClass, Consumer, Visited,
3670 IncludeDependentBases, LoadExternal);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003671 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003672 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003673 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003674 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003675 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003676 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003677 }
3678 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003679 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003680 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003681 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003682 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684
Douglas Gregor0b59e802010-04-19 18:02:19 +00003685 // If there is an implementation, traverse it.
3686 if (Category->getImplementation()) {
3687 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688 LookupVisibleDecls(Category->getImplementation(), Result,
Sam McCallbb2cf632018-01-12 14:51:47 +00003689 QualifiedNameLookup, true, Consumer, Visited,
3690 IncludeDependentBases, LoadExternal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003692 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003693}
3694
3695static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3696 UnqualUsingDirectiveSet &UDirs,
3697 VisibleDeclConsumer &Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003698 VisibleDeclsRecord &Visited,
3699 bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003700 if (!S)
3701 return;
3702
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703 if (!S->getEntity() ||
3704 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003705 !Visited.alreadyVisitedContext(S->getEntity())) ||
3706 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003707 FindLocalExternScope FindLocals(Result);
Benjamin Kramer17ba6692017-10-13 22:14:34 +00003708 // Walk through the declarations in this Scope. The consumer might add new
3709 // decls to the scope as part of deserialization, so make a copy first.
3710 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
3711 for (Decl *D : ScopeDecls) {
Aaron Ballman35c54952014-03-17 16:55:25 +00003712 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003713 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003714 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003715 Visited.add(ND);
3716 }
3717 }
3718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719
Douglas Gregor66230062010-03-15 14:33:29 +00003720 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003721 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003722 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003723 // Look into this scope's declaration context, along with any of its
3724 // parent lookup contexts (e.g., enclosing classes), up to the point
3725 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003726 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003727 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003728
Douglas Gregorea166062010-03-15 15:26:48 +00003729 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003730 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003731 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3732 if (Method->isInstanceMethod()) {
3733 // For instance methods, look for ivars in the method's interface.
3734 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3735 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003736 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003738 /*InBaseClass=*/false, Consumer, Visited,
3739 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003740 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003741 }
3742
3743 // We've already performed all of the name lookup that we need
3744 // to for Objective-C methods; the next context will be the
3745 // outer scope.
3746 break;
3747 }
3748
Douglas Gregor2d435302009-12-30 17:04:44 +00003749 if (Ctx->isFunctionOrMethod())
3750 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751
3752 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003753 /*InBaseClass=*/false, Consumer, Visited,
3754 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003755 }
3756 } else if (!S->getParent()) {
3757 // Look into the translation unit scope. We walk through the translation
3758 // unit's declaration context, because the Scope itself won't have all of
3759 // the declarations if we loaded a precompiled header.
3760 // FIXME: We would like the translation unit's Scope object to point to the
3761 // translation unit, so we don't need this special "if" branch. However,
3762 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003764 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003765 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003766 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003768 /*InBaseClass=*/false, Consumer, Visited,
3769 /*IncludeDependentBases=*/false, LoadExternal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770 }
3771
Douglas Gregor2d435302009-12-30 17:04:44 +00003772 if (Entity) {
3773 // Lookup visible declarations in any namespaces found by using
3774 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003775 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3776 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777 Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003778 /*InBaseClass=*/false, Consumer, Visited,
3779 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003780 }
3781
3782 // Lookup names in the parent scope.
3783 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003784 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited,
3785 LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003786}
3787
3788void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003789 VisibleDeclConsumer &Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003790 bool IncludeGlobalScope, bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003791 // Determine the set of using directives available during
3792 // unqualified name lookup.
3793 Scope *Initial = S;
Richard Smithb920f852017-10-11 01:19:11 +00003794 UnqualUsingDirectiveSet UDirs(*this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003795 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003796 // Find the first namespace or translation-unit scope.
3797 while (S && !isNamespaceOrTranslationUnitScope(S))
3798 S = S->getParent();
3799
3800 UDirs.visitScopeChain(Initial, S);
3801 }
3802 UDirs.done();
3803
3804 // Look for visible declarations.
3805 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);
Sam McCallbb2cf632018-01-12 14:51:47 +00003811 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003812}
3813
3814void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003815 VisibleDeclConsumer &Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003816 bool IncludeGlobalScope,
Sam McCallbb2cf632018-01-12 14:51:47 +00003817 bool IncludeDependentBases, bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003818 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003819 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003820 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003821 if (!IncludeGlobalScope)
3822 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003823 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Alex Lorenze6afa392017-05-11 13:48:57 +00003825 /*InBaseClass=*/false, Consumer, Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003826 IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003827}
3828
Chris Lattner43e7f312011-02-18 02:08:43 +00003829/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003830/// If GnuLabelLoc is a valid source location, then this is a definition
3831/// of an __label__ label name, otherwise it is a normal label definition
3832/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003833LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003834 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003835 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003836 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003837
3838 if (GnuLabelLoc.isValid()) {
3839 // Local label definitions always shadow existing labels.
3840 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3841 Scope *S = CurScope;
3842 PushOnScopeChains(Res, S, true);
3843 return cast<LabelDecl>(Res);
3844 }
3845
3846 // Not a GNU local label.
3847 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3848 // If we found a label, check to see if it is in the same context as us.
3849 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003850 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003851 Res = nullptr;
3852 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003853 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003854 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3855 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003856 assert(S && "Not in a function?");
3857 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003858 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003859 return cast<LabelDecl>(Res);
3860}
3861
3862//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003863// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003864//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003865
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003866static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3867 TypoCorrection &Candidate) {
3868 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3869 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3870}
3871
3872static void LookupPotentialTypoResult(Sema &SemaRef,
3873 LookupResult &Res,
3874 IdentifierInfo *Name,
3875 Scope *S, CXXScopeSpec *SS,
3876 DeclContext *MemberContext,
3877 bool EnteringContext,
3878 bool isObjCIvarLookup,
3879 bool FindHidden);
3880
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003881/// Check whether the declarations found for a typo correction are
Richard Smith3092d722017-06-05 22:29:36 +00003882/// visible. Set the correction's RequiresImport flag to true if none of the
3883/// declarations are visible, false otherwise.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003884static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003885 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3886
3887 for (/**/; DI != DE; ++DI)
3888 if (!LookupResult::isVisible(SemaRef, *DI))
3889 break;
Richard Smith3092d722017-06-05 22:29:36 +00003890 // No filtering needed if all decls are visible.
3891 if (DI == DE) {
3892 TC.setRequiresImport(false);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003893 return;
Richard Smith3092d722017-06-05 22:29:36 +00003894 }
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003895
3896 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3897 bool AnyVisibleDecls = !NewDecls.empty();
3898
3899 for (/**/; DI != DE; ++DI) {
Richard Smith041740f2018-01-06 00:09:23 +00003900 if (LookupResult::isVisible(SemaRef, *DI)) {
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003901 if (!AnyVisibleDecls) {
3902 // Found a visible decl, discard all hidden ones.
3903 AnyVisibleDecls = true;
3904 NewDecls.clear();
3905 }
Richard Smith041740f2018-01-06 00:09:23 +00003906 NewDecls.push_back(*DI);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003907 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3908 NewDecls.push_back(*DI);
3909 }
3910
3911 if (NewDecls.empty())
3912 TC = TypoCorrection();
3913 else {
3914 TC.setCorrectionDecls(NewDecls);
3915 TC.setRequiresImport(!AnyVisibleDecls);
3916 }
3917}
3918
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003919// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3920// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3921// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3922static void getNestedNameSpecifierIdentifiers(
3923 NestedNameSpecifier *NNS,
3924 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3925 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3926 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3927 else
3928 Identifiers.clear();
3929
3930 const IdentifierInfo *II = nullptr;
3931
3932 switch (NNS->getKind()) {
3933 case NestedNameSpecifier::Identifier:
3934 II = NNS->getAsIdentifier();
3935 break;
3936
3937 case NestedNameSpecifier::Namespace:
3938 if (NNS->getAsNamespace()->isAnonymousNamespace())
3939 return;
3940 II = NNS->getAsNamespace()->getIdentifier();
3941 break;
3942
3943 case NestedNameSpecifier::NamespaceAlias:
3944 II = NNS->getAsNamespaceAlias()->getIdentifier();
3945 break;
3946
3947 case NestedNameSpecifier::TypeSpecWithTemplate:
3948 case NestedNameSpecifier::TypeSpec:
3949 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3950 break;
3951
3952 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003953 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003954 return;
3955 }
3956
3957 if (II)
3958 Identifiers.push_back(II);
3959}
3960
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003961void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003962 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003963 // Don't consider hidden names for typo correction.
3964 if (Hiding)
3965 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966
Douglas Gregor2d435302009-12-30 17:04:44 +00003967 // Only consider entities with identifiers for names, ignoring
3968 // special names (constructors, overloaded operators, selectors,
3969 // etc.).
3970 IdentifierInfo *Name = ND->getIdentifier();
3971 if (!Name)
3972 return;
3973
Richard Smithe156254d2013-08-20 20:35:18 +00003974 // Only consider visible declarations and declarations from modules with
3975 // names that exactly match.
Richard Smith041740f2018-01-06 00:09:23 +00003976 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
Richard Smithe156254d2013-08-20 20:35:18 +00003977 return;
3978
Douglas Gregor57756ea2010-10-14 22:11:03 +00003979 FoundName(Name->getName());
3980}
3981
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003982void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003983 // Compute the edit distance between the typo and the name of this
3984 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003985 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003986}
3987
3988void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3989 // Compute the edit distance between the typo and this keyword,
3990 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003991 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003992}
3993
3994void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3995 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003996 // Use a simple length-based heuristic to determine the minimum possible
3997 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003998 StringRef TypoStr = Typo->getName();
3999 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4000 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00004001 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00004003 // Compute an upper bound on the allowable edit distance, so that the
4004 // edit-distance algorithm can short-circuit.
Fangrui Songaadc93c2018-09-09 17:20:03 +00004005 unsigned UpperBound = (TypoStr.size() + 2) / 3;
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004006 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Fangrui Songaadc93c2018-09-09 17:20:03 +00004007 if (ED > UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004009 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004010 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00004011 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004012 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004013}
4014
Kaelyn Takatad2287c32014-10-27 18:07:13 +00004015static const unsigned MaxTypoDistanceResultSets = 5;
4016
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004017void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004018 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004019 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004020
4021 // For very short typos, ignore potential corrections that have a different
4022 // base identifier from the typo or which have a normalized edit distance
4023 // longer than the typo itself.
4024 if (TypoStr.size() < 3 &&
4025 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4026 return;
4027
4028 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004029 if (Correction.isResolved()) {
4030 checkCorrectionVisibility(SemaRef, Correction);
4031 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4032 return;
4033 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004034
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004035 TypoResultList &CList =
4036 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00004037
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004038 if (!CList.empty() && !CList.back().isResolved())
4039 CList.pop_back();
4040 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4041 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
4042 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
4043 RI != RIEnd; ++RI) {
4044 // If the Correction refers to a decl already in the result list,
4045 // replace the existing result if the string representation of Correction
4046 // comes before the current result alphabetically, then stop as there is
4047 // nothing more to be done to add Correction to the candidate set.
4048 if (RI->getCorrectionDecl() == NewND) {
4049 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
4050 *RI = Correction;
4051 return;
4052 }
4053 }
4054 }
4055 if (CList.empty() || Correction.isResolved())
4056 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004057
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004058 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004059 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4060}
4061
4062void TypoCorrectionConsumer::addNamespaces(
4063 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4064 SearchNamespaces = true;
4065
4066 for (auto KNPair : KnownNamespaces)
4067 Namespaces.addNameSpecifier(KNPair.first);
4068
4069 bool SSIsTemplate = false;
4070 if (NestedNameSpecifier *NNS =
4071 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4072 if (const Type *T = NNS->getAsType())
4073 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4074 }
Richard Smith2a40fb72015-11-18 01:19:02 +00004075 // Do not transform this into an iterator-based loop. The loop body can
4076 // trigger the creation of further types (through lazy deserialization) and
Raphael Isemannb23ccec2018-12-10 12:37:46 +00004077 // invalid iterators into this list.
Richard Smith2a40fb72015-11-18 01:19:02 +00004078 auto &Types = SemaRef.getASTContext().getTypes();
4079 for (unsigned I = 0; I != Types.size(); ++I) {
4080 const auto *TI = Types[I];
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004081 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4082 CD = CD->getCanonicalDecl();
4083 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4084 !CD->isUnion() && CD->getIdentifier() &&
4085 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4086 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4087 Namespaces.addNameSpecifier(CD);
4088 }
4089 }
4090}
4091
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004092const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4093 if (++CurrentTCIndex < ValidatedCorrections.size())
4094 return ValidatedCorrections[CurrentTCIndex];
4095
4096 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004097 while (!CorrectionResults.empty()) {
4098 auto DI = CorrectionResults.begin();
4099 if (DI->second.empty()) {
4100 CorrectionResults.erase(DI);
4101 continue;
4102 }
4103
4104 auto RI = DI->second.begin();
4105 if (RI->second.empty()) {
4106 DI->second.erase(RI);
4107 performQualifiedLookups();
4108 continue;
4109 }
4110
4111 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004112 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004113 ValidatedCorrections.push_back(TC);
4114 return ValidatedCorrections[CurrentTCIndex];
4115 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004116 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004117 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004118}
4119
4120bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4121 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4122 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004123 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004124retry_lookup:
4125 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4126 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004127 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004128 Name == Typo && !Candidate.WillReplaceSpecifier());
4129 switch (Result.getResultKind()) {
4130 case LookupResult::NotFound:
4131 case LookupResult::NotFoundInCurrentInstantiation:
4132 case LookupResult::FoundUnresolvedValue:
4133 if (TempSS) {
4134 // Immediately retry the lookup without the given CXXScopeSpec
4135 TempSS = nullptr;
4136 Candidate.WillReplaceSpecifier(true);
4137 goto retry_lookup;
4138 }
4139 if (TempMemberContext) {
4140 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004141 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004142 TempMemberContext = nullptr;
4143 goto retry_lookup;
4144 }
4145 if (SearchNamespaces)
4146 QualifiedResults.push_back(Candidate);
4147 break;
4148
4149 case LookupResult::Ambiguous:
4150 // We don't deal with ambiguities.
4151 break;
4152
4153 case LookupResult::Found:
4154 case LookupResult::FoundOverloaded:
4155 // Store all of the Decls for overloaded symbols
4156 for (auto *TRD : Result)
4157 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004158 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004159 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004160 if (SearchNamespaces)
4161 QualifiedResults.push_back(Candidate);
4162 break;
4163 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00004164 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004165 return true;
4166 }
4167 return false;
4168}
4169
4170void TypoCorrectionConsumer::performQualifiedLookups() {
4171 unsigned TypoLen = Typo->getName().size();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00004172 for (const TypoCorrection &QR : QualifiedResults) {
4173 for (const auto &NSI : Namespaces) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004174 DeclContext *Ctx = NSI.DeclCtx;
4175 const Type *NSType = NSI.NameSpecifier->getAsType();
4176
4177 // If the current NestedNameSpecifier refers to a class and the
4178 // current correction candidate is the name of that class, then skip
4179 // it as it is unlikely a qualified version of the class' constructor
4180 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00004181 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4182 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004183 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4184 continue;
4185 }
4186
4187 TypoCorrection TC(QR);
4188 TC.ClearCorrectionDecls();
4189 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4190 TC.setQualifierDistance(NSI.EditDistance);
4191 TC.setCallbackDistance(0); // Reset the callback distance
4192
4193 // If the current correction candidate and namespace combination are
4194 // too far away from the original typo based on the normalized edit
4195 // distance, then skip performing a qualified name lookup.
4196 unsigned TmpED = TC.getEditDistance(true);
4197 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4198 TypoLen / TmpED < 3)
4199 continue;
4200
4201 Result.clear();
4202 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4203 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4204 continue;
4205
4206 // Any corrections added below will be validated in subsequent
4207 // iterations of the main while() loop over the Consumer's contents.
4208 switch (Result.getResultKind()) {
4209 case LookupResult::Found:
4210 case LookupResult::FoundOverloaded: {
4211 if (SS && SS->isValid()) {
4212 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4213 std::string OldQualified;
4214 llvm::raw_string_ostream OldOStream(OldQualified);
4215 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4216 OldOStream << Typo->getName();
4217 // If correction candidate would be an identical written qualified
Raphael Isemannb23ccec2018-12-10 12:37:46 +00004218 // identifier, then the existing CXXScopeSpec probably included a
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004219 // typedef that didn't get accounted for properly.
4220 if (OldOStream.str() == NewQualified)
4221 break;
4222 }
4223 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4224 TRD != TRDEnd; ++TRD) {
4225 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4226 NSType ? NSType->getAsCXXRecordDecl()
4227 : nullptr,
4228 TRD.getPair()) == Sema::AR_accessible)
4229 TC.addCorrectionDecl(*TRD);
4230 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004231 if (TC.isResolved()) {
4232 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004233 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004234 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004235 break;
4236 }
4237 case LookupResult::NotFound:
4238 case LookupResult::NotFoundInCurrentInstantiation:
4239 case LookupResult::Ambiguous:
4240 case LookupResult::FoundUnresolvedValue:
4241 break;
4242 }
4243 }
4244 }
4245 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004246}
4247
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004248TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4249 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004250 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004251 if (NestedNameSpecifier *NNS =
4252 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4253 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4254 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4255
4256 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4257 }
4258 // Build the list of identifiers that would be used for an absolute
4259 // (from the global context) NestedNameSpecifier referring to the current
4260 // context.
David Majnemerf7e36092016-06-23 00:15:04 +00004261 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4262 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004263 CurContextIdentifiers.push_back(ND->getIdentifier());
4264 }
4265
4266 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004267 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4268 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4269 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004270}
4271
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004272auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4273 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004274 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004275 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004276 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004277 DC = DC->getLookupParent()) {
4278 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4279 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4280 !(ND && ND->isAnonymousNamespace()))
4281 Chain.push_back(DC->getPrimaryContext());
4282 }
4283 return Chain;
4284}
4285
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004286unsigned
4287TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4288 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004289 unsigned NumSpecifiers = 0;
David Majnemerf7e36092016-06-23 00:15:04 +00004290 for (DeclContext *C : llvm::reverse(DeclChain)) {
4291 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004292 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4293 ++NumSpecifiers;
David Majnemerf7e36092016-06-23 00:15:04 +00004294 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004295 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4296 RD->getTypeForDecl());
4297 ++NumSpecifiers;
4298 }
4299 }
4300 return NumSpecifiers;
4301}
4302
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004303void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4304 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004305 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004306 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004307 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004308 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4309
4310 // Eliminate common elements from the two DeclContext chains.
David Majnemerf7e36092016-06-23 00:15:04 +00004311 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4312 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4313 break;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004314 NamespaceDeclChain.pop_back();
4315 }
4316
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004317 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004318 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004319
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004320 // Add an explicit leading '::' specifier if needed.
4321 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004322 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004323 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004324 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004325 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004326 } else if (NamedDecl *ND =
4327 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004328 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004329 bool SameNameSpecifier = false;
4330 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004331 CurNameSpecifierIdentifiers.end(),
4332 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004333 std::string NewNameSpecifier;
4334 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4335 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4336 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4337 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4338 SpecifierOStream.flush();
4339 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004340 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004341 if (SameNameSpecifier ||
4342 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4343 Name) != CurContextIdentifiers.end()) {
4344 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4345 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4346 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004347 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004348 }
4349 }
4350
4351 // If the built NestedNameSpecifier would be replacing an existing
4352 // NestedNameSpecifier, use the number of component identifiers that
4353 // would need to be changed as the edit distance instead of the number
4354 // of components in the built NestedNameSpecifier.
4355 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4356 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4357 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4358 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004359 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4360 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004361 }
4362
Hans Wennborg66010132014-06-11 21:24:13 +00004363 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4364 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004365}
4366
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004367/// Perform name lookup for a possible result for typo correction.
Douglas Gregord507d772010-10-20 03:06:34 +00004368static void LookupPotentialTypoResult(Sema &SemaRef,
4369 LookupResult &Res,
4370 IdentifierInfo *Name,
4371 Scope *S, CXXScopeSpec *SS,
4372 DeclContext *MemberContext,
4373 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004374 bool isObjCIvarLookup,
4375 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004376 Res.suppressDiagnostics();
4377 Res.clear();
4378 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004379 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004381 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004382 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004383 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4384 Res.addDecl(Ivar);
4385 Res.resolveKind();
4386 return;
4387 }
4388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389
Manman Ren5b786402016-01-28 18:49:28 +00004390 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4391 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregord507d772010-10-20 03:06:34 +00004392 Res.addDecl(Prop);
4393 Res.resolveKind();
4394 return;
4395 }
4396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
Douglas Gregord507d772010-10-20 03:06:34 +00004398 SemaRef.LookupQualifiedName(Res, MemberContext);
4399 return;
4400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
4402 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004403 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404
Douglas Gregord507d772010-10-20 03:06:34 +00004405 // Fake ivar lookup; this should really be part of
4406 // LookupParsedName.
4407 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4408 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004410 (Res.isSingleResult() &&
4411 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004413 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4414 Res.addDecl(IV);
4415 Res.resolveKind();
4416 }
4417 }
4418 }
4419}
4420
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004421/// Add keywords to the consumer as possible typo corrections.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004422static void AddKeywordsToConsumer(Sema &SemaRef,
4423 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004424 Scope *S, CorrectionCandidateCallback &CCC,
4425 bool AfterNestedNameSpecifier) {
4426 if (AfterNestedNameSpecifier) {
4427 // For 'X::', we know exactly which keywords can appear next.
4428 Consumer.addKeywordResult("template");
4429 if (CCC.WantExpressionKeywords)
4430 Consumer.addKeywordResult("operator");
4431 return;
4432 }
4433
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004434 if (CCC.WantObjCSuper)
4435 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004436
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004437 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004438 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004439 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004440 "char", "const", "double", "enum", "float", "int", "long", "short",
Fangrui Song6907ce22018-07-30 19:24:48 +00004441 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004442 "_Complex", "_Imaginary",
4443 // storage-specifiers as well
4444 "extern", "inline", "static", "typedef"
4445 };
4446
Craig Toppere5ce8312013-07-15 03:38:40 +00004447 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004448 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4449 Consumer.addKeywordResult(CTypeSpecs[I]);
4450
David Blaikiebbafb8a2012-03-11 07:00:24 +00004451 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004452 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004453 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004454 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004455 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004456 Consumer.addKeywordResult("_Bool");
Fangrui Song6907ce22018-07-30 19:24:48 +00004457
David Blaikiebbafb8a2012-03-11 07:00:24 +00004458 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004459 Consumer.addKeywordResult("class");
4460 Consumer.addKeywordResult("typename");
4461 Consumer.addKeywordResult("wchar_t");
4462
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004463 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004464 Consumer.addKeywordResult("char16_t");
4465 Consumer.addKeywordResult("char32_t");
4466 Consumer.addKeywordResult("constexpr");
4467 Consumer.addKeywordResult("decltype");
4468 Consumer.addKeywordResult("thread_local");
4469 }
4470 }
4471
Richard Smith7b301e22018-05-24 21:51:52 +00004472 if (SemaRef.getLangOpts().GNUKeywords)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004473 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004474 } else if (CCC.WantFunctionLikeCasts) {
4475 static const char *const CastableTypeSpecs[] = {
4476 "char", "double", "float", "int", "long", "short",
4477 "signed", "unsigned", "void"
4478 };
4479 for (auto *kw : CastableTypeSpecs)
4480 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004481 }
4482
David Blaikiebbafb8a2012-03-11 07:00:24 +00004483 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004484 Consumer.addKeywordResult("const_cast");
4485 Consumer.addKeywordResult("dynamic_cast");
4486 Consumer.addKeywordResult("reinterpret_cast");
4487 Consumer.addKeywordResult("static_cast");
4488 }
4489
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004490 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004491 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004492 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004493 Consumer.addKeywordResult("false");
4494 Consumer.addKeywordResult("true");
4495 }
4496
David Blaikiebbafb8a2012-03-11 07:00:24 +00004497 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004498 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004499 "delete", "new", "operator", "throw", "typeid"
4500 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004501 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004502 for (unsigned I = 0; I != NumCXXExprs; ++I)
4503 Consumer.addKeywordResult(CXXExprs[I]);
4504
4505 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4506 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4507 Consumer.addKeywordResult("this");
4508
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004509 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004510 Consumer.addKeywordResult("alignof");
4511 Consumer.addKeywordResult("nullptr");
4512 }
4513 }
Jordan Rose58d54722012-06-30 21:33:57 +00004514
4515 if (SemaRef.getLangOpts().C11) {
4516 // FIXME: We should not suggest _Alignof if the alignof macro
4517 // is present.
4518 Consumer.addKeywordResult("_Alignof");
4519 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004520 }
4521
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004522 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004523 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4524 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004525 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004526 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004527 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004528 for (unsigned I = 0; I != NumCStmts; ++I)
4529 Consumer.addKeywordResult(CStmts[I]);
4530
David Blaikiebbafb8a2012-03-11 07:00:24 +00004531 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004532 Consumer.addKeywordResult("catch");
4533 Consumer.addKeywordResult("try");
4534 }
4535
4536 if (S && S->getBreakParent())
4537 Consumer.addKeywordResult("break");
4538
4539 if (S && S->getContinueParent())
4540 Consumer.addKeywordResult("continue");
4541
Reid Kleckner87a31802018-03-12 21:43:02 +00004542 if (SemaRef.getCurFunction() &&
4543 !SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004544 Consumer.addKeywordResult("case");
4545 Consumer.addKeywordResult("default");
4546 }
4547 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004548 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004549 Consumer.addKeywordResult("namespace");
4550 Consumer.addKeywordResult("template");
4551 }
4552
4553 if (S && S->isClassScope()) {
4554 Consumer.addKeywordResult("explicit");
4555 Consumer.addKeywordResult("friend");
4556 Consumer.addKeywordResult("mutable");
4557 Consumer.addKeywordResult("private");
4558 Consumer.addKeywordResult("protected");
4559 Consumer.addKeywordResult("public");
4560 Consumer.addKeywordResult("virtual");
4561 }
4562 }
4563
David Blaikiebbafb8a2012-03-11 07:00:24 +00004564 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004565 Consumer.addKeywordResult("using");
4566
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004567 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004568 Consumer.addKeywordResult("static_assert");
4569 }
4570 }
4571}
4572
Kaelyn Takata6c759512014-10-27 18:07:37 +00004573std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4574 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4575 Scope *S, CXXScopeSpec *SS,
4576 std::unique_ptr<CorrectionCandidateCallback> CCC,
4577 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004578 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004579
4580 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4581 DisableTypoCorrection)
4582 return nullptr;
4583
4584 // In Microsoft mode, don't perform typo correction in a template member
4585 // function dependent context because it interferes with the "lookup into
4586 // dependent bases of class templates" feature.
4587 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4588 isa<CXXMethodDecl>(CurContext))
4589 return nullptr;
4590
4591 // We only attempt to correct typos for identifiers.
4592 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4593 if (!Typo)
4594 return nullptr;
4595
4596 // If the scope specifier itself was invalid, don't try to correct
4597 // typos.
4598 if (SS && SS->isInvalid())
4599 return nullptr;
4600
Richard Smith696e3122017-02-23 01:43:54 +00004601 // Never try to correct typos during any kind of code synthesis.
4602 if (!CodeSynthesisContexts.empty())
Kaelyn Takata6c759512014-10-27 18:07:37 +00004603 return nullptr;
4604
4605 // Don't try to correct 'super'.
4606 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4607 return nullptr;
4608
4609 // Abort if typo correction already failed for this specific typo.
4610 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4611 if (locs != TypoCorrectionFailures.end() &&
4612 locs->second.count(TypoName.getLoc()))
4613 return nullptr;
4614
4615 // Don't try to correct the identifier "vector" when in AltiVec mode.
4616 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4617 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004618 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004619 return nullptr;
4620
Nick Lewycky24653262014-12-16 21:39:02 +00004621 // Provide a stop gap for files that are just seriously broken. Trying
4622 // to correct all typos can turn into a HUGE performance penalty, causing
4623 // some files to take minutes to get rejected by the parser.
4624 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4625 if (Limit && TyposCorrected >= Limit)
4626 return nullptr;
4627 ++TyposCorrected;
4628
Kaelyn Takata6c759512014-10-27 18:07:37 +00004629 // If we're handling a missing symbol error, using modules, and the
4630 // special search all modules option is used, look for a missing import.
4631 if (ErrorRecovery && getLangOpts().Modules &&
4632 getLangOpts().ModulesSearchAll) {
4633 // The following has the side effect of loading the missing module.
4634 getModuleLoader().lookupMissingImports(Typo->getName(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004635 TypoName.getBeginLoc());
Kaelyn Takata6c759512014-10-27 18:07:37 +00004636 }
4637
4638 CorrectionCandidateCallback &CCCRef = *CCC;
4639 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4640 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4641 EnteringContext);
4642
Kaelyn Takata6c759512014-10-27 18:07:37 +00004643 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004644 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004645 DeclContext *QualifiedDC = MemberContext;
4646 if (MemberContext) {
4647 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4648
4649 // Look in qualified interfaces.
4650 if (OPT) {
4651 for (auto *I : OPT->quals())
4652 LookupVisibleDecls(I, LookupKind, *Consumer);
4653 }
4654 } else if (SS && SS->isSet()) {
4655 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4656 if (!QualifiedDC)
4657 return nullptr;
4658
Kaelyn Takata6c759512014-10-27 18:07:37 +00004659 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4660 } else {
4661 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004662 }
4663
4664 // Determine whether we are going to search in the various namespaces for
4665 // corrections.
4666 bool SearchNamespaces
4667 = getLangOpts().CPlusPlus &&
4668 (IsUnqualifiedLookup || (SS && SS->isSet()));
4669
4670 if (IsUnqualifiedLookup || SearchNamespaces) {
4671 // For unqualified lookup, look through all of the names that we have
4672 // seen in this translation unit.
4673 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4674 for (const auto &I : Context.Idents)
4675 Consumer->FoundName(I.getKey());
4676
4677 // Walk through identifiers in external identifier sources.
4678 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4679 if (IdentifierInfoLookup *External
4680 = Context.Idents.getExternalIdentifierLookup()) {
4681 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4682 do {
4683 StringRef Name = Iter->Next();
4684 if (Name.empty())
4685 break;
4686
4687 Consumer->FoundName(Name);
4688 } while (true);
4689 }
4690 }
4691
4692 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4693
4694 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4695 // to search those namespaces.
4696 if (SearchNamespaces) {
4697 // Load any externally-known namespaces.
4698 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4699 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4700 LoadedExternalKnownNamespaces = true;
4701 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4702 for (auto *N : ExternalKnownNamespaces)
4703 KnownNamespaces[N] = true;
4704 }
4705
4706 Consumer->addNamespaces(KnownNamespaces);
4707 }
4708
4709 return Consumer;
4710}
4711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004712/// Try to "correct" a typo in the source code by finding
Douglas Gregor2d435302009-12-30 17:04:44 +00004713/// visible declarations whose names are similar to the name that was
4714/// present in the source code.
4715///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004716/// \param TypoName the \c DeclarationNameInfo structure that contains
4717/// the name that was present in the source code along with its location.
4718///
4719/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004720///
4721/// \param S the scope in which name lookup occurs.
4722///
4723/// \param SS the nested-name-specifier that precedes the name we're
4724/// looking for, if present.
4725///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004726/// \param CCC A CorrectionCandidateCallback object that provides further
4727/// validation of typo correction candidates. It also provides flags for
4728/// determining the set of keywords permitted.
4729///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004730/// \param MemberContext if non-NULL, the context in which to look for
4731/// a member access expression.
4732///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004733/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004734/// the nested-name-specifier SS.
4735///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004736/// \param OPT when non-NULL, the search for visible declarations will
4737/// also walk the protocols in the qualified interfaces of \p OPT.
4738///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004739/// \returns a \c TypoCorrection containing the corrected name if the typo
4740/// along with information such as the \c NamedDecl where the corrected name
4741/// was declared, and any additional \c NestedNameSpecifier needed to access
4742/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4743TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4744 Sema::LookupNameKind LookupKind,
4745 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004746 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004747 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004748 DeclContext *MemberContext,
4749 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004750 const ObjCObjectPointerType *OPT,
4751 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004752 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4753
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004754 // Always let the ExternalSource have the first chance at correction, even
4755 // if we would otherwise have given up.
4756 if (ExternalSource) {
4757 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004758 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004759 return Correction;
4760 }
4761
Kaelyn Takata6c759512014-10-27 18:07:37 +00004762 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4763 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4764 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4765 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4766 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
Kaelyn Takata6c759512014-10-27 18:07:37 +00004768 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004769 auto Consumer = makeTypoCorrectionConsumer(
4770 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004771 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004772
Kaelyn Takata6c759512014-10-27 18:07:37 +00004773 if (!Consumer)
4774 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004776 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004777 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004778 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004779
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004780 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4781 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004782 unsigned ED = Consumer->getBestEditDistance(true);
4783 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004784 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004785 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004786
Kaelyn Takata6c759512014-10-27 18:07:37 +00004787 TypoCorrection BestTC = Consumer->getNextCorrection();
4788 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004789 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004790 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004791
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004792 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004793
Kaelyn Takata6c759512014-10-27 18:07:37 +00004794 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004795 // If this was an unqualified lookup and we believe the callback
4796 // object wouldn't have filtered out possible corrections, note
4797 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004798 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004799 }
4800
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004801 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004802 if (!SecondBestTC ||
4803 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4804 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004806 // Don't correct to a keyword that's the same as the typo; the keyword
4807 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004808 if (ED == 0 && Result.isKeyword())
4809 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004810
David Blaikie04ea41c2012-10-12 20:00:44 +00004811 TypoCorrection TC = Result;
4812 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004813 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004814 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004815 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004816 // Prefer 'super' when we're completing in a message-receiver
4817 // context.
4818
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004819 if (BestTC.getCorrection().getAsString() != "super") {
4820 if (SecondBestTC.getCorrection().getAsString() == "super")
4821 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004822 else if ((*Consumer)["super"].front().isKeyword())
4823 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004824 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004825 // Don't correct to a keyword that's the same as the typo; the keyword
4826 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004827 if (BestTC.getEditDistance() == 0 ||
4828 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004829 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004831 BestTC.setCorrectionRange(SS, TypoName);
4832 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004835 // Record the failure's location if needed and return an empty correction. If
4836 // this was an unqualified lookup and we believe the callback object did not
4837 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004838 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004839}
4840
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004841/// Try to "correct" a typo in the source code by finding
Kaelyn Takata6c759512014-10-27 18:07:37 +00004842/// visible declarations whose names are similar to the name that was
4843/// present in the source code.
4844///
4845/// \param TypoName the \c DeclarationNameInfo structure that contains
4846/// the name that was present in the source code along with its location.
4847///
4848/// \param LookupKind the name-lookup criteria used to search for the name.
4849///
4850/// \param S the scope in which name lookup occurs.
4851///
4852/// \param SS the nested-name-specifier that precedes the name we're
4853/// looking for, if present.
4854///
4855/// \param CCC A CorrectionCandidateCallback object that provides further
4856/// validation of typo correction candidates. It also provides flags for
4857/// determining the set of keywords permitted.
4858///
4859/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4860/// diagnostics when the actual typo correction is attempted.
4861///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004862/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4863/// Expr from a typo correction candidate.
4864///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004865/// \param MemberContext if non-NULL, the context in which to look for
4866/// a member access expression.
4867///
4868/// \param EnteringContext whether we're entering the context described by
4869/// the nested-name-specifier SS.
4870///
4871/// \param OPT when non-NULL, the search for visible declarations will
4872/// also walk the protocols in the qualified interfaces of \p OPT.
4873///
4874/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4875/// Expr representing the result of performing typo correction, or nullptr if
4876/// typo correction is not possible. If nullptr is returned, no diagnostics will
4877/// be emitted and it is the responsibility of the caller to emit any that are
4878/// needed.
4879TypoExpr *Sema::CorrectTypoDelayed(
4880 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4881 Scope *S, CXXScopeSpec *SS,
4882 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004883 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004884 DeclContext *MemberContext, bool EnteringContext,
4885 const ObjCObjectPointerType *OPT) {
4886 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4887
Kaelyn Takata6c759512014-10-27 18:07:37 +00004888 auto Consumer = makeTypoCorrectionConsumer(
4889 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004890 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004891
Benjamin Kramerb8727332016-05-19 10:46:10 +00004892 // Give the external sema source a chance to correct the typo.
4893 TypoCorrection ExternalTypo;
4894 if (ExternalSource && Consumer) {
4895 ExternalTypo = ExternalSource->CorrectTypo(
Benjamin Kramer97d7a662016-05-19 21:53:33 +00004896 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
4897 MemberContext, EnteringContext, OPT);
Benjamin Kramerb8727332016-05-19 10:46:10 +00004898 if (ExternalTypo)
4899 Consumer->addCorrection(ExternalTypo);
4900 }
4901
Kaelyn Takata6c759512014-10-27 18:07:37 +00004902 if (!Consumer || Consumer->empty())
4903 return nullptr;
4904
4905 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4906 // is not more that about a third of the length of the typo's identifier.
4907 unsigned ED = Consumer->getBestEditDistance(true);
4908 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Benjamin Kramerb8727332016-05-19 10:46:10 +00004909 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004910 return nullptr;
4911
4912 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004913 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004914}
4915
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004916void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4917 if (!CDecl) return;
4918
4919 if (isKeyword())
4920 CorrectionDecls.clear();
4921
Richard Smithde6d6c42015-12-29 19:43:10 +00004922 CorrectionDecls.push_back(CDecl);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004923
4924 if (!CorrectionName)
4925 CorrectionName = CDecl->getDeclName();
4926}
4927
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004928std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4929 if (CorrectionNameSpec) {
4930 std::string tmpBuffer;
4931 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4932 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004933 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004934 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004935 }
4936
4937 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004938}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004939
Nico Weberb58e51c2014-11-19 05:21:39 +00004940bool CorrectionCandidateCallback::ValidateCandidate(
4941 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004942 if (!candidate.isResolved())
4943 return true;
4944
4945 if (candidate.isKeyword())
4946 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4947 WantRemainingKeywords || WantObjCSuper;
4948
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004949 bool HasNonType = false;
4950 bool HasStaticMethod = false;
4951 bool HasNonStaticMethod = false;
4952 for (Decl *D : candidate) {
4953 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4954 D = FTD->getTemplatedDecl();
4955 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4956 if (Method->isStatic())
4957 HasStaticMethod = true;
4958 else
4959 HasNonStaticMethod = true;
4960 }
4961 if (!isa<TypeDecl>(D))
4962 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004963 }
4964
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004965 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4966 !candidate.getCorrectionSpecifier())
4967 return false;
4968
4969 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004970}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004971
4972FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004973 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004974 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004975 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004976 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004977 WantTypeSpecifiers = false;
4978 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004979 WantRemainingKeywords = false;
4980}
4981
4982bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4983 if (!candidate.getCorrectionDecl())
4984 return candidate.isKeyword();
4985
Aaron Ballman1e606f42014-07-15 22:03:49 +00004986 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004987 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004988 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004989 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4990 FD = FTD->getTemplatedDecl();
4991 if (!HasExplicitTemplateArgs && !FD) {
4992 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4993 // If the Decl is neither a function nor a template function,
4994 // determine if it is a pointer or reference to a function. If so,
4995 // check against the number of arguments expected for the pointee.
4996 QualType ValType = cast<ValueDecl>(ND)->getType();
Erik Pilkington1c5ae9b2018-07-10 02:15:07 +00004997 if (ValType.isNull())
4998 continue;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004999 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5000 ValType = ValType->getPointeeType();
5001 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00005002 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005003 return true;
5004 }
5005 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005006
5007 // Skip the current candidate if it is not a FunctionDecl or does not accept
5008 // the current number of arguments.
5009 if (!FD || !(FD->getNumParams() >= NumArgs &&
5010 FD->getMinRequiredArguments() <= NumArgs))
5011 continue;
5012
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005013 // If the current candidate is a non-static C++ method, skip the candidate
5014 // unless the method being corrected--or the current DeclContext, if the
5015 // function being corrected is not a method--is a method in the same class
5016 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005017 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005018 if (MemberFn || !MD->isStatic()) {
5019 CXXMethodDecl *CurMD =
5020 MemberFn
5021 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5022 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005023 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00005024 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005025 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5026 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5027 continue;
5028 }
5029 }
5030 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005031 }
5032 return false;
5033}
Richard Smithf9b15102013-08-17 00:46:16 +00005034
5035void Sema::diagnoseTypo(const TypoCorrection &Correction,
5036 const PartialDiagnostic &TypoDiag,
5037 bool ErrorRecovery) {
5038 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5039 ErrorRecovery);
5040}
5041
Richard Smithe156254d2013-08-20 20:35:18 +00005042/// Find which declaration we should import to provide the definition of
5043/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00005044static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5045 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005046 return VD->getDefinition();
Yaron Keren18c3d062016-07-13 19:04:51 +00005047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5048 return FD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005049 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005050 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005051 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005052 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005053 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005054 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005055 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005056 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005057 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00005058}
5059
Richard Smithf2b1eb92015-06-15 20:15:48 +00005060void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005061 MissingImportKind MIK, bool Recover) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005062 // Suggest importing a module providing the definition of this entity, if
5063 // possible.
5064 NamedDecl *Def = getDefinitionToImport(Decl);
5065 if (!Def)
5066 Def = Decl;
5067
Richard Smithc4577662018-09-12 02:13:47 +00005068 Module *Owner = getOwningModule(Def);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005069 assert(Owner && "definition of hidden declaration is not in a module");
5070
Richard Smith35c1df52015-06-17 20:16:32 +00005071 llvm::SmallVector<Module*, 8> OwningModules;
5072 OwningModules.push_back(Owner);
Richard Smithc4577662018-09-12 02:13:47 +00005073 auto Merged = Context.getModulesWithMergedDefinition(Def);
Richard Smith35c1df52015-06-17 20:16:32 +00005074 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5075
Richard Smith6739a102016-05-05 00:56:12 +00005076 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
Richard Smith35c1df52015-06-17 20:16:32 +00005077 Recover);
5078}
5079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005080/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
Richard Smith4eb83932016-04-27 21:57:05 +00005081/// suggesting the addition of a #include of the specified file.
5082static std::string getIncludeStringForHeader(Preprocessor &PP,
5083 const FileEntry *E) {
5084 bool IsSystem;
5085 auto Path =
5086 PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem);
5087 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5088}
5089
Richard Smith35c1df52015-06-17 20:16:32 +00005090void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5091 SourceLocation DeclLoc,
5092 ArrayRef<Module *> Modules,
5093 MissingImportKind MIK, bool Recover) {
5094 assert(!Modules.empty());
5095
Richard Smith54f04402017-05-18 02:29:20 +00005096 // Weed out duplicates from module list.
5097 llvm::SmallVector<Module*, 8> UniqueModules;
5098 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5099 for (auto *M : Modules)
5100 if (UniqueModuleSet.insert(M).second)
5101 UniqueModules.push_back(M);
5102 Modules = UniqueModules;
5103
Richard Smith35c1df52015-06-17 20:16:32 +00005104 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005105 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00005106 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00005107 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005108 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00005109 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005110 ModuleList += "[...]";
5111 break;
5112 }
5113 ModuleList += M->getFullModuleName();
5114 }
5115
Richard Smith35c1df52015-06-17 20:16:32 +00005116 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5117 << (int)MIK << Decl << ModuleList;
Richard Smithcbf7d8a2017-05-19 23:49:00 +00005118 } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics(
5119 UseLoc, Modules[0], DeclLoc)) {
Richard Smith4eb83932016-04-27 21:57:05 +00005120 // The right way to make the declaration visible is to include a header;
5121 // suggest doing so.
5122 //
5123 // FIXME: Find a smart place to suggest inserting a #include, and add
5124 // a FixItHint there.
5125 Diag(UseLoc, diag::err_module_unimported_use_header)
5126 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5127 << getIncludeStringForHeader(PP, E);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005128 } else {
Richard Smithacef17a2016-05-05 02:14:06 +00005129 // FIXME: Add a FixItHint that imports the corresponding module.
Richard Smith35c1df52015-06-17 20:16:32 +00005130 Diag(UseLoc, diag::err_module_unimported_use)
5131 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00005132 }
Richard Smith35c1df52015-06-17 20:16:32 +00005133
5134 unsigned DiagID;
5135 switch (MIK) {
5136 case MissingImportKind::Declaration:
5137 DiagID = diag::note_previous_declaration;
5138 break;
5139 case MissingImportKind::Definition:
5140 DiagID = diag::note_previous_definition;
5141 break;
5142 case MissingImportKind::DefaultArgument:
5143 DiagID = diag::note_default_argument_declared_here;
5144 break;
Richard Smith6739a102016-05-05 00:56:12 +00005145 case MissingImportKind::ExplicitSpecialization:
5146 DiagID = diag::note_explicit_specialization_declared_here;
5147 break;
5148 case MissingImportKind::PartialSpecialization:
5149 DiagID = diag::note_partial_specialization_declared_here;
5150 break;
Richard Smith35c1df52015-06-17 20:16:32 +00005151 }
5152 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005153
5154 // Try to recover by implicitly importing this module.
5155 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00005156 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005157}
5158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005159/// Diagnose a successfully-corrected typo. Separated from the correction
Richard Smithf9b15102013-08-17 00:46:16 +00005160/// itself to allow external validation of the result, etc.
5161///
5162/// \param Correction The result of performing typo correction.
5163/// \param TypoDiag The diagnostic to produce. This will have the corrected
5164/// string added to it (and usually also a fixit).
5165/// \param PrevNote A note to use when indicating the location of the entity to
5166/// which we are correcting. Will have the correction string added to it.
5167/// \param ErrorRecovery If \c true (the default), the caller is going to
5168/// recover from the typo as if the corrected string had been typed.
5169/// In this case, \c PDiag must be an error, and we will attach a fixit
5170/// to it.
5171void Sema::diagnoseTypo(const TypoCorrection &Correction,
5172 const PartialDiagnostic &TypoDiag,
5173 const PartialDiagnostic &PrevNote,
5174 bool ErrorRecovery) {
5175 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5176 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5177 FixItHint FixTypo = FixItHint::CreateReplacement(
5178 Correction.getCorrectionRange(), CorrectedStr);
5179
Richard Smithe156254d2013-08-20 20:35:18 +00005180 // Maybe we're just missing a module import.
5181 if (Correction.requiresImport()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00005182 NamedDecl *Decl = Correction.getFoundDecl();
Richard Smithe156254d2013-08-20 20:35:18 +00005183 assert(Decl && "import required but no declaration to import");
5184
Richard Smithf2b1eb92015-06-15 20:15:48 +00005185 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005186 MissingImportKind::Declaration, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00005187 return;
5188 }
5189
Richard Smithf9b15102013-08-17 00:46:16 +00005190 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5191 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5192
5193 NamedDecl *ChosenDecl =
Richard Smithde6d6c42015-12-29 19:43:10 +00005194 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00005195 if (PrevNote.getDiagID() && ChosenDecl)
5196 Diag(ChosenDecl->getLocation(), PrevNote)
5197 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
Benjamin Kramer7de99692016-11-16 18:15:26 +00005198
5199 // Add any extra diagnostics.
5200 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5201 Diag(Correction.getCorrectionRange().getBegin(), PD);
Richard Smithf9b15102013-08-17 00:46:16 +00005202}
Kaelyn Takata6c759512014-10-27 18:07:37 +00005203
Kaelyn Takata8363f042014-10-27 18:07:42 +00005204TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5205 TypoDiagnosticGenerator TDG,
5206 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00005207 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5208 auto TE = new (Context) TypoExpr(Context.DependentTy);
5209 auto &State = DelayedTypos[TE];
5210 State.Consumer = std::move(TCC);
5211 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00005212 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00005213 return TE;
5214}
5215
5216const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5217 auto Entry = DelayedTypos.find(TE);
5218 assert(Entry != DelayedTypos.end() &&
5219 "Failed to get the state for a TypoExpr!");
5220 return Entry->second;
5221}
5222
5223void Sema::clearDelayedTypo(TypoExpr *TE) {
5224 DelayedTypos.erase(TE);
5225}
Richard Smithba3a4f92016-01-12 21:59:26 +00005226
5227void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5228 DeclarationNameInfo Name(II, IILoc);
5229 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5230 R.suppressDiagnostics();
5231 R.setHideTags(false);
5232 LookupName(R, S);
5233 R.dump();
5234}