5852 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements name lookup for C, C++, Objective-C, and10// Objective-C++.11//12//===----------------------------------------------------------------------===//13 14#include "clang/AST/ASTContext.h"15#include "clang/AST/CXXInheritance.h"16#include "clang/AST/Decl.h"17#include "clang/AST/DeclCXX.h"18#include "clang/AST/DeclLookups.h"19#include "clang/AST/DeclObjC.h"20#include "clang/AST/DeclTemplate.h"21#include "clang/AST/Expr.h"22#include "clang/AST/ExprCXX.h"23#include "clang/Basic/Builtins.h"24#include "clang/Basic/LangOptions.h"25#include "clang/Basic/TargetInfo.h"26#include "clang/Lex/HeaderSearch.h"27#include "clang/Lex/ModuleLoader.h"28#include "clang/Lex/Preprocessor.h"29#include "clang/Sema/DeclSpec.h"30#include "clang/Sema/Lookup.h"31#include "clang/Sema/Overload.h"32#include "clang/Sema/RISCVIntrinsicManager.h"33#include "clang/Sema/Scope.h"34#include "clang/Sema/ScopeInfo.h"35#include "clang/Sema/Sema.h"36#include "clang/Sema/SemaInternal.h"37#include "clang/Sema/SemaRISCV.h"38#include "clang/Sema/TemplateDeduction.h"39#include "clang/Sema/TypoCorrection.h"40#include "llvm/ADT/STLExtras.h"41#include "llvm/ADT/STLForwardCompat.h"42#include "llvm/ADT/SmallPtrSet.h"43#include "llvm/ADT/TinyPtrVector.h"44#include "llvm/ADT/edit_distance.h"45#include "llvm/Support/Casting.h"46#include "llvm/Support/ErrorHandling.h"47#include <algorithm>48#include <iterator>49#include <list>50#include <optional>51#include <set>52#include <utility>53#include <vector>54 55#include "OpenCLBuiltins.inc"56 57using namespace clang;58using namespace sema;59 60namespace {61 class UnqualUsingEntry {62 const DeclContext *Nominated;63 const DeclContext *CommonAncestor;64 65 public:66 UnqualUsingEntry(const DeclContext *Nominated,67 const DeclContext *CommonAncestor)68 : Nominated(Nominated), CommonAncestor(CommonAncestor) {69 }70 71 const DeclContext *getCommonAncestor() const {72 return CommonAncestor;73 }74 75 const DeclContext *getNominatedNamespace() const {76 return Nominated;77 }78 79 // Sort by the pointer value of the common ancestor.80 struct Comparator {81 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {82 return L.getCommonAncestor() < R.getCommonAncestor();83 }84 85 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {86 return E.getCommonAncestor() < DC;87 }88 89 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {90 return DC < E.getCommonAncestor();91 }92 };93 };94 95 /// A collection of using directives, as used by C++ unqualified96 /// 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 they111 // were declared in the nearest enclosing namespace which contains112 // 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 may119 // 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 directives132 // recursively. Treats all using directives as if they were133 // declared in the context.134 //135 // A given context is only every visited once, so it is important136 // that contexts be visited from the inside out in order to get137 // 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 using146 // directives recursively. Treats all using directives as if they147 // 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 nominated158 // by its using directives, transitively) as if they appeared in159 // 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 given179 // context. This helps implement C++ [namespace.udir]p3:180 // The using-directive is transitive: if a scope contains a181 // using-directive that nominates a second namespace that itself182 // contains using-directives, the effect is as if the183 // using-directives from the second namespace also appeared in184 // the first.185 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {186 // Find the common ancestor between the effective context and187 // the nominated namespace.188 DeclContext *Common = UD->getNominatedNamespace();189 while (!Common->Encloses(EffectiveDC))190 Common = Common->getParent();191 Common = Common->getPrimaryContext();192 193 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));194 }195 196 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }197 198 typedef ListTy::const_iterator const_iterator;199 200 const_iterator begin() const { return list.begin(); }201 const_iterator end() const { return list.end(); }202 203 llvm::iterator_range<const_iterator>204 getNamespacesFor(const DeclContext *DC) const {205 return llvm::make_range(std::equal_range(begin(), end(),206 DC->getPrimaryContext(),207 UnqualUsingEntry::Comparator()));208 }209 };210} // end anonymous namespace211 212// Retrieve the set of identifier namespaces that correspond to a213// specific kind of name lookup.214static inline unsigned getIDNS(Sema::LookupNameKind NameKind,215 bool CPlusPlus,216 bool Redeclaration) {217 unsigned IDNS = 0;218 switch (NameKind) {219 case Sema::LookupObjCImplicitSelfParam:220 case Sema::LookupOrdinaryName:221 case Sema::LookupRedeclarationWithLinkage:222 case Sema::LookupLocalFriendName:223 case Sema::LookupDestructorName:224 IDNS = Decl::IDNS_Ordinary;225 if (CPlusPlus) {226 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;227 if (Redeclaration)228 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;229 }230 if (Redeclaration)231 IDNS |= Decl::IDNS_LocalExtern;232 break;233 234 case Sema::LookupOperatorName:235 // Operator lookup is its own crazy thing; it is not the same236 // as (e.g.) looking up an operator name for redeclaration.237 assert(!Redeclaration && "cannot do redeclaration operator lookup");238 IDNS = Decl::IDNS_NonMemberOperator;239 break;240 241 case Sema::LookupTagName:242 if (CPlusPlus) {243 IDNS = Decl::IDNS_Type;244 245 // When looking for a redeclaration of a tag name, we add:246 // 1) TagFriend to find undeclared friend decls247 // 2) Namespace because they can't "overload" with tag decls.248 // 3) Tag because it includes class templates, which can't249 // "overload" with tag decls.250 if (Redeclaration)251 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;252 } else {253 IDNS = Decl::IDNS_Tag;254 }255 break;256 257 case Sema::LookupLabel:258 IDNS = Decl::IDNS_Label;259 break;260 261 case Sema::LookupMemberName:262 IDNS = Decl::IDNS_Member;263 if (CPlusPlus)264 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;265 break;266 267 case Sema::LookupNestedNameSpecifierName:268 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;269 break;270 271 case Sema::LookupNamespaceName:272 IDNS = Decl::IDNS_Namespace;273 break;274 275 case Sema::LookupUsingDeclName:276 assert(Redeclaration && "should only be used for redecl lookup");277 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |278 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |279 Decl::IDNS_LocalExtern;280 break;281 282 case Sema::LookupObjCProtocolName:283 IDNS = Decl::IDNS_ObjCProtocol;284 break;285 286 case Sema::LookupOMPReductionName:287 IDNS = Decl::IDNS_OMPReduction;288 break;289 290 case Sema::LookupOMPMapperName:291 IDNS = Decl::IDNS_OMPMapper;292 break;293 294 case Sema::LookupAnyName:295 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member296 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol297 | Decl::IDNS_Type;298 break;299 }300 return IDNS;301}302 303void LookupResult::configure() {304 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,305 isForRedeclaration());306 307 // If we're looking for one of the allocation or deallocation308 // operators, make sure that the implicitly-declared new and delete309 // operators can be found.310 switch (NameInfo.getName().getCXXOverloadedOperator()) {311 case OO_New:312 case OO_Delete:313 case OO_Array_New:314 case OO_Array_Delete:315 getSema().DeclareGlobalNewDelete();316 break;317 318 default:319 break;320 }321 322 // Compiler builtins are always visible, regardless of where they end323 // 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 &&343 (Ambiguity == LookupAmbiguityKind::AmbiguousBaseSubobjects ||344 Ambiguity == LookupAmbiguityKind::AmbiguousBaseSubobjectTypes)));345 assert((Paths != nullptr) ==346 (ResultKind == LookupResultKind::Ambiguous &&347 (Ambiguity == LookupAmbiguityKind::AmbiguousBaseSubobjectTypes ||348 Ambiguity == LookupAmbiguityKind::AmbiguousBaseSubobjects)));349 return true;350}351 352// Necessary because CXXBasePaths is not complete in Sema.h353void LookupResult::deletePaths(CXXBasePaths *Paths) {354 delete Paths;355}356 357/// Get a representative context for a declaration such that two declarations358/// will have the same context if they were found within the same scope.359static const DeclContext *getContextForScopeMatching(const Decl *D) {360 // For function-local declarations, use that function as the context. This361 // doesn't account for scopes within the function; the caller must deal with362 // 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. The368 // declaration must have been found there.369 return D->getDeclContext()->getRedeclContext();370}371 372/// Determine whether \p D is a better lookup result than \p Existing,373/// given that they declare the same entity.374static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,375 const NamedDecl *D,376 const NamedDecl *Existing) {377 // When looking up redeclarations of a using declaration, prefer a using378 // shadow declaration over any other declaration of the same entity.379 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&380 !isa<UsingShadowDecl>(Existing))381 return true;382 383 const auto *DUnderlying = D->getUnderlyingDecl();384 const auto *EUnderlying = Existing->getUnderlyingDecl();385 386 // If they have different underlying declarations, prefer a typedef over the387 // original type (this happens when two type declarations denote the same388 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef389 // 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 tag391 // declaration over a typedef. Also prefer a tag over a typedef for392 // destructor name lookup because in some contexts we only accept a393 // 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 =398 Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName;399 return HaveTag != WantTag;400 }401 402 // Pick the function with more default arguments.403 // FIXME: In the presence of ambiguous default arguments, we should keep both,404 // so we can diagnose the ambiguity if the default argument is needed.405 // See C++ [over.match.best]p3.406 if (const auto *DFD = dyn_cast<FunctionDecl>(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, check414 // 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 default423 // arguments (and their visibility) is monotonically increasing across the424 // 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, an428 // earlier default argument being visible does not imply that a later429 // default argument is visible, so we can't just check the first one.430 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();431 I != N; ++I) {432 if (!S.hasVisibleDefaultArgument(433 ETD->getTemplateParameters()->getParam(I)) &&434 S.hasVisibleDefaultArgument(435 DTD->getTemplateParameters()->getParam(I)))436 return true;437 }438 }439 440 // VarDecl can have incomplete array types, prefer the one with more complete441 // 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 name472 // that is not a typedef name and the other declarations shall all refer to473 // the same variable, non-static data member, or enumerator, or all refer474 // to functions and function templates; in this case the class name or475 // enumeration name is hidden.476 // C++ [basic.scope.hiding]p2:477 // A class name or enumeration name can be hidden by the name of a478 // variable, data member, function, or enumerator declared in the same479 // scope.480 // An UnresolvedUsingValueDecl always instantiates to one of these.481 D = D->getUnderlyingDecl();482 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||483 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||484 isa<UnresolvedUsingValueDecl>(D);485}486 487/// Resolves the result kind of this lookup.488void LookupResult::resolveKind() {489 unsigned N = Decls.size();490 491 // Fast case: no possible ambiguity.492 if (N == 0) {493 assert(ResultKind == LookupResultKind::NotFound ||494 ResultKind == LookupResultKind::NotFoundInCurrentInstantiation);495 return;496 }497 498 // If there's a single decl, we need to examine it to decide what499 // kind of lookup this is.500 if (N == 1) {501 const NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();502 if (isa<FunctionTemplateDecl>(D))503 ResultKind = LookupResultKind::FoundOverloaded;504 else if (isa<UnresolvedUsingValueDecl>(D))505 ResultKind = LookupResultKind::FoundUnresolvedValue;506 return;507 }508 509 // Don't do any extra resolution if we've already resolved as ambiguous.510 if (ResultKind == LookupResultKind::Ambiguous)511 return;512 513 llvm::SmallDenseMap<const NamedDecl *, unsigned, 16> Unique;514 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;515 516 bool Ambiguous = false;517 bool ReferenceToPlaceHolderVariable = false;518 bool HasTag = false, HasFunction = false;519 bool HasFunctionTemplate = false, HasUnresolved = false;520 const NamedDecl *HasNonFunction = nullptr;521 522 llvm::SmallVector<const NamedDecl *, 4> EquivalentNonFunctions;523 llvm::BitVector RemovedDecls(N);524 525 for (unsigned I = 0; I < N; I++) {526 const NamedDecl *D = Decls[I]->getUnderlyingDecl();527 D = cast<NamedDecl>(D->getCanonicalDecl());528 529 // Ignore an invalid declaration unless it's the only one left.530 // Also ignore HLSLBufferDecl which not have name conflict with other Decls.531 if ((D->isInvalidDecl() || isa<HLSLBufferDecl>(D)) &&532 N - RemovedDecls.count() > 1) {533 RemovedDecls.set(I);534 continue;535 }536 537 // C++ [basic.scope.hiding]p2:538 // A class name or enumeration name can be hidden by the name of539 // an object, function, or enumerator declared in the same540 // 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 hidden543 // 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 scope562 // and, through using declarations and directives, across scopes. There is563 // no ambiguity if they all refer to the same type, so unique based on the564 // 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 this575 // 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 and586 // discard the other.587 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],588 Decls[*ExistingI]))589 Decls[*ExistingI] = Decls[I];590 RemovedDecls.set(I);591 continue;592 }593 594 // Otherwise, do some decl type analysis and then continue.595 596 if (isa<UnresolvedUsingValueDecl>(D)) {597 HasUnresolved = true;598 } else if (isa<TagDecl>(D)) {599 if (HasTag)600 Ambiguous = true;601 HasTag = true;602 } else if (isa<FunctionTemplateDecl>(D)) {603 HasFunction = true;604 HasFunctionTemplate = true;605 } else if (isa<FunctionDecl>(D)) {606 HasFunction = true;607 } else {608 if (HasNonFunction) {609 // If we're about to create an ambiguity between two declarations that610 // are equivalent, but one is an internal linkage declaration from one611 // module and the other is an internal linkage declaration from another612 // 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()) &&620 getContextForScopeMatching(D) ==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 with631 // the lookup result, in case the ambiguity is resolved by the caller.632 if (!EquivalentNonFunctions.empty() && !Ambiguous)633 getSema().diagnoseEquivalentInternalLinkageDeclarations(634 getNameLoc(), HasNonFunction, EquivalentNonFunctions);635 636 // Remove decls by replacing them with decls from the end (which637 // means that we need to iterate from the end) and then truncating638 // 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)648 setAmbiguous(LookupAmbiguityKind::AmbiguousReferenceToPlaceholderVariable);649 else if (Ambiguous)650 setAmbiguous(LookupAmbiguityKind::AmbiguousReference);651 else if (HasUnresolved)652 ResultKind = LookupResultKind::FoundUnresolvedValue;653 else if (N > 1 || HasFunctionTemplate)654 ResultKind = LookupResultKind::FoundOverloaded;655 else656 ResultKind = LookupResultKind::Found;657}658 659void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {660 CXXBasePaths::const_paths_iterator I, E;661 for (I = P.begin(), E = P.end(); I != E; ++I)662 for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;663 ++DI)664 addDecl(*DI);665}666 667void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {668 Paths = new CXXBasePaths;669 Paths->swap(P);670 addDeclsFromBasePaths(*Paths);671 resolveKind();672 setAmbiguous(LookupAmbiguityKind::AmbiguousBaseSubobjects);673}674 675void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {676 Paths = new CXXBasePaths;677 Paths->swap(P);678 addDeclsFromBasePaths(*Paths);679 resolveKind();680 setAmbiguous(LookupAmbiguityKind::AmbiguousBaseSubobjectTypes);681}682 683void LookupResult::print(raw_ostream &Out) {684 Out << Decls.size() << " result(s)";685 if (isAmbiguous()) Out << ", ambiguous";686 if (Paths) Out << ", base paths present";687 688 for (iterator I = begin(), E = end(); I != E; ++I) {689 Out << "\n";690 (*I)->print(Out, 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) {711 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),712 Sema::LookupTagName);713 S.LookupName(Result, S.TUScope);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);719 return S.Context.getCanonicalTagType(Decl);720}721 722/// Lookup an OpenCL typedef type.723static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {724 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),725 Sema::LookupOrdinaryName);726 S.LookupName(Result, S.TUScope);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);732 return S.Context.getTypedefType(ElaboratedTypeKeyword::None,733 /*Qualifier=*/std::nullopt, Decl);734}735 736/// Get the QualType instances of the return type and arguments for an OpenCL737/// 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 generic741/// 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 each745/// argument, ArgTypes contains QualTypes for the Cartesian product746/// of (vector sizes) x (types) .747static void GetQualTypesForOpenCLBuiltin(748 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,749 SmallVector<QualType, 1> &RetTypes,750 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {751 // Get the QualType instances of the return types.752 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];753 OCL2Qual(S, 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++) {759 SmallVector<QualType, 1> Ty;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 builtin768/// function.769/// \param Context (in) The ASTContext instance.770/// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic771/// type used as return type or as argument.772/// Only meaningful for generic types, otherwise equals 1.773/// \param FunctionList (out) List of FunctionTypes.774/// \param RetTypes (in) List of the possible return types.775/// \param ArgTypes (in) List of the possible types for the arguments.776static void GetOpenCLBuiltinFctOverloads(777 ASTContext &Context, unsigned GenTypeMaxCnt,778 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,779 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {780 FunctionProtoType::ExtProtoInfo PI(781 Context.getTargetInfo().getDefaultCallingConv());782 PI.Variadic = false;783 784 // Do not attempt to create any FunctionTypes if there are no return types,785 // which happens when a type belongs to a disabled extension.786 if (RetTypes.size() == 0)787 return;788 789 // Create FunctionTypes for each (gen)type.790 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {791 SmallVector<QualType, 5> ArgList;792 793 for (unsigned A = 0; A < ArgTypes.size(); A++) {794 // Bail out if there is an argument that has no available types.795 if (ArgTypes[A].size() == 0)796 return;797 798 // Builtins such as "max" have an "sgentype" argument that represents799 // the corresponding scalar type of a gentype. The number of gentypes800 // 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 a813/// non-null <Index, Len> pair, then the name is referencing an OpenCL814/// builtin function. Add all candidate signatures to the LookUpResult.815///816/// \param S (in) The Sema instance.817/// \param LR (inout) The LookupResult instance.818/// \param II (in) The identifier being resolved.819/// \param FctIndex (in) Starting index in the BuiltinTable.820/// \param Len (in) The signature list has Len elements.821static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR,822 IdentifierInfo *II,823 const unsigned FctIndex,824 const unsigned Len) {825 // The builtin function declaration uses generic types (gentype).826 bool HasGenType = false;827 828 // Maximum number of types contained in a generic type used as return type or829 // 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 currently839 // 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 is845 // not defined. This indicates that the extension is not supported by the846 // target, so the builtin function should not be available.847 StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];848 if (!Extensions.empty()) {849 SmallVector<StringRef, 2> ExtVec;850 Extensions.split(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 862 SmallVector<QualType, 1> RetTypes;863 SmallVector<SmallVector<QualType, 1>, 5> ArgTypes;864 865 // Obtain QualType lists for the function signature.866 GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,867 ArgTypes);868 if (GenTypeMaxCnt > 1) {869 HasGenType = true;870 }871 872 // Create function overload for each type combination.873 std::vector<QualType> FunctionList;874 GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,875 ArgTypes);876 877 SourceLocation Loc = LR.getNameLoc();878 DeclContext *Parent = Context.getTranslationUnitDecl();879 FunctionDecl *NewOpenCLBuiltin;880 881 for (const auto &FTy : FunctionList) {882 NewOpenCLBuiltin = FunctionDecl::Create(883 Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,884 S.getCurFPFeatures().isFPConstrained(), false,885 FTy->isFunctionProtoType());886 NewOpenCLBuiltin->setImplicit();887 888 // Create Decl objects for each parameter, adding them to the889 // FunctionDecl.890 const auto *FP = cast<FunctionProtoType>(FTy);891 SmallVector<ParmVarDecl *, 4> ParmList;892 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {893 ParmVarDecl *Parm = ParmVarDecl::Create(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 921bool Sema::LookupBuiltin(LookupResult &R) {922 Sema::LookupNameKind NameKind = R.getLookupKind();923 924 // If we didn't find a use of this identifier, and if the identifier925 // corresponds to a compiler builtin, create the decl object for the builtin926 // now, injecting it into translation unit scope, and return it.927 if (NameKind == Sema::LookupOrdinaryName ||928 NameKind == Sema::LookupRedeclarationWithLinkage) {929 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();930 if (II) {931 if (NameKind == Sema::LookupOrdinaryName) {932 if (getLangOpts().CPlusPlus) {933#define BuiltinTemplate(BIName)934#define CPlusPlusBuiltinTemplate(BIName) \935 if (II == getASTContext().get##BIName##Name()) { \936 R.addDecl(getASTContext().get##BIName##Decl()); \937 return true; \938 }939#include "clang/Basic/BuiltinTemplates.inc"940 }941 if (getLangOpts().HLSL) {942#define BuiltinTemplate(BIName)943#define HLSLBuiltinTemplate(BIName) \944 if (II == getASTContext().get##BIName##Name()) { \945 R.addDecl(getASTContext().get##BIName##Decl()); \946 return true; \947 }948#include "clang/Basic/BuiltinTemplates.inc"949 }950 }951 952 // Check if this is an OpenCL Builtin, and if so, insert its overloads.953 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {954 auto Index = isOpenCLBuiltin(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)965 RISCV().IntrinsicManager = CreateRISCVIntrinsicManager(*this);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 predefined976 // library functions like 'malloc'. Instead, we'll just error.977 if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) &&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" and995/// saves it for later use in building builtin declaration of996/// objc_msgSendSuper and objc_msgSendSuper_stret.997static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) {998 ASTContext &Context = Sema.Context;999 LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),1000 Sema::LookupTagName);1001 Sema.LookupName(Result, S);1002 if (Result.getResultKind() == LookupResultKind::Found)1003 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())1004 Context.setObjCSuperType(Context.getCanonicalTagType(TD));1005}1006 1007void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) {1008 if (ID == Builtin::BIobjc_msgSendSuper)1009 LookupPredefedObjCSuperType(*this, S);1010}1011 1012/// Determine whether we can declare a special member function within1013/// the class at this point.1014static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {1015 // We need to have a definition for the class.1016 if (!Class->getDefinition() || Class->isDependentContext())1017 return false;1018 1019 // We can't be in the middle of defining the class.1020 return !Class->isBeingDefined();1021}1022 1023void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {1024 if (!CanDeclareSpecialMemberFunction(Class))1025 return;1026 1027 // If the default constructor has not yet been declared, do so now.1028 if (Class->needsImplicitDefaultConstructor())1029 DeclareImplicitDefaultConstructor(Class);1030 1031 // If the copy constructor has not yet been declared, do so now.1032 if (Class->needsImplicitCopyConstructor())1033 DeclareImplicitCopyConstructor(Class);1034 1035 // If the copy assignment operator has not yet been declared, do so now.1036 if (Class->needsImplicitCopyAssignment())1037 DeclareImplicitCopyAssignment(Class);1038 1039 if (getLangOpts().CPlusPlus11) {1040 // If the move constructor has not yet been declared, do so now.1041 if (Class->needsImplicitMoveConstructor())1042 DeclareImplicitMoveConstructor(Class);1043 1044 // If the move assignment operator has not yet been declared, do so now.1045 if (Class->needsImplicitMoveAssignment())1046 DeclareImplicitMoveAssignment(Class);1047 }1048 1049 // If the destructor has not yet been declared, do so now.1050 if (Class->needsImplicitDestructor())1051 DeclareImplicitDestructor(Class);1052}1053 1054/// Determine whether this is the name of an implicitly-declared1055/// special member function.1056static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {1057 switch (Name.getNameKind()) {1058 case DeclarationName::CXXConstructorName:1059 case DeclarationName::CXXDestructorName:1060 return true;1061 1062 case DeclarationName::CXXOperatorName:1063 return Name.getCXXOverloadedOperator() == OO_Equal;1064 1065 default:1066 break;1067 }1068 1069 return false;1070}1071 1072/// If there are any implicit member functions with the given name1073/// that need to be declared in the given declaration context, do so.1074static void DeclareImplicitMemberFunctionsWithName(Sema &S,1075 DeclarationName Name,1076 SourceLocation Loc,1077 const DeclContext *DC) {1078 if (!DC)1079 return;1080 1081 switch (Name.getNameKind()) {1082 case DeclarationName::CXXConstructorName:1083 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))1084 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {1085 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);1086 if (Record->needsImplicitDefaultConstructor())1087 S.DeclareImplicitDefaultConstructor(Class);1088 if (Record->needsImplicitCopyConstructor())1089 S.DeclareImplicitCopyConstructor(Class);1090 if (S.getLangOpts().CPlusPlus11 &&1091 Record->needsImplicitMoveConstructor())1092 S.DeclareImplicitMoveConstructor(Class);1093 }1094 break;1095 1096 case DeclarationName::CXXDestructorName:1097 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))1098 if (Record->getDefinition() && Record->needsImplicitDestructor() &&1099 CanDeclareSpecialMemberFunction(Record))1100 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));1101 break;1102 1103 case DeclarationName::CXXOperatorName:1104 if (Name.getCXXOverloadedOperator() != OO_Equal)1105 break;1106 1107 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {1108 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {1109 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);1110 if (Record->needsImplicitCopyAssignment())1111 S.DeclareImplicitCopyAssignment(Class);1112 if (S.getLangOpts().CPlusPlus11 &&1113 Record->needsImplicitMoveAssignment())1114 S.DeclareImplicitMoveAssignment(Class);1115 }1116 }1117 break;1118 1119 case DeclarationName::CXXDeductionGuideName:1120 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);1121 break;1122 1123 default:1124 break;1125 }1126}1127 1128// Adds all qualifying matches for a name within a decl context to the1129// 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()1151 != DeclarationName::CXXConversionFunctionName ||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 by1158 // name lookup. Instead, any conversion function templates visible in the1159 // context of the use are considered. [...]1160 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);1161 if (!Record->isCompleteDefinition())1162 return Found;1163 1164 // For conversion operators, 'operator auto' should only match1165 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered1166 // as a candidate for template substitution.1167 auto *ContainedDeducedType =1168 R.getLookupName().getCXXNameType()->getContainedDeducedType();1169 if (R.getLookupName().getNameKind() ==1170 DeclarationName::CXXConversionFunctionName &&1171 ContainedDeducedType && ContainedDeducedType->isUndeducedType())1172 return Found;1173 1174 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),1175 UEnd = Record->conversion_end(); U != UEnd; ++U) {1176 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);1177 if (!ConvTemplate)1178 continue;1179 1180 // When we're performing lookup for the purposes of redeclaration, just1181 // add the conversion function template. When we deduce template1182 // arguments for specializations, we'll end up unifying the return1183 // 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 succeeds1192 // (14.9.2.3), the resulting specialization is used as if found by1193 // name lookup.1194 //1195 // When referencing a conversion function for any purpose other than1196 // a redeclaration (such that we'll be building an expression with the1197 // result), perform template argument deduction and place the1198 // specialization into the result set. We do this to avoid forcing all1199 // callers to perform special deduction for conversion functions.1200 TemplateDeductionInfo Info(R.getNameLoc());1201 FunctionDecl *Specialization = nullptr;1202 1203 const FunctionProtoType *ConvProto1204 = 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 conversion1208 // function to have, if it were to match the name given.1209 // FIXME: Calling convention!1210 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();1211 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);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 would1217 // expect the function to have.1218 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,1219 Specialization, Info) ==1220 TemplateDeductionResult::Success) {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 the1240 // 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 1250static bool isNamespaceOrTranslationUnitScope(Scope *S) {1251 if (DeclContext *Ctx = S->getEntity())1252 return Ctx->isFileContext();1253 return false;1254}1255 1256/// Find the outer declaration context from this scope. This indicates the1257/// context that we should search up to (exclusive) before considering the1258/// parent of the specified scope.1259static DeclContext *findOuterContext(Scope *S) {1260 for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())1261 if (DeclContext *DC = OuterS->getLookupEntity())1262 return DC;1263 return nullptr;1264}1265 1266namespace {1267/// An RAII object to specify that we want to find block scope extern1268/// declarations.1269struct FindLocalExternScope {1270 FindLocalExternScope(LookupResult &R)1271 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &1272 Decl::IDNS_LocalExtern) {1273 R.setFindLocalExtern(R.getIdentifierNamespace() &1274 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));1275 }1276 void restore() {1277 R.setFindLocalExtern(OldFindLocalExtern);1278 }1279 ~FindLocalExternScope() {1280 restore();1281 }1282 LookupResult &R;1283 bool OldFindLocalExtern;1284};1285} // end anonymous namespace1286 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 declare1295 if (isImplicitlyDeclaredMemberFunctionName(Name)) {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 if1303 // - it is a conversion-function-id whose conversion-type-id1304 // is dependent, or1305 // - it is operator= and the current class is a templated entity, or1306 // - the unqualified-id is the postfix-expression in a dependent call.1307 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&1308 Name.getCXXNameType()->isDependentType()) {1309 R.setNotFoundInCurrentInstantiation();1310 return false;1311 }1312 1313 // Implicitly declare member functions with the name we're looking for, if in1314 // fact we are in a scope where it matters.1315 1316 Scope *Initial = S;1317 IdentifierResolver::iterator1318 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 if1324 // they were declared in the nearest enclosing namespace which contains1325 // both the using-directive and the nominated namespace.1326 // [Note: in this context, "contains" means "contains directly or1327 // 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 scope1336 // }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 diagnose1354 // the invalid redeclaration.1355 1356 // Determine whether this (or a previous) declaration is1357 // out-of-scope.1358 if (!LeftStartingScope && !Initial->isDeclScope(*I))1359 LeftStartingScope = true;1360 1361 // If we found something outside of our starting scope that1362 // 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 the1369 // namespace scope1370 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 name1386 // specified is an unqualified name, a prior declaration is1387 // looked up without considering scopes that are outside the1388 // 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, since1396 // those entities will be found in the nearest enclosing1397 // 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 the1403 // function/method are present within the Scope.1404 if (Ctx->isFunctionOrMethod()) {1405 // If we have an Objective-C instance method, look for ivars1406 // 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 name1427 // 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 directives1440 // 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 by1462 // this qualified name lookup will also be on the identifier chain. For1463 // example, inside a class without any base classes, we never need to1464 // perform qualified lookup because all of the members are on top of the1465 // 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 all1481 // nominated namespaces by those using-directives.1482 //1483 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we1484 // 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 local1491 // 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 scopes1497 // that aren't strictly lexical, and therefore we walk through the1498 // 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 scope1505 // with this same name and in an acceptable identifier1506 // namespace, so that we can construct an overload set if we1507 // 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, since1523 // those entities will be found in the nearest enclosing1524 // non-transparent context.1525 if (Ctx->isTransparentContext())1526 continue;1527 1528 // If we have a context, and it's not a context stashed in the1529 // template parameter scope for an out-of-line definition, also1530 // 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 1557void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {1558 if (auto *M = getCurrentModule())1559 Context.mergeDefinitionIntoModule(ND, M);1560 else1561 // We're not building a module; just make the definition visible.1562 ND->setVisibleDespiteOwningModule();1563 1564 // If ND is a template declaration, make the template parameters1565 // visible too. They're not (necessarily) within a mergeable DeclContext.1566 if (auto *TD = dyn_cast<TemplateDecl>(ND))1567 for (auto *Param : *TD->getTemplateParameters())1568 makeMergedDefinitionVisible(Param);1569 1570 // If we import a named module which contains a header, and then we include a1571 // header which contains a definition of enums, we will skip parsing the enums1572 // in the current TU. But we need to ensure the visibility of the enum1573 // contants, since they are able to be found with the parents of their1574 // parents.1575 if (auto *ED = dyn_cast<EnumDecl>(ND);1576 ED && ED->isFromGlobalModule() && !ED->isScoped()) {1577 for (auto *ECD : ED->enumerators()) {1578 ECD->setVisibleDespiteOwningModule();1579 DeclContext *RedeclCtx = ED->getDeclContext()->getRedeclContext();1580 if (RedeclCtx->lookup(ECD->getDeclName()).empty())1581 RedeclCtx->makeDeclVisibleInContext(ECD);1582 }1583 }1584}1585 1586/// Find the module in which the given declaration was defined.1587static Module *getDefiningModule(Sema &S, Decl *Entity) {1588 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {1589 // If this function was instantiated from a template, the defining module is1590 // the module containing the pattern.1591 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())1592 Entity = Pattern;1593 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {1594 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())1595 Entity = Pattern;1596 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {1597 if (auto *Pattern = ED->getTemplateInstantiationPattern())1598 Entity = Pattern;1599 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {1600 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())1601 Entity = Pattern;1602 }1603 1604 // Walk up to the containing context. That might also have been instantiated1605 // from a template.1606 DeclContext *Context = Entity->getLexicalDeclContext();1607 if (Context->isFileContext())1608 return S.getOwningModule(Entity);1609 return getDefiningModule(S, cast<Decl>(Context));1610}1611 1612llvm::DenseSet<Module*> &Sema::getLookupModules() {1613 unsigned N = CodeSynthesisContexts.size();1614 for (unsigned I = CodeSynthesisContextLookupModules.size();1615 I != N; ++I) {1616 Module *M = CodeSynthesisContexts[I].Entity ?1617 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :1618 nullptr;1619 if (M && !LookupModulesCache.insert(M).second)1620 M = nullptr;1621 CodeSynthesisContextLookupModules.push_back(M);1622 }1623 return LookupModulesCache;1624}1625 1626bool Sema::isUsableModule(const Module *M) {1627 assert(M && "We shouldn't check nullness for module here");1628 // Return quickly if we cached the result.1629 if (UsableModuleUnitsCache.count(M))1630 return true;1631 1632 // If M is the global module fragment of the current translation unit. So it1633 // should be usable.1634 // [module.global.frag]p1:1635 // The global module fragment can be used to provide declarations that are1636 // attached to the global module and usable within the module unit.1637 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment) {1638 UsableModuleUnitsCache.insert(M);1639 return true;1640 }1641 1642 // Otherwise, the global module fragment from other translation unit is not1643 // directly usable.1644 if (M->isExplicitGlobalModule())1645 return false;1646 1647 Module *Current = getCurrentModule();1648 1649 // If we're not parsing a module, we can't use all the declarations from1650 // another module easily.1651 if (!Current)1652 return false;1653 1654 // For implicit global module, the decls in the same modules with the parent1655 // module should be visible to the decls in the implicit global module.1656 if (Current->isImplicitGlobalModule())1657 Current = Current->getTopLevelModule();1658 if (M->isImplicitGlobalModule())1659 M = M->getTopLevelModule();1660 1661 // If M is the module we're parsing or M and the current module unit lives in1662 // the same module, M should be usable.1663 //1664 // Note: It should be fine to search the vector `ModuleScopes` linearly since1665 // it should be generally small enough. There should be rare module fragments1666 // in a named module unit.1667 if (llvm::count_if(ModuleScopes,1668 [&M](const ModuleScope &MS) { return MS.Module == M; }) ||1669 getASTContext().isInSameModule(M, Current)) {1670 UsableModuleUnitsCache.insert(M);1671 return true;1672 }1673 1674 return false;1675}1676 1677bool Sema::hasVisibleMergedDefinition(const NamedDecl *Def) {1678 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))1679 if (isModuleVisible(Merged))1680 return true;1681 return false;1682}1683 1684bool Sema::hasMergedDefinitionInCurrentModule(const NamedDecl *Def) {1685 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))1686 if (isUsableModule(Merged))1687 return true;1688 return false;1689}1690 1691template <typename ParmDecl>1692static bool1693hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D,1694 llvm::SmallVectorImpl<Module *> *Modules,1695 Sema::AcceptableKind Kind) {1696 if (!D->hasDefaultArgument())1697 return false;1698 1699 llvm::SmallPtrSet<const ParmDecl *, 4> Visited;1700 while (D && Visited.insert(D).second) {1701 auto &DefaultArg = D->getDefaultArgStorage();1702 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))1703 return true;1704 1705 if (!DefaultArg.isInherited() && Modules) {1706 auto *NonConstD = const_cast<ParmDecl*>(D);1707 Modules->push_back(S.getOwningModule(NonConstD));1708 }1709 1710 // If there was a previous default argument, maybe its parameter is1711 // acceptable.1712 D = DefaultArg.getInheritedFrom();1713 }1714 return false;1715}1716 1717bool Sema::hasAcceptableDefaultArgument(1718 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,1719 Sema::AcceptableKind Kind) {1720 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))1721 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);1722 1723 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))1724 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);1725 1726 return ::hasAcceptableDefaultArgument(1727 *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);1728}1729 1730bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,1731 llvm::SmallVectorImpl<Module *> *Modules) {1732 return hasAcceptableDefaultArgument(D, Modules,1733 Sema::AcceptableKind::Visible);1734}1735 1736bool Sema::hasReachableDefaultArgument(1737 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1738 return hasAcceptableDefaultArgument(D, Modules,1739 Sema::AcceptableKind::Reachable);1740}1741 1742template <typename Filter>1743static bool1744hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,1745 llvm::SmallVectorImpl<Module *> *Modules, Filter F,1746 Sema::AcceptableKind Kind) {1747 bool HasFilteredRedecls = false;1748 1749 for (auto *Redecl : D->redecls()) {1750 auto *R = cast<NamedDecl>(Redecl);1751 if (!F(R))1752 continue;1753 1754 if (S.isAcceptable(R, Kind))1755 return true;1756 1757 HasFilteredRedecls = true;1758 1759 if (Modules)1760 Modules->push_back(R->getOwningModule());1761 }1762 1763 // Only return false if there is at least one redecl that is not filtered out.1764 if (HasFilteredRedecls)1765 return false;1766 1767 return true;1768}1769 1770static bool1771hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,1772 llvm::SmallVectorImpl<Module *> *Modules,1773 Sema::AcceptableKind Kind) {1774 return hasAcceptableDeclarationImpl(1775 S, D, Modules,1776 [](const NamedDecl *D) {1777 if (auto *RD = dyn_cast<CXXRecordDecl>(D))1778 return RD->getTemplateSpecializationKind() ==1779 TSK_ExplicitSpecialization;1780 if (auto *FD = dyn_cast<FunctionDecl>(D))1781 return FD->getTemplateSpecializationKind() ==1782 TSK_ExplicitSpecialization;1783 if (auto *VD = dyn_cast<VarDecl>(D))1784 return VD->getTemplateSpecializationKind() ==1785 TSK_ExplicitSpecialization;1786 llvm_unreachable("unknown explicit specialization kind");1787 },1788 Kind);1789}1790 1791bool Sema::hasVisibleExplicitSpecialization(1792 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1793 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,1794 Sema::AcceptableKind::Visible);1795}1796 1797bool Sema::hasReachableExplicitSpecialization(1798 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1799 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,1800 Sema::AcceptableKind::Reachable);1801}1802 1803static bool1804hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,1805 llvm::SmallVectorImpl<Module *> *Modules,1806 Sema::AcceptableKind Kind) {1807 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&1808 "not a member specialization");1809 return hasAcceptableDeclarationImpl(1810 S, D, Modules,1811 [](const NamedDecl *D) {1812 // If the specialization is declared at namespace scope, then it's a1813 // member specialization declaration. If it's lexically inside the class1814 // definition then it was instantiated.1815 //1816 // FIXME: This is a hack. There should be a better way to determine1817 // this.1818 // FIXME: What about MS-style explicit specializations declared within a1819 // class definition?1820 return D->getLexicalDeclContext()->isFileContext();1821 },1822 Kind);1823}1824 1825bool Sema::hasVisibleMemberSpecialization(1826 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1827 return hasAcceptableMemberSpecialization(*this, D, Modules,1828 Sema::AcceptableKind::Visible);1829}1830 1831bool Sema::hasReachableMemberSpecialization(1832 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1833 return hasAcceptableMemberSpecialization(*this, D, Modules,1834 Sema::AcceptableKind::Reachable);1835}1836 1837/// Determine whether a declaration is acceptable to name lookup.1838///1839/// This routine determines whether the declaration D is acceptable in the1840/// current lookup context, taking into account the current template1841/// instantiation stack. During template instantiation, a declaration is1842/// acceptable if it is acceptable from a module containing any entity on the1843/// template instantiation path (by instantiating a template, you allow it to1844/// see the declarations that your module can see, including those later on in1845/// your module).1846bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,1847 Sema::AcceptableKind Kind) {1848 assert(!D->isUnconditionallyVisible() &&1849 "should not call this: not in slow case");1850 1851 Module *DeclModule = SemaRef.getOwningModule(D);1852 assert(DeclModule && "hidden decl has no owning module");1853 1854 // If the owning module is visible, the decl is acceptable.1855 if (SemaRef.isModuleVisible(DeclModule,1856 D->isInvisibleOutsideTheOwningModule()))1857 return true;1858 1859 // Determine whether a decl context is a file context for the purpose of1860 // visibility/reachability. This looks through some (export and linkage spec)1861 // transparent contexts, but not others (enums).1862 auto IsEffectivelyFileContext = [](const DeclContext *DC) {1863 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||1864 isa<ExportDecl>(DC);1865 };1866 1867 // If this declaration is not at namespace scope1868 // then it is acceptable if its lexical parent has a acceptable definition.1869 DeclContext *DC = D->getLexicalDeclContext();1870 if (DC && !IsEffectivelyFileContext(DC)) {1871 // For a parameter, check whether our current template declaration's1872 // lexical context is acceptable, not whether there's some other acceptable1873 // definition of it, because parameters aren't "within" the definition.1874 //1875 // In C++ we need to check for a acceptable definition due to ODR merging,1876 // and in C we must not because each declaration of a function gets its own1877 // set of declarations for tags in prototype scope.1878 bool AcceptableWithinParent;1879 if (D->isTemplateParameter()) {1880 bool SearchDefinitions = true;1881 if (const auto *DCD = dyn_cast<Decl>(DC)) {1882 if (const auto *TD = DCD->getDescribedTemplate()) {1883 TemplateParameterList *TPL = TD->getTemplateParameters();1884 auto Index = getDepthAndIndex(D).second;1885 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;1886 }1887 }1888 if (SearchDefinitions)1889 AcceptableWithinParent =1890 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);1891 else1892 AcceptableWithinParent =1893 isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);1894 } else if (isa<ParmVarDecl>(D) ||1895 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))1896 AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);1897 else if (D->isModulePrivate()) {1898 // A module-private declaration is only acceptable if an enclosing lexical1899 // parent was merged with another definition in the current module.1900 AcceptableWithinParent = false;1901 do {1902 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {1903 AcceptableWithinParent = true;1904 break;1905 }1906 DC = DC->getLexicalParent();1907 } while (!IsEffectivelyFileContext(DC));1908 } else {1909 AcceptableWithinParent =1910 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);1911 }1912 1913 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&1914 Kind == Sema::AcceptableKind::Visible &&1915 // FIXME: Do something better in this case.1916 !SemaRef.getLangOpts().ModulesLocalVisibility) {1917 // Cache the fact that this declaration is implicitly visible because1918 // its parent has a visible definition.1919 D->setVisibleDespiteOwningModule();1920 }1921 return AcceptableWithinParent;1922 }1923 1924 if (Kind == Sema::AcceptableKind::Visible)1925 return false;1926 1927 assert(Kind == Sema::AcceptableKind::Reachable &&1928 "Additional Sema::AcceptableKind?");1929 return isReachableSlow(SemaRef, D);1930}1931 1932bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {1933 // The module might be ordinarily visible. For a module-private query, that1934 // means it is part of the current module.1935 if (ModulePrivate && isUsableModule(M))1936 return true;1937 1938 // For a query which is not module-private, that means it is in our visible1939 // module set.1940 if (!ModulePrivate && VisibleModules.isVisible(M))1941 return true;1942 1943 // Otherwise, it might be visible by virtue of the query being within a1944 // template instantiation or similar that is permitted to look inside M.1945 1946 // Find the extra places where we need to look.1947 const auto &LookupModules = getLookupModules();1948 if (LookupModules.empty())1949 return false;1950 1951 // If our lookup set contains the module, it's visible.1952 if (LookupModules.count(M))1953 return true;1954 1955 // The global module fragments are visible to its corresponding module unit.1956 // So the global module fragment should be visible if the its corresponding1957 // module unit is visible.1958 if (M->isGlobalModule() && LookupModules.count(M->getTopLevelModule()))1959 return true;1960 1961 // For a module-private query, that's everywhere we get to look.1962 if (ModulePrivate)1963 return false;1964 1965 // Check whether M is transitively exported to an import of the lookup set.1966 return llvm::any_of(LookupModules, [&](const Module *LookupM) {1967 return LookupM->isModuleVisible(M);1968 });1969}1970 1971// FIXME: Return false directly if we don't have an interface dependency on the1972// translation unit containing D.1973bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {1974 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");1975 1976 Module *DeclModule = SemaRef.getOwningModule(D);1977 assert(DeclModule && "hidden decl has no owning module");1978 1979 // Entities in header like modules are reachable only if they're visible.1980 if (DeclModule->isHeaderLikeModule())1981 return false;1982 1983 if (!D->isInAnotherModuleUnit())1984 return true;1985 1986 // [module.reach]/p3:1987 // A declaration D is reachable from a point P if:1988 // ...1989 // - D is not discarded ([module.global.frag]), appears in a translation unit1990 // that is reachable from P, and does not appear within a private module1991 // fragment.1992 //1993 // A declaration that's discarded in the GMF should be module-private.1994 if (D->isModulePrivate())1995 return false;1996 1997 Module *DeclTopModule = DeclModule->getTopLevelModule();1998 1999 // [module.reach]/p12000 // A translation unit U is necessarily reachable from a point P if U is a2001 // module interface unit on which the translation unit containing P has an2002 // interface dependency, or the translation unit containing P imports U, in2003 // either case prior to P ([module.import]).2004 //2005 // [module.import]/p102006 // A translation unit has an interface dependency on a translation unit U if2007 // it contains a declaration (possibly a module-declaration) that imports U2008 // or if it has an interface dependency on a translation unit that has an2009 // interface dependency on U.2010 //2011 // So we could conclude the module unit U is necessarily reachable if:2012 // (1) The module unit U is module interface unit.2013 // (2) The current unit has an interface dependency on the module unit U.2014 //2015 // Here we only check for the first condition. Since we couldn't see2016 // DeclModule if it isn't (transitively) imported.2017 if (DeclTopModule->isModuleInterfaceUnit())2018 return true;2019 2020 // [module.reach]/p1,22021 // A translation unit U is necessarily reachable from a point P if U is a2022 // module interface unit on which the translation unit containing P has an2023 // interface dependency, or the translation unit containing P imports U, in2024 // either case prior to P2025 //2026 // Additional translation units on2027 // which the point within the program has an interface dependency may be2028 // considered reachable, but it is unspecified which are and under what2029 // circumstances.2030 Module *CurrentM = SemaRef.getCurrentModule();2031 2032 // Directly imported module are necessarily reachable.2033 // Since we can't export import a module implementation partition unit, we2034 // don't need to count for Exports here.2035 if (CurrentM && CurrentM->getTopLevelModule()->Imports.count(DeclTopModule))2036 return true;2037 2038 // Then we treat all module implementation partition unit as unreachable.2039 return false;2040}2041 2042bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {2043 return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);2044}2045 2046bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {2047 // FIXME: If there are both visible and hidden declarations, we need to take2048 // into account whether redeclaration is possible. Example:2049 //2050 // Non-imported module:2051 // int f(T); // #12052 // Some TU:2053 // static int f(U); // #2, not a redeclaration of #12054 // int f(T); // #3, finds both, should link with #1 if T != U, but2055 // // with #2 if T == U; neither should be ambiguous.2056 for (auto *D : R) {2057 if (isVisible(D))2058 return true;2059 assert(D->isExternallyDeclarable() &&2060 "should not have hidden, non-externally-declarable result here");2061 }2062 2063 // This function is called once "New" is essentially complete, but before a2064 // previous declaration is attached. We can't query the linkage of "New" in2065 // general, because attaching the previous declaration can change the2066 // linkage of New to match the previous declaration.2067 //2068 // However, because we've just determined that there is no *visible* prior2069 // declaration, we can compute the linkage here. There are two possibilities:2070 //2071 // * This is not a redeclaration; it's safe to compute the linkage now.2072 //2073 // * This is a redeclaration of a prior declaration that is externally2074 // redeclarable. In that case, the linkage of the declaration is not2075 // changed by attaching the prior declaration, because both are externally2076 // declarable (and thus ExternalLinkage or VisibleNoLinkage).2077 //2078 // FIXME: This is subtle and fragile.2079 return New->isExternallyDeclarable();2080}2081 2082/// Retrieve the visible declaration corresponding to D, if any.2083///2084/// This routine determines whether the declaration D is visible in the current2085/// module, with the current imports. If not, it checks whether any2086/// redeclaration of D is visible, and if so, returns that declaration.2087///2088/// \returns D, or a visible previous declaration of D, whichever is more recent2089/// and visible. If no declaration of D is visible, returns null.2090static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,2091 unsigned IDNS) {2092 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");2093 2094 for (auto *RD : D->redecls()) {2095 // Don't bother with extra checks if we already know this one isn't visible.2096 if (RD == D)2097 continue;2098 2099 auto ND = cast<NamedDecl>(RD);2100 // FIXME: This is wrong in the case where the previous declaration is not2101 // visible in the same scope as D. This needs to be done much more2102 // carefully.2103 if (ND->isInIdentifierNamespace(IDNS) &&2104 LookupResult::isAvailableForLookup(SemaRef, ND))2105 return ND;2106 }2107 2108 return nullptr;2109}2110 2111bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,2112 llvm::SmallVectorImpl<Module *> *Modules) {2113 assert(!isVisible(D) && "not in slow case");2114 return hasAcceptableDeclarationImpl(2115 *this, D, Modules, [](const NamedDecl *) { return true; },2116 Sema::AcceptableKind::Visible);2117}2118 2119bool Sema::hasReachableDeclarationSlow(2120 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {2121 assert(!isReachable(D) && "not in slow case");2122 return hasAcceptableDeclarationImpl(2123 *this, D, Modules, [](const NamedDecl *) { return true; },2124 Sema::AcceptableKind::Reachable);2125}2126 2127NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {2128 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {2129 // Namespaces are a bit of a special case: we expect there to be a lot of2130 // redeclarations of some namespaces, all declarations of a namespace are2131 // essentially interchangeable, all declarations are found by name lookup2132 // if any is, and namespaces are never looked up during template2133 // instantiation. So we benefit from caching the check in this case, and2134 // it is correct to do so.2135 auto *Key = ND->getCanonicalDecl();2136 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))2137 return Acceptable;2138 auto *Acceptable = isVisible(getSema(), Key)2139 ? Key2140 : findAcceptableDecl(getSema(), Key, IDNS);2141 if (Acceptable)2142 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));2143 return Acceptable;2144 }2145 2146 return findAcceptableDecl(getSema(), D, IDNS);2147}2148 2149bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) {2150 // If this declaration is already visible, return it directly.2151 if (D->isUnconditionallyVisible())2152 return true;2153 2154 // During template instantiation, we can refer to hidden declarations, if2155 // they were visible in any module along the path of instantiation.2156 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);2157}2158 2159bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) {2160 if (D->isUnconditionallyVisible())2161 return true;2162 2163 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);2164}2165 2166bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) {2167 // We should check the visibility at the callsite already.2168 if (isVisible(SemaRef, ND))2169 return true;2170 2171 // Deduction guide lives in namespace scope generally, but it is just a2172 // hint to the compilers. What we actually lookup for is the generated member2173 // of the corresponding template. So it is sufficient to check the2174 // reachability of the template decl.2175 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())2176 return SemaRef.hasReachableDefinition(DeductionGuide);2177 2178 // FIXME: The lookup for allocation function is a standalone process.2179 // (We can find the logics in Sema::FindAllocationFunctions)2180 //2181 // Such structure makes it a problem when we instantiate a template2182 // declaration using placement allocation function if the placement2183 // allocation function is invisible.2184 // (See https://github.com/llvm/llvm-project/issues/59601)2185 //2186 // Here we workaround it by making the placement allocation functions2187 // always acceptable. The downside is that we can't diagnose the direct2188 // use of the invisible placement allocation functions. (Although such uses2189 // should be rare).2190 if (auto *FD = dyn_cast<FunctionDecl>(ND);2191 FD && FD->isReservedGlobalPlacementOperator())2192 return true;2193 2194 auto *DC = ND->getDeclContext();2195 // If ND is not visible and it is at namespace scope, it shouldn't be found2196 // by name lookup.2197 if (DC->isFileContext())2198 return false;2199 2200 // [module.interface]p72201 // Class and enumeration member names can be found by name lookup in any2202 // context in which a definition of the type is reachable.2203 //2204 // NOTE: The above wording may be problematic. See2205 // https://github.com/llvm/llvm-project/issues/131058 But it is much complext2206 // to adjust it in Sema's lookup process. Now we hacked it in ASTWriter. See2207 // the comments in ASTDeclContextNameLookupTrait::getLookupVisibility.2208 if (auto *TD = dyn_cast<TagDecl>(DC))2209 return SemaRef.hasReachableDefinition(TD);2210 2211 return false;2212}2213 2214bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,2215 bool ForceNoCPlusPlus) {2216 DeclarationName Name = R.getLookupName();2217 if (!Name) return false;2218 2219 LookupNameKind NameKind = R.getLookupKind();2220 2221 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {2222 // Unqualified name lookup in C/Objective-C is purely lexical, so2223 // search in the declarations attached to the name.2224 if (NameKind == Sema::LookupRedeclarationWithLinkage) {2225 // Find the nearest non-transparent declaration scope.2226 while (!(S->getFlags() & Scope::DeclScope) ||2227 (S->getEntity() && S->getEntity()->isTransparentContext()))2228 S = S->getParent();2229 }2230 2231 // When performing a scope lookup, we want to find local extern decls.2232 FindLocalExternScope FindLocals(R);2233 2234 // Scan up the scope chain looking for a decl that matches this2235 // identifier that is in the appropriate namespace. This search2236 // should not take long, as shadowing of names is uncommon, and2237 // deep shadowing is extremely uncommon.2238 bool LeftStartingScope = false;2239 2240 for (IdentifierResolver::iterator I = IdResolver.begin(Name),2241 IEnd = IdResolver.end();2242 I != IEnd; ++I)2243 if (NamedDecl *D = R.getAcceptableDecl(*I)) {2244 if (NameKind == LookupRedeclarationWithLinkage) {2245 // Determine whether this (or a previous) declaration is2246 // out-of-scope.2247 if (!LeftStartingScope && !S->isDeclScope(*I))2248 LeftStartingScope = true;2249 2250 // If we found something outside of our starting scope that2251 // does not have linkage, skip it.2252 if (LeftStartingScope && !((*I)->hasLinkage())) {2253 R.setShadowed();2254 continue;2255 }2256 }2257 else if (NameKind == LookupObjCImplicitSelfParam &&2258 !isa<ImplicitParamDecl>(*I))2259 continue;2260 2261 R.addDecl(D);2262 2263 // Check whether there are any other declarations with the same name2264 // and in the same scope.2265 if (I != IEnd) {2266 // Find the scope in which this declaration was declared (if it2267 // actually exists in a Scope).2268 while (S && !S->isDeclScope(D))2269 S = S->getParent();2270 2271 // If the scope containing the declaration is the translation unit,2272 // then we'll need to perform our checks based on the matching2273 // DeclContexts rather than matching scopes.2274 if (S && isNamespaceOrTranslationUnitScope(S))2275 S = nullptr;2276 2277 // Compute the DeclContext, if we need it.2278 DeclContext *DC = nullptr;2279 if (!S)2280 DC = (*I)->getDeclContext()->getRedeclContext();2281 2282 IdentifierResolver::iterator LastI = I;2283 for (++LastI; LastI != IEnd; ++LastI) {2284 if (S) {2285 // Match based on scope.2286 if (!S->isDeclScope(*LastI))2287 break;2288 } else {2289 // Match based on DeclContext.2290 DeclContext *LastDC2291 = (*LastI)->getDeclContext()->getRedeclContext();2292 if (!LastDC->Equals(DC))2293 break;2294 }2295 2296 // If the declaration is in the right namespace and visible, add it.2297 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))2298 R.addDecl(LastD);2299 }2300 2301 R.resolveKind();2302 }2303 2304 return true;2305 }2306 } else {2307 // Perform C++ unqualified name lookup.2308 if (CppLookupName(R, S))2309 return true;2310 }2311 2312 // If we didn't find a use of this identifier, and if the identifier2313 // corresponds to a compiler builtin, create the decl object for the builtin2314 // now, injecting it into translation unit scope, and return it.2315 if (AllowBuiltinCreation && LookupBuiltin(R))2316 return true;2317 2318 // If we didn't find a use of this identifier, the ExternalSource2319 // may be able to handle the situation.2320 // Note: some lookup failures are expected!2321 // See e.g. R.isForRedeclaration().2322 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));2323}2324 2325/// Perform qualified name lookup in the namespaces nominated by2326/// using directives by the given context.2327///2328/// C++98 [namespace.qual]p2:2329/// Given X::m (where X is a user-declared namespace), or given \::m2330/// (where X is the global namespace), let S be the set of all2331/// declarations of m in X and in the transitive closure of all2332/// namespaces nominated by using-directives in X and its used2333/// namespaces, except that using-directives are ignored in any2334/// namespace, including X, directly containing one or more2335/// declarations of m. No namespace is searched more than once in2336/// the lookup of a name. If S is the empty set, the program is2337/// ill-formed. Otherwise, if S has exactly one member, or if the2338/// context of the reference is a using-declaration2339/// (namespace.udecl), S is the required set of declarations of2340/// m. Otherwise if the use of m is not one that allows a unique2341/// declaration to be chosen from S, the program is ill-formed.2342///2343/// C++98 [namespace.qual]p5:2344/// During the lookup of a qualified namespace member name, if the2345/// lookup finds more than one declaration of the member, and if one2346/// declaration introduces a class name or enumeration name and the2347/// other declarations either introduce the same object, the same2348/// enumerator or a set of functions, the non-type name hides the2349/// class or enumeration name if and only if the declarations are2350/// from the same namespace; otherwise (the declarations are from2351/// different namespaces), the program is ill-formed.2352static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,2353 DeclContext *StartDC) {2354 assert(StartDC->isFileContext() && "start context is not a file context");2355 2356 // We have not yet looked into these namespaces, much less added2357 // their "using-children" to the queue.2358 SmallVector<NamespaceDecl*, 8> Queue;2359 2360 // We have at least added all these contexts to the queue.2361 llvm::SmallPtrSet<DeclContext*, 8> Visited;2362 Visited.insert(StartDC);2363 2364 // We have already looked into the initial namespace; seed the queue2365 // with its using-children.2366 for (auto *I : StartDC->using_directives()) {2367 NamespaceDecl *ND = I->getNominatedNamespace()->getFirstDecl();2368 if (S.isVisible(I) && Visited.insert(ND).second)2369 Queue.push_back(ND);2370 }2371 2372 // The easiest way to implement the restriction in [namespace.qual]p52373 // is to check whether any of the individual results found a tag2374 // and, if so, to declare an ambiguity if the final result is not2375 // a tag.2376 bool FoundTag = false;2377 bool FoundNonTag = false;2378 2379 LookupResult LocalR(LookupResult::Temporary, R);2380 2381 bool Found = false;2382 while (!Queue.empty()) {2383 NamespaceDecl *ND = Queue.pop_back_val();2384 2385 // We go through some convolutions here to avoid copying results2386 // between LookupResults.2387 bool UseLocal = !R.empty();2388 LookupResult &DirectR = UseLocal ? LocalR : R;2389 bool FoundDirect = LookupDirect(S, DirectR, ND);2390 2391 if (FoundDirect) {2392 // First do any local hiding.2393 DirectR.resolveKind();2394 2395 // If the local result is a tag, remember that.2396 if (DirectR.isSingleTagDecl())2397 FoundTag = true;2398 else2399 FoundNonTag = true;2400 2401 // Append the local results to the total results if necessary.2402 if (UseLocal) {2403 R.addAllDecls(LocalR);2404 LocalR.clear();2405 }2406 }2407 2408 // If we find names in this namespace, ignore its using directives.2409 if (FoundDirect) {2410 Found = true;2411 continue;2412 }2413 2414 for (auto *I : ND->using_directives()) {2415 NamespaceDecl *Nom = I->getNominatedNamespace();2416 if (S.isVisible(I) && Visited.insert(Nom).second)2417 Queue.push_back(Nom);2418 }2419 }2420 2421 if (Found) {2422 if (FoundTag && FoundNonTag)2423 R.setAmbiguousQualifiedTagHiding();2424 else2425 R.resolveKind();2426 }2427 2428 return Found;2429}2430 2431bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,2432 bool InUnqualifiedLookup) {2433 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");2434 2435 if (!R.getLookupName())2436 return false;2437 2438#ifndef NDEBUG2439 // Make sure that the declaration context is complete.2440 if (const auto *TD = dyn_cast<TagDecl>(LookupCtx);2441 TD && !TD->isDependentType() && TD->getDefinition() == nullptr)2442 llvm_unreachable("Declaration context must already be complete!");2443#endif2444 2445 struct QualifiedLookupInScope {2446 bool oldVal;2447 DeclContext *Context;2448 // Set flag in DeclContext informing debugger that we're looking for qualified name2449 QualifiedLookupInScope(DeclContext *ctx)2450 : oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) {2451 ctx->setUseQualifiedLookup();2452 }2453 ~QualifiedLookupInScope() {2454 Context->setUseQualifiedLookup(oldVal);2455 }2456 } QL(LookupCtx);2457 2458 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);2459 // FIXME: Per [temp.dep.general]p2, an unqualified name is also dependent2460 // if it's a dependent conversion-function-id or operator= where the current2461 // class is a templated entity. This should be handled in LookupName.2462 if (!InUnqualifiedLookup && !R.isForRedeclaration()) {2463 // C++23 [temp.dep.type]p5:2464 // A qualified name is dependent if2465 // - it is a conversion-function-id whose conversion-type-id2466 // is dependent, or2467 // - [...]2468 // - its lookup context is the current instantiation and it2469 // is operator=, or2470 // - [...]2471 if (DeclarationName Name = R.getLookupName();2472 Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&2473 Name.getCXXNameType()->isDependentType()) {2474 R.setNotFoundInCurrentInstantiation();2475 return false;2476 }2477 }2478 2479 if (LookupDirect(*this, R, LookupCtx)) {2480 R.resolveKind();2481 if (LookupRec)2482 R.setNamingClass(LookupRec);2483 return true;2484 }2485 2486 // Don't descend into implied contexts for redeclarations.2487 // C++98 [namespace.qual]p6:2488 // In a declaration for a namespace member in which the2489 // declarator-id is a qualified-id, given that the qualified-id2490 // for the namespace member has the form2491 // nested-name-specifier unqualified-id2492 // the unqualified-id shall name a member of the namespace2493 // designated by the nested-name-specifier.2494 // See also [class.mfct]p5 and [class.static.data]p2.2495 if (R.isForRedeclaration())2496 return false;2497 2498 // If this is a namespace, look it up in the implied namespaces.2499 if (LookupCtx->isFileContext())2500 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);2501 2502 // If this isn't a C++ class, we aren't allowed to look into base2503 // classes, we're done.2504 if (!LookupRec || !LookupRec->getDefinition())2505 return false;2506 2507 // We're done for lookups that can never succeed for C++ classes.2508 if (R.getLookupKind() == LookupOperatorName ||2509 R.getLookupKind() == LookupNamespaceName ||2510 R.getLookupKind() == LookupObjCProtocolName ||2511 R.getLookupKind() == LookupLabel)2512 return false;2513 2514 // If we're performing qualified name lookup into a dependent class,2515 // then we are actually looking into a current instantiation. If we have any2516 // dependent base classes, then we either have to delay lookup until2517 // template instantiation time (at which point all bases will be available)2518 // or we have to fail.2519 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&2520 LookupRec->hasAnyDependentBases()) {2521 R.setNotFoundInCurrentInstantiation();2522 return false;2523 }2524 2525 // Perform lookup into our base classes.2526 2527 DeclarationName Name = R.getLookupName();2528 unsigned IDNS = R.getIdentifierNamespace();2529 2530 // Look for this member in our base classes.2531 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,2532 CXXBasePath &Path) -> bool {2533 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();2534 // Drop leading non-matching lookup results from the declaration list so2535 // we don't need to consider them again below.2536 for (Path.Decls = BaseRecord->lookup(Name).begin();2537 Path.Decls != Path.Decls.end(); ++Path.Decls) {2538 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))2539 return true;2540 }2541 return false;2542 };2543 2544 CXXBasePaths Paths;2545 Paths.setOrigin(LookupRec);2546 if (!LookupRec->lookupInBases(BaseCallback, Paths))2547 return false;2548 2549 R.setNamingClass(LookupRec);2550 2551 // C++ [class.member.lookup]p2:2552 // [...] If the resulting set of declarations are not all from2553 // sub-objects of the same type, or the set has a nonstatic member2554 // and includes members from distinct sub-objects, there is an2555 // ambiguity and the program is ill-formed. Otherwise that set is2556 // the result of the lookup.2557 QualType SubobjectType;2558 int SubobjectNumber = 0;2559 AccessSpecifier SubobjectAccess = AS_none;2560 2561 // Check whether the given lookup result contains only static members.2562 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {2563 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)2564 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())2565 return false;2566 return true;2567 };2568 2569 bool TemplateNameLookup = R.isTemplateNameLookup();2570 2571 // Determine whether two sets of members contain the same members, as2572 // required by C++ [class.member.lookup]p6.2573 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,2574 DeclContext::lookup_iterator B) {2575 using Iterator = DeclContextLookupResult::iterator;2576 using Result = const void *;2577 2578 auto Next = [&](Iterator &It, Iterator End) -> Result {2579 while (It != End) {2580 NamedDecl *ND = *It++;2581 if (!ND->isInIdentifierNamespace(IDNS))2582 continue;2583 2584 // C++ [temp.local]p3:2585 // A lookup that finds an injected-class-name (10.2) can result in2586 // an ambiguity in certain cases (for example, if it is found in2587 // more than one base class). If all of the injected-class-names2588 // that are found refer to specializations of the same class2589 // template, and if the name is used as a template-name, the2590 // reference refers to the class template itself and not a2591 // specialization thereof, and is not ambiguous.2592 if (TemplateNameLookup)2593 if (auto *TD = getAsTemplateNameDecl(ND))2594 ND = TD;2595 2596 // C++ [class.member.lookup]p3:2597 // type declarations (including injected-class-names) are replaced by2598 // the types they designate2599 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl()))2600 return Context.getCanonicalTypeDeclType(TD).getAsOpaquePtr();2601 2602 return ND->getUnderlyingDecl()->getCanonicalDecl();2603 }2604 return nullptr;2605 };2606 2607 // We'll often find the declarations are in the same order. Handle this2608 // case (and the special case of only one declaration) efficiently.2609 Iterator AIt = A, BIt = B, AEnd, BEnd;2610 while (true) {2611 Result AResult = Next(AIt, AEnd);2612 Result BResult = Next(BIt, BEnd);2613 if (!AResult && !BResult)2614 return true;2615 if (!AResult || !BResult)2616 return false;2617 if (AResult != BResult) {2618 // Found a mismatch; carefully check both lists, accounting for the2619 // possibility of declarations appearing more than once.2620 llvm::SmallDenseMap<Result, bool, 32> AResults;2621 for (; AResult; AResult = Next(AIt, AEnd))2622 AResults.insert({AResult, /*FoundInB*/false});2623 unsigned Found = 0;2624 for (; BResult; BResult = Next(BIt, BEnd)) {2625 auto It = AResults.find(BResult);2626 if (It == AResults.end())2627 return false;2628 if (!It->second) {2629 It->second = true;2630 ++Found;2631 }2632 }2633 return AResults.size() == Found;2634 }2635 }2636 };2637 2638 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();2639 Path != PathEnd; ++Path) {2640 const CXXBasePathElement &PathElement = Path->back();2641 2642 // Pick the best (i.e. most permissive i.e. numerically lowest) access2643 // across all paths.2644 SubobjectAccess = std::min(SubobjectAccess, Path->Access);2645 2646 // Determine whether we're looking at a distinct sub-object or not.2647 if (SubobjectType.isNull()) {2648 // This is the first subobject we've looked at. Record its type.2649 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());2650 SubobjectNumber = PathElement.SubobjectNumber;2651 continue;2652 }2653 2654 if (SubobjectType !=2655 Context.getCanonicalType(PathElement.Base->getType())) {2656 // We found members of the given name in two subobjects of2657 // different types. If the declaration sets aren't the same, this2658 // lookup is ambiguous.2659 //2660 // FIXME: The language rule says that this applies irrespective of2661 // whether the sets contain only static members.2662 if (HasOnlyStaticMembers(Path->Decls) &&2663 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))2664 continue;2665 2666 R.setAmbiguousBaseSubobjectTypes(Paths);2667 return true;2668 }2669 2670 // FIXME: This language rule no longer exists. Checking for ambiguous base2671 // subobjects should be done as part of formation of a class member access2672 // expression (when converting the object parameter to the member's type).2673 if (SubobjectNumber != PathElement.SubobjectNumber) {2674 // We have a different subobject of the same type.2675 2676 // C++ [class.member.lookup]p5:2677 // A static member, a nested type or an enumerator defined in2678 // a base class T can unambiguously be found even if an object2679 // has more than one base class subobject of type T.2680 if (HasOnlyStaticMembers(Path->Decls))2681 continue;2682 2683 // We have found a nonstatic member name in multiple, distinct2684 // subobjects. Name lookup is ambiguous.2685 R.setAmbiguousBaseSubobjects(Paths);2686 return true;2687 }2688 }2689 2690 // Lookup in a base class succeeded; return these results.2691 2692 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();2693 I != E; ++I) {2694 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,2695 (*I)->getAccess());2696 if (NamedDecl *ND = R.getAcceptableDecl(*I))2697 R.addDecl(ND, AS);2698 }2699 R.resolveKind();2700 return true;2701}2702 2703bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,2704 CXXScopeSpec &SS) {2705 NestedNameSpecifier Qualifier = SS.getScopeRep();2706 if (Qualifier.getKind() == NestedNameSpecifier::Kind::MicrosoftSuper)2707 return LookupInSuper(R, Qualifier.getAsMicrosoftSuper());2708 return LookupQualifiedName(R, LookupCtx);2709}2710 2711bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,2712 QualType ObjectType, bool AllowBuiltinCreation,2713 bool EnteringContext) {2714 // When the scope specifier is invalid, don't even look for anything.2715 if (SS && SS->isInvalid())2716 return false;2717 2718 // Determine where to perform name lookup2719 DeclContext *DC = nullptr;2720 bool IsDependent = false;2721 if (!ObjectType.isNull()) {2722 // This nested-name-specifier occurs in a member access expression, e.g.,2723 // x->B::f, and we are looking into the type of the object.2724 assert((!SS || SS->isEmpty()) &&2725 "ObjectType and scope specifier cannot coexist");2726 DC = computeDeclContext(ObjectType);2727 IsDependent = !DC && ObjectType->isDependentType();2728 assert(((!DC && ObjectType->isDependentType()) ||2729 !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() ||2730 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&2731 "Caller should have completed object type");2732 } else if (SS && SS->isNotEmpty()) {2733 // This nested-name-specifier occurs after another nested-name-specifier,2734 // so long into the context associated with the prior nested-name-specifier.2735 if ((DC = computeDeclContext(*SS, EnteringContext))) {2736 // The declaration context must be complete.2737 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))2738 return false;2739 R.setContextRange(SS->getRange());2740 // FIXME: '__super' lookup semantics could be implemented by a2741 // LookupResult::isSuperLookup flag which skips the initial search of2742 // the lookup context in LookupQualified.2743 if (NestedNameSpecifier Qualifier = SS->getScopeRep();2744 Qualifier.getKind() == NestedNameSpecifier::Kind::MicrosoftSuper)2745 return LookupInSuper(R, Qualifier.getAsMicrosoftSuper());2746 }2747 IsDependent = !DC && isDependentScopeSpecifier(*SS);2748 } else {2749 // Perform unqualified name lookup starting in the given scope.2750 return LookupName(R, S, AllowBuiltinCreation);2751 }2752 2753 // If we were able to compute a declaration context, perform qualified name2754 // lookup in that context.2755 if (DC)2756 return LookupQualifiedName(R, DC);2757 else if (IsDependent)2758 // We could not resolve the scope specified to a specific declaration2759 // context, which means that SS refers to an unknown specialization.2760 // Name lookup can't find anything in this case.2761 R.setNotFoundInCurrentInstantiation();2762 return false;2763}2764 2765bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {2766 // The access-control rules we use here are essentially the rules for2767 // doing a lookup in Class that just magically skipped the direct2768 // members of Class itself. That is, the naming class is Class, and the2769 // access includes the access of the base.2770 for (const auto &BaseSpec : Class->bases()) {2771 auto *RD = BaseSpec.getType()->castAsCXXRecordDecl();2772 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());2773 Result.setBaseObjectType(Context.getCanonicalTagType(Class));2774 LookupQualifiedName(Result, RD);2775 2776 // Copy the lookup results into the target, merging the base's access into2777 // the path access.2778 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {2779 R.addDecl(I.getDecl(),2780 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),2781 I.getAccess()));2782 }2783 2784 Result.suppressDiagnostics();2785 }2786 2787 R.resolveKind();2788 R.setNamingClass(Class);2789 2790 return !R.empty();2791}2792 2793void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {2794 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");2795 2796 DeclarationName Name = Result.getLookupName();2797 SourceLocation NameLoc = Result.getNameLoc();2798 SourceRange LookupRange = Result.getContextRange();2799 2800 switch (Result.getAmbiguityKind()) {2801 case LookupAmbiguityKind::AmbiguousBaseSubobjects: {2802 CXXBasePaths *Paths = Result.getBasePaths();2803 QualType SubobjectType = Paths->front().back().Base->getType();2804 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)2805 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)2806 << LookupRange;2807 2808 DeclContext::lookup_iterator Found = Paths->front().Decls;2809 while (isa<CXXMethodDecl>(*Found) &&2810 cast<CXXMethodDecl>(*Found)->isStatic())2811 ++Found;2812 2813 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);2814 break;2815 }2816 2817 case LookupAmbiguityKind::AmbiguousBaseSubobjectTypes: {2818 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)2819 << Name << LookupRange;2820 2821 CXXBasePaths *Paths = Result.getBasePaths();2822 std::set<const NamedDecl *> DeclsPrinted;2823 for (CXXBasePaths::paths_iterator Path = Paths->begin(),2824 PathEnd = Paths->end();2825 Path != PathEnd; ++Path) {2826 const NamedDecl *D = *Path->Decls;2827 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))2828 continue;2829 if (DeclsPrinted.insert(D).second) {2830 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))2831 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)2832 << TD->getUnderlyingType();2833 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))2834 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)2835 << Context.getTypeDeclType(TD);2836 else2837 Diag(D->getLocation(), diag::note_ambiguous_member_found);2838 }2839 }2840 break;2841 }2842 2843 case LookupAmbiguityKind::AmbiguousTagHiding: {2844 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;2845 2846 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;2847 2848 for (auto *D : Result)2849 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {2850 TagDecls.insert(TD);2851 Diag(TD->getLocation(), diag::note_hidden_tag);2852 }2853 2854 for (auto *D : Result)2855 if (!isa<TagDecl>(D))2856 Diag(D->getLocation(), diag::note_hiding_object);2857 2858 // For recovery purposes, go ahead and implement the hiding.2859 LookupResult::Filter F = Result.makeFilter();2860 while (F.hasNext()) {2861 if (TagDecls.count(F.next()))2862 F.erase();2863 }2864 F.done();2865 break;2866 }2867 2868 case LookupAmbiguityKind::AmbiguousReferenceToPlaceholderVariable: {2869 Diag(NameLoc, diag::err_using_placeholder_variable) << Name << LookupRange;2870 DeclContext *DC = nullptr;2871 for (auto *D : Result) {2872 Diag(D->getLocation(), diag::note_reference_placeholder) << D;2873 if (DC != nullptr && DC != D->getDeclContext())2874 break;2875 DC = D->getDeclContext();2876 }2877 break;2878 }2879 2880 case LookupAmbiguityKind::AmbiguousReference: {2881 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;2882 2883 for (auto *D : Result)2884 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;2885 break;2886 }2887 }2888}2889 2890namespace {2891 struct AssociatedLookup {2892 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,2893 Sema::AssociatedNamespaceSet &Namespaces,2894 Sema::AssociatedClassSet &Classes)2895 : S(S), Namespaces(Namespaces), Classes(Classes),2896 InstantiationLoc(InstantiationLoc) {2897 }2898 2899 bool addClassTransitive(CXXRecordDecl *RD) {2900 Classes.insert(RD);2901 return ClassesTransitive.insert(RD);2902 }2903 2904 Sema &S;2905 Sema::AssociatedNamespaceSet &Namespaces;2906 Sema::AssociatedClassSet &Classes;2907 SourceLocation InstantiationLoc;2908 2909 private:2910 Sema::AssociatedClassSet ClassesTransitive;2911 };2912} // end anonymous namespace2913 2914static void2915addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);2916 2917// Given the declaration context \param Ctx of a class, class template or2918// enumeration, add the associated namespaces to \param Namespaces as described2919// in [basic.lookup.argdep]p2.2920static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,2921 DeclContext *Ctx) {2922 // The exact wording has been changed in C++14 as a result of2923 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally2924 // to all language versions since it is possible to return a local type2925 // from a lambda in C++11.2926 //2927 // C++14 [basic.lookup.argdep]p2:2928 // If T is a class type [...]. Its associated namespaces are the innermost2929 // enclosing namespaces of its associated classes. [...]2930 //2931 // If T is an enumeration type, its associated namespace is the innermost2932 // enclosing namespace of its declaration. [...]2933 2934 // We additionally skip inline namespaces. The innermost non-inline namespace2935 // contains all names of all its nested inline namespaces anyway, so we can2936 // replace the entire inline namespace tree with its root.2937 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())2938 Ctx = Ctx->getParent();2939 2940 // Actually it is fine to always do `Namespaces.insert(Ctx);` simply. But it2941 // may cause more allocations in Namespaces and more unnecessary lookups. So2942 // we'd like to insert the representative namespace only.2943 DeclContext *PrimaryCtx = Ctx->getPrimaryContext();2944 Decl *PrimaryD = cast<Decl>(PrimaryCtx);2945 Decl *D = cast<Decl>(Ctx);2946 ASTContext &AST = D->getASTContext();2947 2948 // TODO: Technically it is better to insert one namespace per module. e.g.,2949 //2950 // ```2951 // //--- first.cppm2952 // export module first;2953 // namespace ns { ... } // first namespace2954 //2955 // //--- m-partA.cppm2956 // export module m:partA;2957 // import first;2958 //2959 // namespace ns { ... }2960 // namespace ns { ... }2961 //2962 // //--- m-partB.cppm2963 // export module m:partB;2964 // import first;2965 // import :partA;2966 //2967 // namespace ns { ... }2968 // namespace ns { ... }2969 //2970 // ...2971 //2972 // //--- m-partN.cppm2973 // export module m:partN;2974 // import first;2975 // import :partA;2976 // ...2977 // import :part$(N-1);2978 //2979 // namespace ns { ... }2980 // namespace ns { ... }2981 //2982 // consume(ns::any_decl); // the lookup2983 // ```2984 //2985 // We should only insert once for all namespaces in module m.2986 if (D->isInNamedModule() &&2987 !AST.isInSameModule(D->getOwningModule(), PrimaryD->getOwningModule()))2988 Namespaces.insert(Ctx);2989 else2990 Namespaces.insert(PrimaryCtx);2991}2992 2993// Add the associated classes and namespaces for argument-dependent2994// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).2995static void2996addAssociatedClassesAndNamespaces(AssociatedLookup &Result,2997 const TemplateArgument &Arg) {2998 // C++ [basic.lookup.argdep]p2, last bullet:2999 // -- [...] ;3000 switch (Arg.getKind()) {3001 case TemplateArgument::Null:3002 break;3003 3004 case TemplateArgument::Type:3005 // [...] the namespaces and classes associated with the types of the3006 // template arguments provided for template type parameters (excluding3007 // template template parameters)3008 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());3009 break;3010 3011 case TemplateArgument::Template:3012 case TemplateArgument::TemplateExpansion: {3013 // [...] the namespaces in which any template template arguments are3014 // defined; and the classes in which any member templates used as3015 // template template arguments are defined.3016 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();3017 if (ClassTemplateDecl *ClassTemplate3018 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {3019 DeclContext *Ctx = ClassTemplate->getDeclContext();3020 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))3021 Result.Classes.insert(EnclosingClass);3022 // Add the associated namespace for this class.3023 CollectEnclosingNamespace(Result.Namespaces, Ctx);3024 }3025 break;3026 }3027 3028 case TemplateArgument::Declaration:3029 case TemplateArgument::Integral:3030 case TemplateArgument::Expression:3031 case TemplateArgument::NullPtr:3032 case TemplateArgument::StructuralValue:3033 // [Note: non-type template arguments do not contribute to the set of3034 // associated namespaces. ]3035 break;3036 3037 case TemplateArgument::Pack:3038 for (const auto &P : Arg.pack_elements())3039 addAssociatedClassesAndNamespaces(Result, P);3040 break;3041 }3042}3043 3044// Add the associated classes and namespaces for argument-dependent lookup3045// with an argument of class type (C++ [basic.lookup.argdep]p2).3046static void3047addAssociatedClassesAndNamespaces(AssociatedLookup &Result,3048 CXXRecordDecl *Class) {3049 3050 // Just silently ignore anything whose name is __va_list_tag.3051 if (Class->getDeclName() == Result.S.VAListTagName)3052 return;3053 3054 // C++ [basic.lookup.argdep]p2:3055 // [...]3056 // -- If T is a class type (including unions), its associated3057 // classes are: the class itself; the class of which it is a3058 // member, if any; and its direct and indirect base classes.3059 // Its associated namespaces are the innermost enclosing3060 // namespaces of its associated classes.3061 3062 // Add the class of which it is a member, if any.3063 DeclContext *Ctx = Class->getDeclContext();3064 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))3065 Result.Classes.insert(EnclosingClass);3066 3067 // Add the associated namespace for this class.3068 CollectEnclosingNamespace(Result.Namespaces, Ctx);3069 3070 // -- If T is a template-id, its associated namespaces and classes are3071 // the namespace in which the template is defined; for member3072 // templates, the member template's class; the namespaces and classes3073 // associated with the types of the template arguments provided for3074 // template type parameters (excluding template template parameters); the3075 // namespaces in which any template template arguments are defined; and3076 // the classes in which any member templates used as template template3077 // arguments are defined. [Note: non-type template arguments do not3078 // contribute to the set of associated namespaces. ]3079 if (ClassTemplateSpecializationDecl *Spec3080 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {3081 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();3082 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))3083 Result.Classes.insert(EnclosingClass);3084 // Add the associated namespace for this class.3085 CollectEnclosingNamespace(Result.Namespaces, Ctx);3086 3087 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();3088 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)3089 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);3090 }3091 3092 // Add the class itself. If we've already transitively visited this class,3093 // we don't need to visit base classes.3094 if (!Result.addClassTransitive(Class))3095 return;3096 3097 // Only recurse into base classes for complete types.3098 if (!Result.S.isCompleteType(Result.InstantiationLoc,3099 Result.S.Context.getCanonicalTagType(Class)))3100 return;3101 3102 // Add direct and indirect base classes along with their associated3103 // namespaces.3104 SmallVector<CXXRecordDecl *, 32> Bases;3105 Bases.push_back(Class);3106 while (!Bases.empty()) {3107 // Pop this class off the stack.3108 Class = Bases.pop_back_val();3109 3110 // Visit the base classes.3111 for (const auto &Base : Class->bases()) {3112 CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();3113 // In dependent contexts, we do ADL twice, and the first time around,3114 // the base type might be a dependent TemplateSpecializationType, or a3115 // TemplateTypeParmType. If that happens, simply ignore it.3116 // FIXME: If we want to support export, we probably need to add the3117 // namespace of the template in a TemplateSpecializationType, or even3118 // the classes and namespaces of known non-dependent arguments.3119 if (!BaseDecl)3120 continue;3121 if (Result.addClassTransitive(BaseDecl)) {3122 // Find the associated namespace for this base class.3123 DeclContext *BaseCtx = BaseDecl->getDeclContext();3124 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);3125 3126 // Make sure we visit the bases of this base class.3127 if (!BaseDecl->bases().empty())3128 Bases.push_back(BaseDecl);3129 }3130 }3131 }3132}3133 3134// Add the associated classes and namespaces for3135// argument-dependent lookup with an argument of type T3136// (C++ [basic.lookup.koenig]p2).3137static void3138addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {3139 // C++ [basic.lookup.koenig]p2:3140 //3141 // For each argument type T in the function call, there is a set3142 // of zero or more associated namespaces and a set of zero or more3143 // associated classes to be considered. The sets of namespaces and3144 // classes is determined entirely by the types of the function3145 // arguments (and the namespace of any template template3146 // argument). Typedef names and using-declarations used to specify3147 // the types do not contribute to this set. The sets of namespaces3148 // and classes are determined in the following way:3149 3150 SmallVector<const Type *, 16> Queue;3151 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();3152 3153 while (true) {3154 switch (T->getTypeClass()) {3155 3156#define TYPE(Class, Base)3157#define DEPENDENT_TYPE(Class, Base) case Type::Class:3158#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:3159#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:3160#define ABSTRACT_TYPE(Class, Base)3161#include "clang/AST/TypeNodes.inc"3162 // T is canonical. We can also ignore dependent types because3163 // we don't need to do ADL at the definition point, but if we3164 // wanted to implement template export (or if we find some other3165 // use for associated classes and namespaces...) this would be3166 // wrong.3167 break;3168 3169 // -- If T is a pointer to U or an array of U, its associated3170 // namespaces and classes are those associated with U.3171 case Type::Pointer:3172 T = cast<PointerType>(T)->getPointeeType().getTypePtr();3173 continue;3174 case Type::ConstantArray:3175 case Type::IncompleteArray:3176 case Type::VariableArray:3177 T = cast<ArrayType>(T)->getElementType().getTypePtr();3178 continue;3179 3180 // -- If T is a fundamental type, its associated sets of3181 // namespaces and classes are both empty.3182 case Type::Builtin:3183 break;3184 3185 // -- If T is a class type (including unions), its associated3186 // classes are: the class itself; the class of which it is3187 // a member, if any; and its direct and indirect base classes.3188 // Its associated namespaces are the innermost enclosing3189 // namespaces of its associated classes.3190 case Type::Record: {3191 // FIXME: This should use the original decl.3192 auto *Class = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl())3193 ->getDefinitionOrSelf();3194 addAssociatedClassesAndNamespaces(Result, Class);3195 break;3196 }3197 3198 // -- If T is an enumeration type, its associated namespace3199 // is the innermost enclosing namespace of its declaration.3200 // If it is a class member, its associated class is the3201 // member’s class; else it has no associated class.3202 case Type::Enum: {3203 // FIXME: This should use the original decl.3204 auto *Enum = T->castAsEnumDecl();3205 3206 DeclContext *Ctx = Enum->getDeclContext();3207 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))3208 Result.Classes.insert(EnclosingClass);3209 3210 // Add the associated namespace for this enumeration.3211 CollectEnclosingNamespace(Result.Namespaces, Ctx);3212 3213 break;3214 }3215 3216 // -- If T is a function type, its associated namespaces and3217 // classes are those associated with the function parameter3218 // types and those associated with the return type.3219 case Type::FunctionProto: {3220 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);3221 for (const auto &Arg : Proto->param_types())3222 Queue.push_back(Arg.getTypePtr());3223 // fallthrough3224 [[fallthrough]];3225 }3226 case Type::FunctionNoProto: {3227 const FunctionType *FnType = cast<FunctionType>(T);3228 T = FnType->getReturnType().getTypePtr();3229 continue;3230 }3231 3232 // -- If T is a pointer to a member function of a class X, its3233 // associated namespaces and classes are those associated3234 // with the function parameter types and return type,3235 // together with those associated with X.3236 //3237 // -- If T is a pointer to a data member of class X, its3238 // associated namespaces and classes are those associated3239 // with the member type together with those associated with3240 // X.3241 case Type::MemberPointer: {3242 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);3243 if (CXXRecordDecl *Class = MemberPtr->getMostRecentCXXRecordDecl())3244 addAssociatedClassesAndNamespaces(Result, Class);3245 T = MemberPtr->getPointeeType().getTypePtr();3246 continue;3247 }3248 3249 // As an extension, treat this like a normal pointer.3250 case Type::BlockPointer:3251 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();3252 continue;3253 3254 // References aren't covered by the standard, but that's such an3255 // obvious defect that we cover them anyway.3256 case Type::LValueReference:3257 case Type::RValueReference:3258 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();3259 continue;3260 3261 // These are fundamental types.3262 case Type::Vector:3263 case Type::ExtVector:3264 case Type::ConstantMatrix:3265 case Type::Complex:3266 case Type::BitInt:3267 break;3268 3269 // Non-deduced auto types only get here for error cases.3270 case Type::Auto:3271 case Type::DeducedTemplateSpecialization:3272 break;3273 3274 // If T is an Objective-C object or interface type, or a pointer to an3275 // object or interface type, the associated namespace is the global3276 // namespace.3277 case Type::ObjCObject:3278 case Type::ObjCInterface:3279 case Type::ObjCObjectPointer:3280 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());3281 break;3282 3283 // Atomic types are just wrappers; use the associations of the3284 // contained type.3285 case Type::Atomic:3286 T = cast<AtomicType>(T)->getValueType().getTypePtr();3287 continue;3288 case Type::Pipe:3289 T = cast<PipeType>(T)->getElementType().getTypePtr();3290 continue;3291 3292 // Array parameter types are treated as fundamental types.3293 case Type::ArrayParameter:3294 break;3295 3296 case Type::HLSLAttributedResource:3297 T = cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr();3298 break;3299 3300 // Inline SPIR-V types are treated as fundamental types.3301 case Type::HLSLInlineSpirv:3302 break;3303 }3304 3305 if (Queue.empty())3306 break;3307 T = Queue.pop_back_val();3308 }3309}3310 3311void Sema::FindAssociatedClassesAndNamespaces(3312 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,3313 AssociatedNamespaceSet &AssociatedNamespaces,3314 AssociatedClassSet &AssociatedClasses) {3315 AssociatedNamespaces.clear();3316 AssociatedClasses.clear();3317 3318 AssociatedLookup Result(*this, InstantiationLoc,3319 AssociatedNamespaces, AssociatedClasses);3320 3321 // C++ [basic.lookup.koenig]p2:3322 // For each argument type T in the function call, there is a set3323 // of zero or more associated namespaces and a set of zero or more3324 // associated classes to be considered. The sets of namespaces and3325 // classes is determined entirely by the types of the function3326 // arguments (and the namespace of any template template3327 // argument).3328 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {3329 Expr *Arg = Args[ArgIdx];3330 3331 if (Arg->getType() != Context.OverloadTy) {3332 addAssociatedClassesAndNamespaces(Result, Arg->getType());3333 continue;3334 }3335 3336 // [...] In addition, if the argument is the name or address of a3337 // set of overloaded functions and/or function templates, its3338 // associated classes and namespaces are the union of those3339 // associated with each of the members of the set: the namespace3340 // in which the function or function template is defined and the3341 // classes and namespaces associated with its (non-dependent)3342 // parameter types and return type.3343 OverloadExpr *OE = OverloadExpr::find(Arg).Expression;3344 3345 for (const NamedDecl *D : OE->decls()) {3346 // Look through any using declarations to find the underlying function.3347 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();3348 3349 // Add the classes and namespaces associated with the parameter3350 // types and return type of this function.3351 addAssociatedClassesAndNamespaces(Result, FDecl->getType());3352 }3353 }3354}3355 3356NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,3357 SourceLocation Loc,3358 LookupNameKind NameKind,3359 RedeclarationKind Redecl) {3360 LookupResult R(*this, Name, Loc, NameKind, Redecl);3361 LookupName(R, S);3362 return R.getAsSingle<NamedDecl>();3363}3364 3365void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,3366 UnresolvedSetImpl &Functions) {3367 // C++ [over.match.oper]p3:3368 // -- The set of non-member candidates is the result of the3369 // unqualified lookup of operator@ in the context of the3370 // expression according to the usual rules for name lookup in3371 // unqualified function calls (3.4.2) except that all member3372 // functions are ignored.3373 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);3374 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);3375 LookupName(Operators, S);3376 3377 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");3378 Functions.append(Operators.begin(), Operators.end());3379}3380 3381Sema::SpecialMemberOverloadResult3382Sema::LookupSpecialMember(CXXRecordDecl *RD, CXXSpecialMemberKind SM,3383 bool ConstArg, bool VolatileArg, bool RValueThis,3384 bool ConstThis, bool VolatileThis) {3385 assert(CanDeclareSpecialMemberFunction(RD) &&3386 "doing special member lookup into record that isn't fully complete");3387 RD = RD->getDefinition();3388 if (RValueThis || ConstThis || VolatileThis)3389 assert((SM == CXXSpecialMemberKind::CopyAssignment ||3390 SM == CXXSpecialMemberKind::MoveAssignment) &&3391 "constructors and destructors always have unqualified lvalue this");3392 if (ConstArg || VolatileArg)3393 assert((SM != CXXSpecialMemberKind::DefaultConstructor &&3394 SM != CXXSpecialMemberKind::Destructor) &&3395 "parameter-less special members can't have qualified arguments");3396 3397 // FIXME: Get the caller to pass in a location for the lookup.3398 SourceLocation LookupLoc = RD->getLocation();3399 3400 llvm::FoldingSetNodeID ID;3401 ID.AddPointer(RD);3402 ID.AddInteger(llvm::to_underlying(SM));3403 ID.AddInteger(ConstArg);3404 ID.AddInteger(VolatileArg);3405 ID.AddInteger(RValueThis);3406 ID.AddInteger(ConstThis);3407 ID.AddInteger(VolatileThis);3408 3409 void *InsertPoint;3410 SpecialMemberOverloadResultEntry *Result =3411 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);3412 3413 // This was already cached3414 if (Result)3415 return *Result;3416 3417 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();3418 Result = new (Result) SpecialMemberOverloadResultEntry(ID);3419 SpecialMemberCache.InsertNode(Result, InsertPoint);3420 3421 if (SM == CXXSpecialMemberKind::Destructor) {3422 if (RD->needsImplicitDestructor()) {3423 runWithSufficientStackSpace(RD->getLocation(), [&] {3424 DeclareImplicitDestructor(RD);3425 });3426 }3427 CXXDestructorDecl *DD = RD->getDestructor();3428 Result->setMethod(DD);3429 Result->setKind(DD && !DD->isDeleted()3430 ? SpecialMemberOverloadResult::Success3431 : SpecialMemberOverloadResult::NoMemberOrDeleted);3432 return *Result;3433 }3434 3435 // Prepare for overload resolution. Here we construct a synthetic argument3436 // if necessary and make sure that implicit functions are declared.3437 CanQualType CanTy = Context.getCanonicalTagType(RD);3438 DeclarationName Name;3439 Expr *Arg = nullptr;3440 unsigned NumArgs;3441 3442 QualType ArgType = CanTy;3443 ExprValueKind VK = VK_LValue;3444 3445 if (SM == CXXSpecialMemberKind::DefaultConstructor) {3446 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);3447 NumArgs = 0;3448 if (RD->needsImplicitDefaultConstructor()) {3449 runWithSufficientStackSpace(RD->getLocation(), [&] {3450 DeclareImplicitDefaultConstructor(RD);3451 });3452 }3453 } else {3454 if (SM == CXXSpecialMemberKind::CopyConstructor ||3455 SM == CXXSpecialMemberKind::MoveConstructor) {3456 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);3457 if (RD->needsImplicitCopyConstructor()) {3458 runWithSufficientStackSpace(RD->getLocation(), [&] {3459 DeclareImplicitCopyConstructor(RD);3460 });3461 }3462 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {3463 runWithSufficientStackSpace(RD->getLocation(), [&] {3464 DeclareImplicitMoveConstructor(RD);3465 });3466 }3467 } else {3468 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);3469 if (RD->needsImplicitCopyAssignment()) {3470 runWithSufficientStackSpace(RD->getLocation(), [&] {3471 DeclareImplicitCopyAssignment(RD);3472 });3473 }3474 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {3475 runWithSufficientStackSpace(RD->getLocation(), [&] {3476 DeclareImplicitMoveAssignment(RD);3477 });3478 }3479 }3480 3481 if (ConstArg)3482 ArgType.addConst();3483 if (VolatileArg)3484 ArgType.addVolatile();3485 3486 // This isn't /really/ specified by the standard, but it's implied3487 // we should be working from a PRValue in the case of move to ensure3488 // that we prefer to bind to rvalue references, and an LValue in the3489 // case of copy to ensure we don't bind to rvalue references.3490 // Possibly an XValue is actually correct in the case of move, but3491 // there is no semantic difference for class types in this restricted3492 // case.3493 if (SM == CXXSpecialMemberKind::CopyConstructor ||3494 SM == CXXSpecialMemberKind::CopyAssignment)3495 VK = VK_LValue;3496 else3497 VK = VK_PRValue;3498 }3499 3500 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);3501 3502 if (SM != CXXSpecialMemberKind::DefaultConstructor) {3503 NumArgs = 1;3504 Arg = &FakeArg;3505 }3506 3507 // Create the object argument3508 QualType ThisTy = CanTy;3509 if (ConstThis)3510 ThisTy.addConst();3511 if (VolatileThis)3512 ThisTy.addVolatile();3513 Expr::Classification Classification =3514 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)3515 .Classify(Context);3516 3517 // Now we perform lookup on the name we computed earlier and do overload3518 // resolution. Lookup is only performed directly into the class since there3519 // will always be a (possibly implicit) declaration to shadow any others.3520 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);3521 DeclContext::lookup_result R = RD->lookup(Name);3522 3523 if (R.empty()) {3524 // We might have no default constructor because we have a lambda's closure3525 // type, rather than because there's some other declared constructor.3526 // Every class has a copy/move constructor, copy/move assignment, and3527 // destructor.3528 assert(SM == CXXSpecialMemberKind::DefaultConstructor &&3529 "lookup for a constructor or assignment operator was empty");3530 Result->setMethod(nullptr);3531 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);3532 return *Result;3533 }3534 3535 // Copy the candidates as our processing of them may load new declarations3536 // from an external source and invalidate lookup_result.3537 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());3538 3539 for (NamedDecl *CandDecl : Candidates) {3540 if (CandDecl->isInvalidDecl())3541 continue;3542 3543 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);3544 auto CtorInfo = getConstructorInfo(Cand);3545 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {3546 if (SM == CXXSpecialMemberKind::CopyAssignment ||3547 SM == CXXSpecialMemberKind::MoveAssignment)3548 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,3549 llvm::ArrayRef(&Arg, NumArgs), OCS, true);3550 else if (CtorInfo)3551 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,3552 llvm::ArrayRef(&Arg, NumArgs), OCS,3553 /*SuppressUserConversions*/ true);3554 else3555 AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS,3556 /*SuppressUserConversions*/ true);3557 } else if (FunctionTemplateDecl *Tmpl =3558 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {3559 if (SM == CXXSpecialMemberKind::CopyAssignment ||3560 SM == CXXSpecialMemberKind::MoveAssignment)3561 AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy,3562 Classification,3563 llvm::ArrayRef(&Arg, NumArgs), OCS, true);3564 else if (CtorInfo)3565 AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl,3566 CtorInfo.FoundDecl, nullptr,3567 llvm::ArrayRef(&Arg, NumArgs), OCS, true);3568 else3569 AddTemplateOverloadCandidate(Tmpl, Cand, nullptr,3570 llvm::ArrayRef(&Arg, NumArgs), OCS, true);3571 } else {3572 assert(isa<UsingDecl>(Cand.getDecl()) &&3573 "illegal Kind of operator = Decl");3574 }3575 }3576 3577 OverloadCandidateSet::iterator Best;3578 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {3579 case OR_Success:3580 Result->setMethod(cast<CXXMethodDecl>(Best->Function));3581 Result->setKind(SpecialMemberOverloadResult::Success);3582 break;3583 3584 case OR_Deleted:3585 Result->setMethod(cast<CXXMethodDecl>(Best->Function));3586 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);3587 break;3588 3589 case OR_Ambiguous:3590 Result->setMethod(nullptr);3591 Result->setKind(SpecialMemberOverloadResult::Ambiguous);3592 break;3593 3594 case OR_No_Viable_Function:3595 Result->setMethod(nullptr);3596 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);3597 break;3598 }3599 3600 return *Result;3601}3602 3603CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {3604 SpecialMemberOverloadResult Result =3605 LookupSpecialMember(Class, CXXSpecialMemberKind::DefaultConstructor,3606 false, false, false, false, false);3607 3608 return cast_or_null<CXXConstructorDecl>(Result.getMethod());3609}3610 3611CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,3612 unsigned Quals) {3613 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&3614 "non-const, non-volatile qualifiers for copy ctor arg");3615 SpecialMemberOverloadResult Result = LookupSpecialMember(3616 Class, CXXSpecialMemberKind::CopyConstructor, Quals & Qualifiers::Const,3617 Quals & Qualifiers::Volatile, false, false, false);3618 3619 return cast_or_null<CXXConstructorDecl>(Result.getMethod());3620}3621 3622CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,3623 unsigned Quals) {3624 SpecialMemberOverloadResult Result = LookupSpecialMember(3625 Class, CXXSpecialMemberKind::MoveConstructor, Quals & Qualifiers::Const,3626 Quals & Qualifiers::Volatile, false, false, false);3627 3628 return cast_or_null<CXXConstructorDecl>(Result.getMethod());3629}3630 3631DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {3632 // If the implicit constructors have not yet been declared, do so now.3633 if (CanDeclareSpecialMemberFunction(Class)) {3634 runWithSufficientStackSpace(Class->getLocation(), [&] {3635 if (Class->needsImplicitDefaultConstructor())3636 DeclareImplicitDefaultConstructor(Class);3637 if (Class->needsImplicitCopyConstructor())3638 DeclareImplicitCopyConstructor(Class);3639 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())3640 DeclareImplicitMoveConstructor(Class);3641 });3642 }3643 3644 CanQualType T = Context.getCanonicalTagType(Class);3645 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);3646 return Class->lookup(Name);3647}3648 3649CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,3650 unsigned Quals, bool RValueThis,3651 unsigned ThisQuals) {3652 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&3653 "non-const, non-volatile qualifiers for copy assignment arg");3654 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&3655 "non-const, non-volatile qualifiers for copy assignment this");3656 SpecialMemberOverloadResult Result = LookupSpecialMember(3657 Class, CXXSpecialMemberKind::CopyAssignment, Quals & Qualifiers::Const,3658 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,3659 ThisQuals & Qualifiers::Volatile);3660 3661 return Result.getMethod();3662}3663 3664CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,3665 unsigned Quals,3666 bool RValueThis,3667 unsigned ThisQuals) {3668 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&3669 "non-const, non-volatile qualifiers for copy assignment this");3670 SpecialMemberOverloadResult Result = LookupSpecialMember(3671 Class, CXXSpecialMemberKind::MoveAssignment, Quals & Qualifiers::Const,3672 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,3673 ThisQuals & Qualifiers::Volatile);3674 3675 return Result.getMethod();3676}3677 3678CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {3679 return cast_or_null<CXXDestructorDecl>(3680 LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false, false,3681 false, false, false)3682 .getMethod());3683}3684 3685Sema::LiteralOperatorLookupResult3686Sema::LookupLiteralOperator(Scope *S, LookupResult &R,3687 ArrayRef<QualType> ArgTys, bool AllowRaw,3688 bool AllowTemplate, bool AllowStringTemplatePack,3689 bool DiagnoseMissing, StringLiteral *StringLit) {3690 LookupName(R, S);3691 assert(R.getResultKind() != LookupResultKind::Ambiguous &&3692 "literal operator lookup can't be ambiguous");3693 3694 // Filter the lookup results appropriately.3695 LookupResult::Filter F = R.makeFilter();3696 3697 bool AllowCooked = true;3698 bool FoundRaw = false;3699 bool FoundTemplate = false;3700 bool FoundStringTemplatePack = false;3701 bool FoundCooked = false;3702 3703 while (F.hasNext()) {3704 Decl *D = F.next();3705 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))3706 D = USD->getTargetDecl();3707 3708 // If the declaration we found is invalid, skip it.3709 if (D->isInvalidDecl()) {3710 F.erase();3711 continue;3712 }3713 3714 bool IsRaw = false;3715 bool IsTemplate = false;3716 bool IsStringTemplatePack = false;3717 bool IsCooked = false;3718 3719 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {3720 if (FD->getNumParams() == 1 &&3721 FD->getParamDecl(0)->getType()->getAs<PointerType>())3722 IsRaw = true;3723 else if (FD->getNumParams() == ArgTys.size()) {3724 IsCooked = true;3725 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {3726 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();3727 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {3728 IsCooked = false;3729 break;3730 }3731 }3732 }3733 }3734 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {3735 TemplateParameterList *Params = FD->getTemplateParameters();3736 if (Params->size() == 1) {3737 IsTemplate = true;3738 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {3739 // Implied but not stated: user-defined integer and floating literals3740 // only ever use numeric literal operator templates, not templates3741 // taking a parameter of class type.3742 F.erase();3743 continue;3744 }3745 3746 // A string literal template is only considered if the string literal3747 // is a well-formed template argument for the template parameter.3748 if (StringLit) {3749 SFINAETrap Trap(*this);3750 CheckTemplateArgumentInfo CTAI;3751 TemplateArgumentLoc Arg(3752 TemplateArgument(StringLit, /*IsCanonical=*/false), StringLit);3753 if (CheckTemplateArgument(3754 Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(),3755 /*ArgumentPackIndex=*/0, CTAI, CTAK_Specified) ||3756 Trap.hasErrorOccurred())3757 IsTemplate = false;3758 }3759 } else {3760 IsStringTemplatePack = true;3761 }3762 }3763 3764 if (AllowTemplate && StringLit && IsTemplate) {3765 FoundTemplate = true;3766 AllowRaw = false;3767 AllowCooked = false;3768 AllowStringTemplatePack = false;3769 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {3770 F.restart();3771 FoundRaw = FoundCooked = FoundStringTemplatePack = false;3772 }3773 } else if (AllowCooked && IsCooked) {3774 FoundCooked = true;3775 AllowRaw = false;3776 AllowTemplate = StringLit;3777 AllowStringTemplatePack = false;3778 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {3779 // Go through again and remove the raw and template decls we've3780 // already found.3781 F.restart();3782 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;3783 }3784 } else if (AllowRaw && IsRaw) {3785 FoundRaw = true;3786 } else if (AllowTemplate && IsTemplate) {3787 FoundTemplate = true;3788 } else if (AllowStringTemplatePack && IsStringTemplatePack) {3789 FoundStringTemplatePack = true;3790 } else {3791 F.erase();3792 }3793 }3794 3795 F.done();3796 3797 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template3798 // form for string literal operator templates.3799 if (StringLit && FoundTemplate)3800 return LOLR_Template;3801 3802 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching3803 // parameter type, that is used in preference to a raw literal operator3804 // or literal operator template.3805 if (FoundCooked)3806 return LOLR_Cooked;3807 3808 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal3809 // operator template, but not both.3810 if (FoundRaw && FoundTemplate) {3811 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();3812 for (const NamedDecl *D : R)3813 NoteOverloadCandidate(D, D->getUnderlyingDecl()->getAsFunction());3814 return LOLR_Error;3815 }3816 3817 if (FoundRaw)3818 return LOLR_Raw;3819 3820 if (FoundTemplate)3821 return LOLR_Template;3822 3823 if (FoundStringTemplatePack)3824 return LOLR_StringTemplatePack;3825 3826 // Didn't find anything we could use.3827 if (DiagnoseMissing) {3828 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)3829 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]3830 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw3831 << (AllowTemplate || AllowStringTemplatePack);3832 return LOLR_Error;3833 }3834 3835 return LOLR_ErrorNoDiagnostic;3836}3837 3838void ADLResult::insert(NamedDecl *New) {3839 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];3840 3841 // If we haven't yet seen a decl for this key, or the last decl3842 // was exactly this one, we're done.3843 if (Old == nullptr || Old == New) {3844 Old = New;3845 return;3846 }3847 3848 // Otherwise, decide which is a more recent redeclaration.3849 FunctionDecl *OldFD = Old->getAsFunction();3850 FunctionDecl *NewFD = New->getAsFunction();3851 3852 FunctionDecl *Cursor = NewFD;3853 while (true) {3854 Cursor = Cursor->getPreviousDecl();3855 3856 // If we got to the end without finding OldFD, OldFD is the newer3857 // declaration; leave things as they are.3858 if (!Cursor) return;3859 3860 // If we do find OldFD, then NewFD is newer.3861 if (Cursor == OldFD) break;3862 3863 // Otherwise, keep looking.3864 }3865 3866 Old = New;3867}3868 3869void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,3870 ArrayRef<Expr *> Args, ADLResult &Result) {3871 // Find all of the associated namespaces and classes based on the3872 // arguments we have.3873 AssociatedNamespaceSet AssociatedNamespaces;3874 AssociatedClassSet AssociatedClasses;3875 FindAssociatedClassesAndNamespaces(Loc, Args,3876 AssociatedNamespaces,3877 AssociatedClasses);3878 3879 // C++ [basic.lookup.argdep]p3:3880 // Let X be the lookup set produced by unqualified lookup (3.4.1)3881 // and let Y be the lookup set produced by argument dependent3882 // lookup (defined as follows). If X contains [...] then Y is3883 // empty. Otherwise Y is the set of declarations found in the3884 // namespaces associated with the argument types as described3885 // below. The set of declarations found by the lookup of the name3886 // is the union of X and Y.3887 //3888 // Here, we compute Y and add its members to the overloaded3889 // candidate set.3890 for (auto *NS : AssociatedNamespaces) {3891 // When considering an associated namespace, the lookup is the3892 // same as the lookup performed when the associated namespace is3893 // used as a qualifier (3.4.3.2) except that:3894 //3895 // -- Any using-directives in the associated namespace are3896 // ignored.3897 //3898 // -- Any namespace-scope friend functions declared in3899 // associated classes are visible within their respective3900 // namespaces even if they are not visible during an ordinary3901 // lookup (11.4).3902 //3903 // C++20 [basic.lookup.argdep] p4.33904 // -- are exported, are attached to a named module M, do not appear3905 // in the translation unit containing the point of the lookup, and3906 // have the same innermost enclosing non-inline namespace scope as3907 // a declaration of an associated entity attached to M.3908 DeclContext::lookup_result R = NS->lookup(Name);3909 for (auto *D : R) {3910 auto *Underlying = D;3911 if (auto *USD = dyn_cast<UsingShadowDecl>(D))3912 Underlying = USD->getTargetDecl();3913 3914 if (!isa<FunctionDecl>(Underlying) &&3915 !isa<FunctionTemplateDecl>(Underlying))3916 continue;3917 3918 // The declaration is visible to argument-dependent lookup if either3919 // it's ordinarily visible or declared as a friend in an associated3920 // class.3921 bool Visible = false;3922 for (D = D->getMostRecentDecl(); D;3923 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {3924 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {3925 if (isVisible(D)) {3926 Visible = true;3927 break;3928 }3929 3930 if (!getLangOpts().CPlusPlusModules)3931 continue;3932 3933 if (D->isInExportDeclContext()) {3934 Module *FM = D->getOwningModule();3935 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...3936 // exports are only valid in module purview and outside of any3937 // PMF (although a PMF should not even be present in a module3938 // with an import).3939 assert(FM &&3940 (FM->isNamedModule() || FM->isImplicitGlobalModule()) &&3941 !FM->isPrivateModule() && "bad export context");3942 // .. are attached to a named module M, do not appear in the3943 // translation unit containing the point of the lookup..3944 if (D->isInAnotherModuleUnit() &&3945 llvm::any_of(AssociatedClasses, [&](auto *E) {3946 // ... and have the same innermost enclosing non-inline3947 // namespace scope as a declaration of an associated entity3948 // attached to M3949 if (E->getOwningModule() != FM)3950 return false;3951 // TODO: maybe this could be cached when generating the3952 // associated namespaces / entities.3953 DeclContext *Ctx = E->getDeclContext();3954 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())3955 Ctx = Ctx->getParent();3956 return Ctx == NS;3957 })) {3958 Visible = true;3959 break;3960 }3961 }3962 } else if (D->getFriendObjectKind()) {3963 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());3964 // [basic.lookup.argdep]p4:3965 // Argument-dependent lookup finds all declarations of functions and3966 // function templates that3967 // - ...3968 // - are declared as a friend ([class.friend]) of any class with a3969 // reachable definition in the set of associated entities,3970 //3971 // FIXME: If there's a merged definition of D that is reachable, then3972 // the friend declaration should be considered.3973 if (AssociatedClasses.count(RD) && isReachable(D)) {3974 Visible = true;3975 break;3976 }3977 }3978 }3979 3980 // FIXME: Preserve D as the FoundDecl.3981 if (Visible)3982 Result.insert(Underlying);3983 }3984 }3985}3986 3987//----------------------------------------------------------------------------3988// Search for all visible declarations.3989//----------------------------------------------------------------------------3990VisibleDeclConsumer::~VisibleDeclConsumer() { }3991 3992bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }3993 3994namespace {3995 3996class ShadowContextRAII;3997 3998class VisibleDeclsRecord {3999public:4000 /// An entry in the shadow map, which is optimized to store a4001 /// single declaration (the common case) but can also store a list4002 /// of declarations.4003 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;4004 4005private:4006 /// A mapping from declaration names to the declarations that have4007 /// this name within a particular scope.4008 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;4009 4010 /// A list of shadow maps, which is used to model name hiding.4011 std::list<ShadowMap> ShadowMaps;4012 4013 /// The declaration contexts we have already visited.4014 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;4015 4016 friend class ShadowContextRAII;4017 4018public:4019 /// Determine whether we have already visited this context4020 /// (and, if not, note that we are going to visit that context now).4021 bool visitedContext(DeclContext *Ctx) {4022 return !VisitedContexts.insert(Ctx).second;4023 }4024 4025 bool alreadyVisitedContext(DeclContext *Ctx) {4026 return VisitedContexts.count(Ctx);4027 }4028 4029 /// Determine whether the given declaration is hidden in the4030 /// current scope.4031 ///4032 /// \returns the declaration that hides the given declaration, or4033 /// NULL if no such declaration exists.4034 NamedDecl *checkHidden(NamedDecl *ND);4035 4036 /// Add a declaration to the current shadow map.4037 void add(NamedDecl *ND) {4038 ShadowMaps.back()[ND->getDeclName()].push_back(ND);4039 }4040};4041 4042/// RAII object that records when we've entered a shadow context.4043class ShadowContextRAII {4044 VisibleDeclsRecord &Visible;4045 4046 typedef VisibleDeclsRecord::ShadowMap ShadowMap;4047 4048public:4049 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {4050 Visible.ShadowMaps.emplace_back();4051 }4052 4053 ~ShadowContextRAII() {4054 Visible.ShadowMaps.pop_back();4055 }4056};4057 4058} // end anonymous namespace4059 4060NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {4061 unsigned IDNS = ND->getIdentifierNamespace();4062 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();4063 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();4064 SM != SMEnd; ++SM) {4065 ShadowMap::iterator Pos = SM->find(ND->getDeclName());4066 if (Pos == SM->end())4067 continue;4068 4069 for (auto *D : Pos->second) {4070 // A tag declaration does not hide a non-tag declaration.4071 if (D->hasTagIdentifierNamespace() &&4072 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |4073 Decl::IDNS_ObjCProtocol)))4074 continue;4075 4076 // Protocols are in distinct namespaces from everything else.4077 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)4078 || (IDNS & Decl::IDNS_ObjCProtocol)) &&4079 D->getIdentifierNamespace() != IDNS)4080 continue;4081 4082 // Functions and function templates in the same scope overload4083 // rather than hide. FIXME: Look for hiding based on function4084 // signatures!4085 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&4086 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&4087 SM == ShadowMaps.rbegin())4088 continue;4089 4090 // A shadow declaration that's created by a resolved using declaration4091 // is not hidden by the same using declaration.4092 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&4093 cast<UsingShadowDecl>(ND)->getIntroducer() == D)4094 continue;4095 4096 // We've found a declaration that hides this one.4097 return D;4098 }4099 }4100 4101 return nullptr;4102}4103 4104namespace {4105class LookupVisibleHelper {4106public:4107 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,4108 bool LoadExternal)4109 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),4110 LoadExternal(LoadExternal) {}4111 4112 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,4113 bool IncludeGlobalScope) {4114 // Determine the set of using directives available during4115 // unqualified name lookup.4116 Scope *Initial = S;4117 UnqualUsingDirectiveSet UDirs(SemaRef);4118 if (SemaRef.getLangOpts().CPlusPlus) {4119 // Find the first namespace or translation-unit scope.4120 while (S && !isNamespaceOrTranslationUnitScope(S))4121 S = S->getParent();4122 4123 UDirs.visitScopeChain(Initial, S);4124 }4125 UDirs.done();4126 4127 // Look for visible declarations.4128 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);4129 Result.setAllowHidden(Consumer.includeHiddenDecls());4130 if (!IncludeGlobalScope)4131 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());4132 ShadowContextRAII Shadow(Visited);4133 lookupInScope(Initial, Result, UDirs);4134 }4135 4136 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,4137 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {4138 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);4139 Result.setAllowHidden(Consumer.includeHiddenDecls());4140 if (!IncludeGlobalScope)4141 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());4142 4143 ShadowContextRAII Shadow(Visited);4144 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,4145 /*InBaseClass=*/false);4146 }4147 4148private:4149 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,4150 bool QualifiedNameLookup, bool InBaseClass) {4151 if (!Ctx)4152 return;4153 4154 // Make sure we don't visit the same context twice.4155 if (Visited.visitedContext(Ctx->getPrimaryContext()))4156 return;4157 4158 Consumer.EnteredContext(Ctx);4159 4160 // Outside C++, lookup results for the TU live on identifiers.4161 if (isa<TranslationUnitDecl>(Ctx) &&4162 !Result.getSema().getLangOpts().CPlusPlus) {4163 auto &S = Result.getSema();4164 auto &Idents = S.Context.Idents;4165 4166 // Ensure all external identifiers are in the identifier table.4167 if (LoadExternal)4168 if (IdentifierInfoLookup *External =4169 Idents.getExternalIdentifierLookup()) {4170 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());4171 for (StringRef Name = Iter->Next(); !Name.empty();4172 Name = Iter->Next())4173 Idents.get(Name);4174 }4175 4176 // Walk all lookup results in the TU for each identifier.4177 for (const auto &Ident : Idents) {4178 for (auto I = S.IdResolver.begin(Ident.getValue()),4179 E = S.IdResolver.end();4180 I != E; ++I) {4181 if (S.IdResolver.isDeclInScope(*I, Ctx)) {4182 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {4183 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);4184 Visited.add(ND);4185 }4186 }4187 }4188 }4189 4190 return;4191 }4192 4193 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))4194 Result.getSema().ForceDeclarationOfImplicitMembers(Class);4195 4196 llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;4197 // We sometimes skip loading namespace-level results (they tend to be huge).4198 bool Load = LoadExternal ||4199 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));4200 // Enumerate all of the results in this context.4201 for (DeclContextLookupResult R :4202 Load ? Ctx->lookups()4203 : Ctx->noload_lookups(/*PreserveInternalState=*/false))4204 for (auto *D : R)4205 // Rather than visit immediately, we put ND into a vector and visit4206 // all decls, in order, outside of this loop. The reason is that4207 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)4208 // may invalidate the iterators used in the two4209 // loops above.4210 DeclsToVisit.push_back(D);4211 4212 for (auto *D : DeclsToVisit)4213 if (auto *ND = Result.getAcceptableDecl(D)) {4214 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);4215 Visited.add(ND);4216 }4217 4218 DeclsToVisit.clear();4219 4220 // Traverse using directives for qualified name lookup.4221 if (QualifiedNameLookup) {4222 ShadowContextRAII Shadow(Visited);4223 for (auto *I : Ctx->using_directives()) {4224 if (!Result.getSema().isVisible(I))4225 continue;4226 lookupInDeclContext(I->getNominatedNamespace(), Result,4227 QualifiedNameLookup, InBaseClass);4228 }4229 }4230 4231 // Traverse the contexts of inherited C++ classes.4232 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {4233 if (!Record->hasDefinition())4234 return;4235 4236 for (const auto &B : Record->bases()) {4237 QualType BaseType = B.getType();4238 4239 RecordDecl *RD;4240 if (BaseType->isDependentType()) {4241 if (!IncludeDependentBases) {4242 // Don't look into dependent bases, because name lookup can't look4243 // there anyway.4244 continue;4245 }4246 const auto *TST = BaseType->getAs<TemplateSpecializationType>();4247 if (!TST)4248 continue;4249 TemplateName TN = TST->getTemplateName();4250 const auto *TD =4251 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());4252 if (!TD)4253 continue;4254 RD = TD->getTemplatedDecl();4255 } else {4256 RD = BaseType->getAsCXXRecordDecl();4257 if (!RD)4258 continue;4259 }4260 4261 // FIXME: It would be nice to be able to determine whether referencing4262 // a particular member would be ambiguous. For example, given4263 //4264 // struct A { int member; };4265 // struct B { int member; };4266 // struct C : A, B { };4267 //4268 // void f(C *c) { c->### }4269 //4270 // accessing 'member' would result in an ambiguity. However, we4271 // could be smart enough to qualify the member with the base4272 // class, e.g.,4273 //4274 // c->B::member4275 //4276 // or4277 //4278 // c->A::member4279 4280 // Find results in this base class (and its bases).4281 ShadowContextRAII Shadow(Visited);4282 lookupInDeclContext(RD, Result, QualifiedNameLookup,4283 /*InBaseClass=*/true);4284 }4285 }4286 4287 // Traverse the contexts of Objective-C classes.4288 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {4289 // Traverse categories.4290 for (auto *Cat : IFace->visible_categories()) {4291 ShadowContextRAII Shadow(Visited);4292 lookupInDeclContext(Cat, Result, QualifiedNameLookup,4293 /*InBaseClass=*/false);4294 }4295 4296 // Traverse protocols.4297 for (auto *I : IFace->all_referenced_protocols()) {4298 ShadowContextRAII Shadow(Visited);4299 lookupInDeclContext(I, Result, QualifiedNameLookup,4300 /*InBaseClass=*/false);4301 }4302 4303 // Traverse the superclass.4304 if (IFace->getSuperClass()) {4305 ShadowContextRAII Shadow(Visited);4306 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,4307 /*InBaseClass=*/true);4308 }4309 4310 // If there is an implementation, traverse it. We do this to find4311 // synthesized ivars.4312 if (IFace->getImplementation()) {4313 ShadowContextRAII Shadow(Visited);4314 lookupInDeclContext(IFace->getImplementation(), Result,4315 QualifiedNameLookup, InBaseClass);4316 }4317 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {4318 for (auto *I : Protocol->protocols()) {4319 ShadowContextRAII Shadow(Visited);4320 lookupInDeclContext(I, Result, QualifiedNameLookup,4321 /*InBaseClass=*/false);4322 }4323 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {4324 for (auto *I : Category->protocols()) {4325 ShadowContextRAII Shadow(Visited);4326 lookupInDeclContext(I, Result, QualifiedNameLookup,4327 /*InBaseClass=*/false);4328 }4329 4330 // If there is an implementation, traverse it.4331 if (Category->getImplementation()) {4332 ShadowContextRAII Shadow(Visited);4333 lookupInDeclContext(Category->getImplementation(), Result,4334 QualifiedNameLookup, /*InBaseClass=*/true);4335 }4336 }4337 }4338 4339 void lookupInScope(Scope *S, LookupResult &Result,4340 UnqualUsingDirectiveSet &UDirs) {4341 // No clients run in this mode and it's not supported. Please add tests and4342 // remove the assertion if you start relying on it.4343 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");4344 4345 if (!S)4346 return;4347 4348 if (!S->getEntity() ||4349 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||4350 (S->getEntity())->isFunctionOrMethod()) {4351 FindLocalExternScope FindLocals(Result);4352 // Walk through the declarations in this Scope. The consumer might add new4353 // decls to the scope as part of deserialization, so make a copy first.4354 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());4355 for (Decl *D : ScopeDecls) {4356 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))4357 if ((ND = Result.getAcceptableDecl(ND))) {4358 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);4359 Visited.add(ND);4360 }4361 }4362 }4363 4364 DeclContext *Entity = S->getLookupEntity();4365 if (Entity) {4366 // Look into this scope's declaration context, along with any of its4367 // parent lookup contexts (e.g., enclosing classes), up to the point4368 // where we hit the context stored in the next outer scope.4369 DeclContext *OuterCtx = findOuterContext(S);4370 4371 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);4372 Ctx = Ctx->getLookupParent()) {4373 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {4374 if (Method->isInstanceMethod()) {4375 // For instance methods, look for ivars in the method's interface.4376 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),4377 Result.getNameLoc(),4378 Sema::LookupMemberName);4379 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {4380 lookupInDeclContext(IFace, IvarResult,4381 /*QualifiedNameLookup=*/false,4382 /*InBaseClass=*/false);4383 }4384 }4385 4386 // We've already performed all of the name lookup that we need4387 // to for Objective-C methods; the next context will be the4388 // outer scope.4389 break;4390 }4391 4392 if (Ctx->isFunctionOrMethod())4393 continue;4394 4395 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,4396 /*InBaseClass=*/false);4397 }4398 } else if (!S->getParent()) {4399 // Look into the translation unit scope. We walk through the translation4400 // unit's declaration context, because the Scope itself won't have all of4401 // the declarations if we loaded a precompiled header.4402 // FIXME: We would like the translation unit's Scope object to point to4403 // the translation unit, so we don't need this special "if" branch.4404 // However, doing so would force the normal C++ name-lookup code to look4405 // into the translation unit decl when the IdentifierInfo chains would4406 // suffice. Once we fix that problem (which is part of a more general4407 // "don't look in DeclContexts unless we have to" optimization), we can4408 // eliminate this.4409 Entity = Result.getSema().Context.getTranslationUnitDecl();4410 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,4411 /*InBaseClass=*/false);4412 }4413 4414 if (Entity) {4415 // Lookup visible declarations in any namespaces found by using4416 // directives.4417 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))4418 lookupInDeclContext(4419 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,4420 /*QualifiedNameLookup=*/false,4421 /*InBaseClass=*/false);4422 }4423 4424 // Lookup names in the parent scope.4425 ShadowContextRAII Shadow(Visited);4426 lookupInScope(S->getParent(), Result, UDirs);4427 }4428 4429private:4430 VisibleDeclsRecord Visited;4431 VisibleDeclConsumer &Consumer;4432 bool IncludeDependentBases;4433 bool LoadExternal;4434};4435} // namespace4436 4437void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,4438 VisibleDeclConsumer &Consumer,4439 bool IncludeGlobalScope, bool LoadExternal) {4440 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,4441 LoadExternal);4442 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);4443}4444 4445void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,4446 VisibleDeclConsumer &Consumer,4447 bool IncludeGlobalScope,4448 bool IncludeDependentBases, bool LoadExternal) {4449 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);4450 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);4451}4452 4453LabelDecl *Sema::LookupExistingLabel(IdentifierInfo *II, SourceLocation Loc) {4454 NamedDecl *Res = LookupSingleName(CurScope, II, Loc, LookupLabel,4455 RedeclarationKind::NotForRedeclaration);4456 // If we found a label, check to see if it is in the same context as us.4457 // When in a Block, we don't want to reuse a label in an enclosing function.4458 if (!Res || Res->getDeclContext() != CurContext)4459 return nullptr;4460 return cast<LabelDecl>(Res);4461}4462 4463LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,4464 SourceLocation GnuLabelLoc) {4465 if (GnuLabelLoc.isValid()) {4466 // Local label definitions always shadow existing labels.4467 auto *Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);4468 Scope *S = CurScope;4469 PushOnScopeChains(Res, S, true);4470 return cast<LabelDecl>(Res);4471 }4472 4473 // Not a GNU local label.4474 LabelDecl *Res = LookupExistingLabel(II, Loc);4475 if (!Res) {4476 // If not forward referenced or defined already, create the backing decl.4477 Res = LabelDecl::Create(Context, CurContext, Loc, II);4478 Scope *S = CurScope->getFnParent();4479 assert(S && "Not in a function?");4480 PushOnScopeChains(Res, S, true);4481 }4482 return Res;4483}4484 4485//===----------------------------------------------------------------------===//4486// Typo correction4487//===----------------------------------------------------------------------===//4488 4489static bool isCandidateViable(CorrectionCandidateCallback &CCC,4490 TypoCorrection &Candidate) {4491 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));4492 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;4493}4494 4495static void LookupPotentialTypoResult(Sema &SemaRef,4496 LookupResult &Res,4497 IdentifierInfo *Name,4498 Scope *S, CXXScopeSpec *SS,4499 DeclContext *MemberContext,4500 bool EnteringContext,4501 bool isObjCIvarLookup,4502 bool FindHidden);4503 4504/// Check whether the declarations found for a typo correction are4505/// visible. Set the correction's RequiresImport flag to true if none of the4506/// declarations are visible, false otherwise.4507static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {4508 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();4509 4510 for (/**/; DI != DE; ++DI)4511 if (!LookupResult::isVisible(SemaRef, *DI))4512 break;4513 // No filtering needed if all decls are visible.4514 if (DI == DE) {4515 TC.setRequiresImport(false);4516 return;4517 }4518 4519 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);4520 bool AnyVisibleDecls = !NewDecls.empty();4521 4522 for (/**/; DI != DE; ++DI) {4523 if (LookupResult::isVisible(SemaRef, *DI)) {4524 if (!AnyVisibleDecls) {4525 // Found a visible decl, discard all hidden ones.4526 AnyVisibleDecls = true;4527 NewDecls.clear();4528 }4529 NewDecls.push_back(*DI);4530 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())4531 NewDecls.push_back(*DI);4532 }4533 4534 if (NewDecls.empty())4535 TC = TypoCorrection();4536 else {4537 TC.setCorrectionDecls(NewDecls);4538 TC.setRequiresImport(!AnyVisibleDecls);4539 }4540}4541 4542// Fill the supplied vector with the IdentifierInfo pointers for each piece of4543// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",4544// fill the vector with the IdentifierInfo pointers for "foo" and "bar").4545static void getNestedNameSpecifierIdentifiers(4546 NestedNameSpecifier NNS,4547 SmallVectorImpl<const IdentifierInfo *> &Identifiers) {4548 switch (NNS.getKind()) {4549 case NestedNameSpecifier::Kind::Null:4550 Identifiers.clear();4551 return;4552 4553 case NestedNameSpecifier::Kind::Namespace: {4554 auto [Namespace, Prefix] = NNS.getAsNamespaceAndPrefix();4555 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);4556 if (const auto *NS = dyn_cast<NamespaceDecl>(Namespace);4557 NS && NS->isAnonymousNamespace())4558 return;4559 Identifiers.push_back(Namespace->getIdentifier());4560 return;4561 }4562 4563 case NestedNameSpecifier::Kind::Type: {4564 for (const Type *T = NNS.getAsType(); /**/; /**/) {4565 switch (T->getTypeClass()) {4566 case Type::DependentName: {4567 auto *DT = cast<DependentNameType>(T);4568 getNestedNameSpecifierIdentifiers(DT->getQualifier(), Identifiers);4569 Identifiers.push_back(DT->getIdentifier());4570 return;4571 }4572 case Type::TemplateSpecialization: {4573 TemplateName Name =4574 cast<TemplateSpecializationType>(T)->getTemplateName();4575 if (const DependentTemplateName *DTN =4576 Name.getAsDependentTemplateName()) {4577 getNestedNameSpecifierIdentifiers(DTN->getQualifier(), Identifiers);4578 if (const auto *II = DTN->getName().getIdentifier())4579 Identifiers.push_back(II);4580 return;4581 }4582 if (const QualifiedTemplateName *QTN =4583 Name.getAsQualifiedTemplateName()) {4584 getNestedNameSpecifierIdentifiers(QTN->getQualifier(), Identifiers);4585 Name = QTN->getUnderlyingTemplate();4586 }4587 if (const auto *TD = Name.getAsTemplateDecl(/*IgnoreDeduced=*/true))4588 Identifiers.push_back(TD->getIdentifier());4589 return;4590 }4591 case Type::SubstTemplateTypeParm:4592 T = cast<SubstTemplateTypeParmType>(T)4593 ->getReplacementType()4594 .getTypePtr();4595 continue;4596 case Type::TemplateTypeParm:4597 Identifiers.push_back(cast<TemplateTypeParmType>(T)->getIdentifier());4598 return;4599 case Type::Decltype:4600 return;4601 case Type::Enum:4602 case Type::Record:4603 case Type::InjectedClassName: {4604 auto *TT = cast<TagType>(T);4605 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);4606 Identifiers.push_back(TT->getDecl()->getIdentifier());4607 return;4608 }4609 case Type::Typedef: {4610 auto *TT = cast<TypedefType>(T);4611 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);4612 Identifiers.push_back(TT->getDecl()->getIdentifier());4613 return;4614 }4615 case Type::Using: {4616 auto *TT = cast<UsingType>(T);4617 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);4618 Identifiers.push_back(TT->getDecl()->getIdentifier());4619 return;4620 }4621 case Type::UnresolvedUsing: {4622 auto *TT = cast<UnresolvedUsingType>(T);4623 getNestedNameSpecifierIdentifiers(TT->getQualifier(), Identifiers);4624 Identifiers.push_back(TT->getDecl()->getIdentifier());4625 return;4626 }4627 default:4628 Identifiers.push_back(QualType(T, 0).getBaseTypeIdentifier());4629 return;4630 }4631 }4632 break;4633 }4634 4635 case NestedNameSpecifier::Kind::Global:4636 case NestedNameSpecifier::Kind::MicrosoftSuper:4637 return;4638 }4639}4640 4641void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,4642 DeclContext *Ctx, bool InBaseClass) {4643 // Don't consider hidden names for typo correction.4644 if (Hiding)4645 return;4646 4647 // Only consider entities with identifiers for names, ignoring4648 // special names (constructors, overloaded operators, selectors,4649 // etc.).4650 IdentifierInfo *Name = ND->getIdentifier();4651 if (!Name)4652 return;4653 4654 // Only consider visible declarations and declarations from modules with4655 // names that exactly match.4656 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)4657 return;4658 4659 FoundName(Name->getName());4660}4661 4662void TypoCorrectionConsumer::FoundName(StringRef Name) {4663 // Compute the edit distance between the typo and the name of this4664 // entity, and add the identifier to the list of results.4665 addName(Name, nullptr);4666}4667 4668void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {4669 // Compute the edit distance between the typo and this keyword,4670 // and add the keyword to the list of results.4671 addName(Keyword, /*ND=*/nullptr, /*NNS=*/std::nullopt, /*isKeyword=*/true);4672}4673 4674void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,4675 NestedNameSpecifier NNS, bool isKeyword) {4676 // Use a simple length-based heuristic to determine the minimum possible4677 // edit distance. If the minimum isn't good enough, bail out early.4678 StringRef TypoStr = Typo->getName();4679 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());4680 if (MinED && TypoStr.size() / MinED < 3)4681 return;4682 4683 // Compute an upper bound on the allowable edit distance, so that the4684 // edit-distance algorithm can short-circuit.4685 unsigned UpperBound = (TypoStr.size() + 2) / 3;4686 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);4687 if (ED > UpperBound) return;4688 4689 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);4690 if (isKeyword) TC.makeKeyword();4691 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());4692 addCorrection(TC);4693}4694 4695static const unsigned MaxTypoDistanceResultSets = 5;4696 4697void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {4698 StringRef TypoStr = Typo->getName();4699 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();4700 4701 // For very short typos, ignore potential corrections that have a different4702 // base identifier from the typo or which have a normalized edit distance4703 // longer than the typo itself.4704 if (TypoStr.size() < 3 &&4705 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))4706 return;4707 4708 // If the correction is resolved but is not viable, ignore it.4709 if (Correction.isResolved()) {4710 checkCorrectionVisibility(SemaRef, Correction);4711 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))4712 return;4713 }4714 4715 TypoResultList &CList =4716 CorrectionResults[Correction.getEditDistance(false)][Name];4717 4718 if (!CList.empty() && !CList.back().isResolved())4719 CList.pop_back();4720 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {4721 auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {4722 return TypoCorr.getCorrectionDecl() == NewND;4723 });4724 if (RI != CList.end()) {4725 // The Correction refers to a decl already in the list. No insertion is4726 // necessary and all further cases will return.4727 4728 auto IsDeprecated = [](Decl *D) {4729 while (D) {4730 if (D->isDeprecated())4731 return true;4732 D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());4733 }4734 return false;4735 };4736 4737 // Prefer non deprecated Corrections over deprecated and only then4738 // sort using an alphabetical order.4739 std::pair<bool, std::string> NewKey = {4740 IsDeprecated(Correction.getFoundDecl()),4741 Correction.getAsString(SemaRef.getLangOpts())};4742 4743 std::pair<bool, std::string> PrevKey = {4744 IsDeprecated(RI->getFoundDecl()),4745 RI->getAsString(SemaRef.getLangOpts())};4746 4747 if (NewKey < PrevKey)4748 *RI = Correction;4749 return;4750 }4751 }4752 if (CList.empty() || Correction.isResolved())4753 CList.push_back(Correction);4754 4755 while (CorrectionResults.size() > MaxTypoDistanceResultSets)4756 CorrectionResults.erase(std::prev(CorrectionResults.end()));4757}4758 4759void TypoCorrectionConsumer::addNamespaces(4760 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {4761 SearchNamespaces = true;4762 4763 for (auto KNPair : KnownNamespaces)4764 Namespaces.addNameSpecifier(KNPair.first);4765 4766 bool SSIsTemplate = false;4767 if (NestedNameSpecifier NNS = (SS ? SS->getScopeRep() : std::nullopt)) {4768 if (NNS.getKind() == NestedNameSpecifier::Kind::Type)4769 SSIsTemplate =4770 NNS.getAsType()->getTypeClass() == Type::TemplateSpecialization;4771 }4772 // Do not transform this into an iterator-based loop. The loop body can4773 // trigger the creation of further types (through lazy deserialization) and4774 // invalid iterators into this list.4775 auto &Types = SemaRef.getASTContext().getTypes();4776 for (unsigned I = 0; I != Types.size(); ++I) {4777 const auto *TI = Types[I];4778 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {4779 CD = CD->getCanonicalDecl();4780 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&4781 !CD->isUnion() && CD->getIdentifier() &&4782 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&4783 (CD->isBeingDefined() || CD->isCompleteDefinition()))4784 Namespaces.addNameSpecifier(CD);4785 }4786 }4787}4788 4789const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {4790 if (++CurrentTCIndex < ValidatedCorrections.size())4791 return ValidatedCorrections[CurrentTCIndex];4792 4793 CurrentTCIndex = ValidatedCorrections.size();4794 while (!CorrectionResults.empty()) {4795 auto DI = CorrectionResults.begin();4796 if (DI->second.empty()) {4797 CorrectionResults.erase(DI);4798 continue;4799 }4800 4801 auto RI = DI->second.begin();4802 if (RI->second.empty()) {4803 DI->second.erase(RI);4804 performQualifiedLookups();4805 continue;4806 }4807 4808 TypoCorrection TC = RI->second.pop_back_val();4809 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {4810 ValidatedCorrections.push_back(TC);4811 return ValidatedCorrections[CurrentTCIndex];4812 }4813 }4814 return ValidatedCorrections[0]; // The empty correction.4815}4816 4817bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {4818 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();4819 DeclContext *TempMemberContext = MemberContext;4820 CXXScopeSpec *TempSS = SS.get();4821retry_lookup:4822 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,4823 EnteringContext,4824 CorrectionValidator->IsObjCIvarLookup,4825 Name == Typo && !Candidate.WillReplaceSpecifier());4826 switch (Result.getResultKind()) {4827 case LookupResultKind::NotFound:4828 case LookupResultKind::NotFoundInCurrentInstantiation:4829 case LookupResultKind::FoundUnresolvedValue:4830 if (TempSS) {4831 // Immediately retry the lookup without the given CXXScopeSpec4832 TempSS = nullptr;4833 Candidate.WillReplaceSpecifier(true);4834 goto retry_lookup;4835 }4836 if (TempMemberContext) {4837 if (SS && !TempSS)4838 TempSS = SS.get();4839 TempMemberContext = nullptr;4840 goto retry_lookup;4841 }4842 if (SearchNamespaces)4843 QualifiedResults.push_back(Candidate);4844 break;4845 4846 case LookupResultKind::Ambiguous:4847 // We don't deal with ambiguities.4848 break;4849 4850 case LookupResultKind::Found:4851 case LookupResultKind::FoundOverloaded:4852 // Store all of the Decls for overloaded symbols4853 for (auto *TRD : Result)4854 Candidate.addCorrectionDecl(TRD);4855 checkCorrectionVisibility(SemaRef, Candidate);4856 if (!isCandidateViable(*CorrectionValidator, Candidate)) {4857 if (SearchNamespaces)4858 QualifiedResults.push_back(Candidate);4859 break;4860 }4861 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());4862 return true;4863 }4864 return false;4865}4866 4867void TypoCorrectionConsumer::performQualifiedLookups() {4868 unsigned TypoLen = Typo->getName().size();4869 for (const TypoCorrection &QR : QualifiedResults) {4870 for (const auto &NSI : Namespaces) {4871 DeclContext *Ctx = NSI.DeclCtx;4872 CXXRecordDecl *NamingClass = NSI.NameSpecifier.getAsRecordDecl();4873 4874 // If the current NestedNameSpecifier refers to a class and the4875 // current correction candidate is the name of that class, then skip4876 // it as it is unlikely a qualified version of the class' constructor4877 // is an appropriate correction.4878 if (NamingClass &&4879 NamingClass->getIdentifier() == QR.getCorrectionAsIdentifierInfo())4880 continue;4881 4882 TypoCorrection TC(QR);4883 TC.ClearCorrectionDecls();4884 TC.setCorrectionSpecifier(NSI.NameSpecifier);4885 TC.setQualifierDistance(NSI.EditDistance);4886 TC.setCallbackDistance(0); // Reset the callback distance4887 4888 // If the current correction candidate and namespace combination are4889 // too far away from the original typo based on the normalized edit4890 // distance, then skip performing a qualified name lookup.4891 unsigned TmpED = TC.getEditDistance(true);4892 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&4893 TypoLen / TmpED < 3)4894 continue;4895 4896 Result.clear();4897 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());4898 if (!SemaRef.LookupQualifiedName(Result, Ctx))4899 continue;4900 4901 // Any corrections added below will be validated in subsequent4902 // iterations of the main while() loop over the Consumer's contents.4903 switch (Result.getResultKind()) {4904 case LookupResultKind::Found:4905 case LookupResultKind::FoundOverloaded: {4906 if (SS && SS->isValid()) {4907 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());4908 std::string OldQualified;4909 llvm::raw_string_ostream OldOStream(OldQualified);4910 SS->getScopeRep().print(OldOStream, SemaRef.getPrintingPolicy());4911 OldOStream << Typo->getName();4912 // If correction candidate would be an identical written qualified4913 // identifier, then the existing CXXScopeSpec probably included a4914 // typedef that didn't get accounted for properly.4915 if (OldOStream.str() == NewQualified)4916 break;4917 }4918 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();4919 TRD != TRDEnd; ++TRD) {4920 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),4921 NamingClass,4922 TRD.getPair()) == Sema::AR_accessible)4923 TC.addCorrectionDecl(*TRD);4924 }4925 if (TC.isResolved()) {4926 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());4927 addCorrection(TC);4928 }4929 break;4930 }4931 case LookupResultKind::NotFound:4932 case LookupResultKind::NotFoundInCurrentInstantiation:4933 case LookupResultKind::Ambiguous:4934 case LookupResultKind::FoundUnresolvedValue:4935 break;4936 }4937 }4938 }4939 QualifiedResults.clear();4940}4941 4942TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(4943 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)4944 : Context(Context), CurContextChain(buildContextChain(CurContext)) {4945 if (NestedNameSpecifier NNS =4946 CurScopeSpec ? CurScopeSpec->getScopeRep() : std::nullopt) {4947 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);4948 NNS.print(SpecifierOStream, Context.getPrintingPolicy());4949 4950 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);4951 }4952 // Build the list of identifiers that would be used for an absolute4953 // (from the global context) NestedNameSpecifier referring to the current4954 // context.4955 for (DeclContext *C : llvm::reverse(CurContextChain)) {4956 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))4957 CurContextIdentifiers.push_back(ND->getIdentifier());4958 }4959 4960 // Add the global context as a NestedNameSpecifier4961 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),4962 NestedNameSpecifier::getGlobal(), 1};4963 DistanceMap[1].push_back(SI);4964}4965 4966auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(4967 DeclContext *Start) -> DeclContextList {4968 assert(Start && "Building a context chain from a null context");4969 DeclContextList Chain;4970 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;4971 DC = DC->getLookupParent()) {4972 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);4973 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&4974 !(ND && ND->isAnonymousNamespace()))4975 Chain.push_back(DC->getPrimaryContext());4976 }4977 return Chain;4978}4979 4980unsigned4981TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(4982 DeclContextList &DeclChain, NestedNameSpecifier &NNS) {4983 unsigned NumSpecifiers = 0;4984 for (DeclContext *C : llvm::reverse(DeclChain)) {4985 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {4986 NNS = NestedNameSpecifier(Context, ND, NNS);4987 ++NumSpecifiers;4988 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {4989 QualType T = Context.getTagType(ElaboratedTypeKeyword::None, NNS, RD,4990 /*OwnsTag=*/false);4991 NNS = NestedNameSpecifier(T.getTypePtr());4992 ++NumSpecifiers;4993 }4994 }4995 return NumSpecifiers;4996}4997 4998void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(4999 DeclContext *Ctx) {5000 NestedNameSpecifier NNS = std::nullopt;5001 unsigned NumSpecifiers = 0;5002 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));5003 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);5004 5005 // Eliminate common elements from the two DeclContext chains.5006 for (DeclContext *C : llvm::reverse(CurContextChain)) {5007 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)5008 break;5009 NamespaceDeclChain.pop_back();5010 }5011 5012 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain5013 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);5014 5015 // Add an explicit leading '::' specifier if needed.5016 if (NamespaceDeclChain.empty()) {5017 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.5018 NNS = NestedNameSpecifier::getGlobal();5019 NumSpecifiers =5020 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);5021 } else if (NamedDecl *ND =5022 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {5023 IdentifierInfo *Name = ND->getIdentifier();5024 bool SameNameSpecifier = false;5025 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {5026 std::string NewNameSpecifier;5027 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);5028 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;5029 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);5030 NNS.print(SpecifierOStream, Context.getPrintingPolicy());5031 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;5032 }5033 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {5034 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.5035 NNS = NestedNameSpecifier::getGlobal();5036 NumSpecifiers =5037 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);5038 }5039 }5040 5041 // If the built NestedNameSpecifier would be replacing an existing5042 // NestedNameSpecifier, use the number of component identifiers that5043 // would need to be changed as the edit distance instead of the number5044 // of components in the built NestedNameSpecifier.5045 if (NNS && !CurNameSpecifierIdentifiers.empty()) {5046 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;5047 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);5048 NumSpecifiers =5049 llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),5050 llvm::ArrayRef(NewNameSpecifierIdentifiers));5051 }5052 5053 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};5054 DistanceMap[NumSpecifiers].push_back(SI);5055}5056 5057/// Perform name lookup for a possible result for typo correction.5058static void LookupPotentialTypoResult(Sema &SemaRef,5059 LookupResult &Res,5060 IdentifierInfo *Name,5061 Scope *S, CXXScopeSpec *SS,5062 DeclContext *MemberContext,5063 bool EnteringContext,5064 bool isObjCIvarLookup,5065 bool FindHidden) {5066 Res.suppressDiagnostics();5067 Res.clear();5068 Res.setLookupName(Name);5069 Res.setAllowHidden(FindHidden);5070 if (MemberContext) {5071 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {5072 if (isObjCIvarLookup) {5073 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {5074 Res.addDecl(Ivar);5075 Res.resolveKind();5076 return;5077 }5078 }5079 5080 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(5081 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {5082 Res.addDecl(Prop);5083 Res.resolveKind();5084 return;5085 }5086 }5087 5088 SemaRef.LookupQualifiedName(Res, MemberContext);5089 return;5090 }5091 5092 SemaRef.LookupParsedName(Res, S, SS,5093 /*ObjectType=*/QualType(),5094 /*AllowBuiltinCreation=*/false, EnteringContext);5095 5096 // Fake ivar lookup; this should really be part of5097 // LookupParsedName.5098 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {5099 if (Method->isInstanceMethod() && Method->getClassInterface() &&5100 (Res.empty() ||5101 (Res.isSingleResult() &&5102 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {5103 if (ObjCIvarDecl *IV5104 = Method->getClassInterface()->lookupInstanceVariable(Name)) {5105 Res.addDecl(IV);5106 Res.resolveKind();5107 }5108 }5109 }5110}5111 5112/// Add keywords to the consumer as possible typo corrections.5113static void AddKeywordsToConsumer(Sema &SemaRef,5114 TypoCorrectionConsumer &Consumer,5115 Scope *S, CorrectionCandidateCallback &CCC,5116 bool AfterNestedNameSpecifier) {5117 if (AfterNestedNameSpecifier) {5118 // For 'X::', we know exactly which keywords can appear next.5119 Consumer.addKeywordResult("template");5120 if (CCC.WantExpressionKeywords)5121 Consumer.addKeywordResult("operator");5122 return;5123 }5124 5125 if (CCC.WantObjCSuper)5126 Consumer.addKeywordResult("super");5127 5128 if (CCC.WantTypeSpecifiers) {5129 // Add type-specifier keywords to the set of results.5130 static const char *const CTypeSpecs[] = {5131 "char", "const", "double", "enum", "float", "int", "long", "short",5132 "signed", "struct", "union", "unsigned", "void", "volatile",5133 "_Complex",5134 // storage-specifiers as well5135 "extern", "inline", "static", "typedef"5136 };5137 5138 for (const auto *CTS : CTypeSpecs)5139 Consumer.addKeywordResult(CTS);5140 5141 if (SemaRef.getLangOpts().C99 && !SemaRef.getLangOpts().C2y)5142 Consumer.addKeywordResult("_Imaginary");5143 5144 if (SemaRef.getLangOpts().C99)5145 Consumer.addKeywordResult("restrict");5146 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)5147 Consumer.addKeywordResult("bool");5148 else if (SemaRef.getLangOpts().C99)5149 Consumer.addKeywordResult("_Bool");5150 5151 if (SemaRef.getLangOpts().CPlusPlus) {5152 Consumer.addKeywordResult("class");5153 Consumer.addKeywordResult("typename");5154 Consumer.addKeywordResult("wchar_t");5155 5156 if (SemaRef.getLangOpts().CPlusPlus11) {5157 Consumer.addKeywordResult("char16_t");5158 Consumer.addKeywordResult("char32_t");5159 Consumer.addKeywordResult("constexpr");5160 Consumer.addKeywordResult("decltype");5161 Consumer.addKeywordResult("thread_local");5162 }5163 }5164 5165 if (SemaRef.getLangOpts().GNUKeywords)5166 Consumer.addKeywordResult("typeof");5167 } else if (CCC.WantFunctionLikeCasts) {5168 static const char *const CastableTypeSpecs[] = {5169 "char", "double", "float", "int", "long", "short",5170 "signed", "unsigned", "void"5171 };5172 for (auto *kw : CastableTypeSpecs)5173 Consumer.addKeywordResult(kw);5174 }5175 5176 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {5177 Consumer.addKeywordResult("const_cast");5178 Consumer.addKeywordResult("dynamic_cast");5179 Consumer.addKeywordResult("reinterpret_cast");5180 Consumer.addKeywordResult("static_cast");5181 }5182 5183 if (CCC.WantExpressionKeywords) {5184 Consumer.addKeywordResult("sizeof");5185 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {5186 Consumer.addKeywordResult("false");5187 Consumer.addKeywordResult("true");5188 }5189 5190 if (SemaRef.getLangOpts().CPlusPlus) {5191 static const char *const CXXExprs[] = {5192 "delete", "new", "operator", "throw", "typeid"5193 };5194 for (const auto *CE : CXXExprs)5195 Consumer.addKeywordResult(CE);5196 5197 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&5198 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())5199 Consumer.addKeywordResult("this");5200 5201 if (SemaRef.getLangOpts().CPlusPlus11) {5202 Consumer.addKeywordResult("alignof");5203 Consumer.addKeywordResult("nullptr");5204 }5205 }5206 5207 if (SemaRef.getLangOpts().C11) {5208 // FIXME: We should not suggest _Alignof if the alignof macro5209 // is present.5210 Consumer.addKeywordResult("_Alignof");5211 }5212 }5213 5214 if (CCC.WantRemainingKeywords) {5215 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {5216 // Statements.5217 static const char *const CStmts[] = {5218 "do", "else", "for", "goto", "if", "return", "switch", "while" };5219 for (const auto *CS : CStmts)5220 Consumer.addKeywordResult(CS);5221 5222 if (SemaRef.getLangOpts().CPlusPlus) {5223 Consumer.addKeywordResult("catch");5224 Consumer.addKeywordResult("try");5225 }5226 5227 if (S && S->getBreakParent())5228 Consumer.addKeywordResult("break");5229 5230 if (S && S->getContinueParent())5231 Consumer.addKeywordResult("continue");5232 5233 if (SemaRef.getCurFunction() &&5234 !SemaRef.getCurFunction()->SwitchStack.empty()) {5235 Consumer.addKeywordResult("case");5236 Consumer.addKeywordResult("default");5237 }5238 } else {5239 if (SemaRef.getLangOpts().CPlusPlus) {5240 Consumer.addKeywordResult("namespace");5241 Consumer.addKeywordResult("template");5242 }5243 5244 if (S && S->isClassScope()) {5245 Consumer.addKeywordResult("explicit");5246 Consumer.addKeywordResult("friend");5247 Consumer.addKeywordResult("mutable");5248 Consumer.addKeywordResult("private");5249 Consumer.addKeywordResult("protected");5250 Consumer.addKeywordResult("public");5251 Consumer.addKeywordResult("virtual");5252 }5253 }5254 5255 if (SemaRef.getLangOpts().CPlusPlus) {5256 Consumer.addKeywordResult("using");5257 5258 if (SemaRef.getLangOpts().CPlusPlus11)5259 Consumer.addKeywordResult("static_assert");5260 }5261 }5262}5263 5264std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(5265 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,5266 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,5267 DeclContext *MemberContext, bool EnteringContext,5268 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {5269 5270 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||5271 DisableTypoCorrection)5272 return nullptr;5273 5274 // In Microsoft mode, don't perform typo correction in a template member5275 // function dependent context because it interferes with the "lookup into5276 // dependent bases of class templates" feature.5277 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&5278 isa<CXXMethodDecl>(CurContext))5279 return nullptr;5280 5281 // We only attempt to correct typos for identifiers.5282 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();5283 if (!Typo)5284 return nullptr;5285 5286 // If the scope specifier itself was invalid, don't try to correct5287 // typos.5288 if (SS && SS->isInvalid())5289 return nullptr;5290 5291 // Never try to correct typos during any kind of code synthesis.5292 if (!CodeSynthesisContexts.empty())5293 return nullptr;5294 5295 // Don't try to correct 'super'.5296 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())5297 return nullptr;5298 5299 // Abort if typo correction already failed for this specific typo.5300 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);5301 if (locs != TypoCorrectionFailures.end() &&5302 locs->second.count(TypoName.getLoc()))5303 return nullptr;5304 5305 // Don't try to correct the identifier "vector" when in AltiVec mode.5306 // TODO: Figure out why typo correction misbehaves in this case, fix it, and5307 // remove this workaround.5308 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))5309 return nullptr;5310 5311 // Provide a stop gap for files that are just seriously broken. Trying5312 // to correct all typos can turn into a HUGE performance penalty, causing5313 // some files to take minutes to get rejected by the parser.5314 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;5315 if (Limit && TyposCorrected >= Limit)5316 return nullptr;5317 ++TyposCorrected;5318 5319 // If we're handling a missing symbol error, using modules, and the5320 // special search all modules option is used, look for a missing import.5321 if (ErrorRecovery && getLangOpts().Modules &&5322 getLangOpts().ModulesSearchAll) {5323 // The following has the side effect of loading the missing module.5324 getModuleLoader().lookupMissingImports(Typo->getName(),5325 TypoName.getBeginLoc());5326 }5327 5328 // Extend the lifetime of the callback. We delayed this until here5329 // to avoid allocations in the hot path (which is where no typo correction5330 // occurs). Note that CorrectionCandidateCallback is polymorphic and5331 // initially stack-allocated.5332 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();5333 auto Consumer = std::make_unique<TypoCorrectionConsumer>(5334 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,5335 EnteringContext);5336 5337 // Perform name lookup to find visible, similarly-named entities.5338 bool IsUnqualifiedLookup = false;5339 DeclContext *QualifiedDC = MemberContext;5340 if (MemberContext) {5341 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);5342 5343 // Look in qualified interfaces.5344 if (OPT) {5345 for (auto *I : OPT->quals())5346 LookupVisibleDecls(I, LookupKind, *Consumer);5347 }5348 } else if (SS && SS->isSet()) {5349 QualifiedDC = computeDeclContext(*SS, EnteringContext);5350 if (!QualifiedDC)5351 return nullptr;5352 5353 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);5354 } else {5355 IsUnqualifiedLookup = true;5356 }5357 5358 // Determine whether we are going to search in the various namespaces for5359 // corrections.5360 bool SearchNamespaces5361 = getLangOpts().CPlusPlus &&5362 (IsUnqualifiedLookup || (SS && SS->isSet()));5363 5364 if (IsUnqualifiedLookup || SearchNamespaces) {5365 // For unqualified lookup, look through all of the names that we have5366 // seen in this translation unit.5367 // FIXME: Re-add the ability to skip very unlikely potential corrections.5368 for (const auto &I : Context.Idents)5369 Consumer->FoundName(I.getKey());5370 5371 // Walk through identifiers in external identifier sources.5372 // FIXME: Re-add the ability to skip very unlikely potential corrections.5373 if (IdentifierInfoLookup *External5374 = Context.Idents.getExternalIdentifierLookup()) {5375 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());5376 do {5377 StringRef Name = Iter->Next();5378 if (Name.empty())5379 break;5380 5381 Consumer->FoundName(Name);5382 } while (true);5383 }5384 }5385 5386 AddKeywordsToConsumer(*this, *Consumer, S,5387 *Consumer->getCorrectionValidator(),5388 SS && SS->isNotEmpty());5389 5390 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going5391 // to search those namespaces.5392 if (SearchNamespaces) {5393 // Load any externally-known namespaces.5394 if (ExternalSource && !LoadedExternalKnownNamespaces) {5395 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;5396 LoadedExternalKnownNamespaces = true;5397 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);5398 for (auto *N : ExternalKnownNamespaces)5399 KnownNamespaces[N] = true;5400 }5401 5402 Consumer->addNamespaces(KnownNamespaces);5403 }5404 5405 return Consumer;5406}5407 5408TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,5409 Sema::LookupNameKind LookupKind,5410 Scope *S, CXXScopeSpec *SS,5411 CorrectionCandidateCallback &CCC,5412 CorrectTypoKind Mode,5413 DeclContext *MemberContext,5414 bool EnteringContext,5415 const ObjCObjectPointerType *OPT,5416 bool RecordFailure) {5417 // Always let the ExternalSource have the first chance at correction, even5418 // if we would otherwise have given up.5419 if (ExternalSource) {5420 if (TypoCorrection Correction =5421 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,5422 MemberContext, EnteringContext, OPT))5423 return Correction;5424 }5425 5426 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;5427 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for5428 // some instances of CTC_Unknown, while WantRemainingKeywords is true5429 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.5430 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;5431 5432 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();5433 auto Consumer = makeTypoCorrectionConsumer(5434 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT,5435 Mode == CorrectTypoKind::ErrorRecovery);5436 5437 if (!Consumer)5438 return TypoCorrection();5439 5440 // If we haven't found anything, we're done.5441 if (Consumer->empty())5442 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);5443 5444 // Make sure the best edit distance (prior to adding any namespace qualifiers)5445 // is not more that about a third of the length of the typo's identifier.5446 unsigned ED = Consumer->getBestEditDistance(true);5447 unsigned TypoLen = Typo->getName().size();5448 if (ED > 0 && TypoLen / ED < 3)5449 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);5450 5451 TypoCorrection BestTC = Consumer->getNextCorrection();5452 TypoCorrection SecondBestTC = Consumer->getNextCorrection();5453 if (!BestTC)5454 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);5455 5456 ED = BestTC.getEditDistance();5457 5458 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {5459 // If this was an unqualified lookup and we believe the callback5460 // object wouldn't have filtered out possible corrections, note5461 // that no correction was found.5462 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);5463 }5464 5465 // If only a single name remains, return that result.5466 if (!SecondBestTC ||5467 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {5468 const TypoCorrection &Result = BestTC;5469 5470 // Don't correct to a keyword that's the same as the typo; the keyword5471 // wasn't actually in scope.5472 if (ED == 0 && Result.isKeyword())5473 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);5474 5475 TypoCorrection TC = Result;5476 TC.setCorrectionRange(SS, TypoName);5477 checkCorrectionVisibility(*this, TC);5478 return TC;5479 } else if (SecondBestTC && ObjCMessageReceiver) {5480 // Prefer 'super' when we're completing in a message-receiver5481 // context.5482 5483 if (BestTC.getCorrection().getAsString() != "super") {5484 if (SecondBestTC.getCorrection().getAsString() == "super")5485 BestTC = SecondBestTC;5486 else if ((*Consumer)["super"].front().isKeyword())5487 BestTC = (*Consumer)["super"].front();5488 }5489 // Don't correct to a keyword that's the same as the typo; the keyword5490 // wasn't actually in scope.5491 if (BestTC.getEditDistance() == 0 ||5492 BestTC.getCorrection().getAsString() != "super")5493 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);5494 5495 BestTC.setCorrectionRange(SS, TypoName);5496 return BestTC;5497 }5498 5499 // Record the failure's location if needed and return an empty correction. If5500 // this was an unqualified lookup and we believe the callback object did not5501 // filter out possible corrections, also cache the failure for the typo.5502 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);5503}5504 5505void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {5506 if (!CDecl) return;5507 5508 if (isKeyword())5509 CorrectionDecls.clear();5510 5511 CorrectionDecls.push_back(CDecl);5512 5513 if (!CorrectionName)5514 CorrectionName = CDecl->getDeclName();5515}5516 5517std::string TypoCorrection::getAsString(const LangOptions &LO) const {5518 if (CorrectionNameSpec) {5519 std::string tmpBuffer;5520 llvm::raw_string_ostream PrefixOStream(tmpBuffer);5521 CorrectionNameSpec.print(PrefixOStream, PrintingPolicy(LO));5522 PrefixOStream << CorrectionName;5523 return PrefixOStream.str();5524 }5525 5526 return CorrectionName.getAsString();5527}5528 5529bool CorrectionCandidateCallback::ValidateCandidate(5530 const TypoCorrection &candidate) {5531 if (!candidate.isResolved())5532 return true;5533 5534 if (candidate.isKeyword())5535 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||5536 WantRemainingKeywords || WantObjCSuper;5537 5538 bool HasNonType = false;5539 bool HasStaticMethod = false;5540 bool HasNonStaticMethod = false;5541 for (Decl *D : candidate) {5542 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))5543 D = FTD->getTemplatedDecl();5544 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {5545 if (Method->isStatic())5546 HasStaticMethod = true;5547 else5548 HasNonStaticMethod = true;5549 }5550 if (!isa<TypeDecl>(D))5551 HasNonType = true;5552 }5553 5554 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&5555 !candidate.getCorrectionSpecifier())5556 return false;5557 5558 return WantTypeSpecifiers || HasNonType;5559}5560 5561FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,5562 bool HasExplicitTemplateArgs,5563 MemberExpr *ME)5564 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),5565 CurContext(SemaRef.CurContext), MemberFn(ME) {5566 WantTypeSpecifiers = false;5567 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&5568 !HasExplicitTemplateArgs && NumArgs == 1;5569 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;5570 WantRemainingKeywords = false;5571}5572 5573bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {5574 if (!candidate.getCorrectionDecl())5575 return candidate.isKeyword();5576 5577 for (auto *C : candidate) {5578 FunctionDecl *FD = nullptr;5579 NamedDecl *ND = C->getUnderlyingDecl();5580 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))5581 FD = FTD->getTemplatedDecl();5582 if (!HasExplicitTemplateArgs && !FD) {5583 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {5584 // If the Decl is neither a function nor a template function,5585 // determine if it is a pointer or reference to a function. If so,5586 // check against the number of arguments expected for the pointee.5587 QualType ValType = cast<ValueDecl>(ND)->getType();5588 if (ValType.isNull())5589 continue;5590 if (ValType->isAnyPointerType() || ValType->isReferenceType())5591 ValType = ValType->getPointeeType();5592 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())5593 if (FPT->getNumParams() == NumArgs)5594 return true;5595 }5596 }5597 5598 // A typo for a function-style cast can look like a function call in C++.5599 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr5600 : isa<TypeDecl>(ND)) &&5601 CurContext->getParentASTContext().getLangOpts().CPlusPlus)5602 // Only a class or class template can take two or more arguments.5603 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);5604 5605 // Skip the current candidate if it is not a FunctionDecl or does not accept5606 // the current number of arguments.5607 if (!FD || !(FD->getNumParams() >= NumArgs &&5608 FD->getMinRequiredArguments() <= NumArgs))5609 continue;5610 5611 // If the current candidate is a non-static C++ method, skip the candidate5612 // unless the method being corrected--or the current DeclContext, if the5613 // function being corrected is not a method--is a method in the same class5614 // or a descendent class of the candidate's parent class.5615 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {5616 if (MemberFn || !MD->isStatic()) {5617 const auto *CurMD =5618 MemberFn5619 ? dyn_cast_if_present<CXXMethodDecl>(MemberFn->getMemberDecl())5620 : dyn_cast_if_present<CXXMethodDecl>(CurContext);5621 const CXXRecordDecl *CurRD =5622 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;5623 const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();5624 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))5625 continue;5626 }5627 }5628 return true;5629 }5630 return false;5631}5632 5633void Sema::diagnoseTypo(const TypoCorrection &Correction,5634 const PartialDiagnostic &TypoDiag,5635 bool ErrorRecovery) {5636 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),5637 ErrorRecovery);5638}5639 5640/// Find which declaration we should import to provide the definition of5641/// the given declaration.5642static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {5643 if (const auto *VD = dyn_cast<VarDecl>(D))5644 return VD->getDefinition();5645 if (const auto *FD = dyn_cast<FunctionDecl>(D))5646 return FD->getDefinition();5647 if (const auto *TD = dyn_cast<TagDecl>(D))5648 return TD->getDefinition();5649 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))5650 return ID->getDefinition();5651 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))5652 return PD->getDefinition();5653 if (const auto *TD = dyn_cast<TemplateDecl>(D))5654 if (const NamedDecl *TTD = TD->getTemplatedDecl())5655 return getDefinitionToImport(TTD);5656 return nullptr;5657}5658 5659void Sema::diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,5660 MissingImportKind MIK, bool Recover) {5661 // Suggest importing a module providing the definition of this entity, if5662 // possible.5663 const NamedDecl *Def = getDefinitionToImport(Decl);5664 if (!Def)5665 Def = Decl;5666 5667 Module *Owner = getOwningModule(Def);5668 assert(Owner && "definition of hidden declaration is not in a module");5669 5670 llvm::SmallVector<Module*, 8> OwningModules;5671 OwningModules.push_back(Owner);5672 auto Merged = Context.getModulesWithMergedDefinition(Def);5673 llvm::append_range(OwningModules, Merged);5674 5675 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,5676 Recover);5677}5678 5679/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic5680/// suggesting the addition of a #include of the specified file.5681static std::string getHeaderNameForHeader(Preprocessor &PP, FileEntryRef E,5682 llvm::StringRef IncludingFile) {5683 bool IsAngled = false;5684 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(5685 E, IncludingFile, &IsAngled);5686 return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');5687}5688 5689void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl,5690 SourceLocation DeclLoc,5691 ArrayRef<Module *> Modules,5692 MissingImportKind MIK, bool Recover) {5693 assert(!Modules.empty());5694 5695 // See https://github.com/llvm/llvm-project/issues/73893. It is generally5696 // confusing than helpful to show the namespace is not visible.5697 if (isa<NamespaceDecl>(Decl))5698 return;5699 5700 auto NotePrevious = [&] {5701 // FIXME: Suppress the note backtrace even under5702 // -fdiagnostics-show-note-include-stack. We don't care how this5703 // declaration was previously reached.5704 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;5705 };5706 5707 // Weed out duplicates from module list.5708 llvm::SmallVector<Module*, 8> UniqueModules;5709 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;5710 for (auto *M : Modules) {5711 if (M->isExplicitGlobalModule() || M->isPrivateModule())5712 continue;5713 if (UniqueModuleSet.insert(M).second)5714 UniqueModules.push_back(M);5715 }5716 5717 // Try to find a suitable header-name to #include.5718 std::string HeaderName;5719 if (OptionalFileEntryRef Header =5720 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {5721 if (const FileEntry *FE =5722 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))5723 HeaderName =5724 getHeaderNameForHeader(PP, *Header, FE->tryGetRealPathName());5725 }5726 5727 // If we have a #include we should suggest, or if all definition locations5728 // were in global module fragments, don't suggest an import.5729 if (!HeaderName.empty() || UniqueModules.empty()) {5730 // FIXME: Find a smart place to suggest inserting a #include, and add5731 // a FixItHint there.5732 Diag(UseLoc, diag::err_module_unimported_use_header)5733 << (int)MIK << Decl << !HeaderName.empty() << HeaderName;5734 // Produce a note showing where the entity was declared.5735 NotePrevious();5736 if (Recover)5737 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);5738 return;5739 }5740 5741 Modules = UniqueModules;5742 5743 auto GetModuleNameForDiagnostic = [this](const Module *M) -> std::string {5744 if (M->isModuleMapModule())5745 return M->getFullModuleName();5746 5747 if (M->isImplicitGlobalModule())5748 M = M->getTopLevelModule();5749 5750 // If the current module unit is in the same module with M, it is OK to show5751 // the partition name. Otherwise, it'll be sufficient to show the primary5752 // module name.5753 if (getASTContext().isInSameModule(M, getCurrentModule()))5754 return M->getTopLevelModuleName().str();5755 else5756 return M->getPrimaryModuleInterfaceName().str();5757 };5758 5759 if (Modules.size() > 1) {5760 std::string ModuleList;5761 unsigned N = 0;5762 for (const auto *M : Modules) {5763 ModuleList += "\n ";5764 if (++N == 5 && N != Modules.size()) {5765 ModuleList += "[...]";5766 break;5767 }5768 ModuleList += GetModuleNameForDiagnostic(M);5769 }5770 5771 Diag(UseLoc, diag::err_module_unimported_use_multiple)5772 << (int)MIK << Decl << ModuleList;5773 } else {5774 // FIXME: Add a FixItHint that imports the corresponding module.5775 Diag(UseLoc, diag::err_module_unimported_use)5776 << (int)MIK << Decl << GetModuleNameForDiagnostic(Modules[0]);5777 }5778 5779 NotePrevious();5780 5781 // Try to recover by implicitly importing this module.5782 if (Recover)5783 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);5784}5785 5786void Sema::diagnoseTypo(const TypoCorrection &Correction,5787 const PartialDiagnostic &TypoDiag,5788 const PartialDiagnostic &PrevNote,5789 bool ErrorRecovery) {5790 std::string CorrectedStr = Correction.getAsString(getLangOpts());5791 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());5792 FixItHint FixTypo = FixItHint::CreateReplacement(5793 Correction.getCorrectionRange(), CorrectedStr);5794 5795 // Maybe we're just missing a module import.5796 if (Correction.requiresImport()) {5797 NamedDecl *Decl = Correction.getFoundDecl();5798 assert(Decl && "import required but no declaration to import");5799 5800 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,5801 MissingImportKind::Declaration, ErrorRecovery);5802 return;5803 }5804 5805 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)5806 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());5807 5808 NamedDecl *ChosenDecl =5809 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();5810 5811 // For builtin functions which aren't declared anywhere in source,5812 // don't emit the "declared here" note.5813 if (const auto *FD = dyn_cast_if_present<FunctionDecl>(ChosenDecl);5814 FD && FD->getBuiltinID() &&5815 PrevNote.getDiagID() == diag::note_previous_decl &&5816 Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {5817 ChosenDecl = nullptr;5818 }5819 5820 if (PrevNote.getDiagID() && ChosenDecl)5821 Diag(ChosenDecl->getLocation(), PrevNote)5822 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);5823 5824 // Add any extra diagnostics.5825 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())5826 Diag(Correction.getCorrectionRange().getBegin(), PD);5827}5828 5829void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {5830 DeclarationNameInfo Name(II, IILoc);5831 LookupResult R(*this, Name, LookupAnyName,5832 RedeclarationKind::NotForRedeclaration);5833 R.suppressDiagnostics();5834 R.setHideTags(false);5835 LookupName(R, S);5836 R.dump();5837}5838 5839void Sema::ActOnPragmaDump(Expr *E) {5840 E->dump();5841}5842 5843RedeclarationKind Sema::forRedeclarationInCurContext() const {5844 // A declaration with an owning module for linkage can never link against5845 // anything that is not visible. We don't need to check linkage here; if5846 // the context has internal linkage, redeclaration lookup won't find things5847 // from other TUs, and we can't safely compute linkage yet in general.5848 if (cast<Decl>(CurContext)->getOwningModuleForLinkage())5849 return RedeclarationKind::ForVisibleRedeclaration;5850 return RedeclarationKind::ForExternalRedeclaration;5851}5852