Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaLookup.cpp
35233 views
//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements name lookup for C, C++, Objective-C, and9// Objective-C++.10//11//===----------------------------------------------------------------------===//1213#include "clang/AST/ASTContext.h"14#include "clang/AST/CXXInheritance.h"15#include "clang/AST/Decl.h"16#include "clang/AST/DeclCXX.h"17#include "clang/AST/DeclLookups.h"18#include "clang/AST/DeclObjC.h"19#include "clang/AST/DeclTemplate.h"20#include "clang/AST/Expr.h"21#include "clang/AST/ExprCXX.h"22#include "clang/Basic/Builtins.h"23#include "clang/Basic/FileManager.h"24#include "clang/Basic/LangOptions.h"25#include "clang/Lex/HeaderSearch.h"26#include "clang/Lex/ModuleLoader.h"27#include "clang/Lex/Preprocessor.h"28#include "clang/Sema/DeclSpec.h"29#include "clang/Sema/Lookup.h"30#include "clang/Sema/Overload.h"31#include "clang/Sema/RISCVIntrinsicManager.h"32#include "clang/Sema/Scope.h"33#include "clang/Sema/ScopeInfo.h"34#include "clang/Sema/Sema.h"35#include "clang/Sema/SemaInternal.h"36#include "clang/Sema/SemaRISCV.h"37#include "clang/Sema/TemplateDeduction.h"38#include "clang/Sema/TypoCorrection.h"39#include "llvm/ADT/STLExtras.h"40#include "llvm/ADT/STLForwardCompat.h"41#include "llvm/ADT/SmallPtrSet.h"42#include "llvm/ADT/TinyPtrVector.h"43#include "llvm/ADT/edit_distance.h"44#include "llvm/Support/Casting.h"45#include "llvm/Support/ErrorHandling.h"46#include <algorithm>47#include <iterator>48#include <list>49#include <optional>50#include <set>51#include <utility>52#include <vector>5354#include "OpenCLBuiltins.inc"5556using namespace clang;57using namespace sema;5859namespace {60class UnqualUsingEntry {61const DeclContext *Nominated;62const DeclContext *CommonAncestor;6364public:65UnqualUsingEntry(const DeclContext *Nominated,66const DeclContext *CommonAncestor)67: Nominated(Nominated), CommonAncestor(CommonAncestor) {68}6970const DeclContext *getCommonAncestor() const {71return CommonAncestor;72}7374const DeclContext *getNominatedNamespace() const {75return Nominated;76}7778// Sort by the pointer value of the common ancestor.79struct Comparator {80bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {81return L.getCommonAncestor() < R.getCommonAncestor();82}8384bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {85return E.getCommonAncestor() < DC;86}8788bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {89return DC < E.getCommonAncestor();90}91};92};9394/// A collection of using directives, as used by C++ unqualified95/// lookup.96class UnqualUsingDirectiveSet {97Sema &SemaRef;9899typedef SmallVector<UnqualUsingEntry, 8> ListTy;100101ListTy list;102llvm::SmallPtrSet<DeclContext*, 8> visited;103104public:105UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}106107void visitScopeChain(Scope *S, Scope *InnermostFileScope) {108// C++ [namespace.udir]p1:109// During unqualified name lookup, the names appear as if they110// were declared in the nearest enclosing namespace which contains111// both the using-directive and the nominated namespace.112DeclContext *InnermostFileDC = InnermostFileScope->getEntity();113assert(InnermostFileDC && InnermostFileDC->isFileContext());114115for (; S; S = S->getParent()) {116// C++ [namespace.udir]p1:117// A using-directive shall not appear in class scope, but may118// appear in namespace scope or in block scope.119DeclContext *Ctx = S->getEntity();120if (Ctx && Ctx->isFileContext()) {121visit(Ctx, Ctx);122} else if (!Ctx || Ctx->isFunctionOrMethod()) {123for (auto *I : S->using_directives())124if (SemaRef.isVisible(I))125visit(I, InnermostFileDC);126}127}128}129130// Visits a context and collect all of its using directives131// recursively. Treats all using directives as if they were132// declared in the context.133//134// A given context is only every visited once, so it is important135// that contexts be visited from the inside out in order to get136// the effective DCs right.137void visit(DeclContext *DC, DeclContext *EffectiveDC) {138if (!visited.insert(DC).second)139return;140141addUsingDirectives(DC, EffectiveDC);142}143144// Visits a using directive and collects all of its using145// directives recursively. Treats all using directives as if they146// were declared in the effective DC.147void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {148DeclContext *NS = UD->getNominatedNamespace();149if (!visited.insert(NS).second)150return;151152addUsingDirective(UD, EffectiveDC);153addUsingDirectives(NS, EffectiveDC);154}155156// Adds all the using directives in a context (and those nominated157// by its using directives, transitively) as if they appeared in158// the given effective context.159void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {160SmallVector<DeclContext*, 4> queue;161while (true) {162for (auto *UD : DC->using_directives()) {163DeclContext *NS = UD->getNominatedNamespace();164if (SemaRef.isVisible(UD) && visited.insert(NS).second) {165addUsingDirective(UD, EffectiveDC);166queue.push_back(NS);167}168}169170if (queue.empty())171return;172173DC = queue.pop_back_val();174}175}176177// Add a using directive as if it had been declared in the given178// context. This helps implement C++ [namespace.udir]p3:179// The using-directive is transitive: if a scope contains a180// using-directive that nominates a second namespace that itself181// contains using-directives, the effect is as if the182// using-directives from the second namespace also appeared in183// the first.184void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {185// Find the common ancestor between the effective context and186// the nominated namespace.187DeclContext *Common = UD->getNominatedNamespace();188while (!Common->Encloses(EffectiveDC))189Common = Common->getParent();190Common = Common->getPrimaryContext();191192list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));193}194195void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }196197typedef ListTy::const_iterator const_iterator;198199const_iterator begin() const { return list.begin(); }200const_iterator end() const { return list.end(); }201202llvm::iterator_range<const_iterator>203getNamespacesFor(const DeclContext *DC) const {204return llvm::make_range(std::equal_range(begin(), end(),205DC->getPrimaryContext(),206UnqualUsingEntry::Comparator()));207}208};209} // end anonymous namespace210211// Retrieve the set of identifier namespaces that correspond to a212// specific kind of name lookup.213static inline unsigned getIDNS(Sema::LookupNameKind NameKind,214bool CPlusPlus,215bool Redeclaration) {216unsigned IDNS = 0;217switch (NameKind) {218case Sema::LookupObjCImplicitSelfParam:219case Sema::LookupOrdinaryName:220case Sema::LookupRedeclarationWithLinkage:221case Sema::LookupLocalFriendName:222case Sema::LookupDestructorName:223IDNS = Decl::IDNS_Ordinary;224if (CPlusPlus) {225IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;226if (Redeclaration)227IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;228}229if (Redeclaration)230IDNS |= Decl::IDNS_LocalExtern;231break;232233case Sema::LookupOperatorName:234// Operator lookup is its own crazy thing; it is not the same235// as (e.g.) looking up an operator name for redeclaration.236assert(!Redeclaration && "cannot do redeclaration operator lookup");237IDNS = Decl::IDNS_NonMemberOperator;238break;239240case Sema::LookupTagName:241if (CPlusPlus) {242IDNS = Decl::IDNS_Type;243244// When looking for a redeclaration of a tag name, we add:245// 1) TagFriend to find undeclared friend decls246// 2) Namespace because they can't "overload" with tag decls.247// 3) Tag because it includes class templates, which can't248// "overload" with tag decls.249if (Redeclaration)250IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;251} else {252IDNS = Decl::IDNS_Tag;253}254break;255256case Sema::LookupLabel:257IDNS = Decl::IDNS_Label;258break;259260case Sema::LookupMemberName:261IDNS = Decl::IDNS_Member;262if (CPlusPlus)263IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;264break;265266case Sema::LookupNestedNameSpecifierName:267IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;268break;269270case Sema::LookupNamespaceName:271IDNS = Decl::IDNS_Namespace;272break;273274case Sema::LookupUsingDeclName:275assert(Redeclaration && "should only be used for redecl lookup");276IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |277Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |278Decl::IDNS_LocalExtern;279break;280281case Sema::LookupObjCProtocolName:282IDNS = Decl::IDNS_ObjCProtocol;283break;284285case Sema::LookupOMPReductionName:286IDNS = Decl::IDNS_OMPReduction;287break;288289case Sema::LookupOMPMapperName:290IDNS = Decl::IDNS_OMPMapper;291break;292293case Sema::LookupAnyName:294IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member295| Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol296| Decl::IDNS_Type;297break;298}299return IDNS;300}301302void LookupResult::configure() {303IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,304isForRedeclaration());305306// If we're looking for one of the allocation or deallocation307// operators, make sure that the implicitly-declared new and delete308// operators can be found.309switch (NameInfo.getName().getCXXOverloadedOperator()) {310case OO_New:311case OO_Delete:312case OO_Array_New:313case OO_Array_Delete:314getSema().DeclareGlobalNewDelete();315break;316317default:318break;319}320321// Compiler builtins are always visible, regardless of where they end322// up being declared.323if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {324if (unsigned BuiltinID = Id->getBuiltinID()) {325if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))326AllowHidden = true;327}328}329}330331bool LookupResult::checkDebugAssumptions() const {332// This function is never called by NDEBUG builds.333assert(ResultKind != NotFound || Decls.size() == 0);334assert(ResultKind != Found || Decls.size() == 1);335assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||336(Decls.size() == 1 &&337isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));338assert(ResultKind != FoundUnresolvedValue || checkUnresolved());339assert(ResultKind != Ambiguous || Decls.size() > 1 ||340(Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||341Ambiguity == AmbiguousBaseSubobjectTypes)));342assert((Paths != nullptr) == (ResultKind == Ambiguous &&343(Ambiguity == AmbiguousBaseSubobjectTypes ||344Ambiguity == AmbiguousBaseSubobjects)));345return true;346}347348// Necessary because CXXBasePaths is not complete in Sema.h349void LookupResult::deletePaths(CXXBasePaths *Paths) {350delete Paths;351}352353/// Get a representative context for a declaration such that two declarations354/// will have the same context if they were found within the same scope.355static const DeclContext *getContextForScopeMatching(const Decl *D) {356// For function-local declarations, use that function as the context. This357// doesn't account for scopes within the function; the caller must deal with358// those.359if (const DeclContext *DC = D->getLexicalDeclContext();360DC->isFunctionOrMethod())361return DC;362363// Otherwise, look at the semantic context of the declaration. The364// declaration must have been found there.365return D->getDeclContext()->getRedeclContext();366}367368/// Determine whether \p D is a better lookup result than \p Existing,369/// given that they declare the same entity.370static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,371const NamedDecl *D,372const NamedDecl *Existing) {373// When looking up redeclarations of a using declaration, prefer a using374// shadow declaration over any other declaration of the same entity.375if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&376!isa<UsingShadowDecl>(Existing))377return true;378379const auto *DUnderlying = D->getUnderlyingDecl();380const auto *EUnderlying = Existing->getUnderlyingDecl();381382// If they have different underlying declarations, prefer a typedef over the383// original type (this happens when two type declarations denote the same384// type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef385// might carry additional semantic information, such as an alignment override.386// However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag387// declaration over a typedef. Also prefer a tag over a typedef for388// destructor name lookup because in some contexts we only accept a389// class-name in a destructor declaration.390if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {391assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));392bool HaveTag = isa<TagDecl>(EUnderlying);393bool WantTag =394Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName;395return HaveTag != WantTag;396}397398// Pick the function with more default arguments.399// FIXME: In the presence of ambiguous default arguments, we should keep both,400// so we can diagnose the ambiguity if the default argument is needed.401// See C++ [over.match.best]p3.402if (const auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {403const auto *EFD = cast<FunctionDecl>(EUnderlying);404unsigned DMin = DFD->getMinRequiredArguments();405unsigned EMin = EFD->getMinRequiredArguments();406// If D has more default arguments, it is preferred.407if (DMin != EMin)408return DMin < EMin;409// FIXME: When we track visibility for default function arguments, check410// that we pick the declaration with more visible default arguments.411}412413// Pick the template with more default template arguments.414if (const auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {415const auto *ETD = cast<TemplateDecl>(EUnderlying);416unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();417unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();418// If D has more default arguments, it is preferred. Note that default419// arguments (and their visibility) is monotonically increasing across the420// redeclaration chain, so this is a quick proxy for "is more recent".421if (DMin != EMin)422return DMin < EMin;423// If D has more *visible* default arguments, it is preferred. Note, an424// earlier default argument being visible does not imply that a later425// default argument is visible, so we can't just check the first one.426for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();427I != N; ++I) {428if (!S.hasVisibleDefaultArgument(429ETD->getTemplateParameters()->getParam(I)) &&430S.hasVisibleDefaultArgument(431DTD->getTemplateParameters()->getParam(I)))432return true;433}434}435436// VarDecl can have incomplete array types, prefer the one with more complete437// array type.438if (const auto *DVD = dyn_cast<VarDecl>(DUnderlying)) {439const auto *EVD = cast<VarDecl>(EUnderlying);440if (EVD->getType()->isIncompleteType() &&441!DVD->getType()->isIncompleteType()) {442// Prefer the decl with a more complete type if visible.443return S.isVisible(DVD);444}445return false; // Avoid picking up a newer decl, just because it was newer.446}447448// For most kinds of declaration, it doesn't really matter which one we pick.449if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {450// If the existing declaration is hidden, prefer the new one. Otherwise,451// keep what we've got.452return !S.isVisible(Existing);453}454455// Pick the newer declaration; it might have a more precise type.456for (const Decl *Prev = DUnderlying->getPreviousDecl(); Prev;457Prev = Prev->getPreviousDecl())458if (Prev == EUnderlying)459return true;460return false;461}462463/// Determine whether \p D can hide a tag declaration.464static bool canHideTag(const NamedDecl *D) {465// C++ [basic.scope.declarative]p4:466// Given a set of declarations in a single declarative region [...]467// exactly one declaration shall declare a class name or enumeration name468// that is not a typedef name and the other declarations shall all refer to469// the same variable, non-static data member, or enumerator, or all refer470// to functions and function templates; in this case the class name or471// enumeration name is hidden.472// C++ [basic.scope.hiding]p2:473// A class name or enumeration name can be hidden by the name of a474// variable, data member, function, or enumerator declared in the same475// scope.476// An UnresolvedUsingValueDecl always instantiates to one of these.477D = D->getUnderlyingDecl();478return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||479isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||480isa<UnresolvedUsingValueDecl>(D);481}482483/// Resolves the result kind of this lookup.484void LookupResult::resolveKind() {485unsigned N = Decls.size();486487// Fast case: no possible ambiguity.488if (N == 0) {489assert(ResultKind == NotFound ||490ResultKind == NotFoundInCurrentInstantiation);491return;492}493494// If there's a single decl, we need to examine it to decide what495// kind of lookup this is.496if (N == 1) {497const NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();498if (isa<FunctionTemplateDecl>(D))499ResultKind = FoundOverloaded;500else if (isa<UnresolvedUsingValueDecl>(D))501ResultKind = FoundUnresolvedValue;502return;503}504505// Don't do any extra resolution if we've already resolved as ambiguous.506if (ResultKind == Ambiguous) return;507508llvm::SmallDenseMap<const NamedDecl *, unsigned, 16> Unique;509llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;510511bool Ambiguous = false;512bool ReferenceToPlaceHolderVariable = false;513bool HasTag = false, HasFunction = false;514bool HasFunctionTemplate = false, HasUnresolved = false;515const NamedDecl *HasNonFunction = nullptr;516517llvm::SmallVector<const NamedDecl *, 4> EquivalentNonFunctions;518llvm::BitVector RemovedDecls(N);519520for (unsigned I = 0; I < N; I++) {521const NamedDecl *D = Decls[I]->getUnderlyingDecl();522D = cast<NamedDecl>(D->getCanonicalDecl());523524// Ignore an invalid declaration unless it's the only one left.525// Also ignore HLSLBufferDecl which not have name conflict with other Decls.526if ((D->isInvalidDecl() || isa<HLSLBufferDecl>(D)) &&527N - RemovedDecls.count() > 1) {528RemovedDecls.set(I);529continue;530}531532// C++ [basic.scope.hiding]p2:533// A class name or enumeration name can be hidden by the name of534// an object, function, or enumerator declared in the same535// scope. If a class or enumeration name and an object, function,536// or enumerator are declared in the same scope (in any order)537// with the same name, the class or enumeration name is hidden538// wherever the object, function, or enumerator name is visible.539if (HideTags && isa<TagDecl>(D)) {540bool Hidden = false;541for (auto *OtherDecl : Decls) {542if (canHideTag(OtherDecl) && !OtherDecl->isInvalidDecl() &&543getContextForScopeMatching(OtherDecl)->Equals(544getContextForScopeMatching(Decls[I]))) {545RemovedDecls.set(I);546Hidden = true;547break;548}549}550if (Hidden)551continue;552}553554std::optional<unsigned> ExistingI;555556// Redeclarations of types via typedef can occur both within a scope557// and, through using declarations and directives, across scopes. There is558// no ambiguity if they all refer to the same type, so unique based on the559// canonical type.560if (const auto *TD = dyn_cast<TypeDecl>(D)) {561QualType T = getSema().Context.getTypeDeclType(TD);562auto UniqueResult = UniqueTypes.insert(563std::make_pair(getSema().Context.getCanonicalType(T), I));564if (!UniqueResult.second) {565// The type is not unique.566ExistingI = UniqueResult.first->second;567}568}569570// For non-type declarations, check for a prior lookup result naming this571// canonical declaration.572if (!ExistingI) {573auto UniqueResult = Unique.insert(std::make_pair(D, I));574if (!UniqueResult.second) {575// We've seen this entity before.576ExistingI = UniqueResult.first->second;577}578}579580if (ExistingI) {581// This is not a unique lookup result. Pick one of the results and582// discard the other.583if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],584Decls[*ExistingI]))585Decls[*ExistingI] = Decls[I];586RemovedDecls.set(I);587continue;588}589590// Otherwise, do some decl type analysis and then continue.591592if (isa<UnresolvedUsingValueDecl>(D)) {593HasUnresolved = true;594} else if (isa<TagDecl>(D)) {595if (HasTag)596Ambiguous = true;597HasTag = true;598} else if (isa<FunctionTemplateDecl>(D)) {599HasFunction = true;600HasFunctionTemplate = true;601} else if (isa<FunctionDecl>(D)) {602HasFunction = true;603} else {604if (HasNonFunction) {605// If we're about to create an ambiguity between two declarations that606// are equivalent, but one is an internal linkage declaration from one607// module and the other is an internal linkage declaration from another608// module, just skip it.609if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,610D)) {611EquivalentNonFunctions.push_back(D);612RemovedDecls.set(I);613continue;614}615if (D->isPlaceholderVar(getSema().getLangOpts()) &&616getContextForScopeMatching(D) ==617getContextForScopeMatching(Decls[I])) {618ReferenceToPlaceHolderVariable = true;619}620Ambiguous = true;621}622HasNonFunction = D;623}624}625626// FIXME: This diagnostic should really be delayed until we're done with627// the lookup result, in case the ambiguity is resolved by the caller.628if (!EquivalentNonFunctions.empty() && !Ambiguous)629getSema().diagnoseEquivalentInternalLinkageDeclarations(630getNameLoc(), HasNonFunction, EquivalentNonFunctions);631632// Remove decls by replacing them with decls from the end (which633// means that we need to iterate from the end) and then truncating634// to the new size.635for (int I = RemovedDecls.find_last(); I >= 0; I = RemovedDecls.find_prev(I))636Decls[I] = Decls[--N];637Decls.truncate(N);638639if ((HasNonFunction && (HasFunction || HasUnresolved)) ||640(HideTags && HasTag && (HasFunction || HasNonFunction || HasUnresolved)))641Ambiguous = true;642643if (Ambiguous && ReferenceToPlaceHolderVariable)644setAmbiguous(LookupResult::AmbiguousReferenceToPlaceholderVariable);645else if (Ambiguous)646setAmbiguous(LookupResult::AmbiguousReference);647else if (HasUnresolved)648ResultKind = LookupResult::FoundUnresolvedValue;649else if (N > 1 || HasFunctionTemplate)650ResultKind = LookupResult::FoundOverloaded;651else652ResultKind = LookupResult::Found;653}654655void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {656CXXBasePaths::const_paths_iterator I, E;657for (I = P.begin(), E = P.end(); I != E; ++I)658for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;659++DI)660addDecl(*DI);661}662663void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {664Paths = new CXXBasePaths;665Paths->swap(P);666addDeclsFromBasePaths(*Paths);667resolveKind();668setAmbiguous(AmbiguousBaseSubobjects);669}670671void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {672Paths = new CXXBasePaths;673Paths->swap(P);674addDeclsFromBasePaths(*Paths);675resolveKind();676setAmbiguous(AmbiguousBaseSubobjectTypes);677}678679void LookupResult::print(raw_ostream &Out) {680Out << Decls.size() << " result(s)";681if (isAmbiguous()) Out << ", ambiguous";682if (Paths) Out << ", base paths present";683684for (iterator I = begin(), E = end(); I != E; ++I) {685Out << "\n";686(*I)->print(Out, 2);687}688}689690LLVM_DUMP_METHOD void LookupResult::dump() {691llvm::errs() << "lookup results for " << getLookupName().getAsString()692<< ":\n";693for (NamedDecl *D : *this)694D->dump();695}696697/// Diagnose a missing builtin type.698static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,699llvm::StringRef Name) {700S.Diag(SourceLocation(), diag::err_opencl_type_not_found)701<< TypeClass << Name;702return S.Context.VoidTy;703}704705/// Lookup an OpenCL enum type.706static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {707LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),708Sema::LookupTagName);709S.LookupName(Result, S.TUScope);710if (Result.empty())711return diagOpenCLBuiltinTypeError(S, "enum", Name);712EnumDecl *Decl = Result.getAsSingle<EnumDecl>();713if (!Decl)714return diagOpenCLBuiltinTypeError(S, "enum", Name);715return S.Context.getEnumType(Decl);716}717718/// Lookup an OpenCL typedef type.719static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {720LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),721Sema::LookupOrdinaryName);722S.LookupName(Result, S.TUScope);723if (Result.empty())724return diagOpenCLBuiltinTypeError(S, "typedef", Name);725TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();726if (!Decl)727return diagOpenCLBuiltinTypeError(S, "typedef", Name);728return S.Context.getTypedefType(Decl);729}730731/// Get the QualType instances of the return type and arguments for an OpenCL732/// builtin function signature.733/// \param S (in) The Sema instance.734/// \param OpenCLBuiltin (in) The signature currently handled.735/// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic736/// type used as return type or as argument.737/// Only meaningful for generic types, otherwise equals 1.738/// \param RetTypes (out) List of the possible return types.739/// \param ArgTypes (out) List of the possible argument types. For each740/// argument, ArgTypes contains QualTypes for the Cartesian product741/// of (vector sizes) x (types) .742static void GetQualTypesForOpenCLBuiltin(743Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,744SmallVector<QualType, 1> &RetTypes,745SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {746// Get the QualType instances of the return types.747unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];748OCL2Qual(S, TypeTable[Sig], RetTypes);749GenTypeMaxCnt = RetTypes.size();750751// Get the QualType instances of the arguments.752// First type is the return type, skip it.753for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {754SmallVector<QualType, 1> Ty;755OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],756Ty);757GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;758ArgTypes.push_back(std::move(Ty));759}760}761762/// Create a list of the candidate function overloads for an OpenCL builtin763/// function.764/// \param Context (in) The ASTContext instance.765/// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic766/// type used as return type or as argument.767/// Only meaningful for generic types, otherwise equals 1.768/// \param FunctionList (out) List of FunctionTypes.769/// \param RetTypes (in) List of the possible return types.770/// \param ArgTypes (in) List of the possible types for the arguments.771static void GetOpenCLBuiltinFctOverloads(772ASTContext &Context, unsigned GenTypeMaxCnt,773std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,774SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {775FunctionProtoType::ExtProtoInfo PI(776Context.getDefaultCallingConvention(false, false, true));777PI.Variadic = false;778779// Do not attempt to create any FunctionTypes if there are no return types,780// which happens when a type belongs to a disabled extension.781if (RetTypes.size() == 0)782return;783784// Create FunctionTypes for each (gen)type.785for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {786SmallVector<QualType, 5> ArgList;787788for (unsigned A = 0; A < ArgTypes.size(); A++) {789// Bail out if there is an argument that has no available types.790if (ArgTypes[A].size() == 0)791return;792793// Builtins such as "max" have an "sgentype" argument that represents794// the corresponding scalar type of a gentype. The number of gentypes795// must be a multiple of the number of sgentypes.796assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&797"argument type count not compatible with gentype type count");798unsigned Idx = IGenType % ArgTypes[A].size();799ArgList.push_back(ArgTypes[A][Idx]);800}801802FunctionList.push_back(Context.getFunctionType(803RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));804}805}806807/// When trying to resolve a function name, if isOpenCLBuiltin() returns a808/// non-null <Index, Len> pair, then the name is referencing an OpenCL809/// builtin function. Add all candidate signatures to the LookUpResult.810///811/// \param S (in) The Sema instance.812/// \param LR (inout) The LookupResult instance.813/// \param II (in) The identifier being resolved.814/// \param FctIndex (in) Starting index in the BuiltinTable.815/// \param Len (in) The signature list has Len elements.816static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR,817IdentifierInfo *II,818const unsigned FctIndex,819const unsigned Len) {820// The builtin function declaration uses generic types (gentype).821bool HasGenType = false;822823// Maximum number of types contained in a generic type used as return type or824// as argument. Only meaningful for generic types, otherwise equals 1.825unsigned GenTypeMaxCnt;826827ASTContext &Context = S.Context;828829for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {830const OpenCLBuiltinStruct &OpenCLBuiltin =831BuiltinTable[FctIndex + SignatureIndex];832833// Ignore this builtin function if it is not available in the currently834// selected language version.835if (!isOpenCLVersionContainedInMask(Context.getLangOpts(),836OpenCLBuiltin.Versions))837continue;838839// Ignore this builtin function if it carries an extension macro that is840// not defined. This indicates that the extension is not supported by the841// target, so the builtin function should not be available.842StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];843if (!Extensions.empty()) {844SmallVector<StringRef, 2> ExtVec;845Extensions.split(ExtVec, " ");846bool AllExtensionsDefined = true;847for (StringRef Ext : ExtVec) {848if (!S.getPreprocessor().isMacroDefined(Ext)) {849AllExtensionsDefined = false;850break;851}852}853if (!AllExtensionsDefined)854continue;855}856857SmallVector<QualType, 1> RetTypes;858SmallVector<SmallVector<QualType, 1>, 5> ArgTypes;859860// Obtain QualType lists for the function signature.861GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,862ArgTypes);863if (GenTypeMaxCnt > 1) {864HasGenType = true;865}866867// Create function overload for each type combination.868std::vector<QualType> FunctionList;869GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,870ArgTypes);871872SourceLocation Loc = LR.getNameLoc();873DeclContext *Parent = Context.getTranslationUnitDecl();874FunctionDecl *NewOpenCLBuiltin;875876for (const auto &FTy : FunctionList) {877NewOpenCLBuiltin = FunctionDecl::Create(878Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,879S.getCurFPFeatures().isFPConstrained(), false,880FTy->isFunctionProtoType());881NewOpenCLBuiltin->setImplicit();882883// Create Decl objects for each parameter, adding them to the884// FunctionDecl.885const auto *FP = cast<FunctionProtoType>(FTy);886SmallVector<ParmVarDecl *, 4> ParmList;887for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {888ParmVarDecl *Parm = ParmVarDecl::Create(889Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),890nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);891Parm->setScopeInfo(0, IParm);892ParmList.push_back(Parm);893}894NewOpenCLBuiltin->setParams(ParmList);895896// Add function attributes.897if (OpenCLBuiltin.IsPure)898NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context));899if (OpenCLBuiltin.IsConst)900NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context));901if (OpenCLBuiltin.IsConv)902NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context));903904if (!S.getLangOpts().OpenCLCPlusPlus)905NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));906907LR.addDecl(NewOpenCLBuiltin);908}909}910911// If we added overloads, need to resolve the lookup result.912if (Len > 1 || HasGenType)913LR.resolveKind();914}915916bool Sema::LookupBuiltin(LookupResult &R) {917Sema::LookupNameKind NameKind = R.getLookupKind();918919// If we didn't find a use of this identifier, and if the identifier920// corresponds to a compiler builtin, create the decl object for the builtin921// now, injecting it into translation unit scope, and return it.922if (NameKind == Sema::LookupOrdinaryName ||923NameKind == Sema::LookupRedeclarationWithLinkage) {924IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();925if (II) {926if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {927if (II == getASTContext().getMakeIntegerSeqName()) {928R.addDecl(getASTContext().getMakeIntegerSeqDecl());929return true;930} else if (II == getASTContext().getTypePackElementName()) {931R.addDecl(getASTContext().getTypePackElementDecl());932return true;933}934}935936// Check if this is an OpenCL Builtin, and if so, insert its overloads.937if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {938auto Index = isOpenCLBuiltin(II->getName());939if (Index.first) {940InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,941Index.second);942return true;943}944}945946if (RISCV().DeclareRVVBuiltins || RISCV().DeclareSiFiveVectorBuiltins) {947if (!RISCV().IntrinsicManager)948RISCV().IntrinsicManager = CreateRISCVIntrinsicManager(*this);949950RISCV().IntrinsicManager->InitIntrinsicList();951952if (RISCV().IntrinsicManager->CreateIntrinsicIfFound(R, II, PP))953return true;954}955956// If this is a builtin on this (or all) targets, create the decl.957if (unsigned BuiltinID = II->getBuiltinID()) {958// In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined959// library functions like 'malloc'. Instead, we'll just error.960if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) &&961Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))962return false;963964if (NamedDecl *D =965LazilyCreateBuiltin(II, BuiltinID, TUScope,966R.isForRedeclaration(), R.getNameLoc())) {967R.addDecl(D);968return true;969}970}971}972}973974return false;975}976977/// Looks up the declaration of "struct objc_super" and978/// saves it for later use in building builtin declaration of979/// objc_msgSendSuper and objc_msgSendSuper_stret.980static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) {981ASTContext &Context = Sema.Context;982LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),983Sema::LookupTagName);984Sema.LookupName(Result, S);985if (Result.getResultKind() == LookupResult::Found)986if (const TagDecl *TD = Result.getAsSingle<TagDecl>())987Context.setObjCSuperType(Context.getTagDeclType(TD));988}989990void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) {991if (ID == Builtin::BIobjc_msgSendSuper)992LookupPredefedObjCSuperType(*this, S);993}994995/// Determine whether we can declare a special member function within996/// the class at this point.997static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {998// We need to have a definition for the class.999if (!Class->getDefinition() || Class->isDependentContext())1000return false;10011002// We can't be in the middle of defining the class.1003return !Class->isBeingDefined();1004}10051006void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {1007if (!CanDeclareSpecialMemberFunction(Class))1008return;10091010// If the default constructor has not yet been declared, do so now.1011if (Class->needsImplicitDefaultConstructor())1012DeclareImplicitDefaultConstructor(Class);10131014// If the copy constructor has not yet been declared, do so now.1015if (Class->needsImplicitCopyConstructor())1016DeclareImplicitCopyConstructor(Class);10171018// If the copy assignment operator has not yet been declared, do so now.1019if (Class->needsImplicitCopyAssignment())1020DeclareImplicitCopyAssignment(Class);10211022if (getLangOpts().CPlusPlus11) {1023// If the move constructor has not yet been declared, do so now.1024if (Class->needsImplicitMoveConstructor())1025DeclareImplicitMoveConstructor(Class);10261027// If the move assignment operator has not yet been declared, do so now.1028if (Class->needsImplicitMoveAssignment())1029DeclareImplicitMoveAssignment(Class);1030}10311032// If the destructor has not yet been declared, do so now.1033if (Class->needsImplicitDestructor())1034DeclareImplicitDestructor(Class);1035}10361037/// Determine whether this is the name of an implicitly-declared1038/// special member function.1039static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {1040switch (Name.getNameKind()) {1041case DeclarationName::CXXConstructorName:1042case DeclarationName::CXXDestructorName:1043return true;10441045case DeclarationName::CXXOperatorName:1046return Name.getCXXOverloadedOperator() == OO_Equal;10471048default:1049break;1050}10511052return false;1053}10541055/// If there are any implicit member functions with the given name1056/// that need to be declared in the given declaration context, do so.1057static void DeclareImplicitMemberFunctionsWithName(Sema &S,1058DeclarationName Name,1059SourceLocation Loc,1060const DeclContext *DC) {1061if (!DC)1062return;10631064switch (Name.getNameKind()) {1065case DeclarationName::CXXConstructorName:1066if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))1067if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {1068CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);1069if (Record->needsImplicitDefaultConstructor())1070S.DeclareImplicitDefaultConstructor(Class);1071if (Record->needsImplicitCopyConstructor())1072S.DeclareImplicitCopyConstructor(Class);1073if (S.getLangOpts().CPlusPlus11 &&1074Record->needsImplicitMoveConstructor())1075S.DeclareImplicitMoveConstructor(Class);1076}1077break;10781079case DeclarationName::CXXDestructorName:1080if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))1081if (Record->getDefinition() && Record->needsImplicitDestructor() &&1082CanDeclareSpecialMemberFunction(Record))1083S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));1084break;10851086case DeclarationName::CXXOperatorName:1087if (Name.getCXXOverloadedOperator() != OO_Equal)1088break;10891090if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {1091if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {1092CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);1093if (Record->needsImplicitCopyAssignment())1094S.DeclareImplicitCopyAssignment(Class);1095if (S.getLangOpts().CPlusPlus11 &&1096Record->needsImplicitMoveAssignment())1097S.DeclareImplicitMoveAssignment(Class);1098}1099}1100break;11011102case DeclarationName::CXXDeductionGuideName:1103S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);1104break;11051106default:1107break;1108}1109}11101111// Adds all qualifying matches for a name within a decl context to the1112// given lookup result. Returns true if any matches were found.1113static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {1114bool Found = false;11151116// Lazily declare C++ special member functions.1117if (S.getLangOpts().CPlusPlus)1118DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),1119DC);11201121// Perform lookup into this declaration context.1122DeclContext::lookup_result DR = DC->lookup(R.getLookupName());1123for (NamedDecl *D : DR) {1124if ((D = R.getAcceptableDecl(D))) {1125R.addDecl(D);1126Found = true;1127}1128}11291130if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))1131return true;11321133if (R.getLookupName().getNameKind()1134!= DeclarationName::CXXConversionFunctionName ||1135R.getLookupName().getCXXNameType()->isDependentType() ||1136!isa<CXXRecordDecl>(DC))1137return Found;11381139// C++ [temp.mem]p6:1140// A specialization of a conversion function template is not found by1141// name lookup. Instead, any conversion function templates visible in the1142// context of the use are considered. [...]1143const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);1144if (!Record->isCompleteDefinition())1145return Found;11461147// For conversion operators, 'operator auto' should only match1148// 'operator auto'. Since 'auto' is not a type, it shouldn't be considered1149// as a candidate for template substitution.1150auto *ContainedDeducedType =1151R.getLookupName().getCXXNameType()->getContainedDeducedType();1152if (R.getLookupName().getNameKind() ==1153DeclarationName::CXXConversionFunctionName &&1154ContainedDeducedType && ContainedDeducedType->isUndeducedType())1155return Found;11561157for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),1158UEnd = Record->conversion_end(); U != UEnd; ++U) {1159FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);1160if (!ConvTemplate)1161continue;11621163// When we're performing lookup for the purposes of redeclaration, just1164// add the conversion function template. When we deduce template1165// arguments for specializations, we'll end up unifying the return1166// type of the new declaration with the type of the function template.1167if (R.isForRedeclaration()) {1168R.addDecl(ConvTemplate);1169Found = true;1170continue;1171}11721173// C++ [temp.mem]p6:1174// [...] For each such operator, if argument deduction succeeds1175// (14.9.2.3), the resulting specialization is used as if found by1176// name lookup.1177//1178// When referencing a conversion function for any purpose other than1179// a redeclaration (such that we'll be building an expression with the1180// result), perform template argument deduction and place the1181// specialization into the result set. We do this to avoid forcing all1182// callers to perform special deduction for conversion functions.1183TemplateDeductionInfo Info(R.getNameLoc());1184FunctionDecl *Specialization = nullptr;11851186const FunctionProtoType *ConvProto1187= ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();1188assert(ConvProto && "Nonsensical conversion function template type");11891190// Compute the type of the function that we would expect the conversion1191// function to have, if it were to match the name given.1192// FIXME: Calling convention!1193FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();1194EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);1195EPI.ExceptionSpec = EST_None;1196QualType ExpectedType = R.getSema().Context.getFunctionType(1197R.getLookupName().getCXXNameType(), std::nullopt, EPI);11981199// Perform template argument deduction against the type that we would1200// expect the function to have.1201if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,1202Specialization, Info) ==1203TemplateDeductionResult::Success) {1204R.addDecl(Specialization);1205Found = true;1206}1207}12081209return Found;1210}12111212// Performs C++ unqualified lookup into the given file context.1213static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,1214const DeclContext *NS,1215UnqualUsingDirectiveSet &UDirs) {12161217assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");12181219// Perform direct name lookup into the LookupCtx.1220bool Found = LookupDirect(S, R, NS);12211222// Perform direct name lookup into the namespaces nominated by the1223// using directives whose common ancestor is this namespace.1224for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))1225if (LookupDirect(S, R, UUE.getNominatedNamespace()))1226Found = true;12271228R.resolveKind();12291230return Found;1231}12321233static bool isNamespaceOrTranslationUnitScope(Scope *S) {1234if (DeclContext *Ctx = S->getEntity())1235return Ctx->isFileContext();1236return false;1237}12381239/// Find the outer declaration context from this scope. This indicates the1240/// context that we should search up to (exclusive) before considering the1241/// parent of the specified scope.1242static DeclContext *findOuterContext(Scope *S) {1243for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())1244if (DeclContext *DC = OuterS->getLookupEntity())1245return DC;1246return nullptr;1247}12481249namespace {1250/// An RAII object to specify that we want to find block scope extern1251/// declarations.1252struct FindLocalExternScope {1253FindLocalExternScope(LookupResult &R)1254: R(R), OldFindLocalExtern(R.getIdentifierNamespace() &1255Decl::IDNS_LocalExtern) {1256R.setFindLocalExtern(R.getIdentifierNamespace() &1257(Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));1258}1259void restore() {1260R.setFindLocalExtern(OldFindLocalExtern);1261}1262~FindLocalExternScope() {1263restore();1264}1265LookupResult &R;1266bool OldFindLocalExtern;1267};1268} // end anonymous namespace12691270bool Sema::CppLookupName(LookupResult &R, Scope *S) {1271assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");12721273DeclarationName Name = R.getLookupName();1274Sema::LookupNameKind NameKind = R.getLookupKind();12751276// If this is the name of an implicitly-declared special member function,1277// go through the scope stack to implicitly declare1278if (isImplicitlyDeclaredMemberFunctionName(Name)) {1279for (Scope *PreS = S; PreS; PreS = PreS->getParent())1280if (DeclContext *DC = PreS->getEntity())1281DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);1282}12831284// C++23 [temp.dep.general]p2:1285// The component name of an unqualified-id is dependent if1286// - it is a conversion-function-id whose conversion-type-id1287// is dependent, or1288// - it is operator= and the current class is a templated entity, or1289// - the unqualified-id is the postfix-expression in a dependent call.1290if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&1291Name.getCXXNameType()->isDependentType()) {1292R.setNotFoundInCurrentInstantiation();1293return false;1294}12951296// Implicitly declare member functions with the name we're looking for, if in1297// fact we are in a scope where it matters.12981299Scope *Initial = S;1300IdentifierResolver::iterator1301I = IdResolver.begin(Name),1302IEnd = IdResolver.end();13031304// First we lookup local scope.1305// We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]1306// ...During unqualified name lookup (3.4.1), the names appear as if1307// they were declared in the nearest enclosing namespace which contains1308// both the using-directive and the nominated namespace.1309// [Note: in this context, "contains" means "contains directly or1310// indirectly".1311//1312// For example:1313// namespace A { int i; }1314// void foo() {1315// int i;1316// {1317// using namespace A;1318// ++i; // finds local 'i', A::i appears at global scope1319// }1320// }1321//1322UnqualUsingDirectiveSet UDirs(*this);1323bool VisitedUsingDirectives = false;1324bool LeftStartingScope = false;13251326// When performing a scope lookup, we want to find local extern decls.1327FindLocalExternScope FindLocals(R);13281329for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {1330bool SearchNamespaceScope = true;1331// Check whether the IdResolver has anything in this scope.1332for (; I != IEnd && S->isDeclScope(*I); ++I) {1333if (NamedDecl *ND = R.getAcceptableDecl(*I)) {1334if (NameKind == LookupRedeclarationWithLinkage &&1335!(*I)->isTemplateParameter()) {1336// If it's a template parameter, we still find it, so we can diagnose1337// the invalid redeclaration.13381339// Determine whether this (or a previous) declaration is1340// out-of-scope.1341if (!LeftStartingScope && !Initial->isDeclScope(*I))1342LeftStartingScope = true;13431344// If we found something outside of our starting scope that1345// does not have linkage, skip it.1346if (LeftStartingScope && !((*I)->hasLinkage())) {1347R.setShadowed();1348continue;1349}1350} else {1351// We found something in this scope, we should not look at the1352// namespace scope1353SearchNamespaceScope = false;1354}1355R.addDecl(ND);1356}1357}1358if (!SearchNamespaceScope) {1359R.resolveKind();1360if (S->isClassScope())1361if (auto *Record = dyn_cast_if_present<CXXRecordDecl>(S->getEntity()))1362R.setNamingClass(Record);1363return true;1364}13651366if (NameKind == LookupLocalFriendName && !S->isClassScope()) {1367// C++11 [class.friend]p11:1368// If a friend declaration appears in a local class and the name1369// specified is an unqualified name, a prior declaration is1370// looked up without considering scopes that are outside the1371// innermost enclosing non-class scope.1372return false;1373}13741375if (DeclContext *Ctx = S->getLookupEntity()) {1376DeclContext *OuterCtx = findOuterContext(S);1377for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {1378// We do not directly look into transparent contexts, since1379// those entities will be found in the nearest enclosing1380// non-transparent context.1381if (Ctx->isTransparentContext())1382continue;13831384// We do not look directly into function or method contexts,1385// since all of the local variables and parameters of the1386// function/method are present within the Scope.1387if (Ctx->isFunctionOrMethod()) {1388// If we have an Objective-C instance method, look for ivars1389// in the corresponding interface.1390if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {1391if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())1392if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {1393ObjCInterfaceDecl *ClassDeclared;1394if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(1395Name.getAsIdentifierInfo(),1396ClassDeclared)) {1397if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {1398R.addDecl(ND);1399R.resolveKind();1400return true;1401}1402}1403}1404}14051406continue;1407}14081409// If this is a file context, we need to perform unqualified name1410// lookup considering using directives.1411if (Ctx->isFileContext()) {1412// If we haven't handled using directives yet, do so now.1413if (!VisitedUsingDirectives) {1414// Add using directives from this context up to the top level.1415for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {1416if (UCtx->isTransparentContext())1417continue;14181419UDirs.visit(UCtx, UCtx);1420}14211422// Find the innermost file scope, so we can add using directives1423// from local scopes.1424Scope *InnermostFileScope = S;1425while (InnermostFileScope &&1426!isNamespaceOrTranslationUnitScope(InnermostFileScope))1427InnermostFileScope = InnermostFileScope->getParent();1428UDirs.visitScopeChain(Initial, InnermostFileScope);14291430UDirs.done();14311432VisitedUsingDirectives = true;1433}14341435if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {1436R.resolveKind();1437return true;1438}14391440continue;1441}14421443// Perform qualified name lookup into this context.1444// FIXME: In some cases, we know that every name that could be found by1445// this qualified name lookup will also be on the identifier chain. For1446// example, inside a class without any base classes, we never need to1447// perform qualified lookup because all of the members are on top of the1448// identifier chain.1449if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))1450return true;1451}1452}1453}14541455// Stop if we ran out of scopes.1456// FIXME: This really, really shouldn't be happening.1457if (!S) return false;14581459// If we are looking for members, no need to look into global/namespace scope.1460if (NameKind == LookupMemberName)1461return false;14621463// Collect UsingDirectiveDecls in all scopes, and recursively all1464// nominated namespaces by those using-directives.1465//1466// FIXME: Cache this sorted list in Scope structure, and DeclContext, so we1467// don't build it for each lookup!1468if (!VisitedUsingDirectives) {1469UDirs.visitScopeChain(Initial, S);1470UDirs.done();1471}14721473// If we're not performing redeclaration lookup, do not look for local1474// extern declarations outside of a function scope.1475if (!R.isForRedeclaration())1476FindLocals.restore();14771478// Lookup namespace scope, and global scope.1479// Unqualified name lookup in C++ requires looking into scopes1480// that aren't strictly lexical, and therefore we walk through the1481// context as well as walking through the scopes.1482for (; S; S = S->getParent()) {1483// Check whether the IdResolver has anything in this scope.1484bool Found = false;1485for (; I != IEnd && S->isDeclScope(*I); ++I) {1486if (NamedDecl *ND = R.getAcceptableDecl(*I)) {1487// We found something. Look for anything else in our scope1488// with this same name and in an acceptable identifier1489// namespace, so that we can construct an overload set if we1490// need to.1491Found = true;1492R.addDecl(ND);1493}1494}14951496if (Found && S->isTemplateParamScope()) {1497R.resolveKind();1498return true;1499}15001501DeclContext *Ctx = S->getLookupEntity();1502if (Ctx) {1503DeclContext *OuterCtx = findOuterContext(S);1504for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {1505// We do not directly look into transparent contexts, since1506// those entities will be found in the nearest enclosing1507// non-transparent context.1508if (Ctx->isTransparentContext())1509continue;15101511// If we have a context, and it's not a context stashed in the1512// template parameter scope for an out-of-line definition, also1513// look into that context.1514if (!(Found && S->isTemplateParamScope())) {1515assert(Ctx->isFileContext() &&1516"We should have been looking only at file context here already.");15171518// Look into context considering using-directives.1519if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))1520Found = true;1521}15221523if (Found) {1524R.resolveKind();1525return true;1526}15271528if (R.isForRedeclaration() && !Ctx->isTransparentContext())1529return false;1530}1531}15321533if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())1534return false;1535}15361537return !R.empty();1538}15391540void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {1541if (auto *M = getCurrentModule())1542Context.mergeDefinitionIntoModule(ND, M);1543else1544// We're not building a module; just make the definition visible.1545ND->setVisibleDespiteOwningModule();15461547// If ND is a template declaration, make the template parameters1548// visible too. They're not (necessarily) within a mergeable DeclContext.1549if (auto *TD = dyn_cast<TemplateDecl>(ND))1550for (auto *Param : *TD->getTemplateParameters())1551makeMergedDefinitionVisible(Param);1552}15531554/// Find the module in which the given declaration was defined.1555static Module *getDefiningModule(Sema &S, Decl *Entity) {1556if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {1557// If this function was instantiated from a template, the defining module is1558// the module containing the pattern.1559if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())1560Entity = Pattern;1561} else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {1562if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())1563Entity = Pattern;1564} else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {1565if (auto *Pattern = ED->getTemplateInstantiationPattern())1566Entity = Pattern;1567} else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {1568if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())1569Entity = Pattern;1570}15711572// Walk up to the containing context. That might also have been instantiated1573// from a template.1574DeclContext *Context = Entity->getLexicalDeclContext();1575if (Context->isFileContext())1576return S.getOwningModule(Entity);1577return getDefiningModule(S, cast<Decl>(Context));1578}15791580llvm::DenseSet<Module*> &Sema::getLookupModules() {1581unsigned N = CodeSynthesisContexts.size();1582for (unsigned I = CodeSynthesisContextLookupModules.size();1583I != N; ++I) {1584Module *M = CodeSynthesisContexts[I].Entity ?1585getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :1586nullptr;1587if (M && !LookupModulesCache.insert(M).second)1588M = nullptr;1589CodeSynthesisContextLookupModules.push_back(M);1590}1591return LookupModulesCache;1592}15931594bool Sema::isUsableModule(const Module *M) {1595assert(M && "We shouldn't check nullness for module here");1596// Return quickly if we cached the result.1597if (UsableModuleUnitsCache.count(M))1598return true;15991600// If M is the global module fragment of the current translation unit. So it1601// should be usable.1602// [module.global.frag]p1:1603// The global module fragment can be used to provide declarations that are1604// attached to the global module and usable within the module unit.1605if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment) {1606UsableModuleUnitsCache.insert(M);1607return true;1608}16091610// Otherwise, the global module fragment from other translation unit is not1611// directly usable.1612if (M->isGlobalModule())1613return false;16141615Module *Current = getCurrentModule();16161617// If we're not parsing a module, we can't use all the declarations from1618// another module easily.1619if (!Current)1620return false;16211622// If M is the module we're parsing or M and the current module unit lives in1623// the same module, M should be usable.1624//1625// Note: It should be fine to search the vector `ModuleScopes` linearly since1626// it should be generally small enough. There should be rare module fragments1627// in a named module unit.1628if (llvm::count_if(ModuleScopes,1629[&M](const ModuleScope &MS) { return MS.Module == M; }) ||1630getASTContext().isInSameModule(M, Current)) {1631UsableModuleUnitsCache.insert(M);1632return true;1633}16341635return false;1636}16371638bool Sema::hasVisibleMergedDefinition(const NamedDecl *Def) {1639for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))1640if (isModuleVisible(Merged))1641return true;1642return false;1643}16441645bool Sema::hasMergedDefinitionInCurrentModule(const NamedDecl *Def) {1646for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))1647if (isUsableModule(Merged))1648return true;1649return false;1650}16511652template <typename ParmDecl>1653static bool1654hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D,1655llvm::SmallVectorImpl<Module *> *Modules,1656Sema::AcceptableKind Kind) {1657if (!D->hasDefaultArgument())1658return false;16591660llvm::SmallPtrSet<const ParmDecl *, 4> Visited;1661while (D && Visited.insert(D).second) {1662auto &DefaultArg = D->getDefaultArgStorage();1663if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))1664return true;16651666if (!DefaultArg.isInherited() && Modules) {1667auto *NonConstD = const_cast<ParmDecl*>(D);1668Modules->push_back(S.getOwningModule(NonConstD));1669}16701671// If there was a previous default argument, maybe its parameter is1672// acceptable.1673D = DefaultArg.getInheritedFrom();1674}1675return false;1676}16771678bool Sema::hasAcceptableDefaultArgument(1679const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,1680Sema::AcceptableKind Kind) {1681if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))1682return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);16831684if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))1685return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);16861687return ::hasAcceptableDefaultArgument(1688*this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);1689}16901691bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,1692llvm::SmallVectorImpl<Module *> *Modules) {1693return hasAcceptableDefaultArgument(D, Modules,1694Sema::AcceptableKind::Visible);1695}16961697bool Sema::hasReachableDefaultArgument(1698const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1699return hasAcceptableDefaultArgument(D, Modules,1700Sema::AcceptableKind::Reachable);1701}17021703template <typename Filter>1704static bool1705hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,1706llvm::SmallVectorImpl<Module *> *Modules, Filter F,1707Sema::AcceptableKind Kind) {1708bool HasFilteredRedecls = false;17091710for (auto *Redecl : D->redecls()) {1711auto *R = cast<NamedDecl>(Redecl);1712if (!F(R))1713continue;17141715if (S.isAcceptable(R, Kind))1716return true;17171718HasFilteredRedecls = true;17191720if (Modules)1721Modules->push_back(R->getOwningModule());1722}17231724// Only return false if there is at least one redecl that is not filtered out.1725if (HasFilteredRedecls)1726return false;17271728return true;1729}17301731static bool1732hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,1733llvm::SmallVectorImpl<Module *> *Modules,1734Sema::AcceptableKind Kind) {1735return hasAcceptableDeclarationImpl(1736S, D, Modules,1737[](const NamedDecl *D) {1738if (auto *RD = dyn_cast<CXXRecordDecl>(D))1739return RD->getTemplateSpecializationKind() ==1740TSK_ExplicitSpecialization;1741if (auto *FD = dyn_cast<FunctionDecl>(D))1742return FD->getTemplateSpecializationKind() ==1743TSK_ExplicitSpecialization;1744if (auto *VD = dyn_cast<VarDecl>(D))1745return VD->getTemplateSpecializationKind() ==1746TSK_ExplicitSpecialization;1747llvm_unreachable("unknown explicit specialization kind");1748},1749Kind);1750}17511752bool Sema::hasVisibleExplicitSpecialization(1753const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1754return ::hasAcceptableExplicitSpecialization(*this, D, Modules,1755Sema::AcceptableKind::Visible);1756}17571758bool Sema::hasReachableExplicitSpecialization(1759const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1760return ::hasAcceptableExplicitSpecialization(*this, D, Modules,1761Sema::AcceptableKind::Reachable);1762}17631764static bool1765hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,1766llvm::SmallVectorImpl<Module *> *Modules,1767Sema::AcceptableKind Kind) {1768assert(isa<CXXRecordDecl>(D->getDeclContext()) &&1769"not a member specialization");1770return hasAcceptableDeclarationImpl(1771S, D, Modules,1772[](const NamedDecl *D) {1773// If the specialization is declared at namespace scope, then it's a1774// member specialization declaration. If it's lexically inside the class1775// definition then it was instantiated.1776//1777// FIXME: This is a hack. There should be a better way to determine1778// this.1779// FIXME: What about MS-style explicit specializations declared within a1780// class definition?1781return D->getLexicalDeclContext()->isFileContext();1782},1783Kind);1784}17851786bool Sema::hasVisibleMemberSpecialization(1787const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1788return hasAcceptableMemberSpecialization(*this, D, Modules,1789Sema::AcceptableKind::Visible);1790}17911792bool Sema::hasReachableMemberSpecialization(1793const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {1794return hasAcceptableMemberSpecialization(*this, D, Modules,1795Sema::AcceptableKind::Reachable);1796}17971798/// Determine whether a declaration is acceptable to name lookup.1799///1800/// This routine determines whether the declaration D is acceptable in the1801/// current lookup context, taking into account the current template1802/// instantiation stack. During template instantiation, a declaration is1803/// acceptable if it is acceptable from a module containing any entity on the1804/// template instantiation path (by instantiating a template, you allow it to1805/// see the declarations that your module can see, including those later on in1806/// your module).1807bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,1808Sema::AcceptableKind Kind) {1809assert(!D->isUnconditionallyVisible() &&1810"should not call this: not in slow case");18111812Module *DeclModule = SemaRef.getOwningModule(D);1813assert(DeclModule && "hidden decl has no owning module");18141815// If the owning module is visible, the decl is acceptable.1816if (SemaRef.isModuleVisible(DeclModule,1817D->isInvisibleOutsideTheOwningModule()))1818return true;18191820// Determine whether a decl context is a file context for the purpose of1821// visibility/reachability. This looks through some (export and linkage spec)1822// transparent contexts, but not others (enums).1823auto IsEffectivelyFileContext = [](const DeclContext *DC) {1824return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||1825isa<ExportDecl>(DC);1826};18271828// If this declaration is not at namespace scope1829// then it is acceptable if its lexical parent has a acceptable definition.1830DeclContext *DC = D->getLexicalDeclContext();1831if (DC && !IsEffectivelyFileContext(DC)) {1832// For a parameter, check whether our current template declaration's1833// lexical context is acceptable, not whether there's some other acceptable1834// definition of it, because parameters aren't "within" the definition.1835//1836// In C++ we need to check for a acceptable definition due to ODR merging,1837// and in C we must not because each declaration of a function gets its own1838// set of declarations for tags in prototype scope.1839bool AcceptableWithinParent;1840if (D->isTemplateParameter()) {1841bool SearchDefinitions = true;1842if (const auto *DCD = dyn_cast<Decl>(DC)) {1843if (const auto *TD = DCD->getDescribedTemplate()) {1844TemplateParameterList *TPL = TD->getTemplateParameters();1845auto Index = getDepthAndIndex(D).second;1846SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;1847}1848}1849if (SearchDefinitions)1850AcceptableWithinParent =1851SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);1852else1853AcceptableWithinParent =1854isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);1855} else if (isa<ParmVarDecl>(D) ||1856(isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))1857AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);1858else if (D->isModulePrivate()) {1859// A module-private declaration is only acceptable if an enclosing lexical1860// parent was merged with another definition in the current module.1861AcceptableWithinParent = false;1862do {1863if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {1864AcceptableWithinParent = true;1865break;1866}1867DC = DC->getLexicalParent();1868} while (!IsEffectivelyFileContext(DC));1869} else {1870AcceptableWithinParent =1871SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);1872}18731874if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&1875Kind == Sema::AcceptableKind::Visible &&1876// FIXME: Do something better in this case.1877!SemaRef.getLangOpts().ModulesLocalVisibility) {1878// Cache the fact that this declaration is implicitly visible because1879// its parent has a visible definition.1880D->setVisibleDespiteOwningModule();1881}1882return AcceptableWithinParent;1883}18841885if (Kind == Sema::AcceptableKind::Visible)1886return false;18871888assert(Kind == Sema::AcceptableKind::Reachable &&1889"Additional Sema::AcceptableKind?");1890return isReachableSlow(SemaRef, D);1891}18921893bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {1894// The module might be ordinarily visible. For a module-private query, that1895// means it is part of the current module.1896if (ModulePrivate && isUsableModule(M))1897return true;18981899// For a query which is not module-private, that means it is in our visible1900// module set.1901if (!ModulePrivate && VisibleModules.isVisible(M))1902return true;19031904// Otherwise, it might be visible by virtue of the query being within a1905// template instantiation or similar that is permitted to look inside M.19061907// Find the extra places where we need to look.1908const auto &LookupModules = getLookupModules();1909if (LookupModules.empty())1910return false;19111912// If our lookup set contains the module, it's visible.1913if (LookupModules.count(M))1914return true;19151916// The global module fragments are visible to its corresponding module unit.1917// So the global module fragment should be visible if the its corresponding1918// module unit is visible.1919if (M->isGlobalModule() && LookupModules.count(M->getTopLevelModule()))1920return true;19211922// For a module-private query, that's everywhere we get to look.1923if (ModulePrivate)1924return false;19251926// Check whether M is transitively exported to an import of the lookup set.1927return llvm::any_of(LookupModules, [&](const Module *LookupM) {1928return LookupM->isModuleVisible(M);1929});1930}19311932// FIXME: Return false directly if we don't have an interface dependency on the1933// translation unit containing D.1934bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {1935assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");19361937Module *DeclModule = SemaRef.getOwningModule(D);1938assert(DeclModule && "hidden decl has no owning module");19391940// Entities in header like modules are reachable only if they're visible.1941if (DeclModule->isHeaderLikeModule())1942return false;19431944if (!D->isInAnotherModuleUnit())1945return true;19461947// [module.reach]/p3:1948// A declaration D is reachable from a point P if:1949// ...1950// - D is not discarded ([module.global.frag]), appears in a translation unit1951// that is reachable from P, and does not appear within a private module1952// fragment.1953//1954// A declaration that's discarded in the GMF should be module-private.1955if (D->isModulePrivate())1956return false;19571958// [module.reach]/p11959// A translation unit U is necessarily reachable from a point P if U is a1960// module interface unit on which the translation unit containing P has an1961// interface dependency, or the translation unit containing P imports U, in1962// either case prior to P ([module.import]).1963//1964// [module.import]/p101965// A translation unit has an interface dependency on a translation unit U if1966// it contains a declaration (possibly a module-declaration) that imports U1967// or if it has an interface dependency on a translation unit that has an1968// interface dependency on U.1969//1970// So we could conclude the module unit U is necessarily reachable if:1971// (1) The module unit U is module interface unit.1972// (2) The current unit has an interface dependency on the module unit U.1973//1974// Here we only check for the first condition. Since we couldn't see1975// DeclModule if it isn't (transitively) imported.1976if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit())1977return true;19781979// [module.reach]/p21980// Additional translation units on1981// which the point within the program has an interface dependency may be1982// considered reachable, but it is unspecified which are and under what1983// circumstances.1984//1985// The decision here is to treat all additional tranditional units as1986// unreachable.1987return false;1988}19891990bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {1991return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);1992}19931994bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {1995// FIXME: If there are both visible and hidden declarations, we need to take1996// into account whether redeclaration is possible. Example:1997//1998// Non-imported module:1999// int f(T); // #12000// Some TU:2001// static int f(U); // #2, not a redeclaration of #12002// int f(T); // #3, finds both, should link with #1 if T != U, but2003// // with #2 if T == U; neither should be ambiguous.2004for (auto *D : R) {2005if (isVisible(D))2006return true;2007assert(D->isExternallyDeclarable() &&2008"should not have hidden, non-externally-declarable result here");2009}20102011// This function is called once "New" is essentially complete, but before a2012// previous declaration is attached. We can't query the linkage of "New" in2013// general, because attaching the previous declaration can change the2014// linkage of New to match the previous declaration.2015//2016// However, because we've just determined that there is no *visible* prior2017// declaration, we can compute the linkage here. There are two possibilities:2018//2019// * This is not a redeclaration; it's safe to compute the linkage now.2020//2021// * This is a redeclaration of a prior declaration that is externally2022// redeclarable. In that case, the linkage of the declaration is not2023// changed by attaching the prior declaration, because both are externally2024// declarable (and thus ExternalLinkage or VisibleNoLinkage).2025//2026// FIXME: This is subtle and fragile.2027return New->isExternallyDeclarable();2028}20292030/// Retrieve the visible declaration corresponding to D, if any.2031///2032/// This routine determines whether the declaration D is visible in the current2033/// module, with the current imports. If not, it checks whether any2034/// redeclaration of D is visible, and if so, returns that declaration.2035///2036/// \returns D, or a visible previous declaration of D, whichever is more recent2037/// and visible. If no declaration of D is visible, returns null.2038static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,2039unsigned IDNS) {2040assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");20412042for (auto *RD : D->redecls()) {2043// Don't bother with extra checks if we already know this one isn't visible.2044if (RD == D)2045continue;20462047auto ND = cast<NamedDecl>(RD);2048// FIXME: This is wrong in the case where the previous declaration is not2049// visible in the same scope as D. This needs to be done much more2050// carefully.2051if (ND->isInIdentifierNamespace(IDNS) &&2052LookupResult::isAvailableForLookup(SemaRef, ND))2053return ND;2054}20552056return nullptr;2057}20582059bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,2060llvm::SmallVectorImpl<Module *> *Modules) {2061assert(!isVisible(D) && "not in slow case");2062return hasAcceptableDeclarationImpl(2063*this, D, Modules, [](const NamedDecl *) { return true; },2064Sema::AcceptableKind::Visible);2065}20662067bool Sema::hasReachableDeclarationSlow(2068const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {2069assert(!isReachable(D) && "not in slow case");2070return hasAcceptableDeclarationImpl(2071*this, D, Modules, [](const NamedDecl *) { return true; },2072Sema::AcceptableKind::Reachable);2073}20742075NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {2076if (auto *ND = dyn_cast<NamespaceDecl>(D)) {2077// Namespaces are a bit of a special case: we expect there to be a lot of2078// redeclarations of some namespaces, all declarations of a namespace are2079// essentially interchangeable, all declarations are found by name lookup2080// if any is, and namespaces are never looked up during template2081// instantiation. So we benefit from caching the check in this case, and2082// it is correct to do so.2083auto *Key = ND->getCanonicalDecl();2084if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))2085return Acceptable;2086auto *Acceptable = isVisible(getSema(), Key)2087? Key2088: findAcceptableDecl(getSema(), Key, IDNS);2089if (Acceptable)2090getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));2091return Acceptable;2092}20932094return findAcceptableDecl(getSema(), D, IDNS);2095}20962097bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) {2098// If this declaration is already visible, return it directly.2099if (D->isUnconditionallyVisible())2100return true;21012102// During template instantiation, we can refer to hidden declarations, if2103// they were visible in any module along the path of instantiation.2104return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);2105}21062107bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) {2108if (D->isUnconditionallyVisible())2109return true;21102111return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);2112}21132114bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) {2115// We should check the visibility at the callsite already.2116if (isVisible(SemaRef, ND))2117return true;21182119// Deduction guide lives in namespace scope generally, but it is just a2120// hint to the compilers. What we actually lookup for is the generated member2121// of the corresponding template. So it is sufficient to check the2122// reachability of the template decl.2123if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())2124return SemaRef.hasReachableDefinition(DeductionGuide);21252126// FIXME: The lookup for allocation function is a standalone process.2127// (We can find the logics in Sema::FindAllocationFunctions)2128//2129// Such structure makes it a problem when we instantiate a template2130// declaration using placement allocation function if the placement2131// allocation function is invisible.2132// (See https://github.com/llvm/llvm-project/issues/59601)2133//2134// Here we workaround it by making the placement allocation functions2135// always acceptable. The downside is that we can't diagnose the direct2136// use of the invisible placement allocation functions. (Although such uses2137// should be rare).2138if (auto *FD = dyn_cast<FunctionDecl>(ND);2139FD && FD->isReservedGlobalPlacementOperator())2140return true;21412142auto *DC = ND->getDeclContext();2143// If ND is not visible and it is at namespace scope, it shouldn't be found2144// by name lookup.2145if (DC->isFileContext())2146return false;21472148// [module.interface]p72149// Class and enumeration member names can be found by name lookup in any2150// context in which a definition of the type is reachable.2151//2152// FIXME: The current implementation didn't consider about scope. For example,2153// ```2154// // m.cppm2155// export module m;2156// enum E1 { e1 };2157// // Use.cpp2158// import m;2159// void test() {2160// auto a = E1::e1; // Error as expected.2161// auto b = e1; // Should be error. namespace-scope name e1 is not visible2162// }2163// ```2164// For the above example, the current implementation would emit error for `a`2165// correctly. However, the implementation wouldn't diagnose about `b` now.2166// Since we only check the reachability for the parent only.2167// See clang/test/CXX/module/module.interface/p7.cpp for example.2168if (auto *TD = dyn_cast<TagDecl>(DC))2169return SemaRef.hasReachableDefinition(TD);21702171return false;2172}21732174bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,2175bool ForceNoCPlusPlus) {2176DeclarationName Name = R.getLookupName();2177if (!Name) return false;21782179LookupNameKind NameKind = R.getLookupKind();21802181if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {2182// Unqualified name lookup in C/Objective-C is purely lexical, so2183// search in the declarations attached to the name.2184if (NameKind == Sema::LookupRedeclarationWithLinkage) {2185// Find the nearest non-transparent declaration scope.2186while (!(S->getFlags() & Scope::DeclScope) ||2187(S->getEntity() && S->getEntity()->isTransparentContext()))2188S = S->getParent();2189}21902191// When performing a scope lookup, we want to find local extern decls.2192FindLocalExternScope FindLocals(R);21932194// Scan up the scope chain looking for a decl that matches this2195// identifier that is in the appropriate namespace. This search2196// should not take long, as shadowing of names is uncommon, and2197// deep shadowing is extremely uncommon.2198bool LeftStartingScope = false;21992200for (IdentifierResolver::iterator I = IdResolver.begin(Name),2201IEnd = IdResolver.end();2202I != IEnd; ++I)2203if (NamedDecl *D = R.getAcceptableDecl(*I)) {2204if (NameKind == LookupRedeclarationWithLinkage) {2205// Determine whether this (or a previous) declaration is2206// out-of-scope.2207if (!LeftStartingScope && !S->isDeclScope(*I))2208LeftStartingScope = true;22092210// If we found something outside of our starting scope that2211// does not have linkage, skip it.2212if (LeftStartingScope && !((*I)->hasLinkage())) {2213R.setShadowed();2214continue;2215}2216}2217else if (NameKind == LookupObjCImplicitSelfParam &&2218!isa<ImplicitParamDecl>(*I))2219continue;22202221R.addDecl(D);22222223// Check whether there are any other declarations with the same name2224// and in the same scope.2225if (I != IEnd) {2226// Find the scope in which this declaration was declared (if it2227// actually exists in a Scope).2228while (S && !S->isDeclScope(D))2229S = S->getParent();22302231// If the scope containing the declaration is the translation unit,2232// then we'll need to perform our checks based on the matching2233// DeclContexts rather than matching scopes.2234if (S && isNamespaceOrTranslationUnitScope(S))2235S = nullptr;22362237// Compute the DeclContext, if we need it.2238DeclContext *DC = nullptr;2239if (!S)2240DC = (*I)->getDeclContext()->getRedeclContext();22412242IdentifierResolver::iterator LastI = I;2243for (++LastI; LastI != IEnd; ++LastI) {2244if (S) {2245// Match based on scope.2246if (!S->isDeclScope(*LastI))2247break;2248} else {2249// Match based on DeclContext.2250DeclContext *LastDC2251= (*LastI)->getDeclContext()->getRedeclContext();2252if (!LastDC->Equals(DC))2253break;2254}22552256// If the declaration is in the right namespace and visible, add it.2257if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))2258R.addDecl(LastD);2259}22602261R.resolveKind();2262}22632264return true;2265}2266} else {2267// Perform C++ unqualified name lookup.2268if (CppLookupName(R, S))2269return true;2270}22712272// If we didn't find a use of this identifier, and if the identifier2273// corresponds to a compiler builtin, create the decl object for the builtin2274// now, injecting it into translation unit scope, and return it.2275if (AllowBuiltinCreation && LookupBuiltin(R))2276return true;22772278// If we didn't find a use of this identifier, the ExternalSource2279// may be able to handle the situation.2280// Note: some lookup failures are expected!2281// See e.g. R.isForRedeclaration().2282return (ExternalSource && ExternalSource->LookupUnqualified(R, S));2283}22842285/// Perform qualified name lookup in the namespaces nominated by2286/// using directives by the given context.2287///2288/// C++98 [namespace.qual]p2:2289/// Given X::m (where X is a user-declared namespace), or given \::m2290/// (where X is the global namespace), let S be the set of all2291/// declarations of m in X and in the transitive closure of all2292/// namespaces nominated by using-directives in X and its used2293/// namespaces, except that using-directives are ignored in any2294/// namespace, including X, directly containing one or more2295/// declarations of m. No namespace is searched more than once in2296/// the lookup of a name. If S is the empty set, the program is2297/// ill-formed. Otherwise, if S has exactly one member, or if the2298/// context of the reference is a using-declaration2299/// (namespace.udecl), S is the required set of declarations of2300/// m. Otherwise if the use of m is not one that allows a unique2301/// declaration to be chosen from S, the program is ill-formed.2302///2303/// C++98 [namespace.qual]p5:2304/// During the lookup of a qualified namespace member name, if the2305/// lookup finds more than one declaration of the member, and if one2306/// declaration introduces a class name or enumeration name and the2307/// other declarations either introduce the same object, the same2308/// enumerator or a set of functions, the non-type name hides the2309/// class or enumeration name if and only if the declarations are2310/// from the same namespace; otherwise (the declarations are from2311/// different namespaces), the program is ill-formed.2312static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,2313DeclContext *StartDC) {2314assert(StartDC->isFileContext() && "start context is not a file context");23152316// We have not yet looked into these namespaces, much less added2317// their "using-children" to the queue.2318SmallVector<NamespaceDecl*, 8> Queue;23192320// We have at least added all these contexts to the queue.2321llvm::SmallPtrSet<DeclContext*, 8> Visited;2322Visited.insert(StartDC);23232324// We have already looked into the initial namespace; seed the queue2325// with its using-children.2326for (auto *I : StartDC->using_directives()) {2327NamespaceDecl *ND = I->getNominatedNamespace()->getFirstDecl();2328if (S.isVisible(I) && Visited.insert(ND).second)2329Queue.push_back(ND);2330}23312332// The easiest way to implement the restriction in [namespace.qual]p52333// is to check whether any of the individual results found a tag2334// and, if so, to declare an ambiguity if the final result is not2335// a tag.2336bool FoundTag = false;2337bool FoundNonTag = false;23382339LookupResult LocalR(LookupResult::Temporary, R);23402341bool Found = false;2342while (!Queue.empty()) {2343NamespaceDecl *ND = Queue.pop_back_val();23442345// We go through some convolutions here to avoid copying results2346// between LookupResults.2347bool UseLocal = !R.empty();2348LookupResult &DirectR = UseLocal ? LocalR : R;2349bool FoundDirect = LookupDirect(S, DirectR, ND);23502351if (FoundDirect) {2352// First do any local hiding.2353DirectR.resolveKind();23542355// If the local result is a tag, remember that.2356if (DirectR.isSingleTagDecl())2357FoundTag = true;2358else2359FoundNonTag = true;23602361// Append the local results to the total results if necessary.2362if (UseLocal) {2363R.addAllDecls(LocalR);2364LocalR.clear();2365}2366}23672368// If we find names in this namespace, ignore its using directives.2369if (FoundDirect) {2370Found = true;2371continue;2372}23732374for (auto *I : ND->using_directives()) {2375NamespaceDecl *Nom = I->getNominatedNamespace();2376if (S.isVisible(I) && Visited.insert(Nom).second)2377Queue.push_back(Nom);2378}2379}23802381if (Found) {2382if (FoundTag && FoundNonTag)2383R.setAmbiguousQualifiedTagHiding();2384else2385R.resolveKind();2386}23872388return Found;2389}23902391bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,2392bool InUnqualifiedLookup) {2393assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");23942395if (!R.getLookupName())2396return false;23972398// Make sure that the declaration context is complete.2399assert((!isa<TagDecl>(LookupCtx) ||2400LookupCtx->isDependentContext() ||2401cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||2402cast<TagDecl>(LookupCtx)->isBeingDefined()) &&2403"Declaration context must already be complete!");24042405struct QualifiedLookupInScope {2406bool oldVal;2407DeclContext *Context;2408// Set flag in DeclContext informing debugger that we're looking for qualified name2409QualifiedLookupInScope(DeclContext *ctx)2410: oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) {2411ctx->setUseQualifiedLookup();2412}2413~QualifiedLookupInScope() {2414Context->setUseQualifiedLookup(oldVal);2415}2416} QL(LookupCtx);24172418CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);2419// FIXME: Per [temp.dep.general]p2, an unqualified name is also dependent2420// if it's a dependent conversion-function-id or operator= where the current2421// class is a templated entity. This should be handled in LookupName.2422if (!InUnqualifiedLookup && !R.isForRedeclaration()) {2423// C++23 [temp.dep.type]p5:2424// A qualified name is dependent if2425// - it is a conversion-function-id whose conversion-type-id2426// is dependent, or2427// - [...]2428// - its lookup context is the current instantiation and it2429// is operator=, or2430// - [...]2431if (DeclarationName Name = R.getLookupName();2432Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&2433Name.getCXXNameType()->isDependentType()) {2434R.setNotFoundInCurrentInstantiation();2435return false;2436}2437}24382439if (LookupDirect(*this, R, LookupCtx)) {2440R.resolveKind();2441if (LookupRec)2442R.setNamingClass(LookupRec);2443return true;2444}24452446// Don't descend into implied contexts for redeclarations.2447// C++98 [namespace.qual]p6:2448// In a declaration for a namespace member in which the2449// declarator-id is a qualified-id, given that the qualified-id2450// for the namespace member has the form2451// nested-name-specifier unqualified-id2452// the unqualified-id shall name a member of the namespace2453// designated by the nested-name-specifier.2454// See also [class.mfct]p5 and [class.static.data]p2.2455if (R.isForRedeclaration())2456return false;24572458// If this is a namespace, look it up in the implied namespaces.2459if (LookupCtx->isFileContext())2460return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);24612462// If this isn't a C++ class, we aren't allowed to look into base2463// classes, we're done.2464if (!LookupRec || !LookupRec->getDefinition())2465return false;24662467// We're done for lookups that can never succeed for C++ classes.2468if (R.getLookupKind() == LookupOperatorName ||2469R.getLookupKind() == LookupNamespaceName ||2470R.getLookupKind() == LookupObjCProtocolName ||2471R.getLookupKind() == LookupLabel)2472return false;24732474// If we're performing qualified name lookup into a dependent class,2475// then we are actually looking into a current instantiation. If we have any2476// dependent base classes, then we either have to delay lookup until2477// template instantiation time (at which point all bases will be available)2478// or we have to fail.2479if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&2480LookupRec->hasAnyDependentBases()) {2481R.setNotFoundInCurrentInstantiation();2482return false;2483}24842485// Perform lookup into our base classes.24862487DeclarationName Name = R.getLookupName();2488unsigned IDNS = R.getIdentifierNamespace();24892490// Look for this member in our base classes.2491auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,2492CXXBasePath &Path) -> bool {2493CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();2494// Drop leading non-matching lookup results from the declaration list so2495// we don't need to consider them again below.2496for (Path.Decls = BaseRecord->lookup(Name).begin();2497Path.Decls != Path.Decls.end(); ++Path.Decls) {2498if ((*Path.Decls)->isInIdentifierNamespace(IDNS))2499return true;2500}2501return false;2502};25032504CXXBasePaths Paths;2505Paths.setOrigin(LookupRec);2506if (!LookupRec->lookupInBases(BaseCallback, Paths))2507return false;25082509R.setNamingClass(LookupRec);25102511// C++ [class.member.lookup]p2:2512// [...] If the resulting set of declarations are not all from2513// sub-objects of the same type, or the set has a nonstatic member2514// and includes members from distinct sub-objects, there is an2515// ambiguity and the program is ill-formed. Otherwise that set is2516// the result of the lookup.2517QualType SubobjectType;2518int SubobjectNumber = 0;2519AccessSpecifier SubobjectAccess = AS_none;25202521// Check whether the given lookup result contains only static members.2522auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {2523for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)2524if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())2525return false;2526return true;2527};25282529bool TemplateNameLookup = R.isTemplateNameLookup();25302531// Determine whether two sets of members contain the same members, as2532// required by C++ [class.member.lookup]p6.2533auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,2534DeclContext::lookup_iterator B) {2535using Iterator = DeclContextLookupResult::iterator;2536using Result = const void *;25372538auto Next = [&](Iterator &It, Iterator End) -> Result {2539while (It != End) {2540NamedDecl *ND = *It++;2541if (!ND->isInIdentifierNamespace(IDNS))2542continue;25432544// C++ [temp.local]p3:2545// A lookup that finds an injected-class-name (10.2) can result in2546// an ambiguity in certain cases (for example, if it is found in2547// more than one base class). If all of the injected-class-names2548// that are found refer to specializations of the same class2549// template, and if the name is used as a template-name, the2550// reference refers to the class template itself and not a2551// specialization thereof, and is not ambiguous.2552if (TemplateNameLookup)2553if (auto *TD = getAsTemplateNameDecl(ND))2554ND = TD;25552556// C++ [class.member.lookup]p3:2557// type declarations (including injected-class-names) are replaced by2558// the types they designate2559if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {2560QualType T = Context.getTypeDeclType(TD);2561return T.getCanonicalType().getAsOpaquePtr();2562}25632564return ND->getUnderlyingDecl()->getCanonicalDecl();2565}2566return nullptr;2567};25682569// We'll often find the declarations are in the same order. Handle this2570// case (and the special case of only one declaration) efficiently.2571Iterator AIt = A, BIt = B, AEnd, BEnd;2572while (true) {2573Result AResult = Next(AIt, AEnd);2574Result BResult = Next(BIt, BEnd);2575if (!AResult && !BResult)2576return true;2577if (!AResult || !BResult)2578return false;2579if (AResult != BResult) {2580// Found a mismatch; carefully check both lists, accounting for the2581// possibility of declarations appearing more than once.2582llvm::SmallDenseMap<Result, bool, 32> AResults;2583for (; AResult; AResult = Next(AIt, AEnd))2584AResults.insert({AResult, /*FoundInB*/false});2585unsigned Found = 0;2586for (; BResult; BResult = Next(BIt, BEnd)) {2587auto It = AResults.find(BResult);2588if (It == AResults.end())2589return false;2590if (!It->second) {2591It->second = true;2592++Found;2593}2594}2595return AResults.size() == Found;2596}2597}2598};25992600for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();2601Path != PathEnd; ++Path) {2602const CXXBasePathElement &PathElement = Path->back();26032604// Pick the best (i.e. most permissive i.e. numerically lowest) access2605// across all paths.2606SubobjectAccess = std::min(SubobjectAccess, Path->Access);26072608// Determine whether we're looking at a distinct sub-object or not.2609if (SubobjectType.isNull()) {2610// This is the first subobject we've looked at. Record its type.2611SubobjectType = Context.getCanonicalType(PathElement.Base->getType());2612SubobjectNumber = PathElement.SubobjectNumber;2613continue;2614}26152616if (SubobjectType !=2617Context.getCanonicalType(PathElement.Base->getType())) {2618// We found members of the given name in two subobjects of2619// different types. If the declaration sets aren't the same, this2620// lookup is ambiguous.2621//2622// FIXME: The language rule says that this applies irrespective of2623// whether the sets contain only static members.2624if (HasOnlyStaticMembers(Path->Decls) &&2625HasSameDeclarations(Paths.begin()->Decls, Path->Decls))2626continue;26272628R.setAmbiguousBaseSubobjectTypes(Paths);2629return true;2630}26312632// FIXME: This language rule no longer exists. Checking for ambiguous base2633// subobjects should be done as part of formation of a class member access2634// expression (when converting the object parameter to the member's type).2635if (SubobjectNumber != PathElement.SubobjectNumber) {2636// We have a different subobject of the same type.26372638// C++ [class.member.lookup]p5:2639// A static member, a nested type or an enumerator defined in2640// a base class T can unambiguously be found even if an object2641// has more than one base class subobject of type T.2642if (HasOnlyStaticMembers(Path->Decls))2643continue;26442645// We have found a nonstatic member name in multiple, distinct2646// subobjects. Name lookup is ambiguous.2647R.setAmbiguousBaseSubobjects(Paths);2648return true;2649}2650}26512652// Lookup in a base class succeeded; return these results.26532654for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();2655I != E; ++I) {2656AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,2657(*I)->getAccess());2658if (NamedDecl *ND = R.getAcceptableDecl(*I))2659R.addDecl(ND, AS);2660}2661R.resolveKind();2662return true;2663}26642665bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,2666CXXScopeSpec &SS) {2667auto *NNS = SS.getScopeRep();2668if (NNS && NNS->getKind() == NestedNameSpecifier::Super)2669return LookupInSuper(R, NNS->getAsRecordDecl());2670else26712672return LookupQualifiedName(R, LookupCtx);2673}26742675bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,2676QualType ObjectType, bool AllowBuiltinCreation,2677bool EnteringContext) {2678// When the scope specifier is invalid, don't even look for anything.2679if (SS && SS->isInvalid())2680return false;26812682// Determine where to perform name lookup2683DeclContext *DC = nullptr;2684bool IsDependent = false;2685if (!ObjectType.isNull()) {2686// This nested-name-specifier occurs in a member access expression, e.g.,2687// x->B::f, and we are looking into the type of the object.2688assert((!SS || SS->isEmpty()) &&2689"ObjectType and scope specifier cannot coexist");2690DC = computeDeclContext(ObjectType);2691IsDependent = !DC && ObjectType->isDependentType();2692assert(((!DC && ObjectType->isDependentType()) ||2693!ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() ||2694ObjectType->castAs<TagType>()->isBeingDefined()) &&2695"Caller should have completed object type");2696} else if (SS && SS->isNotEmpty()) {2697// This nested-name-specifier occurs after another nested-name-specifier,2698// so long into the context associated with the prior nested-name-specifier.2699if ((DC = computeDeclContext(*SS, EnteringContext))) {2700// The declaration context must be complete.2701if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))2702return false;2703R.setContextRange(SS->getRange());2704// FIXME: '__super' lookup semantics could be implemented by a2705// LookupResult::isSuperLookup flag which skips the initial search of2706// the lookup context in LookupQualified.2707if (NestedNameSpecifier *NNS = SS->getScopeRep();2708NNS->getKind() == NestedNameSpecifier::Super)2709return LookupInSuper(R, NNS->getAsRecordDecl());2710}2711IsDependent = !DC && isDependentScopeSpecifier(*SS);2712} else {2713// Perform unqualified name lookup starting in the given scope.2714return LookupName(R, S, AllowBuiltinCreation);2715}27162717// If we were able to compute a declaration context, perform qualified name2718// lookup in that context.2719if (DC)2720return LookupQualifiedName(R, DC);2721else if (IsDependent)2722// We could not resolve the scope specified to a specific declaration2723// context, which means that SS refers to an unknown specialization.2724// Name lookup can't find anything in this case.2725R.setNotFoundInCurrentInstantiation();2726return false;2727}27282729bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {2730// The access-control rules we use here are essentially the rules for2731// doing a lookup in Class that just magically skipped the direct2732// members of Class itself. That is, the naming class is Class, and the2733// access includes the access of the base.2734for (const auto &BaseSpec : Class->bases()) {2735CXXRecordDecl *RD = cast<CXXRecordDecl>(2736BaseSpec.getType()->castAs<RecordType>()->getDecl());2737LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());2738Result.setBaseObjectType(Context.getRecordType(Class));2739LookupQualifiedName(Result, RD);27402741// Copy the lookup results into the target, merging the base's access into2742// the path access.2743for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {2744R.addDecl(I.getDecl(),2745CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),2746I.getAccess()));2747}27482749Result.suppressDiagnostics();2750}27512752R.resolveKind();2753R.setNamingClass(Class);27542755return !R.empty();2756}27572758void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {2759assert(Result.isAmbiguous() && "Lookup result must be ambiguous");27602761DeclarationName Name = Result.getLookupName();2762SourceLocation NameLoc = Result.getNameLoc();2763SourceRange LookupRange = Result.getContextRange();27642765switch (Result.getAmbiguityKind()) {2766case LookupResult::AmbiguousBaseSubobjects: {2767CXXBasePaths *Paths = Result.getBasePaths();2768QualType SubobjectType = Paths->front().back().Base->getType();2769Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)2770<< Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)2771<< LookupRange;27722773DeclContext::lookup_iterator Found = Paths->front().Decls;2774while (isa<CXXMethodDecl>(*Found) &&2775cast<CXXMethodDecl>(*Found)->isStatic())2776++Found;27772778Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);2779break;2780}27812782case LookupResult::AmbiguousBaseSubobjectTypes: {2783Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)2784<< Name << LookupRange;27852786CXXBasePaths *Paths = Result.getBasePaths();2787std::set<const NamedDecl *> DeclsPrinted;2788for (CXXBasePaths::paths_iterator Path = Paths->begin(),2789PathEnd = Paths->end();2790Path != PathEnd; ++Path) {2791const NamedDecl *D = *Path->Decls;2792if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))2793continue;2794if (DeclsPrinted.insert(D).second) {2795if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))2796Diag(D->getLocation(), diag::note_ambiguous_member_type_found)2797<< TD->getUnderlyingType();2798else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))2799Diag(D->getLocation(), diag::note_ambiguous_member_type_found)2800<< Context.getTypeDeclType(TD);2801else2802Diag(D->getLocation(), diag::note_ambiguous_member_found);2803}2804}2805break;2806}28072808case LookupResult::AmbiguousTagHiding: {2809Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;28102811llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;28122813for (auto *D : Result)2814if (TagDecl *TD = dyn_cast<TagDecl>(D)) {2815TagDecls.insert(TD);2816Diag(TD->getLocation(), diag::note_hidden_tag);2817}28182819for (auto *D : Result)2820if (!isa<TagDecl>(D))2821Diag(D->getLocation(), diag::note_hiding_object);28222823// For recovery purposes, go ahead and implement the hiding.2824LookupResult::Filter F = Result.makeFilter();2825while (F.hasNext()) {2826if (TagDecls.count(F.next()))2827F.erase();2828}2829F.done();2830break;2831}28322833case LookupResult::AmbiguousReferenceToPlaceholderVariable: {2834Diag(NameLoc, diag::err_using_placeholder_variable) << Name << LookupRange;2835DeclContext *DC = nullptr;2836for (auto *D : Result) {2837Diag(D->getLocation(), diag::note_reference_placeholder) << D;2838if (DC != nullptr && DC != D->getDeclContext())2839break;2840DC = D->getDeclContext();2841}2842break;2843}28442845case LookupResult::AmbiguousReference: {2846Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;28472848for (auto *D : Result)2849Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;2850break;2851}2852}2853}28542855namespace {2856struct AssociatedLookup {2857AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,2858Sema::AssociatedNamespaceSet &Namespaces,2859Sema::AssociatedClassSet &Classes)2860: S(S), Namespaces(Namespaces), Classes(Classes),2861InstantiationLoc(InstantiationLoc) {2862}28632864bool addClassTransitive(CXXRecordDecl *RD) {2865Classes.insert(RD);2866return ClassesTransitive.insert(RD);2867}28682869Sema &S;2870Sema::AssociatedNamespaceSet &Namespaces;2871Sema::AssociatedClassSet &Classes;2872SourceLocation InstantiationLoc;28732874private:2875Sema::AssociatedClassSet ClassesTransitive;2876};2877} // end anonymous namespace28782879static void2880addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);28812882// Given the declaration context \param Ctx of a class, class template or2883// enumeration, add the associated namespaces to \param Namespaces as described2884// in [basic.lookup.argdep]p2.2885static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,2886DeclContext *Ctx) {2887// The exact wording has been changed in C++14 as a result of2888// CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally2889// to all language versions since it is possible to return a local type2890// from a lambda in C++11.2891//2892// C++14 [basic.lookup.argdep]p2:2893// If T is a class type [...]. Its associated namespaces are the innermost2894// enclosing namespaces of its associated classes. [...]2895//2896// If T is an enumeration type, its associated namespace is the innermost2897// enclosing namespace of its declaration. [...]28982899// We additionally skip inline namespaces. The innermost non-inline namespace2900// contains all names of all its nested inline namespaces anyway, so we can2901// replace the entire inline namespace tree with its root.2902while (!Ctx->isFileContext() || Ctx->isInlineNamespace())2903Ctx = Ctx->getParent();29042905Namespaces.insert(Ctx->getPrimaryContext());2906}29072908// Add the associated classes and namespaces for argument-dependent2909// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).2910static void2911addAssociatedClassesAndNamespaces(AssociatedLookup &Result,2912const TemplateArgument &Arg) {2913// C++ [basic.lookup.argdep]p2, last bullet:2914// -- [...] ;2915switch (Arg.getKind()) {2916case TemplateArgument::Null:2917break;29182919case TemplateArgument::Type:2920// [...] the namespaces and classes associated with the types of the2921// template arguments provided for template type parameters (excluding2922// template template parameters)2923addAssociatedClassesAndNamespaces(Result, Arg.getAsType());2924break;29252926case TemplateArgument::Template:2927case TemplateArgument::TemplateExpansion: {2928// [...] the namespaces in which any template template arguments are2929// defined; and the classes in which any member templates used as2930// template template arguments are defined.2931TemplateName Template = Arg.getAsTemplateOrTemplatePattern();2932if (ClassTemplateDecl *ClassTemplate2933= dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {2934DeclContext *Ctx = ClassTemplate->getDeclContext();2935if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))2936Result.Classes.insert(EnclosingClass);2937// Add the associated namespace for this class.2938CollectEnclosingNamespace(Result.Namespaces, Ctx);2939}2940break;2941}29422943case TemplateArgument::Declaration:2944case TemplateArgument::Integral:2945case TemplateArgument::Expression:2946case TemplateArgument::NullPtr:2947case TemplateArgument::StructuralValue:2948// [Note: non-type template arguments do not contribute to the set of2949// associated namespaces. ]2950break;29512952case TemplateArgument::Pack:2953for (const auto &P : Arg.pack_elements())2954addAssociatedClassesAndNamespaces(Result, P);2955break;2956}2957}29582959// Add the associated classes and namespaces for argument-dependent lookup2960// with an argument of class type (C++ [basic.lookup.argdep]p2).2961static void2962addAssociatedClassesAndNamespaces(AssociatedLookup &Result,2963CXXRecordDecl *Class) {29642965// Just silently ignore anything whose name is __va_list_tag.2966if (Class->getDeclName() == Result.S.VAListTagName)2967return;29682969// C++ [basic.lookup.argdep]p2:2970// [...]2971// -- If T is a class type (including unions), its associated2972// classes are: the class itself; the class of which it is a2973// member, if any; and its direct and indirect base classes.2974// Its associated namespaces are the innermost enclosing2975// namespaces of its associated classes.29762977// Add the class of which it is a member, if any.2978DeclContext *Ctx = Class->getDeclContext();2979if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))2980Result.Classes.insert(EnclosingClass);29812982// Add the associated namespace for this class.2983CollectEnclosingNamespace(Result.Namespaces, Ctx);29842985// -- If T is a template-id, its associated namespaces and classes are2986// the namespace in which the template is defined; for member2987// templates, the member template's class; the namespaces and classes2988// associated with the types of the template arguments provided for2989// template type parameters (excluding template template parameters); the2990// namespaces in which any template template arguments are defined; and2991// the classes in which any member templates used as template template2992// arguments are defined. [Note: non-type template arguments do not2993// contribute to the set of associated namespaces. ]2994if (ClassTemplateSpecializationDecl *Spec2995= dyn_cast<ClassTemplateSpecializationDecl>(Class)) {2996DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();2997if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))2998Result.Classes.insert(EnclosingClass);2999// Add the associated namespace for this class.3000CollectEnclosingNamespace(Result.Namespaces, Ctx);30013002const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();3003for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)3004addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);3005}30063007// Add the class itself. If we've already transitively visited this class,3008// we don't need to visit base classes.3009if (!Result.addClassTransitive(Class))3010return;30113012// Only recurse into base classes for complete types.3013if (!Result.S.isCompleteType(Result.InstantiationLoc,3014Result.S.Context.getRecordType(Class)))3015return;30163017// Add direct and indirect base classes along with their associated3018// namespaces.3019SmallVector<CXXRecordDecl *, 32> Bases;3020Bases.push_back(Class);3021while (!Bases.empty()) {3022// Pop this class off the stack.3023Class = Bases.pop_back_val();30243025// Visit the base classes.3026for (const auto &Base : Class->bases()) {3027const RecordType *BaseType = Base.getType()->getAs<RecordType>();3028// In dependent contexts, we do ADL twice, and the first time around,3029// the base type might be a dependent TemplateSpecializationType, or a3030// TemplateTypeParmType. If that happens, simply ignore it.3031// FIXME: If we want to support export, we probably need to add the3032// namespace of the template in a TemplateSpecializationType, or even3033// the classes and namespaces of known non-dependent arguments.3034if (!BaseType)3035continue;3036CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());3037if (Result.addClassTransitive(BaseDecl)) {3038// Find the associated namespace for this base class.3039DeclContext *BaseCtx = BaseDecl->getDeclContext();3040CollectEnclosingNamespace(Result.Namespaces, BaseCtx);30413042// Make sure we visit the bases of this base class.3043if (BaseDecl->bases_begin() != BaseDecl->bases_end())3044Bases.push_back(BaseDecl);3045}3046}3047}3048}30493050// Add the associated classes and namespaces for3051// argument-dependent lookup with an argument of type T3052// (C++ [basic.lookup.koenig]p2).3053static void3054addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {3055// C++ [basic.lookup.koenig]p2:3056//3057// For each argument type T in the function call, there is a set3058// of zero or more associated namespaces and a set of zero or more3059// associated classes to be considered. The sets of namespaces and3060// classes is determined entirely by the types of the function3061// arguments (and the namespace of any template template3062// argument). Typedef names and using-declarations used to specify3063// the types do not contribute to this set. The sets of namespaces3064// and classes are determined in the following way:30653066SmallVector<const Type *, 16> Queue;3067const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();30683069while (true) {3070switch (T->getTypeClass()) {30713072#define TYPE(Class, Base)3073#define DEPENDENT_TYPE(Class, Base) case Type::Class:3074#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:3075#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:3076#define ABSTRACT_TYPE(Class, Base)3077#include "clang/AST/TypeNodes.inc"3078// T is canonical. We can also ignore dependent types because3079// we don't need to do ADL at the definition point, but if we3080// wanted to implement template export (or if we find some other3081// use for associated classes and namespaces...) this would be3082// wrong.3083break;30843085// -- If T is a pointer to U or an array of U, its associated3086// namespaces and classes are those associated with U.3087case Type::Pointer:3088T = cast<PointerType>(T)->getPointeeType().getTypePtr();3089continue;3090case Type::ConstantArray:3091case Type::IncompleteArray:3092case Type::VariableArray:3093T = cast<ArrayType>(T)->getElementType().getTypePtr();3094continue;30953096// -- If T is a fundamental type, its associated sets of3097// namespaces and classes are both empty.3098case Type::Builtin:3099break;31003101// -- If T is a class type (including unions), its associated3102// classes are: the class itself; the class of which it is3103// a member, if any; and its direct and indirect base classes.3104// Its associated namespaces are the innermost enclosing3105// namespaces of its associated classes.3106case Type::Record: {3107CXXRecordDecl *Class =3108cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());3109addAssociatedClassesAndNamespaces(Result, Class);3110break;3111}31123113// -- If T is an enumeration type, its associated namespace3114// is the innermost enclosing namespace of its declaration.3115// If it is a class member, its associated class is the3116// member’s class; else it has no associated class.3117case Type::Enum: {3118EnumDecl *Enum = cast<EnumType>(T)->getDecl();31193120DeclContext *Ctx = Enum->getDeclContext();3121if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))3122Result.Classes.insert(EnclosingClass);31233124// Add the associated namespace for this enumeration.3125CollectEnclosingNamespace(Result.Namespaces, Ctx);31263127break;3128}31293130// -- If T is a function type, its associated namespaces and3131// classes are those associated with the function parameter3132// types and those associated with the return type.3133case Type::FunctionProto: {3134const FunctionProtoType *Proto = cast<FunctionProtoType>(T);3135for (const auto &Arg : Proto->param_types())3136Queue.push_back(Arg.getTypePtr());3137// fallthrough3138[[fallthrough]];3139}3140case Type::FunctionNoProto: {3141const FunctionType *FnType = cast<FunctionType>(T);3142T = FnType->getReturnType().getTypePtr();3143continue;3144}31453146// -- If T is a pointer to a member function of a class X, its3147// associated namespaces and classes are those associated3148// with the function parameter types and return type,3149// together with those associated with X.3150//3151// -- If T is a pointer to a data member of class X, its3152// associated namespaces and classes are those associated3153// with the member type together with those associated with3154// X.3155case Type::MemberPointer: {3156const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);31573158// Queue up the class type into which this points.3159Queue.push_back(MemberPtr->getClass());31603161// And directly continue with the pointee type.3162T = MemberPtr->getPointeeType().getTypePtr();3163continue;3164}31653166// As an extension, treat this like a normal pointer.3167case Type::BlockPointer:3168T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();3169continue;31703171// References aren't covered by the standard, but that's such an3172// obvious defect that we cover them anyway.3173case Type::LValueReference:3174case Type::RValueReference:3175T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();3176continue;31773178// These are fundamental types.3179case Type::Vector:3180case Type::ExtVector:3181case Type::ConstantMatrix:3182case Type::Complex:3183case Type::BitInt:3184break;31853186// Non-deduced auto types only get here for error cases.3187case Type::Auto:3188case Type::DeducedTemplateSpecialization:3189break;31903191// If T is an Objective-C object or interface type, or a pointer to an3192// object or interface type, the associated namespace is the global3193// namespace.3194case Type::ObjCObject:3195case Type::ObjCInterface:3196case Type::ObjCObjectPointer:3197Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());3198break;31993200// Atomic types are just wrappers; use the associations of the3201// contained type.3202case Type::Atomic:3203T = cast<AtomicType>(T)->getValueType().getTypePtr();3204continue;3205case Type::Pipe:3206T = cast<PipeType>(T)->getElementType().getTypePtr();3207continue;32083209// Array parameter types are treated as fundamental types.3210case Type::ArrayParameter:3211break;3212}32133214if (Queue.empty())3215break;3216T = Queue.pop_back_val();3217}3218}32193220void Sema::FindAssociatedClassesAndNamespaces(3221SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,3222AssociatedNamespaceSet &AssociatedNamespaces,3223AssociatedClassSet &AssociatedClasses) {3224AssociatedNamespaces.clear();3225AssociatedClasses.clear();32263227AssociatedLookup Result(*this, InstantiationLoc,3228AssociatedNamespaces, AssociatedClasses);32293230// C++ [basic.lookup.koenig]p2:3231// For each argument type T in the function call, there is a set3232// of zero or more associated namespaces and a set of zero or more3233// associated classes to be considered. The sets of namespaces and3234// classes is determined entirely by the types of the function3235// arguments (and the namespace of any template template3236// argument).3237for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {3238Expr *Arg = Args[ArgIdx];32393240if (Arg->getType() != Context.OverloadTy) {3241addAssociatedClassesAndNamespaces(Result, Arg->getType());3242continue;3243}32443245// [...] In addition, if the argument is the name or address of a3246// set of overloaded functions and/or function templates, its3247// associated classes and namespaces are the union of those3248// associated with each of the members of the set: the namespace3249// in which the function or function template is defined and the3250// classes and namespaces associated with its (non-dependent)3251// parameter types and return type.3252OverloadExpr *OE = OverloadExpr::find(Arg).Expression;32533254for (const NamedDecl *D : OE->decls()) {3255// Look through any using declarations to find the underlying function.3256const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();32573258// Add the classes and namespaces associated with the parameter3259// types and return type of this function.3260addAssociatedClassesAndNamespaces(Result, FDecl->getType());3261}3262}3263}32643265NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,3266SourceLocation Loc,3267LookupNameKind NameKind,3268RedeclarationKind Redecl) {3269LookupResult R(*this, Name, Loc, NameKind, Redecl);3270LookupName(R, S);3271return R.getAsSingle<NamedDecl>();3272}32733274void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,3275UnresolvedSetImpl &Functions) {3276// C++ [over.match.oper]p3:3277// -- The set of non-member candidates is the result of the3278// unqualified lookup of operator@ in the context of the3279// expression according to the usual rules for name lookup in3280// unqualified function calls (3.4.2) except that all member3281// functions are ignored.3282DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);3283LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);3284LookupName(Operators, S);32853286assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");3287Functions.append(Operators.begin(), Operators.end());3288}32893290Sema::SpecialMemberOverloadResult3291Sema::LookupSpecialMember(CXXRecordDecl *RD, CXXSpecialMemberKind SM,3292bool ConstArg, bool VolatileArg, bool RValueThis,3293bool ConstThis, bool VolatileThis) {3294assert(CanDeclareSpecialMemberFunction(RD) &&3295"doing special member lookup into record that isn't fully complete");3296RD = RD->getDefinition();3297if (RValueThis || ConstThis || VolatileThis)3298assert((SM == CXXSpecialMemberKind::CopyAssignment ||3299SM == CXXSpecialMemberKind::MoveAssignment) &&3300"constructors and destructors always have unqualified lvalue this");3301if (ConstArg || VolatileArg)3302assert((SM != CXXSpecialMemberKind::DefaultConstructor &&3303SM != CXXSpecialMemberKind::Destructor) &&3304"parameter-less special members can't have qualified arguments");33053306// FIXME: Get the caller to pass in a location for the lookup.3307SourceLocation LookupLoc = RD->getLocation();33083309llvm::FoldingSetNodeID ID;3310ID.AddPointer(RD);3311ID.AddInteger(llvm::to_underlying(SM));3312ID.AddInteger(ConstArg);3313ID.AddInteger(VolatileArg);3314ID.AddInteger(RValueThis);3315ID.AddInteger(ConstThis);3316ID.AddInteger(VolatileThis);33173318void *InsertPoint;3319SpecialMemberOverloadResultEntry *Result =3320SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);33213322// This was already cached3323if (Result)3324return *Result;33253326Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();3327Result = new (Result) SpecialMemberOverloadResultEntry(ID);3328SpecialMemberCache.InsertNode(Result, InsertPoint);33293330if (SM == CXXSpecialMemberKind::Destructor) {3331if (RD->needsImplicitDestructor()) {3332runWithSufficientStackSpace(RD->getLocation(), [&] {3333DeclareImplicitDestructor(RD);3334});3335}3336CXXDestructorDecl *DD = RD->getDestructor();3337Result->setMethod(DD);3338Result->setKind(DD && !DD->isDeleted()3339? SpecialMemberOverloadResult::Success3340: SpecialMemberOverloadResult::NoMemberOrDeleted);3341return *Result;3342}33433344// Prepare for overload resolution. Here we construct a synthetic argument3345// if necessary and make sure that implicit functions are declared.3346CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));3347DeclarationName Name;3348Expr *Arg = nullptr;3349unsigned NumArgs;33503351QualType ArgType = CanTy;3352ExprValueKind VK = VK_LValue;33533354if (SM == CXXSpecialMemberKind::DefaultConstructor) {3355Name = Context.DeclarationNames.getCXXConstructorName(CanTy);3356NumArgs = 0;3357if (RD->needsImplicitDefaultConstructor()) {3358runWithSufficientStackSpace(RD->getLocation(), [&] {3359DeclareImplicitDefaultConstructor(RD);3360});3361}3362} else {3363if (SM == CXXSpecialMemberKind::CopyConstructor ||3364SM == CXXSpecialMemberKind::MoveConstructor) {3365Name = Context.DeclarationNames.getCXXConstructorName(CanTy);3366if (RD->needsImplicitCopyConstructor()) {3367runWithSufficientStackSpace(RD->getLocation(), [&] {3368DeclareImplicitCopyConstructor(RD);3369});3370}3371if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {3372runWithSufficientStackSpace(RD->getLocation(), [&] {3373DeclareImplicitMoveConstructor(RD);3374});3375}3376} else {3377Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);3378if (RD->needsImplicitCopyAssignment()) {3379runWithSufficientStackSpace(RD->getLocation(), [&] {3380DeclareImplicitCopyAssignment(RD);3381});3382}3383if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {3384runWithSufficientStackSpace(RD->getLocation(), [&] {3385DeclareImplicitMoveAssignment(RD);3386});3387}3388}33893390if (ConstArg)3391ArgType.addConst();3392if (VolatileArg)3393ArgType.addVolatile();33943395// This isn't /really/ specified by the standard, but it's implied3396// we should be working from a PRValue in the case of move to ensure3397// that we prefer to bind to rvalue references, and an LValue in the3398// case of copy to ensure we don't bind to rvalue references.3399// Possibly an XValue is actually correct in the case of move, but3400// there is no semantic difference for class types in this restricted3401// case.3402if (SM == CXXSpecialMemberKind::CopyConstructor ||3403SM == CXXSpecialMemberKind::CopyAssignment)3404VK = VK_LValue;3405else3406VK = VK_PRValue;3407}34083409OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);34103411if (SM != CXXSpecialMemberKind::DefaultConstructor) {3412NumArgs = 1;3413Arg = &FakeArg;3414}34153416// Create the object argument3417QualType ThisTy = CanTy;3418if (ConstThis)3419ThisTy.addConst();3420if (VolatileThis)3421ThisTy.addVolatile();3422Expr::Classification Classification =3423OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)3424.Classify(Context);34253426// Now we perform lookup on the name we computed earlier and do overload3427// resolution. Lookup is only performed directly into the class since there3428// will always be a (possibly implicit) declaration to shadow any others.3429OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);3430DeclContext::lookup_result R = RD->lookup(Name);34313432if (R.empty()) {3433// We might have no default constructor because we have a lambda's closure3434// type, rather than because there's some other declared constructor.3435// Every class has a copy/move constructor, copy/move assignment, and3436// destructor.3437assert(SM == CXXSpecialMemberKind::DefaultConstructor &&3438"lookup for a constructor or assignment operator was empty");3439Result->setMethod(nullptr);3440Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);3441return *Result;3442}34433444// Copy the candidates as our processing of them may load new declarations3445// from an external source and invalidate lookup_result.3446SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());34473448for (NamedDecl *CandDecl : Candidates) {3449if (CandDecl->isInvalidDecl())3450continue;34513452DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);3453auto CtorInfo = getConstructorInfo(Cand);3454if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {3455if (SM == CXXSpecialMemberKind::CopyAssignment ||3456SM == CXXSpecialMemberKind::MoveAssignment)3457AddMethodCandidate(M, Cand, RD, ThisTy, Classification,3458llvm::ArrayRef(&Arg, NumArgs), OCS, true);3459else if (CtorInfo)3460AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,3461llvm::ArrayRef(&Arg, NumArgs), OCS,3462/*SuppressUserConversions*/ true);3463else3464AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS,3465/*SuppressUserConversions*/ true);3466} else if (FunctionTemplateDecl *Tmpl =3467dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {3468if (SM == CXXSpecialMemberKind::CopyAssignment ||3469SM == CXXSpecialMemberKind::MoveAssignment)3470AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy,3471Classification,3472llvm::ArrayRef(&Arg, NumArgs), OCS, true);3473else if (CtorInfo)3474AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl,3475CtorInfo.FoundDecl, nullptr,3476llvm::ArrayRef(&Arg, NumArgs), OCS, true);3477else3478AddTemplateOverloadCandidate(Tmpl, Cand, nullptr,3479llvm::ArrayRef(&Arg, NumArgs), OCS, true);3480} else {3481assert(isa<UsingDecl>(Cand.getDecl()) &&3482"illegal Kind of operator = Decl");3483}3484}34853486OverloadCandidateSet::iterator Best;3487switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {3488case OR_Success:3489Result->setMethod(cast<CXXMethodDecl>(Best->Function));3490Result->setKind(SpecialMemberOverloadResult::Success);3491break;34923493case OR_Deleted:3494Result->setMethod(cast<CXXMethodDecl>(Best->Function));3495Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);3496break;34973498case OR_Ambiguous:3499Result->setMethod(nullptr);3500Result->setKind(SpecialMemberOverloadResult::Ambiguous);3501break;35023503case OR_No_Viable_Function:3504Result->setMethod(nullptr);3505Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);3506break;3507}35083509return *Result;3510}35113512CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {3513SpecialMemberOverloadResult Result =3514LookupSpecialMember(Class, CXXSpecialMemberKind::DefaultConstructor,3515false, false, false, false, false);35163517return cast_or_null<CXXConstructorDecl>(Result.getMethod());3518}35193520CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,3521unsigned Quals) {3522assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&3523"non-const, non-volatile qualifiers for copy ctor arg");3524SpecialMemberOverloadResult Result = LookupSpecialMember(3525Class, CXXSpecialMemberKind::CopyConstructor, Quals & Qualifiers::Const,3526Quals & Qualifiers::Volatile, false, false, false);35273528return cast_or_null<CXXConstructorDecl>(Result.getMethod());3529}35303531CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,3532unsigned Quals) {3533SpecialMemberOverloadResult Result = LookupSpecialMember(3534Class, CXXSpecialMemberKind::MoveConstructor, Quals & Qualifiers::Const,3535Quals & Qualifiers::Volatile, false, false, false);35363537return cast_or_null<CXXConstructorDecl>(Result.getMethod());3538}35393540DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {3541// If the implicit constructors have not yet been declared, do so now.3542if (CanDeclareSpecialMemberFunction(Class)) {3543runWithSufficientStackSpace(Class->getLocation(), [&] {3544if (Class->needsImplicitDefaultConstructor())3545DeclareImplicitDefaultConstructor(Class);3546if (Class->needsImplicitCopyConstructor())3547DeclareImplicitCopyConstructor(Class);3548if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())3549DeclareImplicitMoveConstructor(Class);3550});3551}35523553CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));3554DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);3555return Class->lookup(Name);3556}35573558CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,3559unsigned Quals, bool RValueThis,3560unsigned ThisQuals) {3561assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&3562"non-const, non-volatile qualifiers for copy assignment arg");3563assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&3564"non-const, non-volatile qualifiers for copy assignment this");3565SpecialMemberOverloadResult Result = LookupSpecialMember(3566Class, CXXSpecialMemberKind::CopyAssignment, Quals & Qualifiers::Const,3567Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,3568ThisQuals & Qualifiers::Volatile);35693570return Result.getMethod();3571}35723573CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,3574unsigned Quals,3575bool RValueThis,3576unsigned ThisQuals) {3577assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&3578"non-const, non-volatile qualifiers for copy assignment this");3579SpecialMemberOverloadResult Result = LookupSpecialMember(3580Class, CXXSpecialMemberKind::MoveAssignment, Quals & Qualifiers::Const,3581Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,3582ThisQuals & Qualifiers::Volatile);35833584return Result.getMethod();3585}35863587CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {3588return cast_or_null<CXXDestructorDecl>(3589LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false, false,3590false, false, false)3591.getMethod());3592}35933594Sema::LiteralOperatorLookupResult3595Sema::LookupLiteralOperator(Scope *S, LookupResult &R,3596ArrayRef<QualType> ArgTys, bool AllowRaw,3597bool AllowTemplate, bool AllowStringTemplatePack,3598bool DiagnoseMissing, StringLiteral *StringLit) {3599LookupName(R, S);3600assert(R.getResultKind() != LookupResult::Ambiguous &&3601"literal operator lookup can't be ambiguous");36023603// Filter the lookup results appropriately.3604LookupResult::Filter F = R.makeFilter();36053606bool AllowCooked = true;3607bool FoundRaw = false;3608bool FoundTemplate = false;3609bool FoundStringTemplatePack = false;3610bool FoundCooked = false;36113612while (F.hasNext()) {3613Decl *D = F.next();3614if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))3615D = USD->getTargetDecl();36163617// If the declaration we found is invalid, skip it.3618if (D->isInvalidDecl()) {3619F.erase();3620continue;3621}36223623bool IsRaw = false;3624bool IsTemplate = false;3625bool IsStringTemplatePack = false;3626bool IsCooked = false;36273628if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {3629if (FD->getNumParams() == 1 &&3630FD->getParamDecl(0)->getType()->getAs<PointerType>())3631IsRaw = true;3632else if (FD->getNumParams() == ArgTys.size()) {3633IsCooked = true;3634for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {3635QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();3636if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {3637IsCooked = false;3638break;3639}3640}3641}3642}3643if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {3644TemplateParameterList *Params = FD->getTemplateParameters();3645if (Params->size() == 1) {3646IsTemplate = true;3647if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {3648// Implied but not stated: user-defined integer and floating literals3649// only ever use numeric literal operator templates, not templates3650// taking a parameter of class type.3651F.erase();3652continue;3653}36543655// A string literal template is only considered if the string literal3656// is a well-formed template argument for the template parameter.3657if (StringLit) {3658SFINAETrap Trap(*this);3659SmallVector<TemplateArgument, 1> SugaredChecked, CanonicalChecked;3660TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);3661if (CheckTemplateArgument(3662Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(),36630, SugaredChecked, CanonicalChecked, CTAK_Specified) ||3664Trap.hasErrorOccurred())3665IsTemplate = false;3666}3667} else {3668IsStringTemplatePack = true;3669}3670}36713672if (AllowTemplate && StringLit && IsTemplate) {3673FoundTemplate = true;3674AllowRaw = false;3675AllowCooked = false;3676AllowStringTemplatePack = false;3677if (FoundRaw || FoundCooked || FoundStringTemplatePack) {3678F.restart();3679FoundRaw = FoundCooked = FoundStringTemplatePack = false;3680}3681} else if (AllowCooked && IsCooked) {3682FoundCooked = true;3683AllowRaw = false;3684AllowTemplate = StringLit;3685AllowStringTemplatePack = false;3686if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {3687// Go through again and remove the raw and template decls we've3688// already found.3689F.restart();3690FoundRaw = FoundTemplate = FoundStringTemplatePack = false;3691}3692} else if (AllowRaw && IsRaw) {3693FoundRaw = true;3694} else if (AllowTemplate && IsTemplate) {3695FoundTemplate = true;3696} else if (AllowStringTemplatePack && IsStringTemplatePack) {3697FoundStringTemplatePack = true;3698} else {3699F.erase();3700}3701}37023703F.done();37043705// Per C++20 [lex.ext]p5, we prefer the template form over the non-template3706// form for string literal operator templates.3707if (StringLit && FoundTemplate)3708return LOLR_Template;37093710// C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching3711// parameter type, that is used in preference to a raw literal operator3712// or literal operator template.3713if (FoundCooked)3714return LOLR_Cooked;37153716// C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal3717// operator template, but not both.3718if (FoundRaw && FoundTemplate) {3719Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();3720for (const NamedDecl *D : R)3721NoteOverloadCandidate(D, D->getUnderlyingDecl()->getAsFunction());3722return LOLR_Error;3723}37243725if (FoundRaw)3726return LOLR_Raw;37273728if (FoundTemplate)3729return LOLR_Template;37303731if (FoundStringTemplatePack)3732return LOLR_StringTemplatePack;37333734// Didn't find anything we could use.3735if (DiagnoseMissing) {3736Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)3737<< R.getLookupName() << (int)ArgTys.size() << ArgTys[0]3738<< (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw3739<< (AllowTemplate || AllowStringTemplatePack);3740return LOLR_Error;3741}37423743return LOLR_ErrorNoDiagnostic;3744}37453746void ADLResult::insert(NamedDecl *New) {3747NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];37483749// If we haven't yet seen a decl for this key, or the last decl3750// was exactly this one, we're done.3751if (Old == nullptr || Old == New) {3752Old = New;3753return;3754}37553756// Otherwise, decide which is a more recent redeclaration.3757FunctionDecl *OldFD = Old->getAsFunction();3758FunctionDecl *NewFD = New->getAsFunction();37593760FunctionDecl *Cursor = NewFD;3761while (true) {3762Cursor = Cursor->getPreviousDecl();37633764// If we got to the end without finding OldFD, OldFD is the newer3765// declaration; leave things as they are.3766if (!Cursor) return;37673768// If we do find OldFD, then NewFD is newer.3769if (Cursor == OldFD) break;37703771// Otherwise, keep looking.3772}37733774Old = New;3775}37763777void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,3778ArrayRef<Expr *> Args, ADLResult &Result) {3779// Find all of the associated namespaces and classes based on the3780// arguments we have.3781AssociatedNamespaceSet AssociatedNamespaces;3782AssociatedClassSet AssociatedClasses;3783FindAssociatedClassesAndNamespaces(Loc, Args,3784AssociatedNamespaces,3785AssociatedClasses);37863787// C++ [basic.lookup.argdep]p3:3788// Let X be the lookup set produced by unqualified lookup (3.4.1)3789// and let Y be the lookup set produced by argument dependent3790// lookup (defined as follows). If X contains [...] then Y is3791// empty. Otherwise Y is the set of declarations found in the3792// namespaces associated with the argument types as described3793// below. The set of declarations found by the lookup of the name3794// is the union of X and Y.3795//3796// Here, we compute Y and add its members to the overloaded3797// candidate set.3798for (auto *NS : AssociatedNamespaces) {3799// When considering an associated namespace, the lookup is the3800// same as the lookup performed when the associated namespace is3801// used as a qualifier (3.4.3.2) except that:3802//3803// -- Any using-directives in the associated namespace are3804// ignored.3805//3806// -- Any namespace-scope friend functions declared in3807// associated classes are visible within their respective3808// namespaces even if they are not visible during an ordinary3809// lookup (11.4).3810//3811// C++20 [basic.lookup.argdep] p4.33812// -- are exported, are attached to a named module M, do not appear3813// in the translation unit containing the point of the lookup, and3814// have the same innermost enclosing non-inline namespace scope as3815// a declaration of an associated entity attached to M.3816DeclContext::lookup_result R = NS->lookup(Name);3817for (auto *D : R) {3818auto *Underlying = D;3819if (auto *USD = dyn_cast<UsingShadowDecl>(D))3820Underlying = USD->getTargetDecl();38213822if (!isa<FunctionDecl>(Underlying) &&3823!isa<FunctionTemplateDecl>(Underlying))3824continue;38253826// The declaration is visible to argument-dependent lookup if either3827// it's ordinarily visible or declared as a friend in an associated3828// class.3829bool Visible = false;3830for (D = D->getMostRecentDecl(); D;3831D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {3832if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {3833if (isVisible(D)) {3834Visible = true;3835break;3836}38373838if (!getLangOpts().CPlusPlusModules)3839continue;38403841if (D->isInExportDeclContext()) {3842Module *FM = D->getOwningModule();3843// C++20 [basic.lookup.argdep] p4.3 .. are exported ...3844// exports are only valid in module purview and outside of any3845// PMF (although a PMF should not even be present in a module3846// with an import).3847assert(FM && FM->isNamedModule() && !FM->isPrivateModule() &&3848"bad export context");3849// .. are attached to a named module M, do not appear in the3850// translation unit containing the point of the lookup..3851if (D->isInAnotherModuleUnit() &&3852llvm::any_of(AssociatedClasses, [&](auto *E) {3853// ... and have the same innermost enclosing non-inline3854// namespace scope as a declaration of an associated entity3855// attached to M3856if (E->getOwningModule() != FM)3857return false;3858// TODO: maybe this could be cached when generating the3859// associated namespaces / entities.3860DeclContext *Ctx = E->getDeclContext();3861while (!Ctx->isFileContext() || Ctx->isInlineNamespace())3862Ctx = Ctx->getParent();3863return Ctx == NS;3864})) {3865Visible = true;3866break;3867}3868}3869} else if (D->getFriendObjectKind()) {3870auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());3871// [basic.lookup.argdep]p4:3872// Argument-dependent lookup finds all declarations of functions and3873// function templates that3874// - ...3875// - are declared as a friend ([class.friend]) of any class with a3876// reachable definition in the set of associated entities,3877//3878// FIXME: If there's a merged definition of D that is reachable, then3879// the friend declaration should be considered.3880if (AssociatedClasses.count(RD) && isReachable(D)) {3881Visible = true;3882break;3883}3884}3885}38863887// FIXME: Preserve D as the FoundDecl.3888if (Visible)3889Result.insert(Underlying);3890}3891}3892}38933894//----------------------------------------------------------------------------3895// Search for all visible declarations.3896//----------------------------------------------------------------------------3897VisibleDeclConsumer::~VisibleDeclConsumer() { }38983899bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }39003901namespace {39023903class ShadowContextRAII;39043905class VisibleDeclsRecord {3906public:3907/// An entry in the shadow map, which is optimized to store a3908/// single declaration (the common case) but can also store a list3909/// of declarations.3910typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;39113912private:3913/// A mapping from declaration names to the declarations that have3914/// this name within a particular scope.3915typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;39163917/// A list of shadow maps, which is used to model name hiding.3918std::list<ShadowMap> ShadowMaps;39193920/// The declaration contexts we have already visited.3921llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;39223923friend class ShadowContextRAII;39243925public:3926/// Determine whether we have already visited this context3927/// (and, if not, note that we are going to visit that context now).3928bool visitedContext(DeclContext *Ctx) {3929return !VisitedContexts.insert(Ctx).second;3930}39313932bool alreadyVisitedContext(DeclContext *Ctx) {3933return VisitedContexts.count(Ctx);3934}39353936/// Determine whether the given declaration is hidden in the3937/// current scope.3938///3939/// \returns the declaration that hides the given declaration, or3940/// NULL if no such declaration exists.3941NamedDecl *checkHidden(NamedDecl *ND);39423943/// Add a declaration to the current shadow map.3944void add(NamedDecl *ND) {3945ShadowMaps.back()[ND->getDeclName()].push_back(ND);3946}3947};39483949/// RAII object that records when we've entered a shadow context.3950class ShadowContextRAII {3951VisibleDeclsRecord &Visible;39523953typedef VisibleDeclsRecord::ShadowMap ShadowMap;39543955public:3956ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {3957Visible.ShadowMaps.emplace_back();3958}39593960~ShadowContextRAII() {3961Visible.ShadowMaps.pop_back();3962}3963};39643965} // end anonymous namespace39663967NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {3968unsigned IDNS = ND->getIdentifierNamespace();3969std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();3970for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();3971SM != SMEnd; ++SM) {3972ShadowMap::iterator Pos = SM->find(ND->getDeclName());3973if (Pos == SM->end())3974continue;39753976for (auto *D : Pos->second) {3977// A tag declaration does not hide a non-tag declaration.3978if (D->hasTagIdentifierNamespace() &&3979(IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |3980Decl::IDNS_ObjCProtocol)))3981continue;39823983// Protocols are in distinct namespaces from everything else.3984if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)3985|| (IDNS & Decl::IDNS_ObjCProtocol)) &&3986D->getIdentifierNamespace() != IDNS)3987continue;39883989// Functions and function templates in the same scope overload3990// rather than hide. FIXME: Look for hiding based on function3991// signatures!3992if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&3993ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&3994SM == ShadowMaps.rbegin())3995continue;39963997// A shadow declaration that's created by a resolved using declaration3998// is not hidden by the same using declaration.3999if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&4000cast<UsingShadowDecl>(ND)->getIntroducer() == D)4001continue;40024003// We've found a declaration that hides this one.4004return D;4005}4006}40074008return nullptr;4009}40104011namespace {4012class LookupVisibleHelper {4013public:4014LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,4015bool LoadExternal)4016: Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),4017LoadExternal(LoadExternal) {}40184019void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,4020bool IncludeGlobalScope) {4021// Determine the set of using directives available during4022// unqualified name lookup.4023Scope *Initial = S;4024UnqualUsingDirectiveSet UDirs(SemaRef);4025if (SemaRef.getLangOpts().CPlusPlus) {4026// Find the first namespace or translation-unit scope.4027while (S && !isNamespaceOrTranslationUnitScope(S))4028S = S->getParent();40294030UDirs.visitScopeChain(Initial, S);4031}4032UDirs.done();40334034// Look for visible declarations.4035LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);4036Result.setAllowHidden(Consumer.includeHiddenDecls());4037if (!IncludeGlobalScope)4038Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());4039ShadowContextRAII Shadow(Visited);4040lookupInScope(Initial, Result, UDirs);4041}40424043void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,4044Sema::LookupNameKind Kind, bool IncludeGlobalScope) {4045LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);4046Result.setAllowHidden(Consumer.includeHiddenDecls());4047if (!IncludeGlobalScope)4048Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());40494050ShadowContextRAII Shadow(Visited);4051lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,4052/*InBaseClass=*/false);4053}40544055private:4056void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,4057bool QualifiedNameLookup, bool InBaseClass) {4058if (!Ctx)4059return;40604061// Make sure we don't visit the same context twice.4062if (Visited.visitedContext(Ctx->getPrimaryContext()))4063return;40644065Consumer.EnteredContext(Ctx);40664067// Outside C++, lookup results for the TU live on identifiers.4068if (isa<TranslationUnitDecl>(Ctx) &&4069!Result.getSema().getLangOpts().CPlusPlus) {4070auto &S = Result.getSema();4071auto &Idents = S.Context.Idents;40724073// Ensure all external identifiers are in the identifier table.4074if (LoadExternal)4075if (IdentifierInfoLookup *External =4076Idents.getExternalIdentifierLookup()) {4077std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());4078for (StringRef Name = Iter->Next(); !Name.empty();4079Name = Iter->Next())4080Idents.get(Name);4081}40824083// Walk all lookup results in the TU for each identifier.4084for (const auto &Ident : Idents) {4085for (auto I = S.IdResolver.begin(Ident.getValue()),4086E = S.IdResolver.end();4087I != E; ++I) {4088if (S.IdResolver.isDeclInScope(*I, Ctx)) {4089if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {4090Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);4091Visited.add(ND);4092}4093}4094}4095}40964097return;4098}40994100if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))4101Result.getSema().ForceDeclarationOfImplicitMembers(Class);41024103llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;4104// We sometimes skip loading namespace-level results (they tend to be huge).4105bool Load = LoadExternal ||4106!(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));4107// Enumerate all of the results in this context.4108for (DeclContextLookupResult R :4109Load ? Ctx->lookups()4110: Ctx->noload_lookups(/*PreserveInternalState=*/false))4111for (auto *D : R)4112// Rather than visit immediately, we put ND into a vector and visit4113// all decls, in order, outside of this loop. The reason is that4114// Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)4115// may invalidate the iterators used in the two4116// loops above.4117DeclsToVisit.push_back(D);41184119for (auto *D : DeclsToVisit)4120if (auto *ND = Result.getAcceptableDecl(D)) {4121Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);4122Visited.add(ND);4123}41244125DeclsToVisit.clear();41264127// Traverse using directives for qualified name lookup.4128if (QualifiedNameLookup) {4129ShadowContextRAII Shadow(Visited);4130for (auto *I : Ctx->using_directives()) {4131if (!Result.getSema().isVisible(I))4132continue;4133lookupInDeclContext(I->getNominatedNamespace(), Result,4134QualifiedNameLookup, InBaseClass);4135}4136}41374138// Traverse the contexts of inherited C++ classes.4139if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {4140if (!Record->hasDefinition())4141return;41424143for (const auto &B : Record->bases()) {4144QualType BaseType = B.getType();41454146RecordDecl *RD;4147if (BaseType->isDependentType()) {4148if (!IncludeDependentBases) {4149// Don't look into dependent bases, because name lookup can't look4150// there anyway.4151continue;4152}4153const auto *TST = BaseType->getAs<TemplateSpecializationType>();4154if (!TST)4155continue;4156TemplateName TN = TST->getTemplateName();4157const auto *TD =4158dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());4159if (!TD)4160continue;4161RD = TD->getTemplatedDecl();4162} else {4163const auto *Record = BaseType->getAs<RecordType>();4164if (!Record)4165continue;4166RD = Record->getDecl();4167}41684169// FIXME: It would be nice to be able to determine whether referencing4170// a particular member would be ambiguous. For example, given4171//4172// struct A { int member; };4173// struct B { int member; };4174// struct C : A, B { };4175//4176// void f(C *c) { c->### }4177//4178// accessing 'member' would result in an ambiguity. However, we4179// could be smart enough to qualify the member with the base4180// class, e.g.,4181//4182// c->B::member4183//4184// or4185//4186// c->A::member41874188// Find results in this base class (and its bases).4189ShadowContextRAII Shadow(Visited);4190lookupInDeclContext(RD, Result, QualifiedNameLookup,4191/*InBaseClass=*/true);4192}4193}41944195// Traverse the contexts of Objective-C classes.4196if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {4197// Traverse categories.4198for (auto *Cat : IFace->visible_categories()) {4199ShadowContextRAII Shadow(Visited);4200lookupInDeclContext(Cat, Result, QualifiedNameLookup,4201/*InBaseClass=*/false);4202}42034204// Traverse protocols.4205for (auto *I : IFace->all_referenced_protocols()) {4206ShadowContextRAII Shadow(Visited);4207lookupInDeclContext(I, Result, QualifiedNameLookup,4208/*InBaseClass=*/false);4209}42104211// Traverse the superclass.4212if (IFace->getSuperClass()) {4213ShadowContextRAII Shadow(Visited);4214lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,4215/*InBaseClass=*/true);4216}42174218// If there is an implementation, traverse it. We do this to find4219// synthesized ivars.4220if (IFace->getImplementation()) {4221ShadowContextRAII Shadow(Visited);4222lookupInDeclContext(IFace->getImplementation(), Result,4223QualifiedNameLookup, InBaseClass);4224}4225} else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {4226for (auto *I : Protocol->protocols()) {4227ShadowContextRAII Shadow(Visited);4228lookupInDeclContext(I, Result, QualifiedNameLookup,4229/*InBaseClass=*/false);4230}4231} else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {4232for (auto *I : Category->protocols()) {4233ShadowContextRAII Shadow(Visited);4234lookupInDeclContext(I, Result, QualifiedNameLookup,4235/*InBaseClass=*/false);4236}42374238// If there is an implementation, traverse it.4239if (Category->getImplementation()) {4240ShadowContextRAII Shadow(Visited);4241lookupInDeclContext(Category->getImplementation(), Result,4242QualifiedNameLookup, /*InBaseClass=*/true);4243}4244}4245}42464247void lookupInScope(Scope *S, LookupResult &Result,4248UnqualUsingDirectiveSet &UDirs) {4249// No clients run in this mode and it's not supported. Please add tests and4250// remove the assertion if you start relying on it.4251assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");42524253if (!S)4254return;42554256if (!S->getEntity() ||4257(!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||4258(S->getEntity())->isFunctionOrMethod()) {4259FindLocalExternScope FindLocals(Result);4260// Walk through the declarations in this Scope. The consumer might add new4261// decls to the scope as part of deserialization, so make a copy first.4262SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());4263for (Decl *D : ScopeDecls) {4264if (NamedDecl *ND = dyn_cast<NamedDecl>(D))4265if ((ND = Result.getAcceptableDecl(ND))) {4266Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);4267Visited.add(ND);4268}4269}4270}42714272DeclContext *Entity = S->getLookupEntity();4273if (Entity) {4274// Look into this scope's declaration context, along with any of its4275// parent lookup contexts (e.g., enclosing classes), up to the point4276// where we hit the context stored in the next outer scope.4277DeclContext *OuterCtx = findOuterContext(S);42784279for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);4280Ctx = Ctx->getLookupParent()) {4281if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {4282if (Method->isInstanceMethod()) {4283// For instance methods, look for ivars in the method's interface.4284LookupResult IvarResult(Result.getSema(), Result.getLookupName(),4285Result.getNameLoc(),4286Sema::LookupMemberName);4287if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {4288lookupInDeclContext(IFace, IvarResult,4289/*QualifiedNameLookup=*/false,4290/*InBaseClass=*/false);4291}4292}42934294// We've already performed all of the name lookup that we need4295// to for Objective-C methods; the next context will be the4296// outer scope.4297break;4298}42994300if (Ctx->isFunctionOrMethod())4301continue;43024303lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,4304/*InBaseClass=*/false);4305}4306} else if (!S->getParent()) {4307// Look into the translation unit scope. We walk through the translation4308// unit's declaration context, because the Scope itself won't have all of4309// the declarations if we loaded a precompiled header.4310// FIXME: We would like the translation unit's Scope object to point to4311// the translation unit, so we don't need this special "if" branch.4312// However, doing so would force the normal C++ name-lookup code to look4313// into the translation unit decl when the IdentifierInfo chains would4314// suffice. Once we fix that problem (which is part of a more general4315// "don't look in DeclContexts unless we have to" optimization), we can4316// eliminate this.4317Entity = Result.getSema().Context.getTranslationUnitDecl();4318lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,4319/*InBaseClass=*/false);4320}43214322if (Entity) {4323// Lookup visible declarations in any namespaces found by using4324// directives.4325for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))4326lookupInDeclContext(4327const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,4328/*QualifiedNameLookup=*/false,4329/*InBaseClass=*/false);4330}43314332// Lookup names in the parent scope.4333ShadowContextRAII Shadow(Visited);4334lookupInScope(S->getParent(), Result, UDirs);4335}43364337private:4338VisibleDeclsRecord Visited;4339VisibleDeclConsumer &Consumer;4340bool IncludeDependentBases;4341bool LoadExternal;4342};4343} // namespace43444345void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,4346VisibleDeclConsumer &Consumer,4347bool IncludeGlobalScope, bool LoadExternal) {4348LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,4349LoadExternal);4350H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);4351}43524353void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,4354VisibleDeclConsumer &Consumer,4355bool IncludeGlobalScope,4356bool IncludeDependentBases, bool LoadExternal) {4357LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);4358H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);4359}43604361LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,4362SourceLocation GnuLabelLoc) {4363// Do a lookup to see if we have a label with this name already.4364NamedDecl *Res = nullptr;43654366if (GnuLabelLoc.isValid()) {4367// Local label definitions always shadow existing labels.4368Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);4369Scope *S = CurScope;4370PushOnScopeChains(Res, S, true);4371return cast<LabelDecl>(Res);4372}43734374// Not a GNU local label.4375Res = LookupSingleName(CurScope, II, Loc, LookupLabel,4376RedeclarationKind::NotForRedeclaration);4377// If we found a label, check to see if it is in the same context as us.4378// When in a Block, we don't want to reuse a label in an enclosing function.4379if (Res && Res->getDeclContext() != CurContext)4380Res = nullptr;4381if (!Res) {4382// If not forward referenced or defined already, create the backing decl.4383Res = LabelDecl::Create(Context, CurContext, Loc, II);4384Scope *S = CurScope->getFnParent();4385assert(S && "Not in a function?");4386PushOnScopeChains(Res, S, true);4387}4388return cast<LabelDecl>(Res);4389}43904391//===----------------------------------------------------------------------===//4392// Typo correction4393//===----------------------------------------------------------------------===//43944395static bool isCandidateViable(CorrectionCandidateCallback &CCC,4396TypoCorrection &Candidate) {4397Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));4398return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;4399}44004401static void LookupPotentialTypoResult(Sema &SemaRef,4402LookupResult &Res,4403IdentifierInfo *Name,4404Scope *S, CXXScopeSpec *SS,4405DeclContext *MemberContext,4406bool EnteringContext,4407bool isObjCIvarLookup,4408bool FindHidden);44094410/// Check whether the declarations found for a typo correction are4411/// visible. Set the correction's RequiresImport flag to true if none of the4412/// declarations are visible, false otherwise.4413static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {4414TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();44154416for (/**/; DI != DE; ++DI)4417if (!LookupResult::isVisible(SemaRef, *DI))4418break;4419// No filtering needed if all decls are visible.4420if (DI == DE) {4421TC.setRequiresImport(false);4422return;4423}44244425llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);4426bool AnyVisibleDecls = !NewDecls.empty();44274428for (/**/; DI != DE; ++DI) {4429if (LookupResult::isVisible(SemaRef, *DI)) {4430if (!AnyVisibleDecls) {4431// Found a visible decl, discard all hidden ones.4432AnyVisibleDecls = true;4433NewDecls.clear();4434}4435NewDecls.push_back(*DI);4436} else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())4437NewDecls.push_back(*DI);4438}44394440if (NewDecls.empty())4441TC = TypoCorrection();4442else {4443TC.setCorrectionDecls(NewDecls);4444TC.setRequiresImport(!AnyVisibleDecls);4445}4446}44474448// Fill the supplied vector with the IdentifierInfo pointers for each piece of4449// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",4450// fill the vector with the IdentifierInfo pointers for "foo" and "bar").4451static void getNestedNameSpecifierIdentifiers(4452NestedNameSpecifier *NNS,4453SmallVectorImpl<const IdentifierInfo*> &Identifiers) {4454if (NestedNameSpecifier *Prefix = NNS->getPrefix())4455getNestedNameSpecifierIdentifiers(Prefix, Identifiers);4456else4457Identifiers.clear();44584459const IdentifierInfo *II = nullptr;44604461switch (NNS->getKind()) {4462case NestedNameSpecifier::Identifier:4463II = NNS->getAsIdentifier();4464break;44654466case NestedNameSpecifier::Namespace:4467if (NNS->getAsNamespace()->isAnonymousNamespace())4468return;4469II = NNS->getAsNamespace()->getIdentifier();4470break;44714472case NestedNameSpecifier::NamespaceAlias:4473II = NNS->getAsNamespaceAlias()->getIdentifier();4474break;44754476case NestedNameSpecifier::TypeSpecWithTemplate:4477case NestedNameSpecifier::TypeSpec:4478II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();4479break;44804481case NestedNameSpecifier::Global:4482case NestedNameSpecifier::Super:4483return;4484}44854486if (II)4487Identifiers.push_back(II);4488}44894490void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,4491DeclContext *Ctx, bool InBaseClass) {4492// Don't consider hidden names for typo correction.4493if (Hiding)4494return;44954496// Only consider entities with identifiers for names, ignoring4497// special names (constructors, overloaded operators, selectors,4498// etc.).4499IdentifierInfo *Name = ND->getIdentifier();4500if (!Name)4501return;45024503// Only consider visible declarations and declarations from modules with4504// names that exactly match.4505if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)4506return;45074508FoundName(Name->getName());4509}45104511void TypoCorrectionConsumer::FoundName(StringRef Name) {4512// Compute the edit distance between the typo and the name of this4513// entity, and add the identifier to the list of results.4514addName(Name, nullptr);4515}45164517void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {4518// Compute the edit distance between the typo and this keyword,4519// and add the keyword to the list of results.4520addName(Keyword, nullptr, nullptr, true);4521}45224523void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,4524NestedNameSpecifier *NNS, bool isKeyword) {4525// Use a simple length-based heuristic to determine the minimum possible4526// edit distance. If the minimum isn't good enough, bail out early.4527StringRef TypoStr = Typo->getName();4528unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());4529if (MinED && TypoStr.size() / MinED < 3)4530return;45314532// Compute an upper bound on the allowable edit distance, so that the4533// edit-distance algorithm can short-circuit.4534unsigned UpperBound = (TypoStr.size() + 2) / 3;4535unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);4536if (ED > UpperBound) return;45374538TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);4539if (isKeyword) TC.makeKeyword();4540TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());4541addCorrection(TC);4542}45434544static const unsigned MaxTypoDistanceResultSets = 5;45454546void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {4547StringRef TypoStr = Typo->getName();4548StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();45494550// For very short typos, ignore potential corrections that have a different4551// base identifier from the typo or which have a normalized edit distance4552// longer than the typo itself.4553if (TypoStr.size() < 3 &&4554(Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))4555return;45564557// If the correction is resolved but is not viable, ignore it.4558if (Correction.isResolved()) {4559checkCorrectionVisibility(SemaRef, Correction);4560if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))4561return;4562}45634564TypoResultList &CList =4565CorrectionResults[Correction.getEditDistance(false)][Name];45664567if (!CList.empty() && !CList.back().isResolved())4568CList.pop_back();4569if (NamedDecl *NewND = Correction.getCorrectionDecl()) {4570auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {4571return TypoCorr.getCorrectionDecl() == NewND;4572});4573if (RI != CList.end()) {4574// The Correction refers to a decl already in the list. No insertion is4575// necessary and all further cases will return.45764577auto IsDeprecated = [](Decl *D) {4578while (D) {4579if (D->isDeprecated())4580return true;4581D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());4582}4583return false;4584};45854586// Prefer non deprecated Corrections over deprecated and only then4587// sort using an alphabetical order.4588std::pair<bool, std::string> NewKey = {4589IsDeprecated(Correction.getFoundDecl()),4590Correction.getAsString(SemaRef.getLangOpts())};45914592std::pair<bool, std::string> PrevKey = {4593IsDeprecated(RI->getFoundDecl()),4594RI->getAsString(SemaRef.getLangOpts())};45954596if (NewKey < PrevKey)4597*RI = Correction;4598return;4599}4600}4601if (CList.empty() || Correction.isResolved())4602CList.push_back(Correction);46034604while (CorrectionResults.size() > MaxTypoDistanceResultSets)4605CorrectionResults.erase(std::prev(CorrectionResults.end()));4606}46074608void TypoCorrectionConsumer::addNamespaces(4609const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {4610SearchNamespaces = true;46114612for (auto KNPair : KnownNamespaces)4613Namespaces.addNameSpecifier(KNPair.first);46144615bool SSIsTemplate = false;4616if (NestedNameSpecifier *NNS =4617(SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {4618if (const Type *T = NNS->getAsType())4619SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;4620}4621// Do not transform this into an iterator-based loop. The loop body can4622// trigger the creation of further types (through lazy deserialization) and4623// invalid iterators into this list.4624auto &Types = SemaRef.getASTContext().getTypes();4625for (unsigned I = 0; I != Types.size(); ++I) {4626const auto *TI = Types[I];4627if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {4628CD = CD->getCanonicalDecl();4629if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&4630!CD->isUnion() && CD->getIdentifier() &&4631(SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&4632(CD->isBeingDefined() || CD->isCompleteDefinition()))4633Namespaces.addNameSpecifier(CD);4634}4635}4636}46374638const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {4639if (++CurrentTCIndex < ValidatedCorrections.size())4640return ValidatedCorrections[CurrentTCIndex];46414642CurrentTCIndex = ValidatedCorrections.size();4643while (!CorrectionResults.empty()) {4644auto DI = CorrectionResults.begin();4645if (DI->second.empty()) {4646CorrectionResults.erase(DI);4647continue;4648}46494650auto RI = DI->second.begin();4651if (RI->second.empty()) {4652DI->second.erase(RI);4653performQualifiedLookups();4654continue;4655}46564657TypoCorrection TC = RI->second.pop_back_val();4658if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {4659ValidatedCorrections.push_back(TC);4660return ValidatedCorrections[CurrentTCIndex];4661}4662}4663return ValidatedCorrections[0]; // The empty correction.4664}46654666bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {4667IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();4668DeclContext *TempMemberContext = MemberContext;4669CXXScopeSpec *TempSS = SS.get();4670retry_lookup:4671LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,4672EnteringContext,4673CorrectionValidator->IsObjCIvarLookup,4674Name == Typo && !Candidate.WillReplaceSpecifier());4675switch (Result.getResultKind()) {4676case LookupResult::NotFound:4677case LookupResult::NotFoundInCurrentInstantiation:4678case LookupResult::FoundUnresolvedValue:4679if (TempSS) {4680// Immediately retry the lookup without the given CXXScopeSpec4681TempSS = nullptr;4682Candidate.WillReplaceSpecifier(true);4683goto retry_lookup;4684}4685if (TempMemberContext) {4686if (SS && !TempSS)4687TempSS = SS.get();4688TempMemberContext = nullptr;4689goto retry_lookup;4690}4691if (SearchNamespaces)4692QualifiedResults.push_back(Candidate);4693break;46944695case LookupResult::Ambiguous:4696// We don't deal with ambiguities.4697break;46984699case LookupResult::Found:4700case LookupResult::FoundOverloaded:4701// Store all of the Decls for overloaded symbols4702for (auto *TRD : Result)4703Candidate.addCorrectionDecl(TRD);4704checkCorrectionVisibility(SemaRef, Candidate);4705if (!isCandidateViable(*CorrectionValidator, Candidate)) {4706if (SearchNamespaces)4707QualifiedResults.push_back(Candidate);4708break;4709}4710Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());4711return true;4712}4713return false;4714}47154716void TypoCorrectionConsumer::performQualifiedLookups() {4717unsigned TypoLen = Typo->getName().size();4718for (const TypoCorrection &QR : QualifiedResults) {4719for (const auto &NSI : Namespaces) {4720DeclContext *Ctx = NSI.DeclCtx;4721const Type *NSType = NSI.NameSpecifier->getAsType();47224723// If the current NestedNameSpecifier refers to a class and the4724// current correction candidate is the name of that class, then skip4725// it as it is unlikely a qualified version of the class' constructor4726// is an appropriate correction.4727if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :4728nullptr) {4729if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())4730continue;4731}47324733TypoCorrection TC(QR);4734TC.ClearCorrectionDecls();4735TC.setCorrectionSpecifier(NSI.NameSpecifier);4736TC.setQualifierDistance(NSI.EditDistance);4737TC.setCallbackDistance(0); // Reset the callback distance47384739// If the current correction candidate and namespace combination are4740// too far away from the original typo based on the normalized edit4741// distance, then skip performing a qualified name lookup.4742unsigned TmpED = TC.getEditDistance(true);4743if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&4744TypoLen / TmpED < 3)4745continue;47464747Result.clear();4748Result.setLookupName(QR.getCorrectionAsIdentifierInfo());4749if (!SemaRef.LookupQualifiedName(Result, Ctx))4750continue;47514752// Any corrections added below will be validated in subsequent4753// iterations of the main while() loop over the Consumer's contents.4754switch (Result.getResultKind()) {4755case LookupResult::Found:4756case LookupResult::FoundOverloaded: {4757if (SS && SS->isValid()) {4758std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());4759std::string OldQualified;4760llvm::raw_string_ostream OldOStream(OldQualified);4761SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());4762OldOStream << Typo->getName();4763// If correction candidate would be an identical written qualified4764// identifier, then the existing CXXScopeSpec probably included a4765// typedef that didn't get accounted for properly.4766if (OldOStream.str() == NewQualified)4767break;4768}4769for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();4770TRD != TRDEnd; ++TRD) {4771if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),4772NSType ? NSType->getAsCXXRecordDecl()4773: nullptr,4774TRD.getPair()) == Sema::AR_accessible)4775TC.addCorrectionDecl(*TRD);4776}4777if (TC.isResolved()) {4778TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());4779addCorrection(TC);4780}4781break;4782}4783case LookupResult::NotFound:4784case LookupResult::NotFoundInCurrentInstantiation:4785case LookupResult::Ambiguous:4786case LookupResult::FoundUnresolvedValue:4787break;4788}4789}4790}4791QualifiedResults.clear();4792}47934794TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(4795ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)4796: Context(Context), CurContextChain(buildContextChain(CurContext)) {4797if (NestedNameSpecifier *NNS =4798CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {4799llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);4800NNS->print(SpecifierOStream, Context.getPrintingPolicy());48014802getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);4803}4804// Build the list of identifiers that would be used for an absolute4805// (from the global context) NestedNameSpecifier referring to the current4806// context.4807for (DeclContext *C : llvm::reverse(CurContextChain)) {4808if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))4809CurContextIdentifiers.push_back(ND->getIdentifier());4810}48114812// Add the global context as a NestedNameSpecifier4813SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),4814NestedNameSpecifier::GlobalSpecifier(Context), 1};4815DistanceMap[1].push_back(SI);4816}48174818auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(4819DeclContext *Start) -> DeclContextList {4820assert(Start && "Building a context chain from a null context");4821DeclContextList Chain;4822for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;4823DC = DC->getLookupParent()) {4824NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);4825if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&4826!(ND && ND->isAnonymousNamespace()))4827Chain.push_back(DC->getPrimaryContext());4828}4829return Chain;4830}48314832unsigned4833TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(4834DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {4835unsigned NumSpecifiers = 0;4836for (DeclContext *C : llvm::reverse(DeclChain)) {4837if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {4838NNS = NestedNameSpecifier::Create(Context, NNS, ND);4839++NumSpecifiers;4840} else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {4841NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),4842RD->getTypeForDecl());4843++NumSpecifiers;4844}4845}4846return NumSpecifiers;4847}48484849void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(4850DeclContext *Ctx) {4851NestedNameSpecifier *NNS = nullptr;4852unsigned NumSpecifiers = 0;4853DeclContextList NamespaceDeclChain(buildContextChain(Ctx));4854DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);48554856// Eliminate common elements from the two DeclContext chains.4857for (DeclContext *C : llvm::reverse(CurContextChain)) {4858if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)4859break;4860NamespaceDeclChain.pop_back();4861}48624863// Build the NestedNameSpecifier from what is left of the NamespaceDeclChain4864NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);48654866// Add an explicit leading '::' specifier if needed.4867if (NamespaceDeclChain.empty()) {4868// Rebuild the NestedNameSpecifier as a globally-qualified specifier.4869NNS = NestedNameSpecifier::GlobalSpecifier(Context);4870NumSpecifiers =4871buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);4872} else if (NamedDecl *ND =4873dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {4874IdentifierInfo *Name = ND->getIdentifier();4875bool SameNameSpecifier = false;4876if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {4877std::string NewNameSpecifier;4878llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);4879SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;4880getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);4881NNS->print(SpecifierOStream, Context.getPrintingPolicy());4882SpecifierOStream.flush();4883SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;4884}4885if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {4886// Rebuild the NestedNameSpecifier as a globally-qualified specifier.4887NNS = NestedNameSpecifier::GlobalSpecifier(Context);4888NumSpecifiers =4889buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);4890}4891}48924893// If the built NestedNameSpecifier would be replacing an existing4894// NestedNameSpecifier, use the number of component identifiers that4895// would need to be changed as the edit distance instead of the number4896// of components in the built NestedNameSpecifier.4897if (NNS && !CurNameSpecifierIdentifiers.empty()) {4898SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;4899getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);4900NumSpecifiers =4901llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),4902llvm::ArrayRef(NewNameSpecifierIdentifiers));4903}49044905SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};4906DistanceMap[NumSpecifiers].push_back(SI);4907}49084909/// Perform name lookup for a possible result for typo correction.4910static void LookupPotentialTypoResult(Sema &SemaRef,4911LookupResult &Res,4912IdentifierInfo *Name,4913Scope *S, CXXScopeSpec *SS,4914DeclContext *MemberContext,4915bool EnteringContext,4916bool isObjCIvarLookup,4917bool FindHidden) {4918Res.suppressDiagnostics();4919Res.clear();4920Res.setLookupName(Name);4921Res.setAllowHidden(FindHidden);4922if (MemberContext) {4923if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {4924if (isObjCIvarLookup) {4925if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {4926Res.addDecl(Ivar);4927Res.resolveKind();4928return;4929}4930}49314932if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(4933Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {4934Res.addDecl(Prop);4935Res.resolveKind();4936return;4937}4938}49394940SemaRef.LookupQualifiedName(Res, MemberContext);4941return;4942}49434944SemaRef.LookupParsedName(Res, S, SS,4945/*ObjectType=*/QualType(),4946/*AllowBuiltinCreation=*/false, EnteringContext);49474948// Fake ivar lookup; this should really be part of4949// LookupParsedName.4950if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {4951if (Method->isInstanceMethod() && Method->getClassInterface() &&4952(Res.empty() ||4953(Res.isSingleResult() &&4954Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {4955if (ObjCIvarDecl *IV4956= Method->getClassInterface()->lookupInstanceVariable(Name)) {4957Res.addDecl(IV);4958Res.resolveKind();4959}4960}4961}4962}49634964/// Add keywords to the consumer as possible typo corrections.4965static void AddKeywordsToConsumer(Sema &SemaRef,4966TypoCorrectionConsumer &Consumer,4967Scope *S, CorrectionCandidateCallback &CCC,4968bool AfterNestedNameSpecifier) {4969if (AfterNestedNameSpecifier) {4970// For 'X::', we know exactly which keywords can appear next.4971Consumer.addKeywordResult("template");4972if (CCC.WantExpressionKeywords)4973Consumer.addKeywordResult("operator");4974return;4975}49764977if (CCC.WantObjCSuper)4978Consumer.addKeywordResult("super");49794980if (CCC.WantTypeSpecifiers) {4981// Add type-specifier keywords to the set of results.4982static const char *const CTypeSpecs[] = {4983"char", "const", "double", "enum", "float", "int", "long", "short",4984"signed", "struct", "union", "unsigned", "void", "volatile",4985"_Complex",4986// storage-specifiers as well4987"extern", "inline", "static", "typedef"4988};49894990for (const auto *CTS : CTypeSpecs)4991Consumer.addKeywordResult(CTS);49924993if (SemaRef.getLangOpts().C99 && !SemaRef.getLangOpts().C2y)4994Consumer.addKeywordResult("_Imaginary");49954996if (SemaRef.getLangOpts().C99)4997Consumer.addKeywordResult("restrict");4998if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)4999Consumer.addKeywordResult("bool");5000else if (SemaRef.getLangOpts().C99)5001Consumer.addKeywordResult("_Bool");50025003if (SemaRef.getLangOpts().CPlusPlus) {5004Consumer.addKeywordResult("class");5005Consumer.addKeywordResult("typename");5006Consumer.addKeywordResult("wchar_t");50075008if (SemaRef.getLangOpts().CPlusPlus11) {5009Consumer.addKeywordResult("char16_t");5010Consumer.addKeywordResult("char32_t");5011Consumer.addKeywordResult("constexpr");5012Consumer.addKeywordResult("decltype");5013Consumer.addKeywordResult("thread_local");5014}5015}50165017if (SemaRef.getLangOpts().GNUKeywords)5018Consumer.addKeywordResult("typeof");5019} else if (CCC.WantFunctionLikeCasts) {5020static const char *const CastableTypeSpecs[] = {5021"char", "double", "float", "int", "long", "short",5022"signed", "unsigned", "void"5023};5024for (auto *kw : CastableTypeSpecs)5025Consumer.addKeywordResult(kw);5026}50275028if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {5029Consumer.addKeywordResult("const_cast");5030Consumer.addKeywordResult("dynamic_cast");5031Consumer.addKeywordResult("reinterpret_cast");5032Consumer.addKeywordResult("static_cast");5033}50345035if (CCC.WantExpressionKeywords) {5036Consumer.addKeywordResult("sizeof");5037if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {5038Consumer.addKeywordResult("false");5039Consumer.addKeywordResult("true");5040}50415042if (SemaRef.getLangOpts().CPlusPlus) {5043static const char *const CXXExprs[] = {5044"delete", "new", "operator", "throw", "typeid"5045};5046for (const auto *CE : CXXExprs)5047Consumer.addKeywordResult(CE);50485049if (isa<CXXMethodDecl>(SemaRef.CurContext) &&5050cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())5051Consumer.addKeywordResult("this");50525053if (SemaRef.getLangOpts().CPlusPlus11) {5054Consumer.addKeywordResult("alignof");5055Consumer.addKeywordResult("nullptr");5056}5057}50585059if (SemaRef.getLangOpts().C11) {5060// FIXME: We should not suggest _Alignof if the alignof macro5061// is present.5062Consumer.addKeywordResult("_Alignof");5063}5064}50655066if (CCC.WantRemainingKeywords) {5067if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {5068// Statements.5069static const char *const CStmts[] = {5070"do", "else", "for", "goto", "if", "return", "switch", "while" };5071for (const auto *CS : CStmts)5072Consumer.addKeywordResult(CS);50735074if (SemaRef.getLangOpts().CPlusPlus) {5075Consumer.addKeywordResult("catch");5076Consumer.addKeywordResult("try");5077}50785079if (S && S->getBreakParent())5080Consumer.addKeywordResult("break");50815082if (S && S->getContinueParent())5083Consumer.addKeywordResult("continue");50845085if (SemaRef.getCurFunction() &&5086!SemaRef.getCurFunction()->SwitchStack.empty()) {5087Consumer.addKeywordResult("case");5088Consumer.addKeywordResult("default");5089}5090} else {5091if (SemaRef.getLangOpts().CPlusPlus) {5092Consumer.addKeywordResult("namespace");5093Consumer.addKeywordResult("template");5094}50955096if (S && S->isClassScope()) {5097Consumer.addKeywordResult("explicit");5098Consumer.addKeywordResult("friend");5099Consumer.addKeywordResult("mutable");5100Consumer.addKeywordResult("private");5101Consumer.addKeywordResult("protected");5102Consumer.addKeywordResult("public");5103Consumer.addKeywordResult("virtual");5104}5105}51065107if (SemaRef.getLangOpts().CPlusPlus) {5108Consumer.addKeywordResult("using");51095110if (SemaRef.getLangOpts().CPlusPlus11)5111Consumer.addKeywordResult("static_assert");5112}5113}5114}51155116std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(5117const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,5118Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,5119DeclContext *MemberContext, bool EnteringContext,5120const ObjCObjectPointerType *OPT, bool ErrorRecovery) {51215122if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||5123DisableTypoCorrection)5124return nullptr;51255126// In Microsoft mode, don't perform typo correction in a template member5127// function dependent context because it interferes with the "lookup into5128// dependent bases of class templates" feature.5129if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&5130isa<CXXMethodDecl>(CurContext))5131return nullptr;51325133// We only attempt to correct typos for identifiers.5134IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();5135if (!Typo)5136return nullptr;51375138// If the scope specifier itself was invalid, don't try to correct5139// typos.5140if (SS && SS->isInvalid())5141return nullptr;51425143// Never try to correct typos during any kind of code synthesis.5144if (!CodeSynthesisContexts.empty())5145return nullptr;51465147// Don't try to correct 'super'.5148if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())5149return nullptr;51505151// Abort if typo correction already failed for this specific typo.5152IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);5153if (locs != TypoCorrectionFailures.end() &&5154locs->second.count(TypoName.getLoc()))5155return nullptr;51565157// Don't try to correct the identifier "vector" when in AltiVec mode.5158// TODO: Figure out why typo correction misbehaves in this case, fix it, and5159// remove this workaround.5160if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))5161return nullptr;51625163// Provide a stop gap for files that are just seriously broken. Trying5164// to correct all typos can turn into a HUGE performance penalty, causing5165// some files to take minutes to get rejected by the parser.5166unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;5167if (Limit && TyposCorrected >= Limit)5168return nullptr;5169++TyposCorrected;51705171// If we're handling a missing symbol error, using modules, and the5172// special search all modules option is used, look for a missing import.5173if (ErrorRecovery && getLangOpts().Modules &&5174getLangOpts().ModulesSearchAll) {5175// The following has the side effect of loading the missing module.5176getModuleLoader().lookupMissingImports(Typo->getName(),5177TypoName.getBeginLoc());5178}51795180// Extend the lifetime of the callback. We delayed this until here5181// to avoid allocations in the hot path (which is where no typo correction5182// occurs). Note that CorrectionCandidateCallback is polymorphic and5183// initially stack-allocated.5184std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();5185auto Consumer = std::make_unique<TypoCorrectionConsumer>(5186*this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,5187EnteringContext);51885189// Perform name lookup to find visible, similarly-named entities.5190bool IsUnqualifiedLookup = false;5191DeclContext *QualifiedDC = MemberContext;5192if (MemberContext) {5193LookupVisibleDecls(MemberContext, LookupKind, *Consumer);51945195// Look in qualified interfaces.5196if (OPT) {5197for (auto *I : OPT->quals())5198LookupVisibleDecls(I, LookupKind, *Consumer);5199}5200} else if (SS && SS->isSet()) {5201QualifiedDC = computeDeclContext(*SS, EnteringContext);5202if (!QualifiedDC)5203return nullptr;52045205LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);5206} else {5207IsUnqualifiedLookup = true;5208}52095210// Determine whether we are going to search in the various namespaces for5211// corrections.5212bool SearchNamespaces5213= getLangOpts().CPlusPlus &&5214(IsUnqualifiedLookup || (SS && SS->isSet()));52155216if (IsUnqualifiedLookup || SearchNamespaces) {5217// For unqualified lookup, look through all of the names that we have5218// seen in this translation unit.5219// FIXME: Re-add the ability to skip very unlikely potential corrections.5220for (const auto &I : Context.Idents)5221Consumer->FoundName(I.getKey());52225223// Walk through identifiers in external identifier sources.5224// FIXME: Re-add the ability to skip very unlikely potential corrections.5225if (IdentifierInfoLookup *External5226= Context.Idents.getExternalIdentifierLookup()) {5227std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());5228do {5229StringRef Name = Iter->Next();5230if (Name.empty())5231break;52325233Consumer->FoundName(Name);5234} while (true);5235}5236}52375238AddKeywordsToConsumer(*this, *Consumer, S,5239*Consumer->getCorrectionValidator(),5240SS && SS->isNotEmpty());52415242// Build the NestedNameSpecifiers for the KnownNamespaces, if we're going5243// to search those namespaces.5244if (SearchNamespaces) {5245// Load any externally-known namespaces.5246if (ExternalSource && !LoadedExternalKnownNamespaces) {5247SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;5248LoadedExternalKnownNamespaces = true;5249ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);5250for (auto *N : ExternalKnownNamespaces)5251KnownNamespaces[N] = true;5252}52535254Consumer->addNamespaces(KnownNamespaces);5255}52565257return Consumer;5258}52595260TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,5261Sema::LookupNameKind LookupKind,5262Scope *S, CXXScopeSpec *SS,5263CorrectionCandidateCallback &CCC,5264CorrectTypoKind Mode,5265DeclContext *MemberContext,5266bool EnteringContext,5267const ObjCObjectPointerType *OPT,5268bool RecordFailure) {5269// Always let the ExternalSource have the first chance at correction, even5270// if we would otherwise have given up.5271if (ExternalSource) {5272if (TypoCorrection Correction =5273ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,5274MemberContext, EnteringContext, OPT))5275return Correction;5276}52775278// Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;5279// WantObjCSuper is only true for CTC_ObjCMessageReceiver and for5280// some instances of CTC_Unknown, while WantRemainingKeywords is true5281// for CTC_Unknown but not for CTC_ObjCMessageReceiver.5282bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;52835284IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();5285auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,5286MemberContext, EnteringContext,5287OPT, Mode == CTK_ErrorRecovery);52885289if (!Consumer)5290return TypoCorrection();52915292// If we haven't found anything, we're done.5293if (Consumer->empty())5294return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);52955296// Make sure the best edit distance (prior to adding any namespace qualifiers)5297// is not more that about a third of the length of the typo's identifier.5298unsigned ED = Consumer->getBestEditDistance(true);5299unsigned TypoLen = Typo->getName().size();5300if (ED > 0 && TypoLen / ED < 3)5301return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);53025303TypoCorrection BestTC = Consumer->getNextCorrection();5304TypoCorrection SecondBestTC = Consumer->getNextCorrection();5305if (!BestTC)5306return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);53075308ED = BestTC.getEditDistance();53095310if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {5311// If this was an unqualified lookup and we believe the callback5312// object wouldn't have filtered out possible corrections, note5313// that no correction was found.5314return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);5315}53165317// If only a single name remains, return that result.5318if (!SecondBestTC ||5319SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {5320const TypoCorrection &Result = BestTC;53215322// Don't correct to a keyword that's the same as the typo; the keyword5323// wasn't actually in scope.5324if (ED == 0 && Result.isKeyword())5325return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);53265327TypoCorrection TC = Result;5328TC.setCorrectionRange(SS, TypoName);5329checkCorrectionVisibility(*this, TC);5330return TC;5331} else if (SecondBestTC && ObjCMessageReceiver) {5332// Prefer 'super' when we're completing in a message-receiver5333// context.53345335if (BestTC.getCorrection().getAsString() != "super") {5336if (SecondBestTC.getCorrection().getAsString() == "super")5337BestTC = SecondBestTC;5338else if ((*Consumer)["super"].front().isKeyword())5339BestTC = (*Consumer)["super"].front();5340}5341// Don't correct to a keyword that's the same as the typo; the keyword5342// wasn't actually in scope.5343if (BestTC.getEditDistance() == 0 ||5344BestTC.getCorrection().getAsString() != "super")5345return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);53465347BestTC.setCorrectionRange(SS, TypoName);5348return BestTC;5349}53505351// Record the failure's location if needed and return an empty correction. If5352// this was an unqualified lookup and we believe the callback object did not5353// filter out possible corrections, also cache the failure for the typo.5354return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);5355}53565357TypoExpr *Sema::CorrectTypoDelayed(5358const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,5359Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,5360TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,5361DeclContext *MemberContext, bool EnteringContext,5362const ObjCObjectPointerType *OPT) {5363auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,5364MemberContext, EnteringContext,5365OPT, Mode == CTK_ErrorRecovery);53665367// Give the external sema source a chance to correct the typo.5368TypoCorrection ExternalTypo;5369if (ExternalSource && Consumer) {5370ExternalTypo = ExternalSource->CorrectTypo(5371TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),5372MemberContext, EnteringContext, OPT);5373if (ExternalTypo)5374Consumer->addCorrection(ExternalTypo);5375}53765377if (!Consumer || Consumer->empty())5378return nullptr;53795380// Make sure the best edit distance (prior to adding any namespace qualifiers)5381// is not more that about a third of the length of the typo's identifier.5382unsigned ED = Consumer->getBestEditDistance(true);5383IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();5384if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)5385return nullptr;5386ExprEvalContexts.back().NumTypos++;5387return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),5388TypoName.getLoc());5389}53905391void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {5392if (!CDecl) return;53935394if (isKeyword())5395CorrectionDecls.clear();53965397CorrectionDecls.push_back(CDecl);53985399if (!CorrectionName)5400CorrectionName = CDecl->getDeclName();5401}54025403std::string TypoCorrection::getAsString(const LangOptions &LO) const {5404if (CorrectionNameSpec) {5405std::string tmpBuffer;5406llvm::raw_string_ostream PrefixOStream(tmpBuffer);5407CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));5408PrefixOStream << CorrectionName;5409return PrefixOStream.str();5410}54115412return CorrectionName.getAsString();5413}54145415bool CorrectionCandidateCallback::ValidateCandidate(5416const TypoCorrection &candidate) {5417if (!candidate.isResolved())5418return true;54195420if (candidate.isKeyword())5421return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||5422WantRemainingKeywords || WantObjCSuper;54235424bool HasNonType = false;5425bool HasStaticMethod = false;5426bool HasNonStaticMethod = false;5427for (Decl *D : candidate) {5428if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))5429D = FTD->getTemplatedDecl();5430if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {5431if (Method->isStatic())5432HasStaticMethod = true;5433else5434HasNonStaticMethod = true;5435}5436if (!isa<TypeDecl>(D))5437HasNonType = true;5438}54395440if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&5441!candidate.getCorrectionSpecifier())5442return false;54435444return WantTypeSpecifiers || HasNonType;5445}54465447FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,5448bool HasExplicitTemplateArgs,5449MemberExpr *ME)5450: NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),5451CurContext(SemaRef.CurContext), MemberFn(ME) {5452WantTypeSpecifiers = false;5453WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&5454!HasExplicitTemplateArgs && NumArgs == 1;5455WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;5456WantRemainingKeywords = false;5457}54585459bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {5460if (!candidate.getCorrectionDecl())5461return candidate.isKeyword();54625463for (auto *C : candidate) {5464FunctionDecl *FD = nullptr;5465NamedDecl *ND = C->getUnderlyingDecl();5466if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))5467FD = FTD->getTemplatedDecl();5468if (!HasExplicitTemplateArgs && !FD) {5469if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {5470// If the Decl is neither a function nor a template function,5471// determine if it is a pointer or reference to a function. If so,5472// check against the number of arguments expected for the pointee.5473QualType ValType = cast<ValueDecl>(ND)->getType();5474if (ValType.isNull())5475continue;5476if (ValType->isAnyPointerType() || ValType->isReferenceType())5477ValType = ValType->getPointeeType();5478if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())5479if (FPT->getNumParams() == NumArgs)5480return true;5481}5482}54835484// A typo for a function-style cast can look like a function call in C++.5485if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr5486: isa<TypeDecl>(ND)) &&5487CurContext->getParentASTContext().getLangOpts().CPlusPlus)5488// Only a class or class template can take two or more arguments.5489return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);54905491// Skip the current candidate if it is not a FunctionDecl or does not accept5492// the current number of arguments.5493if (!FD || !(FD->getNumParams() >= NumArgs &&5494FD->getMinRequiredArguments() <= NumArgs))5495continue;54965497// If the current candidate is a non-static C++ method, skip the candidate5498// unless the method being corrected--or the current DeclContext, if the5499// function being corrected is not a method--is a method in the same class5500// or a descendent class of the candidate's parent class.5501if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {5502if (MemberFn || !MD->isStatic()) {5503const auto *CurMD =5504MemberFn5505? dyn_cast_if_present<CXXMethodDecl>(MemberFn->getMemberDecl())5506: dyn_cast_if_present<CXXMethodDecl>(CurContext);5507const CXXRecordDecl *CurRD =5508CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;5509const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();5510if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))5511continue;5512}5513}5514return true;5515}5516return false;5517}55185519void Sema::diagnoseTypo(const TypoCorrection &Correction,5520const PartialDiagnostic &TypoDiag,5521bool ErrorRecovery) {5522diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),5523ErrorRecovery);5524}55255526/// Find which declaration we should import to provide the definition of5527/// the given declaration.5528static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {5529if (const auto *VD = dyn_cast<VarDecl>(D))5530return VD->getDefinition();5531if (const auto *FD = dyn_cast<FunctionDecl>(D))5532return FD->getDefinition();5533if (const auto *TD = dyn_cast<TagDecl>(D))5534return TD->getDefinition();5535if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))5536return ID->getDefinition();5537if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))5538return PD->getDefinition();5539if (const auto *TD = dyn_cast<TemplateDecl>(D))5540if (const NamedDecl *TTD = TD->getTemplatedDecl())5541return getDefinitionToImport(TTD);5542return nullptr;5543}55445545void Sema::diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,5546MissingImportKind MIK, bool Recover) {5547// Suggest importing a module providing the definition of this entity, if5548// possible.5549const NamedDecl *Def = getDefinitionToImport(Decl);5550if (!Def)5551Def = Decl;55525553Module *Owner = getOwningModule(Def);5554assert(Owner && "definition of hidden declaration is not in a module");55555556llvm::SmallVector<Module*, 8> OwningModules;5557OwningModules.push_back(Owner);5558auto Merged = Context.getModulesWithMergedDefinition(Def);5559OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());55605561diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,5562Recover);5563}55645565/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic5566/// suggesting the addition of a #include of the specified file.5567static std::string getHeaderNameForHeader(Preprocessor &PP, FileEntryRef E,5568llvm::StringRef IncludingFile) {5569bool IsAngled = false;5570auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(5571E, IncludingFile, &IsAngled);5572return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');5573}55745575void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl,5576SourceLocation DeclLoc,5577ArrayRef<Module *> Modules,5578MissingImportKind MIK, bool Recover) {5579assert(!Modules.empty());55805581// See https://github.com/llvm/llvm-project/issues/73893. It is generally5582// confusing than helpful to show the namespace is not visible.5583if (isa<NamespaceDecl>(Decl))5584return;55855586auto NotePrevious = [&] {5587// FIXME: Suppress the note backtrace even under5588// -fdiagnostics-show-note-include-stack. We don't care how this5589// declaration was previously reached.5590Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;5591};55925593// Weed out duplicates from module list.5594llvm::SmallVector<Module*, 8> UniqueModules;5595llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;5596for (auto *M : Modules) {5597if (M->isExplicitGlobalModule() || M->isPrivateModule())5598continue;5599if (UniqueModuleSet.insert(M).second)5600UniqueModules.push_back(M);5601}56025603// Try to find a suitable header-name to #include.5604std::string HeaderName;5605if (OptionalFileEntryRef Header =5606PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {5607if (const FileEntry *FE =5608SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))5609HeaderName =5610getHeaderNameForHeader(PP, *Header, FE->tryGetRealPathName());5611}56125613// If we have a #include we should suggest, or if all definition locations5614// were in global module fragments, don't suggest an import.5615if (!HeaderName.empty() || UniqueModules.empty()) {5616// FIXME: Find a smart place to suggest inserting a #include, and add5617// a FixItHint there.5618Diag(UseLoc, diag::err_module_unimported_use_header)5619<< (int)MIK << Decl << !HeaderName.empty() << HeaderName;5620// Produce a note showing where the entity was declared.5621NotePrevious();5622if (Recover)5623createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);5624return;5625}56265627Modules = UniqueModules;56285629auto GetModuleNameForDiagnostic = [this](const Module *M) -> std::string {5630if (M->isModuleMapModule())5631return M->getFullModuleName();56325633if (M->isImplicitGlobalModule())5634M = M->getTopLevelModule();56355636// If the current module unit is in the same module with M, it is OK to show5637// the partition name. Otherwise, it'll be sufficient to show the primary5638// module name.5639if (getASTContext().isInSameModule(M, getCurrentModule()))5640return M->getTopLevelModuleName().str();5641else5642return M->getPrimaryModuleInterfaceName().str();5643};56445645if (Modules.size() > 1) {5646std::string ModuleList;5647unsigned N = 0;5648for (const auto *M : Modules) {5649ModuleList += "\n ";5650if (++N == 5 && N != Modules.size()) {5651ModuleList += "[...]";5652break;5653}5654ModuleList += GetModuleNameForDiagnostic(M);5655}56565657Diag(UseLoc, diag::err_module_unimported_use_multiple)5658<< (int)MIK << Decl << ModuleList;5659} else {5660// FIXME: Add a FixItHint that imports the corresponding module.5661Diag(UseLoc, diag::err_module_unimported_use)5662<< (int)MIK << Decl << GetModuleNameForDiagnostic(Modules[0]);5663}56645665NotePrevious();56665667// Try to recover by implicitly importing this module.5668if (Recover)5669createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);5670}56715672void Sema::diagnoseTypo(const TypoCorrection &Correction,5673const PartialDiagnostic &TypoDiag,5674const PartialDiagnostic &PrevNote,5675bool ErrorRecovery) {5676std::string CorrectedStr = Correction.getAsString(getLangOpts());5677std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());5678FixItHint FixTypo = FixItHint::CreateReplacement(5679Correction.getCorrectionRange(), CorrectedStr);56805681// Maybe we're just missing a module import.5682if (Correction.requiresImport()) {5683NamedDecl *Decl = Correction.getFoundDecl();5684assert(Decl && "import required but no declaration to import");56855686diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,5687MissingImportKind::Declaration, ErrorRecovery);5688return;5689}56905691Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)5692<< CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());56935694NamedDecl *ChosenDecl =5695Correction.isKeyword() ? nullptr : Correction.getFoundDecl();56965697// For builtin functions which aren't declared anywhere in source,5698// don't emit the "declared here" note.5699if (const auto *FD = dyn_cast_if_present<FunctionDecl>(ChosenDecl);5700FD && FD->getBuiltinID() &&5701PrevNote.getDiagID() == diag::note_previous_decl &&5702Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {5703ChosenDecl = nullptr;5704}57055706if (PrevNote.getDiagID() && ChosenDecl)5707Diag(ChosenDecl->getLocation(), PrevNote)5708<< CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);57095710// Add any extra diagnostics.5711for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())5712Diag(Correction.getCorrectionRange().getBegin(), PD);5713}57145715TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,5716TypoDiagnosticGenerator TDG,5717TypoRecoveryCallback TRC,5718SourceLocation TypoLoc) {5719assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");5720auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);5721auto &State = DelayedTypos[TE];5722State.Consumer = std::move(TCC);5723State.DiagHandler = std::move(TDG);5724State.RecoveryHandler = std::move(TRC);5725if (TE)5726TypoExprs.push_back(TE);5727return TE;5728}57295730const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {5731auto Entry = DelayedTypos.find(TE);5732assert(Entry != DelayedTypos.end() &&5733"Failed to get the state for a TypoExpr!");5734return Entry->second;5735}57365737void Sema::clearDelayedTypo(TypoExpr *TE) {5738DelayedTypos.erase(TE);5739}57405741void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {5742DeclarationNameInfo Name(II, IILoc);5743LookupResult R(*this, Name, LookupAnyName,5744RedeclarationKind::NotForRedeclaration);5745R.suppressDiagnostics();5746R.setHideTags(false);5747LookupName(R, S);5748R.dump();5749}57505751void Sema::ActOnPragmaDump(Expr *E) {5752E->dump();5753}57545755RedeclarationKind Sema::forRedeclarationInCurContext() const {5756// A declaration with an owning module for linkage can never link against5757// anything that is not visible. We don't need to check linkage here; if5758// the context has internal linkage, redeclaration lookup won't find things5759// from other TUs, and we can't safely compute linkage yet in general.5760if (cast<Decl>(CurContext)->getOwningModuleForLinkage())5761return RedeclarationKind::ForVisibleRedeclaration;5762return RedeclarationKind::ForExternalRedeclaration;5763}576457655766