Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/BlockExtractor.cpp
35266 views
//===- BlockExtractor.cpp - Extracts blocks into their own functions ------===//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 pass extracts the specified basic blocks from the module into their9// own functions.10//11//===----------------------------------------------------------------------===//1213#include "llvm/Transforms/IPO/BlockExtractor.h"14#include "llvm/ADT/STLExtras.h"15#include "llvm/ADT/Statistic.h"16#include "llvm/IR/Instructions.h"17#include "llvm/IR/Module.h"18#include "llvm/IR/PassManager.h"19#include "llvm/Support/CommandLine.h"20#include "llvm/Support/Debug.h"21#include "llvm/Support/MemoryBuffer.h"22#include "llvm/Transforms/IPO.h"23#include "llvm/Transforms/Utils/BasicBlockUtils.h"24#include "llvm/Transforms/Utils/CodeExtractor.h"2526using namespace llvm;2728#define DEBUG_TYPE "block-extractor"2930STATISTIC(NumExtracted, "Number of basic blocks extracted");3132static cl::opt<std::string> BlockExtractorFile(33"extract-blocks-file", cl::value_desc("filename"),34cl::desc("A file containing list of basic blocks to extract"), cl::Hidden);3536static cl::opt<bool>37BlockExtractorEraseFuncs("extract-blocks-erase-funcs",38cl::desc("Erase the existing functions"),39cl::Hidden);40namespace {41class BlockExtractor {42public:43BlockExtractor(bool EraseFunctions) : EraseFunctions(EraseFunctions) {}44bool runOnModule(Module &M);45void46init(const std::vector<std::vector<BasicBlock *>> &GroupsOfBlocksToExtract) {47GroupsOfBlocks = GroupsOfBlocksToExtract;48if (!BlockExtractorFile.empty())49loadFile();50}5152private:53std::vector<std::vector<BasicBlock *>> GroupsOfBlocks;54bool EraseFunctions;55/// Map a function name to groups of blocks.56SmallVector<std::pair<std::string, SmallVector<std::string, 4>>, 4>57BlocksByName;5859void loadFile();60void splitLandingPadPreds(Function &F);61};6263} // end anonymous namespace6465/// Gets all of the blocks specified in the input file.66void BlockExtractor::loadFile() {67auto ErrOrBuf = MemoryBuffer::getFile(BlockExtractorFile);68if (ErrOrBuf.getError())69report_fatal_error("BlockExtractor couldn't load the file.");70// Read the file.71auto &Buf = *ErrOrBuf;72SmallVector<StringRef, 16> Lines;73Buf->getBuffer().split(Lines, '\n', /*MaxSplit=*/-1,74/*KeepEmpty=*/false);75for (const auto &Line : Lines) {76SmallVector<StringRef, 4> LineSplit;77Line.split(LineSplit, ' ', /*MaxSplit=*/-1,78/*KeepEmpty=*/false);79if (LineSplit.empty())80continue;81if (LineSplit.size()!=2)82report_fatal_error("Invalid line format, expecting lines like: 'funcname bb1[;bb2..]'",83/*GenCrashDiag=*/false);84SmallVector<StringRef, 4> BBNames;85LineSplit[1].split(BBNames, ';', /*MaxSplit=*/-1,86/*KeepEmpty=*/false);87if (BBNames.empty())88report_fatal_error("Missing bbs name");89BlocksByName.push_back(90{std::string(LineSplit[0]), {BBNames.begin(), BBNames.end()}});91}92}9394/// Extracts the landing pads to make sure all of them have only one95/// predecessor.96void BlockExtractor::splitLandingPadPreds(Function &F) {97for (BasicBlock &BB : F) {98for (Instruction &I : BB) {99if (!isa<InvokeInst>(&I))100continue;101InvokeInst *II = cast<InvokeInst>(&I);102BasicBlock *Parent = II->getParent();103BasicBlock *LPad = II->getUnwindDest();104105// Look through the landing pad's predecessors. If one of them ends in an106// 'invoke', then we want to split the landing pad.107bool Split = false;108for (auto *PredBB : predecessors(LPad)) {109if (PredBB->isLandingPad() && PredBB != Parent &&110isa<InvokeInst>(Parent->getTerminator())) {111Split = true;112break;113}114}115116if (!Split)117continue;118119SmallVector<BasicBlock *, 2> NewBBs;120SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", NewBBs);121}122}123}124125bool BlockExtractor::runOnModule(Module &M) {126bool Changed = false;127128// Get all the functions.129SmallVector<Function *, 4> Functions;130for (Function &F : M) {131splitLandingPadPreds(F);132Functions.push_back(&F);133}134135// Get all the blocks specified in the input file.136unsigned NextGroupIdx = GroupsOfBlocks.size();137GroupsOfBlocks.resize(NextGroupIdx + BlocksByName.size());138for (const auto &BInfo : BlocksByName) {139Function *F = M.getFunction(BInfo.first);140if (!F)141report_fatal_error("Invalid function name specified in the input file",142/*GenCrashDiag=*/false);143for (const auto &BBInfo : BInfo.second) {144auto Res = llvm::find_if(145*F, [&](const BasicBlock &BB) { return BB.getName() == BBInfo; });146if (Res == F->end())147report_fatal_error("Invalid block name specified in the input file",148/*GenCrashDiag=*/false);149GroupsOfBlocks[NextGroupIdx].push_back(&*Res);150}151++NextGroupIdx;152}153154// Extract each group of basic blocks.155for (auto &BBs : GroupsOfBlocks) {156SmallVector<BasicBlock *, 32> BlocksToExtractVec;157for (BasicBlock *BB : BBs) {158// Check if the module contains BB.159if (BB->getParent()->getParent() != &M)160report_fatal_error("Invalid basic block", /*GenCrashDiag=*/false);161LLVM_DEBUG(dbgs() << "BlockExtractor: Extracting "162<< BB->getParent()->getName() << ":" << BB->getName()163<< "\n");164BlocksToExtractVec.push_back(BB);165if (const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))166BlocksToExtractVec.push_back(II->getUnwindDest());167++NumExtracted;168Changed = true;169}170CodeExtractorAnalysisCache CEAC(*BBs[0]->getParent());171Function *F = CodeExtractor(BlocksToExtractVec).extractCodeRegion(CEAC);172if (F)173LLVM_DEBUG(dbgs() << "Extracted group '" << (*BBs.begin())->getName()174<< "' in: " << F->getName() << '\n');175else176LLVM_DEBUG(dbgs() << "Failed to extract for group '"177<< (*BBs.begin())->getName() << "'\n");178}179180// Erase the functions.181if (EraseFunctions || BlockExtractorEraseFuncs) {182for (Function *F : Functions) {183LLVM_DEBUG(dbgs() << "BlockExtractor: Trying to delete " << F->getName()184<< "\n");185F->deleteBody();186}187// Set linkage as ExternalLinkage to avoid erasing unreachable functions.188for (Function &F : M)189F.setLinkage(GlobalValue::ExternalLinkage);190Changed = true;191}192193return Changed;194}195196BlockExtractorPass::BlockExtractorPass(197std::vector<std::vector<BasicBlock *>> &&GroupsOfBlocks,198bool EraseFunctions)199: GroupsOfBlocks(GroupsOfBlocks), EraseFunctions(EraseFunctions) {}200201PreservedAnalyses BlockExtractorPass::run(Module &M,202ModuleAnalysisManager &AM) {203BlockExtractor BE(EraseFunctions);204BE.init(GroupsOfBlocks);205return BE.runOnModule(M) ? PreservedAnalyses::none()206: PreservedAnalyses::all();207}208209210