1//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements name lookup for C, C++, Objective-C, and
10// Objective-C++.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclLookups.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/Basic/Builtins.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "clang/Lex/ModuleLoader.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Overload.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "clang/Sema/SemaInternal.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "clang/Sema/TypoCorrection.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/TinyPtrVector.h"
41#include "llvm/ADT/edit_distance.h"
42#include "llvm/Support/ErrorHandling.h"
43#include <algorithm>
44#include <iterator>
45#include <list>
46#include <set>
47#include <utility>
48#include <vector>
49
50#include "OpenCLBuiltins.inc"
51
52using namespace clang;
53using namespace sema;
54
55namespace {
56 class UnqualUsingEntry {
57 const DeclContext *Nominated;
58 const DeclContext *CommonAncestor;
59
60 public:
61 UnqualUsingEntry(const DeclContext *Nominated,
62 const DeclContext *CommonAncestor)
63 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
64 }
65
66 const DeclContext *getCommonAncestor() const {
67 return CommonAncestor;
68 }
69
70 const DeclContext *getNominatedNamespace() const {
71 return Nominated;
72 }
73
74 // Sort by the pointer value of the common ancestor.
75 struct Comparator {
76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
77 return L.getCommonAncestor() < R.getCommonAncestor();
78 }
79
80 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
81 return E.getCommonAncestor() < DC;
82 }
83
84 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
85 return DC < E.getCommonAncestor();
86 }
87 };
88 };
89
90 /// A collection of using directives, as used by C++ unqualified
91 /// lookup.
92 class UnqualUsingDirectiveSet {
93 Sema &SemaRef;
94
95 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
96
97 ListTy list;
98 llvm::SmallPtrSet<DeclContext*, 8> visited;
99
100 public:
101 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
102
103 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
104 // C++ [namespace.udir]p1:
105 // During unqualified name lookup, the names appear as if they
106 // were declared in the nearest enclosing namespace which contains
107 // both the using-directive and the nominated namespace.
108 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
109 assert(InnermostFileDC && InnermostFileDC->isFileContext());
110
111 for (; S; S = S->getParent()) {
112 // C++ [namespace.udir]p1:
113 // A using-directive shall not appear in class scope, but may
114 // appear in namespace scope or in block scope.
115 DeclContext *Ctx = S->getEntity();
116 if (Ctx && Ctx->isFileContext()) {
117 visit(Ctx, Ctx);
118 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
119 for (auto *I : S->using_directives())
120 if (SemaRef.isVisible(I))
121 visit(I, InnermostFileDC);
122 }
123 }
124 }
125
126 // Visits a context and collect all of its using directives
127 // recursively. Treats all using directives as if they were
128 // declared in the context.
129 //
130 // A given context is only every visited once, so it is important
131 // that contexts be visited from the inside out in order to get
132 // the effective DCs right.
133 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
134 if (!visited.insert(DC).second)
135 return;
136
137 addUsingDirectives(DC, EffectiveDC);
138 }
139
140 // Visits a using directive and collects all of its using
141 // directives recursively. Treats all using directives as if they
142 // were declared in the effective DC.
143 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
144 DeclContext *NS = UD->getNominatedNamespace();
145 if (!visited.insert(NS).second)
146 return;
147
148 addUsingDirective(UD, EffectiveDC);
149 addUsingDirectives(NS, EffectiveDC);
150 }
151
152 // Adds all the using directives in a context (and those nominated
153 // by its using directives, transitively) as if they appeared in
154 // the given effective context.
155 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
156 SmallVector<DeclContext*, 4> queue;
157 while (true) {
158 for (auto UD : DC->using_directives()) {
159 DeclContext *NS = UD->getNominatedNamespace();
160 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
161 addUsingDirective(UD, EffectiveDC);
162 queue.push_back(NS);
163 }
164 }
165
166 if (queue.empty())
167 return;
168
169 DC = queue.pop_back_val();
170 }
171 }
172
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
179 // the first.
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
186 Common = Common->getPrimaryContext();
187
188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
189 }
190
191 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
192
193 typedef ListTy::const_iterator const_iterator;
194
195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
198 llvm::iterator_range<const_iterator>
199 getNamespacesFor(DeclContext *DC) const {
200 return llvm::make_range(std::equal_range(begin(), end(),
201 DC->getPrimaryContext(),
202 UnqualUsingEntry::Comparator()));
203 }
204 };
205} // end anonymous namespace
206
207// Retrieve the set of identifier namespaces that correspond to a
208// specific kind of name lookup.
209static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
210 bool CPlusPlus,
211 bool Redeclaration) {
212 unsigned IDNS = 0;
213 switch (NameKind) {
214 case Sema::LookupObjCImplicitSelfParam:
215 case Sema::LookupOrdinaryName:
216 case Sema::LookupRedeclarationWithLinkage:
217 case Sema::LookupLocalFriendName:
218 case Sema::LookupDestructorName:
219 IDNS = Decl::IDNS_Ordinary;
220 if (CPlusPlus) {
221 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
222 if (Redeclaration)
223 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
224 }
225 if (Redeclaration)
226 IDNS |= Decl::IDNS_LocalExtern;
227 break;
228
229 case Sema::LookupOperatorName:
230 // Operator lookup is its own crazy thing; it is not the same
231 // as (e.g.) looking up an operator name for redeclaration.
232 assert(!Redeclaration && "cannot do redeclaration operator lookup");
233 IDNS = Decl::IDNS_NonMemberOperator;
234 break;
235
236 case Sema::LookupTagName:
237 if (CPlusPlus) {
238 IDNS = Decl::IDNS_Type;
239
240 // When looking for a redeclaration of a tag name, we add:
241 // 1) TagFriend to find undeclared friend decls
242 // 2) Namespace because they can't "overload" with tag decls.
243 // 3) Tag because it includes class templates, which can't
244 // "overload" with tag decls.
245 if (Redeclaration)
246 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
247 } else {
248 IDNS = Decl::IDNS_Tag;
249 }
250 break;
251
252 case Sema::LookupLabel:
253 IDNS = Decl::IDNS_Label;
254 break;
255
256 case Sema::LookupMemberName:
257 IDNS = Decl::IDNS_Member;
258 if (CPlusPlus)
259 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
260 break;
261
262 case Sema::LookupNestedNameSpecifierName:
263 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
264 break;
265
266 case Sema::LookupNamespaceName:
267 IDNS = Decl::IDNS_Namespace;
268 break;
269
270 case Sema::LookupUsingDeclName:
271 assert(Redeclaration && "should only be used for redecl lookup");
272 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
273 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
274 Decl::IDNS_LocalExtern;
275 break;
276
277 case Sema::LookupObjCProtocolName:
278 IDNS = Decl::IDNS_ObjCProtocol;
279 break;
280
281 case Sema::LookupOMPReductionName:
282 IDNS = Decl::IDNS_OMPReduction;
283 break;
284
285 case Sema::LookupOMPMapperName:
286 IDNS = Decl::IDNS_OMPMapper;
287 break;
288
289 case Sema::LookupAnyName:
290 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
291 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
292 | Decl::IDNS_Type;
293 break;
294 }
295 return IDNS;
296}
297
298void LookupResult::configure() {
299 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
300 isForRedeclaration());
301
302 // If we're looking for one of the allocation or deallocation
303 // operators, make sure that the implicitly-declared new and delete
304 // operators can be found.
305 switch (NameInfo.getName().getCXXOverloadedOperator()) {
306 case OO_New:
307 case OO_Delete:
308 case OO_Array_New:
309 case OO_Array_Delete:
310 getSema().DeclareGlobalNewDelete();
311 break;
312
313 default:
314 break;
315 }
316
317 // Compiler builtins are always visible, regardless of where they end
318 // up being declared.
319 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
320 if (unsigned BuiltinID = Id->getBuiltinID()) {
321 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
322 AllowHidden = true;
323 }
324 }
325}
326
327bool LookupResult::sanity() const {
328 // This function is never called by NDEBUG builds.
329 assert(ResultKind != NotFound || Decls.size() == 0);
330 assert(ResultKind != Found || Decls.size() == 1);
331 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
332 (Decls.size() == 1 &&
333 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
334 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
335 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
336 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
337 Ambiguity == AmbiguousBaseSubobjectTypes)));
338 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
339 (Ambiguity == AmbiguousBaseSubobjectTypes ||
340 Ambiguity == AmbiguousBaseSubobjects)));
341 return true;
342}
343
344// Necessary because CXXBasePaths is not complete in Sema.h
345void LookupResult::deletePaths(CXXBasePaths *Paths) {
346 delete Paths;
347}
348
349/// Get a representative context for a declaration such that two declarations
350/// will have the same context if they were found within the same scope.
351static DeclContext *getContextForScopeMatching(Decl *D) {
352 // For function-local declarations, use that function as the context. This
353 // doesn't account for scopes within the function; the caller must deal with
354 // those.
355 DeclContext *DC = D->getLexicalDeclContext();
356 if (DC->isFunctionOrMethod())
357 return DC;
358
359 // Otherwise, look at the semantic context of the declaration. The
360 // declaration must have been found there.
361 return D->getDeclContext()->getRedeclContext();
362}
363
364/// Determine whether \p D is a better lookup result than \p Existing,
365/// given that they declare the same entity.
366static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
367 NamedDecl *D, NamedDecl *Existing) {
368 // When looking up redeclarations of a using declaration, prefer a using
369 // shadow declaration over any other declaration of the same entity.
370 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
371 !isa<UsingShadowDecl>(Existing))
372 return true;
373
374 auto *DUnderlying = D->getUnderlyingDecl();
375 auto *EUnderlying = Existing->getUnderlyingDecl();
376
377 // If they have different underlying declarations, prefer a typedef over the
378 // original type (this happens when two type declarations denote the same
379 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
380 // might carry additional semantic information, such as an alignment override.
381 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
382 // declaration over a typedef. Also prefer a tag over a typedef for
383 // destructor name lookup because in some contexts we only accept a
384 // class-name in a destructor declaration.
385 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
386 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
387 bool HaveTag = isa<TagDecl>(EUnderlying);
388 bool WantTag =
389 Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName;
390 return HaveTag != WantTag;
391 }
392
393 // Pick the function with more default arguments.
394 // FIXME: In the presence of ambiguous default arguments, we should keep both,
395 // so we can diagnose the ambiguity if the default argument is needed.
396 // See C++ [over.match.best]p3.
397 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
398 auto *EFD = cast<FunctionDecl>(EUnderlying);
399 unsigned DMin = DFD->getMinRequiredArguments();
400 unsigned EMin = EFD->getMinRequiredArguments();
401 // If D has more default arguments, it is preferred.
402 if (DMin != EMin)
403 return DMin < EMin;
404 // FIXME: When we track visibility for default function arguments, check
405 // that we pick the declaration with more visible default arguments.
406 }
407
408 // Pick the template with more default template arguments.
409 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
410 auto *ETD = cast<TemplateDecl>(EUnderlying);
411 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
412 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
413 // If D has more default arguments, it is preferred. Note that default
414 // arguments (and their visibility) is monotonically increasing across the
415 // redeclaration chain, so this is a quick proxy for "is more recent".
416 if (DMin != EMin)
417 return DMin < EMin;
418 // If D has more *visible* default arguments, it is preferred. Note, an
419 // earlier default argument being visible does not imply that a later
420 // default argument is visible, so we can't just check the first one.
421 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
422 I != N; ++I) {
423 if (!S.hasVisibleDefaultArgument(
424 ETD->getTemplateParameters()->getParam(I)) &&
425 S.hasVisibleDefaultArgument(
426 DTD->getTemplateParameters()->getParam(I)))
427 return true;
428 }
429 }
430
431 // VarDecl can have incomplete array types, prefer the one with more complete
432 // array type.
433 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
434 VarDecl *EVD = cast<VarDecl>(EUnderlying);
435 if (EVD->getType()->isIncompleteType() &&
436 !DVD->getType()->isIncompleteType()) {
437 // Prefer the decl with a more complete type if visible.
438 return S.isVisible(DVD);
439 }
440 return false; // Avoid picking up a newer decl, just because it was newer.
441 }
442
443 // For most kinds of declaration, it doesn't really matter which one we pick.
444 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
445 // If the existing declaration is hidden, prefer the new one. Otherwise,
446 // keep what we've got.
447 return !S.isVisible(Existing);
448 }
449
450 // Pick the newer declaration; it might have a more precise type.
451 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
452 Prev = Prev->getPreviousDecl())
453 if (Prev == EUnderlying)
454 return true;
455 return false;
456}
457
458/// Determine whether \p D can hide a tag declaration.
459static bool canHideTag(NamedDecl *D) {
460 // C++ [basic.scope.declarative]p4:
461 // Given a set of declarations in a single declarative region [...]
462 // exactly one declaration shall declare a class name or enumeration name
463 // that is not a typedef name and the other declarations shall all refer to
464 // the same variable, non-static data member, or enumerator, or all refer
465 // to functions and function templates; in this case the class name or
466 // enumeration name is hidden.
467 // C++ [basic.scope.hiding]p2:
468 // A class name or enumeration name can be hidden by the name of a
469 // variable, data member, function, or enumerator declared in the same
470 // scope.
471 // An UnresolvedUsingValueDecl always instantiates to one of these.
472 D = D->getUnderlyingDecl();
473 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
474 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
475 isa<UnresolvedUsingValueDecl>(D);
476}
477
478/// Resolves the result kind of this lookup.
479void LookupResult::resolveKind() {
480 unsigned N = Decls.size();
481
482 // Fast case: no possible ambiguity.
483 if (N == 0) {
484 assert(ResultKind == NotFound ||
485 ResultKind == NotFoundInCurrentInstantiation);
486 return;
487 }
488
489 // If there's a single decl, we need to examine it to decide what
490 // kind of lookup this is.
491 if (N == 1) {
492 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
493 if (isa<FunctionTemplateDecl>(D))
494 ResultKind = FoundOverloaded;
495 else if (isa<UnresolvedUsingValueDecl>(D))
496 ResultKind = FoundUnresolvedValue;
497 return;
498 }
499
500 // Don't do any extra resolution if we've already resolved as ambiguous.
501 if (ResultKind == Ambiguous) return;
502
503 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
504 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
505
506 bool Ambiguous = false;
507 bool HasTag = false, HasFunction = false;
508 bool HasFunctionTemplate = false, HasUnresolved = false;
509 NamedDecl *HasNonFunction = nullptr;
510
511 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
512
513 unsigned UniqueTagIndex = 0;
514
515 unsigned I = 0;
516 while (I < N) {
517 NamedDecl *D = Decls[I]->getUnderlyingDecl();
518 D = cast<NamedDecl>(D->getCanonicalDecl());
519
520 // Ignore an invalid declaration unless it's the only one left.
521 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
522 Decls[I] = Decls[--N];
523 continue;
524 }
525
526 llvm::Optional<unsigned> ExistingI;
527
528 // Redeclarations of types via typedef can occur both within a scope
529 // and, through using declarations and directives, across scopes. There is
530 // no ambiguity if they all refer to the same type, so unique based on the
531 // canonical type.
532 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
533 QualType T = getSema().Context.getTypeDeclType(TD);
534 auto UniqueResult = UniqueTypes.insert(
535 std::make_pair(getSema().Context.getCanonicalType(T), I));
536 if (!UniqueResult.second) {
537 // The type is not unique.
538 ExistingI = UniqueResult.first->second;
539 }
540 }
541
542 // For non-type declarations, check for a prior lookup result naming this
543 // canonical declaration.
544 if (!ExistingI) {
545 auto UniqueResult = Unique.insert(std::make_pair(D, I));
546 if (!UniqueResult.second) {
547 // We've seen this entity before.
548 ExistingI = UniqueResult.first->second;
549 }
550 }
551
552 if (ExistingI) {
553 // This is not a unique lookup result. Pick one of the results and
554 // discard the other.
555 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
556 Decls[*ExistingI]))
557 Decls[*ExistingI] = Decls[I];
558 Decls[I] = Decls[--N];
559 continue;
560 }
561
562 // Otherwise, do some decl type analysis and then continue.
563
564 if (isa<UnresolvedUsingValueDecl>(D)) {
565 HasUnresolved = true;
566 } else if (isa<TagDecl>(D)) {
567 if (HasTag)
568 Ambiguous = true;
569 UniqueTagIndex = I;
570 HasTag = true;
571 } else if (isa<FunctionTemplateDecl>(D)) {
572 HasFunction = true;
573 HasFunctionTemplate = true;
574 } else if (isa<FunctionDecl>(D)) {
575 HasFunction = true;
576 } else {
577 if (HasNonFunction) {
578 // If we're about to create an ambiguity between two declarations that
579 // are equivalent, but one is an internal linkage declaration from one
580 // module and the other is an internal linkage declaration from another
581 // module, just skip it.
582 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
583 D)) {
584 EquivalentNonFunctions.push_back(D);
585 Decls[I] = Decls[--N];
586 continue;
587 }
588
589 Ambiguous = true;
590 }
591 HasNonFunction = D;
592 }
593 I++;
594 }
595
596 // C++ [basic.scope.hiding]p2:
597 // A class name or enumeration name can be hidden by the name of
598 // an object, function, or enumerator declared in the same
599 // scope. If a class or enumeration name and an object, function,
600 // or enumerator are declared in the same scope (in any order)
601 // with the same name, the class or enumeration name is hidden
602 // wherever the object, function, or enumerator name is visible.
603 // But it's still an error if there are distinct tag types found,
604 // even if they're not visible. (ref?)
605 if (N > 1 && HideTags && HasTag && !Ambiguous &&
606 (HasFunction || HasNonFunction || HasUnresolved)) {
607 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
608 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
609 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
610 getContextForScopeMatching(OtherDecl)) &&
611 canHideTag(OtherDecl))
612 Decls[UniqueTagIndex] = Decls[--N];
613 else
614 Ambiguous = true;
615 }
616
617 // FIXME: This diagnostic should really be delayed until we're done with
618 // the lookup result, in case the ambiguity is resolved by the caller.
619 if (!EquivalentNonFunctions.empty() && !Ambiguous)
620 getSema().diagnoseEquivalentInternalLinkageDeclarations(
621 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
622
623 Decls.set_size(N);
624
625 if (HasNonFunction && (HasFunction || HasUnresolved))
626 Ambiguous = true;
627
628 if (Ambiguous)
629 setAmbiguous(LookupResult::AmbiguousReference);
630 else if (HasUnresolved)
631 ResultKind = LookupResult::FoundUnresolvedValue;
632 else if (N > 1 || HasFunctionTemplate)
633 ResultKind = LookupResult::FoundOverloaded;
634 else
635 ResultKind = LookupResult::Found;
636}
637
638void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
639 CXXBasePaths::const_paths_iterator I, E;
640 for (I = P.begin(), E = P.end(); I != E; ++I)
641 for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;
642 ++DI)
643 addDecl(*DI);
644}
645
646void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
647 Paths = new CXXBasePaths;
648 Paths->swap(P);
649 addDeclsFromBasePaths(*Paths);
650 resolveKind();
651 setAmbiguous(AmbiguousBaseSubobjects);
652}
653
654void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
655 Paths = new CXXBasePaths;
656 Paths->swap(P);
657 addDeclsFromBasePaths(*Paths);
658 resolveKind();
659 setAmbiguous(AmbiguousBaseSubobjectTypes);
660}
661
662void LookupResult::print(raw_ostream &Out) {
663 Out << Decls.size() << " result(s)";
664 if (isAmbiguous()) Out << ", ambiguous";
665 if (Paths) Out << ", base paths present";
666
667 for (iterator I = begin(), E = end(); I != E; ++I) {
668 Out << "\n";
669 (*I)->print(Out, 2);
670 }
671}
672
673LLVM_DUMP_METHOD void LookupResult::dump() {
674 llvm::errs() << "lookup results for " << getLookupName().getAsString()
675 << ":\n";
676 for (NamedDecl *D : *this)
677 D->dump();
678}
679
680/// Diagnose a missing builtin type.
681static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
682 llvm::StringRef Name) {
683 S.Diag(SourceLocation(), diag::err_opencl_type_not_found)
684 << TypeClass << Name;
685 return S.Context.VoidTy;
686}
687
688/// Lookup an OpenCL enum type.
689static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
690 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
691 Sema::LookupTagName);
692 S.LookupName(Result, S.TUScope);
693 if (Result.empty())
694 return diagOpenCLBuiltinTypeError(S, "enum", Name);
695 EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
696 if (!Decl)
697 return diagOpenCLBuiltinTypeError(S, "enum", Name);
698 return S.Context.getEnumType(Decl);
699}
700
701/// Lookup an OpenCL typedef type.
702static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
703 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
704 Sema::LookupOrdinaryName);
705 S.LookupName(Result, S.TUScope);
706 if (Result.empty())
707 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
708 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
709 if (!Decl)
710 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
711 return S.Context.getTypedefType(Decl);
712}
713
714/// Get the QualType instances of the return type and arguments for an OpenCL
715/// builtin function signature.
716/// \param S (in) The Sema instance.
717/// \param OpenCLBuiltin (in) The signature currently handled.
718/// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
719/// type used as return type or as argument.
720/// Only meaningful for generic types, otherwise equals 1.
721/// \param RetTypes (out) List of the possible return types.
722/// \param ArgTypes (out) List of the possible argument types. For each
723/// argument, ArgTypes contains QualTypes for the Cartesian product
724/// of (vector sizes) x (types) .
725static void GetQualTypesForOpenCLBuiltin(
726 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
727 SmallVector<QualType, 1> &RetTypes,
728 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
729 // Get the QualType instances of the return types.
730 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
731 OCL2Qual(S, TypeTable[Sig], RetTypes);
732 GenTypeMaxCnt = RetTypes.size();
733
734 // Get the QualType instances of the arguments.
735 // First type is the return type, skip it.
736 for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {
737 SmallVector<QualType, 1> Ty;
738 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
739 Ty);
740 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
741 ArgTypes.push_back(std::move(Ty));
742 }
743}
744
745/// Create a list of the candidate function overloads for an OpenCL builtin
746/// function.
747/// \param Context (in) The ASTContext instance.
748/// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic
749/// type used as return type or as argument.
750/// Only meaningful for generic types, otherwise equals 1.
751/// \param FunctionList (out) List of FunctionTypes.
752/// \param RetTypes (in) List of the possible return types.
753/// \param ArgTypes (in) List of the possible types for the arguments.
754static void GetOpenCLBuiltinFctOverloads(
755 ASTContext &Context, unsigned GenTypeMaxCnt,
756 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
757 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
758 FunctionProtoType::ExtProtoInfo PI(
759 Context.getDefaultCallingConvention(false, false, true));
760 PI.Variadic = false;
761
762 // Do not attempt to create any FunctionTypes if there are no return types,
763 // which happens when a type belongs to a disabled extension.
764 if (RetTypes.size() == 0)
765 return;
766
767 // Create FunctionTypes for each (gen)type.
768 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
769 SmallVector<QualType, 5> ArgList;
770
771 for (unsigned A = 0; A < ArgTypes.size(); A++) {
772 // Bail out if there is an argument that has no available types.
773 if (ArgTypes[A].size() == 0)
774 return;
775
776 // Builtins such as "max" have an "sgentype" argument that represents
777 // the corresponding scalar type of a gentype. The number of gentypes
778 // must be a multiple of the number of sgentypes.
779 assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&
780 "argument type count not compatible with gentype type count");
781 unsigned Idx = IGenType % ArgTypes[A].size();
782 ArgList.push_back(ArgTypes[A][Idx]);
783 }
784
785 FunctionList.push_back(Context.getFunctionType(
786 RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));
787 }
788}
789
790/// When trying to resolve a function name, if isOpenCLBuiltin() returns a
791/// non-null <Index, Len> pair, then the name is referencing an OpenCL
792/// builtin function. Add all candidate signatures to the LookUpResult.
793///
794/// \param S (in) The Sema instance.
795/// \param LR (inout) The LookupResult instance.
796/// \param II (in) The identifier being resolved.
797/// \param FctIndex (in) Starting index in the BuiltinTable.
798/// \param Len (in) The signature list has Len elements.
799static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR,
800 IdentifierInfo *II,
801 const unsigned FctIndex,
802 const unsigned Len) {
803 // The builtin function declaration uses generic types (gentype).
804 bool HasGenType = false;
805
806 // Maximum number of types contained in a generic type used as return type or
807 // as argument. Only meaningful for generic types, otherwise equals 1.
808 unsigned GenTypeMaxCnt;
809
810 ASTContext &Context = S.Context;
811
812 for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
813 const OpenCLBuiltinStruct &OpenCLBuiltin =
814 BuiltinTable[FctIndex + SignatureIndex];
815
816 // Ignore this builtin function if it is not available in the currently
817 // selected language version.
818 if (!isOpenCLVersionContainedInMask(Context.getLangOpts(),
819 OpenCLBuiltin.Versions))
820 continue;
821
822 // Ignore this builtin function if it carries an extension macro that is
823 // not defined. This indicates that the extension is not supported by the
824 // target, so the builtin function should not be available.
825 StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];
826 if (!Extensions.empty()) {
827 SmallVector<StringRef, 2> ExtVec;
828 Extensions.split(ExtVec, " ");
829 bool AllExtensionsDefined = true;
830 for (StringRef Ext : ExtVec) {
831 if (!S.getPreprocessor().isMacroDefined(Ext)) {
832 AllExtensionsDefined = false;
833 break;
834 }
835 }
836 if (!AllExtensionsDefined)
837 continue;
838 }
839
840 SmallVector<QualType, 1> RetTypes;
841 SmallVector<SmallVector<QualType, 1>, 5> ArgTypes;
842
843 // Obtain QualType lists for the function signature.
844 GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,
845 ArgTypes);
846 if (GenTypeMaxCnt > 1) {
847 HasGenType = true;
848 }
849
850 // Create function overload for each type combination.
851 std::vector<QualType> FunctionList;
852 GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,
853 ArgTypes);
854
855 SourceLocation Loc = LR.getNameLoc();
856 DeclContext *Parent = Context.getTranslationUnitDecl();
857 FunctionDecl *NewOpenCLBuiltin;
858
859 for (const auto &FTy : FunctionList) {
860 NewOpenCLBuiltin = FunctionDecl::Create(
861 Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,
862 false, FTy->isFunctionProtoType());
863 NewOpenCLBuiltin->setImplicit();
864
865 // Create Decl objects for each parameter, adding them to the
866 // FunctionDecl.
867 const auto *FP = cast<FunctionProtoType>(FTy);
868 SmallVector<ParmVarDecl *, 4> ParmList;
869 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
870 ParmVarDecl *Parm = ParmVarDecl::Create(
871 Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),
872 nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);
873 Parm->setScopeInfo(0, IParm);
874 ParmList.push_back(Parm);
875 }
876 NewOpenCLBuiltin->setParams(ParmList);
877
878 // Add function attributes.
879 if (OpenCLBuiltin.IsPure)
880 NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context));
881 if (OpenCLBuiltin.IsConst)
882 NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context));
883 if (OpenCLBuiltin.IsConv)
884 NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context));
885
886 if (!S.getLangOpts().OpenCLCPlusPlus)
887 NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));
888
889 LR.addDecl(NewOpenCLBuiltin);
890 }
891 }
892
893 // If we added overloads, need to resolve the lookup result.
894 if (Len > 1 || HasGenType)
895 LR.resolveKind();
896}
897
898/// Lookup a builtin function, when name lookup would otherwise
899/// fail.
900bool Sema::LookupBuiltin(LookupResult &R) {
901 Sema::LookupNameKind NameKind = R.getLookupKind();
902
903 // If we didn't find a use of this identifier, and if the identifier
904 // corresponds to a compiler builtin, create the decl object for the builtin
905 // now, injecting it into translation unit scope, and return it.
906 if (NameKind == Sema::LookupOrdinaryName ||
907 NameKind == Sema::LookupRedeclarationWithLinkage) {
908 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
909 if (II) {
910 if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
911 if (II == getASTContext().getMakeIntegerSeqName()) {
912 R.addDecl(getASTContext().getMakeIntegerSeqDecl());
913 return true;
914 } else if (II == getASTContext().getTypePackElementName()) {
915 R.addDecl(getASTContext().getTypePackElementDecl());
916 return true;
917 }
918 }
919
920 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
921 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
922 auto Index = isOpenCLBuiltin(II->getName());
923 if (Index.first) {
924 InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,
925 Index.second);
926 return true;
927 }
928 }
929
930 // If this is a builtin on this (or all) targets, create the decl.
931 if (unsigned BuiltinID = II->getBuiltinID()) {
932 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
933 // library functions like 'malloc'. Instead, we'll just error.
934 if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) &&
935 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
936 return false;
937
938 if (NamedDecl *D =
939 LazilyCreateBuiltin(II, BuiltinID, TUScope,
940 R.isForRedeclaration(), R.getNameLoc())) {
941 R.addDecl(D);
942 return true;
943 }
944 }
945 }
946 }
947
948 return false;
949}
950
951/// Looks up the declaration of "struct objc_super" and
952/// saves it for later use in building builtin declaration of
953/// objc_msgSendSuper and objc_msgSendSuper_stret.
954static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) {
955 ASTContext &Context = Sema.Context;
956 LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),
957 Sema::LookupTagName);
958 Sema.LookupName(Result, S);
959 if (Result.getResultKind() == LookupResult::Found)
960 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
961 Context.setObjCSuperType(Context.getTagDeclType(TD));
962}
963
964void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) {
965 if (ID == Builtin::BIobjc_msgSendSuper)
966 LookupPredefedObjCSuperType(*this, S);
967}
968
969/// Determine whether we can declare a special member function within
970/// the class at this point.
971static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
972 // We need to have a definition for the class.
973 if (!Class->getDefinition() || Class->isDependentContext())
974 return false;
975
976 // We can't be in the middle of defining the class.
977 return !Class->isBeingDefined();
978}
979
980void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
981 if (!CanDeclareSpecialMemberFunction(Class))
982 return;
983
984 // If the default constructor has not yet been declared, do so now.
985 if (Class->needsImplicitDefaultConstructor())
986 DeclareImplicitDefaultConstructor(Class);
987
988 // If the copy constructor has not yet been declared, do so now.
989 if (Class->needsImplicitCopyConstructor())
990 DeclareImplicitCopyConstructor(Class);
991
992 // If the copy assignment operator has not yet been declared, do so now.
993 if (Class->needsImplicitCopyAssignment())
994 DeclareImplicitCopyAssignment(Class);
995
996 if (getLangOpts().CPlusPlus11) {
997 // If the move constructor has not yet been declared, do so now.
998 if (Class->needsImplicitMoveConstructor())
999 DeclareImplicitMoveConstructor(Class);
1000
1001 // If the move assignment operator has not yet been declared, do so now.
1002 if (Class->needsImplicitMoveAssignment())
1003 DeclareImplicitMoveAssignment(Class);
1004 }
1005
1006 // If the destructor has not yet been declared, do so now.
1007 if (Class->needsImplicitDestructor())
1008 DeclareImplicitDestructor(Class);
1009}
1010
1011/// Determine whether this is the name of an implicitly-declared
1012/// special member function.
1013static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
1014 switch (Name.getNameKind()) {
1015 case DeclarationName::CXXConstructorName:
1016 case DeclarationName::CXXDestructorName:
1017 return true;
1018
1019 case DeclarationName::CXXOperatorName:
1020 return Name.getCXXOverloadedOperator() == OO_Equal;
1021
1022 default:
1023 break;
1024 }
1025
1026 return false;
1027}
1028
1029/// If there are any implicit member functions with the given name
1030/// that need to be declared in the given declaration context, do so.
1031static void DeclareImplicitMemberFunctionsWithName(Sema &S,
1032 DeclarationName Name,
1033 SourceLocation Loc,
1034 const DeclContext *DC) {
1035 if (!DC)
1036 return;
1037
1038 switch (Name.getNameKind()) {
1039 case DeclarationName::CXXConstructorName:
1040 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1041 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1042 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1043 if (Record->needsImplicitDefaultConstructor())
1044 S.DeclareImplicitDefaultConstructor(Class);
1045 if (Record->needsImplicitCopyConstructor())
1046 S.DeclareImplicitCopyConstructor(Class);
1047 if (S.getLangOpts().CPlusPlus11 &&
1048 Record->needsImplicitMoveConstructor())
1049 S.DeclareImplicitMoveConstructor(Class);
1050 }
1051 break;
1052
1053 case DeclarationName::CXXDestructorName:
1054 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1055 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
1056 CanDeclareSpecialMemberFunction(Record))
1057 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
1058 break;
1059
1060 case DeclarationName::CXXOperatorName:
1061 if (Name.getCXXOverloadedOperator() != OO_Equal)
1062 break;
1063
1064 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
1065 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1066 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1067 if (Record->needsImplicitCopyAssignment())
1068 S.DeclareImplicitCopyAssignment(Class);
1069 if (S.getLangOpts().CPlusPlus11 &&
1070 Record->needsImplicitMoveAssignment())
1071 S.DeclareImplicitMoveAssignment(Class);
1072 }
1073 }
1074 break;
1075
1076 case DeclarationName::CXXDeductionGuideName:
1077 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
1078 break;
1079
1080 default:
1081 break;
1082 }
1083}
1084
1085// Adds all qualifying matches for a name within a decl context to the
1086// given lookup result. Returns true if any matches were found.
1087static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
1088 bool Found = false;
1089
1090 // Lazily declare C++ special member functions.
1091 if (S.getLangOpts().CPlusPlus)
1092 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
1093 DC);
1094
1095 // Perform lookup into this declaration context.
1096 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
1097 for (NamedDecl *D : DR) {
1098 if ((D = R.getAcceptableDecl(D))) {
1099 R.addDecl(D);
1100 Found = true;
1101 }
1102 }
1103
1104 if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
1105 return true;
1106
1107 if (R.getLookupName().getNameKind()
1108 != DeclarationName::CXXConversionFunctionName ||
1109 R.getLookupName().getCXXNameType()->isDependentType() ||
1110 !isa<CXXRecordDecl>(DC))
1111 return Found;
1112
1113 // C++ [temp.mem]p6:
1114 // A specialization of a conversion function template is not found by
1115 // name lookup. Instead, any conversion function templates visible in the
1116 // context of the use are considered. [...]
1117 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1118 if (!Record->isCompleteDefinition())
1119 return Found;
1120
1121 // For conversion operators, 'operator auto' should only match
1122 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
1123 // as a candidate for template substitution.
1124 auto *ContainedDeducedType =
1125 R.getLookupName().getCXXNameType()->getContainedDeducedType();
1126 if (R.getLookupName().getNameKind() ==
1127 DeclarationName::CXXConversionFunctionName &&
1128 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
1129 return Found;
1130
1131 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
1132 UEnd = Record->conversion_end(); U != UEnd; ++U) {
1133 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
1134 if (!ConvTemplate)
1135 continue;
1136
1137 // When we're performing lookup for the purposes of redeclaration, just
1138 // add the conversion function template. When we deduce template
1139 // arguments for specializations, we'll end up unifying the return
1140 // type of the new declaration with the type of the function template.
1141 if (R.isForRedeclaration()) {
1142 R.addDecl(ConvTemplate);
1143 Found = true;
1144 continue;
1145 }
1146
1147 // C++ [temp.mem]p6:
1148 // [...] For each such operator, if argument deduction succeeds
1149 // (14.9.2.3), the resulting specialization is used as if found by
1150 // name lookup.
1151 //
1152 // When referencing a conversion function for any purpose other than
1153 // a redeclaration (such that we'll be building an expression with the
1154 // result), perform template argument deduction and place the
1155 // specialization into the result set. We do this to avoid forcing all
1156 // callers to perform special deduction for conversion functions.
1157 TemplateDeductionInfo Info(R.getNameLoc());
1158 FunctionDecl *Specialization = nullptr;
1159
1160 const FunctionProtoType *ConvProto
1161 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
1162 assert(ConvProto && "Nonsensical conversion function template type");
1163
1164 // Compute the type of the function that we would expect the conversion
1165 // function to have, if it were to match the name given.
1166 // FIXME: Calling convention!
1167 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
1168 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
1169 EPI.ExceptionSpec = EST_None;
1170 QualType ExpectedType
1171 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
1172 None, EPI);
1173
1174 // Perform template argument deduction against the type that we would
1175 // expect the function to have.
1176 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
1177 Specialization, Info)
1178 == Sema::TDK_Success) {
1179 R.addDecl(Specialization);
1180 Found = true;
1181 }
1182 }
1183
1184 return Found;
1185}
1186
1187// Performs C++ unqualified lookup into the given file context.
1188static bool
1189CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
1190 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
1191
1192 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1193
1194 // Perform direct name lookup into the LookupCtx.
1195 bool Found = LookupDirect(S, R, NS);
1196
1197 // Perform direct name lookup into the namespaces nominated by the
1198 // using directives whose common ancestor is this namespace.
1199 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
1200 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
1201 Found = true;
1202
1203 R.resolveKind();
1204
1205 return Found;
1206}
1207
1208static bool isNamespaceOrTranslationUnitScope(Scope *S) {
1209 if (DeclContext *Ctx = S->getEntity())
1210 return Ctx->isFileContext();
1211 return false;
1212}
1213
1214/// Find the outer declaration context from this scope. This indicates the
1215/// context that we should search up to (exclusive) before considering the
1216/// parent of the specified scope.
1217static DeclContext *findOuterContext(Scope *S) {
1218 for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
1219 if (DeclContext *DC = OuterS->getLookupEntity())
1220 return DC;
1221 return nullptr;
1222}
1223
1224namespace {
1225/// An RAII object to specify that we want to find block scope extern
1226/// declarations.
1227struct FindLocalExternScope {
1228 FindLocalExternScope(LookupResult &R)
1229 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1230 Decl::IDNS_LocalExtern) {
1231 R.setFindLocalExtern(R.getIdentifierNamespace() &
1232 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
1233 }
1234 void restore() {
1235 R.setFindLocalExtern(OldFindLocalExtern);
1236 }
1237 ~FindLocalExternScope() {
1238 restore();
1239 }
1240 LookupResult &R;
1241 bool OldFindLocalExtern;
1242};
1243} // end anonymous namespace
1244
1245bool Sema::CppLookupName(LookupResult &R, Scope *S) {
1246 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
1247
1248 DeclarationName Name = R.getLookupName();
1249 Sema::LookupNameKind NameKind = R.getLookupKind();
1250
1251 // If this is the name of an implicitly-declared special member function,
1252 // go through the scope stack to implicitly declare
1253 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1254 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1255 if (DeclContext *DC = PreS->getEntity())
1256 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
1257 }
1258
1259 // Implicitly declare member functions with the name we're looking for, if in
1260 // fact we are in a scope where it matters.
1261
1262 Scope *Initial = S;
1263 IdentifierResolver::iterator
1264 I = IdResolver.begin(Name),
1265 IEnd = IdResolver.end();
1266
1267 // First we lookup local scope.
1268 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1269 // ...During unqualified name lookup (3.4.1), the names appear as if
1270 // they were declared in the nearest enclosing namespace which contains
1271 // both the using-directive and the nominated namespace.
1272 // [Note: in this context, "contains" means "contains directly or
1273 // indirectly".
1274 //
1275 // For example:
1276 // namespace A { int i; }
1277 // void foo() {
1278 // int i;
1279 // {
1280 // using namespace A;
1281 // ++i; // finds local 'i', A::i appears at global scope
1282 // }
1283 // }
1284 //
1285 UnqualUsingDirectiveSet UDirs(*this);
1286 bool VisitedUsingDirectives = false;
1287 bool LeftStartingScope = false;
1288
1289 // When performing a scope lookup, we want to find local extern decls.
1290 FindLocalExternScope FindLocals(R);
1291
1292 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1293 bool SearchNamespaceScope = true;
1294 // Check whether the IdResolver has anything in this scope.
1295 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1296 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1297 if (NameKind == LookupRedeclarationWithLinkage &&
1298 !(*I)->isTemplateParameter()) {
1299 // If it's a template parameter, we still find it, so we can diagnose
1300 // the invalid redeclaration.
1301
1302 // Determine whether this (or a previous) declaration is
1303 // out-of-scope.
1304 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1305 LeftStartingScope = true;
1306
1307 // If we found something outside of our starting scope that
1308 // does not have linkage, skip it.
1309 if (LeftStartingScope && !((*I)->hasLinkage())) {
1310 R.setShadowed();
1311 continue;
1312 }
1313 } else {
1314 // We found something in this scope, we should not look at the
1315 // namespace scope
1316 SearchNamespaceScope = false;
1317 }
1318 R.addDecl(ND);
1319 }
1320 }
1321 if (!SearchNamespaceScope) {
1322 R.resolveKind();
1323 if (S->isClassScope())
1324 if (CXXRecordDecl *Record =
1325 dyn_cast_or_null<CXXRecordDecl>(S->getEntity()))
1326 R.setNamingClass(Record);
1327 return true;
1328 }
1329
1330 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1331 // C++11 [class.friend]p11:
1332 // If a friend declaration appears in a local class and the name
1333 // specified is an unqualified name, a prior declaration is
1334 // looked up without considering scopes that are outside the
1335 // innermost enclosing non-class scope.
1336 return false;
1337 }
1338
1339 if (DeclContext *Ctx = S->getLookupEntity()) {
1340 DeclContext *OuterCtx = findOuterContext(S);
1341 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1342 // We do not directly look into transparent contexts, since
1343 // those entities will be found in the nearest enclosing
1344 // non-transparent context.
1345 if (Ctx->isTransparentContext())
1346 continue;
1347
1348 // We do not look directly into function or method contexts,
1349 // since all of the local variables and parameters of the
1350 // function/method are present within the Scope.
1351 if (Ctx->isFunctionOrMethod()) {
1352 // If we have an Objective-C instance method, look for ivars
1353 // in the corresponding interface.
1354 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1355 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1356 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1357 ObjCInterfaceDecl *ClassDeclared;
1358 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1359 Name.getAsIdentifierInfo(),
1360 ClassDeclared)) {
1361 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1362 R.addDecl(ND);
1363 R.resolveKind();
1364 return true;
1365 }
1366 }
1367 }
1368 }
1369
1370 continue;
1371 }
1372
1373 // If this is a file context, we need to perform unqualified name
1374 // lookup considering using directives.
1375 if (Ctx->isFileContext()) {
1376 // If we haven't handled using directives yet, do so now.
1377 if (!VisitedUsingDirectives) {
1378 // Add using directives from this context up to the top level.
1379 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1380 if (UCtx->isTransparentContext())
1381 continue;
1382
1383 UDirs.visit(UCtx, UCtx);
1384 }
1385
1386 // Find the innermost file scope, so we can add using directives
1387 // from local scopes.
1388 Scope *InnermostFileScope = S;
1389 while (InnermostFileScope &&
1390 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1391 InnermostFileScope = InnermostFileScope->getParent();
1392 UDirs.visitScopeChain(Initial, InnermostFileScope);
1393
1394 UDirs.done();
1395
1396 VisitedUsingDirectives = true;
1397 }
1398
1399 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1400 R.resolveKind();
1401 return true;
1402 }
1403
1404 continue;
1405 }
1406
1407 // Perform qualified name lookup into this context.
1408 // FIXME: In some cases, we know that every name that could be found by
1409 // this qualified name lookup will also be on the identifier chain. For
1410 // example, inside a class without any base classes, we never need to
1411 // perform qualified lookup because all of the members are on top of the
1412 // identifier chain.
1413 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1414 return true;
1415 }
1416 }
1417 }
1418
1419 // Stop if we ran out of scopes.
1420 // FIXME: This really, really shouldn't be happening.
1421 if (!S) return false;
1422
1423 // If we are looking for members, no need to look into global/namespace scope.
1424 if (NameKind == LookupMemberName)
1425 return false;
1426
1427 // Collect UsingDirectiveDecls in all scopes, and recursively all
1428 // nominated namespaces by those using-directives.
1429 //
1430 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1431 // don't build it for each lookup!
1432 if (!VisitedUsingDirectives) {
1433 UDirs.visitScopeChain(Initial, S);
1434 UDirs.done();
1435 }
1436
1437 // If we're not performing redeclaration lookup, do not look for local
1438 // extern declarations outside of a function scope.
1439 if (!R.isForRedeclaration())
1440 FindLocals.restore();
1441
1442 // Lookup namespace scope, and global scope.
1443 // Unqualified name lookup in C++ requires looking into scopes
1444 // that aren't strictly lexical, and therefore we walk through the
1445 // context as well as walking through the scopes.
1446 for (; S; S = S->getParent()) {
1447 // Check whether the IdResolver has anything in this scope.
1448 bool Found = false;
1449 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1450 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1451 // We found something. Look for anything else in our scope
1452 // with this same name and in an acceptable identifier
1453 // namespace, so that we can construct an overload set if we
1454 // need to.
1455 Found = true;
1456 R.addDecl(ND);
1457 }
1458 }
1459
1460 if (Found && S->isTemplateParamScope()) {
1461 R.resolveKind();
1462 return true;
1463 }
1464
1465 DeclContext *Ctx = S->getLookupEntity();
1466 if (Ctx) {
1467 DeclContext *OuterCtx = findOuterContext(S);
1468 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1469 // We do not directly look into transparent contexts, since
1470 // those entities will be found in the nearest enclosing
1471 // non-transparent context.
1472 if (Ctx->isTransparentContext())
1473 continue;
1474
1475 // If we have a context, and it's not a context stashed in the
1476 // template parameter scope for an out-of-line definition, also
1477 // look into that context.
1478 if (!(Found && S->isTemplateParamScope())) {
1479 assert(Ctx->isFileContext() &&
1480 "We should have been looking only at file context here already.");
1481
1482 // Look into context considering using-directives.
1483 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1484 Found = true;
1485 }
1486
1487 if (Found) {
1488 R.resolveKind();
1489 return true;
1490 }
1491
1492 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1493 return false;
1494 }
1495 }
1496
1497 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1498 return false;
1499 }
1500
1501 return !R.empty();
1502}
1503
1504void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1505 if (auto *M = getCurrentModule())
1506 Context.mergeDefinitionIntoModule(ND, M);
1507 else
1508 // We're not building a module; just make the definition visible.
1509 ND->setVisibleDespiteOwningModule();
1510
1511 // If ND is a template declaration, make the template parameters
1512 // visible too. They're not (necessarily) within a mergeable DeclContext.
1513 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1514 for (auto *Param : *TD->getTemplateParameters())
1515 makeMergedDefinitionVisible(Param);
1516}
1517
1518/// Find the module in which the given declaration was defined.
1519static Module *getDefiningModule(Sema &S, Decl *Entity) {
1520 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1521 // If this function was instantiated from a template, the defining module is
1522 // the module containing the pattern.
1523 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1524 Entity = Pattern;
1525 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1526 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1527 Entity = Pattern;
1528 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1529 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1530 Entity = Pattern;
1531 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1532 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1533 Entity = Pattern;
1534 }
1535
1536 // Walk up to the containing context. That might also have been instantiated
1537 // from a template.
1538 DeclContext *Context = Entity->getLexicalDeclContext();
1539 if (Context->isFileContext())
1540 return S.getOwningModule(Entity);
1541 return getDefiningModule(S, cast<Decl>(Context));
1542}
1543
1544llvm::DenseSet<Module*> &Sema::getLookupModules() {
1545 unsigned N = CodeSynthesisContexts.size();
1546 for (unsigned I = CodeSynthesisContextLookupModules.size();
1547 I != N; ++I) {
1548 Module *M = CodeSynthesisContexts[I].Entity ?
1549 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
1550 nullptr;
1551 if (M && !LookupModulesCache.insert(M).second)
1552 M = nullptr;
1553 CodeSynthesisContextLookupModules.push_back(M);
1554 }
1555 return LookupModulesCache;
1556}
1557
1558/// Determine whether the module M is part of the current module from the
1559/// perspective of a module-private visibility check.
1560static bool isInCurrentModule(const Module *M, const LangOptions &LangOpts) {
1561 // If M is the global module fragment of a module that we've not yet finished
1562 // parsing, then it must be part of the current module.
1563 return M->getTopLevelModuleName() == LangOpts.CurrentModule ||
1564 (M->Kind == Module::GlobalModuleFragment && !M->Parent);
1565}
1566
1567bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1568 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1569 if (isModuleVisible(Merged))
1570 return true;
1571 return false;
1572}
1573
1574bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
1575 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1576 if (isInCurrentModule(Merged, getLangOpts()))
1577 return true;
1578 return false;
1579}
1580
1581template<typename ParmDecl>
1582static bool
1583hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1584 llvm::SmallVectorImpl<Module *> *Modules) {
1585 if (!D->hasDefaultArgument())
1586 return false;
1587
1588 while (D) {
1589 auto &DefaultArg = D->getDefaultArgStorage();
1590 if (!DefaultArg.isInherited() && S.isVisible(D))
1591 return true;
1592
1593 if (!DefaultArg.isInherited() && Modules) {
1594 auto *NonConstD = const_cast<ParmDecl*>(D);
1595 Modules->push_back(S.getOwningModule(NonConstD));
1596 }
1597
1598 // If there was a previous default argument, maybe its parameter is visible.
1599 D = DefaultArg.getInheritedFrom();
1600 }
1601 return false;
1602}
1603
1604bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1605 llvm::SmallVectorImpl<Module *> *Modules) {
1606 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1607 return ::hasVisibleDefaultArgument(*this, P, Modules);
1608 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1609 return ::hasVisibleDefaultArgument(*this, P, Modules);
1610 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1611 Modules);
1612}
1613
1614template<typename Filter>
1615static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
1616 llvm::SmallVectorImpl<Module *> *Modules,
1617 Filter F) {
1618 bool HasFilteredRedecls = false;
1619
1620 for (auto *Redecl : D->redecls()) {
1621 auto *R = cast<NamedDecl>(Redecl);
1622 if (!F(R))
1623 continue;
1624
1625 if (S.isVisible(R))
1626 return true;
1627
1628 HasFilteredRedecls = true;
1629
1630 if (Modules)
1631 Modules->push_back(R->getOwningModule());
1632 }
1633
1634 // Only return false if there is at least one redecl that is not filtered out.
1635 if (HasFilteredRedecls)
1636 return false;
1637
1638 return true;
1639}
1640
1641bool Sema::hasVisibleExplicitSpecialization(
1642 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1643 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1644 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1645 return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1646 if (auto *FD = dyn_cast<FunctionDecl>(D))
1647 return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1648 if (auto *VD = dyn_cast<VarDecl>(D))
1649 return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1650 llvm_unreachable("unknown explicit specialization kind");
1651 });
1652}
1653
1654bool Sema::hasVisibleMemberSpecialization(
1655 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1656 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1657 "not a member specialization");
1658 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1659 // If the specialization is declared at namespace scope, then it's a member
1660 // specialization declaration. If it's lexically inside the class
1661 // definition then it was instantiated.
1662 //
1663 // FIXME: This is a hack. There should be a better way to determine this.
1664 // FIXME: What about MS-style explicit specializations declared within a
1665 // class definition?
1666 return D->getLexicalDeclContext()->isFileContext();
1667 });
1668}
1669
1670/// Determine whether a declaration is visible to name lookup.
1671///
1672/// This routine determines whether the declaration D is visible in the current
1673/// lookup context, taking into account the current template instantiation
1674/// stack. During template instantiation, a declaration is visible if it is
1675/// visible from a module containing any entity on the template instantiation
1676/// path (by instantiating a template, you allow it to see the declarations that
1677/// your module can see, including those later on in your module).
1678bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1679 assert(!D->isUnconditionallyVisible() &&
1680 "should not call this: not in slow case");
1681
1682 Module *DeclModule = SemaRef.getOwningModule(D);
1683 assert(DeclModule && "hidden decl has no owning module");
1684
1685 // If the owning module is visible, the decl is visible.
1686 if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
1687 return true;
1688
1689 // Determine whether a decl context is a file context for the purpose of
1690 // visibility. This looks through some (export and linkage spec) transparent
1691 // contexts, but not others (enums).
1692 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1693 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1694 isa<ExportDecl>(DC);
1695 };
1696
1697 // If this declaration is not at namespace scope
1698 // then it is visible if its lexical parent has a visible definition.
1699 DeclContext *DC = D->getLexicalDeclContext();
1700 if (DC && !IsEffectivelyFileContext(DC)) {
1701 // For a parameter, check whether our current template declaration's
1702 // lexical context is visible, not whether there's some other visible
1703 // definition of it, because parameters aren't "within" the definition.
1704 //
1705 // In C++ we need to check for a visible definition due to ODR merging,
1706 // and in C we must not because each declaration of a function gets its own
1707 // set of declarations for tags in prototype scope.
1708 bool VisibleWithinParent;
1709 if (D->isTemplateParameter()) {
1710 bool SearchDefinitions = true;
1711 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1712 if (const auto *TD = DCD->getDescribedTemplate()) {
1713 TemplateParameterList *TPL = TD->getTemplateParameters();
1714 auto Index = getDepthAndIndex(D).second;
1715 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1716 }
1717 }
1718 if (SearchDefinitions)
1719 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
1720 else
1721 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1722 } else if (isa<ParmVarDecl>(D) ||
1723 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1724 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1725 else if (D->isModulePrivate()) {
1726 // A module-private declaration is only visible if an enclosing lexical
1727 // parent was merged with another definition in the current module.
1728 VisibleWithinParent = false;
1729 do {
1730 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1731 VisibleWithinParent = true;
1732 break;
1733 }
1734 DC = DC->getLexicalParent();
1735 } while (!IsEffectivelyFileContext(DC));
1736 } else {
1737 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
1738 }
1739
1740 if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1741 // FIXME: Do something better in this case.
1742 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1743 // Cache the fact that this declaration is implicitly visible because
1744 // its parent has a visible definition.
1745 D->setVisibleDespiteOwningModule();
1746 }
1747 return VisibleWithinParent;
1748 }
1749
1750 return false;
1751}
1752
1753bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1754 // The module might be ordinarily visible. For a module-private query, that
1755 // means it is part of the current module. For any other query, that means it
1756 // is in our visible module set.
1757 if (ModulePrivate) {
1758 if (isInCurrentModule(M, getLangOpts()))
1759 return true;
1760 } else {
1761 if (VisibleModules.isVisible(M))
1762 return true;
1763 }
1764
1765 // Otherwise, it might be visible by virtue of the query being within a
1766 // template instantiation or similar that is permitted to look inside M.
1767
1768 // Find the extra places where we need to look.
1769 const auto &LookupModules = getLookupModules();
1770 if (LookupModules.empty())
1771 return false;
1772
1773 // If our lookup set contains the module, it's visible.
1774 if (LookupModules.count(M))
1775 return true;
1776
1777 // For a module-private query, that's everywhere we get to look.
1778 if (ModulePrivate)
1779 return false;
1780
1781 // Check whether M is transitively exported to an import of the lookup set.
1782 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1783 return LookupM->isModuleVisible(M);
1784 });
1785}
1786
1787bool Sema::isVisibleSlow(const NamedDecl *D) {
1788 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1789}
1790
1791bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1792 // FIXME: If there are both visible and hidden declarations, we need to take
1793 // into account whether redeclaration is possible. Example:
1794 //
1795 // Non-imported module:
1796 // int f(T); // #1
1797 // Some TU:
1798 // static int f(U); // #2, not a redeclaration of #1
1799 // int f(T); // #3, finds both, should link with #1 if T != U, but
1800 // // with #2 if T == U; neither should be ambiguous.
1801 for (auto *D : R) {
1802 if (isVisible(D))
1803 return true;
1804 assert(D->isExternallyDeclarable() &&
1805 "should not have hidden, non-externally-declarable result here");
1806 }
1807
1808 // This function is called once "New" is essentially complete, but before a
1809 // previous declaration is attached. We can't query the linkage of "New" in
1810 // general, because attaching the previous declaration can change the
1811 // linkage of New to match the previous declaration.
1812 //
1813 // However, because we've just determined that there is no *visible* prior
1814 // declaration, we can compute the linkage here. There are two possibilities:
1815 //
1816 // * This is not a redeclaration; it's safe to compute the linkage now.
1817 //
1818 // * This is a redeclaration of a prior declaration that is externally
1819 // redeclarable. In that case, the linkage of the declaration is not
1820 // changed by attaching the prior declaration, because both are externally
1821 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
1822 //
1823 // FIXME: This is subtle and fragile.
1824 return New->isExternallyDeclarable();
1825}
1826
1827/// Retrieve the visible declaration corresponding to D, if any.
1828///
1829/// This routine determines whether the declaration D is visible in the current
1830/// module, with the current imports. If not, it checks whether any
1831/// redeclaration of D is visible, and if so, returns that declaration.
1832///
1833/// \returns D, or a visible previous declaration of D, whichever is more recent
1834/// and visible. If no declaration of D is visible, returns null.
1835static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
1836 unsigned IDNS) {
1837 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
1838
1839 for (auto RD : D->redecls()) {
1840 // Don't bother with extra checks if we already know this one isn't visible.
1841 if (RD == D)
1842 continue;
1843
1844 auto ND = cast<NamedDecl>(RD);
1845 // FIXME: This is wrong in the case where the previous declaration is not
1846 // visible in the same scope as D. This needs to be done much more
1847 // carefully.
1848 if (ND->isInIdentifierNamespace(IDNS) &&
1849 LookupResult::isVisible(SemaRef, ND))
1850 return ND;
1851 }
1852
1853 return nullptr;
1854}
1855
1856bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1857 llvm::SmallVectorImpl<Module *> *Modules) {
1858 assert(!isVisible(D) && "not in slow case");
1859 return hasVisibleDeclarationImpl(*this, D, Modules,
1860 [](const NamedDecl *) { return true; });
1861}
1862
1863NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1864 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1865 // Namespaces are a bit of a special case: we expect there to be a lot of
1866 // redeclarations of some namespaces, all declarations of a namespace are
1867 // essentially interchangeable, all declarations are found by name lookup
1868 // if any is, and namespaces are never looked up during template
1869 // instantiation. So we benefit from caching the check in this case, and
1870 // it is correct to do so.
1871 auto *Key = ND->getCanonicalDecl();
1872 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1873 return Acceptable;
1874 auto *Acceptable = isVisible(getSema(), Key)
1875 ? Key
1876 : findAcceptableDecl(getSema(), Key, IDNS);
1877 if (Acceptable)
1878 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1879 return Acceptable;
1880 }
1881
1882 return findAcceptableDecl(getSema(), D, IDNS);
1883}
1884
1885/// Perform unqualified name lookup starting from a given
1886/// scope.
1887///
1888/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1889/// used to find names within the current scope. For example, 'x' in
1890/// @code
1891/// int x;
1892/// int f() {
1893/// return x; // unqualified name look finds 'x' in the global scope
1894/// }
1895/// @endcode
1896///
1897/// Different lookup criteria can find different names. For example, a
1898/// particular scope can have both a struct and a function of the same
1899/// name, and each can be found by certain lookup criteria. For more
1900/// information about lookup criteria, see the documentation for the
1901/// class LookupCriteria.
1902///
1903/// @param S The scope from which unqualified name lookup will
1904/// begin. If the lookup criteria permits, name lookup may also search
1905/// in the parent scopes.
1906///
1907/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1908/// look up and the lookup kind), and is updated with the results of lookup
1909/// including zero or more declarations and possibly additional information
1910/// used to diagnose ambiguities.
1911///
1912/// @returns \c true if lookup succeeded and false otherwise.
1913bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1914 DeclarationName Name = R.getLookupName();
1915 if (!Name) return false;
1916
1917 LookupNameKind NameKind = R.getLookupKind();
1918
1919 if (!getLangOpts().CPlusPlus) {
1920 // Unqualified name lookup in C/Objective-C is purely lexical, so
1921 // search in the declarations attached to the name.
1922 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1923 // Find the nearest non-transparent declaration scope.
1924 while (!(S->getFlags() & Scope::DeclScope) ||
1925 (S->getEntity() && S->getEntity()->isTransparentContext()))
1926 S = S->getParent();
1927 }
1928
1929 // When performing a scope lookup, we want to find local extern decls.
1930 FindLocalExternScope FindLocals(R);
1931
1932 // Scan up the scope chain looking for a decl that matches this
1933 // identifier that is in the appropriate namespace. This search
1934 // should not take long, as shadowing of names is uncommon, and
1935 // deep shadowing is extremely uncommon.
1936 bool LeftStartingScope = false;
1937
1938 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1939 IEnd = IdResolver.end();
1940 I != IEnd; ++I)
1941 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
1942 if (NameKind == LookupRedeclarationWithLinkage) {
1943 // Determine whether this (or a previous) declaration is
1944 // out-of-scope.
1945 if (!LeftStartingScope && !S->isDeclScope(*I))
1946 LeftStartingScope = true;
1947
1948 // If we found something outside of our starting scope that
1949 // does not have linkage, skip it.
1950 if (LeftStartingScope && !((*I)->hasLinkage())) {
1951 R.setShadowed();
1952 continue;
1953 }
1954 }
1955 else if (NameKind == LookupObjCImplicitSelfParam &&
1956 !isa<ImplicitParamDecl>(*I))
1957 continue;
1958
1959 R.addDecl(D);
1960
1961 // Check whether there are any other declarations with the same name
1962 // and in the same scope.
1963 if (I != IEnd) {
1964 // Find the scope in which this declaration was declared (if it
1965 // actually exists in a Scope).
1966 while (S && !S->isDeclScope(D))
1967 S = S->getParent();
1968
1969 // If the scope containing the declaration is the translation unit,
1970 // then we'll need to perform our checks based on the matching
1971 // DeclContexts rather than matching scopes.
1972 if (S && isNamespaceOrTranslationUnitScope(S))
1973 S = nullptr;
1974
1975 // Compute the DeclContext, if we need it.
1976 DeclContext *DC = nullptr;
1977 if (!S)
1978 DC = (*I)->getDeclContext()->getRedeclContext();
1979
1980 IdentifierResolver::iterator LastI = I;
1981 for (++LastI; LastI != IEnd; ++LastI) {
1982 if (S) {
1983 // Match based on scope.
1984 if (!S->isDeclScope(*LastI))
1985 break;
1986 } else {
1987 // Match based on DeclContext.
1988 DeclContext *LastDC
1989 = (*LastI)->getDeclContext()->getRedeclContext();
1990 if (!LastDC->Equals(DC))
1991 break;
1992 }
1993
1994 // If the declaration is in the right namespace and visible, add it.
1995 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1996 R.addDecl(LastD);
1997 }
1998
1999 R.resolveKind();
2000 }
2001
2002 return true;
2003 }
2004 } else {
2005 // Perform C++ unqualified name lookup.
2006 if (CppLookupName(R, S))
2007 return true;
2008 }
2009
2010 // If we didn't find a use of this identifier, and if the identifier
2011 // corresponds to a compiler builtin, create the decl object for the builtin
2012 // now, injecting it into translation unit scope, and return it.
2013 if (AllowBuiltinCreation && LookupBuiltin(R))
2014 return true;
2015
2016 // If we didn't find a use of this identifier, the ExternalSource
2017 // may be able to handle the situation.
2018 // Note: some lookup failures are expected!
2019 // See e.g. R.isForRedeclaration().
2020 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2021}
2022
2023/// Perform qualified name lookup in the namespaces nominated by
2024/// using directives by the given context.
2025///
2026/// C++98 [namespace.qual]p2:
2027/// Given X::m (where X is a user-declared namespace), or given \::m
2028/// (where X is the global namespace), let S be the set of all
2029/// declarations of m in X and in the transitive closure of all
2030/// namespaces nominated by using-directives in X and its used
2031/// namespaces, except that using-directives are ignored in any
2032/// namespace, including X, directly containing one or more
2033/// declarations of m. No namespace is searched more than once in
2034/// the lookup of a name. If S is the empty set, the program is
2035/// ill-formed. Otherwise, if S has exactly one member, or if the
2036/// context of the reference is a using-declaration
2037/// (namespace.udecl), S is the required set of declarations of
2038/// m. Otherwise if the use of m is not one that allows a unique
2039/// declaration to be chosen from S, the program is ill-formed.
2040///
2041/// C++98 [namespace.qual]p5:
2042/// During the lookup of a qualified namespace member name, if the
2043/// lookup finds more than one declaration of the member, and if one
2044/// declaration introduces a class name or enumeration name and the
2045/// other declarations either introduce the same object, the same
2046/// enumerator or a set of functions, the non-type name hides the
2047/// class or enumeration name if and only if the declarations are
2048/// from the same namespace; otherwise (the declarations are from
2049/// different namespaces), the program is ill-formed.
2050static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
2051 DeclContext *StartDC) {
2052 assert(StartDC->isFileContext() && "start context is not a file context");
2053
2054 // We have not yet looked into these namespaces, much less added
2055 // their "using-children" to the queue.
2056 SmallVector<NamespaceDecl*, 8> Queue;
2057
2058 // We have at least added all these contexts to the queue.
2059 llvm::SmallPtrSet<DeclContext*, 8> Visited;
2060 Visited.insert(StartDC);
2061
2062 // We have already looked into the initial namespace; seed the queue
2063 // with its using-children.
2064 for (auto *I : StartDC->using_directives()) {
2065 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
2066 if (S.isVisible(I) && Visited.insert(ND).second)
2067 Queue.push_back(ND);
2068 }
2069
2070 // The easiest way to implement the restriction in [namespace.qual]p5
2071 // is to check whether any of the individual results found a tag
2072 // and, if so, to declare an ambiguity if the final result is not
2073 // a tag.
2074 bool FoundTag = false;
2075 bool FoundNonTag = false;
2076
2077 LookupResult LocalR(LookupResult::Temporary, R);
2078
2079 bool Found = false;
2080 while (!Queue.empty()) {
2081 NamespaceDecl *ND = Queue.pop_back_val();
2082
2083 // We go through some convolutions here to avoid copying results
2084 // between LookupResults.
2085 bool UseLocal = !R.empty();
2086 LookupResult &DirectR = UseLocal ? LocalR : R;
2087 bool FoundDirect = LookupDirect(S, DirectR, ND);
2088
2089 if (FoundDirect) {
2090 // First do any local hiding.
2091 DirectR.resolveKind();
2092
2093 // If the local result is a tag, remember that.
2094 if (DirectR.isSingleTagDecl())
2095 FoundTag = true;
2096 else
2097 FoundNonTag = true;
2098
2099 // Append the local results to the total results if necessary.
2100 if (UseLocal) {
2101 R.addAllDecls(LocalR);
2102 LocalR.clear();
2103 }
2104 }
2105
2106 // If we find names in this namespace, ignore its using directives.
2107 if (FoundDirect) {
2108 Found = true;
2109 continue;
2110 }
2111
2112 for (auto I : ND->using_directives()) {
2113 NamespaceDecl *Nom = I->getNominatedNamespace();
2114 if (S.isVisible(I) && Visited.insert(Nom).second)
2115 Queue.push_back(Nom);
2116 }
2117 }
2118
2119 if (Found) {
2120 if (FoundTag && FoundNonTag)
2121 R.setAmbiguousQualifiedTagHiding();
2122 else
2123 R.resolveKind();
2124 }
2125
2126 return Found;
2127}
2128
2129/// Perform qualified name lookup into a given context.
2130///
2131/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2132/// names when the context of those names is explicit specified, e.g.,
2133/// "std::vector" or "x->member", or as part of unqualified name lookup.
2134///
2135/// Different lookup criteria can find different names. For example, a
2136/// particular scope can have both a struct and a function of the same
2137/// name, and each can be found by certain lookup criteria. For more
2138/// information about lookup criteria, see the documentation for the
2139/// class LookupCriteria.
2140///
2141/// \param R captures both the lookup criteria and any lookup results found.
2142///
2143/// \param LookupCtx The context in which qualified name lookup will
2144/// search. If the lookup criteria permits, name lookup may also search
2145/// in the parent contexts or (for C++ classes) base classes.
2146///
2147/// \param InUnqualifiedLookup true if this is qualified name lookup that
2148/// occurs as part of unqualified name lookup.
2149///
2150/// \returns true if lookup succeeded, false if it failed.
2151bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2152 bool InUnqualifiedLookup) {
2153 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2154
2155 if (!R.getLookupName())
2156 return false;
2157
2158 // Make sure that the declaration context is complete.
2159 assert((!isa<TagDecl>(LookupCtx) ||
2160 LookupCtx->isDependentContext() ||
2161 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2162 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2163 "Declaration context must already be complete!");
2164
2165 struct QualifiedLookupInScope {
2166 bool oldVal;
2167 DeclContext *Context;
2168 // Set flag in DeclContext informing debugger that we're looking for qualified name
2169 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2170 oldVal = ctx->setUseQualifiedLookup();
2171 }
2172 ~QualifiedLookupInScope() {
2173 Context->setUseQualifiedLookup(oldVal);
2174 }
2175 } QL(LookupCtx);
2176
2177 if (LookupDirect(*this, R, LookupCtx)) {
2178 R.resolveKind();
2179 if (isa<CXXRecordDecl>(LookupCtx))
2180 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2181 return true;
2182 }
2183
2184 // Don't descend into implied contexts for redeclarations.
2185 // C++98 [namespace.qual]p6:
2186 // In a declaration for a namespace member in which the
2187 // declarator-id is a qualified-id, given that the qualified-id
2188 // for the namespace member has the form
2189 // nested-name-specifier unqualified-id
2190 // the unqualified-id shall name a member of the namespace
2191 // designated by the nested-name-specifier.
2192 // See also [class.mfct]p5 and [class.static.data]p2.
2193 if (R.isForRedeclaration())
2194 return false;
2195
2196 // If this is a namespace, look it up in the implied namespaces.
2197 if (LookupCtx->isFileContext())
2198 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2199
2200 // If this isn't a C++ class, we aren't allowed to look into base
2201 // classes, we're done.
2202 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2203 if (!LookupRec || !LookupRec->getDefinition())
2204 return false;
2205
2206 // We're done for lookups that can never succeed for C++ classes.
2207 if (R.getLookupKind() == LookupOperatorName ||
2208 R.getLookupKind() == LookupNamespaceName ||
2209 R.getLookupKind() == LookupObjCProtocolName ||
2210 R.getLookupKind() == LookupLabel)
2211 return false;
2212
2213 // If we're performing qualified name lookup into a dependent class,
2214 // then we are actually looking into a current instantiation. If we have any
2215 // dependent base classes, then we either have to delay lookup until
2216 // template instantiation time (at which point all bases will be available)
2217 // or we have to fail.
2218 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2219 LookupRec->hasAnyDependentBases()) {
2220 R.setNotFoundInCurrentInstantiation();
2221 return false;
2222 }
2223
2224 // Perform lookup into our base classes.
2225
2226 DeclarationName Name = R.getLookupName();
2227 unsigned IDNS = R.getIdentifierNamespace();
2228
2229 // Look for this member in our base classes.
2230 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2231 CXXBasePath &Path) -> bool {
2232 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2233 // Drop leading non-matching lookup results from the declaration list so
2234 // we don't need to consider them again below.
2235 for (Path.Decls = BaseRecord->lookup(Name).begin();
2236 Path.Decls != Path.Decls.end(); ++Path.Decls) {
2237 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2238 return true;
2239 }
2240 return false;
2241 };
2242
2243 CXXBasePaths Paths;
2244 Paths.setOrigin(LookupRec);
2245 if (!LookupRec->lookupInBases(BaseCallback, Paths))
2246 return false;
2247
2248 R.setNamingClass(LookupRec);
2249
2250 // C++ [class.member.lookup]p2:
2251 // [...] If the resulting set of declarations are not all from
2252 // sub-objects of the same type, or the set has a nonstatic member
2253 // and includes members from distinct sub-objects, there is an
2254 // ambiguity and the program is ill-formed. Otherwise that set is
2255 // the result of the lookup.
2256 QualType SubobjectType;
2257 int SubobjectNumber = 0;
2258 AccessSpecifier SubobjectAccess = AS_none;
2259
2260 // Check whether the given lookup result contains only static members.
2261 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2262 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2263 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2264 return false;
2265 return true;
2266 };
2267
2268 bool TemplateNameLookup = R.isTemplateNameLookup();
2269
2270 // Determine whether two sets of members contain the same members, as
2271 // required by C++ [class.member.lookup]p6.
2272 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2273 DeclContext::lookup_iterator B) {
2274 using Iterator = DeclContextLookupResult::iterator;
2275 using Result = const void *;
2276
2277 auto Next = [&](Iterator &It, Iterator End) -> Result {
2278 while (It != End) {
2279 NamedDecl *ND = *It++;
2280 if (!ND->isInIdentifierNamespace(IDNS))
2281 continue;
2282
2283 // C++ [temp.local]p3:
2284 // A lookup that finds an injected-class-name (10.2) can result in
2285 // an ambiguity in certain cases (for example, if it is found in
2286 // more than one base class). If all of the injected-class-names
2287 // that are found refer to specializations of the same class
2288 // template, and if the name is used as a template-name, the
2289 // reference refers to the class template itself and not a
2290 // specialization thereof, and is not ambiguous.
2291 if (TemplateNameLookup)
2292 if (auto *TD = getAsTemplateNameDecl(ND))
2293 ND = TD;
2294
2295 // C++ [class.member.lookup]p3:
2296 // type declarations (including injected-class-names) are replaced by
2297 // the types they designate
2298 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
2299 QualType T = Context.getTypeDeclType(TD);
2300 return T.getCanonicalType().getAsOpaquePtr();
2301 }
2302
2303 return ND->getUnderlyingDecl()->getCanonicalDecl();
2304 }
2305 return nullptr;
2306 };
2307
2308 // We'll often find the declarations are in the same order. Handle this
2309 // case (and the special case of only one declaration) efficiently.
2310 Iterator AIt = A, BIt = B, AEnd, BEnd;
2311 while (true) {
2312 Result AResult = Next(AIt, AEnd);
2313 Result BResult = Next(BIt, BEnd);
2314 if (!AResult && !BResult)
2315 return true;
2316 if (!AResult || !BResult)
2317 return false;
2318 if (AResult != BResult) {
2319 // Found a mismatch; carefully check both lists, accounting for the
2320 // possibility of declarations appearing more than once.
2321 llvm::SmallDenseMap<Result, bool, 32> AResults;
2322 for (; AResult; AResult = Next(AIt, AEnd))
2323 AResults.insert({AResult, /*FoundInB*/false});
2324 unsigned Found = 0;
2325 for (; BResult; BResult = Next(BIt, BEnd)) {
2326 auto It = AResults.find(BResult);
2327 if (It == AResults.end())
2328 return false;
2329 if (!It->second) {
2330 It->second = true;
2331 ++Found;
2332 }
2333 }
2334 return AResults.size() == Found;
2335 }
2336 }
2337 };
2338
2339 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2340 Path != PathEnd; ++Path) {
2341 const CXXBasePathElement &PathElement = Path->back();
2342
2343 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2344 // across all paths.
2345 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2346
2347 // Determine whether we're looking at a distinct sub-object or not.
2348 if (SubobjectType.isNull()) {
2349 // This is the first subobject we've looked at. Record its type.
2350 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2351 SubobjectNumber = PathElement.SubobjectNumber;
2352 continue;
2353 }
2354
2355 if (SubobjectType !=
2356 Context.getCanonicalType(PathElement.Base->getType())) {
2357 // We found members of the given name in two subobjects of
2358 // different types. If the declaration sets aren't the same, this
2359 // lookup is ambiguous.
2360 //
2361 // FIXME: The language rule says that this applies irrespective of
2362 // whether the sets contain only static members.
2363 if (HasOnlyStaticMembers(Path->Decls) &&
2364 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2365 continue;
2366
2367 R.setAmbiguousBaseSubobjectTypes(Paths);
2368 return true;
2369 }
2370
2371 // FIXME: This language rule no longer exists. Checking for ambiguous base
2372 // subobjects should be done as part of formation of a class member access
2373 // expression (when converting the object parameter to the member's type).
2374 if (SubobjectNumber != PathElement.SubobjectNumber) {
2375 // We have a different subobject of the same type.
2376
2377 // C++ [class.member.lookup]p5:
2378 // A static member, a nested type or an enumerator defined in
2379 // a base class T can unambiguously be found even if an object
2380 // has more than one base class subobject of type T.
2381 if (HasOnlyStaticMembers(Path->Decls))
2382 continue;
2383
2384 // We have found a nonstatic member name in multiple, distinct
2385 // subobjects. Name lookup is ambiguous.
2386 R.setAmbiguousBaseSubobjects(Paths);
2387 return true;
2388 }
2389 }
2390
2391 // Lookup in a base class succeeded; return these results.
2392
2393 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2394 I != E; ++I) {
2395 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2396 (*I)->getAccess());
2397 if (NamedDecl *ND = R.getAcceptableDecl(*I))
2398 R.addDecl(ND, AS);
2399 }
2400 R.resolveKind();
2401 return true;
2402}
2403
2404/// Performs qualified name lookup or special type of lookup for
2405/// "__super::" scope specifier.
2406///
2407/// This routine is a convenience overload meant to be called from contexts
2408/// that need to perform a qualified name lookup with an optional C++ scope
2409/// specifier that might require special kind of lookup.
2410///
2411/// \param R captures both the lookup criteria and any lookup results found.
2412///
2413/// \param LookupCtx The context in which qualified name lookup will
2414/// search.
2415///
2416/// \param SS An optional C++ scope-specifier.
2417///
2418/// \returns true if lookup succeeded, false if it failed.
2419bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2420 CXXScopeSpec &SS) {
2421 auto *NNS = SS.getScopeRep();
2422 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2423 return LookupInSuper(R, NNS->getAsRecordDecl());
2424 else
2425
2426 return LookupQualifiedName(R, LookupCtx);
2427}
2428
2429/// Performs name lookup for a name that was parsed in the
2430/// source code, and may contain a C++ scope specifier.
2431///
2432/// This routine is a convenience routine meant to be called from
2433/// contexts that receive a name and an optional C++ scope specifier
2434/// (e.g., "N::M::x"). It will then perform either qualified or
2435/// unqualified name lookup (with LookupQualifiedName or LookupName,
2436/// respectively) on the given name and return those results. It will
2437/// perform a special type of lookup for "__super::" scope specifier.
2438///
2439/// @param S The scope from which unqualified name lookup will
2440/// begin.
2441///
2442/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
2443///
2444/// @param EnteringContext Indicates whether we are going to enter the
2445/// context of the scope-specifier SS (if present).
2446///
2447/// @returns True if any decls were found (but possibly ambiguous)
2448bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2449 bool AllowBuiltinCreation, bool EnteringContext) {
2450 if (SS && SS->isInvalid()) {
2451 // When the scope specifier is invalid, don't even look for
2452 // anything.
2453 return false;
2454 }
2455
2456 if (SS && SS->isSet()) {
2457 NestedNameSpecifier *NNS = SS->getScopeRep();
2458 if (NNS->getKind() == NestedNameSpecifier::Super)
2459 return LookupInSuper(R, NNS->getAsRecordDecl());
2460
2461 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2462 // We have resolved the scope specifier to a particular declaration
2463 // contex, and will perform name lookup in that context.
2464 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2465 return false;
2466
2467 R.setContextRange(SS->getRange());
2468 return LookupQualifiedName(R, DC);
2469 }
2470
2471 // We could not resolve the scope specified to a specific declaration
2472 // context, which means that SS refers to an unknown specialization.
2473 // Name lookup can't find anything in this case.
2474 R.setNotFoundInCurrentInstantiation();
2475 R.setContextRange(SS->getRange());
2476 return false;
2477 }
2478
2479 // Perform unqualified name lookup starting in the given scope.
2480 return LookupName(R, S, AllowBuiltinCreation);
2481}
2482
2483/// Perform qualified name lookup into all base classes of the given
2484/// class.
2485///
2486/// \param R captures both the lookup criteria and any lookup results found.
2487///
2488/// \param Class The context in which qualified name lookup will
2489/// search. Name lookup will search in all base classes merging the results.
2490///
2491/// @returns True if any decls were found (but possibly ambiguous)
2492bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2493 // The access-control rules we use here are essentially the rules for
2494 // doing a lookup in Class that just magically skipped the direct
2495 // members of Class itself. That is, the naming class is Class, and the
2496 // access includes the access of the base.
2497 for (const auto &BaseSpec : Class->bases()) {
2498 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2499 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2500 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2501 Result.setBaseObjectType(Context.getRecordType(Class));
2502 LookupQualifiedName(Result, RD);
2503
2504 // Copy the lookup results into the target, merging the base's access into
2505 // the path access.
2506 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2507 R.addDecl(I.getDecl(),
2508 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2509 I.getAccess()));
2510 }
2511
2512 Result.suppressDiagnostics();
2513 }
2514
2515 R.resolveKind();
2516 R.setNamingClass(Class);
2517
2518 return !R.empty();
2519}
2520
2521/// Produce a diagnostic describing the ambiguity that resulted
2522/// from name lookup.
2523///
2524/// \param Result The result of the ambiguous lookup to be diagnosed.
2525void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2526 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2527
2528 DeclarationName Name = Result.getLookupName();
2529 SourceLocation NameLoc = Result.getNameLoc();
2530 SourceRange LookupRange = Result.getContextRange();
2531
2532 switch (Result.getAmbiguityKind()) {
2533 case LookupResult::AmbiguousBaseSubobjects: {
2534 CXXBasePaths *Paths = Result.getBasePaths();
2535 QualType SubobjectType = Paths->front().back().Base->getType();
2536 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2537 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2538 << LookupRange;
2539
2540 DeclContext::lookup_iterator Found = Paths->front().Decls;
2541 while (isa<CXXMethodDecl>(*Found) &&
2542 cast<CXXMethodDecl>(*Found)->isStatic())
2543 ++Found;
2544
2545 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2546 break;
2547 }
2548
2549 case LookupResult::AmbiguousBaseSubobjectTypes: {
2550 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2551 << Name << LookupRange;
2552
2553 CXXBasePaths *Paths = Result.getBasePaths();
2554 std::set<const NamedDecl *> DeclsPrinted;
2555 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2556 PathEnd = Paths->end();
2557 Path != PathEnd; ++Path) {
2558 const NamedDecl *D = *Path->Decls;
2559 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2560 continue;
2561 if (DeclsPrinted.insert(D).second) {
2562 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2563 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2564 << TD->getUnderlyingType();
2565 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2566 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2567 << Context.getTypeDeclType(TD);
2568 else
2569 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2570 }
2571 }
2572 break;
2573 }
2574
2575 case LookupResult::AmbiguousTagHiding: {
2576 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2577
2578 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2579
2580 for (auto *D : Result)
2581 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2582 TagDecls.insert(TD);
2583 Diag(TD->getLocation(), diag::note_hidden_tag);
2584 }
2585
2586 for (auto *D : Result)
2587 if (!isa<TagDecl>(D))
2588 Diag(D->getLocation(), diag::note_hiding_object);
2589
2590 // For recovery purposes, go ahead and implement the hiding.
2591 LookupResult::Filter F = Result.makeFilter();
2592 while (F.hasNext()) {
2593 if (TagDecls.count(F.next()))
2594 F.erase();
2595 }
2596 F.done();
2597 break;
2598 }
2599
2600 case LookupResult::AmbiguousReference: {
2601 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2602
2603 for (auto *D : Result)
2604 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2605 break;
2606 }
2607 }
2608}
2609
2610namespace {
2611 struct AssociatedLookup {
2612 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2613 Sema::AssociatedNamespaceSet &Namespaces,
2614 Sema::AssociatedClassSet &Classes)
2615 : S(S), Namespaces(Namespaces), Classes(Classes),
2616 InstantiationLoc(InstantiationLoc) {
2617 }
2618
2619 bool addClassTransitive(CXXRecordDecl *RD) {
2620 Classes.insert(RD);
2621 return ClassesTransitive.insert(RD);
2622 }
2623
2624 Sema &S;
2625 Sema::AssociatedNamespaceSet &Namespaces;
2626 Sema::AssociatedClassSet &Classes;
2627 SourceLocation InstantiationLoc;
2628
2629 private:
2630 Sema::AssociatedClassSet ClassesTransitive;
2631 };
2632} // end anonymous namespace
2633
2634static void
2635addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2636
2637// Given the declaration context \param Ctx of a class, class template or
2638// enumeration, add the associated namespaces to \param Namespaces as described
2639// in [basic.lookup.argdep]p2.
2640static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2641 DeclContext *Ctx) {
2642 // The exact wording has been changed in C++14 as a result of
2643 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2644 // to all language versions since it is possible to return a local type
2645 // from a lambda in C++11.
2646 //
2647 // C++14 [basic.lookup.argdep]p2:
2648 // If T is a class type [...]. Its associated namespaces are the innermost
2649 // enclosing namespaces of its associated classes. [...]
2650 //
2651 // If T is an enumeration type, its associated namespace is the innermost
2652 // enclosing namespace of its declaration. [...]
2653
2654 // We additionally skip inline namespaces. The innermost non-inline namespace
2655 // contains all names of all its nested inline namespaces anyway, so we can
2656 // replace the entire inline namespace tree with its root.
2657 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2658 Ctx = Ctx->getParent();
2659
2660 Namespaces.insert(Ctx->getPrimaryContext());
2661}
2662
2663// Add the associated classes and namespaces for argument-dependent
2664// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2665static void
2666addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2667 const TemplateArgument &Arg) {
2668 // C++ [basic.lookup.argdep]p2, last bullet:
2669 // -- [...] ;
2670 switch (Arg.getKind()) {
2671 case TemplateArgument::Null:
2672 break;
2673
2674 case TemplateArgument::Type:
2675 // [...] the namespaces and classes associated with the types of the
2676 // template arguments provided for template type parameters (excluding
2677 // template template parameters)
2678 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2679 break;
2680
2681 case TemplateArgument::Template:
2682 case TemplateArgument::TemplateExpansion: {
2683 // [...] the namespaces in which any template template arguments are
2684 // defined; and the classes in which any member templates used as
2685 // template template arguments are defined.
2686 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2687 if (ClassTemplateDecl *ClassTemplate
2688 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2689 DeclContext *Ctx = ClassTemplate->getDeclContext();
2690 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2691 Result.Classes.insert(EnclosingClass);
2692 // Add the associated namespace for this class.
2693 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2694 }
2695 break;
2696 }
2697
2698 case TemplateArgument::Declaration:
2699 case TemplateArgument::Integral:
2700 case TemplateArgument::Expression:
2701 case TemplateArgument::NullPtr:
2702 // [Note: non-type template arguments do not contribute to the set of
2703 // associated namespaces. ]
2704 break;
2705
2706 case TemplateArgument::Pack:
2707 for (const auto &P : Arg.pack_elements())
2708 addAssociatedClassesAndNamespaces(Result, P);
2709 break;
2710 }
2711}
2712
2713// Add the associated classes and namespaces for argument-dependent lookup
2714// with an argument of class type (C++ [basic.lookup.argdep]p2).
2715static void
2716addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2717 CXXRecordDecl *Class) {
2718
2719 // Just silently ignore anything whose name is __va_list_tag.
2720 if (Class->getDeclName() == Result.S.VAListTagName)
2721 return;
2722
2723 // C++ [basic.lookup.argdep]p2:
2724 // [...]
2725 // -- If T is a class type (including unions), its associated
2726 // classes are: the class itself; the class of which it is a
2727 // member, if any; and its direct and indirect base classes.
2728 // Its associated namespaces are the innermost enclosing
2729 // namespaces of its associated classes.
2730
2731 // Add the class of which it is a member, if any.
2732 DeclContext *Ctx = Class->getDeclContext();
2733 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2734 Result.Classes.insert(EnclosingClass);
2735
2736 // Add the associated namespace for this class.
2737 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2738
2739 // -- If T is a template-id, its associated namespaces and classes are
2740 // the namespace in which the template is defined; for member
2741 // templates, the member template's class; the namespaces and classes
2742 // associated with the types of the template arguments provided for
2743 // template type parameters (excluding template template parameters); the
2744 // namespaces in which any template template arguments are defined; and
2745 // the classes in which any member templates used as template template
2746 // arguments are defined. [Note: non-type template arguments do not
2747 // contribute to the set of associated namespaces. ]
2748 if (ClassTemplateSpecializationDecl *Spec
2749 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2750 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2751 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2752 Result.Classes.insert(EnclosingClass);
2753 // Add the associated namespace for this class.
2754 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2755
2756 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2757 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2758 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2759 }
2760
2761 // Add the class itself. If we've already transitively visited this class,
2762 // we don't need to visit base classes.
2763 if (!Result.addClassTransitive(Class))
2764 return;
2765
2766 // Only recurse into base classes for complete types.
2767 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2768 Result.S.Context.getRecordType(Class)))
2769 return;
2770
2771 // Add direct and indirect base classes along with their associated
2772 // namespaces.
2773 SmallVector<CXXRecordDecl *, 32> Bases;
2774 Bases.push_back(Class);
2775 while (!Bases.empty()) {
2776 // Pop this class off the stack.
2777 Class = Bases.pop_back_val();
2778
2779 // Visit the base classes.
2780 for (const auto &Base : Class->bases()) {
2781 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
2782 // In dependent contexts, we do ADL twice, and the first time around,
2783 // the base type might be a dependent TemplateSpecializationType, or a
2784 // TemplateTypeParmType. If that happens, simply ignore it.
2785 // FIXME: If we want to support export, we probably need to add the
2786 // namespace of the template in a TemplateSpecializationType, or even
2787 // the classes and namespaces of known non-dependent arguments.
2788 if (!BaseType)
2789 continue;
2790 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2791 if (Result.addClassTransitive(BaseDecl)) {
2792 // Find the associated namespace for this base class.
2793 DeclContext *BaseCtx = BaseDecl->getDeclContext();
2794 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2795
2796 // Make sure we visit the bases of this base class.
2797 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2798 Bases.push_back(BaseDecl);
2799 }
2800 }
2801 }
2802}
2803
2804// Add the associated classes and namespaces for
2805// argument-dependent lookup with an argument of type T
2806// (C++ [basic.lookup.koenig]p2).
2807static void
2808addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2809 // C++ [basic.lookup.koenig]p2:
2810 //
2811 // For each argument type T in the function call, there is a set
2812 // of zero or more associated namespaces and a set of zero or more
2813 // associated classes to be considered. The sets of namespaces and
2814 // classes is determined entirely by the types of the function
2815 // arguments (and the namespace of any template template
2816 // argument). Typedef names and using-declarations used to specify
2817 // the types do not contribute to this set. The sets of namespaces
2818 // and classes are determined in the following way:
2819
2820 SmallVector<const Type *, 16> Queue;
2821 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2822
2823 while (true) {
2824 switch (T->getTypeClass()) {
2825
2826#define TYPE(Class, Base)
2827#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2828#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2829#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2830#define ABSTRACT_TYPE(Class, Base)
2831#include "clang/AST/TypeNodes.inc"
2832 // T is canonical. We can also ignore dependent types because
2833 // we don't need to do ADL at the definition point, but if we
2834 // wanted to implement template export (or if we find some other
2835 // use for associated classes and namespaces...) this would be
2836 // wrong.
2837 break;
2838
2839 // -- If T is a pointer to U or an array of U, its associated
2840 // namespaces and classes are those associated with U.
2841 case Type::Pointer:
2842 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2843 continue;
2844 case Type::ConstantArray:
2845 case Type::IncompleteArray:
2846 case Type::VariableArray:
2847 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2848 continue;
2849
2850 // -- If T is a fundamental type, its associated sets of
2851 // namespaces and classes are both empty.
2852 case Type::Builtin:
2853 break;
2854
2855 // -- If T is a class type (including unions), its associated
2856 // classes are: the class itself; the class of which it is
2857 // a member, if any; and its direct and indirect base classes.
2858 // Its associated namespaces are the innermost enclosing
2859 // namespaces of its associated classes.
2860 case Type::Record: {
2861 CXXRecordDecl *Class =
2862 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2863 addAssociatedClassesAndNamespaces(Result, Class);
2864 break;
2865 }
2866
2867 // -- If T is an enumeration type, its associated namespace
2868 // is the innermost enclosing namespace of its declaration.
2869 // If it is a class member, its associated class is the
2870 // member’s class; else it has no associated class.
2871 case Type::Enum: {
2872 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2873
2874 DeclContext *