1 //===- llvm-extract.cpp - LLVM function extraction utility ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility changes the input module to only contain a single function,
11 // which is primarily used for debugging transformations.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/Bitcode/BitcodeWriterPass.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/IRPrintingPasses.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/InitLLVM.h"
29 #include "llvm/Support/Regex.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Support/SystemUtils.h"
32 #include "llvm/Support/ToolOutputFile.h"
33 #include "llvm/Transforms/IPO.h"
37 // InputFilename - The filename to read from.
38 static cl::opt
<std::string
>
39 InputFilename(cl::Positional
, cl::desc("<input bitcode file>"),
40 cl::init("-"), cl::value_desc("filename"));
42 static cl::opt
<std::string
>
43 OutputFilename("o", cl::desc("Specify output filename"),
44 cl::value_desc("filename"), cl::init("-"));
47 Force("f", cl::desc("Enable binary output on terminals"));
50 DeleteFn("delete", cl::desc("Delete specified Globals from Module"));
53 Recursive("recursive",
54 cl::desc("Recursively extract all called functions"));
56 // ExtractFuncs - The functions to extract from the module.
57 static cl::list
<std::string
>
58 ExtractFuncs("func", cl::desc("Specify function to extract"),
59 cl::ZeroOrMore
, cl::value_desc("function"));
61 // ExtractRegExpFuncs - The functions, matched via regular expression, to
62 // extract from the module.
63 static cl::list
<std::string
>
64 ExtractRegExpFuncs("rfunc", cl::desc("Specify function(s) to extract using a "
65 "regular expression"),
66 cl::ZeroOrMore
, cl::value_desc("rfunction"));
68 // ExtractBlocks - The blocks to extract from the module.
69 static cl::list
<std::string
>
71 cl::desc("Specify <function, basic block> pairs to extract"),
72 cl::ZeroOrMore
, cl::value_desc("function:bb"));
74 // ExtractAlias - The alias to extract from the module.
75 static cl::list
<std::string
>
76 ExtractAliases("alias", cl::desc("Specify alias to extract"),
77 cl::ZeroOrMore
, cl::value_desc("alias"));
80 // ExtractRegExpAliases - The aliases, matched via regular expression, to
81 // extract from the module.
82 static cl::list
<std::string
>
83 ExtractRegExpAliases("ralias", cl::desc("Specify alias(es) to extract using a "
84 "regular expression"),
85 cl::ZeroOrMore
, cl::value_desc("ralias"));
87 // ExtractGlobals - The globals to extract from the module.
88 static cl::list
<std::string
>
89 ExtractGlobals("glob", cl::desc("Specify global to extract"),
90 cl::ZeroOrMore
, cl::value_desc("global"));
92 // ExtractRegExpGlobals - The globals, matched via regular expression, to
93 // extract from the module...
94 static cl::list
<std::string
>
95 ExtractRegExpGlobals("rglob", cl::desc("Specify global(s) to extract using a "
96 "regular expression"),
97 cl::ZeroOrMore
, cl::value_desc("rglobal"));
101 cl::desc("Write output as LLVM assembly"), cl::Hidden
);
103 static cl::opt
<bool> PreserveBitcodeUseListOrder(
104 "preserve-bc-uselistorder",
105 cl::desc("Preserve use-list order when writing LLVM bitcode."),
106 cl::init(true), cl::Hidden
);
108 static cl::opt
<bool> PreserveAssemblyUseListOrder(
109 "preserve-ll-uselistorder",
110 cl::desc("Preserve use-list order when writing LLVM assembly."),
111 cl::init(false), cl::Hidden
);
113 int main(int argc
, char **argv
) {
114 InitLLVM
X(argc
, argv
);
117 cl::ParseCommandLineOptions(argc
, argv
, "llvm extractor\n");
119 // Use lazy loading, since we only care about selected global values.
121 std::unique_ptr
<Module
> M
= getLazyIRFileModule(InputFilename
, Err
, Context
);
124 Err
.print(argv
[0], errs());
128 // Use SetVector to avoid duplicates.
129 SetVector
<GlobalValue
*> GVs
;
131 // Figure out which aliases we should extract.
132 for (size_t i
= 0, e
= ExtractAliases
.size(); i
!= e
; ++i
) {
133 GlobalAlias
*GA
= M
->getNamedAlias(ExtractAliases
[i
]);
135 errs() << argv
[0] << ": program doesn't contain alias named '"
136 << ExtractAliases
[i
] << "'!\n";
142 // Extract aliases via regular expression matching.
143 for (size_t i
= 0, e
= ExtractRegExpAliases
.size(); i
!= e
; ++i
) {
145 Regex
RegEx(ExtractRegExpAliases
[i
]);
146 if (!RegEx
.isValid(Error
)) {
147 errs() << argv
[0] << ": '" << ExtractRegExpAliases
[i
] << "' "
148 "invalid regex: " << Error
;
151 for (Module::alias_iterator GA
= M
->alias_begin(), E
= M
->alias_end();
153 if (RegEx
.match(GA
->getName())) {
159 errs() << argv
[0] << ": program doesn't contain global named '"
160 << ExtractRegExpAliases
[i
] << "'!\n";
165 // Figure out which globals we should extract.
166 for (size_t i
= 0, e
= ExtractGlobals
.size(); i
!= e
; ++i
) {
167 GlobalValue
*GV
= M
->getNamedGlobal(ExtractGlobals
[i
]);
169 errs() << argv
[0] << ": program doesn't contain global named '"
170 << ExtractGlobals
[i
] << "'!\n";
176 // Extract globals via regular expression matching.
177 for (size_t i
= 0, e
= ExtractRegExpGlobals
.size(); i
!= e
; ++i
) {
179 Regex
RegEx(ExtractRegExpGlobals
[i
]);
180 if (!RegEx
.isValid(Error
)) {
181 errs() << argv
[0] << ": '" << ExtractRegExpGlobals
[i
] << "' "
182 "invalid regex: " << Error
;
185 for (auto &GV
: M
->globals()) {
186 if (RegEx
.match(GV
.getName())) {
192 errs() << argv
[0] << ": program doesn't contain global named '"
193 << ExtractRegExpGlobals
[i
] << "'!\n";
198 // Figure out which functions we should extract.
199 for (size_t i
= 0, e
= ExtractFuncs
.size(); i
!= e
; ++i
) {
200 GlobalValue
*GV
= M
->getFunction(ExtractFuncs
[i
]);
202 errs() << argv
[0] << ": program doesn't contain function named '"
203 << ExtractFuncs
[i
] << "'!\n";
208 // Extract functions via regular expression matching.
209 for (size_t i
= 0, e
= ExtractRegExpFuncs
.size(); i
!= e
; ++i
) {
211 StringRef RegExStr
= ExtractRegExpFuncs
[i
];
212 Regex
RegEx(RegExStr
);
213 if (!RegEx
.isValid(Error
)) {
214 errs() << argv
[0] << ": '" << ExtractRegExpFuncs
[i
] << "' "
215 "invalid regex: " << Error
;
218 for (Module::iterator F
= M
->begin(), E
= M
->end(); F
!= E
;
220 if (RegEx
.match(F
->getName())) {
226 errs() << argv
[0] << ": program doesn't contain global named '"
227 << ExtractRegExpFuncs
[i
] << "'!\n";
232 // Figure out which BasicBlocks we should extract.
233 SmallVector
<BasicBlock
*, 4> BBs
;
234 for (StringRef StrPair
: ExtractBlocks
) {
235 auto BBInfo
= StrPair
.split(':');
237 Function
*F
= M
->getFunction(BBInfo
.first
);
239 errs() << argv
[0] << ": program doesn't contain a function named '"
240 << BBInfo
.first
<< "'!\n";
243 // Do not materialize this function.
245 // Get the basic block.
246 auto Res
= llvm::find_if(*F
, [&](const BasicBlock
&BB
) {
247 return BB
.getName().equals(BBInfo
.second
);
249 if (Res
== F
->end()) {
250 errs() << argv
[0] << ": function " << F
->getName()
251 << " doesn't contain a basic block named '" << BBInfo
.second
255 BBs
.push_back(&*Res
);
258 // Use *argv instead of argv[0] to work around a wrong GCC warning.
259 ExitOnError
ExitOnErr(std::string(*argv
) + ": error reading input: ");
262 std::vector
<llvm::Function
*> Workqueue
;
263 for (GlobalValue
*GV
: GVs
) {
264 if (auto *F
= dyn_cast
<Function
>(GV
)) {
265 Workqueue
.push_back(F
);
268 while (!Workqueue
.empty()) {
269 Function
*F
= &*Workqueue
.back();
270 Workqueue
.pop_back();
271 ExitOnErr(F
->materialize());
272 for (auto &BB
: *F
) {
274 auto *CI
= dyn_cast
<CallInst
>(&I
);
277 Function
*CF
= CI
->getCalledFunction();
280 if (CF
->isDeclaration() || GVs
.count(CF
))
283 Workqueue
.push_back(CF
);
289 auto Materialize
= [&](GlobalValue
&GV
) { ExitOnErr(GV
.materialize()); };
291 // Materialize requisite global values.
293 for (size_t i
= 0, e
= GVs
.size(); i
!= e
; ++i
)
294 Materialize(*GVs
[i
]);
296 // Deleting. Materialize every GV that's *not* in GVs.
297 SmallPtrSet
<GlobalValue
*, 8> GVSet(GVs
.begin(), GVs
.end());
299 if (!GVSet
.count(&F
))
305 std::vector
<GlobalValue
*> Gvs(GVs
.begin(), GVs
.end());
306 legacy::PassManager Extract
;
307 Extract
.add(createGVExtractionPass(Gvs
, DeleteFn
));
310 // Now that we have all the GVs we want, mark the module as fully
312 // FIXME: should the GVExtractionPass handle this?
313 ExitOnErr(M
->materializeAll());
316 // Extract the specified basic blocks from the module and erase the existing
318 if (!ExtractBlocks
.empty()) {
319 legacy::PassManager PM
;
320 PM
.add(createBlockExtractorPass(BBs
, true));
324 // In addition to deleting all other functions, we also want to spiff it
325 // up a little bit. Do this now.
326 legacy::PassManager Passes
;
329 Passes
.add(createGlobalDCEPass()); // Delete unreachable globals
330 Passes
.add(createStripDeadDebugInfoPass()); // Remove dead debug info
331 Passes
.add(createStripDeadPrototypesPass()); // Remove dead func decls
334 ToolOutputFile
Out(OutputFilename
, EC
, sys::fs::F_None
);
336 errs() << EC
.message() << '\n';
342 createPrintModulePass(Out
.os(), "", PreserveAssemblyUseListOrder
));
343 else if (Force
|| !CheckBitcodeOutputToConsole(Out
.os(), true))
344 Passes
.add(createBitcodeWriterPass(Out
.os(), PreserveBitcodeUseListOrder
));
346 Passes
.run(*M
.get());