Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/IRPartitionLayer.cpp
213799 views
//===----- IRPartitionLayer.cpp - Partition IR module into submodules -----===//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//===----------------------------------------------------------------------===//78#include "llvm/ExecutionEngine/Orc/IRPartitionLayer.h"9#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"10#include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"1112using namespace llvm;13using namespace llvm::orc;1415static ThreadSafeModule extractSubModule(ThreadSafeModule &TSM,16StringRef Suffix,17GVPredicate ShouldExtract) {1819auto DeleteExtractedDefs = [](GlobalValue &GV) {20// Bump the linkage: this global will be provided by the external module.21GV.setLinkage(GlobalValue::ExternalLinkage);2223// Delete the definition in the source module.24if (isa<Function>(GV)) {25auto &F = cast<Function>(GV);26F.deleteBody();27F.setPersonalityFn(nullptr);28} else if (isa<GlobalVariable>(GV)) {29cast<GlobalVariable>(GV).setInitializer(nullptr);30} else if (isa<GlobalAlias>(GV)) {31// We need to turn deleted aliases into function or variable decls based32// on the type of their aliasee.33auto &A = cast<GlobalAlias>(GV);34Constant *Aliasee = A.getAliasee();35assert(A.hasName() && "Anonymous alias?");36assert(Aliasee->hasName() && "Anonymous aliasee");37std::string AliasName = std::string(A.getName());3839if (isa<Function>(Aliasee)) {40auto *F = cloneFunctionDecl(*A.getParent(), *cast<Function>(Aliasee));41A.replaceAllUsesWith(F);42A.eraseFromParent();43F->setName(AliasName);44} else if (isa<GlobalVariable>(Aliasee)) {45auto *G = cloneGlobalVariableDecl(*A.getParent(),46*cast<GlobalVariable>(Aliasee));47A.replaceAllUsesWith(G);48A.eraseFromParent();49G->setName(AliasName);50} else51llvm_unreachable("Alias to unsupported type");52} else53llvm_unreachable("Unsupported global type");54};5556auto NewTSM = cloneToNewContext(TSM, ShouldExtract, DeleteExtractedDefs);57NewTSM.withModuleDo([&](Module &M) {58M.setModuleIdentifier((M.getModuleIdentifier() + Suffix).str());59});6061return NewTSM;62}6364namespace llvm {65namespace orc {6667class PartitioningIRMaterializationUnit : public IRMaterializationUnit {68public:69PartitioningIRMaterializationUnit(ExecutionSession &ES,70const IRSymbolMapper::ManglingOptions &MO,71ThreadSafeModule TSM,72IRPartitionLayer &Parent)73: IRMaterializationUnit(ES, MO, std::move(TSM)), Parent(Parent) {}7475PartitioningIRMaterializationUnit(76ThreadSafeModule TSM, Interface I,77SymbolNameToDefinitionMap SymbolToDefinition, IRPartitionLayer &Parent)78: IRMaterializationUnit(std::move(TSM), std::move(I),79std::move(SymbolToDefinition)),80Parent(Parent) {}8182private:83void materialize(std::unique_ptr<MaterializationResponsibility> R) override {84Parent.emitPartition(std::move(R), std::move(TSM),85std::move(SymbolToDefinition));86}8788void discard(const JITDylib &V, const SymbolStringPtr &Name) override {89// All original symbols were materialized by the CODLayer and should be90// final. The function bodies provided by M should never be overridden.91llvm_unreachable("Discard should never be called on an "92"ExtractingIRMaterializationUnit");93}9495IRPartitionLayer &Parent;96};9798} // namespace orc99} // namespace llvm100101IRPartitionLayer::IRPartitionLayer(ExecutionSession &ES, IRLayer &BaseLayer)102: IRLayer(ES, BaseLayer.getManglingOptions()), BaseLayer(BaseLayer) {}103104void IRPartitionLayer::setPartitionFunction(PartitionFunction Partition) {105this->Partition = Partition;106}107108std::optional<IRPartitionLayer::GlobalValueSet>109IRPartitionLayer::compileRequested(GlobalValueSet Requested) {110return std::move(Requested);111}112113std::optional<IRPartitionLayer::GlobalValueSet>114IRPartitionLayer::compileWholeModule(GlobalValueSet Requested) {115return std::nullopt;116}117118void IRPartitionLayer::emit(std::unique_ptr<MaterializationResponsibility> R,119ThreadSafeModule TSM) {120assert(TSM && "Null module");121122auto &ES = getExecutionSession();123TSM.withModuleDo([&](Module &M) {124// First, do some cleanup on the module:125cleanUpModule(M);126});127128// Create a partitioning materialization unit and pass the responsibility.129if (auto Err = R->replace(std::make_unique<PartitioningIRMaterializationUnit>(130ES, *getManglingOptions(), std::move(TSM), *this))) {131ES.reportError(std::move(Err));132R->failMaterialization();133return;134}135}136137void IRPartitionLayer::cleanUpModule(Module &M) {138for (auto &F : M.functions()) {139if (F.isDeclaration())140continue;141142if (F.hasAvailableExternallyLinkage()) {143F.deleteBody();144F.setPersonalityFn(nullptr);145continue;146}147}148}149150void IRPartitionLayer::expandPartition(GlobalValueSet &Partition) {151// Expands the partition to ensure the following rules hold:152// (1) If any alias is in the partition, its aliasee is also in the partition.153// (2) If any aliasee is in the partition, its aliases are also in the154// partiton.155// (3) If any global variable is in the partition then all global variables156// are in the partition.157assert(!Partition.empty() && "Unexpected empty partition");158159const Module &M = *(*Partition.begin())->getParent();160bool ContainsGlobalVariables = false;161std::vector<const GlobalValue *> GVsToAdd;162163for (const auto *GV : Partition)164if (isa<GlobalAlias>(GV))165GVsToAdd.push_back(166cast<GlobalValue>(cast<GlobalAlias>(GV)->getAliasee()));167else if (isa<GlobalVariable>(GV))168ContainsGlobalVariables = true;169170for (auto &A : M.aliases())171if (Partition.count(cast<GlobalValue>(A.getAliasee())))172GVsToAdd.push_back(&A);173174if (ContainsGlobalVariables)175for (auto &G : M.globals())176GVsToAdd.push_back(&G);177178for (const auto *GV : GVsToAdd)179Partition.insert(GV);180}181182void IRPartitionLayer::emitPartition(183std::unique_ptr<MaterializationResponsibility> R, ThreadSafeModule TSM,184IRMaterializationUnit::SymbolNameToDefinitionMap Defs) {185186// FIXME: Need a 'notify lazy-extracting/emitting' callback to tie the187// extracted module key, extracted module, and source module key188// together. This could be used, for example, to provide a specific189// memory manager instance to the linking layer.190191auto &ES = getExecutionSession();192GlobalValueSet RequestedGVs;193for (auto &Name : R->getRequestedSymbols()) {194if (Name == R->getInitializerSymbol())195TSM.withModuleDo([&](Module &M) {196for (auto &GV : getStaticInitGVs(M))197RequestedGVs.insert(&GV);198});199else {200assert(Defs.count(Name) && "No definition for symbol");201RequestedGVs.insert(Defs[Name]);202}203}204205/// Perform partitioning with the context lock held, since the partition206/// function is allowed to access the globals to compute the partition.207auto GVsToExtract =208TSM.withModuleDo([&](Module &M) { return Partition(RequestedGVs); });209210// Take a 'None' partition to mean the whole module (as opposed to an empty211// partition, which means "materialize nothing"). Emit the whole module212// unmodified to the base layer.213if (GVsToExtract == std::nullopt) {214Defs.clear();215BaseLayer.emit(std::move(R), std::move(TSM));216return;217}218219// If the partition is empty, return the whole module to the symbol table.220if (GVsToExtract->empty()) {221if (auto Err =222R->replace(std::make_unique<PartitioningIRMaterializationUnit>(223std::move(TSM),224MaterializationUnit::Interface(R->getSymbols(),225R->getInitializerSymbol()),226std::move(Defs), *this))) {227getExecutionSession().reportError(std::move(Err));228R->failMaterialization();229return;230}231return;232}233234// Ok -- we actually need to partition the symbols. Promote the symbol235// linkages/names, expand the partition to include any required symbols236// (i.e. symbols that can't be separated from our partition), and237// then extract the partition.238//239// FIXME: We apply this promotion once per partitioning. It's safe, but240// overkill.241auto ExtractedTSM = TSM.withModuleDo([&](Module &M)242-> Expected<ThreadSafeModule> {243auto PromotedGlobals = PromoteSymbols(M);244if (!PromotedGlobals.empty()) {245246MangleAndInterner Mangle(ES, M.getDataLayout());247SymbolFlagsMap SymbolFlags;248IRSymbolMapper::add(ES, *getManglingOptions(), PromotedGlobals,249SymbolFlags);250251if (auto Err = R->defineMaterializing(SymbolFlags))252return std::move(Err);253}254255expandPartition(*GVsToExtract);256257// Submodule name is given by hashing the names of the globals.258std::string SubModuleName;259{260std::vector<const GlobalValue *> HashGVs;261HashGVs.reserve(GVsToExtract->size());262llvm::append_range(HashGVs, *GVsToExtract);263llvm::sort(HashGVs, [](const GlobalValue *LHS, const GlobalValue *RHS) {264return LHS->getName() < RHS->getName();265});266hash_code HC(0);267for (const auto *GV : HashGVs) {268assert(GV->hasName() && "All GVs to extract should be named by now");269auto GVName = GV->getName();270HC = hash_combine(HC, hash_combine_range(GVName));271}272raw_string_ostream(SubModuleName)273<< ".submodule."274<< formatv(sizeof(size_t) == 8 ? "{0:x16}" : "{0:x8}",275static_cast<size_t>(HC))276<< ".ll";277}278279// Extract the requested partiton (plus any necessary aliases) and280// put the rest back into the impl dylib.281auto ShouldExtract = [&](const GlobalValue &GV) -> bool {282return GVsToExtract->count(&GV);283};284285return extractSubModule(TSM, SubModuleName, ShouldExtract);286});287288if (!ExtractedTSM) {289ES.reportError(ExtractedTSM.takeError());290R->failMaterialization();291return;292}293294if (auto Err = R->replace(std::make_unique<PartitioningIRMaterializationUnit>(295ES, *getManglingOptions(), std::move(TSM), *this))) {296ES.reportError(std::move(Err));297R->failMaterialization();298return;299}300BaseLayer.emit(std::move(R), std::move(*ExtractedTSM));301}302303304