clang 23.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
100 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
101
102 ListTy list;
103 llvm::SmallPtrSet<DeclContext*, 8> visited;
104
105 public:
106 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
107
108 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
109 // C++ [namespace.udir]p1:
110 // During unqualified name lookup, the names appear as if they
111 // were declared in the nearest enclosing namespace which contains
112 // both the using-directive and the nominated namespace.
113 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
114 assert(InnermostFileDC && InnermostFileDC->isFileContext());
115
116 for (; S; S = S->getParent()) {
117 // C++ [namespace.udir]p1:
118 // A using-directive shall not appear in class scope, but may
119 // appear in namespace scope or in block scope.
120 DeclContext *Ctx = S->getEntity();
121 if (Ctx && Ctx->isFileContext()) {
122 visit(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) {
149 DeclContext *NS = UD->getNominatedNamespace();
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) {
161 SmallVector<DeclContext*, 4> queue;
162 while (true) {
163 for (auto *UD : DC->using_directives()) {
164 DeclContext *NS = UD->getNominatedNamespace();
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::stable_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.
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();
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();
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();
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
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,
781 Context.getTargetInfo().getDefaultCallingConv());
782 PI.Variadic = false;
783
784 // Do not attempt to create any FunctionTypes if there are no return types,
785 // which happens when a type belongs to a disabled extension.
786 if (RetTypes.size() == 0)
787 return;
788
789 // Create FunctionTypes for each (gen)type.
790 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
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
877 SourceLocation Loc = LR.getNameLoc();
878 DeclContext *Parent = Context.getTranslationUnitDecl();
879 FunctionDecl *NewOpenCLBuiltin;
880
881 for (const auto &FTy : FunctionList) {
882 NewOpenCLBuiltin = FunctionDecl::Create(
883 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 ||
929 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
930 if (II) {
931 if (NameKind == Sema::LookupOrdinaryName) {
932 if (getLangOpts().CPlusPlus) {
933#define BuiltinTemplate(BIName)
934#define CPlusPlusBuiltinTemplate(BIName) \
935 if (II == getASTContext().get##BIName##Name()) { \
936 R.addDecl(getASTContext().get##BIName##Decl()); \
937 return true; \
938 }
939#include "clang/Basic/BuiltinTemplates.inc"
940 }
941 if (getLangOpts().HLSL) {
942#define BuiltinTemplate(BIName)
943#define HLSLBuiltinTemplate(BIName) \
944 if (II == getASTContext().get##BIName##Name()) { \
945 R.addDecl(getASTContext().get##BIName##Decl()); \
946 return true; \
947 }
948#include "clang/Basic/BuiltinTemplates.inc"
949 }
950 }
951
952 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
953 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
954 auto Index = isOpenCLBuiltin(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.
978 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
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,
1076 SourceLocation Loc,
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
1121 break;
1122
1123 default:
1124 break;
1125 }
1126}
1127
1128// Adds all qualifying matches for a name within a decl context to the
1129// given lookup result. Returns true if any matches were found.
1130static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
1131 bool Found = false;
1132
1133 // Lazily declare C++ special member functions.
1134 if (S.getLangOpts().CPlusPlus)
1135 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
1136 DC);
1137
1138 // Perform lookup into this declaration context.
1139 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
1140 for (NamedDecl *D : DR) {
1141 if ((D = R.getAcceptableDecl(D))) {
1142 R.addDecl(D);
1143 Found = true;
1144 }
1145 }
1146
1147 if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
1148 return true;
1149
1150 if (R.getLookupName().getNameKind()
1152 R.getLookupName().getCXXNameType()->isDependentType() ||
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. [...]
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 =
1168 R.getLookupName().getCXXNameType()->getContainedDeducedType();
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.
1200 TemplateDeductionInfo Info(R.getNameLoc());
1201 FunctionDecl *Specialization = nullptr;
1202
1203 const FunctionProtoType *ConvProto
1204 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
1205 assert(ConvProto && "Nonsensical conversion function template type");
1206
1207 // Compute the type of the function that we would expect the conversion
1208 // function to have, if it were to match the name given.
1209 // FIXME: Calling convention!
1212 EPI.ExceptionSpec = EST_None;
1213 QualType ExpectedType = R.getSema().Context.getFunctionType(
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) ==
1221 R.addDecl(Specialization);
1222 Found = true;
1223 }
1224 }
1225
1226 return Found;
1227}
1228
1229// Performs C++ unqualified lookup into the given file context.
1230static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
1231 const DeclContext *NS,
1232 UnqualUsingDirectiveSet &UDirs) {
1233
1234 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1235
1236 // Perform direct name lookup into the LookupCtx.
1237 bool Found = LookupDirect(S, R, 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) {
1273 R.setFindLocalExtern(R.getIdentifierNamespace() &
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())
1298 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
1299 }
1300
1301 // C++23 [temp.dep.general]p2:
1302 // The component name of an unqualified-id is dependent if
1303 // - it is a conversion-function-id whose conversion-type-id
1304 // is dependent, or
1305 // - it is operator= and the current class is a templated entity, or
1306 // - the unqualified-id is the postfix-expression in a dependent call.
1308 Name.getCXXNameType()->isDependentType()) {
1309 R.setNotFoundInCurrentInstantiation();
1310 return false;
1311 }
1312
1313 // Implicitly declare member functions with the name we're looking for, if in
1314 // fact we are in a scope where it matters.
1315
1316 Scope *Initial = S;
1317 IdentifierResolver::iterator
1318 I = IdResolver.begin(Name),
1319 IEnd = IdResolver.end();
1320
1321 // First we lookup local scope.
1322 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1323 // ...During unqualified name lookup (3.4.1), the names appear as if
1324 // they were declared in the nearest enclosing namespace which contains
1325 // both the using-directive and the nominated namespace.
1326 // [Note: in this context, "contains" means "contains directly or
1327 // indirectly".
1328 //
1329 // For example:
1330 // namespace A { int i; }
1331 // void foo() {
1332 // int i;
1333 // {
1334 // using namespace A;
1335 // ++i; // finds local 'i', A::i appears at global scope
1336 // }
1337 // }
1338 //
1339 UnqualUsingDirectiveSet UDirs(*this);
1340 bool VisitedUsingDirectives = false;
1341 bool LeftStartingScope = false;
1342
1343 // When performing a scope lookup, we want to find local extern decls.
1344 FindLocalExternScope FindLocals(R);
1345
1346 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1347 bool SearchNamespaceScope = true;
1348 // Check whether the IdResolver has anything in this scope.
1349 for (; I != IEnd && S->isDeclScope(*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()))
1379 R.setNamingClass(Record);
1380 return true;
1381 }
1382
1383 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1384 // C++11 [class.friend]p11:
1385 // If a friend declaration appears in a local class and the name
1386 // specified is an unqualified name, a prior declaration is
1387 // looked up without considering scopes that are outside the
1388 // innermost enclosing non-class scope.
1389 return false;
1390 }
1391
1392 if (DeclContext *Ctx = S->getLookupEntity()) {
1393 DeclContext *OuterCtx = findOuterContext(S);
1394 for (; Ctx && !Ctx->Equals(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())
1559 Context.mergeDefinitionIntoModule(ND, M);
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->setVisiblePromoted();
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->getDefinition();
1593 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1595 Entity = Pattern->getDefinition();
1596 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1597 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1598 Entity = Pattern->getDefinition();
1599 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1600 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1601 Entity = Pattern->getDefinition();
1602 }
1603 if (!Entity)
1604 return nullptr;
1605
1606 // Walk up to the containing context. That might also have been instantiated
1607 // from a template.
1608 DeclContext *Context = Entity->getLexicalDeclContext();
1609 if (Context->isFileContext())
1610 return S.getOwningModule(Entity);
1611 return getDefiningModule(S, cast<Decl>(Context));
1612}
1613
1614llvm::DenseSet<Module*> &Sema::getLookupModules() {
1615 unsigned N = CodeSynthesisContexts.size();
1616 for (unsigned I = CodeSynthesisContextLookupModules.size();
1617 I != N; ++I) {
1618 Module *M = CodeSynthesisContexts[I].Entity ?
1619 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
1620 nullptr;
1621 if (M && !LookupModulesCache.insert(M).second)
1622 M = nullptr;
1624 }
1625 return LookupModulesCache;
1626}
1627
1628bool Sema::isUsableModule(const Module *M) {
1629 assert(M && "We shouldn't check nullness for module here");
1630 // Return quickly if we cached the result.
1631 if (UsableModuleUnitsCache.count(M))
1632 return true;
1633
1634 // If M is the global module fragment of the current translation unit. So it
1635 // should be usable.
1636 // [module.global.frag]p1:
1637 // The global module fragment can be used to provide declarations that are
1638 // attached to the global module and usable within the module unit.
1639 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment) {
1640 UsableModuleUnitsCache.insert(M);
1641 return true;
1642 }
1643
1644 // Otherwise, the global module fragment from other translation unit is not
1645 // directly usable.
1646 if (M->isExplicitGlobalModule())
1647 return false;
1648
1649 Module *Current = getCurrentModule();
1650
1651 // If we're not parsing a module, we can't use all the declarations from
1652 // another module easily.
1653 if (!Current)
1654 return false;
1655
1656 // For implicit global module, the decls in the same modules with the parent
1657 // module should be visible to the decls in the implicit global module.
1658 if (Current->isImplicitGlobalModule())
1659 Current = Current->getTopLevelModule();
1660 if (M->isImplicitGlobalModule())
1661 M = M->getTopLevelModule();
1662
1663 // If M is the module we're parsing or M and the current module unit lives in
1664 // the same module, M should be usable.
1665 //
1666 // Note: It should be fine to search the vector `ModuleScopes` linearly since
1667 // it should be generally small enough. There should be rare module fragments
1668 // in a named module unit.
1669 if (llvm::count_if(ModuleScopes,
1670 [&M](const ModuleScope &MS) { return MS.Module == M; }) ||
1671 getASTContext().isInSameModule(M, Current)) {
1672 UsableModuleUnitsCache.insert(M);
1673 return true;
1674 }
1675
1676 return false;
1677}
1678
1680 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1681 if (isModuleVisible(Merged))
1682 return true;
1683 return false;
1684}
1685
1687 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1688 if (isUsableModule(Merged))
1689 return true;
1690 return false;
1691}
1692
1693template <typename ParmDecl>
1694static bool
1697 Sema::AcceptableKind Kind) {
1698 if (!D->hasDefaultArgument())
1699 return false;
1700
1702 while (D && Visited.insert(D).second) {
1703 auto &DefaultArg = D->getDefaultArgStorage();
1704 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
1705 return true;
1706
1707 if (!DefaultArg.isInherited() && Modules) {
1708 auto *NonConstD = const_cast<ParmDecl*>(D);
1709 Modules->push_back(S.getOwningModule(NonConstD));
1710 }
1711
1712 // If there was a previous default argument, maybe its parameter is
1713 // acceptable.
1714 D = DefaultArg.getInheritedFrom();
1715 }
1716 return false;
1717}
1718
1720 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,
1721 Sema::AcceptableKind Kind) {
1722 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1723 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1724
1725 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1726 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1727
1728 return ::hasAcceptableDefaultArgument(
1729 *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
1730}
1731
1737
1743
1744template <typename Filter>
1745static bool
1747 llvm::SmallVectorImpl<Module *> *Modules, Filter F,
1748 Sema::AcceptableKind Kind) {
1749 bool HasFilteredRedecls = false;
1750
1751 for (auto *Redecl : D->redecls()) {
1752 auto *R = cast<NamedDecl>(Redecl);
1753 if (!F(R))
1754 continue;
1755
1756 if (S.isAcceptable(R, Kind))
1757 return true;
1758
1759 HasFilteredRedecls = true;
1760
1761 if (Modules)
1762 Modules->push_back(R->getOwningModule());
1763 }
1764
1765 // Only return false if there is at least one redecl that is not filtered out.
1766 if (HasFilteredRedecls)
1767 return false;
1768
1769 return true;
1770}
1771
1772static bool
1775 Sema::AcceptableKind Kind) {
1777 S, D, Modules,
1778 [](const NamedDecl *D) {
1779 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1780 return RD->getTemplateSpecializationKind() ==
1782 if (auto *FD = dyn_cast<FunctionDecl>(D))
1783 return FD->getTemplateSpecializationKind() ==
1785 if (auto *VD = dyn_cast<VarDecl>(D))
1786 return VD->getTemplateSpecializationKind() ==
1788 llvm_unreachable("unknown explicit specialization kind");
1789 },
1790 Kind);
1791}
1792
1794 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1795 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1797}
1798
1800 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1801 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1803}
1804
1805static bool
1808 Sema::AcceptableKind Kind) {
1809 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1810 "not a member specialization");
1812 S, D, Modules,
1813 [](const NamedDecl *D) {
1814 // If the specialization is declared at namespace scope, then it's a
1815 // member specialization declaration. If it's lexically inside the class
1816 // definition then it was instantiated.
1817 //
1818 // FIXME: This is a hack. There should be a better way to determine
1819 // this.
1820 // FIXME: What about MS-style explicit specializations declared within a
1821 // class definition?
1822 return D->getLexicalDeclContext()->isFileContext();
1823 },
1824 Kind);
1825}
1826
1832
1838
1839/// Determine whether a declaration is acceptable to name lookup.
1840///
1841/// This routine determines whether the declaration D is acceptable in the
1842/// current lookup context, taking into account the current template
1843/// instantiation stack. During template instantiation, a declaration is
1844/// acceptable if it is acceptable from a module containing any entity on the
1845/// template instantiation path (by instantiating a template, you allow it to
1846/// see the declarations that your module can see, including those later on in
1847/// your module).
1848bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
1849 Sema::AcceptableKind Kind) {
1850 assert(!D->isUnconditionallyVisible() &&
1851 "should not call this: not in slow case");
1852
1853 Module *DeclModule = SemaRef.getOwningModule(D);
1854 assert(DeclModule && "hidden decl has no owning module");
1855
1856 // If the owning module is visible, the decl is acceptable.
1857 if (SemaRef.isModuleVisible(DeclModule,
1859 return true;
1860
1861 // Determine whether a decl context is a file context for the purpose of
1862 // visibility/reachability. This looks through some (export and linkage spec)
1863 // transparent contexts, but not others (enums).
1864 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1865 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1866 isa<ExportDecl>(DC);
1867 };
1868
1869 // If this declaration is not at namespace scope
1870 // then it is acceptable if its lexical parent has a acceptable definition.
1872 if (DC && !IsEffectivelyFileContext(DC)) {
1873 // For a parameter, check whether our current template declaration's
1874 // lexical context is acceptable, not whether there's some other acceptable
1875 // definition of it, because parameters aren't "within" the definition.
1876 //
1877 // In C++ we need to check for a acceptable definition due to ODR merging,
1878 // and in C we must not because each declaration of a function gets its own
1879 // set of declarations for tags in prototype scope.
1880 bool AcceptableWithinParent;
1881 if (D->isTemplateParameter()) {
1882 bool SearchDefinitions = true;
1883 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1884 if (const auto *TD = DCD->getDescribedTemplate()) {
1885 TemplateParameterList *TPL = TD->getTemplateParameters();
1886 auto Index = getDepthAndIndex(D).second;
1887 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1888 }
1889 }
1890 if (SearchDefinitions)
1891 AcceptableWithinParent =
1892 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1893 else
1894 AcceptableWithinParent =
1895 isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1896 } else if (isa<ParmVarDecl>(D) ||
1897 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1898 AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1899 else if (D->isModulePrivate()) {
1900 // A module-private declaration is only acceptable if an enclosing lexical
1901 // parent was merged with another definition in the current module.
1902 AcceptableWithinParent = false;
1903 do {
1905 AcceptableWithinParent = true;
1906 break;
1907 }
1908 DC = DC->getLexicalParent();
1909 } while (!IsEffectivelyFileContext(DC));
1910 } else {
1911 AcceptableWithinParent =
1912 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1913 }
1914
1915 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1917 // FIXME: Do something better in this case.
1918 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1919 // Cache the fact that this declaration is implicitly visible because
1920 // its parent has a visible definition.
1922 }
1923 return AcceptableWithinParent;
1924 }
1925
1927 return false;
1928
1929 assert(Kind == Sema::AcceptableKind::Reachable &&
1930 "Additional Sema::AcceptableKind?");
1931 return isReachableSlow(SemaRef, D);
1932}
1933
1934bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1935 // The module might be ordinarily visible. For a module-private query, that
1936 // means it is part of the current module.
1937 if (ModulePrivate && isUsableModule(M))
1938 return true;
1939
1940 // For a query which is not module-private, that means it is in our visible
1941 // module set.
1942 if (!ModulePrivate && VisibleModules.isVisible(M))
1943 return true;
1944
1945 // Otherwise, it might be visible by virtue of the query being within a
1946 // template instantiation or similar that is permitted to look inside M.
1947
1948 // Find the extra places where we need to look.
1949 const auto &LookupModules = getLookupModules();
1950 if (LookupModules.empty())
1951 return false;
1952
1953 // If our lookup set contains the module, it's visible.
1954 if (LookupModules.count(M))
1955 return true;
1956
1957 // The global module fragments are visible to its corresponding module unit.
1958 // So the global module fragment should be visible if the its corresponding
1959 // module unit is visible.
1960 if (M->isGlobalModule() && LookupModules.count(M->getTopLevelModule()))
1961 return true;
1962
1963 // For a module-private query, that's everywhere we get to look.
1964 if (ModulePrivate)
1965 return false;
1966
1967 // Check whether M is transitively exported to an import of the lookup set.
1968 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1969 return LookupM->isModuleVisible(M);
1970 });
1971}
1972
1973// FIXME: Return false directly if we don't have an interface dependency on the
1974// translation unit containing D.
1975bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
1976 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
1977
1978 Module *DeclModule = SemaRef.getOwningModule(D);
1979 assert(DeclModule && "hidden decl has no owning module");
1980
1981 // Entities in header like modules are reachable only if they're visible.
1982 if (DeclModule->isHeaderLikeModule())
1983 return false;
1984
1985 if (!D->isInAnotherModuleUnit())
1986 return true;
1987
1988 // [module.reach]/p3:
1989 // A declaration D is reachable from a point P if:
1990 // ...
1991 // - D is not discarded ([module.global.frag]), appears in a translation unit
1992 // that is reachable from P, and does not appear within a private module
1993 // fragment.
1994 //
1995 // A declaration that's discarded in the GMF should be module-private.
1996 if (D->isModulePrivate())
1997 return false;
1998
1999 Module *DeclTopModule = DeclModule->getTopLevelModule();
2000
2001 // [module.reach]/p1
2002 // A translation unit U is necessarily reachable from a point P if U is a
2003 // module interface unit on which the translation unit containing P has an
2004 // interface dependency, or the translation unit containing P imports U, in
2005 // either case prior to P ([module.import]).
2006 //
2007 // [module.import]/p10
2008 // A translation unit has an interface dependency on a translation unit U if
2009 // it contains a declaration (possibly a module-declaration) that imports U
2010 // or if it has an interface dependency on a translation unit that has an
2011 // interface dependency on U.
2012 //
2013 // So we could conclude the module unit U is necessarily reachable if:
2014 // (1) The module unit U is module interface unit.
2015 // (2) The current unit has an interface dependency on the module unit U.
2016 //
2017 // Here we only check for the first condition. Since we couldn't see
2018 // DeclModule if it isn't (transitively) imported.
2019 if (DeclTopModule->isModuleInterfaceUnit())
2020 return true;
2021
2022 // [module.reach]/p1,2
2023 // A translation unit U is necessarily reachable from a point P if U is a
2024 // module interface unit on which the translation unit containing P has an
2025 // interface dependency, or the translation unit containing P imports U, in
2026 // either case prior to P
2027 //
2028 // Additional translation units on
2029 // which the point within the program has an interface dependency may be
2030 // considered reachable, but it is unspecified which are and under what
2031 // circumstances.
2032 Module *CurrentM = SemaRef.getCurrentModule();
2033
2034 // Directly imported module are necessarily reachable.
2035 // Since we can't export import a module implementation partition unit, we
2036 // don't need to count for Exports here.
2037 if (CurrentM &&
2038 llvm::is_contained(CurrentM->getTopLevelModule()->Imports, DeclTopModule))
2039 return true;
2040
2041 // Then we treat all module implementation partition unit as unreachable.
2042 return false;
2043}
2044
2045bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
2046 return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);
2047}
2048
2049bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
2050 // FIXME: If there are both visible and hidden declarations, we need to take
2051 // into account whether redeclaration is possible. Example:
2052 //
2053 // Non-imported module:
2054 // int f(T); // #1
2055 // Some TU:
2056 // static int f(U); // #2, not a redeclaration of #1
2057 // int f(T); // #3, finds both, should link with #1 if T != U, but
2058 // // with #2 if T == U; neither should be ambiguous.
2059 for (auto *D : R) {
2060 if (isVisible(D))
2061 return true;
2062 assert(D->isExternallyDeclarable() &&
2063 "should not have hidden, non-externally-declarable result here");
2064 }
2065
2066 // This function is called once "New" is essentially complete, but before a
2067 // previous declaration is attached. We can't query the linkage of "New" in
2068 // general, because attaching the previous declaration can change the
2069 // linkage of New to match the previous declaration.
2070 //
2071 // However, because we've just determined that there is no *visible* prior
2072 // declaration, we can compute the linkage here. There are two possibilities:
2073 //
2074 // * This is not a redeclaration; it's safe to compute the linkage now.
2075 //
2076 // * This is a redeclaration of a prior declaration that is externally
2077 // redeclarable. In that case, the linkage of the declaration is not
2078 // changed by attaching the prior declaration, because both are externally
2079 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
2080 //
2081 // FIXME: This is subtle and fragile.
2082 return New->isExternallyDeclarable();
2083}
2084
2085/// Retrieve the visible declaration corresponding to D, if any.
2086///
2087/// This routine determines whether the declaration D is visible in the current
2088/// module, with the current imports. If not, it checks whether any
2089/// redeclaration of D is visible, and if so, returns that declaration.
2090///
2091/// \returns D, or a visible previous declaration of D, whichever is more recent
2092/// and visible. If no declaration of D is visible, returns null.
2094 unsigned IDNS) {
2095 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
2096
2097 for (auto *RD : D->redecls()) {
2098 // Don't bother with extra checks if we already know this one isn't visible.
2099 if (RD == D)
2100 continue;
2101
2102 auto ND = cast<NamedDecl>(RD);
2103 // FIXME: This is wrong in the case where the previous declaration is not
2104 // visible in the same scope as D. This needs to be done much more
2105 // carefully.
2106 if (ND->isInIdentifierNamespace(IDNS) &&
2108 return ND;
2109 }
2110
2111 return nullptr;
2112}
2113
2116 assert(!isVisible(D) && "not in slow case");
2118 *this, D, Modules, [](const NamedDecl *) { return true; },
2120}
2121
2123 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
2124 assert(!isReachable(D) && "not in slow case");
2126 *this, D, Modules, [](const NamedDecl *) { return true; },
2128}
2129
2130NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
2131 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
2132 // Namespaces are a bit of a special case: we expect there to be a lot of
2133 // redeclarations of some namespaces, all declarations of a namespace are
2134 // essentially interchangeable, all declarations are found by name lookup
2135 // if any is, and namespaces are never looked up during template
2136 // instantiation. So we benefit from caching the check in this case, and
2137 // it is correct to do so.
2138 auto *Key = ND->getCanonicalDecl();
2139 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
2140 return Acceptable;
2141 auto *Acceptable = isVisible(getSema(), Key)
2142 ? Key
2143 : findAcceptableDecl(getSema(), Key, IDNS);
2144 if (Acceptable)
2145 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
2146 return Acceptable;
2147 }
2148
2149 return findAcceptableDecl(getSema(), D, IDNS);
2150}
2151
2153 // If this declaration is already visible, return it directly.
2154 if (D->isUnconditionallyVisible())
2155 return true;
2156
2157 // During template instantiation, we can refer to hidden declarations, if
2158 // they were visible in any module along the path of instantiation.
2159 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);
2160}
2161
2163 if (D->isUnconditionallyVisible())
2164 return true;
2165
2166 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);
2167}
2168
2170 // We should check the visibility at the callsite already.
2171 if (isVisible(SemaRef, ND))
2172 return true;
2173
2174 // Deduction guide lives in namespace scope generally, but it is just a
2175 // hint to the compilers. What we actually lookup for is the generated member
2176 // of the corresponding template. So it is sufficient to check the
2177 // reachability of the template decl.
2178 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())
2179 return SemaRef.hasReachableDefinition(DeductionGuide);
2180
2181 // FIXME: The lookup for allocation function is a standalone process.
2182 // (We can find the logics in Sema::FindAllocationFunctions)
2183 //
2184 // Such structure makes it a problem when we instantiate a template
2185 // declaration using placement allocation function if the placement
2186 // allocation function is invisible.
2187 // (See https://github.com/llvm/llvm-project/issues/59601)
2188 //
2189 // Here we workaround it by making the placement allocation functions
2190 // always acceptable. The downside is that we can't diagnose the direct
2191 // use of the invisible placement allocation functions. (Although such uses
2192 // should be rare).
2193 if (auto *FD = dyn_cast<FunctionDecl>(ND);
2194 FD && FD->isReservedGlobalPlacementOperator())
2195 return true;
2196
2197 auto *DC = ND->getDeclContext();
2198 // If ND is not visible and it is at namespace scope, it shouldn't be found
2199 // by name lookup.
2200 if (DC->isFileContext())
2201 return false;
2202
2203 // [module.interface]p7
2204 // Class and enumeration member names can be found by name lookup in any
2205 // context in which a definition of the type is reachable.
2206 //
2207 // NOTE: The above wording may be problematic. See
2208 // https://github.com/llvm/llvm-project/issues/131058 But it is much complext
2209 // to adjust it in Sema's lookup process. Now we hacked it in ASTWriter. See
2210 // the comments in ASTDeclContextNameLookupTrait::getLookupVisibility.
2211 if (auto *TD = dyn_cast<TagDecl>(DC))
2212 return SemaRef.hasReachableDefinition(TD);
2213
2214 return false;
2215}
2216
2217bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
2218 bool ForceNoCPlusPlus) {
2219 DeclarationName Name = R.getLookupName();
2220 if (!Name) return false;
2221
2222 LookupNameKind NameKind = R.getLookupKind();
2223
2224 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
2225 // Unqualified name lookup in C/Objective-C is purely lexical, so
2226 // search in the declarations attached to the name.
2227 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
2228 // Find the nearest non-transparent declaration scope.
2229 while (!(S->getFlags() & Scope::DeclScope) ||
2230 (S->getEntity() && S->getEntity()->isTransparentContext()))
2231 S = S->getParent();
2232 }
2233
2234 // When performing a scope lookup, we want to find local extern decls.
2235 FindLocalExternScope FindLocals(R);
2236
2237 // Scan up the scope chain looking for a decl that matches this
2238 // identifier that is in the appropriate namespace. This search
2239 // should not take long, as shadowing of names is uncommon, and
2240 // deep shadowing is extremely uncommon.
2241 bool LeftStartingScope = false;
2242
2243 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2244 IEnd = IdResolver.end();
2245 I != IEnd; ++I)
2246 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
2247 if (NameKind == LookupRedeclarationWithLinkage) {
2248 // Determine whether this (or a previous) declaration is
2249 // out-of-scope.
2250 if (!LeftStartingScope && !S->isDeclScope(*I))
2251 LeftStartingScope = true;
2252
2253 // If we found something outside of our starting scope that
2254 // does not have linkage, skip it.
2255 if (LeftStartingScope && !((*I)->hasLinkage())) {
2256 R.setShadowed();
2257 continue;
2258 }
2259 }
2260 else if (NameKind == LookupObjCImplicitSelfParam &&
2262 continue;
2263
2264 R.addDecl(D);
2265
2266 // Check whether there are any other declarations with the same name
2267 // and in the same scope.
2268 if (I != IEnd) {
2269 // Find the scope in which this declaration was declared (if it
2270 // actually exists in a Scope).
2271 while (S && !S->isDeclScope(D))
2272 S = S->getParent();
2273
2274 // If the scope containing the declaration is the translation unit,
2275 // then we'll need to perform our checks based on the matching
2276 // DeclContexts rather than matching scopes.
2278 S = nullptr;
2279
2280 // Compute the DeclContext, if we need it.
2281 DeclContext *DC = nullptr;
2282 if (!S)
2283 DC = (*I)->getDeclContext()->getRedeclContext();
2284
2286 for (++LastI; LastI != IEnd; ++LastI) {
2287 if (S) {
2288 // Match based on scope.
2289 if (!S->isDeclScope(*LastI))
2290 break;
2291 } else {
2292 // Match based on DeclContext.
2293 DeclContext *LastDC
2294 = (*LastI)->getDeclContext()->getRedeclContext();
2295 if (!LastDC->Equals(DC))
2296 break;
2297 }
2298
2299 // If the declaration is in the right namespace and visible, add it.
2300 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
2301 R.addDecl(LastD);
2302 }
2303
2304 R.resolveKind();
2305 }
2306
2307 return true;
2308 }
2309 } else {
2310 // Perform C++ unqualified name lookup.
2311 if (CppLookupName(R, S))
2312 return true;
2313 }
2314
2315 // If we didn't find a use of this identifier, and if the identifier
2316 // corresponds to a compiler builtin, create the decl object for the builtin
2317 // now, injecting it into translation unit scope, and return it.
2318 if (AllowBuiltinCreation && LookupBuiltin(R))
2319 return true;
2320
2321 // If we didn't find a use of this identifier, the ExternalSource
2322 // may be able to handle the situation.
2323 // Note: some lookup failures are expected!
2324 // See e.g. R.isForRedeclaration().
2325 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2326}
2327
2328/// Perform qualified name lookup in the namespaces nominated by
2329/// using directives by the given context.
2330///
2331/// C++98 [namespace.qual]p2:
2332/// Given X::m (where X is a user-declared namespace), or given \::m
2333/// (where X is the global namespace), let S be the set of all
2334/// declarations of m in X and in the transitive closure of all
2335/// namespaces nominated by using-directives in X and its used
2336/// namespaces, except that using-directives are ignored in any
2337/// namespace, including X, directly containing one or more
2338/// declarations of m. No namespace is searched more than once in
2339/// the lookup of a name. If S is the empty set, the program is
2340/// ill-formed. Otherwise, if S has exactly one member, or if the
2341/// context of the reference is a using-declaration
2342/// (namespace.udecl), S is the required set of declarations of
2343/// m. Otherwise if the use of m is not one that allows a unique
2344/// declaration to be chosen from S, the program is ill-formed.
2345///
2346/// C++98 [namespace.qual]p5:
2347/// During the lookup of a qualified namespace member name, if the
2348/// lookup finds more than one declaration of the member, and if one
2349/// declaration introduces a class name or enumeration name and the
2350/// other declarations either introduce the same object, the same
2351/// enumerator or a set of functions, the non-type name hides the
2352/// class or enumeration name if and only if the declarations are
2353/// from the same namespace; otherwise (the declarations are from
2354/// different namespaces), the program is ill-formed.
2356 DeclContext *StartDC) {
2357 assert(StartDC->isFileContext() && "start context is not a file context");
2358
2359 // We have not yet looked into these namespaces, much less added
2360 // their "using-children" to the queue.
2362
2363 // We have at least added all these contexts to the queue.
2365 Visited.insert(StartDC);
2366
2367 // We have already looked into the initial namespace; seed the queue
2368 // with its using-children.
2369 for (auto *I : StartDC->using_directives()) {
2370 NamespaceDecl *ND = I->getNominatedNamespace()->getFirstDecl();
2371 if (S.isVisible(I) && Visited.insert(ND).second)
2372 Queue.push_back(ND);
2373 }
2374
2375 // The easiest way to implement the restriction in [namespace.qual]p5
2376 // is to check whether any of the individual results found a tag
2377 // and, if so, to declare an ambiguity if the final result is not
2378 // a tag.
2379 bool FoundTag = false;
2380 bool FoundNonTag = false;
2381
2383
2384 bool Found = false;
2385 while (!Queue.empty()) {
2386 NamespaceDecl *ND = Queue.pop_back_val();
2387
2388 // We go through some convolutions here to avoid copying results
2389 // between LookupResults.
2390 bool UseLocal = !R.empty();
2391 LookupResult &DirectR = UseLocal ? LocalR : R;
2392 bool FoundDirect = LookupDirect(S, DirectR, ND);
2393
2394 if (FoundDirect) {
2395 // First do any local hiding.
2396 DirectR.resolveKind();
2397
2398 // If the local result is a tag, remember that.
2399 if (DirectR.isSingleTagDecl())
2400 FoundTag = true;
2401 else
2402 FoundNonTag = true;
2403
2404 // Append the local results to the total results if necessary.
2405 if (UseLocal) {
2406 R.addAllDecls(LocalR);
2407 LocalR.clear();
2408 }
2409 }
2410
2411 // If we find names in this namespace, ignore its using directives.
2412 if (FoundDirect) {
2413 Found = true;
2414 continue;
2415 }
2416
2417 for (auto *I : ND->using_directives()) {
2418 NamespaceDecl *Nom = I->getNominatedNamespace();
2419 if (S.isVisible(I) && Visited.insert(Nom).second)
2420 Queue.push_back(Nom);
2421 }
2422 }
2423
2424 if (Found) {
2425 if (FoundTag && FoundNonTag)
2426 R.setAmbiguousQualifiedTagHiding();
2427 else
2428 R.resolveKind();
2429 }
2430
2431 return Found;
2432}
2433
2435 bool InUnqualifiedLookup) {
2436 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2437
2438 if (!R.getLookupName())
2439 return false;
2440
2441#ifndef NDEBUG
2442 // Make sure that the declaration context is complete.
2443 if (const auto *TD = dyn_cast<TagDecl>(LookupCtx);
2444 TD && !TD->isDependentType() && TD->getDefinition() == nullptr)
2445 llvm_unreachable("Declaration context must already be complete!");
2446#endif
2447
2448 struct QualifiedLookupInScope {
2449 bool oldVal;
2451 // Set flag in DeclContext informing debugger that we're looking for qualified name
2452 QualifiedLookupInScope(DeclContext *ctx)
2453 : oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) {
2454 ctx->setUseQualifiedLookup();
2455 }
2456 ~QualifiedLookupInScope() {
2457 Context->setUseQualifiedLookup(oldVal);
2458 }
2459 } QL(LookupCtx);
2460
2461 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2462 // FIXME: Per [temp.dep.general]p2, an unqualified name is also dependent
2463 // if it's a dependent conversion-function-id or operator= where the current
2464 // class is a templated entity. This should be handled in LookupName.
2465 if (!InUnqualifiedLookup && !R.isForRedeclaration()) {
2466 // C++23 [temp.dep.type]p5:
2467 // A qualified name is dependent if
2468 // - it is a conversion-function-id whose conversion-type-id
2469 // is dependent, or
2470 // - [...]
2471 // - its lookup context is the current instantiation and it
2472 // is operator=, or
2473 // - [...]
2474 if (DeclarationName Name = R.getLookupName();
2476 Name.getCXXNameType()->isDependentType()) {
2477 R.setNotFoundInCurrentInstantiation();
2478 return false;
2479 }
2480 }
2481
2482 if (LookupDirect(*this, R, LookupCtx)) {
2483 R.resolveKind();
2484 if (LookupRec)
2485 R.setNamingClass(LookupRec);
2486 return true;
2487 }
2488
2489 // Don't descend into implied contexts for redeclarations.
2490 // C++98 [namespace.qual]p6:
2491 // In a declaration for a namespace member in which the
2492 // declarator-id is a qualified-id, given that the qualified-id
2493 // for the namespace member has the form
2494 // nested-name-specifier unqualified-id
2495 // the unqualified-id shall name a member of the namespace
2496 // designated by the nested-name-specifier.
2497 // See also [class.mfct]p5 and [class.static.data]p2.
2498 if (R.isForRedeclaration())
2499 return false;
2500
2501 // If this is a namespace, look it up in the implied namespaces.
2502 if (LookupCtx->isFileContext())
2503 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2504
2505 // If this isn't a C++ class, we aren't allowed to look into base
2506 // classes, we're done.
2507 if (!LookupRec || !LookupRec->getDefinition())
2508 return false;
2509
2510 // We're done for lookups that can never succeed for C++ classes.
2511 if (R.getLookupKind() == LookupOperatorName ||
2512 R.getLookupKind() == LookupNamespaceName ||
2513 R.getLookupKind() == LookupObjCProtocolName ||
2514 R.getLookupKind() == LookupLabel)
2515 return false;
2516
2517 // If we're performing qualified name lookup into a dependent class,
2518 // then we are actually looking into a current instantiation. If we have any
2519 // dependent base classes, then we either have to delay lookup until
2520 // template instantiation time (at which point all bases will be available)
2521 // or we have to fail.
2522 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2523 LookupRec->hasAnyDependentBases()) {
2524 R.setNotFoundInCurrentInstantiation();
2525 return false;
2526 }
2527
2528 // Perform lookup into our base classes.
2529
2530 DeclarationName Name = R.getLookupName();
2531 unsigned IDNS = R.getIdentifierNamespace();
2532
2533 // Look for this member in our base classes.
2534 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2535 CXXBasePath &Path) -> bool {
2536 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2537 // Drop leading non-matching lookup results from the declaration list so
2538 // we don't need to consider them again below.
2539 for (Path.Decls = BaseRecord->lookup(Name).begin();
2540 Path.Decls != Path.Decls.end(); ++Path.Decls) {
2541 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2542 return true;
2543 }
2544 return false;
2545 };
2546
2547 CXXBasePaths Paths;
2548 Paths.setOrigin(LookupRec);
2549 if (!LookupRec->lookupInBases(BaseCallback, Paths))
2550 return false;
2551
2552 R.setNamingClass(LookupRec);
2553
2554 // C++ [class.member.lookup]p2:
2555 // [...] If the resulting set of declarations are not all from
2556 // sub-objects of the same type, or the set has a nonstatic member
2557 // and includes members from distinct sub-objects, there is an
2558 // ambiguity and the program is ill-formed. Otherwise that set is
2559 // the result of the lookup.
2560 QualType SubobjectType;
2561 int SubobjectNumber = 0;
2562 AccessSpecifier SubobjectAccess = AS_none;
2563
2564 // Check whether the given lookup result contains only static members.
2565 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2566 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2567 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2568 return false;
2569 return true;
2570 };
2571
2572 bool TemplateNameLookup = R.isTemplateNameLookup();
2573
2574 // Determine whether two sets of members contain the same members, as
2575 // required by C++ [class.member.lookup]p6.
2576 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2578 using Iterator = DeclContextLookupResult::iterator;
2579 using Result = const void *;
2580
2581 auto Next = [&](Iterator &It, Iterator End) -> Result {
2582 while (It != End) {
2583 NamedDecl *ND = *It++;
2584 if (!ND->isInIdentifierNamespace(IDNS))
2585 continue;
2586
2587 // C++ [temp.local]p3:
2588 // A lookup that finds an injected-class-name (10.2) can result in
2589 // an ambiguity in certain cases (for example, if it is found in
2590 // more than one base class). If all of the injected-class-names
2591 // that are found refer to specializations of the same class
2592 // template, and if the name is used as a template-name, the
2593 // reference refers to the class template itself and not a
2594 // specialization thereof, and is not ambiguous.
2595 if (TemplateNameLookup)
2596 if (auto *TD = getAsTemplateNameDecl(ND))
2597 ND = TD;
2598
2599 // C++ [class.member.lookup]p3:
2600 // type declarations (including injected-class-names) are replaced by
2601 // the types they designate
2602 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl()))
2603 return Context.getCanonicalTypeDeclType(TD).getAsOpaquePtr();
2604
2605 return ND->getUnderlyingDecl()->getCanonicalDecl();
2606 }
2607 return nullptr;
2608 };
2609
2610 // We'll often find the declarations are in the same order. Handle this
2611 // case (and the special case of only one declaration) efficiently.
2612 Iterator AIt = A, BIt = B, AEnd, BEnd;
2613 while (true) {
2614 Result AResult = Next(AIt, AEnd);
2615 Result BResult = Next(BIt, BEnd);
2616 if (!AResult && !BResult)
2617 return true;
2618 if (!AResult || !BResult)
2619 return false;
2620 if (AResult != BResult) {
2621 // Found a mismatch; carefully check both lists, accounting for the
2622 // possibility of declarations appearing more than once.
2623 llvm::SmallDenseMap<Result, bool, 32> AResults;
2624 for (; AResult; AResult = Next(AIt, AEnd))
2625 AResults.insert({AResult, /*FoundInB*/false});
2626 unsigned Found = 0;
2627 for (; BResult; BResult = Next(BIt, BEnd)) {
2628 auto It = AResults.find(BResult);
2629 if (It == AResults.end())
2630 return false;
2631 if (!It->second) {
2632 It->second = true;
2633 ++Found;
2634 }
2635 }
2636 return AResults.size() == Found;
2637 }
2638 }
2639 };
2640
2641 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2642 Path != PathEnd; ++Path) {
2643 const CXXBasePathElement &PathElement = Path->back();
2644
2645 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2646 // across all paths.
2647 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2648
2649 // Determine whether we're looking at a distinct sub-object or not.
2650 if (SubobjectType.isNull()) {
2651 // This is the first subobject we've looked at. Record its type.
2652 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2653 SubobjectNumber = PathElement.SubobjectNumber;
2654 continue;
2655 }
2656
2657 if (SubobjectType !=
2658 Context.getCanonicalType(PathElement.Base->getType())) {
2659 // We found members of the given name in two subobjects of
2660 // different types. If the declaration sets aren't the same, this
2661 // lookup is ambiguous.
2662 //
2663 // FIXME: The language rule says that this applies irrespective of
2664 // whether the sets contain only static members.
2665 if (HasOnlyStaticMembers(Path->Decls) &&
2666 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2667 continue;
2668
2669 R.setAmbiguousBaseSubobjectTypes(Paths);
2670 return true;
2671 }
2672
2673 // FIXME: This language rule no longer exists. Checking for ambiguous base
2674 // subobjects should be done as part of formation of a class member access
2675 // expression (when converting the object parameter to the member's type).
2676 if (SubobjectNumber != PathElement.SubobjectNumber) {
2677 // We have a different subobject of the same type.
2678
2679 // C++ [class.member.lookup]p5:
2680 // A static member, a nested type or an enumerator defined in
2681 // a base class T can unambiguously be found even if an object
2682 // has more than one base class subobject of type T.
2683 if (HasOnlyStaticMembers(Path->Decls))
2684 continue;
2685
2686 // We have found a nonstatic member name in multiple, distinct
2687 // subobjects. Name lookup is ambiguous.
2688 R.setAmbiguousBaseSubobjects(Paths);
2689 return true;
2690 }
2691 }
2692
2693 // Lookup in a base class succeeded; return these results.
2694
2695 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2696 I != E; ++I) {
2697 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2698 (*I)->getAccess());
2699 if (NamedDecl *ND = R.getAcceptableDecl(*I))
2700 R.addDecl(ND, AS);
2701 }
2702 R.resolveKind();
2703 return true;
2704}
2705
2707 CXXScopeSpec &SS) {
2708 NestedNameSpecifier Qualifier = SS.getScopeRep();
2709 if (Qualifier.getKind() == NestedNameSpecifier::Kind::MicrosoftSuper)
2710 return LookupInSuper(R, Qualifier.getAsMicrosoftSuper());
2711 return LookupQualifiedName(R, LookupCtx);
2712}
2713
2715 QualType ObjectType, bool AllowBuiltinCreation,
2716 bool EnteringContext) {
2717 // When the scope specifier is invalid, don't even look for anything.
2718 if (SS && SS->isInvalid())
2719 return false;
2720
2721 // Determine where to perform name lookup
2722 DeclContext *DC = nullptr;
2723 bool IsDependent = false;
2724 if (!ObjectType.isNull()) {
2725 // This nested-name-specifier occurs in a member access expression, e.g.,
2726 // x->B::f, and we are looking into the type of the object.
2727 assert((!SS || SS->isEmpty()) &&
2728 "ObjectType and scope specifier cannot coexist");
2729 DC = computeDeclContext(ObjectType);
2730 IsDependent = !DC && ObjectType->isDependentType();
2731 assert(((!DC && ObjectType->isDependentType()) ||
2732 !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() ||
2733 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
2734 "Caller should have completed object type");
2735 } else if (SS && SS->isNotEmpty()) {
2736 // This nested-name-specifier occurs after another nested-name-specifier,
2737 // so long into the context associated with the prior nested-name-specifier.
2738 if ((DC = computeDeclContext(*SS, EnteringContext))) {
2739 // The declaration context must be complete.
2740 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2741 return false;
2742 R.setContextRange(SS->getRange());
2743 // FIXME: '__super' lookup semantics could be implemented by a
2744 // LookupResult::isSuperLookup flag which skips the initial search of
2745 // the lookup context in LookupQualified.
2746 if (NestedNameSpecifier Qualifier = SS->getScopeRep();
2747 Qualifier.getKind() == NestedNameSpecifier::Kind::MicrosoftSuper)
2748 return LookupInSuper(R, Qualifier.getAsMicrosoftSuper());
2749 }
2750 IsDependent = !DC && isDependentScopeSpecifier(*SS);
2751 } else {
2752 // Perform unqualified name lookup starting in the given scope.
2753 return LookupName(R, S, AllowBuiltinCreation);
2754 }
2755
2756 // If we were able to compute a declaration context, perform qualified name
2757 // lookup in that context.
2758 if (DC)
2759 return LookupQualifiedName(R, DC);
2760 else if (IsDependent)
2761 // We could not resolve the scope specified to a specific declaration
2762 // context, which means that SS refers to an unknown specialization.
2763 // Name lookup can't find anything in this case.
2764 R.setNotFoundInCurrentInstantiation();
2765 return false;
2766}
2767
2769 // The access-control rules we use here are essentially the rules for
2770 // doing a lookup in Class that just magically skipped the direct
2771 // members of Class itself. That is, the naming class is Class, and the
2772 // access includes the access of the base.
2773 for (const auto &BaseSpec : Class->bases()) {
2774 auto *RD = BaseSpec.getType()->castAsCXXRecordDecl();
2775 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2776 Result.setBaseObjectType(Context.getCanonicalTagType(Class));
2778
2779 // Copy the lookup results into the target, merging the base's access into
2780 // the path access.
2781 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2782 R.addDecl(I.getDecl(),
2783 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2784 I.getAccess()));
2785 }
2786
2787 Result.suppressDiagnostics();
2788 }
2789
2790 R.resolveKind();
2791 R.setNamingClass(Class);
2792
2793 return !R.empty();
2794}
2795
2797 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2798
2799 DeclarationName Name = Result.getLookupName();
2800 SourceLocation NameLoc = Result.getNameLoc();
2801 SourceRange LookupRange = Result.getContextRange();
2802
2803 switch (Result.getAmbiguityKind()) {
2805 CXXBasePaths *Paths = Result.getBasePaths();
2806 QualType SubobjectType = Paths->front().back().Base->getType();
2807 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2808 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2809 << LookupRange;
2810
2812 while (isa<CXXMethodDecl>(*Found) &&
2813 cast<CXXMethodDecl>(*Found)->isStatic())
2814 ++Found;
2815
2816 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2817 break;
2818 }
2819
2821 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2822 << Name << LookupRange;
2823
2824 CXXBasePaths *Paths = Result.getBasePaths();
2825 std::set<const NamedDecl *> DeclsPrinted;
2826 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2827 PathEnd = Paths->end();
2828 Path != PathEnd; ++Path) {
2829 const NamedDecl *D = *Path->Decls;
2830 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2831 continue;
2832 if (DeclsPrinted.insert(D).second) {
2833 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2834 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2835 << TD->getUnderlyingType();
2836 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2837 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2838 << Context.getTypeDeclType(TD);
2839 else
2840 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2841 }
2842 }
2843 break;
2844 }
2845
2847 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2848
2850
2851 for (auto *D : Result)
2852 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2853 TagDecls.insert(TD);
2854 Diag(TD->getLocation(), diag::note_hidden_tag);
2855 }
2856
2857 for (auto *D : Result)
2858 if (!isa<TagDecl>(D))
2859 Diag(D->getLocation(), diag::note_hiding_object);
2860
2861 // For recovery purposes, go ahead and implement the hiding.
2862 LookupResult::Filter F = Result.makeFilter();
2863 while (F.hasNext()) {
2864 if (TagDecls.count(F.next()))
2865 F.erase();
2866 }
2867 F.done();
2868 break;
2869 }
2870
2872 Diag(NameLoc, diag::err_using_placeholder_variable) << Name << LookupRange;
2873 DeclContext *DC = nullptr;
2874 for (auto *D : Result) {
2875 Diag(D->getLocation(), diag::note_reference_placeholder) << D;
2876 if (DC != nullptr && DC != D->getDeclContext())
2877 break;
2878 DC = D->getDeclContext();
2879 }
2880 break;
2881 }
2882
2884 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2885
2886 for (auto *D : Result)
2887 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2888 break;
2889 }
2890 }
2891}
2892
2893namespace {
2894 struct AssociatedLookup {
2895 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2896 Sema::AssociatedNamespaceSet &Namespaces,
2897 Sema::AssociatedClassSet &Classes)
2898 : S(S), Namespaces(Namespaces), Classes(Classes),
2899 InstantiationLoc(InstantiationLoc) {
2900 }
2901
2902 bool addClassTransitive(CXXRecordDecl *RD) {
2903 Classes.insert(RD);
2904 return ClassesTransitive.insert(RD);
2905 }
2906
2907 Sema &S;
2908 Sema::AssociatedNamespaceSet &Namespaces;
2909 Sema::AssociatedClassSet &Classes;
2910 SourceLocation InstantiationLoc;
2911
2912 private:
2913 Sema::AssociatedClassSet ClassesTransitive;
2914 };
2915} // end anonymous namespace
2916
2917static void
2919
2920// Given the declaration context \param Ctx of a class, class template or
2921// enumeration, add the associated namespaces to \param Namespaces as described
2922// in [basic.lookup.argdep]p2.
2924 DeclContext *Ctx) {
2925 // The exact wording has been changed in C++14 as a result of
2926 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2927 // to all language versions since it is possible to return a local type
2928 // from a lambda in C++11.
2929 //
2930 // C++14 [basic.lookup.argdep]p2:
2931 // If T is a class type [...]. Its associated namespaces are the innermost
2932 // enclosing namespaces of its associated classes. [...]
2933 //
2934 // If T is an enumeration type, its associated namespace is the innermost
2935 // enclosing namespace of its declaration. [...]
2936
2937 // We additionally skip inline namespaces. The innermost non-inline namespace
2938 // contains all names of all its nested inline namespaces anyway, so we can
2939 // replace the entire inline namespace tree with its root.
2940 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2941 Ctx = Ctx->getParent();
2942
2943 // Actually it is fine to always do `Namespaces.insert(Ctx);` simply. But it
2944 // may cause more allocations in Namespaces and more unnecessary lookups. So
2945 // we'd like to insert the representative namespace only.
2946 DeclContext *PrimaryCtx = Ctx->getPrimaryContext();
2947 Decl *PrimaryD = cast<Decl>(PrimaryCtx);
2948 Decl *D = cast<Decl>(Ctx);
2949 ASTContext &AST = D->getASTContext();
2950
2951 // TODO: Technically it is better to insert one namespace per module. e.g.,
2952 //
2953 // ```
2954 // //--- first.cppm
2955 // export module first;
2956 // namespace ns { ... } // first namespace
2957 //
2958 // //--- m-partA.cppm
2959 // export module m:partA;
2960 // import first;
2961 //
2962 // namespace ns { ... }
2963 // namespace ns { ... }
2964 //
2965 // //--- m-partB.cppm
2966 // export module m:partB;
2967 // import first;
2968 // import :partA;
2969 //
2970 // namespace ns { ... }
2971 // namespace ns { ... }
2972 //
2973 // ...
2974 //
2975 // //--- m-partN.cppm
2976 // export module m:partN;
2977 // import first;
2978 // import :partA;
2979 // ...
2980 // import :part$(N-1);
2981 //
2982 // namespace ns { ... }
2983 // namespace ns { ... }
2984 //
2985 // consume(ns::any_decl); // the lookup
2986 // ```
2987 //
2988 // We should only insert once for all namespaces in module m.
2989 if (D->isInNamedModule() &&
2990 !AST.isInSameModule(D->getOwningModule(), PrimaryD->getOwningModule()))
2991 Namespaces.insert(Ctx);
2992 else
2993 Namespaces.insert(PrimaryCtx);
2994}
2995
2996// Add the associated classes and namespaces for argument-dependent
2997// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2998static void
3000 const TemplateArgument &Arg) {
3001 // C++ [basic.lookup.argdep]p2, last bullet:
3002 // -- [...] ;
3003 switch (Arg.getKind()) {
3005 break;
3006
3008 // [...] the namespaces and classes associated with the types of the
3009 // template arguments provided for template type parameters (excluding
3010 // template template parameters)
3012 break;
3013
3016 // [...] the namespaces in which any template template arguments are
3017 // defined; and the classes in which any member templates used as
3018 // template template arguments are defined.
3020 if (ClassTemplateDecl *ClassTemplate
3021 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
3022 DeclContext *Ctx = ClassTemplate->getDeclContext();
3023 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3024 Result.Classes.insert(EnclosingClass);
3025 // Add the associated namespace for this class.
3026 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3027 }
3028 break;
3029 }
3030
3036 // [Note: non-type template arguments do not contribute to the set of
3037 // associated namespaces. ]
3038 break;
3039
3041 for (const auto &P : Arg.pack_elements())
3043 break;
3044 }
3045}
3046
3047// Add the associated classes and namespaces for argument-dependent lookup
3048// with an argument of class type (C++ [basic.lookup.argdep]p2).
3049static void
3051 CXXRecordDecl *Class) {
3052
3053 // Just silently ignore anything whose name is __va_list_tag.
3054 if (Class->getDeclName() == Result.S.VAListTagName)
3055 return;
3056
3057 // C++ [basic.lookup.argdep]p2:
3058 // [...]
3059 // -- If T is a class type (including unions), its associated
3060 // classes are: the class itself; the class of which it is a
3061 // member, if any; and its direct and indirect base classes.
3062 // Its associated namespaces are the innermost enclosing
3063 // namespaces of its associated classes.
3064
3065 // Add the class of which it is a member, if any.
3066 DeclContext *Ctx = Class->getDeclContext();
3067 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3068 Result.Classes.insert(EnclosingClass);
3069
3070 // Add the associated namespace for this class.
3071 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3072
3073 // -- If T is a template-id, its associated namespaces and classes are
3074 // the namespace in which the template is defined; for member
3075 // templates, the member template's class; the namespaces and classes
3076 // associated with the types of the template arguments provided for
3077 // template type parameters (excluding template template parameters); the
3078 // namespaces in which any template template arguments are defined; and
3079 // the classes in which any member templates used as template template
3080 // arguments are defined. [Note: non-type template arguments do not
3081 // contribute to the set of associated namespaces. ]
3083 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
3084 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
3085 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3086 Result.Classes.insert(EnclosingClass);
3087 // Add the associated namespace for this class.
3088 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3089
3090 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3091 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3092 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
3093 }
3094
3095 // Add the class itself. If we've already transitively visited this class,
3096 // we don't need to visit base classes.
3097 if (!Result.addClassTransitive(Class))
3098 return;
3099
3100 // Only recurse into base classes for complete types.
3101 if (!Result.S.isCompleteType(Result.InstantiationLoc,
3102 Result.S.Context.getCanonicalTagType(Class)))
3103 return;
3104
3105 // Add direct and indirect base classes along with their associated
3106 // namespaces.
3108 Bases.push_back(Class);
3109 while (!Bases.empty()) {
3110 // Pop this class off the stack.
3111 Class = Bases.pop_back_val();
3112
3113 // Visit the base classes.
3114 for (const auto &Base : Class->bases()) {
3115 CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3116 // In dependent contexts, we do ADL twice, and the first time around,
3117 // the base type might be a dependent TemplateSpecializationType, or a
3118 // TemplateTypeParmType. If that happens, simply ignore it.
3119 // FIXME: If we want to support export, we probably need to add the
3120 // namespace of the template in a TemplateSpecializationType, or even
3121 // the classes and namespaces of known non-dependent arguments.
3122 if (!BaseDecl)
3123 continue;
3124 if (Result.addClassTransitive(BaseDecl)) {
3125 // Find the associated namespace for this base class.
3126 DeclContext *BaseCtx = BaseDecl->getDeclContext();
3127 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
3128
3129 // Make sure we visit the bases of this base class.
3130 if (!BaseDecl->bases().empty())
3131 Bases.push_back(BaseDecl);
3132 }
3133 }
3134 }
3135}
3136
3137// Add the associated classes and namespaces for
3138// argument-dependent lookup with an argument of type T
3139// (C++ [basic.lookup.koenig]p2).
3140static void
3142 // C++ [basic.lookup.koenig]p2:
3143 //
3144 // For each argument type T in the function call, there is a set
3145 // of zero or more associated namespaces and a set of zero or more
3146 // associated classes to be considered. The sets of namespaces and
3147 // classes is determined entirely by the types of the function
3148 // arguments (and the namespace of any template template
3149 // argument). Typedef names and using-declarations used to specify
3150 // the types do not contribute to this set. The sets of namespaces
3151 // and classes are determined in the following way:
3152
3154 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
3155
3156 while (true) {
3157 switch (T->getTypeClass()) {
3158
3159#define TYPE(Class, Base)
3160#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3161#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3162#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3163#define ABSTRACT_TYPE(Class, Base)
3164#include "clang/AST/TypeNodes.inc"
3165 // T is canonical. We can also ignore dependent types because
3166 // we don't need to do ADL at the definition point, but if we
3167 // wanted to implement template export (or if we find some other
3168 // use for associated classes and namespaces...) this would be
3169 // wrong.
3170 break;
3171
3172 // -- If T is a pointer to U or an array of U, its associated
3173 // namespaces and classes are those associated with U.
3174 case Type::Pointer:
3175 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
3176 continue;
3177 case Type::ConstantArray:
3178 case Type::IncompleteArray:
3179 case Type::VariableArray:
3180 T = cast<ArrayType>(T)->getElementType().getTypePtr();
3181 continue;
3182
3183 // -- If T is a fundamental type, its associated sets of
3184 // namespaces and classes are both empty.
3185 case Type::Builtin:
3186 break;
3187
3188 // -- If T is a class type (including unions), its associated
3189 // classes are: the class itself; the class of which it is
3190 // a member, if any; and its direct and indirect base classes.
3191 // Its associated namespaces are the innermost enclosing
3192 // namespaces of its associated classes.
3193 case Type::Record: {
3194 // FIXME: This should use the original decl.
3195 auto *Class = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl())
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: {
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);
3246 if (CXXRecordDecl *Class = MemberPtr->getMostRecentCXXRecordDecl())
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 case Type::OverflowBehavior:
3307 T = cast<OverflowBehaviorType>(T)->getUnderlyingType().getTypePtr();
3308 }
3309
3310 if (Queue.empty())
3311 break;
3312 T = Queue.pop_back_val();
3313 }
3314}
3315
3317 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3318 AssociatedNamespaceSet &AssociatedNamespaces,
3319 AssociatedClassSet &AssociatedClasses) {
3320 AssociatedNamespaces.clear();
3321 AssociatedClasses.clear();
3322
3323 AssociatedLookup Result(*this, InstantiationLoc,
3324 AssociatedNamespaces, AssociatedClasses);
3325
3326 // C++ [basic.lookup.koenig]p2:
3327 // For each argument type T in the function call, there is a set
3328 // of zero or more associated namespaces and a set of zero or more
3329 // associated classes to be considered. The sets of namespaces and
3330 // classes is determined entirely by the types of the function
3331 // arguments (and the namespace of any template template
3332 // argument).
3333 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3334 Expr *Arg = Args[ArgIdx];
3335
3336 if (Arg->getType() != Context.OverloadTy) {
3338 continue;
3339 }
3340
3341 // [...] In addition, if the argument is the name or address of a
3342 // set of overloaded functions and/or function templates, its
3343 // associated classes and namespaces are the union of those
3344 // associated with each of the members of the set: the namespace
3345 // in which the function or function template is defined and the
3346 // classes and namespaces associated with its (non-dependent)
3347 // parameter types and return type.
3349
3350 for (const NamedDecl *D : OE->decls()) {
3351 // Look through any using declarations to find the underlying function.
3352 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3353
3354 // Add the classes and namespaces associated with the parameter
3355 // types and return type of this function.
3357 }
3358 }
3359}
3360
3362 SourceLocation Loc,
3363 LookupNameKind NameKind,
3364 RedeclarationKind Redecl) {
3365 LookupResult R(*this, Name, Loc, NameKind, Redecl);
3366 LookupName(R, S);
3367 return R.getAsSingle<NamedDecl>();
3368}
3369
3371 UnresolvedSetImpl &Functions) {
3372 // C++ [over.match.oper]p3:
3373 // -- The set of non-member candidates is the result of the
3374 // unqualified lookup of operator@ in the context of the
3375 // expression according to the usual rules for name lookup in
3376 // unqualified function calls (3.4.2) except that all member
3377 // functions are ignored.
3378 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3379 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3380 LookupName(Operators, S);
3381
3382 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3383 Functions.append(Operators.begin(), Operators.end());
3384}
3385
3388 bool ConstArg, bool VolatileArg, bool RValueThis,
3389 bool ConstThis, bool VolatileThis) {
3391 "doing special member lookup into record that isn't fully complete");
3392 RD = RD->getDefinition();
3393 if (RValueThis || ConstThis || VolatileThis)
3396 "constructors and destructors always have unqualified lvalue this");
3397 if (ConstArg || VolatileArg)
3400 "parameter-less special members can't have qualified arguments");
3401
3402 // FIXME: Get the caller to pass in a location for the lookup.
3403 SourceLocation LookupLoc = RD->getLocation();
3404
3405 llvm::FoldingSetNodeID ID;
3406 ID.AddPointer(RD);
3407 ID.AddInteger(llvm::to_underlying(SM));
3408 ID.AddInteger(ConstArg);
3409 ID.AddInteger(VolatileArg);
3410 ID.AddInteger(RValueThis);
3411 ID.AddInteger(ConstThis);
3412 ID.AddInteger(VolatileThis);
3413
3414 void *InsertPoint;
3416 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3417
3418 // This was already cached
3419 if (Result)
3420 return *Result;
3421
3424 SpecialMemberCache.InsertNode(Result, InsertPoint);
3425
3427 if (RD->needsImplicitDestructor()) {
3429 DeclareImplicitDestructor(RD);
3430 });
3431 }
3432 CXXDestructorDecl *DD = RD->getDestructor();
3433 Result->setMethod(DD);
3434 Result->setKind(DD && !DD->isDeleted()
3437 return *Result;
3438 }
3439
3440 // Prepare for overload resolution. Here we construct a synthetic argument
3441 // if necessary and make sure that implicit functions are declared.
3442 CanQualType CanTy = Context.getCanonicalTagType(RD);
3443 DeclarationName Name;
3444 Expr *Arg = nullptr;
3445 unsigned NumArgs;
3446
3447 QualType ArgType = CanTy;
3449
3451 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3452 NumArgs = 0;
3455 DeclareImplicitDefaultConstructor(RD);
3456 });
3457 }
3458 } else {
3461 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3462 if (RD->needsImplicitCopyConstructor()) {
3464 DeclareImplicitCopyConstructor(RD);
3465 });
3466 }
3469 DeclareImplicitMoveConstructor(RD);
3470 });
3471 }
3472 } else {
3473 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3474 if (RD->needsImplicitCopyAssignment()) {
3476 DeclareImplicitCopyAssignment(RD);
3477 });
3478 }
3481 DeclareImplicitMoveAssignment(RD);
3482 });
3483 }
3484 }
3485
3486 if (ConstArg)
3487 ArgType.addConst();
3488 if (VolatileArg)
3489 ArgType.addVolatile();
3490
3491 // This isn't /really/ specified by the standard, but it's implied
3492 // we should be working from a PRValue in the case of move to ensure
3493 // that we prefer to bind to rvalue references, and an LValue in the
3494 // case of copy to ensure we don't bind to rvalue references.
3495 // Possibly an XValue is actually correct in the case of move, but
3496 // there is no semantic difference for class types in this restricted
3497 // case.
3500 VK = VK_LValue;
3501 else
3502 VK = VK_PRValue;
3503 }
3504
3505 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3506
3508 NumArgs = 1;
3509 Arg = &FakeArg;
3510 }
3511
3512 // Create the object argument
3513 QualType ThisTy = CanTy;
3514 if (ConstThis)
3515 ThisTy.addConst();
3516 if (VolatileThis)
3517 ThisTy.addVolatile();
3518 Expr::Classification Classification =
3519 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3520 .Classify(Context);
3521
3522 // Now we perform lookup on the name we computed earlier and do overload
3523 // resolution. Lookup is only performed directly into the class since there
3524 // will always be a (possibly implicit) declaration to shadow any others.
3526 DeclContext::lookup_result R = RD->lookup(Name);
3527
3528 if (R.empty()) {
3529 // We might have no default constructor because we have a lambda's closure
3530 // type, rather than because there's some other declared constructor.
3531 // Every class has a copy/move constructor, copy/move assignment, and
3532 // destructor.
3534 "lookup for a constructor or assignment operator was empty");
3535 Result->setMethod(nullptr);
3537 return *Result;
3538 }
3539
3540 // Copy the candidates as our processing of them may load new declarations
3541 // from an external source and invalidate lookup_result.
3542 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3543
3544 for (NamedDecl *CandDecl : Candidates) {
3545 if (CandDecl->isInvalidDecl())
3546 continue;
3547
3549 auto CtorInfo = getConstructorInfo(Cand);
3550 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3553 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3554 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3555 else if (CtorInfo)
3556 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3557 llvm::ArrayRef(&Arg, NumArgs), OCS,
3558 /*SuppressUserConversions*/ true);
3559 else
3560 AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS,
3561 /*SuppressUserConversions*/ true);
3562 } else if (FunctionTemplateDecl *Tmpl =
3563 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3566 AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy,
3567 Classification,
3568 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3569 else if (CtorInfo)
3570 AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl,
3571 CtorInfo.FoundDecl, nullptr,
3572 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3573 else
3574 AddTemplateOverloadCandidate(Tmpl, Cand, nullptr,
3575 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3576 } else {
3577 assert(isa<UsingDecl>(Cand.getDecl()) &&
3578 "illegal Kind of operator = Decl");
3579 }
3580 }
3581
3583 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3584 case OR_Success:
3585 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3587 break;
3588
3589 case OR_Deleted:
3590 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3592 break;
3593
3594 case OR_Ambiguous:
3595 Result->setMethod(nullptr);
3597 break;
3598
3600 Result->setMethod(nullptr);
3602 break;
3603 }
3604
3605 return *Result;
3606}
3607
3611 false, false, false, false, false);
3612
3613 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3614}
3615
3617 unsigned Quals) {
3618 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3619 "non-const, non-volatile qualifiers for copy ctor arg");
3622 Quals & Qualifiers::Volatile, false, false, false);
3623
3624 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3625}
3626
3628 unsigned Quals) {
3631 Quals & Qualifiers::Volatile, false, false, false);
3632
3633 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3634}
3635
3637 // If the implicit constructors have not yet been declared, do so now.
3639 runWithSufficientStackSpace(Class->getLocation(), [&] {
3640 if (Class->needsImplicitDefaultConstructor())
3641 DeclareImplicitDefaultConstructor(Class);
3642 if (Class->needsImplicitCopyConstructor())
3643 DeclareImplicitCopyConstructor(Class);
3644 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3645 DeclareImplicitMoveConstructor(Class);
3646 });
3647 }
3648
3649 CanQualType T = Context.getCanonicalTagType(Class);
3650 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3651 return Class->lookup(Name);
3652}
3653
3655 unsigned Quals, bool RValueThis,
3656 unsigned ThisQuals) {
3657 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3658 "non-const, non-volatile qualifiers for copy assignment arg");
3659 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3660 "non-const, non-volatile qualifiers for copy assignment this");
3663 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,
3664 ThisQuals & Qualifiers::Volatile);
3665
3666 return Result.getMethod();
3667}
3668
3670 unsigned Quals,
3671 bool RValueThis,
3672 unsigned ThisQuals) {
3673 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3674 "non-const, non-volatile qualifiers for copy assignment this");
3677 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,
3678 ThisQuals & Qualifiers::Volatile);
3679
3680 return Result.getMethod();
3681}
3682
3684 return cast_or_null<CXXDestructorDecl>(
3686 false, false, false)
3687 .getMethod());
3688}
3689
3692 ArrayRef<QualType> ArgTys, bool AllowRaw,
3693 bool AllowTemplate, bool AllowStringTemplatePack,
3694 bool DiagnoseMissing, StringLiteral *StringLit) {
3695 LookupName(R, S);
3696 assert(R.getResultKind() != LookupResultKind::Ambiguous &&
3697 "literal operator lookup can't be ambiguous");
3698
3699 // Filter the lookup results appropriately.
3700 LookupResult::Filter F = R.makeFilter();
3701
3702 bool AllowCooked = true;
3703 bool FoundRaw = false;
3704 bool FoundTemplate = false;
3705 bool FoundStringTemplatePack = false;
3706 bool FoundCooked = false;
3707
3708 while (F.hasNext()) {
3709 Decl *D = F.next();
3710 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3711 D = USD->getTargetDecl();
3712
3713 // If the declaration we found is invalid, skip it.
3714 if (D->isInvalidDecl()) {
3715 F.erase();
3716 continue;
3717 }
3718
3719 bool IsRaw = false;
3720 bool IsTemplate = false;
3721 bool IsStringTemplatePack = false;
3722 bool IsCooked = false;
3723
3724 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3725 if (FD->getNumParams() == 1 &&
3726 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3727 IsRaw = true;
3728 else if (FD->getNumParams() == ArgTys.size()) {
3729 IsCooked = true;
3730 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3731 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3732 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3733 IsCooked = false;
3734 break;
3735 }
3736 }
3737 }
3738 }
3739 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3740 TemplateParameterList *Params = FD->getTemplateParameters();
3741 if (Params->size() == 1) {
3742 IsTemplate = true;
3743 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3744 // Implied but not stated: user-defined integer and floating literals
3745 // only ever use numeric literal operator templates, not templates
3746 // taking a parameter of class type.
3747 F.erase();
3748 continue;
3749 }
3750
3751 // A string literal template is only considered if the string literal
3752 // is a well-formed template argument for the template parameter.
3753 if (StringLit) {
3754 SFINAETrap Trap(*this);
3757 TemplateArgument(StringLit, /*IsCanonical=*/false), StringLit);
3759 Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(),
3760 /*ArgumentPackIndex=*/0, CTAI, CTAK_Specified) ||
3761 Trap.hasErrorOccurred())
3762 IsTemplate = false;
3763 }
3764 } else {
3765 IsStringTemplatePack = true;
3766 }
3767 }
3768
3769 if (AllowTemplate && StringLit && IsTemplate) {
3770 FoundTemplate = true;
3771 AllowRaw = false;
3772 AllowCooked = false;
3773 AllowStringTemplatePack = false;
3774 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3775 F.restart();
3776 FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3777 }
3778 } else if (AllowCooked && IsCooked) {
3779 FoundCooked = true;
3780 AllowRaw = false;
3781 AllowTemplate = StringLit;
3782 AllowStringTemplatePack = false;
3783 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3784 // Go through again and remove the raw and template decls we've
3785 // already found.
3786 F.restart();
3787 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3788 }
3789 } else if (AllowRaw && IsRaw) {
3790 FoundRaw = true;
3791 } else if (AllowTemplate && IsTemplate) {
3792 FoundTemplate = true;
3793 } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3794 FoundStringTemplatePack = true;
3795 } else {
3796 F.erase();
3797 }
3798 }
3799
3800 F.done();
3801
3802 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3803 // form for string literal operator templates.
3804 if (StringLit && FoundTemplate)
3805 return LOLR_Template;
3806
3807 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3808 // parameter type, that is used in preference to a raw literal operator
3809 // or literal operator template.
3810 if (FoundCooked)
3811 return LOLR_Cooked;
3812
3813 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3814 // operator template, but not both.
3815 if (FoundRaw && FoundTemplate) {
3816 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3817 for (const NamedDecl *D : R)
3819 return LOLR_Error;
3820 }
3821
3822 if (FoundRaw)
3823 return LOLR_Raw;
3824
3825 if (FoundTemplate)
3826 return LOLR_Template;
3827
3828 if (FoundStringTemplatePack)
3830
3831 // Didn't find anything we could use.
3832 if (DiagnoseMissing) {
3833 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3834 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3835 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3836 << (AllowTemplate || AllowStringTemplatePack);
3837 return LOLR_Error;
3838 }
3839
3841}
3842
3844 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3845
3846 // If we haven't yet seen a decl for this key, or the last decl
3847 // was exactly this one, we're done.
3848 if (Old == nullptr || Old == New) {
3849 Old = New;
3850 return;
3851 }
3852
3853 // Otherwise, decide which is a more recent redeclaration.
3854 FunctionDecl *OldFD = Old->getAsFunction();
3855 FunctionDecl *NewFD = New->getAsFunction();
3856
3857 FunctionDecl *Cursor = NewFD;
3858 while (true) {
3859 Cursor = Cursor->getPreviousDecl();
3860
3861 // If we got to the end without finding OldFD, OldFD is the newer
3862 // declaration; leave things as they are.
3863 if (!Cursor) return;
3864
3865 // If we do find OldFD, then NewFD is newer.
3866 if (Cursor == OldFD) break;
3867
3868 // Otherwise, keep looking.
3869 }
3870
3871 Old = New;
3872}
3873
3876 // Find all of the associated namespaces and classes based on the
3877 // arguments we have.
3878 AssociatedNamespaceSet AssociatedNamespaces;
3879 AssociatedClassSet AssociatedClasses;
3881 AssociatedNamespaces,
3882 AssociatedClasses);
3883
3884 // C++ [basic.lookup.argdep]p3:
3885 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3886 // and let Y be the lookup set produced by argument dependent
3887 // lookup (defined as follows). If X contains [...] then Y is
3888 // empty. Otherwise Y is the set of declarations found in the
3889 // namespaces associated with the argument types as described
3890 // below. The set of declarations found by the lookup of the name
3891 // is the union of X and Y.
3892 //
3893 // Here, we compute Y and add its members to the overloaded
3894 // candidate set.
3895 for (auto *NS : AssociatedNamespaces) {
3896 // When considering an associated namespace, the lookup is the
3897 // same as the lookup performed when the associated namespace is
3898 // used as a qualifier (3.4.3.2) except that:
3899 //
3900 // -- Any using-directives in the associated namespace are
3901 // ignored.
3902 //
3903 // -- Any namespace-scope friend functions declared in
3904 // associated classes are visible within their respective
3905 // namespaces even if they are not visible during an ordinary
3906 // lookup (11.4).
3907 //
3908 // C++20 [basic.lookup.argdep] p4.3
3909 // -- are exported, are attached to a named module M, do not appear
3910 // in the translation unit containing the point of the lookup, and
3911 // have the same innermost enclosing non-inline namespace scope as
3912 // a declaration of an associated entity attached to M.
3913 DeclContext::lookup_result R = NS->lookup(Name);
3914 for (auto *D : R) {
3915 auto *Underlying = D;
3916 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3917 Underlying = USD->getTargetDecl();
3918
3919 if (!isa<FunctionDecl>(Underlying) &&
3920 !isa<FunctionTemplateDecl>(Underlying))
3921 continue;
3922
3923 // The declaration is visible to argument-dependent lookup if either
3924 // it's ordinarily visible or declared as a friend in an associated
3925 // class.
3926 bool Visible = false;
3927 for (D = D->getMostRecentDecl(); D;
3928 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3930 if (isVisible(D)) {
3931 Visible = true;
3932 break;
3933 }
3934
3935 if (!D->getOwningModule() ||
3937 continue;
3938
3939 if (D->isInExportDeclContext()) {
3940 Module *FM = D->getOwningModule();
3941 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
3942 // exports are only valid in module purview and outside of any
3943 // PMF (although a PMF should not even be present in a module
3944 // with an import).
3945 assert(FM &&
3946 (FM->isNamedModule() || FM->isImplicitGlobalModule()) &&
3947 !FM->isPrivateModule() && "bad export context");
3948 // .. are attached to a named module M, do not appear in the
3949 // translation unit containing the point of the lookup..
3950 if (D->isInAnotherModuleUnit() &&
3951 llvm::any_of(AssociatedClasses, [&](auto *E) {
3952 // ... and have the same innermost enclosing non-inline
3953 // namespace scope as a declaration of an associated entity
3954 // attached to M
3955 if (E->getOwningModule() != FM)
3956 return false;
3957 // TODO: maybe this could be cached when generating the
3958 // associated namespaces / entities.
3959 DeclContext *Ctx = E->getDeclContext();
3960 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
3961 Ctx = Ctx->getParent();
3962 return Ctx == NS;
3963 })) {
3964 Visible = true;
3965 break;
3966 }
3967 }
3968 }
3969
3970 if (D->getFriendObjectKind()) {
3972 // [basic.lookup.argdep]p4:
3973 // Argument-dependent lookup finds all declarations of functions and
3974 // function templates that
3975 // - ...
3976 // - are declared as a friend ([class.friend]) of any class with a
3977 // reachable definition in the set of associated entities,
3978 //
3979 // FIXME: If there's a merged definition of D that is reachable, then
3980 // the friend declaration should be considered.
3981 if (AssociatedClasses.count(RD) && isReachable(D)) {
3982 Visible = true;
3983 break;
3984 }
3985 }
3986 }
3987
3988 // FIXME: Preserve D as the FoundDecl.
3989 if (Visible)
3990 Result.insert(Underlying);
3991 }
3992 }
3993}
3994
3995//----------------------------------------------------------------------------
3996// Search for all visible declarations.
3997//----------------------------------------------------------------------------
3999
4000bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
4001
4002namespace {
4003
4004class ShadowContextRAII;
4005
4006class VisibleDeclsRecord {
4007public:
4008 /// An entry in the shadow map, which is optimized to store a
4009 /// single declaration (the common case) but can also store a list
4010 /// of declarations.
4011 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
4012
4013private:
4014 /// A mapping from declaration names to the declarations that have
4015 /// this name within a particular scope.
4016 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
4017
4018 /// A list of shadow maps, which is used to model name hiding.
4019 std::list<ShadowMap> ShadowMaps;
4020
4021 /// The declaration contexts we have already visited.
4023
4024 friend class ShadowContextRAII;
4025
4026public:
4027 /// Determine whether we have already visited this context
4028 /// (and, if not, note that we are going to visit that context now).
4029 bool visitedContext(DeclContext *Ctx) {
4030 return !VisitedContexts.insert(Ctx).second;
4031 }
4032
4033 bool alreadyVisitedContext(DeclContext *Ctx) {
4034 return VisitedContexts.count(Ctx);
4035 }
4036
4037 /// Determine whether the given declaration is hidden in the
4038 /// current scope.
4039 ///
4040 /// \returns the declaration that hides the given declaration, or
4041 /// NULL if no such declaration exists.
4042 NamedDecl *checkHidden(NamedDecl *ND);
4043
4044 /// Add a declaration to the current shadow map.
4045 void add(NamedDecl *ND) {
4046 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
4047 }
4048};
4049
4050/// RAII object that records when we've entered a shadow context.
4051class ShadowContextRAII {
4052 VisibleDeclsRecord &Visible;
4053
4054 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
4055
4056public:
4057 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
4058 Visible.ShadowMaps.emplace_back();
4059 }
4060
4061 ~ShadowContextRAII() {
4062 Visible.ShadowMaps.pop_back();
4063 }
4064};
4065
4066} // end anonymous namespace
4067
4068NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
4069 unsigned IDNS = ND->getIdentifierNamespace();
4070 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
4071 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
4072 SM != SMEnd; ++SM) {
4073 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
4074 if (Pos == SM->end())
4075 continue;
4076
4077 for (auto *D : Pos->second) {
4078 // A tag declaration does not hide a non-tag declaration.
4079 if (D->hasTagIdentifierNamespace() &&
4082 continue;
4083
4084 // Protocols are in distinct namespaces from everything else.
4086 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
4087 D->getIdentifierNamespace() != IDNS)
4088 continue;
4089
4090 // Functions and function templates in the same scope overload
4091 // rather than hide. FIXME: Look for hiding based on function
4092 // signatures!
4095 SM == ShadowMaps.rbegin())
4096 continue;
4097
4098 // A shadow declaration that's created by a resolved using declaration
4099 // is not hidden by the same using declaration.
4100 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
4101 cast<UsingShadowDecl>(ND)->getIntroducer() == D)
4102 continue;
4103
4104 // We've found a declaration that hides this one.
4105 return D;
4106 }
4107 }
4108
4109 return nullptr;
4110}
4111
4112namespace {
4113class LookupVisibleHelper {
4114public:
4115 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
4116 bool LoadExternal)
4117 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4118 LoadExternal(LoadExternal) {}
4119
4120 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4121 bool IncludeGlobalScope) {
4122 // Determine the set of using directives available during
4123 // unqualified name lookup.
4124 Scope *Initial = S;
4125 UnqualUsingDirectiveSet UDirs(SemaRef);
4126 if (SemaRef.getLangOpts().CPlusPlus) {
4127 // Find the first namespace or translation-unit scope.
4128 while (S && !isNamespaceOrTranslationUnitScope(S))
4129 S = S->getParent();
4130
4131 UDirs.visitScopeChain(Initial, S);
4132 }
4133 UDirs.done();
4134
4135 // Look for visible declarations.
4136 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4137 Result.setAllowHidden(Consumer.includeHiddenDecls());
4138 if (!IncludeGlobalScope)
4139 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4140 ShadowContextRAII Shadow(Visited);
4141 lookupInScope(Initial, Result, UDirs);
4142 }
4143
4144 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4145 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4146 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4147 Result.setAllowHidden(Consumer.includeHiddenDecls());
4148 if (!IncludeGlobalScope)
4149 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4150
4151 ShadowContextRAII Shadow(Visited);
4152 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4153 /*InBaseClass=*/false);
4154 }
4155
4156private:
4157 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4158 bool QualifiedNameLookup, bool InBaseClass) {
4159 if (!Ctx)
4160 return;
4161
4162 // Make sure we don't visit the same context twice.
4163 if (Visited.visitedContext(Ctx->getPrimaryContext()))
4164 return;
4165
4166 Consumer.EnteredContext(Ctx);
4167
4168 // Outside C++, lookup results for the TU live on identifiers.
4169 if (isa<TranslationUnitDecl>(Ctx) &&
4170 !Result.getSema().getLangOpts().CPlusPlus) {
4171 auto &S = Result.getSema();
4172 auto &Idents = S.Context.Idents;
4173
4174 // Ensure all external identifiers are in the identifier table.
4175 if (LoadExternal)
4176 if (IdentifierInfoLookup *External =
4177 Idents.getExternalIdentifierLookup()) {
4178 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4179 for (StringRef Name = Iter->Next(); !Name.empty();
4180 Name = Iter->Next())
4181 Idents.get(Name);
4182 }
4183
4184 // Walk all lookup results in the TU for each identifier.
4185 for (const auto &Ident : Idents) {
4186 for (auto I = S.IdResolver.begin(Ident.getValue()),
4187 E = S.IdResolver.end();
4188 I != E; ++I) {
4189 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
4190 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4191 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4192 Visited.add(ND);
4193 }
4194 }
4195 }
4196 }
4197
4198 return;
4199 }
4200
4201 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
4202 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4203
4204 llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;
4205 // We sometimes skip loading namespace-level results (they tend to be huge).
4206 bool Load = LoadExternal ||
4208 // Enumerate all of the results in this context.
4209 for (DeclContextLookupResult R :
4210 Load ? Ctx->lookups()
4211 : Ctx->noload_lookups(/*PreserveInternalState=*/false))
4212 for (auto *D : R)
4213 // Rather than visit immediately, we put ND into a vector and visit
4214 // all decls, in order, outside of this loop. The reason is that
4215 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)
4216 // may invalidate the iterators used in the two
4217 // loops above.
4218 DeclsToVisit.push_back(D);
4219
4220 for (auto *D : DeclsToVisit)
4221 if (auto *ND = Result.getAcceptableDecl(D)) {
4222 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4223 Visited.add(ND);
4224 }
4225
4226 DeclsToVisit.clear();
4227
4228 // Traverse using directives for qualified name lookup.
4229 if (QualifiedNameLookup) {
4230 ShadowContextRAII Shadow(Visited);
4231 for (auto *I : Ctx->using_directives()) {
4232 if (!Result.getSema().isVisible(I))
4233 continue;
4234 lookupInDeclContext(I->getNominatedNamespace(), Result,
4235 QualifiedNameLookup, InBaseClass);
4236 }
4237 }
4238
4239 // Traverse the contexts of inherited C++ classes.
4240 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
4241 if (!Record->hasDefinition())
4242 return;
4243
4244 for (const auto &B : Record->bases()) {
4245 QualType BaseType = B.getType();
4246
4247 RecordDecl *RD;
4248 if (BaseType->isDependentType()) {
4249 if (!IncludeDependentBases) {
4250 // Don't look into dependent bases, because name lookup can't look
4251 // there anyway.
4252 continue;
4253 }
4254 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
4255 if (!TST)
4256 continue;
4257 TemplateName TN = TST->getTemplateName();
4258 const auto *TD =
4259 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
4260 if (!TD)
4261 continue;
4262 RD = TD->getTemplatedDecl();
4263 } else {
4264 RD = BaseType->getAsCXXRecordDecl();
4265 if (!RD)
4266 continue;
4267 }
4268
4269 // FIXME: It would be nice to be able to determine whether referencing
4270 // a particular member would be ambiguous. For example, given
4271 //
4272 // struct A { int member; };
4273 // struct B { int member; };
4274 // struct C : A, B { };
4275 //
4276 // void f(C *c) { c->### }
4277 //
4278 // accessing 'member' would result in an ambiguity. However, we
4279 // could be smart enough to qualify the member with the base
4280 // class, e.g.,
4281 //
4282 // c->B::member
4283 //
4284 // or
4285 //
4286 // c->A::member
4287
4288 // Find results in this base class (and its bases).
4289 ShadowContextRAII Shadow(Visited);
4290 lookupInDeclContext(RD, Result, QualifiedNameLookup,
4291 /*InBaseClass=*/true);
4292 }
4293 }
4294
4295 // Traverse the contexts of Objective-C classes.
4296 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
4297 // Traverse categories.
4298 for (auto *Cat : IFace->visible_categories()) {
4299 ShadowContextRAII Shadow(Visited);
4300 lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4301 /*InBaseClass=*/false);
4302 }
4303
4304 // Traverse protocols.
4305 for (auto *I : IFace->all_referenced_protocols()) {
4306 ShadowContextRAII Shadow(Visited);
4307 lookupInDeclContext(I, Result, QualifiedNameLookup,
4308 /*InBaseClass=*/false);
4309 }
4310
4311 // Traverse the superclass.
4312 if (IFace->getSuperClass()) {
4313 ShadowContextRAII Shadow(Visited);
4314 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4315 /*InBaseClass=*/true);
4316 }
4317
4318 // If there is an implementation, traverse it. We do this to find
4319 // synthesized ivars.
4320 if (IFace->getImplementation()) {
4321 ShadowContextRAII Shadow(Visited);
4322 lookupInDeclContext(IFace->getImplementation(), Result,
4323 QualifiedNameLookup, InBaseClass);
4324 }
4325 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4326 for (auto *I : Protocol->protocols()) {
4327 ShadowContextRAII Shadow(Visited);
4328 lookupInDeclContext(I, Result, QualifiedNameLookup,
4329 /*InBaseClass=*/false);
4330 }
4331 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4332 for (auto *I : Category->protocols()) {
4333 ShadowContextRAII Shadow(Visited);
4334 lookupInDeclContext(I, Result, QualifiedNameLookup,
4335 /*InBaseClass=*/false);
4336 }
4337
4338 // If there is an implementation, traverse it.
4339 if (Category->getImplementation()) {
4340 ShadowContextRAII Shadow(Visited);
4341 lookupInDeclContext(Category->getImplementation(), Result,
4342 QualifiedNameLookup, /*InBaseClass=*/true);
4343 }
4344 }
4345 }
4346
4347 void lookupInScope(Scope *S, LookupResult &Result,
4348 UnqualUsingDirectiveSet &UDirs) {
4349 // No clients run in this mode and it's not supported. Please add tests and
4350 // remove the assertion if you start relying on it.
4351 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4352
4353 if (!S)
4354 return;
4355
4356 if (!S->getEntity() ||
4357 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4358 (S->getEntity())->isFunctionOrMethod()) {
4359 FindLocalExternScope FindLocals(Result);
4360 // Walk through the declarations in this Scope. The consumer might add new
4361 // decls to the scope as part of deserialization, so make a copy first.
4362 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4363 for (Decl *D : ScopeDecls) {
4364 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4365 if ((ND = Result.getAcceptableDecl(ND))) {
4366 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4367 Visited.add(ND);
4368 }
4369 }
4370 }
4371
4372 DeclContext *Entity = S->getLookupEntity();
4373 if (Entity) {
4374 // Look into this scope's declaration context, along with any of its
4375 // parent lookup contexts (e.g., enclosing classes), up to the point
4376 // where we hit the context stored in the next outer scope.
4377 DeclContext *OuterCtx = findOuterContext(S);
4378
4379 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4380 Ctx = Ctx->getLookupParent()) {
4381 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4382 if (Method->isInstanceMethod()) {
4383 // For instance methods, look for ivars in the method's interface.
4384 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4385 Result.getNameLoc(),
4387 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4388 lookupInDeclContext(IFace, IvarResult,
4389 /*QualifiedNameLookup=*/false,
4390 /*InBaseClass=*/false);
4391 }
4392 }
4393
4394 // We've already performed all of the name lookup that we need
4395 // to for Objective-C methods; the next context will be the
4396 // outer scope.
4397 break;
4398 }
4399
4400 if (Ctx->isFunctionOrMethod())
4401 continue;
4402
4403 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4404 /*InBaseClass=*/false);
4405 }
4406 } else if (!S->getParent()) {
4407 // Look into the translation unit scope. We walk through the translation
4408 // unit's declaration context, because the Scope itself won't have all of
4409 // the declarations if we loaded a precompiled header.
4410 // FIXME: We would like the translation unit's Scope object to point to
4411 // the translation unit, so we don't need this special "if" branch.
4412 // However, doing so would force the normal C++ name-lookup code to look
4413 // into the translation unit decl when the IdentifierInfo chains would
4414 // suffice. Once we fix that problem (which is part of a more general
4415 // "don't look in DeclContexts unless we have to" optimization), we can
4416 // eliminate this.
4417 Entity = Result.getSema().Context.getTranslationUnitDecl();
4418 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4419 /*InBaseClass=*/false);
4420 }
4421
4422 if (Entity) {
4423 // Lookup visible declarations in any namespaces found by using
4424 // directives.
4425 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4426 lookupInDeclContext(
4427 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4428 /*QualifiedNameLookup=*/false,
4429 /*InBaseClass=*/false);
4430 }
4431
4432 // Lookup names in the parent scope.
4433 ShadowContextRAII Shadow(Visited);
4434 lookupInScope(S->getParent(), Result, UDirs);
4435 }
4436
4437private:
4438 VisibleDeclsRecord Visited;
4439 VisibleDeclConsumer &Consumer;
4440 bool IncludeDependentBases;
4441 bool LoadExternal;
4442};
4443} // namespace
4444
4447 bool IncludeGlobalScope, bool LoadExternal) {
4448 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4449 LoadExternal);
4450 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4451}
4452
4455 bool IncludeGlobalScope,
4456 bool IncludeDependentBases, bool LoadExternal) {
4457 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4458 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4459}
4460
4462 NamedDecl *Res = LookupSingleName(CurScope, II, Loc, LookupLabel,
4464 // If we found a label, check to see if it is in the same context as us.
4465 // When in a Block, we don't want to reuse a label in an enclosing function.
4466 if (!Res || Res->getDeclContext() != CurContext)
4467 return nullptr;
4468 return cast<LabelDecl>(Res);
4469}
4470
4472 SourceLocation GnuLabelLoc) {
4473 if (GnuLabelLoc.isValid()) {
4474 // Local label definitions always shadow existing labels.
4475 auto *Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4476 Scope *S = CurScope;
4477 PushOnScopeChains(Res, S, true);
4478 return cast<LabelDecl>(Res);
4479 }
4480
4481 // Not a GNU local label.
4482 LabelDecl *Res = LookupExistingLabel(II, Loc);
4483 if (!Res) {
4484 // If not forward referenced or defined already, create the backing decl.
4485 Res = LabelDecl::Create(Context, CurContext, Loc, II);
4486 Scope *S = CurScope->getFnParent();
4487 assert(S && "Not in a function?");
4488 PushOnScopeChains(Res, S, true);
4489 }
4490 return Res;
4491}
4492
4493//===----------------------------------------------------------------------===//
4494// Typo correction
4495//===----------------------------------------------------------------------===//
4496
4498 TypoCorrection &Candidate) {
4499 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4500 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4501}
4502
4503static void LookupPotentialTypoResult(Sema &SemaRef,
4504 LookupResult &Res,
4505 IdentifierInfo *Name,
4506 Scope *S, CXXScopeSpec *SS,
4507 DeclContext *MemberContext,
4508 bool EnteringContext,
4509 bool isObjCIvarLookup,
4510 bool FindHidden);
4511
4512/// Check whether the declarations found for a typo correction are
4513/// visible. Set the correction's RequiresImport flag to true if none of the
4514/// declarations are visible, false otherwise.
4516 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4517
4518 for (/**/; DI != DE; ++DI)
4519 if (!LookupResult::isVisible(SemaRef, *DI))
4520 break;
4521 // No filtering needed if all decls are visible.
4522 if (DI == DE) {
4523 TC.setRequiresImport(false);
4524 return;
4525 }
4526
4527 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4528 bool AnyVisibleDecls = !NewDecls.empty();
4529
4530 for (/**/; DI != DE; ++DI) {
4531 if (LookupResult::isVisible(SemaRef, *DI)) {
4532 if (!AnyVisibleDecls) {
4533 // Found a visible decl, discard all hidden ones.
4534 AnyVisibleDecls = true;
4535 NewDecls.clear();
4536 }
4537 NewDecls.push_back(*DI);
4538 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4539 NewDecls.push_back(*DI);
4540 }
4541
4542 if (NewDecls.empty())
4543 TC = TypoCorrection();
4544 else {
4545 TC.setCorrectionDecls(NewDecls);
4546 TC.setRequiresImport(!AnyVisibleDecls);
4547 }
4548}
4549
4550// Fill the supplied vector with the IdentifierInfo pointers for each piece of
4551// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4552// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4556 switch (NNS.getKind()) {
4558 Identifiers.clear();
4559 return;
4560
4562 auto [Namespace, Prefix] = NNS.getAsNamespaceAndPrefix();
4563 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4564 if (const auto *NS = dyn_cast<NamespaceDecl>(Namespace);
4565 NS && NS->isAnonymousNamespace())
4566 return;
4567 Identifiers.push_back(Namespace->getIdentifier());
4568 return;
4569 }
4570
4572 for (const Type *T = NNS.getAsType(); /**/; /**/) {
4573 switch (T->getTypeClass()) {
4574 case Type::DependentName: {
4575 auto *DT = cast<DependentNameType>(T);
4576 getNestedNameSpecifierIdentifiers(DT->getQualifier(), Identifiers);
4577 Identifiers.push_back(DT->getIdentifier());
4578 return;
4579 }
4580 case Type::TemplateSpecialization: {
4581 TemplateName Name =
4582 cast<TemplateSpecializationType>(T)->getTemplateName();
4583 if (const DependentTemplateName *DTN =
4585 getNestedNameSpecifierIdentifiers(DTN->getQualifier(), Identifiers);
4586 if (const auto *II = DTN->getName().getIdentifier())
4587 Identifiers.push_back(II);
4588 return;
4589 }
4590 if (const QualifiedTemplateName *QTN =
4592 getNestedNameSpecifierIdentifiers(QTN->getQualifier(), Identifiers);
4593 Name = QTN->getUnderlyingTemplate();
4594 }
4595 if (const auto *TD = Name.getAsTemplateDecl(/*IgnoreDeduced=*/true))
4596 Identifiers.push_back(TD->getIdentifier());
4597 return;
4598 }
4599 case Type::SubstTemplateTypeParm:
4601 ->getReplacementType()
4602 .getTypePtr();
4603 continue;
4604 case Type::TemplateTypeParm:
4605 Identifiers.push_back(cast<TemplateTypeParmType>(T)->getIdentifier());
4606 return;
4607 case Type::Decltype:
4608 return;
4609 case Type::Enum:
4610 case Type::Record:
4611 case Type::InjectedClassName: {
4612 auto *TT = cast<TagType>(T);
4613 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);
4614 Identifiers.push_back(TT->getDecl()->getIdentifier());
4615 return;
4616 }
4617 case Type::Typedef: {
4618 auto *TT = cast<TypedefType>(T);
4619 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);
4620 Identifiers.push_back(TT->getDecl()->getIdentifier());
4621 return;
4622 }
4623 case Type::Using: {
4624 auto *TT = cast<UsingType>(T);
4625 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);
4626 Identifiers.push_back(TT->getDecl()->getIdentifier());
4627 return;
4628 }
4629 case Type::UnresolvedUsing: {
4630 auto *TT = cast<UnresolvedUsingType>(T);
4631 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);
4632 Identifiers.push_back(TT->getDecl()->getIdentifier());
4633 return;
4634 }
4635 default:
4636 Identifiers.push_back(QualType(T, 0).getBaseTypeIdentifier());
4637 return;
4638 }
4639 }
4640 break;
4641 }
4642
4645 return;
4646 }
4647}
4648
4650 DeclContext *Ctx, bool InBaseClass) {
4651 // Don't consider hidden names for typo correction.
4652 if (Hiding)
4653 return;
4654
4655 // Only consider entities with identifiers for names, ignoring
4656 // special names (constructors, overloaded operators, selectors,
4657 // etc.).
4658 IdentifierInfo *Name = ND->getIdentifier();
4659 if (!Name)
4660 return;
4661
4662 // Only consider visible declarations and declarations from modules with
4663 // names that exactly match.
4664 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4665 return;
4666
4667 FoundName(Name->getName());
4668}
4669
4671 // Compute the edit distance between the typo and the name of this
4672 // entity, and add the identifier to the list of results.
4673 addName(Name, nullptr);
4674}
4675
4677 // Compute the edit distance between the typo and this keyword,
4678 // and add the keyword to the list of results.
4679 addName(Keyword, /*ND=*/nullptr, /*NNS=*/std::nullopt, /*isKeyword=*/true);
4680}
4681
4682void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4683 NestedNameSpecifier NNS, bool isKeyword) {
4684 // Use a simple length-based heuristic to determine the minimum possible
4685 // edit distance. If the minimum isn't good enough, bail out early.
4686 StringRef TypoStr = Typo->getName();
4687 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4688 if (MinED && TypoStr.size() / MinED < 3)
4689 return;
4690
4691 // Compute an upper bound on the allowable edit distance, so that the
4692 // edit-distance algorithm can short-circuit.
4693 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4694 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4695 if (ED > UpperBound) return;
4696
4697 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4698 if (isKeyword) TC.makeKeyword();
4699 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4700 addCorrection(TC);
4701}
4702
4703static const unsigned MaxTypoDistanceResultSets = 5;
4704
4706 StringRef TypoStr = Typo->getName();
4707 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4708
4709 // For very short typos, ignore potential corrections that have a different
4710 // base identifier from the typo or which have a normalized edit distance
4711 // longer than the typo itself.
4712 if (TypoStr.size() < 3 &&
4713 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4714 return;
4715
4716 // If the correction is resolved but is not viable, ignore it.
4717 if (Correction.isResolved()) {
4718 checkCorrectionVisibility(SemaRef, Correction);
4719 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4720 return;
4721 }
4722
4723 TypoResultList &CList =
4724 CorrectionResults[Correction.getEditDistance(false)][Name];
4725
4726 if (!CList.empty() && !CList.back().isResolved())
4727 CList.pop_back();
4728 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4729 auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4730 return TypoCorr.getCorrectionDecl() == NewND;
4731 });
4732 if (RI != CList.end()) {
4733 // The Correction refers to a decl already in the list. No insertion is
4734 // necessary and all further cases will return.
4735
4736 auto IsDeprecated = [](Decl *D) {
4737 while (D) {
4738 if (D->isDeprecated())
4739 return true;
4740 D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4741 }
4742 return false;
4743 };
4744
4745 // Prefer non deprecated Corrections over deprecated and only then
4746 // sort using an alphabetical order.
4747 std::pair<bool, std::string> NewKey = {
4748 IsDeprecated(Correction.getFoundDecl()),
4749 Correction.getAsString(SemaRef.getLangOpts())};
4750
4751 std::pair<bool, std::string> PrevKey = {
4752 IsDeprecated(RI->getFoundDecl()),
4753 RI->getAsString(SemaRef.getLangOpts())};
4754
4755 if (NewKey < PrevKey)
4756 *RI = std::move(Correction);
4757 return;
4758 }
4759 }
4760 if (CList.empty() || Correction.isResolved())
4761 CList.push_back(Correction);
4762
4763 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4764 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4765}
4766
4768 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4769 SearchNamespaces = true;
4770
4771 for (auto KNPair : KnownNamespaces)
4772 Namespaces.addNameSpecifier(KNPair.first);
4773
4774 bool SSIsTemplate = false;
4775 if (NestedNameSpecifier NNS = (SS ? SS->getScopeRep() : std::nullopt)) {
4777 SSIsTemplate =
4778 NNS.getAsType()->getTypeClass() == Type::TemplateSpecialization;
4779 }
4780 // Do not transform this into an iterator-based loop. The loop body can
4781 // trigger the creation of further types (through lazy deserialization) and
4782 // invalid iterators into this list.
4783 auto &Types = SemaRef.getASTContext().getTypes();
4784 for (unsigned I = 0; I != Types.size(); ++I) {
4785 const auto *TI = Types[I];
4786 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4787 CD = CD->getCanonicalDecl();
4788 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4789 !CD->isUnion() && CD->getIdentifier() &&
4790 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4791 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4792 Namespaces.addNameSpecifier(CD);
4793 }
4794 }
4795}
4796
4798 if (++CurrentTCIndex < ValidatedCorrections.size())
4799 return ValidatedCorrections[CurrentTCIndex];
4800
4801 CurrentTCIndex = ValidatedCorrections.size();
4802 while (!CorrectionResults.empty()) {
4803 auto DI = CorrectionResults.begin();
4804 if (DI->second.empty()) {
4805 CorrectionResults.erase(DI);
4806 continue;
4807 }
4808
4809 auto RI = DI->second.begin();
4810 if (RI->second.empty()) {
4811 DI->second.erase(RI);
4812 performQualifiedLookups();
4813 continue;
4814 }
4815
4816 TypoCorrection TC = RI->second.pop_back_val();
4817 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4818 ValidatedCorrections.push_back(TC);
4819 return ValidatedCorrections[CurrentTCIndex];
4820 }
4821 }
4822 return ValidatedCorrections[0]; // The empty correction.
4823}
4824
4825bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4827 DeclContext *TempMemberContext = MemberContext;
4828 CXXScopeSpec *TempSS = SS.get();
4829retry_lookup:
4830 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4831 EnteringContext,
4832 CorrectionValidator->IsObjCIvarLookup,
4833 Name == Typo && !Candidate.WillReplaceSpecifier());
4834 switch (Result.getResultKind()) {
4838 if (TempSS) {
4839 // Immediately retry the lookup without the given CXXScopeSpec
4840 TempSS = nullptr;
4841 Candidate.WillReplaceSpecifier(true);
4842 goto retry_lookup;
4843 }
4844 if (TempMemberContext) {
4845 if (SS && !TempSS)
4846 TempSS = SS.get();
4847 TempMemberContext = nullptr;
4848 goto retry_lookup;
4849 }
4850 if (SearchNamespaces)
4851 QualifiedResults.push_back(Candidate);
4852 break;
4853
4855 // We don't deal with ambiguities.
4856 break;
4857
4860 // Store all of the Decls for overloaded symbols
4861 for (auto *TRD : Result)
4862 Candidate.addCorrectionDecl(TRD);
4863 checkCorrectionVisibility(SemaRef, Candidate);
4864 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4865 if (SearchNamespaces)
4866 QualifiedResults.push_back(Candidate);
4867 break;
4868 }
4869 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4870 return true;
4871 }
4872 return false;
4873}
4874
4875void TypoCorrectionConsumer::performQualifiedLookups() {
4876 unsigned TypoLen = Typo->getName().size();
4877 for (const TypoCorrection &QR : QualifiedResults) {
4878 for (const auto &NSI : Namespaces) {
4879 DeclContext *Ctx = NSI.DeclCtx;
4880 CXXRecordDecl *NamingClass = NSI.NameSpecifier.getAsRecordDecl();
4881
4882 // If the current NestedNameSpecifier refers to a class and the
4883 // current correction candidate is the name of that class, then skip
4884 // it as it is unlikely a qualified version of the class' constructor
4885 // is an appropriate correction.
4886 if (NamingClass &&
4887 NamingClass->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4888 continue;
4889
4890 TypoCorrection TC(QR);
4891 TC.ClearCorrectionDecls();
4892 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4893 TC.setQualifierDistance(NSI.EditDistance);
4894 TC.setCallbackDistance(0); // Reset the callback distance
4895
4896 // If the current correction candidate and namespace combination are
4897 // too far away from the original typo based on the normalized edit
4898 // distance, then skip performing a qualified name lookup.
4899 unsigned TmpED = TC.getEditDistance(true);
4900 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4901 TypoLen / TmpED < 3)
4902 continue;
4903
4904 Result.clear();
4905 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4906 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4907 continue;
4908
4909 // Any corrections added below will be validated in subsequent
4910 // iterations of the main while() loop over the Consumer's contents.
4911 switch (Result.getResultKind()) {
4914 if (SS && SS->isValid()) {
4915 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4916 std::string OldQualified;
4917 llvm::raw_string_ostream OldOStream(OldQualified);
4918 SS->getScopeRep().print(OldOStream, SemaRef.getPrintingPolicy());
4919 OldOStream << Typo->getName();
4920 // If correction candidate would be an identical written qualified
4921 // identifier, then the existing CXXScopeSpec probably included a
4922 // typedef that didn't get accounted for properly.
4923 if (OldOStream.str() == NewQualified)
4924 break;
4925 }
4926 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4927 TRD != TRDEnd; ++TRD) {
4928 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4929 NamingClass,
4930 TRD.getPair()) == Sema::AR_accessible)
4931 TC.addCorrectionDecl(*TRD);
4932 }
4933 if (TC.isResolved()) {
4934 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4935 addCorrection(TC);
4936 }
4937 break;
4938 }
4943 break;
4944 }
4945 }
4946 }
4947 QualifiedResults.clear();
4948}
4949
4950TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4951 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4952 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4953 if (NestedNameSpecifier NNS =
4954 CurScopeSpec ? CurScopeSpec->getScopeRep() : std::nullopt) {
4955 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4956 NNS.print(SpecifierOStream, Context.getPrintingPolicy());
4957
4958 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4959 }
4960 // Build the list of identifiers that would be used for an absolute
4961 // (from the global context) NestedNameSpecifier referring to the current
4962 // context.
4963 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4964 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4965 CurContextIdentifiers.push_back(ND->getIdentifier());
4966 }
4967
4968 // Add the global context as a NestedNameSpecifier
4969 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4971 DistanceMap[1].push_back(SI);
4972}
4973
4974auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4975 DeclContext *Start) -> DeclContextList {
4976 assert(Start && "Building a context chain from a null context");
4977 DeclContextList Chain;
4978 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4979 DC = DC->getLookupParent()) {
4980 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4981 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4982 !(ND && ND->isAnonymousNamespace()))
4983 Chain.push_back(DC->getPrimaryContext());
4984 }
4985 return Chain;
4986}
4987
4988unsigned
4989TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4990 DeclContextList &DeclChain, NestedNameSpecifier &NNS) {
4991 unsigned NumSpecifiers = 0;
4992 for (DeclContext *C : llvm::reverse(DeclChain)) {
4993 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4994 NNS = NestedNameSpecifier(Context, ND, NNS);
4995 ++NumSpecifiers;
4996 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4997 QualType T = Context.getTagType(ElaboratedTypeKeyword::None, NNS, RD,
4998 /*OwnsTag=*/false);
4999 NNS = NestedNameSpecifier(T.getTypePtr());
5000 ++NumSpecifiers;
5001 }
5002 }
5003 return NumSpecifiers;
5004}
5005
5006void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
5007 DeclContext *Ctx) {
5008 NestedNameSpecifier NNS = std::nullopt;
5009 unsigned NumSpecifiers = 0;
5010 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
5011 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
5012
5013 // Eliminate common elements from the two DeclContext chains.
5014 for (DeclContext *C : llvm::reverse(CurContextChain)) {
5015 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
5016 break;
5017 NamespaceDeclChain.pop_back();
5018 }
5019
5020 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
5021 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
5022
5023 // Add an explicit leading '::' specifier if needed.
5024 if (NamespaceDeclChain.empty()) {
5025 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
5027 NumSpecifiers =
5028 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
5029 } else if (NamedDecl *ND =
5030 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
5031 IdentifierInfo *Name = ND->getIdentifier();
5032 bool SameNameSpecifier = false;
5033 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
5034 std::string NewNameSpecifier;
5035 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
5036 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
5037 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
5038 NNS.print(SpecifierOStream, Context.getPrintingPolicy());
5039 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
5040 }
5041 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
5042 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
5044 NumSpecifiers =
5045 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
5046 }
5047 }
5048
5049 // If the built NestedNameSpecifier would be replacing an existing
5050 // NestedNameSpecifier, use the number of component identifiers that
5051 // would need to be changed as the edit distance instead of the number
5052 // of components in the built NestedNameSpecifier.
5053 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
5054 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
5055 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
5056 NumSpecifiers =
5057 llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),
5058 llvm::ArrayRef(NewNameSpecifierIdentifiers));
5059 }
5060
5061 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
5062 DistanceMap[NumSpecifiers].push_back(SI);
5063}
5064
5065/// Perform name lookup for a possible result for typo correction.
5066static void LookupPotentialTypoResult(Sema &SemaRef,
5067 LookupResult &Res,
5068 IdentifierInfo *Name,
5069 Scope *S, CXXScopeSpec *SS,
5070 DeclContext *MemberContext,
5071 bool EnteringContext,
5072 bool isObjCIvarLookup,
5073 bool FindHidden) {
5074 Res.suppressDiagnostics();
5075 Res.clear();
5076 Res.setLookupName(Name);
5077 Res.setAllowHidden(FindHidden);
5078 if (MemberContext) {
5079 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
5080 if (isObjCIvarLookup) {
5081 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
5082 Res.addDecl(Ivar);
5083 Res.resolveKind();
5084 return;
5085 }
5086 }
5087
5088 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
5090 Res.addDecl(Prop);
5091 Res.resolveKind();
5092 return;
5093 }
5094 }
5095
5096 SemaRef.LookupQualifiedName(Res, MemberContext);
5097 return;
5098 }
5099
5100 SemaRef.LookupParsedName(Res, S, SS,
5101 /*ObjectType=*/QualType(),
5102 /*AllowBuiltinCreation=*/false, EnteringContext);
5103
5104 // Fake ivar lookup; this should really be part of
5105 // LookupParsedName.
5106 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
5107 if (Method->isInstanceMethod() && Method->getClassInterface() &&
5108 (Res.empty() ||
5109 (Res.isSingleResult() &&
5111 if (ObjCIvarDecl *IV
5112 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
5113 Res.addDecl(IV);
5114 Res.resolveKind();
5115 }
5116 }
5117 }
5118}
5119
5120/// Add keywords to the consumer as possible typo corrections.
5121static void AddKeywordsToConsumer(Sema &SemaRef,
5122 TypoCorrectionConsumer &Consumer,
5124 bool AfterNestedNameSpecifier) {
5125 if (AfterNestedNameSpecifier) {
5126 // For 'X::', we know exactly which keywords can appear next.
5127 Consumer.addKeywordResult("template");
5128 if (CCC.WantExpressionKeywords)
5129 Consumer.addKeywordResult("operator");
5130 return;
5131 }
5132
5133 if (CCC.WantObjCSuper)
5134 Consumer.addKeywordResult("super");
5135
5136 if (CCC.WantTypeSpecifiers) {
5137 // Add type-specifier keywords to the set of results.
5138 static const char *const CTypeSpecs[] = {
5139 "char", "const", "double", "enum", "float", "int", "long", "short",
5140 "signed", "struct", "union", "unsigned", "void", "volatile",
5141 "_Complex",
5142 // storage-specifiers as well
5143 "extern", "inline", "static", "typedef"
5144 };
5145
5146 for (const auto *CTS : CTypeSpecs)
5147 Consumer.addKeywordResult(CTS);
5148
5149 if (SemaRef.getLangOpts().C99 && !SemaRef.getLangOpts().C2y)
5150 Consumer.addKeywordResult("_Imaginary");
5151
5152 if (SemaRef.getLangOpts().C99)
5153 Consumer.addKeywordResult("restrict");
5154 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
5155 Consumer.addKeywordResult("bool");
5156 else if (SemaRef.getLangOpts().C99)
5157 Consumer.addKeywordResult("_Bool");
5158
5159 if (SemaRef.getLangOpts().CPlusPlus) {
5160 Consumer.addKeywordResult("class");
5161 Consumer.addKeywordResult("typename");
5162 Consumer.addKeywordResult("wchar_t");
5163
5164 if (SemaRef.getLangOpts().CPlusPlus11) {
5165 Consumer.addKeywordResult("char16_t");
5166 Consumer.addKeywordResult("char32_t");
5167 Consumer.addKeywordResult("constexpr");
5168 Consumer.addKeywordResult("decltype");
5169 Consumer.addKeywordResult("thread_local");
5170 }
5171 }
5172
5173 if (SemaRef.getLangOpts().GNUKeywords)
5174 Consumer.addKeywordResult("typeof");
5175 } else if (CCC.WantFunctionLikeCasts) {
5176 static const char *const CastableTypeSpecs[] = {
5177 "char", "double", "float", "int", "long", "short",
5178 "signed", "unsigned", "void"
5179 };
5180 for (auto *kw : CastableTypeSpecs)
5181 Consumer.addKeywordResult(kw);
5182 }
5183
5184 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5185 Consumer.addKeywordResult("const_cast");
5186 Consumer.addKeywordResult("dynamic_cast");
5187 Consumer.addKeywordResult("reinterpret_cast");
5188 Consumer.addKeywordResult("static_cast");
5189 }
5190
5191 if (CCC.WantExpressionKeywords) {
5192 Consumer.addKeywordResult("sizeof");
5193 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5194 Consumer.addKeywordResult("false");
5195 Consumer.addKeywordResult("true");
5196 }
5197
5198 if (SemaRef.getLangOpts().CPlusPlus) {
5199 static const char *const CXXExprs[] = {
5200 "delete", "new", "operator", "throw", "typeid"
5201 };
5202 for (const auto *CE : CXXExprs)
5203 Consumer.addKeywordResult(CE);
5204
5205 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
5206 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
5207 Consumer.addKeywordResult("this");
5208
5209 if (SemaRef.getLangOpts().CPlusPlus11) {
5210 Consumer.addKeywordResult("alignof");
5211 Consumer.addKeywordResult("nullptr");
5212 }
5213 }
5214
5215 if (SemaRef.getLangOpts().C11) {
5216 // FIXME: We should not suggest _Alignof if the alignof macro
5217 // is present.
5218 Consumer.addKeywordResult("_Alignof");
5219 }
5220 }
5221
5222 if (CCC.WantRemainingKeywords) {
5223 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5224 // Statements.
5225 static const char *const CStmts[] = {
5226 "do", "else", "for", "goto", "if", "return", "switch", "while" };
5227 for (const auto *CS : CStmts)
5228 Consumer.addKeywordResult(CS);
5229
5230 if (SemaRef.getLangOpts().CPlusPlus) {
5231 Consumer.addKeywordResult("catch");
5232 Consumer.addKeywordResult("try");
5233 }
5234
5235 if (S && S->getBreakParent())
5236 Consumer.addKeywordResult("break");
5237
5238 if (S && S->getContinueParent())
5239 Consumer.addKeywordResult("continue");
5240
5241 if (SemaRef.getCurFunction() &&
5242 !SemaRef.getCurFunction()->SwitchStack.empty()) {
5243 Consumer.addKeywordResult("case");
5244 Consumer.addKeywordResult("default");
5245 }
5246 } else {
5247 if (SemaRef.getLangOpts().CPlusPlus) {
5248 Consumer.addKeywordResult("namespace");
5249 Consumer.addKeywordResult("template");
5250 }
5251
5252 if (S && S->isClassScope()) {
5253 Consumer.addKeywordResult("explicit");
5254 Consumer.addKeywordResult("friend");
5255 Consumer.addKeywordResult("mutable");
5256 Consumer.addKeywordResult("private");
5257 Consumer.addKeywordResult("protected");
5258 Consumer.addKeywordResult("public");
5259 Consumer.addKeywordResult("virtual");
5260 }
5261 }
5262
5263 if (SemaRef.getLangOpts().CPlusPlus) {
5264 Consumer.addKeywordResult("using");
5265
5266 if (SemaRef.getLangOpts().CPlusPlus11)
5267 Consumer.addKeywordResult("static_assert");
5268 }
5269 }
5270}
5271
5272std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5273 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5274 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5275 DeclContext *MemberContext, bool EnteringContext,
5276 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5277
5278 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5279 DisableTypoCorrection)
5280 return nullptr;
5281
5282 // In Microsoft mode, don't perform typo correction in a template member
5283 // function dependent context because it interferes with the "lookup into
5284 // dependent bases of class templates" feature.
5285 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5286 isa<CXXMethodDecl>(CurContext))
5287 return nullptr;
5288
5289 // We only attempt to correct typos for identifiers.
5290 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5291 if (!Typo)
5292 return nullptr;
5293
5294 // If the scope specifier itself was invalid, don't try to correct
5295 // typos.
5296 if (SS && SS->isInvalid())
5297 return nullptr;
5298
5299 // Never try to correct typos during any kind of code synthesis.
5300 if (!CodeSynthesisContexts.empty())
5301 return nullptr;
5302
5303 // Don't try to correct 'super'.
5304 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5305 return nullptr;
5306
5307 // Abort if typo correction already failed for this specific typo.
5308 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
5309 if (locs != TypoCorrectionFailures.end() &&
5310 locs->second.count(TypoName.getLoc()))
5311 return nullptr;
5312
5313 // Don't try to correct the identifier "vector" when in AltiVec mode.
5314 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5315 // remove this workaround.
5316 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
5317 return nullptr;
5318
5319 // Provide a stop gap for files that are just seriously broken. Trying
5320 // to correct all typos can turn into a HUGE performance penalty, causing
5321 // some files to take minutes to get rejected by the parser.
5322 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5323 if (Limit && TyposCorrected >= Limit)
5324 return nullptr;
5325 ++TyposCorrected;
5326
5327 // If we're handling a missing symbol error, using modules, and the
5328 // special search all modules option is used, look for a missing import.
5329 if (ErrorRecovery && getLangOpts().Modules &&
5330 getLangOpts().ModulesSearchAll) {
5331 // The following has the side effect of loading the missing module.
5332 getModuleLoader().lookupMissingImports(Typo->getName(),
5333 TypoName.getBeginLoc());
5334 }
5335
5336 // Extend the lifetime of the callback. We delayed this until here
5337 // to avoid allocations in the hot path (which is where no typo correction
5338 // occurs). Note that CorrectionCandidateCallback is polymorphic and
5339 // initially stack-allocated.
5340 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5341 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5342 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5343 EnteringContext);
5344
5345 // Perform name lookup to find visible, similarly-named entities.
5346 bool IsUnqualifiedLookup = false;
5347 DeclContext *QualifiedDC = MemberContext;
5348 if (MemberContext) {
5349 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
5350
5351 // Look in qualified interfaces.
5352 if (OPT) {
5353 for (auto *I : OPT->quals())
5354 LookupVisibleDecls(I, LookupKind, *Consumer);
5355 }
5356 } else if (SS && SS->isSet()) {
5357 QualifiedDC = computeDeclContext(*SS, EnteringContext);
5358 if (!QualifiedDC)
5359 return nullptr;
5360
5361 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
5362 } else {
5363 IsUnqualifiedLookup = true;
5364 }
5365
5366 // Determine whether we are going to search in the various namespaces for
5367 // corrections.
5368 bool SearchNamespaces
5369 = getLangOpts().CPlusPlus &&
5370 (IsUnqualifiedLookup || (SS && SS->isSet()));
5371
5372 if (IsUnqualifiedLookup || SearchNamespaces) {
5373 // For unqualified lookup, look through all of the names that we have
5374 // seen in this translation unit.
5375 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5376 for (const auto &I : Context.Idents)
5377 Consumer->FoundName(I.getKey());
5378
5379 // Walk through identifiers in external identifier sources.
5380 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5381 if (IdentifierInfoLookup *External
5382 = Context.Idents.getExternalIdentifierLookup()) {
5383 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5384 do {
5385 StringRef Name = Iter->Next();
5386 if (Name.empty())
5387 break;
5388
5389 Consumer->FoundName(Name);
5390 } while (true);
5391 }
5392 }
5393
5394 AddKeywordsToConsumer(*this, *Consumer, S,
5395 *Consumer->getCorrectionValidator(),
5396 SS && SS->isNotEmpty());
5397
5398 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5399 // to search those namespaces.
5400 if (SearchNamespaces) {
5401 // Load any externally-known namespaces.
5402 if (ExternalSource && !LoadedExternalKnownNamespaces) {
5403 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5404 LoadedExternalKnownNamespaces = true;
5405 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5406 for (auto *N : ExternalKnownNamespaces)
5407 KnownNamespaces[N] = true;
5408 }
5409
5410 Consumer->addNamespaces(KnownNamespaces);
5411 }
5412
5413 return Consumer;
5414}
5415
5417 Sema::LookupNameKind LookupKind,
5418 Scope *S, CXXScopeSpec *SS,
5420 CorrectTypoKind Mode,
5421 DeclContext *MemberContext,
5422 bool EnteringContext,
5423 const ObjCObjectPointerType *OPT,
5424 bool RecordFailure) {
5425 // Always let the ExternalSource have the first chance at correction, even
5426 // if we would otherwise have given up.
5427 if (ExternalSource) {
5428 if (TypoCorrection Correction =
5429 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5430 MemberContext, EnteringContext, OPT))
5431 return Correction;
5432 }
5433
5434 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5435 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5436 // some instances of CTC_Unknown, while WantRemainingKeywords is true
5437 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5438 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5439
5440 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5441 auto Consumer = makeTypoCorrectionConsumer(
5442 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT,
5444
5445 if (!Consumer)
5446 return TypoCorrection();
5447
5448 // If we haven't found anything, we're done.
5449 if (Consumer->empty())
5450 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5451
5452 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5453 // is not more that about a third of the length of the typo's identifier.
5454 unsigned ED = Consumer->getBestEditDistance(true);
5455 unsigned TypoLen = Typo->getName().size();
5456 if (ED > 0 && TypoLen / ED < 3)
5457 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5458
5459 TypoCorrection BestTC = Consumer->getNextCorrection();
5460 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5461 if (!BestTC)
5462 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5463
5464 ED = BestTC.getEditDistance();
5465
5466 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5467 // If this was an unqualified lookup and we believe the callback
5468 // object wouldn't have filtered out possible corrections, note
5469 // that no correction was found.
5470 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5471 }
5472
5473 // If only a single name remains, return that result.
5474 if (!SecondBestTC ||
5475 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5476 const TypoCorrection &Result = BestTC;
5477
5478 // Don't correct to a keyword that's the same as the typo; the keyword
5479 // wasn't actually in scope.
5480 if (ED == 0 && Result.isKeyword())
5481 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5482
5484 TC.setCorrectionRange(SS, TypoName);
5485 checkCorrectionVisibility(*this, TC);
5486 return TC;
5487 } else if (SecondBestTC && ObjCMessageReceiver) {
5488 // Prefer 'super' when we're completing in a message-receiver
5489 // context.
5490
5491 if (BestTC.getCorrection().getAsString() != "super") {
5492 if (SecondBestTC.getCorrection().getAsString() == "super")
5493 BestTC = std::move(SecondBestTC);
5494 else if ((*Consumer)["super"].front().isKeyword())
5495 BestTC = (*Consumer)["super"].front();
5496 }
5497 // Don't correct to a keyword that's the same as the typo; the keyword
5498 // wasn't actually in scope.
5499 if (BestTC.getEditDistance() == 0 ||
5500 BestTC.getCorrection().getAsString() != "super")
5501 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5502
5503 BestTC.setCorrectionRange(SS, TypoName);
5504 return BestTC;
5505 }
5506
5507 // Record the failure's location if needed and return an empty correction. If
5508 // this was an unqualified lookup and we believe the callback object did not
5509 // filter out possible corrections, also cache the failure for the typo.
5510 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5511}
5512
5514 if (!CDecl) return;
5515
5516 if (isKeyword())
5517 CorrectionDecls.clear();
5518
5519 CorrectionDecls.push_back(CDecl);
5520
5521 if (!CorrectionName)
5522 CorrectionName = CDecl->getDeclName();
5523}
5524
5525std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5526 if (CorrectionNameSpec) {
5527 std::string tmpBuffer;
5528 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5529 CorrectionNameSpec.print(PrefixOStream, PrintingPolicy(LO));
5530 PrefixOStream << CorrectionName;
5531 return PrefixOStream.str();
5532 }
5533
5534 return CorrectionName.getAsString();
5535}
5536
5538 const TypoCorrection &candidate) {
5539 if (!candidate.isResolved())
5540 return true;
5541
5542 if (candidate.isKeyword())
5545
5546 bool HasNonType = false;
5547 bool HasStaticMethod = false;
5548 bool HasNonStaticMethod = false;
5549 for (Decl *D : candidate) {
5550 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5551 D = FTD->getTemplatedDecl();
5552 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5553 if (Method->isStatic())
5554 HasStaticMethod = true;
5555 else
5556 HasNonStaticMethod = true;
5557 }
5558 if (!isa<TypeDecl>(D))
5559 HasNonType = true;
5560 }
5561
5562 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5563 !candidate.getCorrectionSpecifier())
5564 return false;
5565
5566 return WantTypeSpecifiers || HasNonType;
5567}
5568
5570 bool HasExplicitTemplateArgs,
5571 MemberExpr *ME)
5572 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5573 CurContext(SemaRef.CurContext), MemberFn(ME) {
5574 WantTypeSpecifiers = false;
5576 !HasExplicitTemplateArgs && NumArgs == 1;
5577 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5578 WantRemainingKeywords = false;
5579}
5580
5582 if (!candidate.getCorrectionDecl())
5583 return candidate.isKeyword();
5584
5585 for (auto *C : candidate) {
5586 FunctionDecl *FD = nullptr;
5587 NamedDecl *ND = C->getUnderlyingDecl();
5588 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5589 FD = FTD->getTemplatedDecl();
5590 if (!HasExplicitTemplateArgs && !FD) {
5591 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5592 // If the Decl is neither a function nor a template function,
5593 // determine if it is a pointer or reference to a function. If so,
5594 // check against the number of arguments expected for the pointee.
5595 QualType ValType = cast<ValueDecl>(ND)->getType();
5596 if (ValType.isNull())
5597 continue;
5598 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5599 ValType = ValType->getPointeeType();
5600 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5601 if (FPT->getNumParams() == NumArgs)
5602 return true;
5603 }
5604 }
5605
5606 // A typo for a function-style cast can look like a function call in C++.
5607 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5608 : isa<TypeDecl>(ND)) &&
5609 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5610 // Only a class or class template can take two or more arguments.
5611 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5612
5613 // Skip the current candidate if it is not a FunctionDecl or does not accept
5614 // the current number of arguments.
5615 if (!FD || !(FD->getNumParams() >= NumArgs &&
5616 FD->getMinRequiredArguments() <= NumArgs))
5617 continue;
5618
5619 // If the current candidate is a non-static C++ method, skip the candidate
5620 // unless the method being corrected--or the current DeclContext, if the
5621 // function being corrected is not a method--is a method in the same class
5622 // or a descendent class of the candidate's parent class.
5623 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
5624 if (MemberFn || !MD->isStatic()) {
5625 const auto *CurMD =
5626 MemberFn
5627 ? dyn_cast_if_present<CXXMethodDecl>(MemberFn->getMemberDecl())
5628 : dyn_cast_if_present<CXXMethodDecl>(CurContext);
5629 const CXXRecordDecl *CurRD =
5630 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5631 const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5632 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5633 continue;
5634 }
5635 }
5636 return true;
5637 }
5638 return false;
5639}
5640
5641void Sema::diagnoseTypo(const TypoCorrection &Correction,
5642 const PartialDiagnostic &TypoDiag,
5643 bool ErrorRecovery) {
5644 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5646}
5647
5648/// Find which declaration we should import to provide the definition of
5649/// the given declaration.
5651 if (const auto *VD = dyn_cast<VarDecl>(D))
5652 return VD->getDefinition();
5653 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5654 return FD->getDefinition();
5655 if (const auto *TD = dyn_cast<TagDecl>(D))
5656 return TD->getDefinition();
5657 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
5658 return ID->getDefinition();
5659 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))
5660 return PD->getDefinition();
5661 if (const auto *TD = dyn_cast<TemplateDecl>(D))
5662 if (const NamedDecl *TTD = TD->getTemplatedDecl())
5663 return getDefinitionToImport(TTD);
5664 return nullptr;
5665}
5666
5668 MissingImportKind MIK, bool Recover) {
5669 // Suggest importing a module providing the definition of this entity, if
5670 // possible.
5671 const NamedDecl *Def = getDefinitionToImport(Decl);
5672 if (!Def)
5673 Def = Decl;
5674
5675 Module *Owner = getOwningModule(Def);
5676 assert(Owner && "definition of hidden declaration is not in a module");
5677
5678 llvm::SmallVector<Module*, 8> OwningModules;
5679 OwningModules.push_back(Owner);
5680 auto Merged = Context.getModulesWithMergedDefinition(Def);
5681 llvm::append_range(OwningModules, Merged);
5682
5683 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5684 Recover);
5685}
5686
5687/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5688/// suggesting the addition of a #include of the specified file.
5690 llvm::StringRef IncludingFile) {
5691 bool IsAngled = false;
5693 E, IncludingFile, &IsAngled);
5694 return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');
5695}
5696
5698 SourceLocation DeclLoc,
5699 ArrayRef<Module *> Modules,
5700 MissingImportKind MIK, bool Recover) {
5701 assert(!Modules.empty());
5702
5703 // See https://github.com/llvm/llvm-project/issues/73893. It is generally
5704 // confusing than helpful to show the namespace is not visible.
5706 return;
5707
5708 auto NotePrevious = [&] {
5709 // FIXME: Suppress the note backtrace even under
5710 // -fdiagnostics-show-note-include-stack. We don't care how this
5711 // declaration was previously reached.
5712 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5713 };
5714
5715 // Weed out duplicates from module list.
5716 llvm::SmallVector<Module*, 8> UniqueModules;
5717 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5718 for (auto *M : Modules) {
5719 if (M->isExplicitGlobalModule() || M->isPrivateModule())
5720 continue;
5721 if (UniqueModuleSet.insert(M).second)
5722 UniqueModules.push_back(M);
5723 }
5724
5725 // Try to find a suitable header-name to #include.
5726 std::string HeaderName;
5727 if (OptionalFileEntryRef Header =
5728 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5729 if (const FileEntry *FE =
5730 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5731 HeaderName =
5732 getHeaderNameForHeader(PP, *Header, FE->tryGetRealPathName());
5733 }
5734
5735 // If we have a #include we should suggest, or if all definition locations
5736 // were in global module fragments, don't suggest an import.
5737 if (!HeaderName.empty() || UniqueModules.empty()) {
5738 // FIXME: Find a smart place to suggest inserting a #include, and add
5739 // a FixItHint there.
5740 Diag(UseLoc, diag::err_module_unimported_use_header)
5741 << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5742 // Produce a note showing where the entity was declared.
5743 NotePrevious();
5744 if (Recover)
5746 return;
5747 }
5748
5749 Modules = UniqueModules;
5750
5751 auto GetModuleNameForDiagnostic = [this](const Module *M) -> std::string {
5752 if (M->isModuleMapModule())
5753 return M->getFullModuleName();
5754
5755 if (M->isImplicitGlobalModule())
5756 M = M->getTopLevelModule();
5757
5758 // If the current module unit is in the same module with M, it is OK to show
5759 // the partition name. Otherwise, it'll be sufficient to show the primary
5760 // module name.
5761 if (getASTContext().isInSameModule(M, getCurrentModule()))
5762 return M->getTopLevelModuleName().str();
5763 else
5764 return M->getPrimaryModuleInterfaceName().str();
5765 };
5766
5767 if (Modules.size() > 1) {
5768 std::string ModuleList;
5769 unsigned N = 0;
5770 for (const auto *M : Modules) {
5771 ModuleList += "\n ";
5772 if (++N == 5 && N != Modules.size()) {
5773 ModuleList += "[...]";
5774 break;
5775 }
5776 ModuleList += GetModuleNameForDiagnostic(M);
5777 }
5778
5779 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5780 << (int)MIK << Decl << ModuleList;
5781 } else {
5782 // FIXME: Add a FixItHint that imports the corresponding module.
5783 Diag(UseLoc, diag::err_module_unimported_use)
5784 << (int)MIK << Decl << GetModuleNameForDiagnostic(Modules[0]);
5785 }
5786
5787 NotePrevious();
5788
5789 // Try to recover by implicitly importing this module.
5790 if (Recover)
5792}
5793
5794void Sema::diagnoseTypo(const TypoCorrection &Correction,
5795 const PartialDiagnostic &TypoDiag,
5796 const PartialDiagnostic &PrevNote,
5797 bool ErrorRecovery) {
5798 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5799 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5801 Correction.getCorrectionRange(), CorrectedStr);
5802
5803 // Maybe we're just missing a module import.
5804 if (Correction.requiresImport()) {
5805 NamedDecl *Decl = Correction.getFoundDecl();
5806 assert(Decl && "import required but no declaration to import");
5807
5810 return;
5811 }
5812
5813 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5814 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5815
5816 NamedDecl *ChosenDecl =
5817 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5818
5819 // For builtin functions which aren't declared anywhere in source,
5820 // don't emit the "declared here" note.
5821 if (const auto *FD = dyn_cast_if_present<FunctionDecl>(ChosenDecl);
5822 FD && FD->getBuiltinID() &&
5823 PrevNote.getDiagID() == diag::note_previous_decl &&
5824 Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {
5825 ChosenDecl = nullptr;
5826 }
5827
5828 if (PrevNote.getDiagID() && ChosenDecl)
5829 Diag(ChosenDecl->getLocation(), PrevNote)
5830 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5831
5832 // Add any extra diagnostics.
5833 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5834 Diag(Correction.getCorrectionRange().getBegin(), PD);
5835}
5836
5838 DeclarationNameInfo Name(II, IILoc);
5839 LookupResult R(*this, Name, LookupAnyName,
5841 R.suppressDiagnostics();
5842 R.setHideTags(false);
5843 LookupName(R, S);
5844 R.dump();
5845}
5846
5848 E->dump();
5849}
5850
5852 // A declaration with an owning module for linkage can never link against
5853 // anything that is not visible. We don't need to check linkage here; if
5854 // the context has internal linkage, redeclaration lookup won't find things
5855 // from other TUs, and we can't safely compute linkage yet in general.
5856 if (cast<Decl>(CurContext)->getOwningModuleForLinkage())
5859}
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
#define SM(sm)
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.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
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.
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.
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 inclu...
static void addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T)
static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name)
Lookup an OpenCL typedef type.
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.
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.
static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass, llvm::StringRef Name)
Diagnose a missing builtin type.
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 ...
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.
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)
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,...
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...
static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, const DeclContext *NS, UnqualUsingDirectiveSet &UDirs)
This file declares semantic analysis functions specific to RISC-V.
__DEVICE__ long long abs(long long __n)
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:223
TranslationUnitDecl * getTranslationUnitDecl() const
IdentifierTable & Idents
Definition ASTContext.h:802
Builtin::Context & BuiltinInfo
Definition ASTContext.h:804
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:855
CanQualType VoidTy
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.
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition Builtins.h:321
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
paths_iterator begin()
paths_iterator end()
void setOrigin(const CXXRecordDecl *Rec)
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:2620
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
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:603
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:1727
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2084
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:2126
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1119
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:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
SourceRange getRange() const
Definition DeclSpec.h:82
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
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
DeclListNode::iterator iterator
Definition DeclBase.h:1405
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2591
bool isFileContext() const
Definition DeclBase.h:2193
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
lookups_range noload_lookups(bool PreserveInternalState) const
Definition DeclLookups.h:89
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2138
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2198
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
lookups_range lookups() const
Definition DeclLookups.h:75
bool shouldUseQualifiedLookup() const
Definition DeclBase.h:2736
void setUseQualifiedLookup(bool use=true) const
Definition DeclBase.h:2732
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
bool isInlineNamespace() const
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
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:1074
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1239
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition DeclBase.h:1132
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
bool isInNamedModule() const
Whether this declaration comes from a named module.
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:867
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:906
bool isInvisibleOutsideTheOwningModule() const
Definition DeclBase.h:678
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
void dump() const
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2806
bool isInvalidDecl() const
Definition DeclBase.h:596
unsigned getIdentifierNamespace() const
Definition DeclBase.h:902
SourceLocation getLocation() const
Definition DeclBase.h:447
@ 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:770
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1062
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition DeclBase.h:962
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasTagIdentifierNamespace() const
Definition DeclBase.h:912
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:878
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 an enum.
Definition Decl.h:4017
The return type of classify().
Definition Expr.h:339
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:415
QualType getType() const
Definition Expr.h:144
bool isFPConstrained() const
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:273
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:141
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:2018
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:2179
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3822
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:4240
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2532
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3801
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5369
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5658
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5809
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4788
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4565
QualType getReturnType() const
Definition TypeBase.h:4905
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 includ...
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.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
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:524
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition Decl.cpp:5576
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
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
Represents the results of name lookup.
Definition Lookup.h:147
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 setAllowHidden(bool AH)
Specify whether hidden declarations are visible, e.g., for recovery reasons.
Definition Lookup.h:298
static bool isAcceptable(Sema &SemaRef, NamedDecl *D, Sema::AcceptableKind Kind)
Definition Lookup.h:376
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
void setAmbiguousBaseSubobjects(CXXBasePaths &P)
Make these results show that the name was found in distinct base classes of the same type.
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.
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.
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
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
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void print(raw_ostream &)
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
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3715
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:950
bool isPrivateModule() const
Definition Module.h:448
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:1056
bool isModuleInterfaceUnit() const
Definition Module.h:898
bool isModuleMapModule() const
Definition Module.h:450
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:905
bool isExplicitGlobalModule() const
Definition Module.h:441
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:438
bool isImplicitGlobalModule() const
Definition Module.h:444
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:423
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:940
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:658
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:656
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1096
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
bool isExternallyDeclarable() const
Determine whether this declaration can be redeclared in a different translation unit.
Definition Decl.h:439
Represent a C++ namespace.
Definition Decl.h:592
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:643
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.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
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:8058
qual_range quals() const
Definition TypeBase.h:8177
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
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:3132
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
llvm::iterator_range< decls_iterator > decls() const
Definition ExprCXX.h:3231
Represents a parameter to a function.
Definition Decl.h:1808
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1841
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:2932
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3390
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool isMacroDefined(StringRef Id)
HeaderSearch & getHeaderSearchInfo() const
A (possibly-)qualified type.
Definition TypeBase.h:937
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
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:8440
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1179
Represents a template name as written in source code.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:410
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:284
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
DeclContext * getLookupEntity() const
Get the DeclContext in which to continue unqualified lookup after a lookup in this scope.
Definition Scope.h:389
using_directives_range using_directives()
Definition Scope.h:642
Scope * getContinueParent()
getContinueParent - Return the closest scope that a continue statement would be affected by.
Definition Scope.h:294
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:380
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:383
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:463
Scope * getBreakParent()
getBreakParent - Return the closest scope that a break statement would be affected by.
Definition Scope.h:304
decl_range decls() const
Definition Scope.h:338
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
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:12505
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12539
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition Sema.h:9378
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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.
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:13640
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13624
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:9416
@ LookupLabel
Label name lookup.
Definition Sema.h:9425
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9447
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9439
@ LookupOMPReductionName
Look up the name of an OpenMP user-defined reduction operation.
Definition Sema.h:9461
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9455
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition Sema.h:9457
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9452
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9432
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9459
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9443
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition Sema.h:9435
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9423
@ LookupOMPMapperName
Look up the name of an OpenMP user-defined mapper.
Definition Sema.h:9463
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9465
bool hasReachableDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
MissingImportKind
Kinds of missing import.
Definition Sema.h:9854
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:1686
Preprocessor & getPreprocessor() const
Definition Sema.h:938
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.
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12067
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:13644
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
ASTContext & Context
Definition Sema.h:1308
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
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.
ASTContext & getASTContext() const
Definition Sema.h:939
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9413
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3638
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1730
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:934
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition Sema.h:932
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:1307
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:15563
SemaHLSL & HLSL()
Definition Sema.h:1483
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9412
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
SemaRISCV & RISCV()
Definition Sema.h:1548
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1737
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1341
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15557
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9946
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:2628
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:1446
SemaOpenCL & OpenCL()
Definition Sema.h:1528
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:15570
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:9406
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.
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1584
ASTConsumer & Consumer
Definition Sema.h:1309
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:1267
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:1311
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...
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.
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13635
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1253
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
LiteralOperatorLookupResult
The possible outcomes of name lookup for a literal operator.
Definition Sema.h:9469
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9473
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9479
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9471
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9476
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9487
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9483
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:3519
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,...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
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().
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3723
A template argument list.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
Represents a template argument.
QualType getAsType() const
Retrieve the type for a type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
Represents a declaration of a type.
Definition Decl.h:3519
The base class of the type hierarchy.
Definition TypeBase.h:1875
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:9337
bool isReferenceType() const
Definition TypeBase.h:8701
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:790
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2844
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3181
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2528
bool isAnyPointerType() const
Definition TypeBase.h:8685
TypeClass getTypeClass() const
Definition TypeBase.h:2445
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9270
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3568
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)
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.
void append(iterator I, iterator E)
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition DeclCXX.cpp:3344
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3404
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition Decl.cpp:2686
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.
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:2183
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
@ CPlusPlus
@ CPlusPlus11
@ 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...
Definition Template.h:50
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
std::unique_ptr< sema::RISCVIntrinsicManager > CreateRISCVIntrinsicManager(Sema &S)
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ AmbiguousBaseSubobjects
Name lookup results in an ambiguity because multiple nonstatic entities that meet the lookup criteria...
Definition Lookup.h:94
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:137
@ AmbiguousReferenceToPlaceholderVariable
Name lookup results in an ambiguity because multiple placeholder variables were found in the same sco...
Definition Lookup.h:120
@ AmbiguousReference
Name lookup results in an ambiguity because multiple definitions of entity that meet the lookup crite...
Definition Lookup.h:109
@ AmbiguousBaseSubobjectTypes
Name lookup results in an ambiguity because multiple entities that meet the lookup criteria were foun...
Definition Lookup.h:80
@ SC_Extern
Definition Specifiers.h:255
@ SC_None
Definition Specifiers.h:254
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
CorrectTypoKind
Definition Sema.h:818
llvm::Expected< QualType > ExpectedType
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
for(const auto &A :T->param_types())
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:201
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1519
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5989
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5979
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5982
@ 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:5454
Describes how types, statements, expressions, and declarations should be printed.