clang 22.0.0git
SemaLookup.cpp
Go to the documentation of this file.
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
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Overload.h"
33#include "clang/Sema/Scope.h"
35#include "clang/Sema/Sema.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
101
102 ListTy list;
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(Ctx, Ctx);
123 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
124 for (auto *I : S->using_directives())
125 if (SemaRef.isVisible(I))
126 visit(I, 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(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) {
150 if (!visited.insert(NS).second)
151 return;
152
153 addUsingDirective(UD, EffectiveDC);
154 addUsingDirectives(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) {
162 while (true) {
163 for (auto *UD : DC->using_directives()) {
165 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
166 addUsingDirective(UD, EffectiveDC);
167 queue.push_back(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(EffectiveDC))
190 Common = Common->getParent();
191 Common = Common->getPrimaryContext();
192
193 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
194 }
195
196 void done() { llvm::sort(list, 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(std::equal_range(begin(), end(),
206 DC->getPrimaryContext(),
207 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) {
224 IDNS = Decl::IDNS_Ordinary;
225 if (CPlusPlus) {
227 if (Redeclaration)
229 }
230 if (Redeclaration)
232 break;
233
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");
239 break;
240
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)
252 } else {
253 IDNS = Decl::IDNS_Tag;
254 }
255 break;
256
258 IDNS = Decl::IDNS_Label;
259 break;
260
262 IDNS = Decl::IDNS_Member;
263 if (CPlusPlus)
265 break;
266
269 break;
270
273 break;
274
276 assert(Redeclaration && "should only be used for redecl lookup");
280 break;
281
284 break;
285
288 break;
289
292 break;
293
298 break;
299 }
300 return IDNS;
301}
302
303void LookupResult::configure() {
304 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
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:
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(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 &&
345 assert((Paths != nullptr) ==
346 (ResultKind == LookupResultKind::Ambiguous &&
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.
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.
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>(D) &&
380 !isa<UsingShadowDecl>(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>(EUnderlying);
397 bool WantTag =
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>(DUnderlying)) {
407 const auto *EFD = cast<FunctionDecl>(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>(DUnderlying)) {
419 const auto *ETD = cast<TemplateDecl>(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) {
433 ETD->getTemplateParameters()->getParam(I)) &&
435 DTD->getTemplateParameters()->getParam(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>(DUnderlying)) {
443 const auto *EVD = cast<VarDecl>(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(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>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
454 // If the existing declaration is hidden, prefer the new one. Otherwise,
455 // keep what we've got.
456 return !S.isVisible(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>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
483 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
484 isa<UnresolvedUsingValueDecl>(D);
485}
486
487/// Resolves the result kind of this lookup.
489 unsigned N = Decls.size();
490
491 // Fast case: no possible ambiguity.
492 if (N == 0) {
493 assert(ResultKind == LookupResultKind::NotFound ||
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>(D))
504 else if (isa<UnresolvedUsingValueDecl>(D))
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>(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>(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>(D)) {
545 bool Hidden = false;
546 for (auto *OtherDecl : Decls) {
547 if (canHideTag(OtherDecl) && !OtherDecl->isInvalidDecl() &&
548 getContextForScopeMatching(OtherDecl)->Equals(
549 getContextForScopeMatching(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>(D)) {
566 auto UniqueResult = UniqueTypes.insert(
567 std::make_pair(getSema().Context.getCanonicalTypeDeclType(TD), 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(std::make_pair(D, 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.
588 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>(D)) {
597 HasUnresolved = true;
598 } else if (isa<TagDecl>(D)) {
599 if (HasTag)
600 Ambiguous = true;
601 HasTag = true;
602 } else if (isa<FunctionTemplateDecl>(D)) {
603 HasFunction = true;
604 HasFunctionTemplate = true;
605 } else if (isa<FunctionDecl>(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(HasNonFunction,
614 D)) {
615 EquivalentNonFunctions.push_back(D);
616 RemovedDecls.set(I);
617 continue;
618 }
619 if (D->isPlaceholderVar(getSema().getLangOpts()) &&
621 getContextForScopeMatching(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)
634 getNameLoc(), HasNonFunction, 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(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)
649 else if (Ambiguous)
651 else if (HasUnresolved)
653 else if (N > 1 || HasFunctionTemplate)
655 else
656 ResultKind = LookupResultKind::Found;
657}
658
659void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
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(*DI);
665}
666
668 Paths = new CXXBasePaths;
669 Paths->swap(P);
670 addDeclsFromBasePaths(*Paths);
671 resolveKind();
673}
674
676 Paths = new CXXBasePaths;
677 Paths->swap(P);
678 addDeclsFromBasePaths(*Paths);
679 resolveKind();
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, 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(SourceLocation(), 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) {
714 if (Result.empty())
715 return diagOpenCLBuiltinTypeError(S, "enum", Name);
716 EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
717 if (!Decl)
718 return diagOpenCLBuiltinTypeError(S, "enum", Name);
720}
721
722/// Lookup an OpenCL typedef type.
723static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
727 if (Result.empty())
728 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
729 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
730 if (!Decl)
731 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
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) .
748 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
749 SmallVector<QualType, 1> &RetTypes,
751 // Get the QualType instances of the return types.
752 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
753 OCL2Qual(S, TypeTable[Sig], 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++) {
760 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
761 Ty);
762 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
763 ArgTypes.push_back(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.
777 ASTContext &Context, unsigned GenTypeMaxCnt,
778 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
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++) {
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(ArgTypes[A][Idx]);
805 }
806
807 FunctionList.push_back(Context.getFunctionType(
808 RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, 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.
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(Context.getLangOpts(),
841 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()) {
850 Extensions.split(ExtVec, " ");
851 bool AllExtensionsDefined = true;
852 for (StringRef Ext : ExtVec) {
853 if (!S.getPreprocessor().isMacroDefined(Ext)) {
854 AllExtensionsDefined = false;
855 break;
856 }
857 }
858 if (!AllExtensionsDefined)
859 continue;
860 }
861
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
879 FunctionDecl *NewOpenCLBuiltin;
880
881 for (const auto &FTy : FunctionList) {
882 NewOpenCLBuiltin = FunctionDecl::Create(
883 Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,
885 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>(FTy);
892 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
894 Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),
895 nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);
896 Parm->setScopeInfo(0, IParm);
897 ParmList.push_back(Parm);
898 }
899 NewOpenCLBuiltin->setParams(ParmList);
900
901 // Add function attributes.
902 if (OpenCLBuiltin.IsPure)
903 NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context));
904 if (OpenCLBuiltin.IsConst)
905 NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context));
906 if (OpenCLBuiltin.IsConv)
907 NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context));
908
909 if (!S.getLangOpts().OpenCLCPlusPlus)
910 NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));
911
912 LR.addDecl(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
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 ||
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(II->getName());
955 if (Index.first) {
956 InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,
957 Index.second);
958 return true;
959 }
960 }
961
962 if (RISCV().DeclareRVVBuiltins || RISCV().DeclareSiFiveVectorBuiltins ||
963 RISCV().DeclareAndesVectorBuiltins) {
964 if (!RISCV().IntrinsicManager)
966
967 RISCV().IntrinsicManager->InitIntrinsicList();
968
969 if (RISCV().IntrinsicManager->CreateIntrinsicIfFound(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.
979 return false;
980
981 if (NamedDecl *D =
982 LazilyCreateBuiltin(II, BuiltinID, TUScope,
983 R.isForRedeclaration(), 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.
998 ASTContext &Context = Sema.Context;
999 LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),
1002 if (Result.getResultKind() == LookupResultKind::Found)
1003 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1004 Context.setObjCSuperType(Context.getCanonicalTagType(TD));
1005}
1006
1008 if (ID == Builtin::BIobjc_msgSendSuper)
1010}
1011
1012/// Determine whether we can declare a special member function within
1013/// the class at this point.
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
1025 return;
1026
1027 // If the default constructor has not yet been declared, do so now.
1028 if (Class->needsImplicitDefaultConstructor())
1030
1031 // If the copy constructor has not yet been declared, do so now.
1032 if (Class->needsImplicitCopyConstructor())
1034
1035 // If the copy assignment operator has not yet been declared, do so now.
1036 if (Class->needsImplicitCopyAssignment())
1038
1039 if (getLangOpts().CPlusPlus11) {
1040 // If the move constructor has not yet been declared, do so now.
1041 if (Class->needsImplicitMoveConstructor())
1043
1044 // If the move assignment operator has not yet been declared, do so now.
1045 if (Class->needsImplicitMoveAssignment())
1047 }
1048
1049 // If the destructor has not yet been declared, do so now.
1050 if (Class->needsImplicitDestructor())
1052}
1053
1054/// Determine whether this is the name of an implicitly-declared
1055/// special member function.
1057 switch (Name.getNameKind()) {
1060 return true;
1061
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.
1075 DeclarationName Name,
1077 const DeclContext *DC) {
1078 if (!DC)
1079 return;
1080
1081 switch (Name.getNameKind()) {
1083 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1084 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1085 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1086 if (Record->needsImplicitDefaultConstructor())
1088 if (Record->needsImplicitCopyConstructor())
1090 if (S.getLangOpts().CPlusPlus11 &&
1091 Record->needsImplicitMoveConstructor())
1093 }
1094 break;
1095
1097 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1098 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
1101 break;
1102
1104 if (Name.getCXXOverloadedOperator() != OO_Equal)
1105 break;
1106
1107 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
1108 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1109 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1110 if (Record->needsImplicitCopyAssignment())
1112 if (S.getLangOpts().CPlusPlus11 &&
1113 Record->needsImplicitMoveAssignment())
1115 }
1116 }
1117 break;
1118
1120 S.DeclareImplicitDeductionGuides(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)
1136 DC);
1137
1138 // Perform lookup into this declaration context.
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()
1153 !isa<CXXRecordDecl>(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>(DC);
1161 if (!Record->isCompleteDefinition())
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 =
1169 if (R.getLookupName().getNameKind() ==
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>(*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(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.
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!
1212 EPI.ExceptionSpec = EST_None;
1214 R.getLookupName().getCXXNameType(), {}, EPI);
1215
1216 // Perform template argument deduction against the type that we would
1217 // expect the function to have.
1218 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
1219 Specialization, Info) ==
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, 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(NS))
1242 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
1243 Found = true;
1244
1245 R.resolveKind();
1246
1247 return Found;
1248}
1249
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.
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) {
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
1296 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1297 if (DeclContext *DC = PreS->getEntity())
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()) {
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;
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(*I); ++I) {
1350 if (NamedDecl *ND = R.getAcceptableDecl(*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(*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(ND);
1373 }
1374 }
1375 if (!SearchNamespaceScope) {
1376 R.resolveKind();
1377 if (S->isClassScope())
1378 if (auto *Record = dyn_cast_if_present<CXXRecordDecl>(S->getEntity()))
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(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>(Ctx)) {
1408 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1409 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1410 ObjCInterfaceDecl *ClassDeclared;
1411 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1412 Name.getAsIdentifierInfo(),
1413 ClassDeclared)) {
1414 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1415 R.addDecl(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(UCtx, 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(InnermostFileScope))
1444 InnermostFileScope = InnermostFileScope->getParent();
1445 UDirs.visitScopeChain(Initial, InnermostFileScope);
1446
1447 UDirs.done();
1448
1449 VisitedUsingDirectives = true;
1450 }
1451
1452 if (CppNamespaceLookup(*this, R, Context, 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, 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(Initial, 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(*I); ++I) {
1503 if (NamedDecl *ND = R.getAcceptableDecl(*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(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(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(*this, R, Context, 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
1558 if (auto *M = getCurrentModule())
1560 else
1561 // We're not building a module; just make the definition visible.
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>(ND))
1567 for (auto *Param : *TD->getTemplateParameters())
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>(ND);
1576 ED && ED->isFromGlobalModule() && !ED->isScoped()) {
1577 for (auto *ECD : ED->enumerators()) {
1578 ECD->setVisibleDespiteOwningModule();
1579 DeclContext *RedeclCtx = ED->getDeclContext()->getRedeclContext();
1580 if (RedeclCtx->lookup(ECD->getDeclName()).empty())
1581 RedeclCtx->makeDeclVisibleInContext(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>(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;
1593 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1595 Entity = Pattern;
1596 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1597 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1598 Entity = Pattern;
1599 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1600 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1601 Entity = Pattern;
1602 }
1603
1604 // Walk up to the containing context. That might also have been instantiated
1605 // from a template.
1606 DeclContext *Context = Entity->getLexicalDeclContext();
1607 if (Context->isFileContext())
1608 return S.getOwningModule(Entity);
1609 return getDefiningModule(S, cast<Decl>(Context));
1610}
1611
1612llvm::DenseSet<Module*> &Sema::getLookupModules() {
1613 unsigned N = CodeSynthesisContexts.size();
1614 for (unsigned I = CodeSynthesisContextLookupModules.size();
1615 I != N; ++I) {
1616 Module *M = CodeSynthesisContexts[I].Entity ?
1617 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
1618 nullptr;
1619 if (M && !LookupModulesCache.insert(M).second)
1620 M = nullptr;
1622 }
1623 return LookupModulesCache;
1624}
1625
1626bool Sema::isUsableModule(const Module *M) {
1627 assert(M && "We shouldn't check nullness for module here");
1628 // Return quickly if we cached the result.
1629 if (UsableModuleUnitsCache.count(M))
1630 return true;
1631
1632 // If M is the global module fragment of the current translation unit. So it
1633 // should be usable.
1634 // [module.global.frag]p1:
1635 // The global module fragment can be used to provide declarations that are
1636 // attached to the global module and usable within the module unit.
1637 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment) {
1638 UsableModuleUnitsCache.insert(M);
1639 return true;
1640 }
1641
1642 // Otherwise, the global module fragment from other translation unit is not
1643 // directly usable.
1644 if (M->isExplicitGlobalModule())
1645 return false;
1646
1647 Module *Current = getCurrentModule();
1648
1649 // If we're not parsing a module, we can't use all the declarations from
1650 // another module easily.
1651 if (!Current)
1652 return false;
1653
1654 // For implicit global module, the decls in the same modules with the parent
1655 // module should be visible to the decls in the implicit global module.
1656 if (Current->isImplicitGlobalModule())
1657 Current = Current->getTopLevelModule();
1658 if (M->isImplicitGlobalModule())
1659 M = M->getTopLevelModule();
1660
1661 // If M is the module we're parsing or M and the current module unit lives in
1662 // the same module, M should be usable.
1663 //
1664 // Note: It should be fine to search the vector `ModuleScopes` linearly since
1665 // it should be generally small enough. There should be rare module fragments
1666 // in a named module unit.
1667 if (llvm::count_if(ModuleScopes,
1668 [&M](const ModuleScope &MS) { return MS.Module == M; }) ||
1669 getASTContext().isInSameModule(M, Current)) {
1670 UsableModuleUnitsCache.insert(M);
1671 return true;
1672 }
1673
1674 return false;
1675}
1676
1678 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1679 if (isModuleVisible(Merged))
1680 return true;
1681 return false;
1682}
1683
1685 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1686 if (isUsableModule(Merged))
1687 return true;
1688 return false;
1689}
1690
1691template <typename ParmDecl>
1692static bool
1695 Sema::AcceptableKind Kind) {
1696 if (!D->hasDefaultArgument())
1697 return false;
1698
1700 while (D && Visited.insert(D).second) {
1701 auto &DefaultArg = D->getDefaultArgStorage();
1702 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
1703 return true;
1704
1705 if (!DefaultArg.isInherited() && Modules) {
1706 auto *NonConstD = const_cast<ParmDecl*>(D);
1707 Modules->push_back(S.getOwningModule(NonConstD));
1708 }
1709
1710 // If there was a previous default argument, maybe its parameter is
1711 // acceptable.
1712 D = DefaultArg.getInheritedFrom();
1713 }
1714 return false;
1715}
1716
1719 Sema::AcceptableKind Kind) {
1720 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1721 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1722
1723 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1724 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1725
1726 return ::hasAcceptableDefaultArgument(
1727 *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
1728}
1729
1732 return hasAcceptableDefaultArgument(D, Modules,
1734}
1735
1737 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1738 return hasAcceptableDefaultArgument(D, Modules,
1740}
1741
1742template <typename Filter>
1743static bool
1745 llvm::SmallVectorImpl<Module *> *Modules, Filter F,
1746 Sema::AcceptableKind Kind) {
1747 bool HasFilteredRedecls = false;
1748
1749 for (auto *Redecl : D->redecls()) {
1750 auto *R = cast<NamedDecl>(Redecl);
1751 if (!F(R))
1752 continue;
1753
1754 if (S.isAcceptable(R, Kind))
1755 return true;
1756
1757 HasFilteredRedecls = true;
1758
1759 if (Modules)
1760 Modules->push_back(R->getOwningModule());
1761 }
1762
1763 // Only return false if there is at least one redecl that is not filtered out.
1764 if (HasFilteredRedecls)
1765 return false;
1766
1767 return true;
1768}
1769
1770static bool
1773 Sema::AcceptableKind Kind) {
1775 S, D, Modules,
1776 [](const NamedDecl *D) {
1777 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1778 return RD->getTemplateSpecializationKind() ==
1780 if (auto *FD = dyn_cast<FunctionDecl>(D))
1781 return FD->getTemplateSpecializationKind() ==
1783 if (auto *VD = dyn_cast<VarDecl>(D))
1784 return VD->getTemplateSpecializationKind() ==
1786 llvm_unreachable("unknown explicit specialization kind");
1787 },
1788 Kind);
1789}
1790
1792 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1793 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1795}
1796
1798 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1799 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1801}
1802
1803static bool
1806 Sema::AcceptableKind Kind) {
1807 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1808 "not a member specialization");
1810 S, D, Modules,
1811 [](const NamedDecl *D) {
1812 // If the specialization is declared at namespace scope, then it's a
1813 // member specialization declaration. If it's lexically inside the class
1814 // definition then it was instantiated.
1815 //
1816 // FIXME: This is a hack. There should be a better way to determine
1817 // this.
1818 // FIXME: What about MS-style explicit specializations declared within a
1819 // class definition?
1820 return D->getLexicalDeclContext()->isFileContext();
1821 },
1822 Kind);
1823}
1824
1826 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1827 return hasAcceptableMemberSpecialization(*this, D, Modules,
1829}
1830
1832 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1833 return hasAcceptableMemberSpecialization(*this, D, Modules,
1835}
1836
1837/// Determine whether a declaration is acceptable to name lookup.
1838///
1839/// This routine determines whether the declaration D is acceptable in the
1840/// current lookup context, taking into account the current template
1841/// instantiation stack. During template instantiation, a declaration is
1842/// acceptable if it is acceptable from a module containing any entity on the
1843/// template instantiation path (by instantiating a template, you allow it to
1844/// see the declarations that your module can see, including those later on in
1845/// your module).
1846bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
1847 Sema::AcceptableKind Kind) {
1848 assert(!D->isUnconditionallyVisible() &&
1849 "should not call this: not in slow case");
1850
1851 Module *DeclModule = SemaRef.getOwningModule(D);
1852 assert(DeclModule && "hidden decl has no owning module");
1853
1854 // If the owning module is visible, the decl is acceptable.
1855 if (SemaRef.isModuleVisible(DeclModule,
1857 return true;
1858
1859 // Determine whether a decl context is a file context for the purpose of
1860 // visibility/reachability. This looks through some (export and linkage spec)
1861 // transparent contexts, but not others (enums).
1862 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1863 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1864 isa<ExportDecl>(DC);
1865 };
1866
1867 // If this declaration is not at namespace scope
1868 // then it is acceptable if its lexical parent has a acceptable definition.
1870 if (DC && !IsEffectivelyFileContext(DC)) {
1871 // For a parameter, check whether our current template declaration's
1872 // lexical context is acceptable, not whether there's some other acceptable
1873 // definition of it, because parameters aren't "within" the definition.
1874 //
1875 // In C++ we need to check for a acceptable definition due to ODR merging,
1876 // and in C we must not because each declaration of a function gets its own
1877 // set of declarations for tags in prototype scope.
1878 bool AcceptableWithinParent;
1879 if (D->isTemplateParameter()) {
1880 bool SearchDefinitions = true;
1881 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1882 if (const auto *TD = DCD->getDescribedTemplate()) {
1883 TemplateParameterList *TPL = TD->getTemplateParameters();
1884 auto Index = getDepthAndIndex(D).second;
1885 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1886 }
1887 }
1888 if (SearchDefinitions)
1889 AcceptableWithinParent =
1890 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1891 else
1892 AcceptableWithinParent =
1893 isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1894 } else if (isa<ParmVarDecl>(D) ||
1895 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1896 AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1897 else if (D->isModulePrivate()) {
1898 // A module-private declaration is only acceptable if an enclosing lexical
1899 // parent was merged with another definition in the current module.
1900 AcceptableWithinParent = false;
1901 do {
1902 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1903 AcceptableWithinParent = true;
1904 break;
1905 }
1906 DC = DC->getLexicalParent();
1907 } while (!IsEffectivelyFileContext(DC));
1908 } else {
1909 AcceptableWithinParent =
1910 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1911 }
1912
1913 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1915 // FIXME: Do something better in this case.
1916 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1917 // Cache the fact that this declaration is implicitly visible because
1918 // its parent has a visible definition.
1920 }
1921 return AcceptableWithinParent;
1922 }
1923
1925 return false;
1926
1927 assert(Kind == Sema::AcceptableKind::Reachable &&
1928 "Additional Sema::AcceptableKind?");
1929 return isReachableSlow(SemaRef, D);
1930}
1931
1932bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1933 // The module might be ordinarily visible. For a module-private query, that
1934 // means it is part of the current module.
1935 if (ModulePrivate && isUsableModule(M))
1936 return true;
1937
1938 // For a query which is not module-private, that means it is in our visible
1939 // module set.
1940 if (!ModulePrivate && VisibleModules.isVisible(M))
1941 return true;
1942
1943 // Otherwise, it might be visible by virtue of the query being within a
1944 // template instantiation or similar that is permitted to look inside M.
1945
1946 // Find the extra places where we need to look.
1947 const auto &LookupModules = getLookupModules();
1948 if (LookupModules.empty())
1949 return false;
1950
1951 // If our lookup set contains the module, it's visible.
1952 if (LookupModules.count(M))
1953 return true;
1954
1955 // The global module fragments are visible to its corresponding module unit.
1956 // So the global module fragment should be visible if the its corresponding
1957 // module unit is visible.
1958 if (M->isGlobalModule() && LookupModules.count(M->getTopLevelModule()))
1959 return true;
1960
1961 // For a module-private query, that's everywhere we get to look.
1962 if (ModulePrivate)
1963 return false;
1964
1965 // Check whether M is transitively exported to an import of the lookup set.
1966 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1967 return LookupM->isModuleVisible(M);
1968 });
1969}
1970
1971// FIXME: Return false directly if we don't have an interface dependency on the
1972// translation unit containing D.
1973bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
1974 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
1975
1976 Module *DeclModule = SemaRef.getOwningModule(D);
1977 assert(DeclModule && "hidden decl has no owning module");
1978
1979 // Entities in header like modules are reachable only if they're visible.
1980 if (DeclModule->isHeaderLikeModule())
1981 return false;
1982
1983 if (!D->isInAnotherModuleUnit())
1984 return true;
1985
1986 // [module.reach]/p3:
1987 // A declaration D is reachable from a point P if:
1988 // ...
1989 // - D is not discarded ([module.global.frag]), appears in a translation unit
1990 // that is reachable from P, and does not appear within a private module
1991 // fragment.
1992 //
1993 // A declaration that's discarded in the GMF should be module-private.
1994 if (D->isModulePrivate())
1995 return false;
1996
1997 Module *DeclTopModule = DeclModule->getTopLevelModule();
1998
1999 // [module.reach]/p1
2000 // A translation unit U is necessarily reachable from a point P if U is a
2001 // module interface unit on which the translation unit containing P has an
2002 // interface dependency, or the translation unit containing P imports U, in
2003 // either case prior to P ([module.import]).
2004 //
2005 // [module.import]/p10
2006 // A translation unit has an interface dependency on a translation unit U if
2007 // it contains a declaration (possibly a module-declaration) that imports U
2008 // or if it has an interface dependency on a translation unit that has an
2009 // interface dependency on U.
2010 //
2011 // So we could conclude the module unit U is necessarily reachable if:
2012 // (1) The module unit U is module interface unit.
2013 // (2) The current unit has an interface dependency on the module unit U.
2014 //
2015 // Here we only check for the first condition. Since we couldn't see
2016 // DeclModule if it isn't (transitively) imported.
2017 if (DeclTopModule->isModuleInterfaceUnit())
2018 return true;
2019
2020 // [module.reach]/p1,2
2021 // A translation unit U is necessarily reachable from a point P if U is a
2022 // module interface unit on which the translation unit containing P has an
2023 // interface dependency, or the translation unit containing P imports U, in
2024 // either case prior to P
2025 //
2026 // Additional translation units on
2027 // which the point within the program has an interface dependency may be
2028 // considered reachable, but it is unspecified which are and under what
2029 // circumstances.
2030 Module *CurrentM = SemaRef.getCurrentModule();
2031
2032 // Directly imported module are necessarily reachable.
2033 // Since we can't export import a module implementation partition unit, we
2034 // don't need to count for Exports here.
2035 if (CurrentM && CurrentM->getTopLevelModule()->Imports.count(DeclTopModule))
2036 return true;
2037
2038 // Then we treat all module implementation partition unit as unreachable.
2039 return false;
2040}
2041
2042bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
2043 return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);
2044}
2045
2046bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
2047 // FIXME: If there are both visible and hidden declarations, we need to take
2048 // into account whether redeclaration is possible. Example:
2049 //
2050 // Non-imported module:
2051 // int f(T); // #1
2052 // Some TU:
2053 // static int f(U); // #2, not a redeclaration of #1
2054 // int f(T); // #3, finds both, should link with #1 if T != U, but
2055 // // with #2 if T == U; neither should be ambiguous.
2056 for (auto *D : R) {
2057 if (isVisible(D))
2058 return true;
2059 assert(D->isExternallyDeclarable() &&
2060 "should not have hidden, non-externally-declarable result here");
2061 }
2062
2063 // This function is called once "New" is essentially complete, but before a
2064 // previous declaration is attached. We can't query the linkage of "New" in
2065 // general, because attaching the previous declaration can change the
2066 // linkage of New to match the previous declaration.
2067 //
2068 // However, because we've just determined that there is no *visible* prior
2069 // declaration, we can compute the linkage here. There are two possibilities:
2070 //
2071 // * This is not a redeclaration; it's safe to compute the linkage now.
2072 //
2073 // * This is a redeclaration of a prior declaration that is externally
2074 // redeclarable. In that case, the linkage of the declaration is not
2075 // changed by attaching the prior declaration, because both are externally
2076 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
2077 //
2078 // FIXME: This is subtle and fragile.
2079 return New->isExternallyDeclarable();
2080}
2081
2082/// Retrieve the visible declaration corresponding to D, if any.
2083///
2084/// This routine determines whether the declaration D is visible in the current
2085/// module, with the current imports. If not, it checks whether any
2086/// redeclaration of D is visible, and if so, returns that declaration.
2087///
2088/// \returns D, or a visible previous declaration of D, whichever is more recent
2089/// and visible. If no declaration of D is visible, returns null.
2091 unsigned IDNS) {
2092 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
2093
2094 for (auto *RD : D->redecls()) {
2095 // Don't bother with extra checks if we already know this one isn't visible.
2096 if (RD == D)
2097 continue;
2098
2099 auto ND = cast<NamedDecl>(RD);
2100 // FIXME: This is wrong in the case where the previous declaration is not
2101 // visible in the same scope as D. This needs to be done much more
2102 // carefully.
2103 if (ND->isInIdentifierNamespace(IDNS) &&
2105 return ND;
2106 }
2107
2108 return nullptr;
2109}
2110
2113 assert(!isVisible(D) && "not in slow case");
2115 *this, D, Modules, [](const NamedDecl *) { return true; },
2117}
2118
2120 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
2121 assert(!isReachable(D) && "not in slow case");
2123 *this, D, Modules, [](const NamedDecl *) { return true; },
2125}
2126
2127NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
2128 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
2129 // Namespaces are a bit of a special case: we expect there to be a lot of
2130 // redeclarations of some namespaces, all declarations of a namespace are
2131 // essentially interchangeable, all declarations are found by name lookup
2132 // if any is, and namespaces are never looked up during template
2133 // instantiation. So we benefit from caching the check in this case, and
2134 // it is correct to do so.
2135 auto *Key = ND->getCanonicalDecl();
2136 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
2137 return Acceptable;
2138 auto *Acceptable = isVisible(getSema(), Key)
2139 ? Key
2140 : findAcceptableDecl(getSema(), Key, IDNS);
2141 if (Acceptable)
2142 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
2143 return Acceptable;
2144 }
2145
2146 return findAcceptableDecl(getSema(), D, IDNS);
2147}
2148
2150 // If this declaration is already visible, return it directly.
2152 return true;
2153
2154 // During template instantiation, we can refer to hidden declarations, if
2155 // they were visible in any module along the path of instantiation.
2156 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);
2157}
2158
2161 return true;
2162
2163 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);
2164}
2165
2167 // We should check the visibility at the callsite already.
2168 if (isVisible(SemaRef, ND))
2169 return true;
2170
2171 // Deduction guide lives in namespace scope generally, but it is just a
2172 // hint to the compilers. What we actually lookup for is the generated member
2173 // of the corresponding template. So it is sufficient to check the
2174 // reachability of the template decl.
2175 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())
2176 return SemaRef.hasReachableDefinition(DeductionGuide);
2177
2178 // FIXME: The lookup for allocation function is a standalone process.
2179 // (We can find the logics in Sema::FindAllocationFunctions)
2180 //
2181 // Such structure makes it a problem when we instantiate a template
2182 // declaration using placement allocation function if the placement
2183 // allocation function is invisible.
2184 // (See https://github.com/llvm/llvm-project/issues/59601)
2185 //
2186 // Here we workaround it by making the placement allocation functions
2187 // always acceptable. The downside is that we can't diagnose the direct
2188 // use of the invisible placement allocation functions. (Although such uses
2189 // should be rare).
2190 if (auto *FD = dyn_cast<FunctionDecl>(ND);
2191 FD && FD->isReservedGlobalPlacementOperator())
2192 return true;
2193
2194 auto *DC = ND->getDeclContext();
2195 // If ND is not visible and it is at namespace scope, it shouldn't be found
2196 // by name lookup.
2197 if (DC->isFileContext())
2198 return false;
2199
2200 // [module.interface]p7
2201 // Class and enumeration member names can be found by name lookup in any
2202 // context in which a definition of the type is reachable.
2203 //
2204 // NOTE: The above wording may be problematic. See
2205 // https://github.com/llvm/llvm-project/issues/131058 But it is much complext
2206 // to adjust it in Sema's lookup process. Now we hacked it in ASTWriter. See
2207 // the comments in ASTDeclContextNameLookupTrait::getLookupVisibility.
2208 if (auto *TD = dyn_cast<TagDecl>(DC))
2209 return SemaRef.hasReachableDefinition(TD);
2210
2211 return false;
2212}
2213
2214bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
2215 bool ForceNoCPlusPlus) {
2216 DeclarationName Name = R.getLookupName();
2217 if (!Name) return false;
2218
2219 LookupNameKind NameKind = R.getLookupKind();
2220
2221 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
2222 // Unqualified name lookup in C/Objective-C is purely lexical, so
2223 // search in the declarations attached to the name.
2224 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
2225 // Find the nearest non-transparent declaration scope.
2226 while (!(S->getFlags() & Scope::DeclScope) ||
2227 (S->getEntity() && S->getEntity()->isTransparentContext()))
2228 S = S->getParent();
2229 }
2230
2231 // When performing a scope lookup, we want to find local extern decls.
2232 FindLocalExternScope FindLocals(R);
2233
2234 // Scan up the scope chain looking for a decl that matches this
2235 // identifier that is in the appropriate namespace. This search
2236 // should not take long, as shadowing of names is uncommon, and
2237 // deep shadowing is extremely uncommon.
2238 bool LeftStartingScope = false;
2239
2241 IEnd = IdResolver.end();
2242 I != IEnd; ++I)
2243 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
2244 if (NameKind == LookupRedeclarationWithLinkage) {
2245 // Determine whether this (or a previous) declaration is
2246 // out-of-scope.
2247 if (!LeftStartingScope && !S->isDeclScope(*I))
2248 LeftStartingScope = true;
2249
2250 // If we found something outside of our starting scope that
2251 // does not have linkage, skip it.
2252 if (LeftStartingScope && !((*I)->hasLinkage())) {
2253 R.setShadowed();
2254 continue;
2255 }
2256 }
2257 else if (NameKind == LookupObjCImplicitSelfParam &&
2258 !isa<ImplicitParamDecl>(*I))
2259 continue;
2260
2261 R.addDecl(D);
2262
2263 // Check whether there are any other declarations with the same name
2264 // and in the same scope.
2265 if (I != IEnd) {
2266 // Find the scope in which this declaration was declared (if it
2267 // actually exists in a Scope).
2268 while (S && !S->isDeclScope(D))
2269 S = S->getParent();
2270
2271 // If the scope containing the declaration is the translation unit,
2272 // then we'll need to perform our checks based on the matching
2273 // DeclContexts rather than matching scopes.
2275 S = nullptr;
2276
2277 // Compute the DeclContext, if we need it.
2278 DeclContext *DC = nullptr;
2279 if (!S)
2280 DC = (*I)->getDeclContext()->getRedeclContext();
2281
2283 for (++LastI; LastI != IEnd; ++LastI) {
2284 if (S) {
2285 // Match based on scope.
2286 if (!S->isDeclScope(*LastI))
2287 break;
2288 } else {
2289 // Match based on DeclContext.
2290 DeclContext *LastDC
2291 = (*LastI)->getDeclContext()->getRedeclContext();
2292 if (!LastDC->Equals(DC))
2293 break;
2294 }
2295
2296 // If the declaration is in the right namespace and visible, add it.
2297 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
2298 R.addDecl(LastD);
2299 }
2300
2301 R.resolveKind();
2302 }
2303
2304 return true;
2305 }
2306 } else {
2307 // Perform C++ unqualified name lookup.
2308 if (CppLookupName(R, S))
2309 return true;
2310 }
2311
2312 // If we didn't find a use of this identifier, and if the identifier
2313 // corresponds to a compiler builtin, create the decl object for the builtin
2314 // now, injecting it into translation unit scope, and return it.
2315 if (AllowBuiltinCreation && LookupBuiltin(R))
2316 return true;
2317
2318 // If we didn't find a use of this identifier, the ExternalSource
2319 // may be able to handle the situation.
2320 // Note: some lookup failures are expected!
2321 // See e.g. R.isForRedeclaration().
2322 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2323}
2324
2325/// Perform qualified name lookup in the namespaces nominated by
2326/// using directives by the given context.
2327///
2328/// C++98 [namespace.qual]p2:
2329/// Given X::m (where X is a user-declared namespace), or given \::m
2330/// (where X is the global namespace), let S be the set of all
2331/// declarations of m in X and in the transitive closure of all
2332/// namespaces nominated by using-directives in X and its used
2333/// namespaces, except that using-directives are ignored in any
2334/// namespace, including X, directly containing one or more
2335/// declarations of m. No namespace is searched more than once in
2336/// the lookup of a name. If S is the empty set, the program is
2337/// ill-formed. Otherwise, if S has exactly one member, or if the
2338/// context of the reference is a using-declaration
2339/// (namespace.udecl), S is the required set of declarations of
2340/// m. Otherwise if the use of m is not one that allows a unique
2341/// declaration to be chosen from S, the program is ill-formed.
2342///
2343/// C++98 [namespace.qual]p5:
2344/// During the lookup of a qualified namespace member name, if the
2345/// lookup finds more than one declaration of the member, and if one
2346/// declaration introduces a class name or enumeration name and the
2347/// other declarations either introduce the same object, the same
2348/// enumerator or a set of functions, the non-type name hides the
2349/// class or enumeration name if and only if the declarations are
2350/// from the same namespace; otherwise (the declarations are from
2351/// different namespaces), the program is ill-formed.
2353 DeclContext *StartDC) {
2354 assert(StartDC->isFileContext() && "start context is not a file context");
2355
2356 // We have not yet looked into these namespaces, much less added
2357 // their "using-children" to the queue.
2359
2360 // We have at least added all these contexts to the queue.
2362 Visited.insert(StartDC);
2363
2364 // We have already looked into the initial namespace; seed the queue
2365 // with its using-children.
2366 for (auto *I : StartDC->using_directives()) {
2367 NamespaceDecl *ND = I->getNominatedNamespace()->getFirstDecl();
2368 if (S.isVisible(I) && Visited.insert(ND).second)
2369 Queue.push_back(ND);
2370 }
2371
2372 // The easiest way to implement the restriction in [namespace.qual]p5
2373 // is to check whether any of the individual results found a tag
2374 // and, if so, to declare an ambiguity if the final result is not
2375 // a tag.
2376 bool FoundTag = false;
2377 bool FoundNonTag = false;
2378
2380
2381 bool Found = false;
2382 while (!Queue.empty()) {
2383 NamespaceDecl *ND = Queue.pop_back_val();
2384
2385 // We go through some convolutions here to avoid copying results
2386 // between LookupResults.
2387 bool UseLocal = !R.empty();
2388 LookupResult &DirectR = UseLocal ? LocalR : R;
2389 bool FoundDirect = LookupDirect(S, DirectR, ND);
2390
2391 if (FoundDirect) {
2392 // First do any local hiding.
2393 DirectR.resolveKind();
2394
2395 // If the local result is a tag, remember that.
2396 if (DirectR.isSingleTagDecl())
2397 FoundTag = true;
2398 else
2399 FoundNonTag = true;
2400
2401 // Append the local results to the total results if necessary.
2402 if (UseLocal) {
2403 R.addAllDecls(LocalR);
2404 LocalR.clear();
2405 }
2406 }
2407
2408 // If we find names in this namespace, ignore its using directives.
2409 if (FoundDirect) {
2410 Found = true;
2411 continue;
2412 }
2413
2414 for (auto *I : ND->using_directives()) {
2415 NamespaceDecl *Nom = I->getNominatedNamespace();
2416 if (S.isVisible(I) && Visited.insert(Nom).second)
2417 Queue.push_back(Nom);
2418 }
2419 }
2420
2421 if (Found) {
2422 if (FoundTag && FoundNonTag)
2424 else
2425 R.resolveKind();
2426 }
2427
2428 return Found;
2429}
2430
2432 bool InUnqualifiedLookup) {
2433 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2434
2435 if (!R.getLookupName())
2436 return false;
2437
2438#ifndef NDEBUG
2439 // Make sure that the declaration context is complete.
2440 if (const auto *TD = dyn_cast<TagDecl>(LookupCtx);
2441 TD && !TD->isDependentType() && TD->getDefinition() == nullptr)
2442 llvm_unreachable("Declaration context must already be complete!");
2443#endif
2444
2445 struct QualifiedLookupInScope {
2446 bool oldVal;
2447 DeclContext *Context;
2448 // Set flag in DeclContext informing debugger that we're looking for qualified name
2449 QualifiedLookupInScope(DeclContext *ctx)
2450 : oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) {
2451 ctx->setUseQualifiedLookup();
2452 }
2453 ~QualifiedLookupInScope() {
2454 Context->setUseQualifiedLookup(oldVal);
2455 }
2456 } QL(LookupCtx);
2457
2458 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2459 // FIXME: Per [temp.dep.general]p2, an unqualified name is also dependent
2460 // if it's a dependent conversion-function-id or operator= where the current
2461 // class is a templated entity. This should be handled in LookupName.
2462 if (!InUnqualifiedLookup && !R.isForRedeclaration()) {
2463 // C++23 [temp.dep.type]p5:
2464 // A qualified name is dependent if
2465 // - it is a conversion-function-id whose conversion-type-id
2466 // is dependent, or
2467 // - [...]
2468 // - its lookup context is the current instantiation and it
2469 // is operator=, or
2470 // - [...]
2471 if (DeclarationName Name = R.getLookupName();
2472 Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2473 Name.getCXXNameType()->isDependentType()) {
2475 return false;
2476 }
2477 }
2478
2479 if (LookupDirect(*this, R, LookupCtx)) {
2480 R.resolveKind();
2481 if (LookupRec)
2482 R.setNamingClass(LookupRec);
2483 return true;
2484 }
2485
2486 // Don't descend into implied contexts for redeclarations.
2487 // C++98 [namespace.qual]p6:
2488 // In a declaration for a namespace member in which the
2489 // declarator-id is a qualified-id, given that the qualified-id
2490 // for the namespace member has the form
2491 // nested-name-specifier unqualified-id
2492 // the unqualified-id shall name a member of the namespace
2493 // designated by the nested-name-specifier.
2494 // See also [class.mfct]p5 and [class.static.data]p2.
2495 if (R.isForRedeclaration())
2496 return false;
2497
2498 // If this is a namespace, look it up in the implied namespaces.
2499 if (LookupCtx->isFileContext())
2500 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2501
2502 // If this isn't a C++ class, we aren't allowed to look into base
2503 // classes, we're done.
2504 if (!LookupRec || !LookupRec->getDefinition())
2505 return false;
2506
2507 // We're done for lookups that can never succeed for C++ classes.
2508 if (R.getLookupKind() == LookupOperatorName ||
2512 return false;
2513
2514 // If we're performing qualified name lookup into a dependent class,
2515 // then we are actually looking into a current instantiation. If we have any
2516 // dependent base classes, then we either have to delay lookup until
2517 // template instantiation time (at which point all bases will be available)
2518 // or we have to fail.
2519 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2520 LookupRec->hasAnyDependentBases()) {
2522 return false;
2523 }
2524
2525 // Perform lookup into our base classes.
2526
2527 DeclarationName Name = R.getLookupName();
2528 unsigned IDNS = R.getIdentifierNamespace();
2529
2530 // Look for this member in our base classes.
2531 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2532 CXXBasePath &Path) -> bool {
2533 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2534 // Drop leading non-matching lookup results from the declaration list so
2535 // we don't need to consider them again below.
2536 for (Path.Decls = BaseRecord->lookup(Name).begin();
2537 Path.Decls != Path.Decls.end(); ++Path.Decls) {
2538 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2539 return true;
2540 }
2541 return false;
2542 };
2543
2544 CXXBasePaths Paths;
2545 Paths.setOrigin(LookupRec);
2546 if (!LookupRec->lookupInBases(BaseCallback, Paths))
2547 return false;
2548
2549 R.setNamingClass(LookupRec);
2550
2551 // C++ [class.member.lookup]p2:
2552 // [...] If the resulting set of declarations are not all from
2553 // sub-objects of the same type, or the set has a nonstatic member
2554 // and includes members from distinct sub-objects, there is an
2555 // ambiguity and the program is ill-formed. Otherwise that set is
2556 // the result of the lookup.
2557 QualType SubobjectType;
2558 int SubobjectNumber = 0;
2559 AccessSpecifier SubobjectAccess = AS_none;
2560
2561 // Check whether the given lookup result contains only static members.
2562 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2563 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2564 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2565 return false;
2566 return true;
2567 };
2568
2569 bool TemplateNameLookup = R.isTemplateNameLookup();
2570
2571 // Determine whether two sets of members contain the same members, as
2572 // required by C++ [class.member.lookup]p6.
2573 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2575 using Iterator = DeclContextLookupResult::iterator;
2576 using Result = const void *;
2577
2578 auto Next = [&](Iterator &It, Iterator End) -> Result {
2579 while (It != End) {
2580 NamedDecl *ND = *It++;
2581 if (!ND->isInIdentifierNamespace(IDNS))
2582 continue;
2583
2584 // C++ [temp.local]p3:
2585 // A lookup that finds an injected-class-name (10.2) can result in
2586 // an ambiguity in certain cases (for example, if it is found in
2587 // more than one base class). If all of the injected-class-names
2588 // that are found refer to specializations of the same class
2589 // template, and if the name is used as a template-name, the
2590 // reference refers to the class template itself and not a
2591 // specialization thereof, and is not ambiguous.
2592 if (TemplateNameLookup)
2593 if (auto *TD = getAsTemplateNameDecl(ND))
2594 ND = TD;
2595
2596 // C++ [class.member.lookup]p3:
2597 // type declarations (including injected-class-names) are replaced by
2598 // the types they designate
2599 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl()))
2601
2602 return ND->getUnderlyingDecl()->getCanonicalDecl();
2603 }
2604 return nullptr;
2605 };
2606
2607 // We'll often find the declarations are in the same order. Handle this
2608 // case (and the special case of only one declaration) efficiently.
2609 Iterator AIt = A, BIt = B, AEnd, BEnd;
2610 while (true) {
2611 Result AResult = Next(AIt, AEnd);
2612 Result BResult = Next(BIt, BEnd);
2613 if (!AResult && !BResult)
2614 return true;
2615 if (!AResult || !BResult)
2616 return false;
2617 if (AResult != BResult) {
2618 // Found a mismatch; carefully check both lists, accounting for the
2619 // possibility of declarations appearing more than once.
2620 llvm::SmallDenseMap<Result, bool, 32> AResults;
2621 for (; AResult; AResult = Next(AIt, AEnd))
2622 AResults.insert({AResult, /*FoundInB*/false});
2623 unsigned Found = 0;
2624 for (; BResult; BResult = Next(BIt, BEnd)) {
2625 auto It = AResults.find(BResult);
2626 if (It == AResults.end())
2627 return false;
2628 if (!It->second) {
2629 It->second = true;
2630 ++Found;
2631 }
2632 }
2633 return AResults.size() == Found;
2634 }
2635 }
2636 };
2637
2638 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2639 Path != PathEnd; ++Path) {
2640 const CXXBasePathElement &PathElement = Path->back();
2641
2642 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2643 // across all paths.
2644 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2645
2646 // Determine whether we're looking at a distinct sub-object or not.
2647 if (SubobjectType.isNull()) {
2648 // This is the first subobject we've looked at. Record its type.
2649 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2650 SubobjectNumber = PathElement.SubobjectNumber;
2651 continue;
2652 }
2653
2654 if (SubobjectType !=
2655 Context.getCanonicalType(PathElement.Base->getType())) {
2656 // We found members of the given name in two subobjects of
2657 // different types. If the declaration sets aren't the same, this
2658 // lookup is ambiguous.
2659 //
2660 // FIXME: The language rule says that this applies irrespective of
2661 // whether the sets contain only static members.
2662 if (HasOnlyStaticMembers(Path->Decls) &&
2663 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2664 continue;
2665
2666 R.setAmbiguousBaseSubobjectTypes(Paths);
2667 return true;
2668 }
2669
2670 // FIXME: This language rule no longer exists. Checking for ambiguous base
2671 // subobjects should be done as part of formation of a class member access
2672 // expression (when converting the object parameter to the member's type).
2673 if (SubobjectNumber != PathElement.SubobjectNumber) {
2674 // We have a different subobject of the same type.
2675
2676 // C++ [class.member.lookup]p5:
2677 // A static member, a nested type or an enumerator defined in
2678 // a base class T can unambiguously be found even if an object
2679 // has more than one base class subobject of type T.
2680 if (HasOnlyStaticMembers(Path->Decls))
2681 continue;
2682
2683 // We have found a nonstatic member name in multiple, distinct
2684 // subobjects. Name lookup is ambiguous.
2685 R.setAmbiguousBaseSubobjects(Paths);
2686 return true;
2687 }
2688 }
2689
2690 // Lookup in a base class succeeded; return these results.
2691
2692 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2693 I != E; ++I) {
2694 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2695 (*I)->getAccess());
2696 if (NamedDecl *ND = R.getAcceptableDecl(*I))
2697 R.addDecl(ND, AS);
2698 }
2699 R.resolveKind();
2700 return true;
2701}
2702
2704 CXXScopeSpec &SS) {
2705 NestedNameSpecifier Qualifier = SS.getScopeRep();
2706 if (Qualifier.getKind() == NestedNameSpecifier::Kind::MicrosoftSuper)
2707 return LookupInSuper(R, Qualifier.getAsMicrosoftSuper());
2708 return LookupQualifiedName(R, LookupCtx);
2709}
2710
2712 QualType ObjectType, bool AllowBuiltinCreation,
2713 bool EnteringContext) {
2714 // When the scope specifier is invalid, don't even look for anything.
2715 if (SS && SS->isInvalid())
2716 return false;
2717
2718 // Determine where to perform name lookup
2719 DeclContext *DC = nullptr;
2720 bool IsDependent = false;
2721 if (!ObjectType.isNull()) {
2722 // This nested-name-specifier occurs in a member access expression, e.g.,
2723 // x->B::f, and we are looking into the type of the object.
2724 assert((!SS || SS->isEmpty()) &&
2725 "ObjectType and scope specifier cannot coexist");
2726 DC = computeDeclContext(ObjectType);
2727 IsDependent = !DC && ObjectType->isDependentType();
2728 assert(((!DC && ObjectType->isDependentType()) ||
2729 !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() ||
2730 ObjectType->castAs<TagType>()
2731 ->getOriginalDecl()
2732 ->isEntityBeingDefined()) &&
2733 "Caller should have completed object type");
2734 } else if (SS && SS->isNotEmpty()) {
2735 // This nested-name-specifier occurs after another nested-name-specifier,
2736 // so long into the context associated with the prior nested-name-specifier.
2737 if ((DC = computeDeclContext(*SS, EnteringContext))) {
2738 // The declaration context must be complete.
2739 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2740 return false;
2741 R.setContextRange(SS->getRange());
2742 // FIXME: '__super' lookup semantics could be implemented by a
2743 // LookupResult::isSuperLookup flag which skips the initial search of
2744 // the lookup context in LookupQualified.
2745 if (NestedNameSpecifier Qualifier = SS->getScopeRep();
2746 Qualifier.getKind() == NestedNameSpecifier::Kind::MicrosoftSuper)
2747 return LookupInSuper(R, Qualifier.getAsMicrosoftSuper());
2748 }
2749 IsDependent = !DC && isDependentScopeSpecifier(*SS);
2750 } else {
2751 // Perform unqualified name lookup starting in the given scope.
2752 return LookupName(R, S, AllowBuiltinCreation);
2753 }
2754
2755 // If we were able to compute a declaration context, perform qualified name
2756 // lookup in that context.
2757 if (DC)
2758 return LookupQualifiedName(R, DC);
2759 else if (IsDependent)
2760 // We could not resolve the scope specified to a specific declaration
2761 // context, which means that SS refers to an unknown specialization.
2762 // Name lookup can't find anything in this case.
2764 return false;
2765}
2766
2768 // The access-control rules we use here are essentially the rules for
2769 // doing a lookup in Class that just magically skipped the direct
2770 // members of Class itself. That is, the naming class is Class, and the
2771 // access includes the access of the base.
2772 for (const auto &BaseSpec : Class->bases()) {
2773 auto *RD = BaseSpec.getType()->castAsCXXRecordDecl();
2775 Result.setBaseObjectType(Context.getCanonicalTagType(Class));
2777
2778 // Copy the lookup results into the target, merging the base's access into
2779 // the path access.
2780 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2781 R.addDecl(I.getDecl(),
2782 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2783 I.getAccess()));
2784 }
2785
2786 Result.suppressDiagnostics();
2787 }
2788
2789 R.resolveKind();
2791
2792 return !R.empty();
2793}
2794
2796 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2797
2798 DeclarationName Name = Result.getLookupName();
2799 SourceLocation NameLoc = Result.getNameLoc();
2800 SourceRange LookupRange = Result.getContextRange();
2801
2802 switch (Result.getAmbiguityKind()) {
2804 CXXBasePaths *Paths = Result.getBasePaths();
2805 QualType SubobjectType = Paths->front().back().Base->getType();
2806 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2807 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2808 << LookupRange;
2809
2810 DeclContext::lookup_iterator Found = Paths->front().Decls;
2811 while (isa<CXXMethodDecl>(*Found) &&
2812 cast<CXXMethodDecl>(*Found)->isStatic())
2813 ++Found;
2814
2815 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2816 break;
2817 }
2818
2820 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2821 << Name << LookupRange;
2822
2823 CXXBasePaths *Paths = Result.getBasePaths();
2824 std::set<const NamedDecl *> DeclsPrinted;
2825 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2826 PathEnd = Paths->end();
2827 Path != PathEnd; ++Path) {
2828 const NamedDecl *D = *Path->Decls;
2829 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2830 continue;
2831 if (DeclsPrinted.insert(D).second) {
2832 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2833 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2834 << TD->getUnderlyingType();
2835 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2836 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2837 << Context.getTypeDeclType(TD);
2838 else
2839 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2840 }
2841 }
2842 break;
2843 }
2844
2846 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2847
2849
2850 for (auto *D : Result)
2851 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2852 TagDecls.insert(TD);
2853 Diag(TD->getLocation(), diag::note_hidden_tag);
2854 }
2855
2856 for (auto *D : Result)
2857 if (!isa<TagDecl>(D))
2858 Diag(D->getLocation(), diag::note_hiding_object);
2859
2860 // For recovery purposes, go ahead and implement the hiding.
2861 LookupResult::Filter F = Result.makeFilter();
2862 while (F.hasNext()) {
2863 if (TagDecls.count(F.next()))
2864 F.erase();
2865 }
2866 F.done();
2867 break;
2868 }
2869
2871 Diag(NameLoc, diag::err_using_placeholder_variable) << Name << LookupRange;
2872 DeclContext *DC = nullptr;
2873 for (auto *D : Result) {
2874 Diag(D->getLocation(), diag::note_reference_placeholder) << D;
2875 if (DC != nullptr && DC != D->getDeclContext())
2876 break;
2877 DC = D->getDeclContext();
2878 }
2879 break;
2880 }
2881
2883 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2884
2885 for (auto *D : Result)
2886 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2887 break;
2888 }
2889 }
2890}
2891
2892namespace {
2893 struct AssociatedLookup {
2894 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2895 Sema::AssociatedNamespaceSet &Namespaces,
2896 Sema::AssociatedClassSet &Classes)
2897 : S(S), Namespaces(Namespaces), Classes(Classes),
2898 InstantiationLoc(InstantiationLoc) {
2899 }
2900
2901 bool addClassTransitive(CXXRecordDecl *RD) {
2902 Classes.insert(RD);
2903 return ClassesTransitive.insert(RD);
2904 }
2905
2906 Sema &S;
2907 Sema::AssociatedNamespaceSet &Namespaces;
2908 Sema::AssociatedClassSet &Classes;
2909 SourceLocation InstantiationLoc;
2910
2911 private:
2912 Sema::AssociatedClassSet ClassesTransitive;
2913 };
2914} // end anonymous namespace
2915
2916static void
2918
2919// Given the declaration context \param Ctx of a class, class template or
2920// enumeration, add the associated namespaces to \param Namespaces as described
2921// in [basic.lookup.argdep]p2.
2923 DeclContext *Ctx) {
2924 // The exact wording has been changed in C++14 as a result of
2925 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2926 // to all language versions since it is possible to return a local type
2927 // from a lambda in C++11.
2928 //
2929 // C++14 [basic.lookup.argdep]p2:
2930 // If T is a class type [...]. Its associated namespaces are the innermost
2931 // enclosing namespaces of its associated classes. [...]
2932 //
2933 // If T is an enumeration type, its associated namespace is the innermost
2934 // enclosing namespace of its declaration. [...]
2935
2936 // We additionally skip inline namespaces. The innermost non-inline namespace
2937 // contains all names of all its nested inline namespaces anyway, so we can
2938 // replace the entire inline namespace tree with its root.
2939 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2940 Ctx = Ctx->getParent();
2941
2942 // Actually it is fine to always do `Namespaces.insert(Ctx);` simply. But it
2943 // may cause more allocations in Namespaces and more unnecessary lookups. So
2944 // we'd like to insert the representative namespace only.
2945 DeclContext *PrimaryCtx = Ctx->getPrimaryContext();
2946 Decl *PrimaryD = cast<Decl>(PrimaryCtx);
2947 Decl *D = cast<Decl>(Ctx);
2948 ASTContext &AST = D->getASTContext();
2949
2950 // TODO: Technically it is better to insert one namespace per module. e.g.,
2951 //
2952 // ```
2953 // //--- first.cppm
2954 // export module first;
2955 // namespace ns { ... } // first namespace
2956 //
2957 // //--- m-partA.cppm
2958 // export module m:partA;
2959 // import first;
2960 //
2961 // namespace ns { ... }
2962 // namespace ns { ... }
2963 //
2964 // //--- m-partB.cppm
2965 // export module m:partB;
2966 // import first;
2967 // import :partA;
2968 //
2969 // namespace ns { ... }
2970 // namespace ns { ... }
2971 //
2972 // ...
2973 //
2974 // //--- m-partN.cppm
2975 // export module m:partN;
2976 // import first;
2977 // import :partA;
2978 // ...
2979 // import :part$(N-1);
2980 //
2981 // namespace ns { ... }
2982 // namespace ns { ... }
2983 //
2984 // consume(ns::any_decl); // the lookup
2985 // ```
2986 //
2987 // We should only insert once for all namespaces in module m.
2988 if (D->isInNamedModule() &&
2989 !AST.isInSameModule(D->getOwningModule(), PrimaryD->getOwningModule()))
2990 Namespaces.insert(Ctx);
2991 else
2992 Namespaces.insert(PrimaryCtx);
2993}
2994
2995// Add the associated classes and namespaces for argument-dependent
2996// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2997static void
2999 const TemplateArgument &Arg) {
3000 // C++ [basic.lookup.argdep]p2, last bullet:
3001 // -- [...] ;
3002 switch (Arg.getKind()) {
3004 break;
3005
3007 // [...] the namespaces and classes associated with the types of the
3008 // template arguments provided for template type parameters (excluding
3009 // template template parameters)
3011 break;
3012
3015 // [...] the namespaces in which any template template arguments are
3016 // defined; and the classes in which any member templates used as
3017 // template template arguments are defined.
3019 if (ClassTemplateDecl *ClassTemplate
3020 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
3021 DeclContext *Ctx = ClassTemplate->getDeclContext();
3022 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3023 Result.Classes.insert(EnclosingClass);
3024 // Add the associated namespace for this class.
3025 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3026 }
3027 break;
3028 }
3029
3035 // [Note: non-type template arguments do not contribute to the set of
3036 // associated namespaces. ]
3037 break;
3038
3040 for (const auto &P : Arg.pack_elements())
3042 break;
3043 }
3044}
3045
3046// Add the associated classes and namespaces for argument-dependent lookup
3047// with an argument of class type (C++ [basic.lookup.argdep]p2).
3048static void
3051
3052 // Just silently ignore anything whose name is __va_list_tag.
3053 if (Class->getDeclName() == Result.S.VAListTagName)
3054 return;
3055
3056 // C++ [basic.lookup.argdep]p2:
3057 // [...]
3058 // -- If T is a class type (including unions), its associated
3059 // classes are: the class itself; the class of which it is a
3060 // member, if any; and its direct and indirect base classes.
3061 // Its associated namespaces are the innermost enclosing
3062 // namespaces of its associated classes.
3063
3064 // Add the class of which it is a member, if any.
3065 DeclContext *Ctx = Class->getDeclContext();
3066 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3067 Result.Classes.insert(EnclosingClass);
3068
3069 // Add the associated namespace for this class.
3070 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3071
3072 // -- If T is a template-id, its associated namespaces and classes are
3073 // the namespace in which the template is defined; for member
3074 // templates, the member template's class; the namespaces and classes
3075 // associated with the types of the template arguments provided for
3076 // template type parameters (excluding template template parameters); the
3077 // namespaces in which any template template arguments are defined; and
3078 // the classes in which any member templates used as template template
3079 // arguments are defined. [Note: non-type template arguments do not
3080 // contribute to the set of associated namespaces. ]
3082 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
3083 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
3084 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3085 Result.Classes.insert(EnclosingClass);
3086 // Add the associated namespace for this class.
3087 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3088
3089 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3090 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3091 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
3092 }
3093
3094 // Add the class itself. If we've already transitively visited this class,
3095 // we don't need to visit base classes.
3096 if (!Result.addClassTransitive(Class))
3097 return;
3098
3099 // Only recurse into base classes for complete types.
3100 if (!Result.S.isCompleteType(Result.InstantiationLoc,
3101 Result.S.Context.getCanonicalTagType(Class)))
3102 return;
3103
3104 // Add direct and indirect base classes along with their associated
3105 // namespaces.
3107 Bases.push_back(Class);
3108 while (!Bases.empty()) {
3109 // Pop this class off the stack.
3110 Class = Bases.pop_back_val();
3111
3112 // Visit the base classes.
3113 for (const auto &Base : Class->bases()) {
3114 CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3115 // In dependent contexts, we do ADL twice, and the first time around,
3116 // the base type might be a dependent TemplateSpecializationType, or a
3117 // TemplateTypeParmType. If that happens, simply ignore it.
3118 // FIXME: If we want to support export, we probably need to add the
3119 // namespace of the template in a TemplateSpecializationType, or even
3120 // the classes and namespaces of known non-dependent arguments.
3121 if (!BaseDecl)
3122 continue;
3123 if (Result.addClassTransitive(BaseDecl)) {
3124 // Find the associated namespace for this base class.
3125 DeclContext *BaseCtx = BaseDecl->getDeclContext();
3126 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
3127
3128 // Make sure we visit the bases of this base class.
3129 if (!BaseDecl->bases().empty())
3130 Bases.push_back(BaseDecl);
3131 }
3132 }
3133 }
3134}
3135
3136// Add the associated classes and namespaces for
3137// argument-dependent lookup with an argument of type T
3138// (C++ [basic.lookup.koenig]p2).
3139static void
3141 // C++ [basic.lookup.koenig]p2:
3142 //
3143 // For each argument type T in the function call, there is a set
3144 // of zero or more associated namespaces and a set of zero or more
3145 // associated classes to be considered. The sets of namespaces and
3146 // classes is determined entirely by the types of the function
3147 // arguments (and the namespace of any template template
3148 // argument). Typedef names and using-declarations used to specify
3149 // the types do not contribute to this set. The sets of namespaces
3150 // and classes are determined in the following way:
3151
3153 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
3154
3155 while (true) {
3156 switch (T->getTypeClass()) {
3157
3158#define TYPE(Class, Base)
3159#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3160#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3161#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3162#define ABSTRACT_TYPE(Class, Base)
3163#include "clang/AST/TypeNodes.inc"
3164 // T is canonical. We can also ignore dependent types because
3165 // we don't need to do ADL at the definition point, but if we
3166 // wanted to implement template export (or if we find some other
3167 // use for associated classes and namespaces...) this would be
3168 // wrong.
3169 break;
3170
3171 // -- If T is a pointer to U or an array of U, its associated
3172 // namespaces and classes are those associated with U.
3173 case Type::Pointer:
3174 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
3175 continue;
3176 case Type::ConstantArray:
3177 case Type::IncompleteArray:
3178 case Type::VariableArray:
3179 T = cast<ArrayType>(T)->getElementType().getTypePtr();
3180 continue;
3181
3182 // -- If T is a fundamental type, its associated sets of
3183 // namespaces and classes are both empty.
3184 case Type::Builtin:
3185 break;
3186
3187 // -- If T is a class type (including unions), its associated
3188 // classes are: the class itself; the class of which it is
3189 // a member, if any; and its direct and indirect base classes.
3190 // Its associated namespaces are the innermost enclosing
3191 // namespaces of its associated classes.
3192 case Type::Record: {
3193 // FIXME: This should use the original decl.
3195 cast<CXXRecordDecl>(cast<RecordType>(T)->getOriginalDecl())
3196 ->getDefinitionOrSelf();
3198 break;
3199 }
3200
3201 // -- If T is an enumeration type, its associated namespace
3202 // is the innermost enclosing namespace of its declaration.
3203 // If it is a class member, its associated class is the
3204 // member’s class; else it has no associated class.
3205 case Type::Enum: {
3206 // FIXME: This should use the original decl.
3207 auto *Enum = T->castAsEnumDecl();
3208
3209 DeclContext *Ctx = Enum->getDeclContext();
3210 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3211 Result.Classes.insert(EnclosingClass);
3212
3213 // Add the associated namespace for this enumeration.
3214 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3215
3216 break;
3217 }
3218
3219 // -- If T is a function type, its associated namespaces and
3220 // classes are those associated with the function parameter
3221 // types and those associated with the return type.
3222 case Type::FunctionProto: {
3223 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
3224 for (const auto &Arg : Proto->param_types())
3225 Queue.push_back(Arg.getTypePtr());
3226 // fallthrough
3227 [[fallthrough]];
3228 }
3229 case Type::FunctionNoProto: {
3230 const FunctionType *FnType = cast<FunctionType>(T);
3231 T = FnType->getReturnType().getTypePtr();
3232 continue;
3233 }
3234
3235 // -- If T is a pointer to a member function of a class X, its
3236 // associated namespaces and classes are those associated
3237 // with the function parameter types and return type,
3238 // together with those associated with X.
3239 //
3240 // -- If T is a pointer to a data member of class X, its
3241 // associated namespaces and classes are those associated
3242 // with the member type together with those associated with
3243 // X.
3244 case Type::MemberPointer: {
3245 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
3248 T = MemberPtr->getPointeeType().getTypePtr();
3249 continue;
3250 }
3251
3252 // As an extension, treat this like a normal pointer.
3253 case Type::BlockPointer:
3254 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
3255 continue;
3256
3257 // References aren't covered by the standard, but that's such an
3258 // obvious defect that we cover them anyway.
3259 case Type::LValueReference:
3260 case Type::RValueReference:
3261 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
3262 continue;
3263
3264 // These are fundamental types.
3265 case Type::Vector:
3266 case Type::ExtVector:
3267 case Type::ConstantMatrix:
3268 case Type::Complex:
3269 case Type::BitInt:
3270 break;
3271
3272 // Non-deduced auto types only get here for error cases.
3273 case Type::Auto:
3274 case Type::DeducedTemplateSpecialization:
3275 break;
3276
3277 // If T is an Objective-C object or interface type, or a pointer to an
3278 // object or interface type, the associated namespace is the global
3279 // namespace.
3280 case Type::ObjCObject:
3281 case Type::ObjCInterface:
3282 case Type::ObjCObjectPointer:
3283 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
3284 break;
3285
3286 // Atomic types are just wrappers; use the associations of the
3287 // contained type.
3288 case Type::Atomic:
3289 T = cast<AtomicType>(T)->getValueType().getTypePtr();
3290 continue;
3291 case Type::Pipe:
3292 T = cast<PipeType>(T)->getElementType().getTypePtr();
3293 continue;
3294
3295 // Array parameter types are treated as fundamental types.
3296 case Type::ArrayParameter:
3297 break;
3298
3299 case Type::HLSLAttributedResource:
3300 T = cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr();
3301 break;
3302
3303 // Inline SPIR-V types are treated as fundamental types.
3304 case Type::HLSLInlineSpirv:
3305 break;
3306 }
3307
3308 if (Queue.empty())
3309 break;
3310 T = Queue.pop_back_val();
3311 }
3312}
3313
3315 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3316 AssociatedNamespaceSet &AssociatedNamespaces,
3317 AssociatedClassSet &AssociatedClasses) {
3318 AssociatedNamespaces.clear();
3319 AssociatedClasses.clear();
3320
3321 AssociatedLookup Result(*this, InstantiationLoc,
3322 AssociatedNamespaces, AssociatedClasses);
3323
3324 // C++ [basic.lookup.koenig]p2:
3325 // For each argument type T in the function call, there is a set
3326 // of zero or more associated namespaces and a set of zero or more
3327 // associated classes to be considered. The sets of namespaces and
3328 // classes is determined entirely by the types of the function
3329 // arguments (and the namespace of any template template
3330 // argument).
3331 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3332 Expr *Arg = Args[ArgIdx];
3333
3334 if (Arg->getType() != Context.OverloadTy) {
3336 continue;
3337 }
3338
3339 // [...] In addition, if the argument is the name or address of a
3340 // set of overloaded functions and/or function templates, its
3341 // associated classes and namespaces are the union of those
3342 // associated with each of the members of the set: the namespace
3343 // in which the function or function template is defined and the
3344 // classes and namespaces associated with its (non-dependent)
3345 // parameter types and return type.
3347
3348 for (const NamedDecl *D : OE->decls()) {
3349 // Look through any using declarations to find the underlying function.
3350 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3351
3352 // Add the classes and namespaces associated with the parameter
3353 // types and return type of this function.
3355 }
3356 }
3357}
3358
3361 LookupNameKind NameKind,
3362 RedeclarationKind Redecl) {
3363 LookupResult R(*this, Name, Loc, NameKind, Redecl);
3364 LookupName(R, S);
3365 return R.getAsSingle<NamedDecl>();
3366}
3367
3369 UnresolvedSetImpl &Functions) {
3370 // C++ [over.match.oper]p3:
3371 // -- The set of non-member candidates is the result of the
3372 // unqualified lookup of operator@ in the context of the
3373 // expression according to the usual rules for name lookup in
3374 // unqualified function calls (3.4.2) except that all member
3375 // functions are ignored.
3377 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3378 LookupName(Operators, S);
3379
3380 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3381 Functions.append(Operators.begin(), Operators.end());
3382}
3383
3386 bool ConstArg, bool VolatileArg, bool RValueThis,
3387 bool ConstThis, bool VolatileThis) {
3389 "doing special member lookup into record that isn't fully complete");
3390 RD = RD->getDefinition();
3391 if (RValueThis || ConstThis || VolatileThis)
3394 "constructors and destructors always have unqualified lvalue this");
3395 if (ConstArg || VolatileArg)
3398 "parameter-less special members can't have qualified arguments");
3399
3400 // FIXME: Get the caller to pass in a location for the lookup.
3401 SourceLocation LookupLoc = RD->getLocation();
3402
3403 llvm::FoldingSetNodeID ID;
3404 ID.AddPointer(RD);
3405 ID.AddInteger(llvm::to_underlying(SM));
3406 ID.AddInteger(ConstArg);
3407 ID.AddInteger(VolatileArg);
3408 ID.AddInteger(RValueThis);
3409 ID.AddInteger(ConstThis);
3410 ID.AddInteger(VolatileThis);
3411
3412 void *InsertPoint;
3414 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3415
3416 // This was already cached
3417 if (Result)
3418 return *Result;
3419
3422 SpecialMemberCache.InsertNode(Result, InsertPoint);
3423
3425 if (RD->needsImplicitDestructor()) {
3427 DeclareImplicitDestructor(RD);
3428 });
3429 }
3430 CXXDestructorDecl *DD = RD->getDestructor();
3431 Result->setMethod(DD);
3432 Result->setKind(DD && !DD->isDeleted()
3435 return *Result;
3436 }
3437
3438 // Prepare for overload resolution. Here we construct a synthetic argument
3439 // if necessary and make sure that implicit functions are declared.
3441 DeclarationName Name;
3442 Expr *Arg = nullptr;
3443 unsigned NumArgs;
3444
3445 QualType ArgType = CanTy;
3447
3450 NumArgs = 0;
3453 DeclareImplicitDefaultConstructor(RD);
3454 });
3455 }
3456 } else {
3460 if (RD->needsImplicitCopyConstructor()) {
3462 DeclareImplicitCopyConstructor(RD);
3463 });
3464 }
3467 DeclareImplicitMoveConstructor(RD);
3468 });
3469 }
3470 } else {
3472 if (RD->needsImplicitCopyAssignment()) {
3474 DeclareImplicitCopyAssignment(RD);
3475 });
3476 }
3479 DeclareImplicitMoveAssignment(RD);
3480 });
3481 }
3482 }
3483
3484 if (ConstArg)
3485 ArgType.addConst();
3486 if (VolatileArg)
3487 ArgType.addVolatile();
3488
3489 // This isn't /really/ specified by the standard, but it's implied
3490 // we should be working from a PRValue in the case of move to ensure
3491 // that we prefer to bind to rvalue references, and an LValue in the
3492 // case of copy to ensure we don't bind to rvalue references.
3493 // Possibly an XValue is actually correct in the case of move, but
3494 // there is no semantic difference for class types in this restricted
3495 // case.
3498 VK = VK_LValue;
3499 else
3500 VK = VK_PRValue;
3501 }
3502
3503 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3504
3506 NumArgs = 1;
3507 Arg = &FakeArg;
3508 }
3509
3510 // Create the object argument
3511 QualType ThisTy = CanTy;
3512 if (ConstThis)
3513 ThisTy.addConst();
3514 if (VolatileThis)
3515 ThisTy.addVolatile();
3516 Expr::Classification Classification =
3517 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3518 .Classify(Context);
3519
3520 // Now we perform lookup on the name we computed earlier and do overload
3521 // resolution. Lookup is only performed directly into the class since there
3522 // will always be a (possibly implicit) declaration to shadow any others.
3524 DeclContext::lookup_result R = RD->lookup(Name);
3525
3526 if (R.empty()) {
3527 // We might have no default constructor because we have a lambda's closure
3528 // type, rather than because there's some other declared constructor.
3529 // Every class has a copy/move constructor, copy/move assignment, and
3530 // destructor.
3532 "lookup for a constructor or assignment operator was empty");
3533 Result->setMethod(nullptr);
3535 return *Result;
3536 }
3537
3538 // Copy the candidates as our processing of them may load new declarations
3539 // from an external source and invalidate lookup_result.
3540 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3541
3542 for (NamedDecl *CandDecl : Candidates) {
3543 if (CandDecl->isInvalidDecl())
3544 continue;
3545
3547 auto CtorInfo = getConstructorInfo(Cand);
3548 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3551 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3552 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3553 else if (CtorInfo)
3554 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3555 llvm::ArrayRef(&Arg, NumArgs), OCS,
3556 /*SuppressUserConversions*/ true);
3557 else
3558 AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS,
3559 /*SuppressUserConversions*/ true);
3560 } else if (FunctionTemplateDecl *Tmpl =
3561 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3564 AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy,
3565 Classification,
3566 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3567 else if (CtorInfo)
3568 AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl,
3569 CtorInfo.FoundDecl, nullptr,
3570 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3571 else
3572 AddTemplateOverloadCandidate(Tmpl, Cand, nullptr,
3573 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3574 } else {
3575 assert(isa<UsingDecl>(Cand.getDecl()) &&
3576 "illegal Kind of operator = Decl");
3577 }
3578 }
3579
3581 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3582 case OR_Success:
3583 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3585 break;
3586
3587 case OR_Deleted:
3588 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3590 break;
3591
3592 case OR_Ambiguous:
3593 Result->setMethod(nullptr);
3595 break;
3596
3598 Result->setMethod(nullptr);
3600 break;
3601 }
3602
3603 return *Result;
3604}
3605
3609 false, false, false, false, false);
3610
3611 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3612}
3613
3615 unsigned Quals) {
3616 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3617 "non-const, non-volatile qualifiers for copy ctor arg");
3620 Quals & Qualifiers::Volatile, false, false, false);
3621
3622 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3623}
3624
3626 unsigned Quals) {
3629 Quals & Qualifiers::Volatile, false, false, false);
3630
3631 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3632}
3633
3635 // If the implicit constructors have not yet been declared, do so now.
3637 runWithSufficientStackSpace(Class->getLocation(), [&] {
3638 if (Class->needsImplicitDefaultConstructor())
3639 DeclareImplicitDefaultConstructor(Class);
3640 if (Class->needsImplicitCopyConstructor())
3641 DeclareImplicitCopyConstructor(Class);
3642 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3643 DeclareImplicitMoveConstructor(Class);
3644 });
3645 }
3646
3649 return Class->lookup(Name);
3650}
3651
3653 unsigned Quals, bool RValueThis,
3654 unsigned ThisQuals) {
3655 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3656 "non-const, non-volatile qualifiers for copy assignment arg");
3657 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3658 "non-const, non-volatile qualifiers for copy assignment this");
3661 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,
3662 ThisQuals & Qualifiers::Volatile);
3663
3664 return Result.getMethod();
3665}
3666
3668 unsigned Quals,
3669 bool RValueThis,
3670 unsigned ThisQuals) {
3671 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3672 "non-const, non-volatile qualifiers for copy assignment this");
3675 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,
3676 ThisQuals & Qualifiers::Volatile);
3677
3678 return Result.getMethod();
3679}
3680
3682 return cast_or_null<CXXDestructorDecl>(
3684 false, false, false)
3685 .getMethod());
3686}
3687
3690 ArrayRef<QualType> ArgTys, bool AllowRaw,
3691 bool AllowTemplate, bool AllowStringTemplatePack,
3692 bool DiagnoseMissing, StringLiteral *StringLit) {
3693 LookupName(R, S);
3695 "literal operator lookup can't be ambiguous");
3696
3697 // Filter the lookup results appropriately.
3699
3700 bool AllowCooked = true;
3701 bool FoundRaw = false;
3702 bool FoundTemplate = false;
3703 bool FoundStringTemplatePack = false;
3704 bool FoundCooked = false;
3705
3706 while (F.hasNext()) {
3707 Decl *D = F.next();
3708 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3709 D = USD->getTargetDecl();
3710
3711 // If the declaration we found is invalid, skip it.
3712 if (D->isInvalidDecl()) {
3713 F.erase();
3714 continue;
3715 }
3716
3717 bool IsRaw = false;
3718 bool IsTemplate = false;
3719 bool IsStringTemplatePack = false;
3720 bool IsCooked = false;
3721
3722 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3723 if (FD->getNumParams() == 1 &&
3724 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3725 IsRaw = true;
3726 else if (FD->getNumParams() == ArgTys.size()) {
3727 IsCooked = true;
3728 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3729 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3730 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3731 IsCooked = false;
3732 break;
3733 }
3734 }
3735 }
3736 }
3737 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3738 TemplateParameterList *Params = FD->getTemplateParameters();
3739 if (Params->size() == 1) {
3740 IsTemplate = true;
3741 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3742 // Implied but not stated: user-defined integer and floating literals
3743 // only ever use numeric literal operator templates, not templates
3744 // taking a parameter of class type.
3745 F.erase();
3746 continue;
3747 }
3748
3749 // A string literal template is only considered if the string literal
3750 // is a well-formed template argument for the template parameter.
3751 if (StringLit) {
3752 SFINAETrap Trap(*this);
3755 TemplateArgument(StringLit, /*IsCanonical=*/false), StringLit);
3757 Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(),
3758 /*ArgumentPackIndex=*/0, CTAI, CTAK_Specified) ||
3759 Trap.hasErrorOccurred())
3760 IsTemplate = false;
3761 }
3762 } else {
3763 IsStringTemplatePack = true;
3764 }
3765 }
3766
3767 if (AllowTemplate && StringLit && IsTemplate) {
3768 FoundTemplate = true;
3769 AllowRaw = false;
3770 AllowCooked = false;
3771 AllowStringTemplatePack = false;
3772 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3773 F.restart();
3774 FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3775 }
3776 } else if (AllowCooked && IsCooked) {
3777 FoundCooked = true;
3778 AllowRaw = false;
3779 AllowTemplate = StringLit;
3780 AllowStringTemplatePack = false;
3781 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3782 // Go through again and remove the raw and template decls we've
3783 // already found.
3784 F.restart();
3785 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3786 }
3787 } else if (AllowRaw && IsRaw) {
3788 FoundRaw = true;
3789 } else if (AllowTemplate && IsTemplate) {
3790 FoundTemplate = true;
3791 } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3792 FoundStringTemplatePack = true;
3793 } else {
3794 F.erase();
3795 }
3796 }
3797
3798 F.done();
3799
3800 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3801 // form for string literal operator templates.
3802 if (StringLit && FoundTemplate)
3803 return LOLR_Template;
3804
3805 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3806 // parameter type, that is used in preference to a raw literal operator
3807 // or literal operator template.
3808 if (FoundCooked)
3809 return LOLR_Cooked;
3810
3811 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3812 // operator template, but not both.
3813 if (FoundRaw && FoundTemplate) {
3814 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3815 for (const NamedDecl *D : R)
3816 NoteOverloadCandidate(D, D->getUnderlyingDecl()->getAsFunction());
3817 return LOLR_Error;
3818 }
3819
3820 if (FoundRaw)
3821 return LOLR_Raw;
3822
3823 if (FoundTemplate)
3824 return LOLR_Template;
3825
3826 if (FoundStringTemplatePack)
3828
3829 // Didn't find anything we could use.
3830 if (DiagnoseMissing) {
3831 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3832 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3833 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3834 << (AllowTemplate || AllowStringTemplatePack);
3835 return LOLR_Error;
3836 }
3837
3839}
3840
3842 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3843
3844 // If we haven't yet seen a decl for this key, or the last decl
3845 // was exactly this one, we're done.
3846 if (Old == nullptr || Old == New) {
3847 Old = New;
3848 return;
3849 }
3850
3851 // Otherwise, decide which is a more recent redeclaration.
3852 FunctionDecl *OldFD = Old->getAsFunction();
3853 FunctionDecl *NewFD = New->getAsFunction();
3854
3855 FunctionDecl *Cursor = NewFD;
3856 while (true) {
3857 Cursor = Cursor->getPreviousDecl();
3858
3859 // If we got to the end without finding OldFD, OldFD is the newer
3860 // declaration; leave things as they are.
3861 if (!Cursor) return;
3862
3863 // If we do find OldFD, then NewFD is newer.
3864 if (Cursor == OldFD) break;
3865
3866 // Otherwise, keep looking.
3867 }
3868
3869 Old = New;
3870}
3871
3874 // Find all of the associated namespaces and classes based on the
3875 // arguments we have.
3876 AssociatedNamespaceSet AssociatedNamespaces;
3877 AssociatedClassSet AssociatedClasses;
3879 AssociatedNamespaces,
3880 AssociatedClasses);
3881
3882 // C++ [basic.lookup.argdep]p3:
3883 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3884 // and let Y be the lookup set produced by argument dependent
3885 // lookup (defined as follows). If X contains [...] then Y is
3886 // empty. Otherwise Y is the set of declarations found in the
3887 // namespaces associated with the argument types as described
3888 // below. The set of declarations found by the lookup of the name
3889 // is the union of X and Y.
3890 //
3891 // Here, we compute Y and add its members to the overloaded
3892 // candidate set.
3893 for (auto *NS : AssociatedNamespaces) {
3894 // When considering an associated namespace, the lookup is the
3895 // same as the lookup performed when the associated namespace is
3896 // used as a qualifier (3.4.3.2) except that:
3897 //
3898 // -- Any using-directives in the associated namespace are
3899 // ignored.
3900 //
3901 // -- Any namespace-scope friend functions declared in
3902 // associated classes are visible within their respective
3903 // namespaces even if they are not visible during an ordinary
3904 // lookup (11.4).
3905 //
3906 // C++20 [basic.lookup.argdep] p4.3
3907 // -- are exported, are attached to a named module M, do not appear
3908 // in the translation unit containing the point of the lookup, and
3909 // have the same innermost enclosing non-inline namespace scope as
3910 // a declaration of an associated entity attached to M.
3911 DeclContext::lookup_result R = NS->lookup(Name);
3912 for (auto *D : R) {
3913 auto *Underlying = D;
3914 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3915 Underlying = USD->getTargetDecl();
3916
3917 if (!isa<FunctionDecl>(Underlying) &&
3918 !isa<FunctionTemplateDecl>(Underlying))
3919 continue;
3920
3921 // The declaration is visible to argument-dependent lookup if either
3922 // it's ordinarily visible or declared as a friend in an associated
3923 // class.
3924 bool Visible = false;
3925 for (D = D->getMostRecentDecl(); D;
3926 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3928 if (isVisible(D)) {
3929 Visible = true;
3930 break;
3931 }
3932
3933 if (!getLangOpts().CPlusPlusModules)
3934 continue;
3935
3936 if (D->isInExportDeclContext()) {
3937 Module *FM = D->getOwningModule();
3938 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
3939 // exports are only valid in module purview and outside of any
3940 // PMF (although a PMF should not even be present in a module
3941 // with an import).
3942 assert(FM &&
3943 (FM->isNamedModule() || FM->isImplicitGlobalModule()) &&
3944 !FM->isPrivateModule() && "bad export context");
3945 // .. are attached to a named module M, do not appear in the
3946 // translation unit containing the point of the lookup..
3947 if (D->isInAnotherModuleUnit() &&
3948 llvm::any_of(AssociatedClasses, [&](auto *E) {
3949 // ... and have the same innermost enclosing non-inline
3950 // namespace scope as a declaration of an associated entity
3951 // attached to M
3952 if (E->getOwningModule() != FM)
3953 return false;
3954 // TODO: maybe this could be cached when generating the
3955 // associated namespaces / entities.
3956 DeclContext *Ctx = E->getDeclContext();
3957 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
3958 Ctx = Ctx->getParent();
3959 return Ctx == NS;
3960 })) {
3961 Visible = true;
3962 break;
3963 }
3964 }
3965 } else if (D->getFriendObjectKind()) {
3966 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3967 // [basic.lookup.argdep]p4:
3968 // Argument-dependent lookup finds all declarations of functions and
3969 // function templates that
3970 // - ...
3971 // - are declared as a friend ([class.friend]) of any class with a
3972 // reachable definition in the set of associated entities,
3973 //
3974 // FIXME: If there's a merged definition of D that is reachable, then
3975 // the friend declaration should be considered.
3976 if (AssociatedClasses.count(RD) && isReachable(D)) {
3977 Visible = true;
3978 break;
3979 }
3980 }
3981 }
3982
3983 // FIXME: Preserve D as the FoundDecl.
3984 if (Visible)
3985 Result.insert(Underlying);
3986 }
3987 }
3988}
3989
3990//----------------------------------------------------------------------------
3991// Search for all visible declarations.
3992//----------------------------------------------------------------------------
3994
3995bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3996
3997namespace {
3998
3999class ShadowContextRAII;
4000
4001class VisibleDeclsRecord {
4002public:
4003 /// An entry in the shadow map, which is optimized to store a
4004 /// single declaration (the common case) but can also store a list
4005 /// of declarations.
4006 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
4007
4008private:
4009 /// A mapping from declaration names to the declarations that have
4010 /// this name within a particular scope.
4011 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
4012
4013 /// A list of shadow maps, which is used to model name hiding.
4014 std::list<ShadowMap> ShadowMaps;
4015
4016 /// The declaration contexts we have already visited.
4018
4019 friend class ShadowContextRAII;
4020
4021public:
4022 /// Determine whether we have already visited this context
4023 /// (and, if not, note that we are going to visit that context now).
4024 bool visitedContext(DeclContext *Ctx) {
4025 return !VisitedContexts.insert(Ctx).second;
4026 }
4027
4028 bool alreadyVisitedContext(DeclContext *Ctx) {
4029 return VisitedContexts.count(Ctx);
4030 }
4031
4032 /// Determine whether the given declaration is hidden in the
4033 /// current scope.
4034 ///
4035 /// \returns the declaration that hides the given declaration, or
4036 /// NULL if no such declaration exists.
4037 NamedDecl *checkHidden(NamedDecl *ND);
4038
4039 /// Add a declaration to the current shadow map.
4040 void add(NamedDecl *ND) {
4041 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
4042 }
4043};
4044
4045/// RAII object that records when we've entered a shadow context.
4046class ShadowContextRAII {
4047 VisibleDeclsRecord &Visible;
4048
4049 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
4050
4051public:
4052 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
4053 Visible.ShadowMaps.emplace_back();
4054 }
4055
4056 ~ShadowContextRAII() {
4057 Visible.ShadowMaps.pop_back();
4058 }
4059};
4060
4061} // end anonymous namespace
4062
4063NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
4064 unsigned IDNS = ND->getIdentifierNamespace();
4065 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
4066 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
4067 SM != SMEnd; ++SM) {
4068 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
4069 if (Pos == SM->end())
4070 continue;
4071
4072 for (auto *D : Pos->second) {
4073 // A tag declaration does not hide a non-tag declaration.
4077 continue;
4078
4079 // Protocols are in distinct namespaces from everything else.
4081 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
4082 D->getIdentifierNamespace() != IDNS)
4083 continue;
4084
4085 // Functions and function templates in the same scope overload
4086 // rather than hide. FIXME: Look for hiding based on function
4087 // signatures!
4088 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4090 SM == ShadowMaps.rbegin())
4091 continue;
4092
4093 // A shadow declaration that's created by a resolved using declaration
4094 // is not hidden by the same using declaration.
4095 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
4096 cast<UsingShadowDecl>(ND)->getIntroducer() == D)
4097 continue;
4098
4099 // We've found a declaration that hides this one.
4100 return D;
4101 }
4102 }
4103
4104 return nullptr;
4105}
4106
4107namespace {
4108class LookupVisibleHelper {
4109public:
4110 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
4111 bool LoadExternal)
4112 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4113 LoadExternal(LoadExternal) {}
4114
4115 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4116 bool IncludeGlobalScope) {
4117 // Determine the set of using directives available during
4118 // unqualified name lookup.
4119 Scope *Initial = S;
4120 UnqualUsingDirectiveSet UDirs(SemaRef);
4121 if (SemaRef.getLangOpts().CPlusPlus) {
4122 // Find the first namespace or translation-unit scope.
4123 while (S && !isNamespaceOrTranslationUnitScope(S))
4124 S = S->getParent();
4125
4126 UDirs.visitScopeChain(Initial, S);
4127 }
4128 UDirs.done();
4129
4130 // Look for visible declarations.
4131 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4132 Result.setAllowHidden(Consumer.includeHiddenDecls());
4133 if (!IncludeGlobalScope)
4134 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4135 ShadowContextRAII Shadow(Visited);
4136 lookupInScope(Initial, Result, UDirs);
4137 }
4138
4139 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4140 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4141 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4142 Result.setAllowHidden(Consumer.includeHiddenDecls());
4143 if (!IncludeGlobalScope)
4144 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4145
4146 ShadowContextRAII Shadow(Visited);
4147 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4148 /*InBaseClass=*/false);
4149 }
4150
4151private:
4152 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4153 bool QualifiedNameLookup, bool InBaseClass) {
4154 if (!Ctx)
4155 return;
4156
4157 // Make sure we don't visit the same context twice.
4158 if (Visited.visitedContext(Ctx->getPrimaryContext()))
4159 return;
4160
4161 Consumer.EnteredContext(Ctx);
4162
4163 // Outside C++, lookup results for the TU live on identifiers.
4164 if (isa<TranslationUnitDecl>(Ctx) &&
4165 !Result.getSema().getLangOpts().CPlusPlus) {
4166 auto &S = Result.getSema();
4167 auto &Idents = S.Context.Idents;
4168
4169 // Ensure all external identifiers are in the identifier table.
4170 if (LoadExternal)
4172 Idents.getExternalIdentifierLookup()) {
4173 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4174 for (StringRef Name = Iter->Next(); !Name.empty();
4175 Name = Iter->Next())
4176 Idents.get(Name);
4177 }
4178
4179 // Walk all lookup results in the TU for each identifier.
4180 for (const auto &Ident : Idents) {
4181 for (auto I = S.IdResolver.begin(Ident.getValue()),
4182 E = S.IdResolver.end();
4183 I != E; ++I) {
4184 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
4185 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4186 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4187 Visited.add(ND);
4188 }
4189 }
4190 }
4191 }
4192
4193 return;
4194 }
4195
4196 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
4197 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4198
4200 // We sometimes skip loading namespace-level results (they tend to be huge).
4201 bool Load = LoadExternal ||
4202 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
4203 // Enumerate all of the results in this context.
4205 Load ? Ctx->lookups()
4206 : Ctx->noload_lookups(/*PreserveInternalState=*/false))
4207 for (auto *D : R)
4208 // Rather than visit immediately, we put ND into a vector and visit
4209 // all decls, in order, outside of this loop. The reason is that
4210 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)
4211 // may invalidate the iterators used in the two
4212 // loops above.
4213 DeclsToVisit.push_back(D);
4214
4215 for (auto *D : DeclsToVisit)
4216 if (auto *ND = Result.getAcceptableDecl(D)) {
4217 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4218 Visited.add(ND);
4219 }
4220
4221 DeclsToVisit.clear();
4222
4223 // Traverse using directives for qualified name lookup.
4224 if (QualifiedNameLookup) {
4225 ShadowContextRAII Shadow(Visited);
4226 for (auto *I : Ctx->using_directives()) {
4227 if (!Result.getSema().isVisible(I))
4228 continue;
4229 lookupInDeclContext(I->getNominatedNamespace(), Result,
4230 QualifiedNameLookup, InBaseClass);
4231 }
4232 }
4233
4234 // Traverse the contexts of inherited C++ classes.
4235 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
4236 if (!Record->hasDefinition())
4237 return;
4238
4239 for (const auto &B : Record->bases()) {
4240 QualType BaseType = B.getType();
4241
4242 RecordDecl *RD;
4243 if (BaseType->isDependentType()) {
4244 if (!IncludeDependentBases) {
4245 // Don't look into dependent bases, because name lookup can't look
4246 // there anyway.
4247 continue;
4248 }
4249 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
4250 if (!TST)
4251 continue;
4252 TemplateName TN = TST->getTemplateName();
4253 const auto *TD =
4254 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
4255 if (!TD)
4256 continue;
4257 RD = TD->getTemplatedDecl();
4258 } else {
4259 RD = BaseType->getAsCXXRecordDecl();
4260 if (!RD)
4261 continue;
4262 }
4263
4264 // FIXME: It would be nice to be able to determine whether referencing
4265 // a particular member would be ambiguous. For example, given
4266 //
4267 // struct A { int member; };
4268 // struct B { int member; };
4269 // struct C : A, B { };
4270 //
4271 // void f(C *c) { c->### }
4272 //
4273 // accessing 'member' would result in an ambiguity. However, we
4274 // could be smart enough to qualify the member with the base
4275 // class, e.g.,
4276 //
4277 // c->B::member
4278 //
4279 // or
4280 //
4281 // c->A::member
4282
4283 // Find results in this base class (and its bases).
4284 ShadowContextRAII Shadow(Visited);
4285 lookupInDeclContext(RD, Result, QualifiedNameLookup,
4286 /*InBaseClass=*/true);
4287 }
4288 }
4289
4290 // Traverse the contexts of Objective-C classes.
4291 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
4292 // Traverse categories.
4293 for (auto *Cat : IFace->visible_categories()) {
4294 ShadowContextRAII Shadow(Visited);
4295 lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4296 /*InBaseClass=*/false);
4297 }
4298
4299 // Traverse protocols.
4300 for (auto *I : IFace->all_referenced_protocols()) {
4301 ShadowContextRAII Shadow(Visited);
4302 lookupInDeclContext(I, Result, QualifiedNameLookup,
4303 /*InBaseClass=*/false);
4304 }
4305
4306 // Traverse the superclass.
4307 if (IFace->getSuperClass()) {
4308 ShadowContextRAII Shadow(Visited);
4309 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4310 /*InBaseClass=*/true);
4311 }
4312
4313 // If there is an implementation, traverse it. We do this to find
4314 // synthesized ivars.
4315 if (IFace->getImplementation()) {
4316 ShadowContextRAII Shadow(Visited);
4317 lookupInDeclContext(IFace->getImplementation(), Result,
4318 QualifiedNameLookup, InBaseClass);
4319 }
4320 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4321 for (auto *I : Protocol->protocols()) {
4322 ShadowContextRAII Shadow(Visited);
4323 lookupInDeclContext(I, Result, QualifiedNameLookup,
4324 /*InBaseClass=*/false);
4325 }
4326 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4327 for (auto *I : Category->protocols()) {
4328 ShadowContextRAII Shadow(Visited);
4329 lookupInDeclContext(I, Result, QualifiedNameLookup,
4330 /*InBaseClass=*/false);
4331 }
4332
4333 // If there is an implementation, traverse it.
4334 if (Category->getImplementation()) {
4335 ShadowContextRAII Shadow(Visited);
4336 lookupInDeclContext(Category->getImplementation(), Result,
4337 QualifiedNameLookup, /*InBaseClass=*/true);
4338 }
4339 }
4340 }
4341
4342 void lookupInScope(Scope *S, LookupResult &Result,
4343 UnqualUsingDirectiveSet &UDirs) {
4344 // No clients run in this mode and it's not supported. Please add tests and
4345 // remove the assertion if you start relying on it.
4346 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4347
4348 if (!S)
4349 return;
4350
4351 if (!S->getEntity() ||
4352 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4353 (S->getEntity())->isFunctionOrMethod()) {
4354 FindLocalExternScope FindLocals(Result);
4355 // Walk through the declarations in this Scope. The consumer might add new
4356 // decls to the scope as part of deserialization, so make a copy first.
4357 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4358 for (Decl *D : ScopeDecls) {
4359 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4360 if ((ND = Result.getAcceptableDecl(ND))) {
4361 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4362 Visited.add(ND);
4363 }
4364 }
4365 }
4366
4367 DeclContext *Entity = S->getLookupEntity();
4368 if (Entity) {
4369 // Look into this scope's declaration context, along with any of its
4370 // parent lookup contexts (e.g., enclosing classes), up to the point
4371 // where we hit the context stored in the next outer scope.
4372 DeclContext *OuterCtx = findOuterContext(S);
4373
4374 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4375 Ctx = Ctx->getLookupParent()) {
4376 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4377 if (Method->isInstanceMethod()) {
4378 // For instance methods, look for ivars in the method's interface.
4379 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4380 Result.getNameLoc(),
4382 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4383 lookupInDeclContext(IFace, IvarResult,
4384 /*QualifiedNameLookup=*/false,
4385 /*InBaseClass=*/false);
4386 }
4387 }
4388
4389 // We've already performed all of the name lookup that we need
4390 // to for Objective-C methods; the next context will be the
4391 // outer scope.
4392 break;
4393 }
4394
4395 if (Ctx->isFunctionOrMethod())
4396 continue;
4397
4398 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4399 /*InBaseClass=*/false);
4400 }
4401 } else if (!S->getParent()) {
4402 // Look into the translation unit scope. We walk through the translation
4403 // unit's declaration context, because the Scope itself won't have all of
4404 // the declarations if we loaded a precompiled header.
4405 // FIXME: We would like the translation unit's Scope object to point to
4406 // the translation unit, so we don't need this special "if" branch.
4407 // However, doing so would force the normal C++ name-lookup code to look
4408 // into the translation unit decl when the IdentifierInfo chains would
4409 // suffice. Once we fix that problem (which is part of a more general
4410 // "don't look in DeclContexts unless we have to" optimization), we can
4411 // eliminate this.
4412 Entity = Result.getSema().Context.getTranslationUnitDecl();
4413 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4414 /*InBaseClass=*/false);
4415 }
4416
4417 if (Entity) {
4418 // Lookup visible declarations in any namespaces found by using
4419 // directives.
4420 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4421 lookupInDeclContext(
4422 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4423 /*QualifiedNameLookup=*/false,
4424 /*InBaseClass=*/false);
4425 }
4426
4427 // Lookup names in the parent scope.
4428 ShadowContextRAII Shadow(Visited);
4429 lookupInScope(S->getParent(), Result, UDirs);
4430 }
4431
4432private:
4433 VisibleDeclsRecord Visited;
4434 VisibleDeclConsumer &Consumer;
4435 bool IncludeDependentBases;
4436 bool LoadExternal;
4437};
4438} // namespace
4439
4441 VisibleDeclConsumer &Consumer,
4442 bool IncludeGlobalScope, bool LoadExternal) {
4443 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4444 LoadExternal);
4445 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4446}
4447
4449 VisibleDeclConsumer &Consumer,
4450 bool IncludeGlobalScope,
4451 bool IncludeDependentBases, bool LoadExternal) {
4452 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4453 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4454}
4455
4457 NamedDecl *Res = LookupSingleName(CurScope, II, Loc, LookupLabel,
4458 RedeclarationKind::NotForRedeclaration);
4459 // If we found a label, check to see if it is in the same context as us.
4460 // When in a Block, we don't want to reuse a label in an enclosing function.
4461 if (!Res || Res->getDeclContext() != CurContext)
4462 return nullptr;
4463 return cast<LabelDecl>(Res);
4464}
4465
4467 SourceLocation GnuLabelLoc) {
4468 if (GnuLabelLoc.isValid()) {
4469 // Local label definitions always shadow existing labels.
4470 auto *Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4471 Scope *S = CurScope;
4472 PushOnScopeChains(Res, S, true);
4473 return cast<LabelDecl>(Res);
4474 }
4475
4476 // Not a GNU local label.
4477 LabelDecl *Res = LookupExistingLabel(II, Loc);
4478 if (!Res) {
4479 // If not forward referenced or defined already, create the backing decl.
4481 Scope *S = CurScope->getFnParent();
4482 assert(S && "Not in a function?");
4483 PushOnScopeChains(Res, S, true);
4484 }
4485 return Res;
4486}
4487
4488//===----------------------------------------------------------------------===//
4489// Typo correction
4490//===----------------------------------------------------------------------===//
4491
4493 TypoCorrection &Candidate) {
4494 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4495 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4496}
4497
4498static void LookupPotentialTypoResult(Sema &SemaRef,
4499 LookupResult &Res,
4500 IdentifierInfo *Name,
4501 Scope *S, CXXScopeSpec *SS,
4502 DeclContext *MemberContext,
4503 bool EnteringContext,
4504 bool isObjCIvarLookup,
4505 bool FindHidden);
4506
4507/// Check whether the declarations found for a typo correction are
4508/// visible. Set the correction's RequiresImport flag to true if none of the
4509/// declarations are visible, false otherwise.
4511 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4512
4513 for (/**/; DI != DE; ++DI)
4514 if (!LookupResult::isVisible(SemaRef, *DI))
4515 break;
4516 // No filtering needed if all decls are visible.
4517 if (DI == DE) {
4518 TC.setRequiresImport(false);
4519 return;
4520 }
4521
4522 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4523 bool AnyVisibleDecls = !NewDecls.empty();
4524
4525 for (/**/; DI != DE; ++DI) {
4526 if (LookupResult::isVisible(SemaRef, *DI)) {
4527 if (!AnyVisibleDecls) {
4528 // Found a visible decl, discard all hidden ones.
4529 AnyVisibleDecls = true;
4530 NewDecls.clear();
4531 }
4532 NewDecls.push_back(*DI);
4533 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4534 NewDecls.push_back(*DI);
4535 }
4536
4537 if (NewDecls.empty())
4538 TC = TypoCorrection();
4539 else {
4540 TC.setCorrectionDecls(NewDecls);
4541 TC.setRequiresImport(!AnyVisibleDecls);
4542 }
4543}
4544
4545// Fill the supplied vector with the IdentifierInfo pointers for each piece of
4546// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4547// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4551 switch (NNS.getKind()) {
4553 Identifiers.clear();
4554 return;
4555
4557 auto [Namespace, Prefix] = NNS.getAsNamespaceAndPrefix();
4558 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4559 if (const auto *NS = dyn_cast<NamespaceDecl>(Namespace);
4560 NS && NS->isAnonymousNamespace())
4561 return;
4562 Identifiers.push_back(Namespace->getIdentifier());
4563 return;
4564 }
4565
4567 for (const Type *T = NNS.getAsType(); /**/; /**/) {
4568 switch (T->getTypeClass()) {
4569 case Type::DependentName: {
4570 auto *DT = cast<DependentNameType>(T);
4571 getNestedNameSpecifierIdentifiers(DT->getQualifier(), Identifiers);
4572 Identifiers.push_back(DT->getIdentifier());
4573 return;
4574 }
4575 case Type::TemplateSpecialization: {
4576 TemplateName Name =
4577 cast<TemplateSpecializationType>(T)->getTemplateName();
4578 if (const QualifiedTemplateName *QTN =
4579 Name.getAsQualifiedTemplateName()) {
4580 getNestedNameSpecifierIdentifiers(QTN->getQualifier(), Identifiers);
4581 Name = QTN->getUnderlyingTemplate();
4582 }
4583 if (const auto *TD = Name.getAsTemplateDecl(/*IgnoreDeduced=*/true))
4584 Identifiers.push_back(TD->getIdentifier());
4585 return;
4586 }
4587 case Type::DependentTemplateSpecialization: {
4588 const DependentTemplateStorage &S =
4589 cast<DependentTemplateSpecializationType>(T)
4590 ->getDependentTemplateName();
4591 getNestedNameSpecifierIdentifiers(S.getQualifier(), Identifiers);
4592 // FIXME: Should this dig into the Name as well?
4593 // Identifiers.push_back(S.getName().getIdentifier());
4594 return;
4595 }
4596 case Type::SubstTemplateTypeParm:
4597 T = cast<SubstTemplateTypeParmType>(T)
4598 ->getReplacementType()
4599 .getTypePtr();
4600 continue;
4601 case Type::TemplateTypeParm:
4602 Identifiers.push_back(cast<TemplateTypeParmType>(T)->getIdentifier());
4603 return;
4604 case Type::Decltype:
4605 return;
4606 case Type::Enum:
4607 case Type::Record:
4608 case Type::InjectedClassName: {
4609 auto *TT = cast<TagType>(T);
4610 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);
4611 Identifiers.push_back(TT->getOriginalDecl()->getIdentifier());
4612 return;
4613 }
4614 case Type::Typedef: {
4615 auto *TT = cast<TypedefType>(T);
4616 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);
4617 Identifiers.push_back(TT->getDecl()->getIdentifier());
4618 return;
4619 }
4620 case Type::Using: {
4621 auto *TT = cast<UsingType>(T);
4622 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);
4623 Identifiers.push_back(TT->getDecl()->getIdentifier());
4624 return;
4625 }
4626 case Type::UnresolvedUsing: {
4627 auto *TT = cast<UnresolvedUsingType>(T);
4628 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);
4629 Identifiers.push_back(TT->getDecl()->getIdentifier());
4630 return;
4631 }
4632 default:
4633 Identifiers.push_back(QualType(T, 0).getBaseTypeIdentifier());
4634 return;
4635 }
4636 }
4637 break;
4638 }
4639
4642 return;
4643 }
4644}
4645
4647 DeclContext *Ctx, bool InBaseClass) {
4648 // Don't consider hidden names for typo correction.
4649 if (Hiding)
4650 return;
4651
4652 // Only consider entities with identifiers for names, ignoring
4653 // special names (constructors, overloaded operators, selectors,
4654 // etc.).
4655 IdentifierInfo *Name = ND->getIdentifier();
4656 if (!Name)
4657 return;
4658
4659 // Only consider visible declarations and declarations from modules with
4660 // names that exactly match.
4661 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4662 return;
4663
4664 FoundName(Name->getName());
4665}
4666
4668 // Compute the edit distance between the typo and the name of this
4669 // entity, and add the identifier to the list of results.
4670 addName(Name, nullptr);
4671}
4672
4674 // Compute the edit distance between the typo and this keyword,
4675 // and add the keyword to the list of results.
4676 addName(Keyword, /*ND=*/nullptr, /*NNS=*/std::nullopt, /*isKeyword=*/true);
4677}
4678
4679void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4680 NestedNameSpecifier NNS, bool isKeyword) {
4681 // Use a simple length-based heuristic to determine the minimum possible
4682 // edit distance. If the minimum isn't good enough, bail out early.
4683 StringRef TypoStr = Typo->getName();
4684 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4685 if (MinED && TypoStr.size() / MinED < 3)
4686 return;
4687
4688 // Compute an upper bound on the allowable edit distance, so that the
4689 // edit-distance algorithm can short-circuit.
4690 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4691 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4692 if (ED > UpperBound) return;
4693
4694 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4695 if (isKeyword) TC.makeKeyword();
4696 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4697 addCorrection(TC);
4698}
4699
4700static const unsigned MaxTypoDistanceResultSets = 5;
4701
4703 StringRef TypoStr = Typo->getName();
4704 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4705
4706 // For very short typos, ignore potential corrections that have a different
4707 // base identifier from the typo or which have a normalized edit distance
4708 // longer than the typo itself.
4709 if (TypoStr.size() < 3 &&
4710 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4711 return;
4712
4713 // If the correction is resolved but is not viable, ignore it.
4714 if (Correction.isResolved()) {
4715 checkCorrectionVisibility(SemaRef, Correction);
4716 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4717 return;
4718 }
4719
4720 TypoResultList &CList =
4721 CorrectionResults[Correction.getEditDistance(false)][Name];
4722
4723 if (!CList.empty() && !CList.back().isResolved())
4724 CList.pop_back();
4725 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4726 auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4727 return TypoCorr.getCorrectionDecl() == NewND;
4728 });
4729 if (RI != CList.end()) {
4730 // The Correction refers to a decl already in the list. No insertion is
4731 // necessary and all further cases will return.
4732
4733 auto IsDeprecated = [](Decl *D) {
4734 while (D) {
4735 if (D->isDeprecated())
4736 return true;
4737 D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4738 }
4739 return false;
4740 };
4741
4742 // Prefer non deprecated Corrections over deprecated and only then
4743 // sort using an alphabetical order.
4744 std::pair<bool, std::string> NewKey = {
4745 IsDeprecated(Correction.getFoundDecl()),
4746 Correction.getAsString(SemaRef.getLangOpts())};
4747
4748 std::pair<bool, std::string> PrevKey = {
4749 IsDeprecated(RI->getFoundDecl()),
4750 RI->getAsString(SemaRef.getLangOpts())};
4751
4752 if (NewKey < PrevKey)
4753 *RI = Correction;
4754 return;
4755 }
4756 }
4757 if (CList.empty() || Correction.isResolved())
4758 CList.push_back(Correction);
4759
4760 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4761 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4762}
4763
4765 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4766 SearchNamespaces = true;
4767
4768 for (auto KNPair : KnownNamespaces)
4769 Namespaces.addNameSpecifier(KNPair.first);
4770
4771 bool SSIsTemplate = false;
4772 if (NestedNameSpecifier NNS = (SS ? SS->getScopeRep() : std::nullopt)) {
4774 SSIsTemplate =
4775 NNS.getAsType()->getTypeClass() == Type::TemplateSpecialization;
4776 }
4777 // Do not transform this into an iterator-based loop. The loop body can
4778 // trigger the creation of further types (through lazy deserialization) and
4779 // invalid iterators into this list.
4780 auto &Types = SemaRef.getASTContext().getTypes();
4781 for (unsigned I = 0; I != Types.size(); ++I) {
4782 const auto *TI = Types[I];
4783 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4784 CD = CD->getCanonicalDecl();
4785 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4786 !CD->isUnion() && CD->getIdentifier() &&
4787 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4788 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4789 Namespaces.addNameSpecifier(CD);
4790 }
4791 }
4792}
4793
4795 if (++CurrentTCIndex < ValidatedCorrections.size())
4796 return ValidatedCorrections[CurrentTCIndex];
4797
4798 CurrentTCIndex = ValidatedCorrections.size();
4799 while (!CorrectionResults.empty()) {
4800 auto DI = CorrectionResults.begin();
4801 if (DI->second.empty()) {
4802 CorrectionResults.erase(DI);
4803 continue;
4804 }
4805
4806 auto RI = DI->second.begin();
4807 if (RI->second.empty()) {
4808 DI->second.erase(RI);
4809 performQualifiedLookups();
4810 continue;
4811 }
4812
4813 TypoCorrection TC = RI->second.pop_back_val();
4814 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4815 ValidatedCorrections.push_back(TC);
4816 return ValidatedCorrections[CurrentTCIndex];
4817 }
4818 }
4819 return ValidatedCorrections[0]; // The empty correction.
4820}
4821
4822bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4824 DeclContext *TempMemberContext = MemberContext;
4825 CXXScopeSpec *TempSS = SS.get();
4826retry_lookup:
4827 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4828 EnteringContext,
4829 CorrectionValidator->IsObjCIvarLookup,
4830 Name == Typo && !Candidate.WillReplaceSpecifier());
4831 switch (Result.getResultKind()) {
4835 if (TempSS) {
4836 // Immediately retry the lookup without the given CXXScopeSpec
4837 TempSS = nullptr;
4838 Candidate.WillReplaceSpecifier(true);
4839 goto retry_lookup;
4840 }
4841 if (TempMemberContext) {
4842 if (SS && !TempSS)
4843 TempSS = SS.get();
4844 TempMemberContext = nullptr;
4845 goto retry_lookup;
4846 }
4847 if (SearchNamespaces)
4848 QualifiedResults.push_back(Candidate);
4849 break;
4850
4852 // We don't deal with ambiguities.
4853 break;
4854
4857 // Store all of the Decls for overloaded symbols
4858 for (auto *TRD : Result)
4859 Candidate.addCorrectionDecl(TRD);
4860 checkCorrectionVisibility(SemaRef, Candidate);
4861 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4862 if (SearchNamespaces)
4863 QualifiedResults.push_back(Candidate);
4864 break;
4865 }
4866 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4867 return true;
4868 }
4869 return false;
4870}
4871
4872void TypoCorrectionConsumer::performQualifiedLookups() {
4873 unsigned TypoLen = Typo->getName().size();
4874 for (const TypoCorrection &QR : QualifiedResults) {
4875 for (const auto &NSI : Namespaces) {
4876 DeclContext *Ctx = NSI.DeclCtx;
4877 CXXRecordDecl *NamingClass = NSI.NameSpecifier.getAsRecordDecl();
4878
4879 // If the current NestedNameSpecifier refers to a class and the
4880 // current correction candidate is the name of that class, then skip
4881 // it as it is unlikely a qualified version of the class' constructor
4882 // is an appropriate correction.
4883 if (NamingClass &&
4884 NamingClass->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4885 continue;
4886
4887 TypoCorrection TC(QR);
4888 TC.ClearCorrectionDecls();
4889 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4890 TC.setQualifierDistance(NSI.EditDistance);
4891 TC.setCallbackDistance(0); // Reset the callback distance
4892
4893 // If the current correction candidate and namespace combination are
4894 // too far away from the original typo based on the normalized edit
4895 // distance, then skip performing a qualified name lookup.
4896 unsigned TmpED = TC.getEditDistance(true);
4897 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4898 TypoLen / TmpED < 3)
4899 continue;
4900
4901 Result.clear();
4902 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4903 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4904 continue;
4905
4906 // Any corrections added below will be validated in subsequent
4907 // iterations of the main while() loop over the Consumer's contents.
4908 switch (Result.getResultKind()) {
4911 if (SS && SS->isValid()) {
4912 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4913 std::string OldQualified;
4914 llvm::raw_string_ostream OldOStream(OldQualified);
4915 SS->getScopeRep().print(OldOStream, SemaRef.getPrintingPolicy());
4916 OldOStream << Typo->getName();
4917 // If correction candidate would be an identical written qualified
4918 // identifier, then the existing CXXScopeSpec probably included a
4919 // typedef that didn't get accounted for properly.
4920 if (OldOStream.str() == NewQualified)
4921 break;
4922 }
4923 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4924 TRD != TRDEnd; ++TRD) {
4925 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4926 NamingClass,
4927 TRD.getPair()) == Sema::AR_accessible)
4928 TC.addCorrectionDecl(*TRD);
4929 }
4930 if (TC.isResolved()) {
4931 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4932 addCorrection(TC);
4933 }
4934 break;
4935 }
4940 break;
4941 }
4942 }
4943 }
4944 QualifiedResults.clear();
4945}
4946
4947TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4948 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4949 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4950 if (NestedNameSpecifier NNS =
4951 CurScopeSpec ? CurScopeSpec->getScopeRep() : std::nullopt) {
4952 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4953 NNS.print(SpecifierOStream, Context.getPrintingPolicy());
4954
4955 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4956 }
4957 // Build the list of identifiers that would be used for an absolute
4958 // (from the global context) NestedNameSpecifier referring to the current
4959 // context.
4960 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4961 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4962 CurContextIdentifiers.push_back(ND->getIdentifier());
4963 }
4964
4965 // Add the global context as a NestedNameSpecifier
4966 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4968 DistanceMap[1].push_back(SI);
4969}
4970
4971auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4972 DeclContext *Start) -> DeclContextList {
4973 assert(Start && "Building a context chain from a null context");
4974 DeclContextList Chain;
4975 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4976 DC = DC->getLookupParent()) {
4977 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4978 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4979 !(ND && ND->isAnonymousNamespace()))
4980 Chain.push_back(DC->getPrimaryContext());
4981 }
4982 return Chain;
4983}
4984
4985unsigned
4986TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4987 DeclContextList &DeclChain, NestedNameSpecifier &NNS) {
4988 unsigned NumSpecifiers = 0;
4989 for (DeclContext *C : llvm::reverse(DeclChain)) {
4990 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4991 NNS = NestedNameSpecifier(Context, ND, NNS);
4992 ++NumSpecifiers;
4993 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4995 /*OwnsTag=*/false);
4996 NNS = NestedNameSpecifier(T.getTypePtr());
4997 ++NumSpecifiers;
4998 }
4999 }
5000 return NumSpecifiers;
5001}
5002
5003void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
5004 DeclContext *Ctx) {
5005 NestedNameSpecifier NNS = std::nullopt;
5006 unsigned NumSpecifiers = 0;
5007 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
5008 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
5009
5010 // Eliminate common elements from the two DeclContext chains.
5011 for (DeclContext *C : llvm::reverse(CurContextChain)) {
5012 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
5013 break;
5014 NamespaceDeclChain.pop_back();
5015 }
5016
5017 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
5018 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
5019
5020 // Add an explicit leading '::' specifier if needed.
5021 if (NamespaceDeclChain.empty()) {
5022 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
5024 NumSpecifiers =
5025 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
5026 } else if (NamedDecl *ND =
5027 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
5028 IdentifierInfo *Name = ND->getIdentifier();
5029 bool SameNameSpecifier = false;
5030 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
5031 std::string NewNameSpecifier;
5032 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
5033 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
5034 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
5035 NNS.print(SpecifierOStream, Context.getPrintingPolicy());
5036 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
5037 }
5038 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
5039 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
5041 NumSpecifiers =
5042 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
5043 }
5044 }
5045
5046 // If the built NestedNameSpecifier would be replacing an existing
5047 // NestedNameSpecifier, use the number of component identifiers that
5048 // would need to be changed as the edit distance instead of the number
5049 // of components in the built NestedNameSpecifier.
5050 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
5051 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
5052 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
5053 NumSpecifiers =
5054 llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),
5055 llvm::ArrayRef(NewNameSpecifierIdentifiers));
5056 }
5057
5058 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
5059 DistanceMap[NumSpecifiers].push_back(SI);
5060}
5061
5062/// Perform name lookup for a possible result for typo correction.
5063static void LookupPotentialTypoResult(Sema &SemaRef,
5064 LookupResult &Res,
5065 IdentifierInfo *Name,
5066 Scope *S, CXXScopeSpec *SS,
5067 DeclContext *MemberContext,
5068 bool EnteringContext,
5069 bool isObjCIvarLookup,
5070 bool FindHidden) {
5071 Res.suppressDiagnostics();
5072 Res.clear();
5073 Res.setLookupName(Name);
5074 Res.setAllowHidden(FindHidden);
5075 if (MemberContext) {
5076 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
5077 if (isObjCIvarLookup) {
5078 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
5079 Res.addDecl(Ivar);
5080 Res.resolveKind();
5081 return;
5082 }
5083 }
5084
5085 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
5087 Res.addDecl(Prop);
5088 Res.resolveKind();
5089 return;
5090 }
5091 }
5092
5093 SemaRef.LookupQualifiedName(Res, MemberContext);
5094 return;
5095 }
5096
5097 SemaRef.LookupParsedName(Res, S, SS,
5098 /*ObjectType=*/QualType(),
5099 /*AllowBuiltinCreation=*/false, EnteringContext);
5100
5101 // Fake ivar lookup; this should really be part of
5102 // LookupParsedName.
5103 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
5104 if (Method->isInstanceMethod() && Method->getClassInterface() &&
5105 (Res.empty() ||
5106 (Res.isSingleResult() &&
5108 if (ObjCIvarDecl *IV
5109 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
5110 Res.addDecl(IV);
5111 Res.resolveKind();
5112 }
5113 }
5114 }
5115}
5116
5117/// Add keywords to the consumer as possible typo corrections.
5118static void AddKeywordsToConsumer(Sema &SemaRef,
5119 TypoCorrectionConsumer &Consumer,
5121 bool AfterNestedNameSpecifier) {
5122 if (AfterNestedNameSpecifier) {
5123 // For 'X::', we know exactly which keywords can appear next.
5124 Consumer.addKeywordResult("template");
5125 if (CCC.WantExpressionKeywords)
5126 Consumer.addKeywordResult("operator");
5127 return;
5128 }
5129
5130 if (CCC.WantObjCSuper)
5131 Consumer.addKeywordResult("super");
5132
5133 if (CCC.WantTypeSpecifiers) {
5134 // Add type-specifier keywords to the set of results.
5135 static const char *const CTypeSpecs[] = {
5136 "char", "const", "double", "enum", "float", "int", "long", "short",
5137 "signed", "struct", "union", "unsigned", "void", "volatile",
5138 "_Complex",
5139 // storage-specifiers as well
5140 "extern", "inline", "static", "typedef"
5141 };
5142
5143 for (const auto *CTS : CTypeSpecs)
5144 Consumer.addKeywordResult(CTS);
5145
5146 if (SemaRef.getLangOpts().C99 && !SemaRef.getLangOpts().C2y)
5147 Consumer.addKeywordResult("_Imaginary");
5148
5149 if (SemaRef.getLangOpts().C99)
5150 Consumer.addKeywordResult("restrict");
5151 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
5152 Consumer.addKeywordResult("bool");
5153 else if (SemaRef.getLangOpts().C99)
5154 Consumer.addKeywordResult("_Bool");
5155
5156 if (SemaRef.getLangOpts().CPlusPlus) {
5157 Consumer.addKeywordResult("class");
5158 Consumer.addKeywordResult("typename");
5159 Consumer.addKeywordResult("wchar_t");
5160
5161 if (SemaRef.getLangOpts().CPlusPlus11) {
5162 Consumer.addKeywordResult("char16_t");
5163 Consumer.addKeywordResult("char32_t");
5164 Consumer.addKeywordResult("constexpr");
5165 Consumer.addKeywordResult("decltype");
5166 Consumer.addKeywordResult("thread_local");
5167 }
5168 }
5169
5170 if (SemaRef.getLangOpts().GNUKeywords)
5171 Consumer.addKeywordResult("typeof");
5172 } else if (CCC.WantFunctionLikeCasts) {
5173 static const char *const CastableTypeSpecs[] = {
5174 "char", "double", "float", "int", "long", "short",
5175 "signed", "unsigned", "void"
5176 };
5177 for (auto *kw : CastableTypeSpecs)
5178 Consumer.addKeywordResult(kw);
5179 }
5180
5181 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5182 Consumer.addKeywordResult("const_cast");
5183 Consumer.addKeywordResult("dynamic_cast");
5184 Consumer.addKeywordResult("reinterpret_cast");
5185 Consumer.addKeywordResult("static_cast");
5186 }
5187
5188 if (CCC.WantExpressionKeywords) {
5189 Consumer.addKeywordResult("sizeof");
5190 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5191 Consumer.addKeywordResult("false");
5192 Consumer.addKeywordResult("true");
5193 }
5194
5195 if (SemaRef.getLangOpts().CPlusPlus) {
5196 static const char *const CXXExprs[] = {
5197 "delete", "new", "operator", "throw", "typeid"
5198 };
5199 for (const auto *CE : CXXExprs)
5200 Consumer.addKeywordResult(CE);
5201
5202 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
5203 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
5204 Consumer.addKeywordResult("this");
5205
5206 if (SemaRef.getLangOpts().CPlusPlus11) {
5207 Consumer.addKeywordResult("alignof");
5208 Consumer.addKeywordResult("nullptr");
5209 }
5210 }
5211
5212 if (SemaRef.getLangOpts().C11) {
5213 // FIXME: We should not suggest _Alignof if the alignof macro
5214 // is present.
5215 Consumer.addKeywordResult("_Alignof");
5216 }
5217 }
5218
5219 if (CCC.WantRemainingKeywords) {
5220 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5221 // Statements.
5222 static const char *const CStmts[] = {
5223 "do", "else", "for", "goto", "if", "return", "switch", "while" };
5224 for (const auto *CS : CStmts)
5225 Consumer.addKeywordResult(CS);
5226
5227 if (SemaRef.getLangOpts().CPlusPlus) {
5228 Consumer.addKeywordResult("catch");
5229 Consumer.addKeywordResult("try");
5230 }
5231
5232 if (S && S->getBreakParent())
5233 Consumer.addKeywordResult("break");
5234
5235 if (S && S->getContinueParent())
5236 Consumer.addKeywordResult("continue");
5237
5238 if (SemaRef.getCurFunction() &&
5239 !SemaRef.getCurFunction()->SwitchStack.empty()) {
5240 Consumer.addKeywordResult("case");
5241 Consumer.addKeywordResult("default");
5242 }
5243 } else {
5244 if (SemaRef.getLangOpts().CPlusPlus) {
5245 Consumer.addKeywordResult("namespace");
5246 Consumer.addKeywordResult("template");
5247 }
5248
5249 if (S && S->isClassScope()) {
5250 Consumer.addKeywordResult("explicit");
5251 Consumer.addKeywordResult("friend");
5252 Consumer.addKeywordResult("mutable");
5253 Consumer.addKeywordResult("private");
5254 Consumer.addKeywordResult("protected");
5255 Consumer.addKeywordResult("public");
5256 Consumer.addKeywordResult("virtual");
5257 }
5258 }
5259
5260 if (SemaRef.getLangOpts().CPlusPlus) {
5261 Consumer.addKeywordResult("using");
5262
5263 if (SemaRef.getLangOpts().CPlusPlus11)
5264 Consumer.addKeywordResult("static_assert");
5265 }
5266 }
5267}
5268
5269std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5270 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5272 DeclContext *MemberContext, bool EnteringContext,
5273 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5274
5275 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5277 return nullptr;
5278
5279 // In Microsoft mode, don't perform typo correction in a template member
5280 // function dependent context because it interferes with the "lookup into
5281 // dependent bases of class templates" feature.
5282 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5283 isa<CXXMethodDecl>(CurContext))
5284 return nullptr;
5285
5286 // We only attempt to correct typos for identifiers.
5287 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5288 if (!Typo)
5289 return nullptr;
5290
5291 // If the scope specifier itself was invalid, don't try to correct
5292 // typos.
5293 if (SS && SS->isInvalid())
5294 return nullptr;
5295
5296 // Never try to correct typos during any kind of code synthesis.
5297 if (!CodeSynthesisContexts.empty())
5298 return nullptr;
5299
5300 // Don't try to correct 'super'.
5301 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5302 return nullptr;
5303
5304 // Abort if typo correction already failed for this specific typo.
5305 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
5306 if (locs != TypoCorrectionFailures.end() &&
5307 locs->second.count(TypoName.getLoc()))
5308 return nullptr;
5309
5310 // Don't try to correct the identifier "vector" when in AltiVec mode.
5311 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5312 // remove this workaround.
5313 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
5314 return nullptr;
5315
5316 // Provide a stop gap for files that are just seriously broken. Trying
5317 // to correct all typos can turn into a HUGE performance penalty, causing
5318 // some files to take minutes to get rejected by the parser.
5319 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5320 if (Limit && TyposCorrected >= Limit)
5321 return nullptr;
5323
5324 // If we're handling a missing symbol error, using modules, and the
5325 // special search all modules option is used, look for a missing import.
5326 if (ErrorRecovery && getLangOpts().Modules &&
5327 getLangOpts().ModulesSearchAll) {
5328 // The following has the side effect of loading the missing module.
5330 TypoName.getBeginLoc());
5331 }
5332
5333 // Extend the lifetime of the callback. We delayed this until here
5334 // to avoid allocations in the hot path (which is where no typo correction
5335 // occurs). Note that CorrectionCandidateCallback is polymorphic and
5336 // initially stack-allocated.
5337 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5338 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5339 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5340 EnteringContext);
5341
5342 // Perform name lookup to find visible, similarly-named entities.
5343 bool IsUnqualifiedLookup = false;
5344 DeclContext *QualifiedDC = MemberContext;
5345 if (MemberContext) {
5346 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
5347
5348 // Look in qualified interfaces.
5349 if (OPT) {
5350 for (auto *I : OPT->quals())
5351 LookupVisibleDecls(I, LookupKind, *Consumer);
5352 }
5353 } else if (SS && SS->isSet()) {
5354 QualifiedDC = computeDeclContext(*SS, EnteringContext);
5355 if (!QualifiedDC)
5356 return nullptr;
5357
5358 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
5359 } else {
5360 IsUnqualifiedLookup = true;
5361 }
5362
5363 // Determine whether we are going to search in the various namespaces for
5364 // corrections.
5365 bool SearchNamespaces
5366 = getLangOpts().CPlusPlus &&
5367 (IsUnqualifiedLookup || (SS && SS->isSet()));
5368
5369 if (IsUnqualifiedLookup || SearchNamespaces) {
5370 // For unqualified lookup, look through all of the names that we have
5371 // seen in this translation unit.
5372 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5373 for (const auto &I : Context.Idents)
5374 Consumer->FoundName(I.getKey());
5375
5376 // Walk through identifiers in external identifier sources.
5377 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5380 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5381 do {
5382 StringRef Name = Iter->Next();
5383 if (Name.empty())
5384 break;
5385
5386 Consumer->FoundName(Name);
5387 } while (true);
5388 }
5389 }
5390
5392 *Consumer->getCorrectionValidator(),
5393 SS && SS->isNotEmpty());
5394
5395 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5396 // to search those namespaces.
5397 if (SearchNamespaces) {
5398 // Load any externally-known namespaces.
5399 if (ExternalSource && !LoadedExternalKnownNamespaces) {
5400 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5401 LoadedExternalKnownNamespaces = true;
5402 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5403 for (auto *N : ExternalKnownNamespaces)
5404 KnownNamespaces[N] = true;
5405 }
5406
5407 Consumer->addNamespaces(KnownNamespaces);
5408 }
5409
5410 return Consumer;
5411}
5412
5414 Sema::LookupNameKind LookupKind,
5415 Scope *S, CXXScopeSpec *SS,
5417 CorrectTypoKind Mode,
5418 DeclContext *MemberContext,
5419 bool EnteringContext,
5420 const ObjCObjectPointerType *OPT,
5421 bool RecordFailure) {
5422 // Always let the ExternalSource have the first chance at correction, even
5423 // if we would otherwise have given up.
5424 if (ExternalSource) {
5425 if (TypoCorrection Correction =
5426 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5427 MemberContext, EnteringContext, OPT))
5428 return Correction;
5429 }
5430
5431 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5432 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5433 // some instances of CTC_Unknown, while WantRemainingKeywords is true
5434 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5435 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5436
5437 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5438 auto Consumer = makeTypoCorrectionConsumer(
5439 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT,
5441
5442 if (!Consumer)
5443 return TypoCorrection();
5444
5445 // If we haven't found anything, we're done.
5446 if (Consumer->empty())
5447 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5448
5449 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5450 // is not more that about a third of the length of the typo's identifier.
5451 unsigned ED = Consumer->getBestEditDistance(true);
5452 unsigned TypoLen = Typo->getName().size();
5453 if (ED > 0 && TypoLen / ED < 3)
5454 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5455
5456 TypoCorrection BestTC = Consumer->getNextCorrection();
5457 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5458 if (!BestTC)
5459 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5460
5461 ED = BestTC.getEditDistance();
5462
5463 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5464 // If this was an unqualified lookup and we believe the callback
5465 // object wouldn't have filtered out possible corrections, note
5466 // that no correction was found.
5467 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5468 }
5469
5470 // If only a single name remains, return that result.
5471 if (!SecondBestTC ||
5472 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5473 const TypoCorrection &Result = BestTC;
5474
5475 // Don't correct to a keyword that's the same as the typo; the keyword
5476 // wasn't actually in scope.
5477 if (ED == 0 && Result.isKeyword())
5478 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5479
5481 TC.setCorrectionRange(SS, TypoName);
5482 checkCorrectionVisibility(*this, TC);
5483 return TC;
5484 } else if (SecondBestTC && ObjCMessageReceiver) {
5485 // Prefer 'super' when we're completing in a message-receiver
5486 // context.
5487
5488 if (BestTC.getCorrection().getAsString() != "super") {
5489 if (SecondBestTC.getCorrection().getAsString() == "super")
5490 BestTC = SecondBestTC;
5491 else if ((*Consumer)["super"].front().isKeyword())
5492 BestTC = (*Consumer)["super"].front();
5493 }
5494 // Don't correct to a keyword that's the same as the typo; the keyword
5495 // wasn't actually in scope.
5496 if (BestTC.getEditDistance() == 0 ||
5497 BestTC.getCorrection().getAsString() != "super")
5498 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5499
5500 BestTC.setCorrectionRange(SS, TypoName);
5501 return BestTC;
5502 }
5503
5504 // Record the failure's location if needed and return an empty correction. If
5505 // this was an unqualified lookup and we believe the callback object did not
5506 // filter out possible corrections, also cache the failure for the typo.
5507 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5508}
5509
5511 if (!CDecl) return;
5512
5513 if (isKeyword())
5514 CorrectionDecls.clear();
5515
5516 CorrectionDecls.push_back(CDecl);
5517
5518 if (!CorrectionName)
5519 CorrectionName = CDecl->getDeclName();
5520}
5521
5522std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5523 if (CorrectionNameSpec) {
5524 std::string tmpBuffer;
5525 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5526 CorrectionNameSpec.print(PrefixOStream, PrintingPolicy(LO));
5527 PrefixOStream << CorrectionName;
5528 return PrefixOStream.str();
5529 }
5530
5531 return CorrectionName.getAsString();
5532}
5533
5535 const TypoCorrection &candidate) {
5536 if (!candidate.isResolved())
5537 return true;
5538
5539 if (candidate.isKeyword())
5542
5543 bool HasNonType = false;
5544 bool HasStaticMethod = false;
5545 bool HasNonStaticMethod = false;
5546 for (Decl *D : candidate) {
5547 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5548 D = FTD->getTemplatedDecl();
5549 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5550 if (Method->isStatic())
5551 HasStaticMethod = true;
5552 else
5553 HasNonStaticMethod = true;
5554 }
5555 if (!isa<TypeDecl>(D))
5556 HasNonType = true;
5557 }
5558
5559 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5560 !candidate.getCorrectionSpecifier())
5561 return false;
5562
5563 return WantTypeSpecifiers || HasNonType;
5564}
5565
5567 bool HasExplicitTemplateArgs,
5568 MemberExpr *ME)
5569 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5570 CurContext(SemaRef.CurContext), MemberFn(ME) {
5571 WantTypeSpecifiers = false;
5572 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5573 !HasExplicitTemplateArgs && NumArgs == 1;
5574 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5575 WantRemainingKeywords = false;
5576}
5577
5579 if (!candidate.getCorrectionDecl())
5580 return candidate.isKeyword();
5581
5582 for (auto *C : candidate) {
5583 FunctionDecl *FD = nullptr;
5584 NamedDecl *ND = C->getUnderlyingDecl();
5585 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5586 FD = FTD->getTemplatedDecl();
5587 if (!HasExplicitTemplateArgs && !FD) {
5588 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5589 // If the Decl is neither a function nor a template function,
5590 // determine if it is a pointer or reference to a function. If so,
5591 // check against the number of arguments expected for the pointee.
5592 QualType ValType = cast<ValueDecl>(ND)->getType();
5593 if (ValType.isNull())
5594 continue;
5595 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5596 ValType = ValType->getPointeeType();
5597 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5598 if (FPT->getNumParams() == NumArgs)
5599 return true;
5600 }
5601 }
5602
5603 // A typo for a function-style cast can look like a function call in C++.
5604 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5605 : isa<TypeDecl>(ND)) &&
5606 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5607 // Only a class or class template can take two or more arguments.
5608 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5609
5610 // Skip the current candidate if it is not a FunctionDecl or does not accept
5611 // the current number of arguments.
5612 if (!FD || !(FD->getNumParams() >= NumArgs &&
5613 FD->getMinRequiredArguments() <= NumArgs))
5614 continue;
5615
5616 // If the current candidate is a non-static C++ method, skip the candidate
5617 // unless the method being corrected--or the current DeclContext, if the
5618 // function being corrected is not a method--is a method in the same class
5619 // or a descendent class of the candidate's parent class.
5620 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
5621 if (MemberFn || !MD->isStatic()) {
5622 const auto *CurMD =
5623 MemberFn
5624 ? dyn_cast_if_present<CXXMethodDecl>(MemberFn->getMemberDecl())
5625 : dyn_cast_if_present<CXXMethodDecl>(CurContext);
5626 const CXXRecordDecl *CurRD =
5627 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5628 const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5629 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5630 continue;
5631 }
5632 }
5633 return true;
5634 }
5635 return false;
5636}
5637
5638void Sema::diagnoseTypo(const TypoCorrection &Correction,
5639 const PartialDiagnostic &TypoDiag,
5640 bool ErrorRecovery) {
5641 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5643}
5644
5645/// Find which declaration we should import to provide the definition of
5646/// the given declaration.
5648 if (const auto *VD = dyn_cast<VarDecl>(D))
5649 return VD->getDefinition();
5650 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5651 return FD->getDefinition();
5652 if (const auto *TD = dyn_cast<TagDecl>(D))
5653 return TD->getDefinition();
5654 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
5655 return ID->getDefinition();
5656 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))
5657 return PD->getDefinition();
5658 if (const auto *TD = dyn_cast<TemplateDecl>(D))
5659 if (const NamedDecl *TTD = TD->getTemplatedDecl())
5660 return getDefinitionToImport(TTD);
5661 return nullptr;
5662}
5663
5665 MissingImportKind MIK, bool Recover) {
5666 // Suggest importing a module providing the definition of this entity, if
5667 // possible.
5668 const NamedDecl *Def = getDefinitionToImport(Decl);
5669 if (!Def)
5670 Def = Decl;
5671
5672 Module *Owner = getOwningModule(Def);
5673 assert(Owner && "definition of hidden declaration is not in a module");
5674
5675 llvm::SmallVector<Module*, 8> OwningModules;
5676 OwningModules.push_back(Owner);
5677 auto Merged = Context.getModulesWithMergedDefinition(Def);
5678 llvm::append_range(OwningModules, Merged);
5679
5680 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5681 Recover);
5682}
5683
5684/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5685/// suggesting the addition of a #include of the specified file.
5687 llvm::StringRef IncludingFile) {
5688 bool IsAngled = false;
5690 E, IncludingFile, &IsAngled);
5691 return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');
5692}
5693
5695 SourceLocation DeclLoc,
5696 ArrayRef<Module *> Modules,
5697 MissingImportKind MIK, bool Recover) {
5698 assert(!Modules.empty());
5699
5700 // See https://github.com/llvm/llvm-project/issues/73893. It is generally
5701 // confusing than helpful to show the namespace is not visible.
5702 if (isa<NamespaceDecl>(Decl))
5703 return;
5704
5705 auto NotePrevious = [&] {
5706 // FIXME: Suppress the note backtrace even under
5707 // -fdiagnostics-show-note-include-stack. We don't care how this
5708 // declaration was previously reached.
5709 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5710 };
5711
5712 // Weed out duplicates from module list.
5713 llvm::SmallVector<Module*, 8> UniqueModules;
5714 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5715 for (auto *M : Modules) {
5716 if (M->isExplicitGlobalModule() || M->isPrivateModule())
5717 continue;
5718 if (UniqueModuleSet.insert(M).second)
5719 UniqueModules.push_back(M);
5720 }
5721
5722 // Try to find a suitable header-name to #include.
5723 std::string HeaderName;
5724 if (OptionalFileEntryRef Header =
5725 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5726 if (const FileEntry *FE =
5728 HeaderName =
5729 getHeaderNameForHeader(PP, *Header, FE->tryGetRealPathName());
5730 }
5731
5732 // If we have a #include we should suggest, or if all definition locations
5733 // were in global module fragments, don't suggest an import.
5734 if (!HeaderName.empty() || UniqueModules.empty()) {
5735 // FIXME: Find a smart place to suggest inserting a #include, and add
5736 // a FixItHint there.
5737 Diag(UseLoc, diag::err_module_unimported_use_header)
5738 << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5739 // Produce a note showing where the entity was declared.
5740 NotePrevious();
5741 if (Recover)
5743 return;
5744 }
5745
5746 Modules = UniqueModules;
5747
5748 auto GetModuleNameForDiagnostic = [this](const Module *M) -> std::string {
5749 if (M->isModuleMapModule())
5750 return M->getFullModuleName();
5751
5752 if (M->isImplicitGlobalModule())
5753 M = M->getTopLevelModule();
5754
5755 // If the current module unit is in the same module with M, it is OK to show
5756 // the partition name. Otherwise, it'll be sufficient to show the primary
5757 // module name.
5759 return M->getTopLevelModuleName().str();
5760 else
5761 return M->getPrimaryModuleInterfaceName().str();
5762 };
5763
5764 if (Modules.size() > 1) {
5765 std::string ModuleList;
5766 unsigned N = 0;
5767 for (const auto *M : Modules) {
5768 ModuleList += "\n ";
5769 if (++N == 5 && N != Modules.size()) {
5770 ModuleList += "[...]";
5771 break;
5772 }
5773 ModuleList += GetModuleNameForDiagnostic(M);
5774 }
5775
5776 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5777 << (int)MIK << Decl << ModuleList;
5778 } else {
5779 // FIXME: Add a FixItHint that imports the corresponding module.
5780 Diag(UseLoc, diag::err_module_unimported_use)
5781 << (int)MIK << Decl << GetModuleNameForDiagnostic(Modules[0]);
5782 }
5783
5784 NotePrevious();
5785
5786 // Try to recover by implicitly importing this module.
5787 if (Recover)
5789}
5790
5791void Sema::diagnoseTypo(const TypoCorrection &Correction,
5792 const PartialDiagnostic &TypoDiag,
5793 const PartialDiagnostic &PrevNote,
5794 bool ErrorRecovery) {
5795 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5796 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5798 Correction.getCorrectionRange(), CorrectedStr);
5799
5800 // Maybe we're just missing a module import.
5801 if (Correction.requiresImport()) {
5802 NamedDecl *Decl = Correction.getFoundDecl();
5803 assert(Decl && "import required but no declaration to import");
5804
5807 return;
5808 }
5809
5810 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5811 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5812
5813 NamedDecl *ChosenDecl =
5814 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5815
5816 // For builtin functions which aren't declared anywhere in source,
5817 // don't emit the "declared here" note.
5818 if (const auto *FD = dyn_cast_if_present<FunctionDecl>(ChosenDecl);
5819 FD && FD->getBuiltinID() &&
5820 PrevNote.getDiagID() == diag::note_previous_decl &&
5821 Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {
5822 ChosenDecl = nullptr;
5823 }
5824
5825 if (PrevNote.getDiagID() && ChosenDecl)
5826 Diag(ChosenDecl->getLocation(), PrevNote)
5827 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5828
5829 // Add any extra diagnostics.
5830 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5831 Diag(Correction.getCorrectionRange().getBegin(), PD);
5832}
5833
5835 DeclarationNameInfo Name(II, IILoc);
5836 LookupResult R(*this, Name, LookupAnyName,
5837 RedeclarationKind::NotForRedeclaration);
5839 R.setHideTags(false);
5840 LookupName(R, S);
5841 R.dump();
5842}
5843
5845 E->dump();
5846}
5847
5849 // A declaration with an owning module for linkage can never link against
5850 // anything that is not visible. We don't need to check linkage here; if
5851 // the context has internal linkage, redeclaration lookup won't find things
5852 // from other TUs, and we can't safely compute linkage yet in general.
5853 if (cast<Decl>(CurContext)->getOwningModuleForLinkage())
5854 return RedeclarationKind::ForVisibleRedeclaration;
5855 return RedeclarationKind::ForExternalRedeclaration;
5856}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
int Category
Definition: Format.cpp:3180
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:145
unsigned Iter
Definition: HTMLLogger.cpp:153
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:31
#define SM(sm)
Definition: OffloadArch.cpp:16
static StringRef getIdentifier(const Token &Tok)
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Redeclaration.h:18
uint32_t Id
Definition: SemaARM.cpp:1179
static Module * getDefiningModule(Sema &S, Decl *Entity)
Find the module in which the given declaration was defined.
static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind, const NamedDecl *D, const NamedDecl *Existing)
Determine whether D is a better lookup result than Existing, given that they declare the same entity.
Definition: SemaLookup.cpp:374
static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class)
Determine whether we can declare a special member function within the class at this point.
static bool canHideTag(const NamedDecl *D)
Determine whether D can hide a tag declaration.
Definition: SemaLookup.cpp:468
static std::string getHeaderNameForHeader(Preprocessor &PP, FileEntryRef E, llvm::StringRef IncludingFile)
Get a "quoted.h" or <angled.h> include path to use in a diagnostic suggesting the addition of a #incl...
static void addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T)
static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name)
Lookup an OpenCL typedef type.
Definition: SemaLookup.cpp:723
static DeclContext * findOuterContext(Scope *S)
Find the outer declaration context from this scope.
static void LookupPotentialTypoResult(Sema &SemaRef, LookupResult &Res, IdentifierInfo *Name, Scope *S, CXXScopeSpec *SS, DeclContext *MemberContext, bool EnteringContext, bool isObjCIvarLookup, bool FindHidden)
Perform name lookup for a possible result for typo correction.
static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC)
Check whether the declarations found for a typo correction are visible.
static bool isNamespaceOrTranslationUnitScope(Scope *S)
static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, DeclContext *StartDC)
Perform qualified name lookup in the namespaces nominated by using directives by the given context.
static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC)
static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name)
Lookup an OpenCL enum type.
Definition: SemaLookup.cpp:710
static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, DeclContext *Ctx)
static bool hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name)
Determine whether this is the name of an implicitly-declared special member function.
static void getNestedNameSpecifierIdentifiers(NestedNameSpecifier NNS, SmallVectorImpl< const IdentifierInfo * > &Identifiers)
static void DeclareImplicitMemberFunctionsWithName(Sema &S, DeclarationName Name, SourceLocation Loc, const DeclContext *DC)
If there are any implicit member functions with the given name that need to be declared in the given ...
static void AddKeywordsToConsumer(Sema &SemaRef, TypoCorrectionConsumer &Consumer, Scope *S, CorrectionCandidateCallback &CCC, bool AfterNestedNameSpecifier)
Add keywords to the consumer as possible typo corrections.
static void GetQualTypesForOpenCLBuiltin(Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt, SmallVector< QualType, 1 > &RetTypes, SmallVector< SmallVector< QualType, 1 >, 5 > &ArgTypes)
Get the QualType instances of the return type and arguments for an OpenCL builtin function signature.
Definition: SemaLookup.cpp:747
static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass, llvm::StringRef Name)
Diagnose a missing builtin type.
Definition: SemaLookup.cpp:702
static bool hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
static bool hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Filter F, Sema::AcceptableKind Kind)
static bool isCandidateViable(CorrectionCandidateCallback &CCC, TypoCorrection &Candidate)
static const DeclContext * getContextForScopeMatching(const Decl *D)
Get a representative context for a declaration such that two declarations will have the same context ...
Definition: SemaLookup.cpp:359
static NamedDecl * findAcceptableDecl(Sema &SemaRef, NamedDecl *D, unsigned IDNS)
Retrieve the visible declaration corresponding to D, if any.
static void GetOpenCLBuiltinFctOverloads(ASTContext &Context, unsigned GenTypeMaxCnt, std::vector< QualType > &FunctionList, SmallVector< QualType, 1 > &RetTypes, SmallVector< SmallVector< QualType, 1 >, 5 > &ArgTypes)
Create a list of the candidate function overloads for an OpenCL builtin function.
Definition: SemaLookup.cpp:776
static const unsigned MaxTypoDistanceResultSets
static const NamedDecl * getDefinitionToImport(const NamedDecl *D)
Find which declaration we should import to provide the definition of the given declaration.
static bool hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
static unsigned getIDNS(Sema::LookupNameKind NameKind, bool CPlusPlus, bool Redeclaration)
Definition: SemaLookup.cpp:214
static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR, IdentifierInfo *II, const unsigned FctIndex, const unsigned Len)
When trying to resolve a function name, if isOpenCLBuiltin() returns a non-null <Index,...
Definition: SemaLookup.cpp:821
static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S)
Looks up the declaration of "struct objc_super" and saves it for later use in building builtin declar...
Definition: SemaLookup.cpp:997
static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, const DeclContext *NS, UnqualUsingDirectiveSet &UDirs)
SourceLocation Loc
Definition: SemaObjC.cpp:754
This file declares semantic analysis functions specific to RISC-V.
__DEVICE__ long long abs(long long __n)
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:871
void insert(NamedDecl *D)
Adds a new ADL candidate to this map.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1201
const SmallVectorImpl< Type * > & getTypes() const
Definition: ASTContext.h:1363
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:744
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
IdentifierTable & Idents
Definition: ASTContext.h:740
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:742
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
void setObjCSuperType(QualType ST)
Definition: ASTContext.h:2102
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
CanQualType OverloadTy
Definition: ASTContext.h:1250
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:793
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2898
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
Definition: ASTContext.h:1222
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1750
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
CanQualType getCanonicalTagType(const TagDecl *TD) const
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:313
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
std::list< CXXBasePath >::iterator paths_iterator
std::list< CXXBasePath >::const_iterator const_paths_iterator
void swap(CXXBasePaths &Other)
Swap this data structure's contents with another CXXBasePaths object.
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2604
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_range bases()
Definition: DeclCXX.h:608
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:600
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:766
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:892
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:548
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1721
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2075
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:799
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1007
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2121
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:983
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:925
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:180
SourceRange getRange() const
Definition: DeclSpec.h:79
bool isSet() const
Deprecated.
Definition: DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:178
void * getAsOpaquePtr() const
Retrieve the internal representation of this canonical type.
Declaration of a class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
virtual unsigned RankCandidate(const TypoCorrection &candidate)
Method used by Sema::CorrectTypo to assign an "edit distance" rank to a candidate (where a lower valu...
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
virtual std::unique_ptr< CorrectionCandidateCallback > clone()=0
Clone this CorrectionCandidateCallback.
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1382
DeclListNode::iterator iterator
Definition: DeclBase.h:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
Definition: DeclBase.cpp:2174
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2238
bool isFileContext() const
Definition: DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2077
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1392
ASTContext & getParentASTContext() const
Definition: DeclBase.h:2138
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1879
bool isTranslationUnit() const
Definition: DeclBase.h:2185
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2022
bool shouldUseQualifiedLookup() const
Definition: DeclBase.h:2723
void setUseQualifiedLookup(bool use=true) const
Definition: DeclBase.h:2719
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1459
bool isInlineNamespace() const
Definition: DeclBase.cpp:1337
bool isFunctionOrMethod() const
Definition: DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1309
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Definition: DeclBase.cpp:1428
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1076
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:648
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1226
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1119
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:524
void addAttr(Attr *A)
Definition: DeclBase.cpp:1022
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1184
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:859
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:893
bool isInvisibleOutsideTheOwningModule() const
Definition: DeclBase.h:670
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1121
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Definition: DeclBase.cpp:1138
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:251
void dump() const
Definition: ASTDumper.cpp:220
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2793
bool isInvalidDecl() const
Definition: DeclBase.h:588
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:889
SourceLocation getLocation() const
Definition: DeclBase.h:439
@ IDNS_NonMemberOperator
This declaration is a C++ operator declared in a non-class context.
Definition: DeclBase.h:168
@ IDNS_TagFriend
This declaration is a friend class.
Definition: DeclBase.h:157
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
@ IDNS_Type
Types, declared with 'struct foo', typedefs, etc.
Definition: DeclBase.h:130
@ IDNS_OMPReduction
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:178
@ IDNS_Label
Labels, declared with 'x:' and referenced with 'goto x'.
Definition: DeclBase.h:117
@ IDNS_Member
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:136
@ IDNS_OMPMapper
This declaration is an OpenMP user defined mapper.
Definition: DeclBase.h:181
@ IDNS_ObjCProtocol
Objective C @protocol.
Definition: DeclBase.h:147
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
Definition: DeclBase.h:140
@ IDNS_OrdinaryFriend
This declaration is a friend function.
Definition: DeclBase.h:152
@ IDNS_Using
This declaration is a using declaration.
Definition: DeclBase.h:163
@ IDNS_LocalExtern
This declaration is a function-local extern declaration of a variable or function.
Definition: DeclBase.h:175
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:125
bool isDeprecated(std::string *Message=nullptr) const
Determine whether this declaration is marked 'deprecated'.
Definition: DeclBase.h:762
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:234
void setImplicit(bool I=true)
Definition: DeclBase.h:594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1049
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:949
DeclContext * getDeclContext()
Definition: DeclBase.h:448
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:509
bool hasTagIdentifierNamespace() const
Definition: DeclBase.h:899
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition: DeclBase.cpp:530
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:870
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
std::string getAsString() const
Retrieve the human-readable string for this name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:590
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:596
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:878
Represents an enum.
Definition: Decl.h:4004
The return type of classify().
Definition: Expr.h:337
This represents one expression.
Definition: Expr.h:112
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:412
QualType getType() const
Definition: Expr.h:144
bool isFPConstrained() const
Definition: LangOptions.h:844
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:306
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:78
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:139
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs, MemberExpr *ME=nullptr)
Represents a function declaration or definition.
Definition: Decl.h:1999
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition: Decl.h:2188
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3788
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4205
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2539
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3767
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
ExtProtoInfo getExtProtoInfo() const
Definition: TypeBase.h:5571
ArrayRef< QualType > param_types() const
Definition: TypeBase.h:5722
Declaration of a template function.
Definition: DeclTemplate.h:952
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:998
ExtInfo withCallingConv(CallingConv cc) const
Definition: TypeBase.h:4701
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
QualType getReturnType() const
Definition: TypeBase.h:4818
std::string suggestPathToFileForDiagnostics(FileEntryRef File, llvm::StringRef MainFile, bool *IsAngled=nullptr) const
Suggest a path by which the specified file could be found, for use in diagnostics to suggest a #inclu...
Provides lookups to, and iteration over, IdentiferInfo objects.
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
iterator end()
Returns the end iterator.
bool isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IdentifierInfoLookup * getExternalIdentifierLookup() const
Retrieve the external identifier lookup object, if any.
Represents the declaration of a label.
Definition: Decl.h:523
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:5423
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:677
void restart()
Restart the iteration.
Definition: Lookup.h:718
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:723
bool hasNext() const
Definition: Lookup.h:708
NamedDecl * next()
Definition: Lookup.h:712
Represents the results of name lookup.
Definition: Lookup.h:147
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:488
void setShadowed()
Note that we found and ignored a declaration while performing lookup.
Definition: Lookup.h:514
static bool isAvailableForLookup(Sema &SemaRef, NamedDecl *ND)
Determine whether this lookup is permitted to see the declaration.
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:607
void setFindLocalExtern(bool FindLocalExtern)
Definition: Lookup.h:755
void setAllowHidden(bool AH)
Specify whether hidden declarations are visible, e.g., for recovery reasons.
Definition: Lookup.h:298
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void setContextRange(SourceRange SR)
Sets a 'context' source range.
Definition: Lookup.h:653
static bool isAcceptable(Sema &SemaRef, NamedDecl *D, Sema::AcceptableKind Kind)
Definition: Lookup.h:376
void setAmbiguousQualifiedTagHiding()
Make these results show that the name was found in different contexts and a tag decl was hidden by an...
Definition: Lookup.h:602
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
bool isTemplateNameLookup() const
Definition: Lookup.h:322
void setAmbiguousBaseSubobjects(CXXBasePaths &P)
Make these results show that the name was found in distinct base classes of the same type.
Definition: SemaLookup.cpp:667
bool isSingleTagDecl() const
Asks if the result is a single tag decl.
Definition: Lookup.h:582
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:488
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:666
void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P)
Make these results show that the name was found in base classes of different types.
Definition: SemaLookup.cpp:675
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:569
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:311
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:408
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
unsigned getIdentifierNamespace() const
Returns the identifier namespace mask for this lookup.
Definition: Lookup.h:426
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:672
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:457
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void print(raw_ostream &)
Definition: SemaLookup.cpp:683
static bool isReachable(Sema &SemaRef, NamedDecl *D)
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:636
bool isForRedeclaration() const
True if this lookup is just looking for an existing declaration.
Definition: Lookup.h:280
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
void setNotFoundInCurrentInstantiation()
Note that while no result was found in the current instantiation, there were dependent base classes t...
Definition: Lookup.h:501
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3300
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3383
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition: Type.cpp:5502
QualType getPointeeType() const
Definition: TypeBase.h:3687
virtual bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc)=0
Check global module index for missing imports.
Describes a module or submodule.
Definition: Module.h:144
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:732
bool isPrivateModule() const
Definition: Module.h:249
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition: Module.h:458
bool isModuleVisible(const Module *M) const
Determine whether the specified module would be visible to a lookup at the end of this module.
Definition: Module.h:827
bool isModuleInterfaceUnit() const
Definition: Module.h:680
bool isModuleMapModule() const
Definition: Module.h:251
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:648
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition: Module.h:687
bool isExplicitGlobalModule() const
Definition: Module.h:242
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition: Module.h:239
bool isImplicitGlobalModule() const
Definition: Module.h:245
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:239
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:224
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:722
This represents a decl that may have a name.
Definition: Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:294
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
Represent a C++ namespace.
Definition: Decl.h:591
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:642
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
NamespaceAndPrefix getAsNamespaceAndPrefix() const
void print(raw_ostream &OS, const PrintingPolicy &Policy, bool ResolveTemplateArguments=false, bool PrintFinalScopeResOp=true) const
Print this nested name specifier to the given output stream.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Type
A type, stored as a Type*.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2329
Represents an ObjC class declaration.
Definition: DeclObjC.h:1154
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1952
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: TypeBase.h:7961
qual_range quals() const
Definition: TypeBase.h:8080
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:731
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2084
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1369
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:3122
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3183
llvm::iterator_range< decls_iterator > decls() const
Definition: ExprCXX.h:3221
Represents a parameter to a function.
Definition: Decl.h:1789
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1822
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2946
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:145
bool isMacroDefined(StringRef Id)
HeaderSearch & getHeaderSearchInfo() const
OptionalFileEntryRef getHeaderToIncludeForDiagnostics(SourceLocation IncLoc, SourceLocation MLoc)
We want to produce a diagnostic at location IncLoc concerning an unreachable effect at location MLoc ...
A (possibly-)qualified type.
Definition: TypeBase.h:937
void addConst()
Add the const type qualifier to this QualType.
Definition: TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: TypeBase.h:1164
Represents a template name as written in source code.
Definition: TemplateName.h:504
Represents a struct/union/class.
Definition: Decl.h:4309
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition: Scope.h:291
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:398
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:401
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:287
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:33
std::unique_ptr< sema::RISCVIntrinsicManager > IntrinsicManager
Definition: SemaRISCV.h:57
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12359
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12392
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:9239
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:9378
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:13446
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13430
llvm::DenseSet< Module * > & getLookupModules()
Get the set of additional modules that should be checked during name lookup.
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:9277
@ LookupLabel
Label name lookup.
Definition: Sema.h:9286
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9281
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9308
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:9300
@ LookupOMPReductionName
Look up the name of an OpenMP user-defined reduction operation.
Definition: Sema.h:9322
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9316
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition: Sema.h:9318
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9313
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:9293
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:9320
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:9304
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9289
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition: Sema.h:9296
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9284
@ LookupOMPMapperName
Look up the name of an OpenMP user-defined mapper.
Definition: Sema.h:9324
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9326
bool hasReachableDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
MissingImportKind
Kinds of missing import.
Definition: Sema.h:9715
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules)
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class)
Perform qualified name lookup into all base classes of the given class.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
@ AR_accessible
Definition: Sema.h:1651
Preprocessor & getPreprocessor() const
Definition: Sema.h:917
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
IdentifierInfo * getSuperIdentifier() const
Definition: Sema.cpp:2866
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11895
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
Definition: Sema.h:9221
llvm::DenseMap< NamedDecl *, NamedDecl * > VisibleNamespaceCache
Map from the most recent declaration of a namespace to the most recent visible declaration of that na...
Definition: Sema.h:13450
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
ASTContext & Context
Definition: Sema.h:1276
IdentifierSourceLocations TypoCorrectionFailures
A cache containing identifiers for which typo correction failed and their locations,...
Definition: Sema.h:9232
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:915
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:921
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1555
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2388
ASTContext & getASTContext() const
Definition: Sema.h:918
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
unsigned TyposCorrected
The number of typos corrected by CorrectTypo.
Definition: Sema.h:9224
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:1184
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition: Sema.h:3573
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1652
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
FPOptions & getCurFPFeatures()
Definition: Sema.h:913
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition: Sema.h:911
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope=true, bool LoadExternal=true)
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:1275
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:15330
SemaHLSL & HLSL()
Definition: Sema.h:1448
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
SemaRISCV & RISCV()
Definition: Sema.h:1513
AcceptableKind
Definition: Sema.h:9269
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1659
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1307
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:15324
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9807
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2512
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1411
SemaOpenCL & OpenCL()
Definition: Sema.h:1493
CXXMethodDecl * LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the moving assignment operator for the given class.
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
CXXConstructorDecl * LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the moving constructor for the given class.
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition: Sema.h:15337
CXXMethodDecl * LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the copying assignment operator for the given class.
bool isModuleVisible(const Module *M, bool ModulePrivate=false)
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
bool hasVisibleMergedDefinition(const NamedDecl *Def)
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:9267
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation())
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
RedeclarationKind forRedeclarationInCurContext() const
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
ASTConsumer & Consumer
Definition: Sema.h:1277
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition: Sema.cpp:109
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1239
void DiagnoseAmbiguousLookup(LookupResult &Result)
Produce a diagnostic describing the ambiguity that resulted from name lookup.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:1279
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
DiagnosticsEngine & Diags
Definition: Sema.h:1278
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
bool hasAcceptableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
Determine if the template parameter D has a reachable default argument.
AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found)
Checks access to a member.
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition: Sema.h:13441
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:1225
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:627
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
Definition: SemaType.cpp:9268
LiteralOperatorLookupResult
The possible outcomes of name lookup for a literal operator.
Definition: Sema.h:9330
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition: Sema.h:9334
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:9340
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:9332
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:9337
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:9348
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:9344
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II)
Called on #pragma clang __debug dump II.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
IdentifierResolver IdResolver
Definition: Sema.h:3461
LabelDecl * LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc)
Perform a name lookup for a label with the specified name; this does not create a new label if the lo...
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod)
Create an implicit import of the given module at the given source location, for error recovery,...
Definition: SemaModule.cpp:843
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
Definition: ASTDumper.cpp:290
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1801
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3714
bool isEntityBeingDefined() const
Determines whether this entity is in the process of being defined.
Definition: Decl.h:3898
TagDecl * getOriginalDecl() const
Definition: TypeBase.h:6441
virtual CallingConv getDefaultCallingConv() const
Gets the default calling convention for the given target.
Definition: TargetInfo.h:1719
A template argument list.
Definition: DeclTemplate.h:250
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:286
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:528
Represents a template argument.
Definition: TemplateBase.h:61
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:322
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:440
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:296
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:353
Represents a C++ template name within the type system.
Definition: TemplateName.h:222
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:74
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:146
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: TypeBase.h:7290
Represents a declaration of a type.
Definition: Decl.h:3510
The base class of the type hierarchy.
Definition: TypeBase.h:1833
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2060
QualType getCanonicalTypeInternal() const
Definition: TypeBase.h:3137
EnumDecl * castAsEnumDecl() const
Definition: Type.h:59
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2440
bool isAnyPointerType() const
Definition: TypeBase.h:8588
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3559
void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) override
Invoked each time Sema::LookupVisibleDecls() finds a declaration visible from the current scope or co...
void addKeywordResult(StringRef Keyword)
void addCorrection(TypoCorrection Correction)
const TypoCorrection & getNextCorrection()
Return the next typo correction that passes all internal filters and is deemed valid by the consumer'...
void FoundName(StringRef Name)
void addNamespaces(const llvm::MapVector< NamespaceDecl *, bool > &KnownNamespaces)
Set-up method to add to the consumer the set of namespaces to use in performing corrections to nested...
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
ArrayRef< PartialDiagnostic > getExtraDiagnostics() const
static const unsigned InvalidDistance
void addCorrectionDecl(NamedDecl *CDecl)
Add the given NamedDecl to the list of NamedDecls that are the declarations associated with the Decla...
void setCorrectionDecls(ArrayRef< NamedDecl * > Decls)
Clears the list of NamedDecls and adds the given set.
std::string getAsString(const LangOptions &LO) const
bool requiresImport() const
Returns whether this typo correction is correcting to a declaration that was declared in a module tha...
void setCorrectionRange(CXXScopeSpec *SS, const DeclarationNameInfo &TypoName)
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
decl_iterator end()
void setCallbackDistance(unsigned ED)
decl_iterator begin()
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setRequiresImport(bool Req)
std::string getQuoted(const LangOptions &LO) const
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
unsigned size() const
void append(iterator I, iterator E)
void truncate(unsigned N)
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents C++ using-directive.
Definition: DeclCXX.h:3090
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:3228
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3393
QualType getType() const
Definition: Decl.h:722
Represents a variable declaration or definition.
Definition: Decl.h:925
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition: Decl.cpp:2714
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition: Lookup.h:838
virtual bool includeHiddenDecls() const
Determine whether hidden declarations (from unimported modules) should be given to this consumer.
virtual ~VisibleDeclConsumer()
Destroys the visible declaration consumer.
bool isVisible(const Module *M) const
Determine whether a module is visible.
Definition: Module.h:890
SmallVector< SwitchInfo, 8 > SwitchStack
SwitchStack - This is the current set of active switch statements in the block.
Definition: ScopeInfo.h:209
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
Definition: SPIR.cpp:47
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1948
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
@ NotFound
No entity found met the criteria.
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
@ Found
Name lookup found a single declaration that met the criteria.
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
std::unique_ptr< sema::RISCVIntrinsicManager > CreateRISCVIntrinsicManager(Sema &S)
Definition: SemaRISCV.cpp:498
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
@ AmbiguousBaseSubobjects
Name lookup results in an ambiguity because multiple nonstatic entities that meet the lookup criteria...
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
@ AmbiguousReferenceToPlaceholderVariable
Name lookup results in an ambiguity because multiple placeholder variables were found in the same sco...
@ AmbiguousReference
Name lookup results in an ambiguity because multiple definitions of entity that meet the lookup crite...
@ AmbiguousBaseSubobjectTypes
Name lookup results in an ambiguity because multiple entities that meet the lookup criteria were foun...
@ SC_Extern
Definition: Specifiers.h:251
@ SC_None
Definition: Specifiers.h:250
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:62
CorrectTypoKind
Definition: Sema.h:804
@ Template
We are parsing a template declaration.
@ Keyword
The name has been typo-corrected to a keyword.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:424
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
@ Success
Template argument deduction was successful.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ CC_C
Definition: Specifiers.h:279
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1512
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ EST_None
no exception specification
Represents an element in a path from a derived class to a base class.
int SubobjectNumber
Identifies which base class subobject (of type Base->getType()) this base path element refers to.
const CXXBaseSpecifier * Base
The base specifier that states the link from a derived class to a base class, which will be followed ...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
Extra information about a function prototype.
Definition: TypeBase.h:5367
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57