1dc40be75SVolkan Keles //===- BlockExtractor.cpp - Extracts blocks into their own functions ------===//
2dc40be75SVolkan Keles //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dc40be75SVolkan Keles //
7dc40be75SVolkan Keles //===----------------------------------------------------------------------===//
8dc40be75SVolkan Keles //
9dc40be75SVolkan Keles // This pass extracts the specified basic blocks from the module into their
10dc40be75SVolkan Keles // own functions.
11dc40be75SVolkan Keles //
12dc40be75SVolkan Keles //===----------------------------------------------------------------------===//
13dc40be75SVolkan Keles 
14dc40be75SVolkan Keles #include "llvm/ADT/STLExtras.h"
15dc40be75SVolkan Keles #include "llvm/ADT/Statistic.h"
16dc40be75SVolkan Keles #include "llvm/IR/Instructions.h"
17dc40be75SVolkan Keles #include "llvm/IR/Module.h"
18dc40be75SVolkan Keles #include "llvm/Pass.h"
19dc40be75SVolkan Keles #include "llvm/Support/CommandLine.h"
20dc40be75SVolkan Keles #include "llvm/Support/Debug.h"
21dc40be75SVolkan Keles #include "llvm/Support/MemoryBuffer.h"
22dc40be75SVolkan Keles #include "llvm/Transforms/IPO.h"
23dc40be75SVolkan Keles #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24dc40be75SVolkan Keles #include "llvm/Transforms/Utils/CodeExtractor.h"
25ea3364bfSQuentin Colombet 
26dc40be75SVolkan Keles using namespace llvm;
27dc40be75SVolkan Keles 
28dc40be75SVolkan Keles #define DEBUG_TYPE "block-extractor"
29dc40be75SVolkan Keles 
30dc40be75SVolkan Keles STATISTIC(NumExtracted, "Number of basic blocks extracted");
31dc40be75SVolkan Keles 
32dc40be75SVolkan Keles static cl::opt<std::string> BlockExtractorFile(
33dc40be75SVolkan Keles     "extract-blocks-file", cl::value_desc("filename"),
34dc40be75SVolkan Keles     cl::desc("A file containing list of basic blocks to extract"), cl::Hidden);
35dc40be75SVolkan Keles 
36dc40be75SVolkan Keles cl::opt<bool> BlockExtractorEraseFuncs("extract-blocks-erase-funcs",
37dc40be75SVolkan Keles                                        cl::desc("Erase the existing functions"),
38dc40be75SVolkan Keles                                        cl::Hidden);
39dc40be75SVolkan Keles namespace {
40dc40be75SVolkan Keles class BlockExtractor : public ModulePass {
41ea3364bfSQuentin Colombet   SmallVector<SmallVector<BasicBlock *, 16>, 4> GroupsOfBlocks;
42dc40be75SVolkan Keles   bool EraseFunctions;
43ea3364bfSQuentin Colombet   /// Map a function name to groups of blocks.
44ea3364bfSQuentin Colombet   SmallVector<std::pair<std::string, SmallVector<std::string, 4>>, 4>
45ea3364bfSQuentin Colombet       BlocksByName;
46dc40be75SVolkan Keles 
4731ce2742SQuentin Colombet   void init(const SmallVectorImpl<SmallVector<BasicBlock *, 16>>
4831ce2742SQuentin Colombet                 &GroupsOfBlocksToExtract) {
4931ce2742SQuentin Colombet     for (const SmallVectorImpl<BasicBlock *> &GroupOfBlocks :
5031ce2742SQuentin Colombet          GroupsOfBlocksToExtract) {
5131ce2742SQuentin Colombet       SmallVector<BasicBlock *, 16> NewGroup;
5231ce2742SQuentin Colombet       NewGroup.append(GroupOfBlocks.begin(), GroupOfBlocks.end());
5331ce2742SQuentin Colombet       GroupsOfBlocks.emplace_back(NewGroup);
5431ce2742SQuentin Colombet     }
5531ce2742SQuentin Colombet     if (!BlockExtractorFile.empty())
5631ce2742SQuentin Colombet       loadFile();
5731ce2742SQuentin Colombet   }
5831ce2742SQuentin Colombet 
59dc40be75SVolkan Keles public:
60dc40be75SVolkan Keles   static char ID;
61dc40be75SVolkan Keles   BlockExtractor(const SmallVectorImpl<BasicBlock *> &BlocksToExtract,
62dc40be75SVolkan Keles                  bool EraseFunctions)
63ea3364bfSQuentin Colombet       : ModulePass(ID), EraseFunctions(EraseFunctions) {
64ea3364bfSQuentin Colombet     // We want one group per element of the input list.
6531ce2742SQuentin Colombet     SmallVector<SmallVector<BasicBlock *, 16>, 4> MassagedGroupsOfBlocks;
66ea3364bfSQuentin Colombet     for (BasicBlock *BB : BlocksToExtract) {
67ea3364bfSQuentin Colombet       SmallVector<BasicBlock *, 16> NewGroup;
68ea3364bfSQuentin Colombet       NewGroup.push_back(BB);
6931ce2742SQuentin Colombet       MassagedGroupsOfBlocks.push_back(NewGroup);
70ea3364bfSQuentin Colombet     }
7131ce2742SQuentin Colombet     init(MassagedGroupsOfBlocks);
72dc40be75SVolkan Keles   }
7331ce2742SQuentin Colombet 
7431ce2742SQuentin Colombet   BlockExtractor(const SmallVectorImpl<SmallVector<BasicBlock *, 16>>
7531ce2742SQuentin Colombet                      &GroupsOfBlocksToExtract,
7631ce2742SQuentin Colombet                  bool EraseFunctions)
7731ce2742SQuentin Colombet       : ModulePass(ID), EraseFunctions(EraseFunctions) {
7831ce2742SQuentin Colombet     init(GroupsOfBlocksToExtract);
7931ce2742SQuentin Colombet   }
8031ce2742SQuentin Colombet 
81dc40be75SVolkan Keles   BlockExtractor() : BlockExtractor(SmallVector<BasicBlock *, 0>(), false) {}
82dc40be75SVolkan Keles   bool runOnModule(Module &M) override;
83dc40be75SVolkan Keles 
84dc40be75SVolkan Keles private:
85dc40be75SVolkan Keles   void loadFile();
86dc40be75SVolkan Keles   void splitLandingPadPreds(Function &F);
87dc40be75SVolkan Keles };
88dc40be75SVolkan Keles } // end anonymous namespace
89dc40be75SVolkan Keles 
90dc40be75SVolkan Keles char BlockExtractor::ID = 0;
91dc40be75SVolkan Keles INITIALIZE_PASS(BlockExtractor, "extract-blocks",
92dc40be75SVolkan Keles                 "Extract basic blocks from module", false, false)
93dc40be75SVolkan Keles 
94dc40be75SVolkan Keles ModulePass *llvm::createBlockExtractorPass() { return new BlockExtractor(); }
95dc40be75SVolkan Keles ModulePass *llvm::createBlockExtractorPass(
96dc40be75SVolkan Keles     const SmallVectorImpl<BasicBlock *> &BlocksToExtract, bool EraseFunctions) {
97dc40be75SVolkan Keles   return new BlockExtractor(BlocksToExtract, EraseFunctions);
98dc40be75SVolkan Keles }
9931ce2742SQuentin Colombet ModulePass *llvm::createBlockExtractorPass(
10031ce2742SQuentin Colombet     const SmallVectorImpl<SmallVector<BasicBlock *, 16>>
10131ce2742SQuentin Colombet         &GroupsOfBlocksToExtract,
10231ce2742SQuentin Colombet     bool EraseFunctions) {
10331ce2742SQuentin Colombet   return new BlockExtractor(GroupsOfBlocksToExtract, EraseFunctions);
10431ce2742SQuentin Colombet }
105dc40be75SVolkan Keles 
106dc40be75SVolkan Keles /// Gets all of the blocks specified in the input file.
107dc40be75SVolkan Keles void BlockExtractor::loadFile() {
108dc40be75SVolkan Keles   auto ErrOrBuf = MemoryBuffer::getFile(BlockExtractorFile);
109ebf34ea3SVolkan Keles   if (ErrOrBuf.getError())
110dc40be75SVolkan Keles     report_fatal_error("BlockExtractor couldn't load the file.");
111dc40be75SVolkan Keles   // Read the file.
112dc40be75SVolkan Keles   auto &Buf = *ErrOrBuf;
113dc40be75SVolkan Keles   SmallVector<StringRef, 16> Lines;
114dc40be75SVolkan Keles   Buf->getBuffer().split(Lines, '\n', /*MaxSplit=*/-1,
115dc40be75SVolkan Keles                          /*KeepEmpty=*/false);
116dc40be75SVolkan Keles   for (const auto &Line : Lines) {
117ea3364bfSQuentin Colombet     SmallVector<StringRef, 4> LineSplit;
118ea3364bfSQuentin Colombet     Line.split(LineSplit, ' ', /*MaxSplit=*/-1,
119ea3364bfSQuentin Colombet                /*KeepEmpty=*/false);
120ea3364bfSQuentin Colombet     if (LineSplit.empty())
121ea3364bfSQuentin Colombet       continue;
122*cda334baSJinsong Ji     if (LineSplit.size()!=2)
123*cda334baSJinsong Ji       report_fatal_error("Invalid line format, expecting lines like: 'funcname bb1[;bb2..]'");
124ea3364bfSQuentin Colombet     SmallVector<StringRef, 4> BBNames;
125ae2cbb34SQuentin Colombet     LineSplit[1].split(BBNames, ';', /*MaxSplit=*/-1,
126ea3364bfSQuentin Colombet                        /*KeepEmpty=*/false);
127ea3364bfSQuentin Colombet     if (BBNames.empty())
128ea3364bfSQuentin Colombet       report_fatal_error("Missing bbs name");
129ea3364bfSQuentin Colombet     BlocksByName.push_back({LineSplit[0], {BBNames.begin(), BBNames.end()}});
130dc40be75SVolkan Keles   }
131dc40be75SVolkan Keles }
132dc40be75SVolkan Keles 
133dc40be75SVolkan Keles /// Extracts the landing pads to make sure all of them have only one
134dc40be75SVolkan Keles /// predecessor.
135dc40be75SVolkan Keles void BlockExtractor::splitLandingPadPreds(Function &F) {
136dc40be75SVolkan Keles   for (BasicBlock &BB : F) {
137dc40be75SVolkan Keles     for (Instruction &I : BB) {
138dc40be75SVolkan Keles       if (!isa<InvokeInst>(&I))
139dc40be75SVolkan Keles         continue;
140dc40be75SVolkan Keles       InvokeInst *II = cast<InvokeInst>(&I);
141dc40be75SVolkan Keles       BasicBlock *Parent = II->getParent();
142dc40be75SVolkan Keles       BasicBlock *LPad = II->getUnwindDest();
143dc40be75SVolkan Keles 
144dc40be75SVolkan Keles       // Look through the landing pad's predecessors. If one of them ends in an
145dc40be75SVolkan Keles       // 'invoke', then we want to split the landing pad.
146dc40be75SVolkan Keles       bool Split = false;
147dc40be75SVolkan Keles       for (auto PredBB : predecessors(LPad)) {
148dc40be75SVolkan Keles         if (PredBB->isLandingPad() && PredBB != Parent &&
149dc40be75SVolkan Keles             isa<InvokeInst>(Parent->getTerminator())) {
150dc40be75SVolkan Keles           Split = true;
151dc40be75SVolkan Keles           break;
152dc40be75SVolkan Keles         }
153dc40be75SVolkan Keles       }
154dc40be75SVolkan Keles 
155dc40be75SVolkan Keles       if (!Split)
156dc40be75SVolkan Keles         continue;
157dc40be75SVolkan Keles 
158dc40be75SVolkan Keles       SmallVector<BasicBlock *, 2> NewBBs;
159dc40be75SVolkan Keles       SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", NewBBs);
160dc40be75SVolkan Keles     }
161dc40be75SVolkan Keles   }
162dc40be75SVolkan Keles }
163dc40be75SVolkan Keles 
164dc40be75SVolkan Keles bool BlockExtractor::runOnModule(Module &M) {
165dc40be75SVolkan Keles 
166dc40be75SVolkan Keles   bool Changed = false;
167dc40be75SVolkan Keles 
168dc40be75SVolkan Keles   // Get all the functions.
169dc40be75SVolkan Keles   SmallVector<Function *, 4> Functions;
170dc40be75SVolkan Keles   for (Function &F : M) {
171dc40be75SVolkan Keles     splitLandingPadPreds(F);
172dc40be75SVolkan Keles     Functions.push_back(&F);
173dc40be75SVolkan Keles   }
174dc40be75SVolkan Keles 
175dc40be75SVolkan Keles   // Get all the blocks specified in the input file.
176ea3364bfSQuentin Colombet   unsigned NextGroupIdx = GroupsOfBlocks.size();
177ea3364bfSQuentin Colombet   GroupsOfBlocks.resize(NextGroupIdx + BlocksByName.size());
178dc40be75SVolkan Keles   for (const auto &BInfo : BlocksByName) {
179dc40be75SVolkan Keles     Function *F = M.getFunction(BInfo.first);
180dc40be75SVolkan Keles     if (!F)
181dc40be75SVolkan Keles       report_fatal_error("Invalid function name specified in the input file");
182ea3364bfSQuentin Colombet     for (const auto &BBInfo : BInfo.second) {
183dc40be75SVolkan Keles       auto Res = llvm::find_if(*F, [&](const BasicBlock &BB) {
184ea3364bfSQuentin Colombet         return BB.getName().equals(BBInfo);
185dc40be75SVolkan Keles       });
186dc40be75SVolkan Keles       if (Res == F->end())
187dc40be75SVolkan Keles         report_fatal_error("Invalid block name specified in the input file");
188ea3364bfSQuentin Colombet       GroupsOfBlocks[NextGroupIdx].push_back(&*Res);
189ea3364bfSQuentin Colombet     }
190ea3364bfSQuentin Colombet     ++NextGroupIdx;
191dc40be75SVolkan Keles   }
192dc40be75SVolkan Keles 
193ea3364bfSQuentin Colombet   // Extract each group of basic blocks.
194ea3364bfSQuentin Colombet   for (auto &BBs : GroupsOfBlocks) {
195ea3364bfSQuentin Colombet     SmallVector<BasicBlock *, 32> BlocksToExtractVec;
196ea3364bfSQuentin Colombet     for (BasicBlock *BB : BBs) {
197dc40be75SVolkan Keles       // Check if the module contains BB.
198dc40be75SVolkan Keles       if (BB->getParent()->getParent() != &M)
199dc40be75SVolkan Keles         report_fatal_error("Invalid basic block");
200d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "BlockExtractor: Extracting "
201d34e60caSNicola Zaghen                         << BB->getParent()->getName() << ":" << BB->getName()
202d34e60caSNicola Zaghen                         << "\n");
203dc40be75SVolkan Keles       BlocksToExtractVec.push_back(BB);
204dc40be75SVolkan Keles       if (const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
205dc40be75SVolkan Keles         BlocksToExtractVec.push_back(II->getUnwindDest());
206dc40be75SVolkan Keles       ++NumExtracted;
207dc40be75SVolkan Keles       Changed = true;
208dc40be75SVolkan Keles     }
209ea3364bfSQuentin Colombet     Function *F = CodeExtractor(BlocksToExtractVec).extractCodeRegion();
210ea3364bfSQuentin Colombet     if (F)
211ea3364bfSQuentin Colombet       LLVM_DEBUG(dbgs() << "Extracted group '" << (*BBs.begin())->getName()
212ea3364bfSQuentin Colombet                         << "' in: " << F->getName() << '\n');
213ea3364bfSQuentin Colombet     else
214ea3364bfSQuentin Colombet       LLVM_DEBUG(dbgs() << "Failed to extract for group '"
215ea3364bfSQuentin Colombet                         << (*BBs.begin())->getName() << "'\n");
216ea3364bfSQuentin Colombet   }
217dc40be75SVolkan Keles 
218dc40be75SVolkan Keles   // Erase the functions.
219dc40be75SVolkan Keles   if (EraseFunctions || BlockExtractorEraseFuncs) {
220dc40be75SVolkan Keles     for (Function *F : Functions) {
221d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "BlockExtractor: Trying to delete " << F->getName()
2224ecdb44aSVolkan Keles                         << "\n");
2234ecdb44aSVolkan Keles       F->deleteBody();
224dc40be75SVolkan Keles     }
225dc40be75SVolkan Keles     // Set linkage as ExternalLinkage to avoid erasing unreachable functions.
226dc40be75SVolkan Keles     for (Function &F : M)
227dc40be75SVolkan Keles       F.setLinkage(GlobalValue::ExternalLinkage);
228dc40be75SVolkan Keles     Changed = true;
229dc40be75SVolkan Keles   }
230dc40be75SVolkan Keles 
231dc40be75SVolkan Keles   return Changed;
232dc40be75SVolkan Keles }
233