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/LangOptions.h"
25#include "clang/Basic/TargetInfo.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/RISCVIntrinsicManager.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
36#include "clang/Sema/SemaInternal.h"
37#include "clang/Sema/SemaRISCV.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "clang/Sema/TypoCorrection.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/STLForwardCompat.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/TinyPtrVector.h"
44#include "llvm/ADT/edit_distance.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/ErrorHandling.h"
47#include <algorithm>
48#include <iterator>
49#include <list>
50#include <optional>
51#include <set>
52#include <utility>
53#include <vector>
54
55#include "OpenCLBuiltins.inc"
56
57using namespace clang;
58using namespace sema;
59
60namespace {
61 class UnqualUsingEntry {
62 const DeclContext *Nominated;
63 const DeclContext *CommonAncestor;
64
65 public:
66 UnqualUsingEntry(const DeclContext *Nominated,
67 const DeclContext *CommonAncestor)
68 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
69 }
70
71 const DeclContext *getCommonAncestor() const {
72 return CommonAncestor;
73 }
74
75 const DeclContext *getNominatedNamespace() const {
76 return Nominated;
77 }
78
79 // Sort by the pointer value of the common ancestor.
80 struct Comparator {
81 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
82 return L.getCommonAncestor() < R.getCommonAncestor();
83 }
84
85 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
86 return E.getCommonAncestor() < DC;
87 }
88
89 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
90 return DC < E.getCommonAncestor();
91 }
92 };
93 };
94
95 /// A collection of using directives, as used by C++ unqualified
96 /// lookup.
97 class UnqualUsingDirectiveSet {
98 Sema &SemaRef;
99
100 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
101
102 ListTy list;
103 llvm::SmallPtrSet<DeclContext*, 8> visited;
104
105 public:
106 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
107
108 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
109 // C++ [namespace.udir]p1:
110 // During unqualified name lookup, the names appear as if they
111 // were declared in the nearest enclosing namespace which contains
112 // both the using-directive and the nominated namespace.
113 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
114 assert(InnermostFileDC && InnermostFileDC->isFileContext());
115
116 for (; S; S = S->getParent()) {
117 // C++ [namespace.udir]p1:
118 // A using-directive shall not appear in class scope, but may
119 // appear in namespace scope or in block scope.
120 DeclContext *Ctx = S->getEntity();
121 if (Ctx && Ctx->isFileContext()) {
122 visit(DC: Ctx, EffectiveDC: Ctx);
123 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
124 for (auto *I : S->using_directives())
125 if (SemaRef.isVisible(D: I))
126 visit(UD: I, EffectiveDC: InnermostFileDC);
127 }
128 }
129 }
130
131 // Visits a context and collect all of its using directives
132 // recursively. Treats all using directives as if they were
133 // declared in the context.
134 //
135 // A given context is only every visited once, so it is important
136 // that contexts be visited from the inside out in order to get
137 // the effective DCs right.
138 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
139 if (!visited.insert(Ptr: DC).second)
140 return;
141
142 addUsingDirectives(DC, EffectiveDC);
143 }
144
145 // Visits a using directive and collects all of its using
146 // directives recursively. Treats all using directives as if they
147 // were declared in the effective DC.
148 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
149 DeclContext *NS = UD->getNominatedNamespace();
150 if (!visited.insert(Ptr: NS).second)
151 return;
152
153 addUsingDirective(UD, EffectiveDC);
154 addUsingDirectives(DC: NS, EffectiveDC);
155 }
156
157 // Adds all the using directives in a context (and those nominated
158 // by its using directives, transitively) as if they appeared in
159 // the given effective context.
160 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
161 SmallVector<DeclContext*, 4> queue;
162 while (true) {
163 for (auto *UD : DC->using_directives()) {
164 DeclContext *NS = UD->getNominatedNamespace();
165 if (SemaRef.isVisible(D: UD) && visited.insert(Ptr: NS).second) {
166 addUsingDirective(UD, EffectiveDC);
167 queue.push_back(Elt: NS);
168 }
169 }
170
171 if (queue.empty())
172 return;
173
174 DC = queue.pop_back_val();
175 }
176 }
177
178 // Add a using directive as if it had been declared in the given
179 // context. This helps implement C++ [namespace.udir]p3:
180 // The using-directive is transitive: if a scope contains a
181 // using-directive that nominates a second namespace that itself
182 // contains using-directives, the effect is as if the
183 // using-directives from the second namespace also appeared in
184 // the first.
185 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
186 // Find the common ancestor between the effective context and
187 // the nominated namespace.
188 DeclContext *Common = UD->getNominatedNamespace();
189 while (!Common->Encloses(DC: EffectiveDC))
190 Common = Common->getParent();
191 Common = Common->getPrimaryContext();
192
193 list.push_back(Elt: UnqualUsingEntry(UD->getNominatedNamespace(), Common));
194 }
195
196 void done() { llvm::stable_sort(Range&: list, C: UnqualUsingEntry::Comparator()); }
197
198 typedef ListTy::const_iterator const_iterator;
199
200 const_iterator begin() const { return list.begin(); }
201 const_iterator end() const { return list.end(); }
202
203 llvm::iterator_range<const_iterator>
204 getNamespacesFor(const DeclContext *DC) const {
205 return llvm::make_range(p: std::equal_range(first: begin(), last: end(),
206 val: DC->getPrimaryContext(),
207 comp: UnqualUsingEntry::Comparator()));
208 }
209 };
210} // end anonymous namespace
211
212// Retrieve the set of identifier namespaces that correspond to a
213// specific kind of name lookup.
214static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
215 bool CPlusPlus,
216 bool Redeclaration) {
217 unsigned IDNS = 0;
218 switch (NameKind) {
219 case Sema::LookupObjCImplicitSelfParam:
220 case Sema::LookupOrdinaryName:
221 case Sema::LookupRedeclarationWithLinkage:
222 case Sema::LookupLocalFriendName:
223 case Sema::LookupDestructorName:
224 IDNS = Decl::IDNS_Ordinary;
225 if (CPlusPlus) {
226 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
227 if (Redeclaration)
228 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
229 }
230 if (Redeclaration)
231 IDNS |= Decl::IDNS_LocalExtern;
232 break;
233
234 case Sema::LookupOperatorName:
235 // Operator lookup is its own crazy thing; it is not the same
236 // as (e.g.) looking up an operator name for redeclaration.
237 assert(!Redeclaration && "cannot do redeclaration operator lookup");
238 IDNS = Decl::IDNS_NonMemberOperator;
239 break;
240
241 case Sema::LookupTagName:
242 if (CPlusPlus) {
243 IDNS = Decl::IDNS_Type;
244
245 // When looking for a redeclaration of a tag name, we add:
246 // 1) TagFriend to find undeclared friend decls
247 // 2) Namespace because they can't "overload" with tag decls.
248 // 3) Tag because it includes class templates, which can't
249 // "overload" with tag decls.
250 if (Redeclaration)
251 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
252 } else {
253 IDNS = Decl::IDNS_Tag;
254 }
255 break;
256
257 case Sema::LookupLabel:
258 IDNS = Decl::IDNS_Label;
259 break;
260
261 case Sema::LookupMemberName:
262 IDNS = Decl::IDNS_Member;
263 if (CPlusPlus)
264 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
265 break;
266
267 case Sema::LookupNestedNameSpecifierName:
268 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
269 break;
270
271 case Sema::LookupNamespaceName:
272 IDNS = Decl::IDNS_Namespace;
273 break;
274
275 case Sema::LookupUsingDeclName:
276 assert(Redeclaration && "should only be used for redecl lookup");
277 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
278 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
279 Decl::IDNS_LocalExtern;
280 break;
281
282 case Sema::LookupObjCProtocolName:
283 IDNS = Decl::IDNS_ObjCProtocol;
284 break;
285
286 case Sema::LookupOMPReductionName:
287 IDNS = Decl::IDNS_OMPReduction;
288 break;
289
290 case Sema::LookupOMPMapperName:
291 IDNS = Decl::IDNS_OMPMapper;
292 break;
293
294 case Sema::LookupAnyName:
295 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
296 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
297 | Decl::IDNS_Type;
298 break;
299 }
300 return IDNS;
301}
302
303void LookupResult::configure() {
304 IDNS = getIDNS(NameKind: LookupKind, CPlusPlus: getSema().getLangOpts().CPlusPlus,
305 Redeclaration: isForRedeclaration());
306
307 // If we're looking for one of the allocation or deallocation
308 // operators, make sure that the implicitly-declared new and delete
309 // operators can be found.
310 switch (NameInfo.getName().getCXXOverloadedOperator()) {
311 case OO_New:
312 case OO_Delete:
313 case OO_Array_New:
314 case OO_Array_Delete:
315 getSema().DeclareGlobalNewDelete();
316 break;
317
318 default:
319 break;
320 }
321
322 // Compiler builtins are always visible, regardless of where they end
323 // up being declared.
324 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
325 if (unsigned BuiltinID = Id->getBuiltinID()) {
326 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID))
327 AllowHidden = true;
328 }
329 }
330}
331
332bool LookupResult::checkDebugAssumptions() const {
333 // This function is never called by NDEBUG builds.
334 assert(ResultKind != LookupResultKind::NotFound || Decls.size() == 0);
335 assert(ResultKind != LookupResultKind::Found || Decls.size() == 1);
336 assert(ResultKind != LookupResultKind::FoundOverloaded || Decls.size() > 1 ||
337 (Decls.size() == 1 &&
338 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
339 assert(ResultKind != LookupResultKind::FoundUnresolvedValue ||
340 checkUnresolved());
341 assert(ResultKind != LookupResultKind::Ambiguous || Decls.size() > 1 ||
342 (Decls.size() == 1 &&
343 (Ambiguity == LookupAmbiguityKind::AmbiguousBaseSubobjects ||
344 Ambiguity == LookupAmbiguityKind::AmbiguousBaseSubobjectTypes)));
345 assert((Paths != nullptr) ==
346 (ResultKind == LookupResultKind::Ambiguous &&
347 (Ambiguity == LookupAmbiguityKind::AmbiguousBaseSubobjectTypes ||
348 Ambiguity == LookupAmbiguityKind::AmbiguousBaseSubobjects)));
349 return true;
350}
351
352// Necessary because CXXBasePaths is not complete in Sema.h
353void LookupResult::deletePaths(CXXBasePaths *Paths) {
354 delete Paths;
355}
356
357/// Get a representative context for a declaration such that two declarations
358/// will have the same context if they were found within the same scope.
359static const DeclContext *getContextForScopeMatching(const Decl *D) {
360 // For function-local declarations, use that function as the context. This
361 // doesn't account for scopes within the function; the caller must deal with
362 // those.
363 if (const DeclContext *DC = D->getLexicalDeclContext();
364 DC->isFunctionOrMethod())
365 return DC;
366
367 // Otherwise, look at the semantic context of the declaration. The
368 // declaration must have been found there.
369 return D->getDeclContext()->getRedeclContext();
370}
371
372/// Determine whether \p D is a better lookup result than \p Existing,
373/// given that they declare the same entity.
374static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
375 const NamedDecl *D,
376 const NamedDecl *Existing) {
377 // When looking up redeclarations of a using declaration, prefer a using
378 // shadow declaration over any other declaration of the same entity.
379 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(Val: D) &&
380 !isa<UsingShadowDecl>(Val: Existing))
381 return true;
382
383 const auto *DUnderlying = D->getUnderlyingDecl();
384 const auto *EUnderlying = Existing->getUnderlyingDecl();
385
386 // If they have different underlying declarations, prefer a typedef over the
387 // original type (this happens when two type declarations denote the same
388 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
389 // might carry additional semantic information, such as an alignment override.
390 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
391 // declaration over a typedef. Also prefer a tag over a typedef for
392 // destructor name lookup because in some contexts we only accept a
393 // class-name in a destructor declaration.
394 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
395 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
396 bool HaveTag = isa<TagDecl>(Val: EUnderlying);
397 bool WantTag =
398 Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName;
399 return HaveTag != WantTag;
400 }
401
402 // Pick the function with more default arguments.
403 // FIXME: In the presence of ambiguous default arguments, we should keep both,
404 // so we can diagnose the ambiguity if the default argument is needed.
405 // See C++ [over.match.best]p3.
406 if (const auto *DFD = dyn_cast<FunctionDecl>(Val: DUnderlying)) {
407 const auto *EFD = cast<FunctionDecl>(Val: EUnderlying);
408 unsigned DMin = DFD->getMinRequiredArguments();
409 unsigned EMin = EFD->getMinRequiredArguments();
410 // If D has more default arguments, it is preferred.
411 if (DMin != EMin)
412 return DMin < EMin;
413 // FIXME: When we track visibility for default function arguments, check
414 // that we pick the declaration with more visible default arguments.
415 }
416
417 // Pick the template with more default template arguments.
418 if (const auto *DTD = dyn_cast<TemplateDecl>(Val: DUnderlying)) {
419 const auto *ETD = cast<TemplateDecl>(Val: EUnderlying);
420 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
421 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
422 // If D has more default arguments, it is preferred. Note that default
423 // arguments (and their visibility) is monotonically increasing across the
424 // redeclaration chain, so this is a quick proxy for "is more recent".
425 if (DMin != EMin)
426 return DMin < EMin;
427 // If D has more *visible* default arguments, it is preferred. Note, an
428 // earlier default argument being visible does not imply that a later
429 // default argument is visible, so we can't just check the first one.
430 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
431 I != N; ++I) {
432 if (!S.hasVisibleDefaultArgument(
433 D: ETD->getTemplateParameters()->getParam(Idx: I)) &&
434 S.hasVisibleDefaultArgument(
435 D: DTD->getTemplateParameters()->getParam(Idx: I)))
436 return true;
437 }
438 }
439
440 // VarDecl can have incomplete array types, prefer the one with more complete
441 // array type.
442 if (const auto *DVD = dyn_cast<VarDecl>(Val: DUnderlying)) {
443 const auto *EVD = cast<VarDecl>(Val: EUnderlying);
444 if (EVD->getType()->isIncompleteType() &&
445 !DVD->getType()->isIncompleteType()) {
446 // Prefer the decl with a more complete type if visible.
447 return S.isVisible(D: DVD);
448 }
449 return false; // Avoid picking up a newer decl, just because it was newer.
450 }
451
452 // For most kinds of declaration, it doesn't really matter which one we pick.
453 if (!isa<FunctionDecl>(Val: DUnderlying) && !isa<VarDecl>(Val: DUnderlying)) {
454 // If the existing declaration is hidden, prefer the new one. Otherwise,
455 // keep what we've got.
456 return !S.isVisible(D: Existing);
457 }
458
459 // Pick the newer declaration; it might have a more precise type.
460 for (const Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
461 Prev = Prev->getPreviousDecl())
462 if (Prev == EUnderlying)
463 return true;
464 return false;
465}
466
467/// Determine whether \p D can hide a tag declaration.
468static bool canHideTag(const NamedDecl *D) {
469 // C++ [basic.scope.declarative]p4:
470 // Given a set of declarations in a single declarative region [...]
471 // exactly one declaration shall declare a class name or enumeration name
472 // that is not a typedef name and the other declarations shall all refer to
473 // the same variable, non-static data member, or enumerator, or all refer
474 // to functions and function templates; in this case the class name or
475 // enumeration name is hidden.
476 // C++ [basic.scope.hiding]p2:
477 // A class name or enumeration name can be hidden by the name of a
478 // variable, data member, function, or enumerator declared in the same
479 // scope.
480 // An UnresolvedUsingValueDecl always instantiates to one of these.
481 D = D->getUnderlyingDecl();
482 return isa<VarDecl>(Val: D) || isa<EnumConstantDecl>(Val: D) || isa<FunctionDecl>(Val: D) ||
483 isa<FunctionTemplateDecl>(Val: D) || isa<FieldDecl>(Val: D) ||
484 isa<UnresolvedUsingValueDecl>(Val: D);
485}
486
487/// Resolves the result kind of this lookup.
488void LookupResult::resolveKind() {
489 unsigned N = Decls.size();
490
491 // Fast case: no possible ambiguity.
492 if (N == 0) {
493 assert(ResultKind == LookupResultKind::NotFound ||
494 ResultKind == LookupResultKind::NotFoundInCurrentInstantiation);
495 return;
496 }
497
498 // If there's a single decl, we need to examine it to decide what
499 // kind of lookup this is.
500 if (N == 1) {
501 const NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
502 if (isa<FunctionTemplateDecl>(Val: D))
503 ResultKind = LookupResultKind::FoundOverloaded;
504 else if (isa<UnresolvedUsingValueDecl>(Val: D))
505 ResultKind = LookupResultKind::FoundUnresolvedValue;
506 return;
507 }
508
509 // Don't do any extra resolution if we've already resolved as ambiguous.
510 if (ResultKind == LookupResultKind::Ambiguous)
511 return;
512
513 llvm::SmallDenseMap<const NamedDecl *, unsigned, 16> Unique;
514 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
515
516 bool Ambiguous = false;
517 bool ReferenceToPlaceHolderVariable = false;
518 bool HasTag = false, HasFunction = false;
519 bool HasFunctionTemplate = false, HasUnresolved = false;
520 const NamedDecl *HasNonFunction = nullptr;
521
522 llvm::SmallVector<const NamedDecl *, 4> EquivalentNonFunctions;
523 llvm::BitVector RemovedDecls(N);
524
525 for (unsigned I = 0; I < N; I++) {
526 const NamedDecl *D = Decls[I]->getUnderlyingDecl();
527 D = cast<NamedDecl>(Val: D->getCanonicalDecl());
528
529 // Ignore an invalid declaration unless it's the only one left.
530 // Also ignore HLSLBufferDecl which not have name conflict with other Decls.
531 if ((D->isInvalidDecl() || isa<HLSLBufferDecl>(Val: D)) &&
532 N - RemovedDecls.count() > 1) {
533 RemovedDecls.set(I);
534 continue;
535 }
536
537 // C++ [basic.scope.hiding]p2:
538 // A class name or enumeration name can be hidden by the name of
539 // an object, function, or enumerator declared in the same
540 // scope. If a class or enumeration name and an object, function,
541 // or enumerator are declared in the same scope (in any order)
542 // with the same name, the class or enumeration name is hidden
543 // wherever the object, function, or enumerator name is visible.
544 if (HideTags && isa<TagDecl>(Val: D)) {
545 bool Hidden = false;
546 for (auto *OtherDecl : Decls) {
547 if (canHideTag(D: OtherDecl) && !OtherDecl->isInvalidDecl() &&
548 getContextForScopeMatching(D: OtherDecl)->Equals(
549 DC: getContextForScopeMatching(D: Decls[I]))) {
550 RemovedDecls.set(I);
551 Hidden = true;
552 break;
553 }
554 }
555 if (Hidden)
556 continue;
557 }
558
559 std::optional<unsigned> ExistingI;
560
561 // Redeclarations of types via typedef can occur both within a scope
562 // and, through using declarations and directives, across scopes. There is
563 // no ambiguity if they all refer to the same type, so unique based on the
564 // canonical type.
565 if (const auto *TD = dyn_cast<TypeDecl>(Val: D)) {
566 auto UniqueResult = UniqueTypes.insert(
567 KV: std::make_pair(x: getSema().Context.getCanonicalTypeDeclType(TD), y&: I));
568 if (!UniqueResult.second) {
569 // The type is not unique.
570 ExistingI = UniqueResult.first->second;
571 }
572 }
573
574 // For non-type declarations, check for a prior lookup result naming this
575 // canonical declaration.
576 if (!ExistingI) {
577 auto UniqueResult = Unique.insert(KV: std::make_pair(x&: D, y&: I));
578 if (!UniqueResult.second) {
579 // We've seen this entity before.
580 ExistingI = UniqueResult.first->second;
581 }
582 }
583
584 if (ExistingI) {
585 // This is not a unique lookup result. Pick one of the results and
586 // discard the other.
587 if (isPreferredLookupResult(S&: getSema(), Kind: getLookupKind(), D: Decls[I],
588 Existing: Decls[*ExistingI]))
589 Decls[*ExistingI] = Decls[I];
590 RemovedDecls.set(I);
591 continue;
592 }
593
594 // Otherwise, do some decl type analysis and then continue.
595
596 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
597 HasUnresolved = true;
598 } else if (isa<TagDecl>(Val: D)) {
599 if (HasTag)
600 Ambiguous = true;
601 HasTag = true;
602 } else if (isa<FunctionTemplateDecl>(Val: D)) {
603 HasFunction = true;
604 HasFunctionTemplate = true;
605 } else if (isa<FunctionDecl>(Val: D)) {
606 HasFunction = true;
607 } else {
608 if (HasNonFunction) {
609 // If we're about to create an ambiguity between two declarations that
610 // are equivalent, but one is an internal linkage declaration from one
611 // module and the other is an internal linkage declaration from another
612 // module, just skip it.
613 if (getSema().isEquivalentInternalLinkageDeclaration(A: HasNonFunction,
614 B: D)) {
615 EquivalentNonFunctions.push_back(Elt: D);
616 RemovedDecls.set(I);
617 continue;
618 }
619 if (D->isPlaceholderVar(LangOpts: getSema().getLangOpts()) &&
620 getContextForScopeMatching(D) ==
621 getContextForScopeMatching(D: Decls[I])) {
622 ReferenceToPlaceHolderVariable = true;
623 }
624 Ambiguous = true;
625 }
626 HasNonFunction = D;
627 }
628 }
629
630 // FIXME: This diagnostic should really be delayed until we're done with
631 // the lookup result, in case the ambiguity is resolved by the caller.
632 if (!EquivalentNonFunctions.empty() && !Ambiguous)
633 getSema().diagnoseEquivalentInternalLinkageDeclarations(
634 Loc: getNameLoc(), D: HasNonFunction, Equiv: EquivalentNonFunctions);
635
636 // Remove decls by replacing them with decls from the end (which
637 // means that we need to iterate from the end) and then truncating
638 // to the new size.
639 for (int I = RemovedDecls.find_last(); I >= 0; I = RemovedDecls.find_prev(PriorTo: I))
640 Decls[I] = Decls[--N];
641 Decls.truncate(N);
642
643 if ((HasNonFunction && (HasFunction || HasUnresolved)) ||
644 (HideTags && HasTag && (HasFunction || HasNonFunction || HasUnresolved)))
645 Ambiguous = true;
646
647 if (Ambiguous && ReferenceToPlaceHolderVariable)
648 setAmbiguous(LookupAmbiguityKind::AmbiguousReferenceToPlaceholderVariable);
649 else if (Ambiguous)
650 setAmbiguous(LookupAmbiguityKind::AmbiguousReference);
651 else if (HasUnresolved)
652 ResultKind = LookupResultKind::FoundUnresolvedValue;
653 else if (N > 1 || HasFunctionTemplate)
654 ResultKind = LookupResultKind::FoundOverloaded;
655 else
656 ResultKind = LookupResultKind::Found;
657}
658
659void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
660 CXXBasePaths::const_paths_iterator I, E;
661 for (I = P.begin(), E = P.end(); I != E; ++I)
662 for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;
663 ++DI)
664 addDecl(D: *DI);
665}
666
667void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
668 Paths = new CXXBasePaths;
669 Paths->swap(Other&: P);
670 addDeclsFromBasePaths(P: *Paths);
671 resolveKind();
672 setAmbiguous(LookupAmbiguityKind::AmbiguousBaseSubobjects);
673}
674
675void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
676 Paths = new CXXBasePaths;
677 Paths->swap(Other&: P);
678 addDeclsFromBasePaths(P: *Paths);
679 resolveKind();
680 setAmbiguous(LookupAmbiguityKind::AmbiguousBaseSubobjectTypes);
681}
682
683void LookupResult::print(raw_ostream &Out) {
684 Out << Decls.size() << " result(s)";
685 if (isAmbiguous()) Out << ", ambiguous";
686 if (Paths) Out << ", base paths present";
687
688 for (iterator I = begin(), E = end(); I != E; ++I) {
689 Out << "\n";
690 (*I)->print(Out, Indentation: 2);
691 }
692}
693
694LLVM_DUMP_METHOD void LookupResult::dump() {
695 llvm::errs() << "lookup results for " << getLookupName().getAsString()
696 << ":\n";
697 for (NamedDecl *D : *this)
698 D->dump();
699}
700
701/// Diagnose a missing builtin type.
702static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
703 llvm::StringRef Name) {
704 S.Diag(Loc: SourceLocation(), DiagID: diag::err_opencl_type_not_found)
705 << TypeClass << Name;
706 return S.Context.VoidTy;
707}
708
709/// Lookup an OpenCL enum type.
710static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
711 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
712 Sema::LookupTagName);
713 S.LookupName(R&: Result, S: S.TUScope);
714 if (Result.empty())
715 return diagOpenCLBuiltinTypeError(S, TypeClass: "enum", Name);
716 EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
717 if (!Decl)
718 return diagOpenCLBuiltinTypeError(S, TypeClass: "enum", Name);
719 return S.Context.getCanonicalTagType(TD: Decl);
720}
721
722/// Lookup an OpenCL typedef type.
723static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
724 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
725 Sema::LookupOrdinaryName);
726 S.LookupName(R&: Result, S: S.TUScope);
727 if (Result.empty())
728 return diagOpenCLBuiltinTypeError(S, TypeClass: "typedef", Name);
729 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
730 if (!Decl)
731 return diagOpenCLBuiltinTypeError(S, TypeClass: "typedef", Name);
732 return S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
733 /*Qualifier=*/std::nullopt, Decl);
734}
735
736/// Get the QualType instances of the return type and arguments for an OpenCL
737/// builtin function signature.
738/// \param S (in) The Sema instance.
739/// \param OpenCLBuiltin (in) The signature currently handled.
740/// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
741/// type used as return type or as argument.
742/// Only meaningful for generic types, otherwise equals 1.
743/// \param RetTypes (out) List of the possible return types.
744/// \param ArgTypes (out) List of the possible argument types. For each
745/// argument, ArgTypes contains QualTypes for the Cartesian product
746/// of (vector sizes) x (types) .
747static void GetQualTypesForOpenCLBuiltin(
748 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
749 SmallVector<QualType, 1> &RetTypes,
750 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
751 // Get the QualType instances of the return types.
752 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
753 OCL2Qual(S, Ty: TypeTable[Sig], QT&: RetTypes);
754 GenTypeMaxCnt = RetTypes.size();
755
756 // Get the QualType instances of the arguments.
757 // First type is the return type, skip it.
758 for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {
759 SmallVector<QualType, 1> Ty;
760 OCL2Qual(S, Ty: TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
761 QT&: Ty);
762 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
763 ArgTypes.push_back(Elt: std::move(Ty));
764 }
765}
766
767/// Create a list of the candidate function overloads for an OpenCL builtin
768/// function.
769/// \param Context (in) The ASTContext instance.
770/// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic
771/// type used as return type or as argument.
772/// Only meaningful for generic types, otherwise equals 1.
773/// \param FunctionList (out) List of FunctionTypes.
774/// \param RetTypes (in) List of the possible return types.
775/// \param ArgTypes (in) List of the possible types for the arguments.
776static void GetOpenCLBuiltinFctOverloads(
777 ASTContext &Context, unsigned GenTypeMaxCnt,
778 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
779 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
780 FunctionProtoType::ExtProtoInfo PI(
781 Context.getTargetInfo().getDefaultCallingConv());
782 PI.Variadic = false;
783
784 // Do not attempt to create any FunctionTypes if there are no return types,
785 // which happens when a type belongs to a disabled extension.
786 if (RetTypes.size() == 0)
787 return;
788
789 // Create FunctionTypes for each (gen)type.
790 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
791 SmallVector<QualType, 5> ArgList;
792
793 for (unsigned A = 0; A < ArgTypes.size(); A++) {
794 // Bail out if there is an argument that has no available types.
795 if (ArgTypes[A].size() == 0)
796 return;
797
798 // Builtins such as "max" have an "sgentype" argument that represents
799 // the corresponding scalar type of a gentype. The number of gentypes
800 // must be a multiple of the number of sgentypes.
801 assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&
802 "argument type count not compatible with gentype type count");
803 unsigned Idx = IGenType % ArgTypes[A].size();
804 ArgList.push_back(Elt: ArgTypes[A][Idx]);
805 }
806
807 FunctionList.push_back(x: Context.getFunctionType(
808 ResultTy: RetTypes[(RetTypes.size() != 1) ? IGenType : 0], Args: ArgList, EPI: PI));
809 }
810}
811
812/// When trying to resolve a function name, if isOpenCLBuiltin() returns a
813/// non-null <Index, Len> pair, then the name is referencing an OpenCL
814/// builtin function. Add all candidate signatures to the LookUpResult.
815///
816/// \param S (in) The Sema instance.
817/// \param LR (inout) The LookupResult instance.
818/// \param II (in) The identifier being resolved.
819/// \param FctIndex (in) Starting index in the BuiltinTable.
820/// \param Len (in) The signature list has Len elements.
821static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR,
822 IdentifierInfo *II,
823 const unsigned FctIndex,
824 const unsigned Len) {
825 // The builtin function declaration uses generic types (gentype).
826 bool HasGenType = false;
827
828 // Maximum number of types contained in a generic type used as return type or
829 // as argument. Only meaningful for generic types, otherwise equals 1.
830 unsigned GenTypeMaxCnt;
831
832 ASTContext &Context = S.Context;
833
834 for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
835 const OpenCLBuiltinStruct &OpenCLBuiltin =
836 BuiltinTable[FctIndex + SignatureIndex];
837
838 // Ignore this builtin function if it is not available in the currently
839 // selected language version.
840 if (!isOpenCLVersionContainedInMask(LO: Context.getLangOpts(),
841 Mask: OpenCLBuiltin.Versions))
842 continue;
843
844 // Ignore this builtin function if it carries an extension macro that is
845 // not defined. This indicates that the extension is not supported by the
846 // target, so the builtin function should not be available.
847 StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];
848 if (!Extensions.empty()) {
849 SmallVector<StringRef, 2> ExtVec;
850 Extensions.split(A&: ExtVec, Separator: " ");
851 bool AllExtensionsDefined = true;
852 for (StringRef Ext : ExtVec) {
853 if (!S.getPreprocessor().isMacroDefined(Id: Ext)) {
854 AllExtensionsDefined = false;
855 break;
856 }
857 }
858 if (!AllExtensionsDefined)
859 continue;
860 }
861
862 SmallVector<QualType, 1> RetTypes;
863 SmallVector<SmallVector<QualType, 1>, 5> ArgTypes;
864
865 // Obtain QualType lists for the function signature.
866 GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,
867 ArgTypes);
868 if (GenTypeMaxCnt > 1) {
869 HasGenType = true;
870 }
871
872 // Create function overload for each type combination.
873 std::vector<QualType> FunctionList;
874 GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,
875 ArgTypes);
876
877 SourceLocation Loc = LR.getNameLoc();
878 DeclContext *Parent = Context.getTranslationUnitDecl();
879 FunctionDecl *NewOpenCLBuiltin;
880
881 for (const auto &FTy : FunctionList) {
882 NewOpenCLBuiltin = FunctionDecl::Create(
883 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: FTy, /*TInfo=*/nullptr, SC: SC_Extern,
884 UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(), isInlineSpecified: false,
885 hasWrittenPrototype: FTy->isFunctionProtoType());
886 NewOpenCLBuiltin->setImplicit();
887
888 // Create Decl objects for each parameter, adding them to the
889 // FunctionDecl.
890 const auto *FP = cast<FunctionProtoType>(Val: FTy);
891 SmallVector<ParmVarDecl *, 4> ParmList;
892 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
893 ParmVarDecl *Parm = ParmVarDecl::Create(
894 C&: Context, DC: NewOpenCLBuiltin, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
895 Id: nullptr, T: FP->getParamType(i: IParm), TInfo: nullptr, S: SC_None, DefArg: nullptr);
896 Parm->setScopeInfo(scopeDepth: 0, parameterIndex: IParm);
897 ParmList.push_back(Elt: Parm);
898 }
899 NewOpenCLBuiltin->setParams(ParmList);
900
901 // Add function attributes.
902 if (OpenCLBuiltin.IsPure)
903 NewOpenCLBuiltin->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context));
904 if (OpenCLBuiltin.IsConst)
905 NewOpenCLBuiltin->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context));
906 if (OpenCLBuiltin.IsConv)
907 NewOpenCLBuiltin->addAttr(A: ConvergentAttr::CreateImplicit(Ctx&: Context));
908
909 if (!S.getLangOpts().OpenCLCPlusPlus)
910 NewOpenCLBuiltin->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
911
912 LR.addDecl(D: NewOpenCLBuiltin);
913 }
914 }
915
916 // If we added overloads, need to resolve the lookup result.
917 if (Len > 1 || HasGenType)
918 LR.resolveKind();
919}
920
921bool Sema::LookupBuiltin(LookupResult &R) {
922 Sema::LookupNameKind NameKind = R.getLookupKind();
923
924 // If we didn't find a use of this identifier, and if the identifier
925 // corresponds to a compiler builtin, create the decl object for the builtin
926 // now, injecting it into translation unit scope, and return it.
927 if (NameKind == Sema::LookupOrdinaryName ||
928 NameKind == Sema::LookupRedeclarationWithLinkage) {
929 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
930 if (II) {
931 if (NameKind == Sema::LookupOrdinaryName) {
932 if (getLangOpts().CPlusPlus) {
933#define BuiltinTemplate(BIName)
934#define CPlusPlusBuiltinTemplate(BIName) \
935 if (II == getASTContext().get##BIName##Name()) { \
936 R.addDecl(getASTContext().get##BIName##Decl()); \
937 return true; \
938 }
939#include "clang/Basic/BuiltinTemplates.inc"
940 }
941 if (getLangOpts().HLSL) {
942#define BuiltinTemplate(BIName)
943#define HLSLBuiltinTemplate(BIName) \
944 if (II == getASTContext().get##BIName##Name()) { \
945 R.addDecl(getASTContext().get##BIName##Decl()); \
946 return true; \
947 }
948#include "clang/Basic/BuiltinTemplates.inc"
949 }
950 }
951
952 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
953 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
954 auto Index = isOpenCLBuiltin(Name: II->getName());
955 if (Index.first) {
956 InsertOCLBuiltinDeclarationsFromTable(S&: *this, LR&: R, II, FctIndex: Index.first - 1,
957 Len: Index.second);
958 return true;
959 }
960 }
961
962 if (RISCV().DeclareRVVBuiltins || RISCV().DeclareSiFiveVectorBuiltins ||
963 RISCV().DeclareAndesVectorBuiltins) {
964 if (!RISCV().IntrinsicManager)
965 RISCV().IntrinsicManager = CreateRISCVIntrinsicManager(S&: *this);
966
967 RISCV().IntrinsicManager->InitIntrinsicList();
968
969 if (RISCV().IntrinsicManager->CreateIntrinsicIfFound(LR&: R, II, PP))
970 return true;
971 }
972
973 // If this is a builtin on this (or all) targets, create the decl.
974 if (unsigned BuiltinID = II->getBuiltinID()) {
975 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
976 // library functions like 'malloc'. Instead, we'll just error.
977 if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) &&
978 Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID))
979 return false;
980
981 if (NamedDecl *D =
982 LazilyCreateBuiltin(II, ID: BuiltinID, S: TUScope,
983 ForRedeclaration: R.isForRedeclaration(), Loc: R.getNameLoc())) {
984 R.addDecl(D);
985 return true;
986 }
987 }
988 }
989 }
990
991 return false;
992}
993
994/// Looks up the declaration of "struct objc_super" and
995/// saves it for later use in building builtin declaration of
996/// objc_msgSendSuper and objc_msgSendSuper_stret.
997static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) {
998 ASTContext &Context = Sema.Context;
999 LookupResult Result(Sema, &Context.Idents.get(Name: "objc_super"), SourceLocation(),
1000 Sema::LookupTagName);
1001 Sema.LookupName(R&: Result, S);
1002 if (Result.getResultKind() == LookupResultKind::Found)
1003 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1004 Context.setObjCSuperType(Context.getCanonicalTagType(TD));
1005}
1006
1007void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) {
1008 if (ID == Builtin::BIobjc_msgSendSuper)
1009 LookupPredefedObjCSuperType(Sema&: *this, S);
1010}
1011
1012/// Determine whether we can declare a special member function within
1013/// the class at this point.
1014static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
1015 // We need to have a definition for the class.
1016 if (!Class->getDefinition() || Class->isDependentContext())
1017 return false;
1018
1019 // We can't be in the middle of defining the class.
1020 return !Class->isBeingDefined();
1021}
1022
1023void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
1024 if (!CanDeclareSpecialMemberFunction(Class))
1025 return;
1026
1027 // If the default constructor has not yet been declared, do so now.
1028 if (Class->needsImplicitDefaultConstructor())
1029 DeclareImplicitDefaultConstructor(ClassDecl: Class);
1030
1031 // If the copy constructor has not yet been declared, do so now.
1032 if (Class->needsImplicitCopyConstructor())
1033 DeclareImplicitCopyConstructor(ClassDecl: Class);
1034
1035 // If the copy assignment operator has not yet been declared, do so now.
1036 if (Class->needsImplicitCopyAssignment())
1037 DeclareImplicitCopyAssignment(ClassDecl: Class);
1038
1039 if (getLangOpts().CPlusPlus11) {
1040 // If the move constructor has not yet been declared, do so now.
1041 if (Class->needsImplicitMoveConstructor())
1042 DeclareImplicitMoveConstructor(ClassDecl: Class);
1043
1044 // If the move assignment operator has not yet been declared, do so now.
1045 if (Class->needsImplicitMoveAssignment())
1046 DeclareImplicitMoveAssignment(ClassDecl: Class);
1047 }
1048
1049 // If the destructor has not yet been declared, do so now.
1050 if (Class->needsImplicitDestructor())
1051 DeclareImplicitDestructor(ClassDecl: Class);
1052}
1053
1054/// Determine whether this is the name of an implicitly-declared
1055/// special member function.
1056static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
1057 switch (Name.getNameKind()) {
1058 case DeclarationName::CXXConstructorName:
1059 case DeclarationName::CXXDestructorName:
1060 return true;
1061
1062 case DeclarationName::CXXOperatorName:
1063 return Name.getCXXOverloadedOperator() == OO_Equal;
1064
1065 default:
1066 break;
1067 }
1068
1069 return false;
1070}
1071
1072/// If there are any implicit member functions with the given name
1073/// that need to be declared in the given declaration context, do so.
1074static void DeclareImplicitMemberFunctionsWithName(Sema &S,
1075 DeclarationName Name,
1076 SourceLocation Loc,
1077 const DeclContext *DC) {
1078 if (!DC)
1079 return;
1080
1081 switch (Name.getNameKind()) {
1082 case DeclarationName::CXXConstructorName:
1083 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC))
1084 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Class: Record)) {
1085 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1086 if (Record->needsImplicitDefaultConstructor())
1087 S.DeclareImplicitDefaultConstructor(ClassDecl: Class);
1088 if (Record->needsImplicitCopyConstructor())
1089 S.DeclareImplicitCopyConstructor(ClassDecl: Class);
1090 if (S.getLangOpts().CPlusPlus11 &&
1091 Record->needsImplicitMoveConstructor())
1092 S.DeclareImplicitMoveConstructor(ClassDecl: Class);
1093 }
1094 break;
1095
1096 case DeclarationName::CXXDestructorName:
1097 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC))
1098 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
1099 CanDeclareSpecialMemberFunction(Class: Record))
1100 S.DeclareImplicitDestructor(ClassDecl: const_cast<CXXRecordDecl *>(Record));
1101 break;
1102
1103 case DeclarationName::CXXOperatorName:
1104 if (Name.getCXXOverloadedOperator() != OO_Equal)
1105 break;
1106
1107 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC)) {
1108 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Class: Record)) {
1109 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1110 if (Record->needsImplicitCopyAssignment())
1111 S.DeclareImplicitCopyAssignment(ClassDecl: Class);
1112 if (S.getLangOpts().CPlusPlus11 &&
1113 Record->needsImplicitMoveAssignment())
1114 S.DeclareImplicitMoveAssignment(ClassDecl: Class);
1115 }
1116 }
1117 break;
1118
1119 case DeclarationName::CXXDeductionGuideName:
1120 S.DeclareImplicitDeductionGuides(Template: Name.getCXXDeductionGuideTemplate(), Loc);
1121 break;
1122
1123 default:
1124 break;
1125 }
1126}
1127
1128// Adds all qualifying matches for a name within a decl context to the
1129// given lookup result. Returns true if any matches were found.
1130static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
1131 bool Found = false;
1132
1133 // Lazily declare C++ special member functions.
1134 if (S.getLangOpts().CPlusPlus)
1135 DeclareImplicitMemberFunctionsWithName(S, Name: R.getLookupName(), Loc: R.getNameLoc(),
1136 DC);
1137
1138 // Perform lookup into this declaration context.
1139 DeclContext::lookup_result DR = DC->lookup(Name: R.getLookupName());
1140 for (NamedDecl *D : DR) {
1141 if ((D = R.getAcceptableDecl(D))) {
1142 R.addDecl(D);
1143 Found = true;
1144 }
1145 }
1146
1147 if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
1148 return true;
1149
1150 if (R.getLookupName().getNameKind()
1151 != DeclarationName::CXXConversionFunctionName ||
1152 R.getLookupName().getCXXNameType()->isDependentType() ||
1153 !isa<CXXRecordDecl>(Val: DC))
1154 return Found;
1155
1156 // C++ [temp.mem]p6:
1157 // A specialization of a conversion function template is not found by
1158 // name lookup. Instead, any conversion function templates visible in the
1159 // context of the use are considered. [...]
1160 const CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
1161 if (!Record->isCompleteDefinition() && !R.isForRedeclaration())
1162 return Found;
1163
1164 // For conversion operators, 'operator auto' should only match
1165 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
1166 // as a candidate for template substitution.
1167 auto *ContainedDeducedType =
1168 R.getLookupName().getCXXNameType()->getContainedDeducedType();
1169 if (R.getLookupName().getNameKind() ==
1170 DeclarationName::CXXConversionFunctionName &&
1171 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
1172 return Found;
1173
1174 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
1175 UEnd = Record->conversion_end(); U != UEnd; ++U) {
1176 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: *U);
1177 if (!ConvTemplate)
1178 continue;
1179
1180 // When we're performing lookup for the purposes of redeclaration, just
1181 // add the conversion function template. When we deduce template
1182 // arguments for specializations, we'll end up unifying the return
1183 // type of the new declaration with the type of the function template.
1184 if (R.isForRedeclaration()) {
1185 R.addDecl(D: ConvTemplate);
1186 Found = true;
1187 continue;
1188 }
1189
1190 // C++ [temp.mem]p6:
1191 // [...] For each such operator, if argument deduction succeeds
1192 // (14.9.2.3), the resulting specialization is used as if found by
1193 // name lookup.
1194 //
1195 // When referencing a conversion function for any purpose other than
1196 // a redeclaration (such that we'll be building an expression with the
1197 // result), perform template argument deduction and place the
1198 // specialization into the result set. We do this to avoid forcing all
1199 // callers to perform special deduction for conversion functions.
1200 TemplateDeductionInfo Info(R.getNameLoc());
1201 FunctionDecl *Specialization = nullptr;
1202
1203 const FunctionProtoType *ConvProto
1204 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
1205 assert(ConvProto && "Nonsensical conversion function template type");
1206
1207 // Compute the type of the function that we would expect the conversion
1208 // function to have, if it were to match the name given.
1209 // FIXME: Calling convention!
1210 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
1211 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(cc: CC_C);
1212 EPI.ExceptionSpec = EST_None;
1213 QualType ExpectedType = R.getSema().Context.getFunctionType(
1214 ResultTy: R.getLookupName().getCXXNameType(), Args: {}, EPI);
1215
1216 // Perform template argument deduction against the type that we would
1217 // expect the function to have.
1218 if (R.getSema().DeduceTemplateArguments(FunctionTemplate: ConvTemplate, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedType,
1219 Specialization, Info) ==
1220 TemplateDeductionResult::Success) {
1221 R.addDecl(D: Specialization);
1222 Found = true;
1223 }
1224 }
1225
1226 return Found;
1227}
1228
1229// Performs C++ unqualified lookup into the given file context.
1230static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
1231 const DeclContext *NS,
1232 UnqualUsingDirectiveSet &UDirs) {
1233
1234 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1235
1236 // Perform direct name lookup into the LookupCtx.
1237 bool Found = LookupDirect(S, R, DC: NS);
1238
1239 // Perform direct name lookup into the namespaces nominated by the
1240 // using directives whose common ancestor is this namespace.
1241 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(DC: NS))
1242 if (LookupDirect(S, R, DC: UUE.getNominatedNamespace()))
1243 Found = true;
1244
1245 R.resolveKind();
1246
1247 return Found;
1248}
1249
1250static bool isNamespaceOrTranslationUnitScope(Scope *S) {
1251 if (DeclContext *Ctx = S->getEntity())
1252 return Ctx->isFileContext();
1253 return false;
1254}
1255
1256/// Find the outer declaration context from this scope. This indicates the
1257/// context that we should search up to (exclusive) before considering the
1258/// parent of the specified scope.
1259static DeclContext *findOuterContext(Scope *S) {
1260 for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
1261 if (DeclContext *DC = OuterS->getLookupEntity())
1262 return DC;
1263 return nullptr;
1264}
1265
1266namespace {
1267/// An RAII object to specify that we want to find block scope extern
1268/// declarations.
1269struct FindLocalExternScope {
1270 FindLocalExternScope(LookupResult &R)
1271 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1272 Decl::IDNS_LocalExtern) {
1273 R.setFindLocalExtern(R.getIdentifierNamespace() &
1274 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
1275 }
1276 void restore() {
1277 R.setFindLocalExtern(OldFindLocalExtern);
1278 }
1279 ~FindLocalExternScope() {
1280 restore();
1281 }
1282 LookupResult &R;
1283 bool OldFindLocalExtern;
1284};
1285} // end anonymous namespace
1286
1287bool Sema::CppLookupName(LookupResult &R, Scope *S) {
1288 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
1289
1290 DeclarationName Name = R.getLookupName();
1291 Sema::LookupNameKind NameKind = R.getLookupKind();
1292
1293 // If this is the name of an implicitly-declared special member function,
1294 // go through the scope stack to implicitly declare
1295 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1296 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1297 if (DeclContext *DC = PreS->getEntity())
1298 DeclareImplicitMemberFunctionsWithName(S&: *this, Name, Loc: R.getNameLoc(), DC);
1299 }
1300
1301 // C++23 [temp.dep.general]p2:
1302 // The component name of an unqualified-id is dependent if
1303 // - it is a conversion-function-id whose conversion-type-id
1304 // is dependent, or
1305 // - it is operator= and the current class is a templated entity, or
1306 // - the unqualified-id is the postfix-expression in a dependent call.
1307 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1308 Name.getCXXNameType()->isDependentType()) {
1309 R.setNotFoundInCurrentInstantiation();
1310 return false;
1311 }
1312
1313 // Implicitly declare member functions with the name we're looking for, if in
1314 // fact we are in a scope where it matters.
1315
1316 Scope *Initial = S;
1317 IdentifierResolver::iterator
1318 I = IdResolver.begin(Name),
1319 IEnd = IdResolver.end();
1320
1321 // First we lookup local scope.
1322 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1323 // ...During unqualified name lookup (3.4.1), the names appear as if
1324 // they were declared in the nearest enclosing namespace which contains
1325 // both the using-directive and the nominated namespace.
1326 // [Note: in this context, "contains" means "contains directly or
1327 // indirectly".
1328 //
1329 // For example:
1330 // namespace A { int i; }
1331 // void foo() {
1332 // int i;
1333 // {
1334 // using namespace A;
1335 // ++i; // finds local 'i', A::i appears at global scope
1336 // }
1337 // }
1338 //
1339 UnqualUsingDirectiveSet UDirs(*this);
1340 bool VisitedUsingDirectives = false;
1341 bool LeftStartingScope = false;
1342
1343 // When performing a scope lookup, we want to find local extern decls.
1344 FindLocalExternScope FindLocals(R);
1345
1346 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1347 bool SearchNamespaceScope = true;
1348 // Check whether the IdResolver has anything in this scope.
1349 for (; I != IEnd && S->isDeclScope(D: *I); ++I) {
1350 if (NamedDecl *ND = R.getAcceptableDecl(D: *I)) {
1351 if (NameKind == LookupRedeclarationWithLinkage &&
1352 !(*I)->isTemplateParameter()) {
1353 // If it's a template parameter, we still find it, so we can diagnose
1354 // the invalid redeclaration.
1355
1356 // Determine whether this (or a previous) declaration is
1357 // out-of-scope.
1358 if (!LeftStartingScope && !Initial->isDeclScope(D: *I))
1359 LeftStartingScope = true;
1360
1361 // If we found something outside of our starting scope that
1362 // does not have linkage, skip it.
1363 if (LeftStartingScope && !((*I)->hasLinkage())) {
1364 R.setShadowed();
1365 continue;
1366 }
1367 } else {
1368 // We found something in this scope, we should not look at the
1369 // namespace scope
1370 SearchNamespaceScope = false;
1371 }
1372 R.addDecl(D: ND);
1373 }
1374 }
1375 if (!SearchNamespaceScope) {
1376 R.resolveKind();
1377 if (S->isClassScope())
1378 if (auto *Record = dyn_cast_if_present<CXXRecordDecl>(Val: S->getEntity()))
1379 R.setNamingClass(Record);
1380 return true;
1381 }
1382
1383 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1384 // C++11 [class.friend]p11:
1385 // If a friend declaration appears in a local class and the name
1386 // specified is an unqualified name, a prior declaration is
1387 // looked up without considering scopes that are outside the
1388 // innermost enclosing non-class scope.
1389 return false;
1390 }
1391
1392 if (DeclContext *Ctx = S->getLookupEntity()) {
1393 DeclContext *OuterCtx = findOuterContext(S);
1394 for (; Ctx && !Ctx->Equals(DC: OuterCtx); Ctx = Ctx->getLookupParent()) {
1395 // We do not directly look into transparent contexts, since
1396 // those entities will be found in the nearest enclosing
1397 // non-transparent context.
1398 if (Ctx->isTransparentContext())
1399 continue;
1400
1401 // We do not look directly into function or method contexts,
1402 // since all of the local variables and parameters of the
1403 // function/method are present within the Scope.
1404 if (Ctx->isFunctionOrMethod()) {
1405 // If we have an Objective-C instance method, look for ivars
1406 // in the corresponding interface.
1407 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Val: Ctx)) {
1408 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1409 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1410 ObjCInterfaceDecl *ClassDeclared;
1411 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1412 IVarName: Name.getAsIdentifierInfo(),
1413 ClassDeclared)) {
1414 if (NamedDecl *ND = R.getAcceptableDecl(D: Ivar)) {
1415 R.addDecl(D: ND);
1416 R.resolveKind();
1417 return true;
1418 }
1419 }
1420 }
1421 }
1422
1423 continue;
1424 }
1425
1426 // If this is a file context, we need to perform unqualified name
1427 // lookup considering using directives.
1428 if (Ctx->isFileContext()) {
1429 // If we haven't handled using directives yet, do so now.
1430 if (!VisitedUsingDirectives) {
1431 // Add using directives from this context up to the top level.
1432 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1433 if (UCtx->isTransparentContext())
1434 continue;
1435
1436 UDirs.visit(DC: UCtx, EffectiveDC: UCtx);
1437 }
1438
1439 // Find the innermost file scope, so we can add using directives
1440 // from local scopes.
1441 Scope *InnermostFileScope = S;
1442 while (InnermostFileScope &&
1443 !isNamespaceOrTranslationUnitScope(S: InnermostFileScope))
1444 InnermostFileScope = InnermostFileScope->getParent();
1445 UDirs.visitScopeChain(S: Initial, InnermostFileScope);
1446
1447 UDirs.done();
1448
1449 VisitedUsingDirectives = true;
1450 }
1451
1452 if (CppNamespaceLookup(S&: *this, R, Context, NS: Ctx, UDirs)) {
1453 R.resolveKind();
1454 return true;
1455 }
1456
1457 continue;
1458 }
1459
1460 // Perform qualified name lookup into this context.
1461 // FIXME: In some cases, we know that every name that could be found by
1462 // this qualified name lookup will also be on the identifier chain. For
1463 // example, inside a class without any base classes, we never need to
1464 // perform qualified lookup because all of the members are on top of the
1465 // identifier chain.
1466 if (LookupQualifiedName(R, LookupCtx: Ctx, /*InUnqualifiedLookup=*/true))
1467 return true;
1468 }
1469 }
1470 }
1471
1472 // Stop if we ran out of scopes.
1473 // FIXME: This really, really shouldn't be happening.
1474 if (!S) return false;
1475
1476 // If we are looking for members, no need to look into global/namespace scope.
1477 if (NameKind == LookupMemberName)
1478 return false;
1479
1480 // Collect UsingDirectiveDecls in all scopes, and recursively all
1481 // nominated namespaces by those using-directives.
1482 //
1483 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1484 // don't build it for each lookup!
1485 if (!VisitedUsingDirectives) {
1486 UDirs.visitScopeChain(S: Initial, InnermostFileScope: S);
1487 UDirs.done();
1488 }
1489
1490 // If we're not performing redeclaration lookup, do not look for local
1491 // extern declarations outside of a function scope.
1492 if (!R.isForRedeclaration())
1493 FindLocals.restore();
1494
1495 // Lookup namespace scope, and global scope.
1496 // Unqualified name lookup in C++ requires looking into scopes
1497 // that aren't strictly lexical, and therefore we walk through the
1498 // context as well as walking through the scopes.
1499 for (; S; S = S->getParent()) {
1500 // Check whether the IdResolver has anything in this scope.
1501 bool Found = false;
1502 for (; I != IEnd && S->isDeclScope(D: *I); ++I) {
1503 if (NamedDecl *ND = R.getAcceptableDecl(D: *I)) {
1504 // We found something. Look for anything else in our scope
1505 // with this same name and in an acceptable identifier
1506 // namespace, so that we can construct an overload set if we
1507 // need to.
1508 Found = true;
1509 R.addDecl(D: ND);
1510 }
1511 }
1512
1513 if (Found && S->isTemplateParamScope()) {
1514 R.resolveKind();
1515 return true;
1516 }
1517
1518 DeclContext *Ctx = S->getLookupEntity();
1519 if (Ctx) {
1520 DeclContext *OuterCtx = findOuterContext(S);
1521 for (; Ctx && !Ctx->Equals(DC: OuterCtx); Ctx = Ctx->getLookupParent()) {
1522 // We do not directly look into transparent contexts, since
1523 // those entities will be found in the nearest enclosing
1524 // non-transparent context.
1525 if (Ctx->isTransparentContext())
1526 continue;
1527
1528 // If we have a context, and it's not a context stashed in the
1529 // template parameter scope for an out-of-line definition, also
1530 // look into that context.
1531 if (!(Found && S->isTemplateParamScope())) {
1532 assert(Ctx->isFileContext() &&
1533 "We should have been looking only at file context here already.");
1534
1535 // Look into context considering using-directives.
1536 if (CppNamespaceLookup(S&: *this, R, Context, NS: Ctx, UDirs))
1537 Found = true;
1538 }
1539
1540 if (Found) {
1541 R.resolveKind();
1542 return true;
1543 }
1544
1545 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1546 return false;
1547 }
1548 }
1549
1550 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1551 return false;
1552 }
1553
1554 return !R.empty();
1555}
1556
1557void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1558 if (auto *M = getCurrentModule())
1559 Context.mergeDefinitionIntoModule(ND, M);
1560 else
1561 // We're not building a module; just make the definition visible.
1562 ND->setVisibleDespiteOwningModule();
1563
1564 // If ND is a template declaration, make the template parameters
1565 // visible too. They're not (necessarily) within a mergeable DeclContext.
1566 if (auto *TD = dyn_cast<TemplateDecl>(Val: ND))
1567 for (auto *Param : *TD->getTemplateParameters())
1568 makeMergedDefinitionVisible(ND: Param);
1569
1570 // If we import a named module which contains a header, and then we include a
1571 // header which contains a definition of enums, we will skip parsing the enums
1572 // in the current TU. But we need to ensure the visibility of the enum
1573 // contants, since they are able to be found with the parents of their
1574 // parents.
1575 if (auto *ED = dyn_cast<EnumDecl>(Val: ND);
1576 ED && ED->isFromGlobalModule() && !ED->isScoped()) {
1577 for (auto *ECD : ED->enumerators()) {
1578 ECD->setVisiblePromoted();
1579 DeclContext *RedeclCtx = ED->getDeclContext()->getRedeclContext();
1580 if (RedeclCtx->lookup(Name: ECD->getDeclName()).empty())
1581 RedeclCtx->makeDeclVisibleInContext(D: ECD);
1582 }
1583 }
1584}
1585
1586/// Find the module in which the given declaration was defined.
1587static Module *getDefiningModule(Sema &S, Decl *Entity) {
1588 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Entity)) {
1589 // If this function was instantiated from a template, the defining module is
1590 // the module containing the pattern.
1591 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1592 Entity = Pattern->getDefinition();
1593 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Entity)) {
1594 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1595 Entity = Pattern->getDefinition();
1596 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Entity)) {
1597 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1598 Entity = Pattern->getDefinition();
1599 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: Entity)) {
1600 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1601 Entity = Pattern->getDefinition();
1602 }
1603 if (!Entity)
1604 return nullptr;
1605
1606 // Walk up to the containing context. That might also have been instantiated
1607 // from a template.
1608 DeclContext *Context = Entity->getLexicalDeclContext();
1609 if (Context->isFileContext())
1610 return S.getOwningModule(Entity);
1611 return getDefiningModule(S, Entity: cast<Decl>(Val: Context));
1612}
1613
1614llvm::DenseSet<Module*> &Sema::getLookupModules() {
1615 unsigned N = CodeSynthesisContexts.size();
1616 for (unsigned I = CodeSynthesisContextLookupModules.size();
1617 I != N; ++I) {
1618 Module *M = CodeSynthesisContexts[I].Entity ?
1619 getDefiningModule(S&: *this, Entity: CodeSynthesisContexts[I].Entity) :
1620 nullptr;
1621 if (M && !LookupModulesCache.insert(V: M).second)
1622 M = nullptr;
1623 CodeSynthesisContextLookupModules.push_back(Elt: M);
1624 }
1625 return LookupModulesCache;
1626}
1627
1628bool Sema::isUsableModule(const Module *M) {
1629 assert(M && "We shouldn't check nullness for module here");
1630 // Return quickly if we cached the result.
1631 if (UsableModuleUnitsCache.count(V: M))
1632 return true;
1633
1634 // If M is the global module fragment of the current translation unit. So it
1635 // should be usable.
1636 // [module.global.frag]p1:
1637 // The global module fragment can be used to provide declarations that are
1638 // attached to the global module and usable within the module unit.
1639 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment) {
1640 UsableModuleUnitsCache.insert(V: M);
1641 return true;
1642 }
1643
1644 // Otherwise, the global module fragment from other translation unit is not
1645 // directly usable.
1646 if (M->isExplicitGlobalModule())
1647 return false;
1648
1649 Module *Current = getCurrentModule();
1650
1651 // If we're not parsing a module, we can't use all the declarations from
1652 // another module easily.
1653 if (!Current)
1654 return false;
1655
1656 // For implicit global module, the decls in the same modules with the parent
1657 // module should be visible to the decls in the implicit global module.
1658 if (Current->isImplicitGlobalModule())
1659 Current = Current->getTopLevelModule();
1660 if (M->isImplicitGlobalModule())
1661 M = M->getTopLevelModule();
1662
1663 // If M is the module we're parsing or M and the current module unit lives in
1664 // the same module, M should be usable.
1665 //
1666 // Note: It should be fine to search the vector `ModuleScopes` linearly since
1667 // it should be generally small enough. There should be rare module fragments
1668 // in a named module unit.
1669 if (llvm::count_if(Range&: ModuleScopes,
1670 P: [&M](const ModuleScope &MS) { return MS.Module == M; }) ||
1671 getASTContext().isInSameModule(M1: M, M2: Current)) {
1672 UsableModuleUnitsCache.insert(V: M);
1673 return true;
1674 }
1675
1676 return false;
1677}
1678
1679bool Sema::hasVisibleMergedDefinition(const NamedDecl *Def) {
1680 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1681 if (isModuleVisible(M: Merged))
1682 return true;
1683 return false;
1684}
1685
1686bool Sema::hasMergedDefinitionInCurrentModule(const NamedDecl *Def) {
1687 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1688 if (isUsableModule(M: Merged))
1689 return true;
1690 return false;
1691}
1692
1693template <typename ParmDecl>
1694static bool
1695hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D,
1696 llvm::SmallVectorImpl<Module *> *Modules,
1697 Sema::AcceptableKind Kind) {
1698 if (!D->hasDefaultArgument())
1699 return false;
1700
1701 llvm::SmallPtrSet<const ParmDecl *, 4> Visited;
1702 while (D && Visited.insert(D).second) {
1703 auto &DefaultArg = D->getDefaultArgStorage();
1704 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
1705 return true;
1706
1707 if (!DefaultArg.isInherited() && Modules) {
1708 auto *NonConstD = const_cast<ParmDecl*>(D);
1709 Modules->push_back(Elt: S.getOwningModule(Entity: NonConstD));
1710 }
1711
1712 // If there was a previous default argument, maybe its parameter is
1713 // acceptable.
1714 D = DefaultArg.getInheritedFrom();
1715 }
1716 return false;
1717}
1718
1719bool Sema::hasAcceptableDefaultArgument(
1720 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,
1721 Sema::AcceptableKind Kind) {
1722 if (auto *P = dyn_cast<TemplateTypeParmDecl>(Val: D))
1723 return ::hasAcceptableDefaultArgument(S&: *this, D: P, Modules, Kind);
1724
1725 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1726 return ::hasAcceptableDefaultArgument(S&: *this, D: P, Modules, Kind);
1727
1728 return ::hasAcceptableDefaultArgument(
1729 S&: *this, D: cast<TemplateTemplateParmDecl>(Val: D), Modules, Kind);
1730}
1731
1732bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1733 llvm::SmallVectorImpl<Module *> *Modules) {
1734 return hasAcceptableDefaultArgument(D, Modules,
1735 Kind: Sema::AcceptableKind::Visible);
1736}
1737
1738bool Sema::hasReachableDefaultArgument(
1739 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1740 return hasAcceptableDefaultArgument(D, Modules,
1741 Kind: Sema::AcceptableKind::Reachable);
1742}
1743
1744template <typename Filter>
1745static bool
1746hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,
1747 llvm::SmallVectorImpl<Module *> *Modules, Filter F,
1748 Sema::AcceptableKind Kind) {
1749 bool HasFilteredRedecls = false;
1750
1751 for (auto *Redecl : D->redecls()) {
1752 auto *R = cast<NamedDecl>(Val: Redecl);
1753 if (!F(R))
1754 continue;
1755
1756 if (S.isAcceptable(D: R, Kind))
1757 return true;
1758
1759 HasFilteredRedecls = true;
1760
1761 if (Modules)
1762 Modules->push_back(Elt: R->getOwningModule());
1763 }
1764
1765 // Only return false if there is at least one redecl that is not filtered out.
1766 if (HasFilteredRedecls)
1767 return false;
1768
1769 return true;
1770}
1771
1772static bool
1773hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,
1774 llvm::SmallVectorImpl<Module *> *Modules,
1775 Sema::AcceptableKind Kind) {
1776 return hasAcceptableDeclarationImpl(
1777 S, D, Modules,
1778 F: [](const NamedDecl *D) {
1779 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1780 return RD->getTemplateSpecializationKind() ==
1781 TSK_ExplicitSpecialization;
1782 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1783 return FD->getTemplateSpecializationKind() ==
1784 TSK_ExplicitSpecialization;
1785 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1786 return VD->getTemplateSpecializationKind() ==
1787 TSK_ExplicitSpecialization;
1788 llvm_unreachable("unknown explicit specialization kind");
1789 },
1790 Kind);
1791}
1792
1793bool Sema::hasVisibleExplicitSpecialization(
1794 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1795 return ::hasAcceptableExplicitSpecialization(S&: *this, D, Modules,
1796 Kind: Sema::AcceptableKind::Visible);
1797}
1798
1799bool Sema::hasReachableExplicitSpecialization(
1800 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1801 return ::hasAcceptableExplicitSpecialization(S&: *this, D, Modules,
1802 Kind: Sema::AcceptableKind::Reachable);
1803}
1804
1805static bool
1806hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,
1807 llvm::SmallVectorImpl<Module *> *Modules,
1808 Sema::AcceptableKind Kind) {
1809 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1810 "not a member specialization");
1811 return hasAcceptableDeclarationImpl(
1812 S, D, Modules,
1813 F: [](const NamedDecl *D) {
1814 // If the specialization is declared at namespace scope, then it's a
1815 // member specialization declaration. If it's lexically inside the class
1816 // definition then it was instantiated.
1817 //
1818 // FIXME: This is a hack. There should be a better way to determine
1819 // this.
1820 // FIXME: What about MS-style explicit specializations declared within a
1821 // class definition?
1822 return D->getLexicalDeclContext()->isFileContext();
1823 },
1824 Kind);
1825}
1826
1827bool Sema::hasVisibleMemberSpecialization(
1828 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1829 return hasAcceptableMemberSpecialization(S&: *this, D, Modules,
1830 Kind: Sema::AcceptableKind::Visible);
1831}
1832
1833bool Sema::hasReachableMemberSpecialization(
1834 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1835 return hasAcceptableMemberSpecialization(S&: *this, D, Modules,
1836 Kind: Sema::AcceptableKind::Reachable);
1837}
1838
1839/// Determine whether a declaration is acceptable to name lookup.
1840///
1841/// This routine determines whether the declaration D is acceptable in the
1842/// current lookup context, taking into account the current template
1843/// instantiation stack. During template instantiation, a declaration is
1844/// acceptable if it is acceptable from a module containing any entity on the
1845/// template instantiation path (by instantiating a template, you allow it to
1846/// see the declarations that your module can see, including those later on in
1847/// your module).
1848bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
1849 Sema::AcceptableKind Kind) {
1850 assert(!D->isUnconditionallyVisible() &&
1851 "should not call this: not in slow case");
1852
1853 Module *DeclModule = SemaRef.getOwningModule(Entity: D);
1854 assert(DeclModule && "hidden decl has no owning module");
1855
1856 // If the owning module is visible, the decl is acceptable.
1857 if (SemaRef.isModuleVisible(M: DeclModule,
1858 ModulePrivate: D->isInvisibleOutsideTheOwningModule()))
1859 return true;
1860
1861 // Determine whether a decl context is a file context for the purpose of
1862 // visibility/reachability. This looks through some (export and linkage spec)
1863 // transparent contexts, but not others (enums).
1864 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1865 return DC->isFileContext() || isa<LinkageSpecDecl>(Val: DC) ||
1866 isa<ExportDecl>(Val: DC);
1867 };
1868
1869 // If this declaration is not at namespace scope
1870 // then it is acceptable if its lexical parent has a acceptable definition.
1871 DeclContext *DC = D->getLexicalDeclContext();
1872 if (DC && !IsEffectivelyFileContext(DC)) {
1873 // For a parameter, check whether our current template declaration's
1874 // lexical context is acceptable, not whether there's some other acceptable
1875 // definition of it, because parameters aren't "within" the definition.
1876 //
1877 // In C++ we need to check for a acceptable definition due to ODR merging,
1878 // and in C we must not because each declaration of a function gets its own
1879 // set of declarations for tags in prototype scope.
1880 bool AcceptableWithinParent;
1881 if (D->isTemplateParameter()) {
1882 bool SearchDefinitions = true;
1883 if (const auto *DCD = dyn_cast<Decl>(Val: DC)) {
1884 if (const auto *TD = DCD->getDescribedTemplate()) {
1885 TemplateParameterList *TPL = TD->getTemplateParameters();
1886 auto Index = getDepthAndIndex(ND: D).second;
1887 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Idx: Index) != D;
1888 }
1889 }
1890 if (SearchDefinitions)
1891 AcceptableWithinParent =
1892 SemaRef.hasAcceptableDefinition(D: cast<NamedDecl>(Val: DC), Kind);
1893 else
1894 AcceptableWithinParent =
1895 isAcceptable(SemaRef, D: cast<NamedDecl>(Val: DC), Kind);
1896 } else if (isa<ParmVarDecl>(Val: D) ||
1897 (isa<FunctionDecl>(Val: DC) && !SemaRef.getLangOpts().CPlusPlus))
1898 AcceptableWithinParent = isAcceptable(SemaRef, D: cast<NamedDecl>(Val: DC), Kind);
1899 else if (D->isModulePrivate()) {
1900 // A module-private declaration is only acceptable if an enclosing lexical
1901 // parent was merged with another definition in the current module.
1902 AcceptableWithinParent = false;
1903 do {
1904 if (SemaRef.hasMergedDefinitionInCurrentModule(Def: cast<NamedDecl>(Val: DC))) {
1905 AcceptableWithinParent = true;
1906 break;
1907 }
1908 DC = DC->getLexicalParent();
1909 } while (!IsEffectivelyFileContext(DC));
1910 } else {
1911 AcceptableWithinParent =
1912 SemaRef.hasAcceptableDefinition(D: cast<NamedDecl>(Val: DC), Kind);
1913 }
1914
1915 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1916 Kind == Sema::AcceptableKind::Visible &&
1917 // FIXME: Do something better in this case.
1918 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1919 // Cache the fact that this declaration is implicitly visible because
1920 // its parent has a visible definition.
1921 D->setVisibleDespiteOwningModule();
1922 }
1923 return AcceptableWithinParent;
1924 }
1925
1926 if (Kind == Sema::AcceptableKind::Visible)
1927 return false;
1928
1929 assert(Kind == Sema::AcceptableKind::Reachable &&
1930 "Additional Sema::AcceptableKind?");
1931 return isReachableSlow(SemaRef, D);
1932}
1933
1934bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1935 // The module might be ordinarily visible. For a module-private query, that
1936 // means it is part of the current module.
1937 if (ModulePrivate && isUsableModule(M))
1938 return true;
1939
1940 // For a query which is not module-private, that means it is in our visible
1941 // module set.
1942 if (!ModulePrivate && VisibleModules.isVisible(M))
1943 return true;
1944
1945 // Otherwise, it might be visible by virtue of the query being within a
1946 // template instantiation or similar that is permitted to look inside M.
1947
1948 // Find the extra places where we need to look.
1949 const auto &LookupModules = getLookupModules();
1950 if (LookupModules.empty())
1951 return false;
1952
1953 // If our lookup set contains the module, it's visible.
1954 if (LookupModules.count(V: M))
1955 return true;
1956
1957 // The global module fragments are visible to its corresponding module unit.
1958 // So the global module fragment should be visible if the its corresponding
1959 // module unit is visible.
1960 if (M->isGlobalModule() && LookupModules.count(V: M->getTopLevelModule()))
1961 return true;
1962
1963 // For a module-private query, that's everywhere we get to look.
1964 if (ModulePrivate)
1965 return false;
1966
1967 // Check whether M is transitively exported to an import of the lookup set.
1968 return llvm::any_of(Range: LookupModules, P: [&](const Module *LookupM) {
1969 return LookupM->isModuleVisible(M);
1970 });
1971}
1972
1973// FIXME: Return false directly if we don't have an interface dependency on the
1974// translation unit containing D.
1975bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
1976 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
1977
1978 Module *DeclModule = SemaRef.getOwningModule(Entity: D);
1979 assert(DeclModule && "hidden decl has no owning module");
1980
1981 // Entities in header like modules are reachable only if they're visible.
1982 if (DeclModule->isHeaderLikeModule())
1983 return false;
1984
1985 if (!D->isInAnotherModuleUnit())
1986 return true;
1987
1988 // [module.reach]/p3:
1989 // A declaration D is reachable from a point P if:
1990 // ...
1991 // - D is not discarded ([module.global.frag]), appears in a translation unit
1992 // that is reachable from P, and does not appear within a private module
1993 // fragment.
1994 //
1995 // A declaration that's discarded in the GMF should be module-private.
1996 if (D->isModulePrivate())
1997 return false;
1998
1999 Module *DeclTopModule = DeclModule->getTopLevelModule();
2000
2001 // [module.reach]/p1
2002 // A translation unit U is necessarily reachable from a point P if U is a
2003 // module interface unit on which the translation unit containing P has an
2004 // interface dependency, or the translation unit containing P imports U, in
2005 // either case prior to P ([module.import]).
2006 //
2007 // [module.import]/p10
2008 // A translation unit has an interface dependency on a translation unit U if
2009 // it contains a declaration (possibly a module-declaration) that imports U
2010 // or if it has an interface dependency on a translation unit that has an
2011 // interface dependency on U.
2012 //
2013 // So we could conclude the module unit U is necessarily reachable if:
2014 // (1) The module unit U is module interface unit.
2015 // (2) The current unit has an interface dependency on the module unit U.
2016 //
2017 // Here we only check for the first condition. Since we couldn't see
2018 // DeclModule if it isn't (transitively) imported.
2019 if (DeclTopModule->isModuleInterfaceUnit())
2020 return true;
2021
2022 // [module.reach]/p1,2
2023 // A translation unit U is necessarily reachable from a point P if U is a
2024 // module interface unit on which the translation unit containing P has an
2025 // interface dependency, or the translation unit containing P imports U, in
2026 // either case prior to P
2027 //
2028 // Additional translation units on
2029 // which the point within the program has an interface dependency may be
2030 // considered reachable, but it is unspecified which are and under what
2031 // circumstances.
2032 Module *CurrentM = SemaRef.getCurrentModule();
2033
2034 // Directly imported module are necessarily reachable.
2035 // Since we can't export import a module implementation partition unit, we
2036 // don't need to count for Exports here.
2037 if (CurrentM &&
2038 llvm::is_contained(Range&: CurrentM->getTopLevelModule()->Imports, Element: DeclTopModule))
2039 return true;
2040
2041 // Then we treat all module implementation partition unit as unreachable.
2042 return false;
2043}
2044
2045bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
2046 return LookupResult::isAcceptable(SemaRef&: *this, D: const_cast<NamedDecl *>(D), Kind);
2047}
2048
2049bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
2050 // FIXME: If there are both visible and hidden declarations, we need to take
2051 // into account whether redeclaration is possible. Example:
2052 //
2053 // Non-imported module:
2054 // int f(T); // #1
2055 // Some TU:
2056 // static int f(U); // #2, not a redeclaration of #1
2057 // int f(T); // #3, finds both, should link with #1 if T != U, but
2058 // // with #2 if T == U; neither should be ambiguous.
2059 for (auto *D : R) {
2060 if (isVisible(D))
2061 return true;
2062 assert(D->isExternallyDeclarable() &&
2063 "should not have hidden, non-externally-declarable result here");
2064 }
2065
2066 // This function is called once "New" is essentially complete, but before a
2067 // previous declaration is attached. We can't query the linkage of "New" in
2068 // general, because attaching the previous declaration can change the
2069 // linkage of New to match the previous declaration.
2070 //
2071 // However, because we've just determined that there is no *visible* prior
2072 // declaration, we can compute the linkage here. There are two possibilities:
2073 //
2074 // * This is not a redeclaration; it's safe to compute the linkage now.
2075 //
2076 // * This is a redeclaration of a prior declaration that is externally
2077 // redeclarable. In that case, the linkage of the declaration is not
2078 // changed by attaching the prior declaration, because both are externally
2079 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
2080 //
2081 // FIXME: This is subtle and fragile.
2082 return New->isExternallyDeclarable();
2083}
2084
2085/// Retrieve the visible declaration corresponding to D, if any.
2086///
2087/// This routine determines whether the declaration D is visible in the current
2088/// module, with the current imports. If not, it checks whether any
2089/// redeclaration of D is visible, and if so, returns that declaration.
2090///
2091/// \returns D, or a visible previous declaration of D, whichever is more recent
2092/// and visible. If no declaration of D is visible, returns null.
2093static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
2094 unsigned IDNS) {
2095 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
2096
2097 for (auto *RD : D->redecls()) {
2098 // Don't bother with extra checks if we already know this one isn't visible.
2099 if (RD == D)
2100 continue;
2101
2102 auto ND = cast<NamedDecl>(Val: RD);
2103 // FIXME: This is wrong in the case where the previous declaration is not
2104 // visible in the same scope as D. This needs to be done much more
2105 // carefully.
2106 if (ND->isInIdentifierNamespace(NS: IDNS) &&
2107 LookupResult::isAvailableForLookup(SemaRef, ND))
2108 return ND;
2109 }
2110
2111 return nullptr;
2112}
2113
2114bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
2115 llvm::SmallVectorImpl<Module *> *Modules) {
2116 assert(!isVisible(D) && "not in slow case");
2117 return hasAcceptableDeclarationImpl(
2118 S&: *this, D, Modules, F: [](const NamedDecl *) { return true; },
2119 Kind: Sema::AcceptableKind::Visible);
2120}
2121
2122bool Sema::hasReachableDeclarationSlow(
2123 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
2124 assert(!isReachable(D) && "not in slow case");
2125 return hasAcceptableDeclarationImpl(
2126 S&: *this, D, Modules, F: [](const NamedDecl *) { return true; },
2127 Kind: Sema::AcceptableKind::Reachable);
2128}
2129
2130NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
2131 if (auto *ND = dyn_cast<NamespaceDecl>(Val: D)) {
2132 // Namespaces are a bit of a special case: we expect there to be a lot of
2133 // redeclarations of some namespaces, all declarations of a namespace are
2134 // essentially interchangeable, all declarations are found by name lookup
2135 // if any is, and namespaces are never looked up during template
2136 // instantiation. So we benefit from caching the check in this case, and
2137 // it is correct to do so.
2138 auto *Key = ND->getCanonicalDecl();
2139 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Val: Key))
2140 return Acceptable;
2141 auto *Acceptable = isVisible(SemaRef&: getSema(), D: Key)
2142 ? Key
2143 : findAcceptableDecl(SemaRef&: getSema(), D: Key, IDNS);
2144 if (Acceptable)
2145 getSema().VisibleNamespaceCache.insert(KV: std::make_pair(x&: Key, y&: Acceptable));
2146 return Acceptable;
2147 }
2148
2149 return findAcceptableDecl(SemaRef&: getSema(), D, IDNS);
2150}
2151
2152bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) {
2153 // If this declaration is already visible, return it directly.
2154 if (D->isUnconditionallyVisible())
2155 return true;
2156
2157 // During template instantiation, we can refer to hidden declarations, if
2158 // they were visible in any module along the path of instantiation.
2159 return isAcceptableSlow(SemaRef, D, Kind: Sema::AcceptableKind::Visible);
2160}
2161
2162bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) {
2163 if (D->isUnconditionallyVisible())
2164 return true;
2165
2166 return isAcceptableSlow(SemaRef, D, Kind: Sema::AcceptableKind::Reachable);
2167}
2168
2169bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) {
2170 // We should check the visibility at the callsite already.
2171 if (isVisible(SemaRef, D: ND))
2172 return true;
2173
2174 // Deduction guide lives in namespace scope generally, but it is just a
2175 // hint to the compilers. What we actually lookup for is the generated member
2176 // of the corresponding template. So it is sufficient to check the
2177 // reachability of the template decl.
2178 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())
2179 return SemaRef.hasReachableDefinition(D: DeductionGuide);
2180
2181 // FIXME: The lookup for allocation function is a standalone process.
2182 // (We can find the logics in Sema::FindAllocationFunctions)
2183 //
2184 // Such structure makes it a problem when we instantiate a template
2185 // declaration using placement allocation function if the placement
2186 // allocation function is invisible.
2187 // (See https://github.com/llvm/llvm-project/issues/59601)
2188 //
2189 // Here we workaround it by making the placement allocation functions
2190 // always acceptable. The downside is that we can't diagnose the direct
2191 // use of the invisible placement allocation functions. (Although such uses
2192 // should be rare).
2193 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND);
2194 FD && FD->isReservedGlobalPlacementOperator())
2195 return true;
2196
2197 auto *DC = ND->getDeclContext();
2198 // If ND is not visible and it is at namespace scope, it shouldn't be found
2199 // by name lookup.
2200 if (DC->isFileContext())
2201 return false;
2202
2203 // [module.interface]p7
2204 // Class and enumeration member names can be found by name lookup in any
2205 // context in which a definition of the type is reachable.
2206 //
2207 // NOTE: The above wording may be problematic. See
2208 // https://github.com/llvm/llvm-project/issues/131058 But it is much complext
2209 // to adjust it in Sema's lookup process. Now we hacked it in ASTWriter. See
2210 // the comments in ASTDeclContextNameLookupTrait::getLookupVisibility.
2211 if (auto *TD = dyn_cast<TagDecl>(Val: DC))
2212 return SemaRef.hasReachableDefinition(D: TD);
2213
2214 return false;
2215}
2216
2217bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
2218 bool ForceNoCPlusPlus) {
2219 DeclarationName Name = R.getLookupName();
2220 if (!Name) return false;
2221
2222 LookupNameKind NameKind = R.getLookupKind();
2223
2224 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
2225 // Unqualified name lookup in C/Objective-C is purely lexical, so
2226 // search in the declarations attached to the name.
2227 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
2228 // Find the nearest non-transparent declaration scope.
2229 while (!(S->getFlags() & Scope::DeclScope) ||
2230 (S->getEntity() && S->getEntity()->isTransparentContext()))
2231 S = S->getParent();
2232 }
2233
2234 // When performing a scope lookup, we want to find local extern decls.
2235 FindLocalExternScope FindLocals(R);
2236
2237 // Scan up the scope chain looking for a decl that matches this
2238 // identifier that is in the appropriate namespace. This search
2239 // should not take long, as shadowing of names is uncommon, and
2240 // deep shadowing is extremely uncommon.
2241 bool LeftStartingScope = false;
2242
2243 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2244 IEnd = IdResolver.end();
2245 I != IEnd; ++I)
2246 if (NamedDecl *D = R.getAcceptableDecl(D: *I)) {
2247 if (NameKind == LookupRedeclarationWithLinkage) {
2248 // Determine whether this (or a previous) declaration is
2249 // out-of-scope.
2250 if (!LeftStartingScope && !S->isDeclScope(D: *I))
2251 LeftStartingScope = true;
2252
2253 // If we found something outside of our starting scope that
2254 // does not have linkage, skip it.
2255 if (LeftStartingScope && !((*I)->hasLinkage())) {
2256 R.setShadowed();
2257 continue;
2258 }
2259 }
2260 else if (NameKind == LookupObjCImplicitSelfParam &&
2261 !isa<ImplicitParamDecl>(Val: *I))
2262 continue;
2263
2264 R.addDecl(D);
2265
2266 // Check whether there are any other declarations with the same name
2267 // and in the same scope.
2268 if (I != IEnd) {
2269 // Find the scope in which this declaration was declared (if it
2270 // actually exists in a Scope).
2271 while (S && !S->isDeclScope(D))
2272 S = S->getParent();
2273
2274 // If the scope containing the declaration is the translation unit,
2275 // then we'll need to perform our checks based on the matching
2276 // DeclContexts rather than matching scopes.
2277 if (S && isNamespaceOrTranslationUnitScope(S))
2278 S = nullptr;
2279
2280 // Compute the DeclContext, if we need it.
2281 DeclContext *DC = nullptr;
2282 if (!S)
2283 DC = (*I)->getDeclContext()->getRedeclContext();
2284
2285 IdentifierResolver::iterator LastI = I;
2286 for (++LastI; LastI != IEnd; ++LastI) {
2287 if (S) {
2288 // Match based on scope.
2289 if (!S->isDeclScope(D: *LastI))
2290 break;
2291 } else {
2292 // Match based on DeclContext.
2293 DeclContext *LastDC
2294 = (*LastI)->getDeclContext()->getRedeclContext();
2295 if (!LastDC->Equals(DC))
2296 break;
2297 }
2298
2299 // If the declaration is in the right namespace and visible, add it.
2300 if (NamedDecl *LastD = R.getAcceptableDecl(D: *LastI))
2301 R.addDecl(D: LastD);
2302 }
2303
2304 R.resolveKind();
2305 }
2306
2307 return true;
2308 }
2309 } else {
2310 // Perform C++ unqualified name lookup.
2311 if (CppLookupName(R, S))
2312 return true;
2313 }
2314
2315 // If we didn't find a use of this identifier, and if the identifier
2316 // corresponds to a compiler builtin, create the decl object for the builtin
2317 // now, injecting it into translation unit scope, and return it.
2318 if (AllowBuiltinCreation && LookupBuiltin(R))
2319 return true;
2320
2321 // If we didn't find a use of this identifier, the ExternalSource
2322 // may be able to handle the situation.
2323 // Note: some lookup failures are expected!
2324 // See e.g. R.isForRedeclaration().
2325 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2326}
2327
2328/// Perform qualified name lookup in the namespaces nominated by
2329/// using directives by the given context.
2330///
2331/// C++98 [namespace.qual]p2:
2332/// Given X::m (where X is a user-declared namespace), or given \::m
2333/// (where X is the global namespace), let S be the set of all
2334/// declarations of m in X and in the transitive closure of all
2335/// namespaces nominated by using-directives in X and its used
2336/// namespaces, except that using-directives are ignored in any
2337/// namespace, including X, directly containing one or more
2338/// declarations of m. No namespace is searched more than once in
2339/// the lookup of a name. If S is the empty set, the program is
2340/// ill-formed. Otherwise, if S has exactly one member, or if the
2341/// context of the reference is a using-declaration
2342/// (namespace.udecl), S is the required set of declarations of
2343/// m. Otherwise if the use of m is not one that allows a unique
2344/// declaration to be chosen from S, the program is ill-formed.
2345///
2346/// C++98 [namespace.qual]p5:
2347/// During the lookup of a qualified namespace member name, if the
2348/// lookup finds more than one declaration of the member, and if one
2349/// declaration introduces a class name or enumeration name and the
2350/// other declarations either introduce the same object, the same
2351/// enumerator or a set of functions, the non-type name hides the
2352/// class or enumeration name if and only if the declarations are
2353/// from the same namespace; otherwise (the declarations are from
2354/// different namespaces), the program is ill-formed.
2355static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
2356 DeclContext *StartDC) {
2357 assert(StartDC->isFileContext() && "start context is not a file context");
2358
2359 // We have not yet looked into these namespaces, much less added
2360 // their "using-children" to the queue.
2361 SmallVector<NamespaceDecl*, 8> Queue;
2362
2363 // We have at least added all these contexts to the queue.
2364 llvm::SmallPtrSet<DeclContext*, 8> Visited;
2365 Visited.insert(Ptr: StartDC);
2366
2367 // We have already looked into the initial namespace; seed the queue
2368 // with its using-children.
2369 for (auto *I : StartDC->using_directives()) {
2370 NamespaceDecl *ND = I->getNominatedNamespace()->getFirstDecl();
2371 if (S.isVisible(D: I) && Visited.insert(Ptr: ND).second)
2372 Queue.push_back(Elt: ND);
2373 }
2374
2375 // The easiest way to implement the restriction in [namespace.qual]p5
2376 // is to check whether any of the individual results found a tag
2377 // and, if so, to declare an ambiguity if the final result is not
2378 // a tag.
2379 bool FoundTag = false;
2380 bool FoundNonTag = false;
2381
2382 LookupResult LocalR(LookupResult::Temporary, R);
2383
2384 bool Found = false;
2385 while (!Queue.empty()) {
2386 NamespaceDecl *ND = Queue.pop_back_val();
2387
2388 // We go through some convolutions here to avoid copying results
2389 // between LookupResults.
2390 bool UseLocal = !R.empty();
2391 LookupResult &DirectR = UseLocal ? LocalR : R;
2392 bool FoundDirect = LookupDirect(S, R&: DirectR, DC: ND);
2393
2394 if (FoundDirect) {
2395 // First do any local hiding.
2396 DirectR.resolveKind();
2397
2398 // If the local result is a tag, remember that.
2399 if (DirectR.isSingleTagDecl())
2400 FoundTag = true;
2401 else
2402 FoundNonTag = true;
2403
2404 // Append the local results to the total results if necessary.
2405 if (UseLocal) {
2406 R.addAllDecls(Other: LocalR);
2407 LocalR.clear();
2408 }
2409 }
2410
2411 // If we find names in this namespace, ignore its using directives.
2412 if (FoundDirect) {
2413 Found = true;
2414 continue;
2415 }
2416
2417 for (auto *I : ND->using_directives()) {
2418 NamespaceDecl *Nom = I->getNominatedNamespace();
2419 if (S.isVisible(D: I) && Visited.insert(Ptr: Nom).second)
2420 Queue.push_back(Elt: Nom);
2421 }
2422 }
2423
2424 if (Found) {
2425 if (FoundTag && FoundNonTag)
2426 R.setAmbiguousQualifiedTagHiding();
2427 else
2428 R.resolveKind();
2429 }
2430
2431 return Found;
2432}
2433
2434bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2435 bool InUnqualifiedLookup) {
2436 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2437
2438 if (!R.getLookupName())
2439 return false;
2440
2441#ifndef NDEBUG
2442 // Make sure that the declaration context is complete.
2443 if (const auto *TD = dyn_cast<TagDecl>(LookupCtx);
2444 TD && !TD->isDependentType() && TD->getDefinition() == nullptr)
2445 llvm_unreachable("Declaration context must already be complete!");
2446#endif
2447
2448 // Inform the external source that we're looking for a qualified name.
2449 struct QualifiedLookupInScope {
2450 ExternalSemaSource *Source;
2451 const DeclContext *Context;
2452 QualifiedLookupInScope(ExternalSemaSource *Source, const DeclContext *Ctx)
2453 : Source(Source), Context(Ctx) {
2454 if (Source)
2455 Source->StartedQualifiedLookup(DC: Context);
2456 }
2457 ~QualifiedLookupInScope() {
2458 if (Source)
2459 Source->FinishedQualifiedLookup(DC: Context);
2460 }
2461 } QL(ExternalSource.get(), LookupCtx);
2462
2463 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(Val: LookupCtx);
2464 // FIXME: Per [temp.dep.general]p2, an unqualified name is also dependent
2465 // if it's a dependent conversion-function-id or operator= where the current
2466 // class is a templated entity. This should be handled in LookupName.
2467 if (!InUnqualifiedLookup && !R.isForRedeclaration()) {
2468 // C++23 [temp.dep.type]p5:
2469 // A qualified name is dependent if
2470 // - it is a conversion-function-id whose conversion-type-id
2471 // is dependent, or
2472 // - [...]
2473 // - its lookup context is the current instantiation and it
2474 // is operator=, or
2475 // - [...]
2476 if (DeclarationName Name = R.getLookupName();
2477 Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2478 Name.getCXXNameType()->isDependentType()) {
2479 R.setNotFoundInCurrentInstantiation();
2480 return false;
2481 }
2482 }
2483
2484 if (LookupDirect(S&: *this, R, DC: LookupCtx)) {
2485 R.resolveKind();
2486 if (LookupRec)
2487 R.setNamingClass(LookupRec);
2488 return true;
2489 }
2490
2491 // Don't descend into implied contexts for redeclarations.
2492 // C++98 [namespace.qual]p6:
2493 // In a declaration for a namespace member in which the
2494 // declarator-id is a qualified-id, given that the qualified-id
2495 // for the namespace member has the form
2496 // nested-name-specifier unqualified-id
2497 // the unqualified-id shall name a member of the namespace
2498 // designated by the nested-name-specifier.
2499 // See also [class.mfct]p5 and [class.static.data]p2.
2500 if (R.isForRedeclaration())
2501 return false;
2502
2503 // If this is a namespace, look it up in the implied namespaces.
2504 if (LookupCtx->isFileContext())
2505 return LookupQualifiedNameInUsingDirectives(S&: *this, R, StartDC: LookupCtx);
2506
2507 // If this isn't a C++ class, we aren't allowed to look into base
2508 // classes, we're done.
2509 if (!LookupRec || !LookupRec->getDefinition())
2510 return false;
2511
2512 // We're done for lookups that can never succeed for C++ classes.
2513 if (R.getLookupKind() == LookupOperatorName ||
2514 R.getLookupKind() == LookupNamespaceName ||
2515 R.getLookupKind() == LookupObjCProtocolName ||
2516 R.getLookupKind() == LookupLabel)
2517 return false;
2518
2519 // If we're performing qualified name lookup into a dependent class,
2520 // then we are actually looking into a current instantiation. If we have any
2521 // dependent base classes, then we either have to delay lookup until
2522 // template instantiation time (at which point all bases will be available)
2523 // or we have to fail.
2524 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2525 LookupRec->hasAnyDependentBases()) {
2526 R.setNotFoundInCurrentInstantiation();
2527 return false;
2528 }
2529
2530 // Perform lookup into our base classes.
2531
2532 DeclarationName Name = R.getLookupName();
2533 unsigned IDNS = R.getIdentifierNamespace();
2534
2535 // Look for this member in our base classes.
2536 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2537 CXXBasePath &Path) -> bool {
2538 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2539 // Drop leading non-matching lookup results from the declaration list so
2540 // we don't need to consider them again below.
2541 for (Path.Decls = BaseRecord->lookup(Name).begin();
2542 Path.Decls != Path.Decls.end(); ++Path.Decls) {
2543 if ((*Path.Decls)->isInIdentifierNamespace(NS: IDNS))
2544 return true;
2545 }
2546 return false;
2547 };
2548
2549 CXXBasePaths Paths;
2550 Paths.setOrigin(LookupRec);
2551 if (!LookupRec->lookupInBases(BaseMatches: BaseCallback, Paths))
2552 return false;
2553
2554 R.setNamingClass(LookupRec);
2555
2556 // C++ [class.member.lookup]p2:
2557 // [...] If the resulting set of declarations are not all from
2558 // sub-objects of the same type, or the set has a nonstatic member
2559 // and includes members from distinct sub-objects, there is an
2560 // ambiguity and the program is ill-formed. Otherwise that set is
2561 // the result of the lookup.
2562 QualType SubobjectType;
2563 int SubobjectNumber = 0;
2564 AccessSpecifier SubobjectAccess = AS_none;
2565
2566 // Check whether the given lookup result contains only static members.
2567 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2568 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2569 if ((*I)->isInIdentifierNamespace(NS: IDNS) && (*I)->isCXXInstanceMember())
2570 return false;
2571 return true;
2572 };
2573
2574 bool TemplateNameLookup = R.isTemplateNameLookup();
2575
2576 // Determine whether two sets of members contain the same members, as
2577 // required by C++ [class.member.lookup]p6.
2578 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2579 DeclContext::lookup_iterator B) {
2580 using Iterator = DeclContextLookupResult::iterator;
2581 using Result = const void *;
2582
2583 auto Next = [&](Iterator &It, Iterator End) -> Result {
2584 while (It != End) {
2585 NamedDecl *ND = *It++;
2586 if (!ND->isInIdentifierNamespace(NS: IDNS))
2587 continue;
2588
2589 // C++ [temp.local]p3:
2590 // A lookup that finds an injected-class-name (10.2) can result in
2591 // an ambiguity in certain cases (for example, if it is found in
2592 // more than one base class). If all of the injected-class-names
2593 // that are found refer to specializations of the same class
2594 // template, and if the name is used as a template-name, the
2595 // reference refers to the class template itself and not a
2596 // specialization thereof, and is not ambiguous.
2597 if (TemplateNameLookup)
2598 if (auto *TD = getAsTemplateNameDecl(D: ND))
2599 ND = TD;
2600
2601 // C++ [class.member.lookup]p3:
2602 // type declarations (including injected-class-names) are replaced by
2603 // the types they designate
2604 if (const TypeDecl *TD = dyn_cast<TypeDecl>(Val: ND->getUnderlyingDecl()))
2605 return Context.getCanonicalTypeDeclType(TD).getAsOpaquePtr();
2606
2607 return ND->getUnderlyingDecl()->getCanonicalDecl();
2608 }
2609 return nullptr;
2610 };
2611
2612 // We'll often find the declarations are in the same order. Handle this
2613 // case (and the special case of only one declaration) efficiently.
2614 Iterator AIt = A, BIt = B, AEnd, BEnd;
2615 while (true) {
2616 Result AResult = Next(AIt, AEnd);
2617 Result BResult = Next(BIt, BEnd);
2618 if (!AResult && !BResult)
2619 return true;
2620 if (!AResult || !BResult)
2621 return false;
2622 if (AResult != BResult) {
2623 // Found a mismatch; carefully check both lists, accounting for the
2624 // possibility of declarations appearing more than once.
2625 llvm::SmallDenseMap<Result, bool, 32> AResults;
2626 for (; AResult; AResult = Next(AIt, AEnd))
2627 AResults.insert(KV: {AResult, /*FoundInB*/false});
2628 unsigned Found = 0;
2629 for (; BResult; BResult = Next(BIt, BEnd)) {
2630 auto It = AResults.find(Val: BResult);
2631 if (It == AResults.end())
2632 return false;
2633 if (!It->second) {
2634 It->second = true;
2635 ++Found;
2636 }
2637 }
2638 return AResults.size() == Found;
2639 }
2640 }
2641 };
2642
2643 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2644 Path != PathEnd; ++Path) {
2645 const CXXBasePathElement &PathElement = Path->back();
2646
2647 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2648 // across all paths.
2649 SubobjectAccess = std::min(a: SubobjectAccess, b: Path->Access);
2650
2651 // Determine whether we're looking at a distinct sub-object or not.
2652 if (SubobjectType.isNull()) {
2653 // This is the first subobject we've looked at. Record its type.
2654 SubobjectType = Context.getCanonicalType(T: PathElement.Base->getType());
2655 SubobjectNumber = PathElement.SubobjectNumber;
2656 continue;
2657 }
2658
2659 if (SubobjectType !=
2660 Context.getCanonicalType(T: PathElement.Base->getType())) {
2661 // We found members of the given name in two subobjects of
2662 // different types. If the declaration sets aren't the same, this
2663 // lookup is ambiguous.
2664 //
2665 // FIXME: The language rule says that this applies irrespective of
2666 // whether the sets contain only static members.
2667 if (HasOnlyStaticMembers(Path->Decls) &&
2668 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2669 continue;
2670
2671 R.setAmbiguousBaseSubobjectTypes(Paths);
2672 return true;
2673 }
2674
2675 // FIXME: This language rule no longer exists. Checking for ambiguous base
2676 // subobjects should be done as part of formation of a class member access
2677 // expression (when converting the object parameter to the member's type).
2678 if (SubobjectNumber != PathElement.SubobjectNumber) {
2679 // We have a different subobject of the same type.
2680
2681 // C++ [class.member.lookup]p5:
2682 // A static member, a nested type or an enumerator defined in
2683 // a base class T can unambiguously be found even if an object
2684 // has more than one base class subobject of type T.
2685 if (HasOnlyStaticMembers(Path->Decls))
2686 continue;
2687
2688 // We have found a nonstatic member name in multiple, distinct
2689 // subobjects. Name lookup is ambiguous.
2690 R.setAmbiguousBaseSubobjects(Paths);
2691 return true;
2692 }
2693 }
2694
2695 // Lookup in a base class succeeded; return these results.
2696
2697 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2698 I != E; ++I) {
2699 AccessSpecifier AS = CXXRecordDecl::MergeAccess(PathAccess: SubobjectAccess,
2700 DeclAccess: (*I)->getAccess());
2701 if (NamedDecl *ND = R.getAcceptableDecl(D: *I))
2702 R.addDecl(D: ND, AS);
2703 }
2704 R.resolveKind();
2705 return true;
2706}
2707
2708bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2709 CXXScopeSpec &SS) {
2710 NestedNameSpecifier Qualifier = SS.getScopeRep();
2711 if (Qualifier.getKind() == NestedNameSpecifier::Kind::MicrosoftSuper)
2712 return LookupInSuper(R, Class: Qualifier.getAsMicrosoftSuper());
2713 return LookupQualifiedName(R, LookupCtx);
2714}
2715
2716bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2717 QualType ObjectType, bool AllowBuiltinCreation,
2718 bool EnteringContext) {
2719 // When the scope specifier is invalid, don't even look for anything.
2720 if (SS && SS->isInvalid())
2721 return false;
2722
2723 // Determine where to perform name lookup
2724 DeclContext *DC = nullptr;
2725 bool IsDependent = false;
2726 if (!ObjectType.isNull()) {
2727 // This nested-name-specifier occurs in a member access expression, e.g.,
2728 // x->B::f, and we are looking into the type of the object.
2729 assert((!SS || SS->isEmpty()) &&
2730 "ObjectType and scope specifier cannot coexist");
2731 DC = computeDeclContext(T: ObjectType);
2732 IsDependent = !DC && ObjectType->isDependentType();
2733 assert(((!DC && ObjectType->isDependentType()) ||
2734 !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() ||
2735 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
2736 "Caller should have completed object type");
2737 } else if (SS && SS->isNotEmpty()) {
2738 // This nested-name-specifier occurs after another nested-name-specifier,
2739 // so long into the context associated with the prior nested-name-specifier.
2740 if ((DC = computeDeclContext(SS: *SS, EnteringContext))) {
2741 // The declaration context must be complete.
2742 if (!DC->isDependentContext() && RequireCompleteDeclContext(SS&: *SS, DC))
2743 return false;
2744 R.setContextRange(SS->getRange());
2745 // FIXME: '__super' lookup semantics could be implemented by a
2746 // LookupResult::isSuperLookup flag which skips the initial search of
2747 // the lookup context in LookupQualified.
2748 if (NestedNameSpecifier Qualifier = SS->getScopeRep();
2749 Qualifier.getKind() == NestedNameSpecifier::Kind::MicrosoftSuper)
2750 return LookupInSuper(R, Class: Qualifier.getAsMicrosoftSuper());
2751 }
2752 IsDependent = !DC && isDependentScopeSpecifier(SS: *SS);
2753 } else {
2754 // Perform unqualified name lookup starting in the given scope.
2755 return LookupName(R, S, AllowBuiltinCreation);
2756 }
2757
2758 // If we were able to compute a declaration context, perform qualified name
2759 // lookup in that context.
2760 if (DC)
2761 return LookupQualifiedName(R, LookupCtx: DC);
2762 else if (IsDependent)
2763 // We could not resolve the scope specified to a specific declaration
2764 // context, which means that SS refers to an unknown specialization.
2765 // Name lookup can't find anything in this case.
2766 R.setNotFoundInCurrentInstantiation();
2767 return false;
2768}
2769
2770bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2771 // The access-control rules we use here are essentially the rules for
2772 // doing a lookup in Class that just magically skipped the direct
2773 // members of Class itself. That is, the naming class is Class, and the
2774 // access includes the access of the base.
2775 for (const auto &BaseSpec : Class->bases()) {
2776 auto *RD = BaseSpec.getType()->castAsCXXRecordDecl();
2777 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2778 Result.setBaseObjectType(Context.getCanonicalTagType(TD: Class));
2779 LookupQualifiedName(R&: Result, LookupCtx: RD);
2780
2781 // Copy the lookup results into the target, merging the base's access into
2782 // the path access.
2783 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2784 R.addDecl(D: I.getDecl(),
2785 AS: CXXRecordDecl::MergeAccess(PathAccess: BaseSpec.getAccessSpecifier(),
2786 DeclAccess: I.getAccess()));
2787 }
2788
2789 Result.suppressDiagnostics();
2790 }
2791
2792 R.resolveKind();
2793 R.setNamingClass(Class);
2794
2795 return !R.empty();
2796}
2797
2798void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2799 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2800
2801 DeclarationName Name = Result.getLookupName();
2802 SourceLocation NameLoc = Result.getNameLoc();
2803 SourceRange LookupRange = Result.getContextRange();
2804
2805 switch (Result.getAmbiguityKind()) {
2806 case LookupAmbiguityKind::AmbiguousBaseSubobjects: {
2807 CXXBasePaths *Paths = Result.getBasePaths();
2808 QualType SubobjectType = Paths->front().back().Base->getType();
2809 Diag(Loc: NameLoc, DiagID: diag::err_ambiguous_member_multiple_subobjects)
2810 << Name << SubobjectType << getAmbiguousPathsDisplayString(Paths&: *Paths)
2811 << LookupRange;
2812
2813 DeclContext::lookup_iterator Found = Paths->front().Decls;
2814 while (isa<CXXMethodDecl>(Val: *Found) &&
2815 cast<CXXMethodDecl>(Val: *Found)->isStatic())
2816 ++Found;
2817
2818 Diag(Loc: (*Found)->getLocation(), DiagID: diag::note_ambiguous_member_found);
2819 break;
2820 }
2821
2822 case LookupAmbiguityKind::AmbiguousBaseSubobjectTypes: {
2823 Diag(Loc: NameLoc, DiagID: diag::err_ambiguous_member_multiple_subobject_types)
2824 << Name << LookupRange;
2825
2826 CXXBasePaths *Paths = Result.getBasePaths();
2827 std::set<const NamedDecl *> DeclsPrinted;
2828 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2829 PathEnd = Paths->end();
2830 Path != PathEnd; ++Path) {
2831 const NamedDecl *D = *Path->Decls;
2832 if (!D->isInIdentifierNamespace(NS: Result.getIdentifierNamespace()))
2833 continue;
2834 if (DeclsPrinted.insert(x: D).second) {
2835 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D->getUnderlyingDecl()))
2836 Diag(Loc: D->getLocation(), DiagID: diag::note_ambiguous_member_type_found)
2837 << TD->getUnderlyingType();
2838 else if (const auto *TD = dyn_cast<TypeDecl>(Val: D->getUnderlyingDecl()))
2839 Diag(Loc: D->getLocation(), DiagID: diag::note_ambiguous_member_type_found)
2840 << Context.getTypeDeclType(Decl: TD);
2841 else
2842 Diag(Loc: D->getLocation(), DiagID: diag::note_ambiguous_member_found);
2843 }
2844 }
2845 break;
2846 }
2847
2848 case LookupAmbiguityKind::AmbiguousTagHiding: {
2849 Diag(Loc: NameLoc, DiagID: diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2850
2851 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2852
2853 for (auto *D : Result)
2854 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
2855 TagDecls.insert(Ptr: TD);
2856 Diag(Loc: TD->getLocation(), DiagID: diag::note_hidden_tag);
2857 }
2858
2859 for (auto *D : Result)
2860 if (!isa<TagDecl>(Val: D))
2861 Diag(Loc: D->getLocation(), DiagID: diag::note_hiding_object);
2862
2863 // For recovery purposes, go ahead and implement the hiding.
2864 LookupResult::Filter F = Result.makeFilter();
2865 while (F.hasNext()) {
2866 if (TagDecls.count(Ptr: F.next()))
2867 F.erase();
2868 }
2869 F.done();
2870 break;
2871 }
2872
2873 case LookupAmbiguityKind::AmbiguousReferenceToPlaceholderVariable: {
2874 Diag(Loc: NameLoc, DiagID: diag::err_using_placeholder_variable) << Name << LookupRange;
2875 DeclContext *DC = nullptr;
2876 for (auto *D : Result) {
2877 Diag(Loc: D->getLocation(), DiagID: diag::note_reference_placeholder) << D;
2878 if (DC != nullptr && DC != D->getDeclContext())
2879 break;
2880 DC = D->getDeclContext();
2881 }
2882 break;
2883 }
2884
2885 case LookupAmbiguityKind::AmbiguousReference: {
2886 Diag(Loc: NameLoc, DiagID: diag::err_ambiguous_reference) << Name << LookupRange;
2887
2888 for (auto *D : Result)
2889 Diag(Loc: D->getLocation(), DiagID: diag::note_ambiguous_candidate) << D;
2890 break;
2891 }
2892 }
2893}
2894
2895namespace {
2896 struct AssociatedLookup {
2897 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2898 Sema::AssociatedNamespaceSet &Namespaces,
2899 Sema::AssociatedClassSet &Classes)
2900 : S(S), Namespaces(Namespaces), Classes(Classes),
2901 InstantiationLoc(InstantiationLoc) {
2902 }
2903
2904 bool addClassTransitive(CXXRecordDecl *RD) {
2905 Classes.insert(X: RD);
2906 return ClassesTransitive.insert(X: RD);
2907 }
2908
2909 Sema &S;
2910 Sema::AssociatedNamespaceSet &Namespaces;
2911 Sema::AssociatedClassSet &Classes;
2912 SourceLocation InstantiationLoc;
2913
2914 private:
2915 Sema::AssociatedClassSet ClassesTransitive;
2916 };
2917} // end anonymous namespace
2918
2919static void
2920addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2921
2922// Given the declaration context \param Ctx of a class, class template or
2923// enumeration, add the associated namespaces to \param Namespaces as described
2924// in [basic.lookup.argdep]p2.
2925static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2926 DeclContext *Ctx) {
2927 // The exact wording has been changed in C++14 as a result of
2928 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2929 // to all language versions since it is possible to return a local type
2930 // from a lambda in C++11.
2931 //
2932 // C++14 [basic.lookup.argdep]p2:
2933 // If T is a class type [...]. Its associated namespaces are the innermost
2934 // enclosing namespaces of its associated classes. [...]
2935 //
2936 // If T is an enumeration type, its associated namespace is the innermost
2937 // enclosing namespace of its declaration. [...]
2938
2939 // We additionally skip inline namespaces. The innermost non-inline namespace
2940 // contains all names of all its nested inline namespaces anyway, so we can
2941 // replace the entire inline namespace tree with its root.
2942 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2943 Ctx = Ctx->getParent();
2944
2945 // Actually it is fine to always do `Namespaces.insert(Ctx);` simply. But it
2946 // may cause more allocations in Namespaces and more unnecessary lookups. So
2947 // we'd like to insert the representative namespace only.
2948 DeclContext *PrimaryCtx = Ctx->getPrimaryContext();
2949 Decl *PrimaryD = cast<Decl>(Val: PrimaryCtx);
2950 Decl *D = cast<Decl>(Val: Ctx);
2951 ASTContext &AST = D->getASTContext();
2952
2953 // TODO: Technically it is better to insert one namespace per module. e.g.,
2954 //
2955 // ```
2956 // //--- first.cppm
2957 // export module first;
2958 // namespace ns { ... } // first namespace
2959 //
2960 // //--- m-partA.cppm
2961 // export module m:partA;
2962 // import first;
2963 //
2964 // namespace ns { ... }
2965 // namespace ns { ... }
2966 //
2967 // //--- m-partB.cppm
2968 // export module m:partB;
2969 // import first;
2970 // import :partA;
2971 //
2972 // namespace ns { ... }
2973 // namespace ns { ... }
2974 //
2975 // ...
2976 //
2977 // //--- m-partN.cppm
2978 // export module m:partN;
2979 // import first;
2980 // import :partA;
2981 // ...
2982 // import :part$(N-1);
2983 //
2984 // namespace ns { ... }
2985 // namespace ns { ... }
2986 //
2987 // consume(ns::any_decl); // the lookup
2988 // ```
2989 //
2990 // We should only insert once for all namespaces in module m.
2991 if (D->isInNamedModule() &&
2992 !AST.isInSameModule(M1: D->getOwningModule(), M2: PrimaryD->getOwningModule()))
2993 Namespaces.insert(X: Ctx);
2994 else
2995 Namespaces.insert(X: PrimaryCtx);
2996}
2997
2998// Add the associated classes and namespaces for argument-dependent
2999// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
3000static void
3001addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
3002 const TemplateArgument &Arg) {
3003 // C++ [basic.lookup.argdep]p2, last bullet:
3004 // -- [...] ;
3005 switch (Arg.getKind()) {
3006 case TemplateArgument::Null:
3007 break;
3008
3009 case TemplateArgument::Type:
3010 // [...] the namespaces and classes associated with the types of the
3011 // template arguments provided for template type parameters (excluding
3012 // template template parameters)
3013 addAssociatedClassesAndNamespaces(Result, T: Arg.getAsType());
3014 break;
3015
3016 case TemplateArgument::Template:
3017 case TemplateArgument::TemplateExpansion: {
3018 // [...] the namespaces in which any template template arguments are
3019 // defined; and the classes in which any member templates used as
3020 // template template arguments are defined.
3021 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3022 if (ClassTemplateDecl *ClassTemplate
3023 = dyn_cast<ClassTemplateDecl>(Val: Template.getAsTemplateDecl())) {
3024 DeclContext *Ctx = ClassTemplate->getDeclContext();
3025 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Val: Ctx))
3026 Result.Classes.insert(X: EnclosingClass);
3027 // Add the associated namespace for this class.
3028 CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx);
3029 }
3030 break;
3031 }
3032
3033 case TemplateArgument::Declaration:
3034 case TemplateArgument::Integral:
3035 case TemplateArgument::Expression:
3036 case TemplateArgument::NullPtr:
3037 case TemplateArgument::StructuralValue:
3038 // [Note: non-type template arguments do not contribute to the set of
3039 // associated namespaces. ]
3040 break;
3041
3042 case TemplateArgument::Pack:
3043 for (const auto &P : Arg.pack_elements())
3044 addAssociatedClassesAndNamespaces(Result, Arg: P);
3045 break;
3046 }
3047}
3048
3049// Add the associated classes and namespaces for argument-dependent lookup
3050// with an argument of class type (C++ [basic.lookup.argdep]p2).
3051static void
3052addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
3053 CXXRecordDecl *Class) {
3054
3055 // Just silently ignore anything whose name is __va_list_tag.
3056 if (Class->getDeclName() == Result.S.VAListTagName)
3057 return;
3058
3059 // C++ [basic.lookup.argdep]p2:
3060 // [...]
3061 // -- If T is a class type (including unions), its associated
3062 // classes are: the class itself; the class of which it is a
3063 // member, if any; and its direct and indirect base classes.
3064 // Its associated namespaces are the innermost enclosing
3065 // namespaces of its associated classes.
3066
3067 // Add the class of which it is a member, if any.
3068 DeclContext *Ctx = Class->getDeclContext();
3069 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Val: Ctx))
3070 Result.Classes.insert(X: EnclosingClass);
3071
3072 // Add the associated namespace for this class.
3073 CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx);
3074
3075 // -- If T is a template-id, its associated namespaces and classes are
3076 // the namespace in which the template is defined; for member
3077 // templates, the member template's class; the namespaces and classes
3078 // associated with the types of the template arguments provided for
3079 // template type parameters (excluding template template parameters); the
3080 // namespaces in which any template template arguments are defined; and
3081 // the classes in which any member templates used as template template
3082 // arguments are defined. [Note: non-type template arguments do not
3083 // contribute to the set of associated namespaces. ]
3084 if (ClassTemplateSpecializationDecl *Spec
3085 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class)) {
3086 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
3087 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Val: Ctx))
3088 Result.Classes.insert(X: EnclosingClass);
3089 // Add the associated namespace for this class.
3090 CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx);
3091
3092 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3093 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3094 addAssociatedClassesAndNamespaces(Result, Arg: TemplateArgs[I]);
3095 }
3096
3097 // Add the class itself. If we've already transitively visited this class,
3098 // we don't need to visit base classes.
3099 if (!Result.addClassTransitive(RD: Class))
3100 return;
3101
3102 // Only recurse into base classes for complete types.
3103 if (!Result.S.isCompleteType(Loc: Result.InstantiationLoc,
3104 T: Result.S.Context.getCanonicalTagType(TD: Class)))
3105 return;
3106
3107 // Add direct and indirect base classes along with their associated
3108 // namespaces.
3109 SmallVector<CXXRecordDecl *, 32> Bases;
3110 Bases.push_back(Elt: Class);
3111 while (!Bases.empty()) {
3112 // Pop this class off the stack.
3113 Class = Bases.pop_back_val();
3114
3115 // Visit the base classes.
3116 for (const auto &Base : Class->bases()) {
3117 CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3118 // In dependent contexts, we do ADL twice, and the first time around,
3119 // the base type might be a dependent TemplateSpecializationType, or a
3120 // TemplateTypeParmType. If that happens, simply ignore it.
3121 // FIXME: If we want to support export, we probably need to add the
3122 // namespace of the template in a TemplateSpecializationType, or even
3123 // the classes and namespaces of known non-dependent arguments.
3124 if (!BaseDecl)
3125 continue;
3126 if (Result.addClassTransitive(RD: BaseDecl)) {
3127 // Find the associated namespace for this base class.
3128 DeclContext *BaseCtx = BaseDecl->getDeclContext();
3129 CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx: BaseCtx);
3130
3131 // Make sure we visit the bases of this base class.
3132 if (!BaseDecl->bases().empty())
3133 Bases.push_back(Elt: BaseDecl);
3134 }
3135 }
3136 }
3137}
3138
3139// Add the associated classes and namespaces for
3140// argument-dependent lookup with an argument of type T
3141// (C++ [basic.lookup.koenig]p2).
3142static void
3143addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
3144 // C++ [basic.lookup.koenig]p2:
3145 //
3146 // For each argument type T in the function call, there is a set
3147 // of zero or more associated namespaces and a set of zero or more
3148 // associated classes to be considered. The sets of namespaces and
3149 // classes is determined entirely by the types of the function
3150 // arguments (and the namespace of any template template
3151 // argument). Typedef names and using-declarations used to specify
3152 // the types do not contribute to this set. The sets of namespaces
3153 // and classes are determined in the following way:
3154
3155 SmallVector<const Type *, 16> Queue;
3156 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
3157
3158 while (true) {
3159 switch (T->getTypeClass()) {
3160
3161#define TYPE(Class, Base)
3162#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3163#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3164#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3165#define ABSTRACT_TYPE(Class, Base)
3166#include "clang/AST/TypeNodes.inc"
3167 // T is canonical. We can also ignore dependent types because
3168 // we don't need to do ADL at the definition point, but if we
3169 // wanted to implement template export (or if we find some other
3170 // use for associated classes and namespaces...) this would be
3171 // wrong.
3172 break;
3173
3174 // -- If T is a pointer to U or an array of U, its associated
3175 // namespaces and classes are those associated with U.
3176 case Type::Pointer:
3177 T = cast<PointerType>(Val: T)->getPointeeType().getTypePtr();
3178 continue;
3179 case Type::ConstantArray:
3180 case Type::IncompleteArray:
3181 case Type::VariableArray:
3182 T = cast<ArrayType>(Val: T)->getElementType().getTypePtr();
3183 continue;
3184
3185 // -- If T is a fundamental type, its associated sets of
3186 // namespaces and classes are both empty.
3187 case Type::Builtin:
3188 break;
3189
3190 // -- If T is a class type (including unions), its associated
3191 // classes are: the class itself; the class of which it is
3192 // a member, if any; and its direct and indirect base classes.
3193 // Its associated namespaces are the innermost enclosing
3194 // namespaces of its associated classes.
3195 case Type::Record: {
3196 // FIXME: This should use the original decl.
3197 auto *Class = cast<CXXRecordDecl>(Val: cast<RecordType>(Val: T)->getDecl())
3198 ->getDefinitionOrSelf();
3199 addAssociatedClassesAndNamespaces(Result, Class);
3200 break;
3201 }
3202
3203 // -- If T is an enumeration type, its associated namespace
3204 // is the innermost enclosing namespace of its declaration.
3205 // If it is a class member, its associated class is the
3206 // member’s class; else it has no associated class.
3207 case Type::Enum: {
3208 // FIXME: This should use the original decl.
3209 auto *Enum = T->castAsEnumDecl();
3210
3211 DeclContext *Ctx = Enum->getDeclContext();
3212 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Val: Ctx))
3213 Result.Classes.insert(X: EnclosingClass);
3214
3215 // Add the associated namespace for this enumeration.
3216 CollectEnclosingNamespace(Namespaces&: Result.Namespaces, Ctx);
3217
3218 break;
3219 }
3220
3221 // -- If T is a function type, its associated namespaces and
3222 // classes are those associated with the function parameter
3223 // types and those associated with the return type.
3224 case Type::FunctionProto: {
3225 const FunctionProtoType *Proto = cast<FunctionProtoType>(Val: T);
3226 for (const auto &Arg : Proto->param_types())
3227 Queue.push_back(Elt: Arg.getTypePtr());
3228 // fallthrough
3229 [[fallthrough]];
3230 }
3231 case Type::FunctionNoProto: {
3232 const FunctionType *FnType = cast<FunctionType>(Val: T);
3233 T = FnType->getReturnType().getTypePtr();
3234 continue;
3235 }
3236
3237 // -- If T is a pointer to a member function of a class X, its
3238 // associated namespaces and classes are those associated
3239 // with the function parameter types and return type,
3240 // together with those associated with X.
3241 //
3242 // -- If T is a pointer to a data member of class X, its
3243 // associated namespaces and classes are those associated
3244 // with the member type together with those associated with
3245 // X.
3246 case Type::MemberPointer: {
3247 const MemberPointerType *MemberPtr = cast<MemberPointerType>(Val: T);
3248 if (CXXRecordDecl *Class = MemberPtr->getMostRecentCXXRecordDecl())
3249 addAssociatedClassesAndNamespaces(Result, Class);
3250 T = MemberPtr->getPointeeType().getTypePtr();
3251 continue;
3252 }
3253
3254 // As an extension, treat this like a normal pointer.
3255 case Type::BlockPointer:
3256 T = cast<BlockPointerType>(Val: T)->getPointeeType().getTypePtr();
3257 continue;
3258
3259 // References aren't covered by the standard, but that's such an
3260 // obvious defect that we cover them anyway.
3261 case Type::LValueReference:
3262 case Type::RValueReference:
3263 T = cast<ReferenceType>(Val: T)->getPointeeType().getTypePtr();
3264 continue;
3265
3266 // These are fundamental types.
3267 case Type::Vector:
3268 case Type::ExtVector:
3269 case Type::ConstantMatrix:
3270 case Type::Complex:
3271 case Type::BitInt:
3272 break;
3273
3274 // Non-deduced auto types only get here for error cases.
3275 case Type::Auto:
3276 case Type::DeducedTemplateSpecialization:
3277 break;
3278
3279 // If T is an Objective-C object or interface type, or a pointer to an
3280 // object or interface type, the associated namespace is the global
3281 // namespace.
3282 case Type::ObjCObject:
3283 case Type::ObjCInterface:
3284 case Type::ObjCObjectPointer:
3285 Result.Namespaces.insert(X: Result.S.Context.getTranslationUnitDecl());
3286 break;
3287
3288 // Atomic types are just wrappers; use the associations of the
3289 // contained type.
3290 case Type::Atomic:
3291 T = cast<AtomicType>(Val: T)->getValueType().getTypePtr();
3292 continue;
3293 case Type::Pipe:
3294 T = cast<PipeType>(Val: T)->getElementType().getTypePtr();
3295 continue;
3296
3297 // Array parameter types are treated as fundamental types.
3298 case Type::ArrayParameter:
3299 break;
3300
3301 case Type::HLSLAttributedResource:
3302 T = cast<HLSLAttributedResourceType>(Val: T)->getWrappedType().getTypePtr();
3303 break;
3304
3305 // Inline SPIR-V types are treated as fundamental types.
3306 case Type::HLSLInlineSpirv:
3307 break;
3308 case Type::OverflowBehavior:
3309 T = cast<OverflowBehaviorType>(Val: T)->getUnderlyingType().getTypePtr();
3310 }
3311
3312 if (Queue.empty())
3313 break;
3314 T = Queue.pop_back_val();
3315 }
3316}
3317
3318void Sema::FindAssociatedClassesAndNamespaces(
3319 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3320 AssociatedNamespaceSet &AssociatedNamespaces,
3321 AssociatedClassSet &AssociatedClasses) {
3322 AssociatedNamespaces.clear();
3323 AssociatedClasses.clear();
3324
3325 AssociatedLookup Result(*this, InstantiationLoc,
3326 AssociatedNamespaces, AssociatedClasses);
3327
3328 // C++ [basic.lookup.koenig]p2:
3329 // For each argument type T in the function call, there is a set
3330 // of zero or more associated namespaces and a set of zero or more
3331 // associated classes to be considered. The sets of namespaces and
3332 // classes is determined entirely by the types of the function
3333 // arguments (and the namespace of any template template
3334 // argument).
3335 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3336 Expr *Arg = Args[ArgIdx];
3337
3338 if (Arg->getType() != Context.OverloadTy) {
3339 addAssociatedClassesAndNamespaces(Result, Ty: Arg->getType());
3340 continue;
3341 }
3342
3343 // [...] In addition, if the argument is the name or address of a
3344 // set of overloaded functions and/or function templates, its
3345 // associated classes and namespaces are the union of those
3346 // associated with each of the members of the set: the namespace
3347 // in which the function or function template is defined and the
3348 // classes and namespaces associated with its (non-dependent)
3349 // parameter types and return type.
3350 OverloadExpr *OE = OverloadExpr::find(E: Arg).Expression;
3351
3352 for (const NamedDecl *D : OE->decls()) {
3353 // Look through any using declarations to find the underlying function.
3354 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3355
3356 // Add the classes and namespaces associated with the parameter
3357 // types and return type of this function.
3358 addAssociatedClassesAndNamespaces(Result, Ty: FDecl->getType());
3359 }
3360 }
3361}
3362
3363NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
3364 SourceLocation Loc,
3365 LookupNameKind NameKind,
3366 RedeclarationKind Redecl) {
3367 LookupResult R(*this, Name, Loc, NameKind, Redecl);
3368 LookupName(R, S);
3369 return R.getAsSingle<NamedDecl>();
3370}
3371
3372void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3373 UnresolvedSetImpl &Functions) {
3374 // C++ [over.match.oper]p3:
3375 // -- The set of non-member candidates is the result of the
3376 // unqualified lookup of operator@ in the context of the
3377 // expression according to the usual rules for name lookup in
3378 // unqualified function calls (3.4.2) except that all member
3379 // functions are ignored.
3380 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3381 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3382 LookupName(R&: Operators, S);
3383
3384 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3385 Functions.append(I: Operators.begin(), E: Operators.end());
3386}
3387
3388static Sema::SpecialMemberCacheKey
3389makeSpecialMemberCacheKey(const CXXRecordDecl *RD, CXXSpecialMemberKind SM,
3390 bool ConstArg, bool VolatileArg, bool RValueThis,
3391 bool ConstThis, bool VolatileThis) {
3392 unsigned Flags = llvm::to_underlying(E: SM) << 5;
3393 Flags |= ConstArg << 4;
3394 Flags |= VolatileArg << 3;
3395 Flags |= RValueThis << 2;
3396 Flags |= ConstThis << 1;
3397 Flags |= VolatileThis;
3398 return {RD, Flags};
3399}
3400
3401Sema::SpecialMemberOverloadResult
3402Sema::LookupSpecialMember(CXXRecordDecl *RD, CXXSpecialMemberKind SM,
3403 bool ConstArg, bool VolatileArg, bool RValueThis,
3404 bool ConstThis, bool VolatileThis) {
3405 assert(CanDeclareSpecialMemberFunction(RD) &&
3406 "doing special member lookup into record that isn't fully complete");
3407 RD = RD->getDefinition();
3408 if (RValueThis || ConstThis || VolatileThis)
3409 assert((SM == CXXSpecialMemberKind::CopyAssignment ||
3410 SM == CXXSpecialMemberKind::MoveAssignment) &&
3411 "constructors and destructors always have unqualified lvalue this");
3412 if (ConstArg || VolatileArg)
3413 assert((SM != CXXSpecialMemberKind::DefaultConstructor &&
3414 SM != CXXSpecialMemberKind::Destructor) &&
3415 "parameter-less special members can't have qualified arguments");
3416
3417 // FIXME: Get the caller to pass in a location for the lookup.
3418 SourceLocation LookupLoc = RD->getLocation();
3419
3420 SpecialMemberCacheKey Key = makeSpecialMemberCacheKey(
3421 RD, SM, ConstArg, VolatileArg, RValueThis, ConstThis, VolatileThis);
3422
3423 auto [It, Inserted] = SpecialMemberCache.try_emplace(Key);
3424 if (!Inserted)
3425 return It->second;
3426
3427 SpecialMemberOverloadResult Result;
3428 if (SM == CXXSpecialMemberKind::Destructor) {
3429 if (RD->needsImplicitDestructor()) {
3430 runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] {
3431 DeclareImplicitDestructor(ClassDecl: RD);
3432 });
3433 }
3434 CXXDestructorDecl *DD = RD->getDestructor();
3435 Result.setMethod(DD);
3436 Result.setKind(DD && !DD->isDeleted()
3437 ? SpecialMemberOverloadResult::Success
3438 : SpecialMemberOverloadResult::NoMemberOrDeleted);
3439 return SpecialMemberCache[Key] = Result;
3440 }
3441
3442 // Prepare for overload resolution. Here we construct a synthetic argument
3443 // if necessary and make sure that implicit functions are declared.
3444 CanQualType CanTy = Context.getCanonicalTagType(TD: RD);
3445 DeclarationName Name;
3446 Expr *Arg = nullptr;
3447 unsigned NumArgs;
3448
3449 QualType ArgType = CanTy;
3450 ExprValueKind VK = VK_LValue;
3451
3452 if (SM == CXXSpecialMemberKind::DefaultConstructor) {
3453 Name = Context.DeclarationNames.getCXXConstructorName(Ty: CanTy);
3454 NumArgs = 0;
3455 if (RD->needsImplicitDefaultConstructor()) {
3456 runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] {
3457 DeclareImplicitDefaultConstructor(ClassDecl: RD);
3458 });
3459 }
3460 } else {
3461 if (SM == CXXSpecialMemberKind::CopyConstructor ||
3462 SM == CXXSpecialMemberKind::MoveConstructor) {
3463 Name = Context.DeclarationNames.getCXXConstructorName(Ty: CanTy);
3464 if (RD->needsImplicitCopyConstructor()) {
3465 runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] {
3466 DeclareImplicitCopyConstructor(ClassDecl: RD);
3467 });
3468 }
3469 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {
3470 runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] {
3471 DeclareImplicitMoveConstructor(ClassDecl: RD);
3472 });
3473 }
3474 } else {
3475 Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
3476 if (RD->needsImplicitCopyAssignment()) {
3477 runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] {
3478 DeclareImplicitCopyAssignment(ClassDecl: RD);
3479 });
3480 }
3481 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {
3482 runWithSufficientStackSpace(Loc: RD->getLocation(), Fn: [&] {
3483 DeclareImplicitMoveAssignment(ClassDecl: RD);
3484 });
3485 }
3486 }
3487
3488 if (ConstArg)
3489 ArgType.addConst();
3490 if (VolatileArg)
3491 ArgType.addVolatile();
3492
3493 // This isn't /really/ specified by the standard, but it's implied
3494 // we should be working from a PRValue in the case of move to ensure
3495 // that we prefer to bind to rvalue references, and an LValue in the
3496 // case of copy to ensure we don't bind to rvalue references.
3497 // Possibly an XValue is actually correct in the case of move, but
3498 // there is no semantic difference for class types in this restricted
3499 // case.
3500 if (SM == CXXSpecialMemberKind::CopyConstructor ||
3501 SM == CXXSpecialMemberKind::CopyAssignment)
3502 VK = VK_LValue;
3503 else
3504 VK = VK_PRValue;
3505 }
3506
3507 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3508
3509 if (SM != CXXSpecialMemberKind::DefaultConstructor) {
3510 NumArgs = 1;
3511 Arg = &FakeArg;
3512 }
3513
3514 // Create the object argument
3515 QualType ThisTy = CanTy;
3516 if (ConstThis)
3517 ThisTy.addConst();
3518 if (VolatileThis)
3519 ThisTy.addVolatile();
3520 Expr::Classification Classification =
3521 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3522 .Classify(Ctx&: Context);
3523
3524 // Now we perform lookup on the name we computed earlier and do overload
3525 // resolution. Lookup is only performed directly into the class since there
3526 // will always be a (possibly implicit) declaration to shadow any others.
3527 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
3528 DeclContext::lookup_result R = RD->lookup(Name);
3529
3530 if (R.empty()) {
3531 // We might have no default constructor because we have a lambda's closure
3532 // type, rather than because there's some other declared constructor.
3533 // Every class has a copy/move constructor, copy/move assignment, and
3534 // destructor.
3535 assert(SM == CXXSpecialMemberKind::DefaultConstructor &&
3536 "lookup for a constructor or assignment operator was empty");
3537 Result.setMethod(nullptr);
3538 Result.setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3539 return SpecialMemberCache[Key] = Result;
3540 }
3541
3542 // Copy the candidates as our processing of them may load new declarations
3543 // from an external source and invalidate lookup_result.
3544 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3545
3546 for (NamedDecl *CandDecl : Candidates) {
3547 if (CandDecl->isInvalidDecl())
3548 continue;
3549
3550 DeclAccessPair Cand = DeclAccessPair::make(D: CandDecl, AS: AS_public);
3551 auto CtorInfo = getConstructorInfo(ND: Cand);
3552 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Val: Cand->getUnderlyingDecl())) {
3553 if (SM == CXXSpecialMemberKind::CopyAssignment ||
3554 SM == CXXSpecialMemberKind::MoveAssignment)
3555 AddMethodCandidate(Method: M, FoundDecl: Cand, ActingContext: RD, ObjectType: ThisTy, ObjectClassification: Classification,
3556 Args: llvm::ArrayRef(&Arg, NumArgs), CandidateSet&: OCS, SuppressUserConversions: true);
3557 else if (CtorInfo)
3558 AddOverloadCandidate(Function: CtorInfo.Constructor, FoundDecl: CtorInfo.FoundDecl,
3559 Args: llvm::ArrayRef(&Arg, NumArgs), CandidateSet&: OCS,
3560 /*SuppressUserConversions*/ true);
3561 else
3562 AddOverloadCandidate(Function: M, FoundDecl: Cand, Args: llvm::ArrayRef(&Arg, NumArgs), CandidateSet&: OCS,
3563 /*SuppressUserConversions*/ true);
3564 } else if (FunctionTemplateDecl *Tmpl =
3565 dyn_cast<FunctionTemplateDecl>(Val: Cand->getUnderlyingDecl())) {
3566 if (SM == CXXSpecialMemberKind::CopyAssignment ||
3567 SM == CXXSpecialMemberKind::MoveAssignment)
3568 AddMethodTemplateCandidate(MethodTmpl: Tmpl, FoundDecl: Cand, ActingContext: RD, ExplicitTemplateArgs: nullptr, ObjectType: ThisTy,
3569 ObjectClassification: Classification,
3570 Args: llvm::ArrayRef(&Arg, NumArgs), CandidateSet&: OCS, SuppressUserConversions: true);
3571 else if (CtorInfo)
3572 AddTemplateOverloadCandidate(FunctionTemplate: CtorInfo.ConstructorTmpl,
3573 FoundDecl: CtorInfo.FoundDecl, ExplicitTemplateArgs: nullptr,
3574 Args: llvm::ArrayRef(&Arg, NumArgs), CandidateSet&: OCS, SuppressUserConversions: true);
3575 else
3576 AddTemplateOverloadCandidate(FunctionTemplate: Tmpl, FoundDecl: Cand, ExplicitTemplateArgs: nullptr,
3577 Args: llvm::ArrayRef(&Arg, NumArgs), CandidateSet&: OCS, SuppressUserConversions: true);
3578 } else {
3579 assert(isa<UsingDecl>(Cand.getDecl()) &&
3580 "illegal Kind of operator = Decl");
3581 }
3582 }
3583
3584 OverloadCandidateSet::iterator Best;
3585 switch (OCS.BestViableFunction(S&: *this, Loc: LookupLoc, Best)) {
3586 case OR_Success:
3587 Result.setMethod(cast<CXXMethodDecl>(Val: Best->Function));
3588 Result.setKind(SpecialMemberOverloadResult::Success);
3589 break;
3590
3591 case OR_Deleted:
3592 Result.setMethod(cast<CXXMethodDecl>(Val: Best->Function));
3593 Result.setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3594 break;
3595
3596 case OR_Ambiguous:
3597 Result.setMethod(nullptr);
3598 Result.setKind(SpecialMemberOverloadResult::Ambiguous);
3599 break;
3600
3601 case OR_No_Viable_Function:
3602 Result.setMethod(nullptr);
3603 Result.setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3604 break;
3605 }
3606
3607 return SpecialMemberCache[Key] = Result;
3608}
3609
3610CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
3611 SpecialMemberOverloadResult Result =
3612 LookupSpecialMember(RD: Class, SM: CXXSpecialMemberKind::DefaultConstructor,
3613 ConstArg: false, VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
3614
3615 return cast_or_null<CXXConstructorDecl>(Val: Result.getMethod());
3616}
3617
3618CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
3619 unsigned Quals) {
3620 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3621 "non-const, non-volatile qualifiers for copy ctor arg");
3622 SpecialMemberOverloadResult Result = LookupSpecialMember(
3623 RD: Class, SM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Quals & Qualifiers::Const,
3624 VolatileArg: Quals & Qualifiers::Volatile, RValueThis: false, ConstThis: false, VolatileThis: false);
3625
3626 return cast_or_null<CXXConstructorDecl>(Val: Result.getMethod());
3627}
3628
3629CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3630 unsigned Quals) {
3631 SpecialMemberOverloadResult Result = LookupSpecialMember(
3632 RD: Class, SM: CXXSpecialMemberKind::MoveConstructor, ConstArg: Quals & Qualifiers::Const,
3633 VolatileArg: Quals & Qualifiers::Volatile, RValueThis: false, ConstThis: false, VolatileThis: false);
3634
3635 return cast_or_null<CXXConstructorDecl>(Val: Result.getMethod());
3636}
3637
3638DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
3639 // If the implicit constructors have not yet been declared, do so now.
3640 if (CanDeclareSpecialMemberFunction(Class)) {
3641 runWithSufficientStackSpace(Loc: Class->getLocation(), Fn: [&] {
3642 if (Class->needsImplicitDefaultConstructor())
3643 DeclareImplicitDefaultConstructor(ClassDecl: Class);
3644 if (Class->needsImplicitCopyConstructor())
3645 DeclareImplicitCopyConstructor(ClassDecl: Class);
3646 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3647 DeclareImplicitMoveConstructor(ClassDecl: Class);
3648 });
3649 }
3650
3651 CanQualType T = Context.getCanonicalTagType(TD: Class);
3652 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(Ty: T);
3653 return Class->lookup(Name);
3654}
3655
3656CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3657 unsigned Quals, bool RValueThis,
3658 unsigned ThisQuals) {
3659 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3660 "non-const, non-volatile qualifiers for copy assignment arg");
3661 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3662 "non-const, non-volatile qualifiers for copy assignment this");
3663 SpecialMemberOverloadResult Result = LookupSpecialMember(
3664 RD: Class, SM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Quals & Qualifiers::Const,
3665 VolatileArg: Quals & Qualifiers::Volatile, RValueThis, ConstThis: ThisQuals & Qualifiers::Const,
3666 VolatileThis: ThisQuals & Qualifiers::Volatile);
3667
3668 return Result.getMethod();
3669}
3670
3671CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
3672 unsigned Quals,
3673 bool RValueThis,
3674 unsigned ThisQuals) {
3675 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3676 "non-const, non-volatile qualifiers for copy assignment this");
3677 SpecialMemberOverloadResult Result = LookupSpecialMember(
3678 RD: Class, SM: CXXSpecialMemberKind::MoveAssignment, ConstArg: Quals & Qualifiers::Const,
3679 VolatileArg: Quals & Qualifiers::Volatile, RValueThis, ConstThis: ThisQuals & Qualifiers::Const,
3680 VolatileThis: ThisQuals & Qualifiers::Volatile);
3681
3682 return Result.getMethod();
3683}
3684
3685CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3686 return cast_or_null<CXXDestructorDecl>(
3687 Val: LookupSpecialMember(RD: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false, VolatileArg: false,
3688 RValueThis: false, ConstThis: false, VolatileThis: false)
3689 .getMethod());
3690}
3691
3692Sema::LiteralOperatorLookupResult
3693Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3694 ArrayRef<QualType> ArgTys, bool AllowRaw,
3695 bool AllowTemplate, bool AllowStringTemplatePack,
3696 bool DiagnoseMissing, StringLiteral *StringLit) {
3697 LookupName(R, S);
3698 assert(R.getResultKind() != LookupResultKind::Ambiguous &&
3699 "literal operator lookup can't be ambiguous");
3700
3701 // Filter the lookup results appropriately.
3702 LookupResult::Filter F = R.makeFilter();
3703
3704 bool AllowCooked = true;
3705 bool FoundRaw = false;
3706 bool FoundTemplate = false;
3707 bool FoundStringTemplatePack = false;
3708 bool FoundCooked = false;
3709
3710 while (F.hasNext()) {
3711 Decl *D = F.next();
3712 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(Val: D))
3713 D = USD->getTargetDecl();
3714
3715 // If the declaration we found is invalid, skip it.
3716 if (D->isInvalidDecl()) {
3717 F.erase();
3718 continue;
3719 }
3720
3721 bool IsRaw = false;
3722 bool IsTemplate = false;
3723 bool IsStringTemplatePack = false;
3724 bool IsCooked = false;
3725
3726 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3727 if (FD->getNumParams() == 1 &&
3728 FD->getParamDecl(i: 0)->getType()->getAs<PointerType>())
3729 IsRaw = true;
3730 else if (FD->getNumParams() == ArgTys.size()) {
3731 IsCooked = true;
3732 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3733 QualType ParamTy = FD->getParamDecl(i: ArgIdx)->getType();
3734 if (!Context.hasSameUnqualifiedType(T1: ArgTys[ArgIdx], T2: ParamTy)) {
3735 IsCooked = false;
3736 break;
3737 }
3738 }
3739 }
3740 }
3741 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
3742 TemplateParameterList *Params = FD->getTemplateParameters();
3743 if (Params->size() == 1) {
3744 IsTemplate = true;
3745 if (!Params->getParam(Idx: 0)->isTemplateParameterPack() && !StringLit) {
3746 // Implied but not stated: user-defined integer and floating literals
3747 // only ever use numeric literal operator templates, not templates
3748 // taking a parameter of class type.
3749 F.erase();
3750 continue;
3751 }
3752
3753 // A string literal template is only considered if the string literal
3754 // is a well-formed template argument for the template parameter.
3755 if (StringLit) {
3756 SFINAETrap Trap(*this);
3757 CheckTemplateArgumentInfo CTAI;
3758 TemplateArgumentLoc Arg(
3759 TemplateArgument(StringLit, /*IsCanonical=*/false), StringLit);
3760 if (CheckTemplateArgument(
3761 Param: Params->getParam(Idx: 0), Arg, Template: FD, TemplateLoc: R.getNameLoc(), RAngleLoc: R.getNameLoc(),
3762 /*ArgumentPackIndex=*/0, CTAI, CTAK: CTAK_Specified) ||
3763 Trap.hasErrorOccurred())
3764 IsTemplate = false;
3765 }
3766 } else {
3767 IsStringTemplatePack = true;
3768 }
3769 }
3770
3771 if (AllowTemplate && StringLit && IsTemplate) {
3772 FoundTemplate = true;
3773 AllowRaw = false;
3774 AllowCooked = false;
3775 AllowStringTemplatePack = false;
3776 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3777 F.restart();
3778 FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3779 }
3780 } else if (AllowCooked && IsCooked) {
3781 FoundCooked = true;
3782 AllowRaw = false;
3783 AllowTemplate = StringLit;
3784 AllowStringTemplatePack = false;
3785 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3786 // Go through again and remove the raw and template decls we've
3787 // already found.
3788 F.restart();
3789 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3790 }
3791 } else if (AllowRaw && IsRaw) {
3792 FoundRaw = true;
3793 } else if (AllowTemplate && IsTemplate) {
3794 FoundTemplate = true;
3795 } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3796 FoundStringTemplatePack = true;
3797 } else {
3798 F.erase();
3799 }
3800 }
3801
3802 F.done();
3803
3804 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3805 // form for string literal operator templates.
3806 if (StringLit && FoundTemplate)
3807 return LOLR_Template;
3808
3809 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3810 // parameter type, that is used in preference to a raw literal operator
3811 // or literal operator template.
3812 if (FoundCooked)
3813 return LOLR_Cooked;
3814
3815 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3816 // operator template, but not both.
3817 if (FoundRaw && FoundTemplate) {
3818 Diag(Loc: R.getNameLoc(), DiagID: diag::err_ovl_ambiguous_call) << R.getLookupName();
3819 for (const NamedDecl *D : R)
3820 NoteOverloadCandidate(Found: D, Fn: D->getUnderlyingDecl()->getAsFunction());
3821 return LOLR_Error;
3822 }
3823
3824 if (FoundRaw)
3825 return LOLR_Raw;
3826
3827 if (FoundTemplate)
3828 return LOLR_Template;
3829
3830 if (FoundStringTemplatePack)
3831 return LOLR_StringTemplatePack;
3832
3833 // Didn't find anything we could use.
3834 if (DiagnoseMissing) {
3835 Diag(Loc: R.getNameLoc(), DiagID: diag::err_ovl_no_viable_literal_operator)
3836 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3837 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3838 << (AllowTemplate || AllowStringTemplatePack);
3839 return LOLR_Error;
3840 }
3841
3842 return LOLR_ErrorNoDiagnostic;
3843}
3844
3845void ADLResult::insert(NamedDecl *New) {
3846 NamedDecl *&Old = Decls[cast<NamedDecl>(Val: New->getCanonicalDecl())];
3847
3848 // If we haven't yet seen a decl for this key, or the last decl
3849 // was exactly this one, we're done.
3850 if (Old == nullptr || Old == New) {
3851 Old = New;
3852 return;
3853 }
3854
3855 // Otherwise, decide which is a more recent redeclaration.
3856 FunctionDecl *OldFD = Old->getAsFunction();
3857 FunctionDecl *NewFD = New->getAsFunction();
3858
3859 FunctionDecl *Cursor = NewFD;
3860 while (true) {
3861 Cursor = Cursor->getPreviousDecl();
3862
3863 // If we got to the end without finding OldFD, OldFD is the newer
3864 // declaration; leave things as they are.
3865 if (!Cursor) return;
3866
3867 // If we do find OldFD, then NewFD is newer.
3868 if (Cursor == OldFD) break;
3869
3870 // Otherwise, keep looking.
3871 }
3872
3873 Old = New;
3874}
3875
3876void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3877 ArrayRef<Expr *> Args, ADLResult &Result) {
3878 // Find all of the associated namespaces and classes based on the
3879 // arguments we have.
3880 AssociatedNamespaceSet AssociatedNamespaces;
3881 AssociatedClassSet AssociatedClasses;
3882 FindAssociatedClassesAndNamespaces(InstantiationLoc: Loc, Args,
3883 AssociatedNamespaces,
3884 AssociatedClasses);
3885
3886 // Load the friend classes in case there are unloaded decls.
3887 //
3888 // FIXME: Currently this is inefficient if there are a lot of friends
3889 // in the classes. We just expect the number of friends are limited
3890 // in real world. In case we meet the case that the loading friends
3891 // became a threshold, we can change the structure of friends from
3892 // a list to a name lookup table.
3893 for (CXXRecordDecl *Class : AssociatedClasses)
3894 if (Class->hasDefinition() && Class->hasLazyFriends())
3895 Class->loadLazyFriends();
3896
3897 // C++ [basic.lookup.argdep]p3:
3898 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3899 // and let Y be the lookup set produced by argument dependent
3900 // lookup (defined as follows). If X contains [...] then Y is
3901 // empty. Otherwise Y is the set of declarations found in the
3902 // namespaces associated with the argument types as described
3903 // below. The set of declarations found by the lookup of the name
3904 // is the union of X and Y.
3905 //
3906 // Here, we compute Y and add its members to the overloaded
3907 // candidate set.
3908 for (auto *NS : AssociatedNamespaces) {
3909 // When considering an associated namespace, the lookup is the
3910 // same as the lookup performed when the associated namespace is
3911 // used as a qualifier (3.4.3.2) except that:
3912 //
3913 // -- Any using-directives in the associated namespace are
3914 // ignored.
3915 //
3916 // -- Any namespace-scope friend functions declared in
3917 // associated classes are visible within their respective
3918 // namespaces even if they are not visible during an ordinary
3919 // lookup (11.4).
3920 //
3921 // C++20 [basic.lookup.argdep] p4.3
3922 // -- are exported, are attached to a named module M, do not appear
3923 // in the translation unit containing the point of the lookup, and
3924 // have the same innermost enclosing non-inline namespace scope as
3925 // a declaration of an associated entity attached to M.
3926 DeclContext::lookup_result R = NS->lookup(Name);
3927 for (auto *D : R) {
3928 auto *Underlying = D;
3929 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: D))
3930 Underlying = USD->getTargetDecl();
3931
3932 if (!isa<FunctionDecl>(Val: Underlying) &&
3933 !isa<FunctionTemplateDecl>(Val: Underlying))
3934 continue;
3935
3936 // The declaration is visible to argument-dependent lookup if either
3937 // it's ordinarily visible or declared as a friend in an associated
3938 // class.
3939 bool Visible = false;
3940 for (D = D->getMostRecentDecl(); D;
3941 D = cast_or_null<NamedDecl>(Val: D->getPreviousDecl())) {
3942 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3943 if (isVisible(D)) {
3944 Visible = true;
3945 break;
3946 }
3947
3948 if (!D->getOwningModule() ||
3949 !D->getOwningModule()->getTopLevelModule()->isNamedModule())
3950 continue;
3951
3952 if (D->isInExportDeclContext()) {
3953 Module *FM = D->getOwningModule();
3954 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
3955 // exports are only valid in module purview and outside of any
3956 // PMF (although a PMF should not even be present in a module
3957 // with an import).
3958 assert(FM &&
3959 (FM->isNamedModule() || FM->isImplicitGlobalModule()) &&
3960 !FM->isPrivateModule() && "bad export context");
3961 // .. are attached to a named module M, do not appear in the
3962 // translation unit containing the point of the lookup..
3963 if (D->isInAnotherModuleUnit() &&
3964 llvm::any_of(Range&: AssociatedClasses, P: [&](auto *E) {
3965 // ... and have the same innermost enclosing non-inline
3966 // namespace scope as a declaration of an associated entity
3967 // attached to M
3968 if (E->getOwningModule() != FM)
3969 return false;
3970 // TODO: maybe this could be cached when generating the
3971 // associated namespaces / entities.
3972 DeclContext *Ctx = E->getDeclContext();
3973 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
3974 Ctx = Ctx->getParent();
3975 return Ctx == NS;
3976 })) {
3977 Visible = true;
3978 break;
3979 }
3980 }
3981 }
3982
3983 if (D->getFriendObjectKind()) {
3984 auto *RD = cast<CXXRecordDecl>(Val: D->getLexicalDeclContext());
3985 // [basic.lookup.argdep]p4:
3986 // Argument-dependent lookup finds all declarations of functions and
3987 // function templates that
3988 // - ...
3989 // - are declared as a friend ([class.friend]) of any class with a
3990 // reachable definition in the set of associated entities,
3991 //
3992 // FIXME: If there's a merged definition of D that is reachable, then
3993 // the friend declaration should be considered.
3994 if (AssociatedClasses.count(key: RD) && isReachable(D)) {
3995 Visible = true;
3996 break;
3997 }
3998 }
3999 }
4000
4001 // FIXME: Preserve D as the FoundDecl.
4002 if (Visible)
4003 Result.insert(New: Underlying);
4004 }
4005 }
4006}
4007
4008//----------------------------------------------------------------------------
4009// Search for all visible declarations.
4010//----------------------------------------------------------------------------
4011VisibleDeclConsumer::~VisibleDeclConsumer() { }
4012
4013bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
4014
4015namespace {
4016
4017class ShadowContextRAII;
4018
4019class VisibleDeclsRecord {
4020public:
4021 /// An entry in the shadow map, which is optimized to store a
4022 /// single declaration (the common case) but can also store a list
4023 /// of declarations.
4024 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
4025
4026private:
4027 /// A mapping from declaration names to the declarations that have
4028 /// this name within a particular scope.
4029 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
4030
4031 /// A list of shadow maps, which is used to model name hiding.
4032 std::list<ShadowMap> ShadowMaps;
4033
4034 /// The declaration contexts we have already visited.
4035 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
4036
4037 friend class ShadowContextRAII;
4038
4039public:
4040 /// Determine whether we have already visited this context
4041 /// (and, if not, note that we are going to visit that context now).
4042 bool visitedContext(DeclContext *Ctx) {
4043 return !VisitedContexts.insert(Ptr: Ctx).second;
4044 }
4045
4046 bool alreadyVisitedContext(DeclContext *Ctx) {
4047 return VisitedContexts.count(Ptr: Ctx);
4048 }
4049
4050 /// Determine whether the given declaration is hidden in the
4051 /// current scope.
4052 ///
4053 /// \returns the declaration that hides the given declaration, or
4054 /// NULL if no such declaration exists.
4055 NamedDecl *checkHidden(NamedDecl *ND);
4056
4057 /// Add a declaration to the current shadow map.
4058 void add(NamedDecl *ND) {
4059 ShadowMaps.back()[ND->getDeclName()].push_back(NewVal: ND);
4060 }
4061};
4062
4063/// RAII object that records when we've entered a shadow context.
4064class ShadowContextRAII {
4065 VisibleDeclsRecord &Visible;
4066
4067 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
4068
4069public:
4070 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
4071 Visible.ShadowMaps.emplace_back();
4072 }
4073
4074 ~ShadowContextRAII() {
4075 Visible.ShadowMaps.pop_back();
4076 }
4077};
4078
4079} // end anonymous namespace
4080
4081NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
4082 unsigned IDNS = ND->getIdentifierNamespace();
4083 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
4084 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
4085 SM != SMEnd; ++SM) {
4086 ShadowMap::iterator Pos = SM->find(Val: ND->getDeclName());
4087 if (Pos == SM->end())
4088 continue;
4089
4090 for (auto *D : Pos->second) {
4091 // A tag declaration does not hide a non-tag declaration.
4092 if (D->hasTagIdentifierNamespace() &&
4093 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
4094 Decl::IDNS_ObjCProtocol)))
4095 continue;
4096
4097 // Protocols are in distinct namespaces from everything else.
4098 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
4099 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
4100 D->getIdentifierNamespace() != IDNS)
4101 continue;
4102
4103 // Functions and function templates in the same scope overload
4104 // rather than hide. FIXME: Look for hiding based on function
4105 // signatures!
4106 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4107 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4108 SM == ShadowMaps.rbegin())
4109 continue;
4110
4111 // A shadow declaration that's created by a resolved using declaration
4112 // is not hidden by the same using declaration.
4113 if (isa<UsingShadowDecl>(Val: ND) && isa<UsingDecl>(Val: D) &&
4114 cast<UsingShadowDecl>(Val: ND)->getIntroducer() == D)
4115 continue;
4116
4117 // We've found a declaration that hides this one.
4118 return D;
4119 }
4120 }
4121
4122 return nullptr;
4123}
4124
4125namespace {
4126class LookupVisibleHelper {
4127public:
4128 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
4129 bool LoadExternal)
4130 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4131 LoadExternal(LoadExternal) {}
4132
4133 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4134 bool IncludeGlobalScope) {
4135 // Determine the set of using directives available during
4136 // unqualified name lookup.
4137 Scope *Initial = S;
4138 UnqualUsingDirectiveSet UDirs(SemaRef);
4139 if (SemaRef.getLangOpts().CPlusPlus) {
4140 // Find the first namespace or translation-unit scope.
4141 while (S && !isNamespaceOrTranslationUnitScope(S))
4142 S = S->getParent();
4143
4144 UDirs.visitScopeChain(S: Initial, InnermostFileScope: S);
4145 }
4146 UDirs.done();
4147
4148 // Look for visible declarations.
4149 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4150 Result.setAllowHidden(Consumer.includeHiddenDecls());
4151 if (!IncludeGlobalScope)
4152 Visited.visitedContext(Ctx: SemaRef.getASTContext().getTranslationUnitDecl());
4153 ShadowContextRAII Shadow(Visited);
4154 lookupInScope(S: Initial, Result, UDirs);
4155 }
4156
4157 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4158 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4159 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4160 Result.setAllowHidden(Consumer.includeHiddenDecls());
4161 if (!IncludeGlobalScope)
4162 Visited.visitedContext(Ctx: SemaRef.getASTContext().getTranslationUnitDecl());
4163
4164 ShadowContextRAII Shadow(Visited);
4165 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4166 /*InBaseClass=*/false);
4167 }
4168
4169private:
4170 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4171 bool QualifiedNameLookup, bool InBaseClass) {
4172 if (!Ctx)
4173 return;
4174
4175 // Make sure we don't visit the same context twice.
4176 if (Visited.visitedContext(Ctx: Ctx->getPrimaryContext()))
4177 return;
4178
4179 Consumer.EnteredContext(Ctx);
4180
4181 // Outside C++, lookup results for the TU live on identifiers.
4182 if (isa<TranslationUnitDecl>(Val: Ctx) &&
4183 !Result.getSema().getLangOpts().CPlusPlus) {
4184 auto &S = Result.getSema();
4185 auto &Idents = S.Context.Idents;
4186
4187 // Ensure all external identifiers are in the identifier table.
4188 if (LoadExternal)
4189 if (IdentifierInfoLookup *External =
4190 Idents.getExternalIdentifierLookup()) {
4191 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4192 for (StringRef Name = Iter->Next(); !Name.empty();
4193 Name = Iter->Next())
4194 Idents.get(Name);
4195 }
4196
4197 // Walk all lookup results in the TU for each identifier.
4198 for (const auto &Ident : Idents) {
4199 for (auto I = S.IdResolver.begin(Name: Ident.getValue()),
4200 E = S.IdResolver.end();
4201 I != E; ++I) {
4202 if (S.IdResolver.isDeclInScope(D: *I, Ctx)) {
4203 if (NamedDecl *ND = Result.getAcceptableDecl(D: *I)) {
4204 Consumer.FoundDecl(ND, Hiding: Visited.checkHidden(ND), Ctx, InBaseClass);
4205 Visited.add(ND);
4206 }
4207 }
4208 }
4209 }
4210
4211 return;
4212 }
4213
4214 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: Ctx))
4215 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4216
4217 llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;
4218 // We sometimes skip loading namespace-level results (they tend to be huge).
4219 bool Load = LoadExternal ||
4220 !(isa<TranslationUnitDecl>(Val: Ctx) || isa<NamespaceDecl>(Val: Ctx));
4221 // Enumerate all of the results in this context.
4222 for (DeclContextLookupResult R :
4223 Load ? Ctx->lookups()
4224 : Ctx->noload_lookups(/*PreserveInternalState=*/false))
4225 for (auto *D : R)
4226 // Rather than visit immediately, we put ND into a vector and visit
4227 // all decls, in order, outside of this loop. The reason is that
4228 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)
4229 // may invalidate the iterators used in the two
4230 // loops above.
4231 DeclsToVisit.push_back(Elt: D);
4232
4233 for (auto *D : DeclsToVisit)
4234 if (auto *ND = Result.getAcceptableDecl(D)) {
4235 Consumer.FoundDecl(ND, Hiding: Visited.checkHidden(ND), Ctx, InBaseClass);
4236 Visited.add(ND);
4237 }
4238
4239 DeclsToVisit.clear();
4240
4241 // Traverse using directives for qualified name lookup.
4242 if (QualifiedNameLookup) {
4243 ShadowContextRAII Shadow(Visited);
4244 for (auto *I : Ctx->using_directives()) {
4245 if (!Result.getSema().isVisible(D: I))
4246 continue;
4247 lookupInDeclContext(Ctx: I->getNominatedNamespace(), Result,
4248 QualifiedNameLookup, InBaseClass);
4249 }
4250 }
4251
4252 // Traverse the contexts of inherited C++ classes.
4253 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
4254 if (!Record->hasDefinition())
4255 return;
4256
4257 for (const auto &B : Record->bases()) {
4258 QualType BaseType = B.getType();
4259
4260 RecordDecl *RD;
4261 if (BaseType->isDependentType()) {
4262 if (!IncludeDependentBases) {
4263 // Don't look into dependent bases, because name lookup can't look
4264 // there anyway.
4265 continue;
4266 }
4267 // Look through an alias template, whose TemplateName is a
4268 // TypeAliasTemplateDecl rather than the ClassTemplateDecl we are
4269 // after; otherwise the base is skipped entirely.
4270 const auto *TST = BaseType->getAsNonAliasTemplateSpecializationType();
4271 if (!TST)
4272 continue;
4273 TemplateName TN = TST->getTemplateName();
4274 const auto *TD =
4275 dyn_cast_or_null<ClassTemplateDecl>(Val: TN.getAsTemplateDecl());
4276 if (!TD)
4277 continue;
4278 RD = TD->getTemplatedDecl();
4279 } else {
4280 RD = BaseType->getAsCXXRecordDecl();
4281 if (!RD)
4282 continue;
4283 }
4284
4285 // FIXME: It would be nice to be able to determine whether referencing
4286 // a particular member would be ambiguous. For example, given
4287 //
4288 // struct A { int member; };
4289 // struct B { int member; };
4290 // struct C : A, B { };
4291 //
4292 // void f(C *c) { c->### }
4293 //
4294 // accessing 'member' would result in an ambiguity. However, we
4295 // could be smart enough to qualify the member with the base
4296 // class, e.g.,
4297 //
4298 // c->B::member
4299 //
4300 // or
4301 //
4302 // c->A::member
4303
4304 // Find results in this base class (and its bases).
4305 ShadowContextRAII Shadow(Visited);
4306 lookupInDeclContext(Ctx: RD, Result, QualifiedNameLookup,
4307 /*InBaseClass=*/true);
4308 }
4309 }
4310
4311 // Traverse the contexts of Objective-C classes.
4312 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Val: Ctx)) {
4313 // Traverse categories.
4314 for (auto *Cat : IFace->visible_categories()) {
4315 ShadowContextRAII Shadow(Visited);
4316 lookupInDeclContext(Ctx: Cat, Result, QualifiedNameLookup,
4317 /*InBaseClass=*/false);
4318 }
4319
4320 // Traverse protocols.
4321 for (auto *I : IFace->all_referenced_protocols()) {
4322 ShadowContextRAII Shadow(Visited);
4323 lookupInDeclContext(Ctx: I, Result, QualifiedNameLookup,
4324 /*InBaseClass=*/false);
4325 }
4326
4327 // Traverse the superclass.
4328 if (IFace->getSuperClass()) {
4329 ShadowContextRAII Shadow(Visited);
4330 lookupInDeclContext(Ctx: IFace->getSuperClass(), Result, QualifiedNameLookup,
4331 /*InBaseClass=*/true);
4332 }
4333
4334 // If there is an implementation, traverse it. We do this to find
4335 // synthesized ivars.
4336 if (IFace->getImplementation()) {
4337 ShadowContextRAII Shadow(Visited);
4338 lookupInDeclContext(Ctx: IFace->getImplementation(), Result,
4339 QualifiedNameLookup, InBaseClass);
4340 }
4341 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Val: Ctx)) {
4342 for (auto *I : Protocol->protocols()) {
4343 ShadowContextRAII Shadow(Visited);
4344 lookupInDeclContext(Ctx: I, Result, QualifiedNameLookup,
4345 /*InBaseClass=*/false);
4346 }
4347 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Val: Ctx)) {
4348 for (auto *I : Category->protocols()) {
4349 ShadowContextRAII Shadow(Visited);
4350 lookupInDeclContext(Ctx: I, Result, QualifiedNameLookup,
4351 /*InBaseClass=*/false);
4352 }
4353
4354 // If there is an implementation, traverse it.
4355 if (Category->getImplementation()) {
4356 ShadowContextRAII Shadow(Visited);
4357 lookupInDeclContext(Ctx: Category->getImplementation(), Result,
4358 QualifiedNameLookup, /*InBaseClass=*/true);
4359 }
4360 }
4361 }
4362
4363 void lookupInScope(Scope *S, LookupResult &Result,
4364 UnqualUsingDirectiveSet &UDirs) {
4365 // No clients run in this mode and it's not supported. Please add tests and
4366 // remove the assertion if you start relying on it.
4367 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4368
4369 if (!S)
4370 return;
4371
4372 if (!S->getEntity() ||
4373 (!S->getParent() && !Visited.alreadyVisitedContext(Ctx: S->getEntity())) ||
4374 (S->getEntity())->isFunctionOrMethod()) {
4375 FindLocalExternScope FindLocals(Result);
4376 // Walk through the declarations in this Scope. The consumer might add new
4377 // decls to the scope as part of deserialization, so make a copy first.
4378 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4379 for (Decl *D : ScopeDecls) {
4380 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: D))
4381 if ((ND = Result.getAcceptableDecl(D: ND))) {
4382 Consumer.FoundDecl(ND, Hiding: Visited.checkHidden(ND), Ctx: nullptr, InBaseClass: false);
4383 Visited.add(ND);
4384 }
4385 }
4386 }
4387
4388 DeclContext *Entity = S->getLookupEntity();
4389 if (Entity) {
4390 // Look into this scope's declaration context, along with any of its
4391 // parent lookup contexts (e.g., enclosing classes), up to the point
4392 // where we hit the context stored in the next outer scope.
4393 DeclContext *OuterCtx = findOuterContext(S);
4394
4395 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(DC: OuterCtx);
4396 Ctx = Ctx->getLookupParent()) {
4397 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Val: Ctx)) {
4398 if (Method->isInstanceMethod()) {
4399 // For instance methods, look for ivars in the method's interface.
4400 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4401 Result.getNameLoc(),
4402 Sema::LookupMemberName);
4403 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4404 lookupInDeclContext(Ctx: IFace, Result&: IvarResult,
4405 /*QualifiedNameLookup=*/false,
4406 /*InBaseClass=*/false);
4407 }
4408 }
4409
4410 // We've already performed all of the name lookup that we need
4411 // to for Objective-C methods; the next context will be the
4412 // outer scope.
4413 break;
4414 }
4415
4416 if (Ctx->isFunctionOrMethod())
4417 continue;
4418
4419 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4420 /*InBaseClass=*/false);
4421 }
4422 } else if (!S->getParent()) {
4423 // Look into the translation unit scope. We walk through the translation
4424 // unit's declaration context, because the Scope itself won't have all of
4425 // the declarations if we loaded a precompiled header.
4426 // FIXME: We would like the translation unit's Scope object to point to
4427 // the translation unit, so we don't need this special "if" branch.
4428 // However, doing so would force the normal C++ name-lookup code to look
4429 // into the translation unit decl when the IdentifierInfo chains would
4430 // suffice. Once we fix that problem (which is part of a more general
4431 // "don't look in DeclContexts unless we have to" optimization), we can
4432 // eliminate this.
4433 Entity = Result.getSema().Context.getTranslationUnitDecl();
4434 lookupInDeclContext(Ctx: Entity, Result, /*QualifiedNameLookup=*/false,
4435 /*InBaseClass=*/false);
4436 }
4437
4438 if (Entity) {
4439 // Lookup visible declarations in any namespaces found by using
4440 // directives.
4441 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(DC: Entity))
4442 lookupInDeclContext(
4443 Ctx: const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4444 /*QualifiedNameLookup=*/false,
4445 /*InBaseClass=*/false);
4446 }
4447
4448 // Lookup names in the parent scope.
4449 ShadowContextRAII Shadow(Visited);
4450 lookupInScope(S: S->getParent(), Result, UDirs);
4451 }
4452
4453private:
4454 VisibleDeclsRecord Visited;
4455 VisibleDeclConsumer &Consumer;
4456 bool IncludeDependentBases;
4457 bool LoadExternal;
4458};
4459} // namespace
4460
4461void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4462 VisibleDeclConsumer &Consumer,
4463 bool IncludeGlobalScope, bool LoadExternal) {
4464 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4465 LoadExternal);
4466 H.lookupVisibleDecls(SemaRef&: *this, S, Kind, IncludeGlobalScope);
4467}
4468
4469void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4470 VisibleDeclConsumer &Consumer,
4471 bool IncludeGlobalScope,
4472 bool IncludeDependentBases, bool LoadExternal) {
4473 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4474 H.lookupVisibleDecls(SemaRef&: *this, Ctx, Kind, IncludeGlobalScope);
4475}
4476
4477LabelDecl *Sema::LookupExistingLabel(IdentifierInfo *II, SourceLocation Loc) {
4478 NamedDecl *Res = LookupSingleName(S: CurScope, Name: II, Loc, NameKind: LookupLabel,
4479 Redecl: RedeclarationKind::NotForRedeclaration);
4480 // If we found a label, check to see if it is in the same context as us.
4481 // When in a Block, we don't want to reuse a label in an enclosing function.
4482 if (!Res ||
4483 Res->getDeclContext()->getEnclosingNonExpansionStatementContext() !=
4484 CurContext->getEnclosingNonExpansionStatementContext())
4485 return nullptr;
4486 return cast<LabelDecl>(Val: Res);
4487}
4488
4489LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
4490 SourceLocation GnuLabelLoc,
4491 bool IsLabelStmt) {
4492 if (GnuLabelLoc.isValid()) {
4493 // Local label definitions always shadow existing labels.
4494 auto *Res = LabelDecl::Create(C&: Context, DC: CurContext, IdentL: Loc, II, GnuLabelL: GnuLabelLoc);
4495 Scope *S = CurScope;
4496 PushOnScopeChains(D: Res, S, AddToContext: true);
4497 return cast<LabelDecl>(Val: Res);
4498 }
4499
4500 LabelDecl *Existing = LookupExistingLabel(II, Loc);
4501
4502 // C++26 [stmt.label]p4 An identifier label shall not be enclosed by an
4503 // expansion-statement.
4504 //
4505 // As an extension, we allow GNU local labels since they are logically
4506 // scoped to the containing block, which prevents us from ending up with
4507 // multiple copies of the same label in a function after instantiation.
4508 //
4509 // While allowing this is slightly more complicated, it also has the nice
4510 // side-effect of avoiding otherwise rather horrible diagnostics you'd get
4511 // when trying to use '__label__' if we didn't support this.
4512 if (IsLabelStmt && CurContext->isExpansionStmt()) {
4513 if (Existing && Existing->isGnuLocal())
4514 return Existing;
4515
4516 // Drop the label from the AST as creating it anyway would cause us to
4517 // either issue various unhelpful diagnostics (if we were to declare
4518 // it in the function decl context) or shadow a valid label with the
4519 // same name outside the expansion statement.
4520 Diag(Loc, DiagID: diag::err_expansion_stmt_label);
4521 return nullptr;
4522 }
4523
4524 if (Existing)
4525 return Existing;
4526
4527 // Declare non-local labels outside any expansion statements; this is required
4528 // to support jumping out of an expansion statement.
4529 ContextRAII Ctx{*this, CurContext->getEnclosingNonExpansionStatementContext(),
4530 /*NewThisContext=*/false};
4531
4532 // Not a GNU local label. Create the backing decl.
4533 auto *Res = LabelDecl::Create(C&: Context, DC: CurContext, IdentL: Loc, II);
4534 Scope *S = CurScope->getFnParent();
4535 assert(S && "Not in a function?");
4536 PushOnScopeChains(D: Res, S, AddToContext: true);
4537 return Res;
4538}
4539
4540//===----------------------------------------------------------------------===//
4541// Typo correction
4542//===----------------------------------------------------------------------===//
4543
4544static bool isCandidateViable(CorrectionCandidateCallback &CCC,
4545 TypoCorrection &Candidate) {
4546 Candidate.setCallbackDistance(CCC.RankCandidate(candidate: Candidate));
4547 return Candidate.getEditDistance(Normalized: false) != TypoCorrection::InvalidDistance;
4548}
4549
4550static void LookupPotentialTypoResult(Sema &SemaRef,
4551 LookupResult &Res,
4552 IdentifierInfo *Name,
4553 Scope *S, CXXScopeSpec *SS,
4554 DeclContext *MemberContext,
4555 bool EnteringContext,
4556 bool isObjCIvarLookup,
4557 bool FindHidden);
4558
4559/// Check whether the declarations found for a typo correction are
4560/// visible. Set the correction's RequiresImport flag to true if none of the
4561/// declarations are visible, false otherwise.
4562static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
4563 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4564
4565 for (/**/; DI != DE; ++DI)
4566 if (!LookupResult::isVisible(SemaRef, D: *DI))
4567 break;
4568 // No filtering needed if all decls are visible.
4569 if (DI == DE) {
4570 TC.setRequiresImport(false);
4571 return;
4572 }
4573
4574 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4575 bool AnyVisibleDecls = !NewDecls.empty();
4576
4577 for (/**/; DI != DE; ++DI) {
4578 if (LookupResult::isVisible(SemaRef, D: *DI)) {
4579 if (!AnyVisibleDecls) {
4580 // Found a visible decl, discard all hidden ones.
4581 AnyVisibleDecls = true;
4582 NewDecls.clear();
4583 }
4584 NewDecls.push_back(Elt: *DI);
4585 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4586 NewDecls.push_back(Elt: *DI);
4587 }
4588
4589 if (NewDecls.empty())
4590 TC = TypoCorrection();
4591 else {
4592 TC.setCorrectionDecls(NewDecls);
4593 TC.setRequiresImport(!AnyVisibleDecls);
4594 }
4595}
4596
4597// Fill the supplied vector with the IdentifierInfo pointers for each piece of
4598// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4599// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4600static void getNestedNameSpecifierIdentifiers(
4601 NestedNameSpecifier NNS,
4602 SmallVectorImpl<const IdentifierInfo *> &Identifiers) {
4603 switch (NNS.getKind()) {
4604 case NestedNameSpecifier::Kind::Null:
4605 Identifiers.clear();
4606 return;
4607
4608 case NestedNameSpecifier::Kind::Namespace: {
4609 auto [Namespace, Prefix] = NNS.getAsNamespaceAndPrefix();
4610 getNestedNameSpecifierIdentifiers(NNS: Prefix, Identifiers);
4611 if (const auto *NS = dyn_cast<NamespaceDecl>(Val: Namespace);
4612 NS && NS->isAnonymousNamespace())
4613 return;
4614 Identifiers.push_back(Elt: Namespace->getIdentifier());
4615 return;
4616 }
4617
4618 case NestedNameSpecifier::Kind::Type: {
4619 for (const Type *T = NNS.getAsType(); /**/; /**/) {
4620 switch (T->getTypeClass()) {
4621 case Type::DependentName: {
4622 auto *DT = cast<DependentNameType>(Val: T);
4623 getNestedNameSpecifierIdentifiers(NNS: DT->getQualifier(), Identifiers);
4624 Identifiers.push_back(Elt: DT->getIdentifier());
4625 return;
4626 }
4627 case Type::TemplateSpecialization: {
4628 TemplateName Name =
4629 cast<TemplateSpecializationType>(Val: T)->getTemplateName();
4630 if (const DependentTemplateName *DTN =
4631 Name.getAsDependentTemplateName()) {
4632 getNestedNameSpecifierIdentifiers(NNS: DTN->getQualifier(), Identifiers);
4633 if (const auto *II = DTN->getName().getIdentifier())
4634 Identifiers.push_back(Elt: II);
4635 return;
4636 }
4637 if (const QualifiedTemplateName *QTN =
4638 Name.getAsQualifiedTemplateName()) {
4639 getNestedNameSpecifierIdentifiers(NNS: QTN->getQualifier(), Identifiers);
4640 Name = QTN->getUnderlyingTemplate();
4641 }
4642 if (const auto *TD = Name.getAsTemplateDecl(/*IgnoreDeduced=*/true))
4643 Identifiers.push_back(Elt: TD->getIdentifier());
4644 return;
4645 }
4646 case Type::SubstTemplateTypeParm:
4647 T = cast<SubstTemplateTypeParmType>(Val: T)
4648 ->getReplacementType()
4649 .getTypePtr();
4650 continue;
4651 case Type::TemplateTypeParm:
4652 Identifiers.push_back(Elt: cast<TemplateTypeParmType>(Val: T)->getIdentifier());
4653 return;
4654 case Type::Decltype:
4655 return;
4656 case Type::Enum:
4657 case Type::Record:
4658 case Type::InjectedClassName: {
4659 auto *TT = cast<TagType>(Val: T);
4660 getNestedNameSpecifierIdentifiers(NNS: TT->getQualifier(), Identifiers);
4661 Identifiers.push_back(Elt: TT->getDecl()->getIdentifier());
4662 return;
4663 }
4664 case Type::Typedef: {
4665 auto *TT = cast<TypedefType>(Val: T);
4666 getNestedNameSpecifierIdentifiers(NNS: TT->getQualifier(), Identifiers);
4667 Identifiers.push_back(Elt: TT->getDecl()->getIdentifier());
4668 return;
4669 }
4670 case Type::Using: {
4671 auto *TT = cast<UsingType>(Val: T);
4672 getNestedNameSpecifierIdentifiers(NNS: TT->getQualifier(), Identifiers);
4673 Identifiers.push_back(Elt: TT->getDecl()->getIdentifier());
4674 return;
4675 }
4676 case Type::UnresolvedUsing: {
4677 auto *TT = cast<UnresolvedUsingType>(Val: T);
4678 getNestedNameSpecifierIdentifiers(NNS: TT->getQualifier(), Identifiers);
4679 Identifiers.push_back(Elt: TT->getDecl()->getIdentifier());
4680 return;
4681 }
4682 default:
4683 Identifiers.push_back(Elt: QualType(T, 0).getBaseTypeIdentifier());
4684 return;
4685 }
4686 }
4687 break;
4688 }
4689
4690 case NestedNameSpecifier::Kind::Global:
4691 case NestedNameSpecifier::Kind::MicrosoftSuper:
4692 return;
4693 }
4694}
4695
4696void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
4697 DeclContext *Ctx, bool InBaseClass) {
4698 // Don't consider hidden names for typo correction.
4699 if (Hiding)
4700 return;
4701
4702 // Only consider entities with identifiers for names, ignoring
4703 // special names (constructors, overloaded operators, selectors,
4704 // etc.).
4705 IdentifierInfo *Name = ND->getIdentifier();
4706 if (!Name)
4707 return;
4708
4709 // Only consider visible declarations and declarations from modules with
4710 // names that exactly match.
4711 if (!LookupResult::isVisible(SemaRef, D: ND) && Name != Typo)
4712 return;
4713
4714 FoundName(Name: Name->getName());
4715}
4716
4717void TypoCorrectionConsumer::FoundName(StringRef Name) {
4718 // Compute the edit distance between the typo and the name of this
4719 // entity, and add the identifier to the list of results.
4720 addName(Name, ND: nullptr);
4721}
4722
4723void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4724 // Compute the edit distance between the typo and this keyword,
4725 // and add the keyword to the list of results.
4726 addName(Name: Keyword, /*ND=*/nullptr, /*NNS=*/std::nullopt, /*isKeyword=*/true);
4727}
4728
4729void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4730 NestedNameSpecifier NNS, bool isKeyword) {
4731 // Use a simple length-based heuristic to determine the minimum possible
4732 // edit distance. If the minimum isn't good enough, bail out early.
4733 StringRef TypoStr = Typo->getName();
4734 unsigned MinED = abs(x: (int)Name.size() - (int)TypoStr.size());
4735 if (MinED && TypoStr.size() / MinED < 3)
4736 return;
4737
4738 // Compute an upper bound on the allowable edit distance, so that the
4739 // edit-distance algorithm can short-circuit.
4740 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4741 unsigned ED = TypoStr.edit_distance(Other: Name, AllowReplacements: true, MaxEditDistance: UpperBound);
4742 if (ED > UpperBound) return;
4743
4744 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4745 if (isKeyword) TC.makeKeyword();
4746 TC.setCorrectionRange(SS: nullptr, TypoName: Result.getLookupNameInfo());
4747 addCorrection(Correction: TC);
4748}
4749
4750static const unsigned MaxTypoDistanceResultSets = 5;
4751
4752void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
4753 StringRef TypoStr = Typo->getName();
4754 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4755
4756 // For very short typos, ignore potential corrections that have a different
4757 // base identifier from the typo or which have a normalized edit distance
4758 // longer than the typo itself.
4759 if (TypoStr.size() < 3 &&
4760 (Name != TypoStr || Correction.getEditDistance(Normalized: true) > TypoStr.size()))
4761 return;
4762
4763 // If the correction is resolved but is not viable, ignore it.
4764 if (Correction.isResolved()) {
4765 checkCorrectionVisibility(SemaRef, TC&: Correction);
4766 if (!Correction || !isCandidateViable(CCC&: *CorrectionValidator, Candidate&: Correction))
4767 return;
4768 }
4769
4770 TypoResultList &CList =
4771 CorrectionResults[Correction.getEditDistance(Normalized: false)][Name];
4772
4773 if (!CList.empty() && !CList.back().isResolved())
4774 CList.pop_back();
4775 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4776 auto RI = llvm::find_if(Range&: CList, P: [NewND](const TypoCorrection &TypoCorr) {
4777 return TypoCorr.getCorrectionDecl() == NewND;
4778 });
4779 if (RI != CList.end()) {
4780 // The Correction refers to a decl already in the list. No insertion is
4781 // necessary and all further cases will return.
4782
4783 auto IsDeprecated = [](Decl *D) {
4784 while (D) {
4785 if (D->isDeprecated())
4786 return true;
4787 D = llvm::dyn_cast_or_null<NamespaceDecl>(Val: D->getDeclContext());
4788 }
4789 return false;
4790 };
4791
4792 // Prefer non deprecated Corrections over deprecated and only then
4793 // sort using an alphabetical order.
4794 std::pair<bool, std::string> NewKey = {
4795 IsDeprecated(Correction.getFoundDecl()),
4796 Correction.getAsString(LO: SemaRef.getLangOpts())};
4797
4798 std::pair<bool, std::string> PrevKey = {
4799 IsDeprecated(RI->getFoundDecl()),
4800 RI->getAsString(LO: SemaRef.getLangOpts())};
4801
4802 if (NewKey < PrevKey)
4803 *RI = std::move(Correction);
4804 return;
4805 }
4806 }
4807 if (CList.empty() || Correction.isResolved())
4808 CList.push_back(Elt: Correction);
4809
4810 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4811 CorrectionResults.erase(position: std::prev(x: CorrectionResults.end()));
4812}
4813
4814void TypoCorrectionConsumer::addNamespaces(
4815 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4816 SearchNamespaces = true;
4817
4818 for (auto KNPair : KnownNamespaces)
4819 Namespaces.addNameSpecifier(Ctx: KNPair.first);
4820
4821 bool SSIsTemplate = false;
4822 if (NestedNameSpecifier NNS = (SS ? SS->getScopeRep() : std::nullopt)) {
4823 if (NNS.getKind() == NestedNameSpecifier::Kind::Type)
4824 SSIsTemplate =
4825 NNS.getAsType()->getTypeClass() == Type::TemplateSpecialization;
4826 }
4827 // Do not transform this into an iterator-based loop. The loop body can
4828 // trigger the creation of further types (through lazy deserialization) and
4829 // invalid iterators into this list.
4830 auto &Types = SemaRef.getASTContext().getTypes();
4831 for (unsigned I = 0; I != Types.size(); ++I) {
4832 const auto *TI = Types[I];
4833 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4834 CD = CD->getCanonicalDecl();
4835 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4836 !CD->isUnion() && CD->getIdentifier() &&
4837 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(Val: CD)) &&
4838 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4839 Namespaces.addNameSpecifier(Ctx: CD);
4840 }
4841 }
4842}
4843
4844const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4845 if (++CurrentTCIndex < ValidatedCorrections.size())
4846 return ValidatedCorrections[CurrentTCIndex];
4847
4848 CurrentTCIndex = ValidatedCorrections.size();
4849 while (!CorrectionResults.empty()) {
4850 auto DI = CorrectionResults.begin();
4851 if (DI->second.empty()) {
4852 CorrectionResults.erase(position: DI);
4853 continue;
4854 }
4855
4856 auto RI = DI->second.begin();
4857 if (RI->second.empty()) {
4858 DI->second.erase(I: RI);
4859 performQualifiedLookups();
4860 continue;
4861 }
4862
4863 TypoCorrection TC = RI->second.pop_back_val();
4864 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(Candidate&: TC)) {
4865 ValidatedCorrections.push_back(Elt: TC);
4866 return ValidatedCorrections[CurrentTCIndex];
4867 }
4868 }
4869 return ValidatedCorrections[0]; // The empty correction.
4870}
4871
4872bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4873 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4874 DeclContext *TempMemberContext = MemberContext;
4875 CXXScopeSpec *TempSS = SS.get();
4876retry_lookup:
4877 LookupPotentialTypoResult(SemaRef, Res&: Result, Name, S, SS: TempSS, MemberContext: TempMemberContext,
4878 EnteringContext,
4879 isObjCIvarLookup: CorrectionValidator->IsObjCIvarLookup,
4880 FindHidden: Name == Typo && !Candidate.WillReplaceSpecifier());
4881 switch (Result.getResultKind()) {
4882 case LookupResultKind::NotFound:
4883 case LookupResultKind::NotFoundInCurrentInstantiation:
4884 case LookupResultKind::FoundUnresolvedValue:
4885 if (TempSS) {
4886 // Immediately retry the lookup without the given CXXScopeSpec
4887 TempSS = nullptr;
4888 Candidate.WillReplaceSpecifier(ForceReplacement: true);
4889 goto retry_lookup;
4890 }
4891 if (TempMemberContext) {
4892 if (SS && !TempSS)
4893 TempSS = SS.get();
4894 TempMemberContext = nullptr;
4895 goto retry_lookup;
4896 }
4897 if (SearchNamespaces)
4898 QualifiedResults.push_back(Elt: Candidate);
4899 break;
4900
4901 case LookupResultKind::Ambiguous:
4902 // We don't deal with ambiguities.
4903 break;
4904
4905 case LookupResultKind::Found:
4906 case LookupResultKind::FoundOverloaded:
4907 // Store all of the Decls for overloaded symbols
4908 for (auto *TRD : Result)
4909 Candidate.addCorrectionDecl(CDecl: TRD);
4910 checkCorrectionVisibility(SemaRef, TC&: Candidate);
4911 if (!isCandidateViable(CCC&: *CorrectionValidator, Candidate)) {
4912 if (SearchNamespaces)
4913 QualifiedResults.push_back(Elt: Candidate);
4914 break;
4915 }
4916 Candidate.setCorrectionRange(SS: SS.get(), TypoName: Result.getLookupNameInfo());
4917 return true;
4918 }
4919 return false;
4920}
4921
4922void TypoCorrectionConsumer::performQualifiedLookups() {
4923 unsigned TypoLen = Typo->getName().size();
4924 for (const TypoCorrection &QR : QualifiedResults) {
4925 for (const auto &NSI : Namespaces) {
4926 DeclContext *Ctx = NSI.DeclCtx;
4927 CXXRecordDecl *NamingClass = NSI.NameSpecifier.getAsRecordDecl();
4928
4929 // If the current NestedNameSpecifier refers to a class and the
4930 // current correction candidate is the name of that class, then skip
4931 // it as it is unlikely a qualified version of the class' constructor
4932 // is an appropriate correction.
4933 if (NamingClass &&
4934 NamingClass->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4935 continue;
4936
4937 TypoCorrection TC(QR);
4938 TC.ClearCorrectionDecls();
4939 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4940 TC.setQualifierDistance(NSI.EditDistance);
4941 TC.setCallbackDistance(0); // Reset the callback distance
4942
4943 // If the current correction candidate and namespace combination are
4944 // too far away from the original typo based on the normalized edit
4945 // distance, then skip performing a qualified name lookup.
4946 unsigned TmpED = TC.getEditDistance(Normalized: true);
4947 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4948 TypoLen / TmpED < 3)
4949 continue;
4950
4951 Result.clear();
4952 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4953 if (!SemaRef.LookupQualifiedName(R&: Result, LookupCtx: Ctx))
4954 continue;
4955
4956 // Any corrections added below will be validated in subsequent
4957 // iterations of the main while() loop over the Consumer's contents.
4958 switch (Result.getResultKind()) {
4959 case LookupResultKind::Found:
4960 case LookupResultKind::FoundOverloaded: {
4961 if (SS && SS->isValid()) {
4962 std::string NewQualified = TC.getAsString(LO: SemaRef.getLangOpts());
4963 std::string OldQualified;
4964 llvm::raw_string_ostream OldOStream(OldQualified);
4965 SS->getScopeRep().print(OS&: OldOStream, Policy: SemaRef.getPrintingPolicy());
4966 OldOStream << Typo->getName();
4967 // If correction candidate would be an identical written qualified
4968 // identifier, then the existing CXXScopeSpec probably included a
4969 // typedef that didn't get accounted for properly.
4970 if (OldOStream.str() == NewQualified)
4971 break;
4972 }
4973 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4974 TRD != TRDEnd; ++TRD) {
4975 if (SemaRef.CheckMemberAccess(UseLoc: TC.getCorrectionRange().getBegin(),
4976 NamingClass,
4977 Found: TRD.getPair()) == Sema::AR_accessible)
4978 TC.addCorrectionDecl(CDecl: *TRD);
4979 }
4980 if (TC.isResolved()) {
4981 TC.setCorrectionRange(SS: SS.get(), TypoName: Result.getLookupNameInfo());
4982 addCorrection(Correction: TC);
4983 }
4984 break;
4985 }
4986 case LookupResultKind::NotFound:
4987 case LookupResultKind::NotFoundInCurrentInstantiation:
4988 case LookupResultKind::Ambiguous:
4989 case LookupResultKind::FoundUnresolvedValue:
4990 break;
4991 }
4992 }
4993 }
4994 QualifiedResults.clear();
4995}
4996
4997TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4998 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4999 : Context(Context), CurContextChain(buildContextChain(Start: CurContext)) {
5000 if (NestedNameSpecifier NNS =
5001 CurScopeSpec ? CurScopeSpec->getScopeRep() : std::nullopt) {
5002 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
5003 NNS.print(OS&: SpecifierOStream, Policy: Context.getPrintingPolicy());
5004
5005 getNestedNameSpecifierIdentifiers(NNS, Identifiers&: CurNameSpecifierIdentifiers);
5006 }
5007 // Build the list of identifiers that would be used for an absolute
5008 // (from the global context) NestedNameSpecifier referring to the current
5009 // context.
5010 for (DeclContext *C : llvm::reverse(C&: CurContextChain)) {
5011 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(Val: C))
5012 CurContextIdentifiers.push_back(Elt: ND->getIdentifier());
5013 }
5014
5015 // Add the global context as a NestedNameSpecifier
5016 SpecifierInfo SI = {.DeclCtx: cast<DeclContext>(Val: Context.getTranslationUnitDecl()),
5017 .NameSpecifier: NestedNameSpecifier::getGlobal(), .EditDistance: 1};
5018 DistanceMap[1].push_back(Elt: SI);
5019}
5020
5021auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
5022 DeclContext *Start) -> DeclContextList {
5023 assert(Start && "Building a context chain from a null context");
5024 DeclContextList Chain;
5025 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
5026 DC = DC->getLookupParent()) {
5027 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(Val: DC);
5028 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
5029 !(ND && ND->isAnonymousNamespace()))
5030 Chain.push_back(Elt: DC->getPrimaryContext());
5031 }
5032 return Chain;
5033}
5034
5035unsigned
5036TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
5037 DeclContextList &DeclChain, NestedNameSpecifier &NNS) {
5038 unsigned NumSpecifiers = 0;
5039 for (DeclContext *C : llvm::reverse(C&: DeclChain)) {
5040 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(Val: C)) {
5041 NNS = NestedNameSpecifier(Context, ND, NNS);
5042 ++NumSpecifiers;
5043 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(Val: C)) {
5044 QualType T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier: NNS, TD: RD,
5045 /*OwnsTag=*/false);
5046 NNS = NestedNameSpecifier(T.getTypePtr());
5047 ++NumSpecifiers;
5048 }
5049 }
5050 return NumSpecifiers;
5051}
5052
5053void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
5054 DeclContext *Ctx) {
5055 NestedNameSpecifier NNS = std::nullopt;
5056 unsigned NumSpecifiers = 0;
5057 DeclContextList NamespaceDeclChain(buildContextChain(Start: Ctx));
5058 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
5059
5060 // Eliminate common elements from the two DeclContext chains.
5061 for (DeclContext *C : llvm::reverse(C&: CurContextChain)) {
5062 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
5063 break;
5064 NamespaceDeclChain.pop_back();
5065 }
5066
5067 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
5068 NumSpecifiers = buildNestedNameSpecifier(DeclChain&: NamespaceDeclChain, NNS);
5069
5070 // Add an explicit leading '::' specifier if needed.
5071 if (NamespaceDeclChain.empty()) {
5072 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
5073 NNS = NestedNameSpecifier::getGlobal();
5074 NumSpecifiers =
5075 buildNestedNameSpecifier(DeclChain&: FullNamespaceDeclChain, NNS);
5076 } else if (NamedDecl *ND =
5077 dyn_cast_or_null<NamedDecl>(Val: NamespaceDeclChain.back())) {
5078 IdentifierInfo *Name = ND->getIdentifier();
5079 bool SameNameSpecifier = false;
5080 if (llvm::is_contained(Range&: CurNameSpecifierIdentifiers, Element: Name)) {
5081 std::string NewNameSpecifier;
5082 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
5083 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
5084 getNestedNameSpecifierIdentifiers(NNS, Identifiers&: NewNameSpecifierIdentifiers);
5085 NNS.print(OS&: SpecifierOStream, Policy: Context.getPrintingPolicy());
5086 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
5087 }
5088 if (SameNameSpecifier || llvm::is_contained(Range&: CurContextIdentifiers, Element: Name)) {
5089 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
5090 NNS = NestedNameSpecifier::getGlobal();
5091 NumSpecifiers =
5092 buildNestedNameSpecifier(DeclChain&: FullNamespaceDeclChain, NNS);
5093 }
5094 }
5095
5096 // If the built NestedNameSpecifier would be replacing an existing
5097 // NestedNameSpecifier, use the number of component identifiers that
5098 // would need to be changed as the edit distance instead of the number
5099 // of components in the built NestedNameSpecifier.
5100 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
5101 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
5102 getNestedNameSpecifierIdentifiers(NNS, Identifiers&: NewNameSpecifierIdentifiers);
5103 NumSpecifiers =
5104 llvm::ComputeEditDistance(FromArray: llvm::ArrayRef(CurNameSpecifierIdentifiers),
5105 ToArray: llvm::ArrayRef(NewNameSpecifierIdentifiers));
5106 }
5107
5108 SpecifierInfo SI = {.DeclCtx: Ctx, .NameSpecifier: NNS, .EditDistance: NumSpecifiers};
5109 DistanceMap[NumSpecifiers].push_back(Elt: SI);
5110}
5111
5112/// Perform name lookup for a possible result for typo correction.
5113static void LookupPotentialTypoResult(Sema &SemaRef,
5114 LookupResult &Res,
5115 IdentifierInfo *Name,
5116 Scope *S, CXXScopeSpec *SS,
5117 DeclContext *MemberContext,
5118 bool EnteringContext,
5119 bool isObjCIvarLookup,
5120 bool FindHidden) {
5121 Res.suppressDiagnostics();
5122 Res.clear();
5123 Res.setLookupName(Name);
5124 Res.setAllowHidden(FindHidden);
5125 if (MemberContext) {
5126 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: MemberContext)) {
5127 if (isObjCIvarLookup) {
5128 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(IVarName: Name)) {
5129 Res.addDecl(D: Ivar);
5130 Res.resolveKind();
5131 return;
5132 }
5133 }
5134
5135 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
5136 PropertyId: Name, QueryKind: ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
5137 Res.addDecl(D: Prop);
5138 Res.resolveKind();
5139 return;
5140 }
5141 }
5142
5143 SemaRef.LookupQualifiedName(R&: Res, LookupCtx: MemberContext);
5144 return;
5145 }
5146
5147 SemaRef.LookupParsedName(R&: Res, S, SS,
5148 /*ObjectType=*/QualType(),
5149 /*AllowBuiltinCreation=*/false, EnteringContext);
5150
5151 // Fake ivar lookup; this should really be part of
5152 // LookupParsedName.
5153 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
5154 if (Method->isInstanceMethod() && Method->getClassInterface() &&
5155 (Res.empty() ||
5156 (Res.isSingleResult() &&
5157 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
5158 if (ObjCIvarDecl *IV
5159 = Method->getClassInterface()->lookupInstanceVariable(IVarName: Name)) {
5160 Res.addDecl(D: IV);
5161 Res.resolveKind();
5162 }
5163 }
5164 }
5165}
5166
5167/// Add keywords to the consumer as possible typo corrections.
5168static void AddKeywordsToConsumer(Sema &SemaRef,
5169 TypoCorrectionConsumer &Consumer,
5170 Scope *S, CorrectionCandidateCallback &CCC,
5171 bool AfterNestedNameSpecifier) {
5172 if (AfterNestedNameSpecifier) {
5173 // For 'X::', we know exactly which keywords can appear next.
5174 Consumer.addKeywordResult(Keyword: "template");
5175 if (CCC.WantExpressionKeywords)
5176 Consumer.addKeywordResult(Keyword: "operator");
5177 return;
5178 }
5179
5180 if (CCC.WantObjCSuper)
5181 Consumer.addKeywordResult(Keyword: "super");
5182
5183 if (CCC.WantTypeSpecifiers) {
5184 // Add type-specifier keywords to the set of results.
5185 static const char *const CTypeSpecs[] = {
5186 "char", "const", "double", "enum", "float", "int", "long", "short",
5187 "signed", "struct", "union", "unsigned", "void", "volatile",
5188 "_Complex",
5189 // storage-specifiers as well
5190 "extern", "inline", "static", "typedef"
5191 };
5192
5193 for (const auto *CTS : CTypeSpecs)
5194 Consumer.addKeywordResult(Keyword: CTS);
5195
5196 if (SemaRef.getLangOpts().C99 && !SemaRef.getLangOpts().C2y)
5197 Consumer.addKeywordResult(Keyword: "_Imaginary");
5198
5199 if (SemaRef.getLangOpts().C99)
5200 Consumer.addKeywordResult(Keyword: "restrict");
5201 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
5202 Consumer.addKeywordResult(Keyword: "bool");
5203 else if (SemaRef.getLangOpts().C99)
5204 Consumer.addKeywordResult(Keyword: "_Bool");
5205
5206 if (SemaRef.getLangOpts().CPlusPlus) {
5207 Consumer.addKeywordResult(Keyword: "class");
5208 Consumer.addKeywordResult(Keyword: "typename");
5209 Consumer.addKeywordResult(Keyword: "wchar_t");
5210
5211 if (SemaRef.getLangOpts().CPlusPlus11) {
5212 Consumer.addKeywordResult(Keyword: "char16_t");
5213 Consumer.addKeywordResult(Keyword: "char32_t");
5214 Consumer.addKeywordResult(Keyword: "constexpr");
5215 Consumer.addKeywordResult(Keyword: "decltype");
5216 Consumer.addKeywordResult(Keyword: "thread_local");
5217 }
5218 }
5219
5220 if (SemaRef.getLangOpts().GNUKeywords)
5221 Consumer.addKeywordResult(Keyword: "typeof");
5222 } else if (CCC.WantFunctionLikeCasts) {
5223 static const char *const CastableTypeSpecs[] = {
5224 "char", "double", "float", "int", "long", "short",
5225 "signed", "unsigned", "void"
5226 };
5227 for (auto *kw : CastableTypeSpecs)
5228 Consumer.addKeywordResult(Keyword: kw);
5229 }
5230
5231 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5232 Consumer.addKeywordResult(Keyword: "const_cast");
5233 Consumer.addKeywordResult(Keyword: "dynamic_cast");
5234 Consumer.addKeywordResult(Keyword: "reinterpret_cast");
5235 Consumer.addKeywordResult(Keyword: "static_cast");
5236 }
5237
5238 if (CCC.WantExpressionKeywords) {
5239 Consumer.addKeywordResult(Keyword: "sizeof");
5240 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5241 Consumer.addKeywordResult(Keyword: "false");
5242 Consumer.addKeywordResult(Keyword: "true");
5243 }
5244
5245 if (SemaRef.getLangOpts().CPlusPlus) {
5246 static const char *const CXXExprs[] = {
5247 "delete", "new", "operator", "throw", "typeid"
5248 };
5249 for (const auto *CE : CXXExprs)
5250 Consumer.addKeywordResult(Keyword: CE);
5251
5252 if (isa<CXXMethodDecl>(Val: SemaRef.CurContext) &&
5253 cast<CXXMethodDecl>(Val: SemaRef.CurContext)->isInstance())
5254 Consumer.addKeywordResult(Keyword: "this");
5255
5256 if (SemaRef.getLangOpts().CPlusPlus11) {
5257 Consumer.addKeywordResult(Keyword: "alignof");
5258 Consumer.addKeywordResult(Keyword: "nullptr");
5259 }
5260 }
5261
5262 if (SemaRef.getLangOpts().C11) {
5263 // FIXME: We should not suggest _Alignof if the alignof macro
5264 // is present.
5265 Consumer.addKeywordResult(Keyword: "_Alignof");
5266 }
5267 }
5268
5269 if (CCC.WantRemainingKeywords) {
5270 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5271 // Statements.
5272 static const char *const CStmts[] = {
5273 "do", "else", "for", "goto", "if", "return", "switch", "while" };
5274 for (const auto *CS : CStmts)
5275 Consumer.addKeywordResult(Keyword: CS);
5276
5277 if (SemaRef.getLangOpts().CPlusPlus) {
5278 Consumer.addKeywordResult(Keyword: "catch");
5279 Consumer.addKeywordResult(Keyword: "try");
5280 }
5281
5282 if (S && S->getBreakParent())
5283 Consumer.addKeywordResult(Keyword: "break");
5284
5285 if (S && S->getContinueParent())
5286 Consumer.addKeywordResult(Keyword: "continue");
5287
5288 if (SemaRef.getCurFunction() &&
5289 !SemaRef.getCurFunction()->SwitchStack.empty()) {
5290 Consumer.addKeywordResult(Keyword: "case");
5291 Consumer.addKeywordResult(Keyword: "default");
5292 }
5293 } else {
5294 if (SemaRef.getLangOpts().CPlusPlus) {
5295 Consumer.addKeywordResult(Keyword: "namespace");
5296 Consumer.addKeywordResult(Keyword: "template");
5297 }
5298
5299 if (S && S->isClassScope()) {
5300 Consumer.addKeywordResult(Keyword: "explicit");
5301 Consumer.addKeywordResult(Keyword: "friend");
5302 Consumer.addKeywordResult(Keyword: "mutable");
5303 Consumer.addKeywordResult(Keyword: "private");
5304 Consumer.addKeywordResult(Keyword: "protected");
5305 Consumer.addKeywordResult(Keyword: "public");
5306 Consumer.addKeywordResult(Keyword: "virtual");
5307 }
5308 }
5309
5310 if (SemaRef.getLangOpts().CPlusPlus) {
5311 Consumer.addKeywordResult(Keyword: "using");
5312
5313 if (SemaRef.getLangOpts().CPlusPlus11)
5314 Consumer.addKeywordResult(Keyword: "static_assert");
5315 }
5316 }
5317}
5318
5319std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5320 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5321 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5322 DeclContext *MemberContext, bool EnteringContext,
5323 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5324
5325 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5326 DisableTypoCorrection)
5327 return nullptr;
5328
5329 // In Microsoft mode, don't perform typo correction in a template member
5330 // function dependent context because it interferes with the "lookup into
5331 // dependent bases of class templates" feature.
5332 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5333 isa<CXXMethodDecl>(Val: CurContext))
5334 return nullptr;
5335
5336 // We only attempt to correct typos for identifiers.
5337 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5338 if (!Typo)
5339 return nullptr;
5340
5341 // If the scope specifier itself was invalid, don't try to correct
5342 // typos.
5343 if (SS && SS->isInvalid())
5344 return nullptr;
5345
5346 // Never try to correct typos during any kind of code synthesis.
5347 if (!CodeSynthesisContexts.empty())
5348 return nullptr;
5349
5350 // Don't try to correct 'super'.
5351 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5352 return nullptr;
5353
5354 // Abort if typo correction already failed for this specific typo.
5355 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Val: Typo);
5356 if (locs != TypoCorrectionFailures.end() &&
5357 locs->second.count(V: TypoName.getLoc()))
5358 return nullptr;
5359
5360 // Don't try to correct the identifier "vector" when in AltiVec mode.
5361 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5362 // remove this workaround.
5363 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr(Str: "vector"))
5364 return nullptr;
5365
5366 // Provide a stop gap for files that are just seriously broken. Trying
5367 // to correct all typos can turn into a HUGE performance penalty, causing
5368 // some files to take minutes to get rejected by the parser.
5369 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5370 if (Limit && TyposCorrected >= Limit)
5371 return nullptr;
5372 ++TyposCorrected;
5373
5374 // If we're handling a missing symbol error, using modules, and the
5375 // special search all modules option is used, look for a missing import.
5376 if (ErrorRecovery && getLangOpts().Modules &&
5377 getLangOpts().ModulesSearchAll) {
5378 // The following has the side effect of loading the missing module.
5379 getModuleLoader().lookupMissingImports(Name: Typo->getName(),
5380 TriggerLoc: TypoName.getBeginLoc());
5381 }
5382
5383 // Extend the lifetime of the callback. We delayed this until here
5384 // to avoid allocations in the hot path (which is where no typo correction
5385 // occurs). Note that CorrectionCandidateCallback is polymorphic and
5386 // initially stack-allocated.
5387 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5388 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5389 args&: *this, args: TypoName, args&: LookupKind, args&: S, args&: SS, args: std::move(ClonedCCC), args&: MemberContext,
5390 args&: EnteringContext);
5391
5392 // Perform name lookup to find visible, similarly-named entities.
5393 bool IsUnqualifiedLookup = false;
5394 DeclContext *QualifiedDC = MemberContext;
5395 if (MemberContext) {
5396 LookupVisibleDecls(Ctx: MemberContext, Kind: LookupKind, Consumer&: *Consumer);
5397
5398 // Look in qualified interfaces.
5399 if (OPT) {
5400 for (auto *I : OPT->quals())
5401 LookupVisibleDecls(Ctx: I, Kind: LookupKind, Consumer&: *Consumer);
5402 }
5403 } else if (SS && SS->isSet()) {
5404 QualifiedDC = computeDeclContext(SS: *SS, EnteringContext);
5405 if (!QualifiedDC)
5406 return nullptr;
5407
5408 LookupVisibleDecls(Ctx: QualifiedDC, Kind: LookupKind, Consumer&: *Consumer);
5409 } else {
5410 IsUnqualifiedLookup = true;
5411 }
5412
5413 // Determine whether we are going to search in the various namespaces for
5414 // corrections.
5415 bool SearchNamespaces
5416 = getLangOpts().CPlusPlus &&
5417 (IsUnqualifiedLookup || (SS && SS->isSet()));
5418
5419 if (IsUnqualifiedLookup || SearchNamespaces) {
5420 // For unqualified lookup, look through all of the names that we have
5421 // seen in this translation unit.
5422 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5423 for (const auto &I : Context.Idents)
5424 Consumer->FoundName(Name: I.getKey());
5425
5426 // Walk through identifiers in external identifier sources.
5427 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5428 if (IdentifierInfoLookup *External
5429 = Context.Idents.getExternalIdentifierLookup()) {
5430 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5431 do {
5432 StringRef Name = Iter->Next();
5433 if (Name.empty())
5434 break;
5435
5436 Consumer->FoundName(Name);
5437 } while (true);
5438 }
5439 }
5440
5441 AddKeywordsToConsumer(SemaRef&: *this, Consumer&: *Consumer, S,
5442 CCC&: *Consumer->getCorrectionValidator(),
5443 AfterNestedNameSpecifier: SS && SS->isNotEmpty());
5444
5445 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5446 // to search those namespaces.
5447 if (SearchNamespaces) {
5448 // Load any externally-known namespaces.
5449 if (ExternalSource && !LoadedExternalKnownNamespaces) {
5450 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5451 LoadedExternalKnownNamespaces = true;
5452 ExternalSource->ReadKnownNamespaces(Namespaces&: ExternalKnownNamespaces);
5453 for (auto *N : ExternalKnownNamespaces)
5454 KnownNamespaces[N] = true;
5455 }
5456
5457 Consumer->addNamespaces(KnownNamespaces);
5458 }
5459
5460 return Consumer;
5461}
5462
5463TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
5464 Sema::LookupNameKind LookupKind,
5465 Scope *S, CXXScopeSpec *SS,
5466 CorrectionCandidateCallback &CCC,
5467 CorrectTypoKind Mode,
5468 DeclContext *MemberContext,
5469 bool EnteringContext,
5470 const ObjCObjectPointerType *OPT,
5471 bool RecordFailure) {
5472 // Always let the ExternalSource have the first chance at correction, even
5473 // if we would otherwise have given up.
5474 if (ExternalSource) {
5475 if (TypoCorrection Correction =
5476 ExternalSource->CorrectTypo(Typo: TypoName, LookupKind, S, SS, CCC,
5477 MemberContext, EnteringContext, OPT))
5478 return Correction;
5479 }
5480
5481 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5482 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5483 // some instances of CTC_Unknown, while WantRemainingKeywords is true
5484 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5485 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5486
5487 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5488 auto Consumer = makeTypoCorrectionConsumer(
5489 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT,
5490 ErrorRecovery: Mode == CorrectTypoKind::ErrorRecovery);
5491
5492 if (!Consumer)
5493 return TypoCorrection();
5494
5495 // If we haven't found anything, we're done.
5496 if (Consumer->empty())
5497 return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure);
5498
5499 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5500 // is not more that about a third of the length of the typo's identifier.
5501 unsigned ED = Consumer->getBestEditDistance(Normalized: true);
5502 unsigned TypoLen = Typo->getName().size();
5503 if (ED > 0 && TypoLen / ED < 3)
5504 return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure);
5505
5506 TypoCorrection BestTC = Consumer->getNextCorrection();
5507 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5508 if (!BestTC)
5509 return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure);
5510
5511 ED = BestTC.getEditDistance();
5512
5513 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5514 // If this was an unqualified lookup and we believe the callback
5515 // object wouldn't have filtered out possible corrections, note
5516 // that no correction was found.
5517 return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure);
5518 }
5519
5520 // If only a single name remains, return that result.
5521 if (!SecondBestTC ||
5522 SecondBestTC.getEditDistance(Normalized: false) > BestTC.getEditDistance(Normalized: false)) {
5523 const TypoCorrection &Result = BestTC;
5524
5525 // Don't correct to a keyword that's the same as the typo; the keyword
5526 // wasn't actually in scope.
5527 if (ED == 0 && Result.isKeyword())
5528 return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure);
5529
5530 TypoCorrection TC = Result;
5531 TC.setCorrectionRange(SS, TypoName);
5532 checkCorrectionVisibility(SemaRef&: *this, TC);
5533 return TC;
5534 } else if (SecondBestTC && ObjCMessageReceiver) {
5535 // Prefer 'super' when we're completing in a message-receiver
5536 // context.
5537
5538 if (BestTC.getCorrection().getAsString() != "super") {
5539 if (SecondBestTC.getCorrection().getAsString() == "super")
5540 BestTC = std::move(SecondBestTC);
5541 else if ((*Consumer)["super"].front().isKeyword())
5542 BestTC = (*Consumer)["super"].front();
5543 }
5544 // Don't correct to a keyword that's the same as the typo; the keyword
5545 // wasn't actually in scope.
5546 if (BestTC.getEditDistance() == 0 ||
5547 BestTC.getCorrection().getAsString() != "super")
5548 return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure);
5549
5550 BestTC.setCorrectionRange(SS, TypoName);
5551 return BestTC;
5552 }
5553
5554 // Record the failure's location if needed and return an empty correction. If
5555 // this was an unqualified lookup and we believe the callback object did not
5556 // filter out possible corrections, also cache the failure for the typo.
5557 return FailedCorrection(Typo, TypoLoc: TypoName.getLoc(), RecordFailure: RecordFailure && !SecondBestTC);
5558}
5559
5560void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5561 if (!CDecl) return;
5562
5563 if (isKeyword())
5564 CorrectionDecls.clear();
5565
5566 CorrectionDecls.push_back(Elt: CDecl);
5567
5568 if (!CorrectionName)
5569 CorrectionName = CDecl->getDeclName();
5570}
5571
5572std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5573 if (CorrectionNameSpec) {
5574 std::string tmpBuffer;
5575 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5576 CorrectionNameSpec.print(OS&: PrefixOStream, Policy: PrintingPolicy(LO));
5577 PrefixOStream << CorrectionName;
5578 return PrefixOStream.str();
5579 }
5580
5581 return CorrectionName.getAsString();
5582}
5583
5584bool CorrectionCandidateCallback::ValidateCandidate(
5585 const TypoCorrection &candidate) {
5586 if (!candidate.isResolved())
5587 return true;
5588
5589 if (candidate.isKeyword())
5590 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5591 WantRemainingKeywords || WantObjCSuper;
5592
5593 bool HasNonType = false;
5594 bool HasStaticMethod = false;
5595 bool HasNonStaticMethod = false;
5596 for (Decl *D : candidate) {
5597 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
5598 D = FTD->getTemplatedDecl();
5599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
5600 if (Method->isStatic())
5601 HasStaticMethod = true;
5602 else
5603 HasNonStaticMethod = true;
5604 }
5605 if (!isa<TypeDecl>(Val: D))
5606 HasNonType = true;
5607 }
5608
5609 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5610 !candidate.getCorrectionSpecifier())
5611 return false;
5612
5613 return WantTypeSpecifiers || HasNonType;
5614}
5615
5616FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
5617 bool HasExplicitTemplateArgs,
5618 MemberExpr *ME)
5619 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5620 CurContext(SemaRef.CurContext), MemberFn(ME) {
5621 WantTypeSpecifiers = false;
5622 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5623 !HasExplicitTemplateArgs && NumArgs == 1;
5624 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5625 WantRemainingKeywords = false;
5626}
5627
5628bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5629 if (!candidate.getCorrectionDecl())
5630 return candidate.isKeyword();
5631
5632 for (auto *C : candidate) {
5633 FunctionDecl *FD = nullptr;
5634 NamedDecl *ND = C->getUnderlyingDecl();
5635 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND))
5636 FD = FTD->getTemplatedDecl();
5637 if (!HasExplicitTemplateArgs && !FD) {
5638 if (!(FD = dyn_cast<FunctionDecl>(Val: ND)) && isa<ValueDecl>(Val: ND)) {
5639 // If the Decl is neither a function nor a template function,
5640 // determine if it is a pointer or reference to a function. If so,
5641 // check against the number of arguments expected for the pointee.
5642 QualType ValType = cast<ValueDecl>(Val: ND)->getType();
5643 if (ValType.isNull())
5644 continue;
5645 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5646 ValType = ValType->getPointeeType();
5647 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5648 if (FPT->getNumParams() == NumArgs)
5649 return true;
5650 }
5651 }
5652
5653 // A typo for a function-style cast can look like a function call in C++.
5654 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(D: ND) != nullptr
5655 : isa<TypeDecl>(Val: ND)) &&
5656 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5657 // Only a class or class template can take two or more arguments.
5658 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(Val: ND);
5659
5660 // Skip the current candidate if it is not a FunctionDecl or does not accept
5661 // the current number of arguments.
5662 if (!FD || !(FD->getNumParams() >= NumArgs &&
5663 FD->getMinRequiredArguments() <= NumArgs))
5664 continue;
5665
5666 // If the current candidate is a non-static C++ method, skip the candidate
5667 // unless the method being corrected--or the current DeclContext, if the
5668 // function being corrected is not a method--is a method in the same class
5669 // or a descendent class of the candidate's parent class.
5670 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
5671 if (MemberFn || !MD->isStatic()) {
5672 const auto *CurMD =
5673 MemberFn
5674 ? dyn_cast_if_present<CXXMethodDecl>(Val: MemberFn->getMemberDecl())
5675 : dyn_cast_if_present<CXXMethodDecl>(Val: CurContext);
5676 const CXXRecordDecl *CurRD =
5677 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5678 const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5679 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(Base: RD)))
5680 continue;
5681 }
5682 }
5683 return true;
5684 }
5685 return false;
5686}
5687
5688void Sema::diagnoseTypo(const TypoCorrection &Correction,
5689 const PartialDiagnostic &TypoDiag,
5690 bool ErrorRecovery) {
5691 diagnoseTypo(Correction, TypoDiag, PrevNote: PDiag(DiagID: diag::note_previous_decl),
5692 ErrorRecovery);
5693}
5694
5695/// Find which declaration we should import to provide the definition of
5696/// the given declaration.
5697static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
5698 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
5699 return VD->getDefinition();
5700 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
5701 return FD->getDefinition();
5702 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
5703 return TD->getDefinition();
5704 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: D))
5705 return ID->getDefinition();
5706 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(Val: D))
5707 return PD->getDefinition();
5708 if (const auto *TD = dyn_cast<TemplateDecl>(Val: D))
5709 if (const NamedDecl *TTD = TD->getTemplatedDecl())
5710 return getDefinitionToImport(D: TTD);
5711 return nullptr;
5712}
5713
5714void Sema::diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
5715 MissingImportKind MIK, bool Recover) {
5716 // Suggest importing a module providing the definition of this entity, if
5717 // possible.
5718 const NamedDecl *Def = getDefinitionToImport(D: Decl);
5719 if (!Def)
5720 Def = Decl;
5721
5722 Module *Owner = getOwningModule(Entity: Def);
5723 assert(Owner && "definition of hidden declaration is not in a module");
5724
5725 llvm::SmallVector<Module*, 8> OwningModules;
5726 OwningModules.push_back(Elt: Owner);
5727 auto Merged = Context.getModulesWithMergedDefinition(Def);
5728 llvm::append_range(C&: OwningModules, R&: Merged);
5729
5730 diagnoseMissingImport(Loc, Decl: Def, DeclLoc: Def->getLocation(), Modules: OwningModules, MIK,
5731 Recover);
5732}
5733
5734/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5735/// suggesting the addition of a #include of the specified file.
5736static std::string getHeaderNameForHeader(Preprocessor &PP, FileEntryRef E,
5737 llvm::StringRef IncludingFile) {
5738 bool IsAngled = false;
5739 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5740 File: E, MainFile: IncludingFile, IsAngled: &IsAngled);
5741 return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');
5742}
5743
5744void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl,
5745 SourceLocation DeclLoc,
5746 ArrayRef<Module *> Modules,
5747 MissingImportKind MIK, bool Recover) {
5748 assert(!Modules.empty());
5749
5750 // See https://github.com/llvm/llvm-project/issues/73893. It is generally
5751 // confusing than helpful to show the namespace is not visible.
5752 if (isa<NamespaceDecl>(Val: Decl))
5753 return;
5754
5755 auto NotePrevious = [&] {
5756 // FIXME: Suppress the note backtrace even under
5757 // -fdiagnostics-show-note-include-stack. We don't care how this
5758 // declaration was previously reached.
5759 Diag(Loc: DeclLoc, DiagID: diag::note_unreachable_entity) << (int)MIK;
5760 };
5761
5762 // Weed out duplicates from module list.
5763 llvm::SmallVector<Module*, 8> UniqueModules;
5764 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5765 for (auto *M : Modules) {
5766 if (M->isExplicitGlobalModule() || M->isPrivateModule())
5767 continue;
5768 if (UniqueModuleSet.insert(V: M).second)
5769 UniqueModules.push_back(Elt: M);
5770 }
5771
5772 // Try to find a suitable header-name to #include.
5773 std::string HeaderName;
5774 if (OptionalFileEntryRef Header =
5775 PP.getHeaderToIncludeForDiagnostics(IncLoc: UseLoc, MLoc: DeclLoc)) {
5776 if (const FileEntry *FE =
5777 SourceMgr.getFileEntryForID(FID: SourceMgr.getFileID(SpellingLoc: UseLoc)))
5778 HeaderName =
5779 getHeaderNameForHeader(PP, E: *Header, IncludingFile: FE->tryGetRealPathName());
5780 }
5781
5782 // If we have a #include we should suggest, or if all definition locations
5783 // were in global module fragments, don't suggest an import.
5784 if (!HeaderName.empty() || UniqueModules.empty()) {
5785 // FIXME: Find a smart place to suggest inserting a #include, and add
5786 // a FixItHint there.
5787 Diag(Loc: UseLoc, DiagID: diag::err_module_unimported_use_header)
5788 << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5789 // Produce a note showing where the entity was declared.
5790 NotePrevious();
5791 if (Recover)
5792 createImplicitModuleImportForErrorRecovery(Loc: UseLoc, Mod: Modules[0]);
5793 return;
5794 }
5795
5796 Modules = UniqueModules;
5797
5798 auto GetModuleNameForDiagnostic = [this](const Module *M) -> std::string {
5799 if (M->isModuleMapModule())
5800 return M->getFullModuleName();
5801
5802 if (M->isImplicitGlobalModule())
5803 M = M->getTopLevelModule();
5804
5805 // If the current module unit is in the same module with M, it is OK to show
5806 // the partition name. Otherwise, it'll be sufficient to show the primary
5807 // module name.
5808 if (getASTContext().isInSameModule(M1: M, M2: getCurrentModule()))
5809 return M->getTopLevelModuleName().str();
5810 else
5811 return M->getPrimaryModuleInterfaceName().str();
5812 };
5813
5814 if (Modules.size() > 1) {
5815 std::string ModuleList;
5816 unsigned N = 0;
5817 for (const auto *M : Modules) {
5818 ModuleList += "\n ";
5819 if (++N == 5 && N != Modules.size()) {
5820 ModuleList += "[...]";
5821 break;
5822 }
5823 ModuleList += GetModuleNameForDiagnostic(M);
5824 }
5825
5826 Diag(Loc: UseLoc, DiagID: diag::err_module_unimported_use_multiple)
5827 << (int)MIK << Decl << ModuleList;
5828 } else {
5829 // FIXME: Add a FixItHint that imports the corresponding module.
5830 Diag(Loc: UseLoc, DiagID: diag::err_module_unimported_use)
5831 << (int)MIK << Decl << GetModuleNameForDiagnostic(Modules[0]);
5832 }
5833
5834 NotePrevious();
5835
5836 // Try to recover by implicitly importing this module.
5837 if (Recover)
5838 createImplicitModuleImportForErrorRecovery(Loc: UseLoc, Mod: Modules[0]);
5839}
5840
5841void Sema::diagnoseTypo(const TypoCorrection &Correction,
5842 const PartialDiagnostic &TypoDiag,
5843 const PartialDiagnostic &PrevNote,
5844 bool ErrorRecovery) {
5845 std::string CorrectedStr = Correction.getAsString(LO: getLangOpts());
5846 std::string CorrectedQuotedStr = Correction.getQuoted(LO: getLangOpts());
5847 FixItHint FixTypo = FixItHint::CreateReplacement(
5848 RemoveRange: Correction.getCorrectionRange(), Code: CorrectedStr);
5849
5850 // Maybe we're just missing a module import.
5851 if (Correction.requiresImport()) {
5852 NamedDecl *Decl = Correction.getFoundDecl();
5853 assert(Decl && "import required but no declaration to import");
5854
5855 diagnoseMissingImport(Loc: Correction.getCorrectionRange().getBegin(), Decl,
5856 MIK: MissingImportKind::Declaration, Recover: ErrorRecovery);
5857 return;
5858 }
5859
5860 Diag(Loc: Correction.getCorrectionRange().getBegin(), PD: TypoDiag)
5861 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5862
5863 NamedDecl *ChosenDecl =
5864 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5865
5866 // For builtin functions which aren't declared anywhere in source,
5867 // don't emit the "declared here" note.
5868 if (const auto *FD = dyn_cast_if_present<FunctionDecl>(Val: ChosenDecl);
5869 FD && FD->getBuiltinID() &&
5870 PrevNote.getDiagID() == diag::note_previous_decl &&
5871 Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {
5872 ChosenDecl = nullptr;
5873 }
5874
5875 if (PrevNote.getDiagID() && ChosenDecl)
5876 Diag(Loc: ChosenDecl->getLocation(), PD: PrevNote)
5877 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5878
5879 // Add any extra diagnostics.
5880 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5881 Diag(Loc: Correction.getCorrectionRange().getBegin(), PD);
5882}
5883
5884void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5885 DeclarationNameInfo Name(II, IILoc);
5886 LookupResult R(*this, Name, LookupAnyName,
5887 RedeclarationKind::NotForRedeclaration);
5888 R.suppressDiagnostics();
5889 R.setHideTags(false);
5890 LookupName(R, S);
5891 R.dump();
5892}
5893
5894void Sema::ActOnPragmaDump(Expr *E) {
5895 E->dump();
5896}
5897
5898RedeclarationKind Sema::forRedeclarationInCurContext() const {
5899 // A declaration with an owning module for linkage can never link against
5900 // anything that is not visible. We don't need to check linkage here; if
5901 // the context has internal linkage, redeclaration lookup won't find things
5902 // from other TUs, and we can't safely compute linkage yet in general.
5903 if (cast<Decl>(Val: CurContext)->getOwningModuleForLinkage())
5904 return RedeclarationKind::ForVisibleRedeclaration;
5905 return RedeclarationKind::ForExternalRedeclaration;
5906}
5907