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/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IRReader/IRReader.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/Regex.h"
29 #include "llvm/Support/Signals.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"));
52 // ExtractFuncs - The functions to extract from the module.
53 static cl::list<std::string>
54 ExtractFuncs("func", cl::desc("Specify function to extract"),
55 cl::ZeroOrMore, cl::value_desc("function"));
57 // ExtractRegExpFuncs - The functions, matched via regular expression, to
58 // extract from the module.
59 static cl::list<std::string>
60 ExtractRegExpFuncs("rfunc", cl::desc("Specify function(s) to extract using a "
61 "regular expression"),
62 cl::ZeroOrMore, cl::value_desc("rfunction"));
64 // ExtractAlias - The alias to extract from the module.
65 static cl::list<std::string>
66 ExtractAliases("alias", cl::desc("Specify alias to extract"),
67 cl::ZeroOrMore, cl::value_desc("alias"));
70 // ExtractRegExpAliases - The aliases, matched via regular expression, to
71 // extract from the module.
72 static cl::list<std::string>
73 ExtractRegExpAliases("ralias", cl::desc("Specify alias(es) to extract using a "
74 "regular expression"),
75 cl::ZeroOrMore, cl::value_desc("ralias"));
77 // ExtractGlobals - The globals to extract from the module.
78 static cl::list<std::string>
79 ExtractGlobals("glob", cl::desc("Specify global to extract"),
80 cl::ZeroOrMore, cl::value_desc("global"));
82 // ExtractRegExpGlobals - The globals, matched via regular expression, to
83 // extract from the module...
84 static cl::list<std::string>
85 ExtractRegExpGlobals("rglob", cl::desc("Specify global(s) to extract using a "
86 "regular expression"),
87 cl::ZeroOrMore, cl::value_desc("rglobal"));
91 cl::desc("Write output as LLVM assembly"), cl::Hidden);
93 static cl::opt<bool> PreserveBitcodeUseListOrder(
94 "preserve-bc-uselistorder",
95 cl::desc("Preserve use-list order when writing LLVM bitcode."),
96 cl::init(true), cl::Hidden);
98 static cl::opt<bool> PreserveAssemblyUseListOrder(
99 "preserve-ll-uselistorder",
100 cl::desc("Preserve use-list order when writing LLVM assembly."),
101 cl::init(false), cl::Hidden);
103 int main(int argc, char **argv) {
104 // Print a stack trace if we signal out.
105 sys::PrintStackTraceOnErrorSignal();
106 PrettyStackTraceProgram X(argc, argv);
108 LLVMContext &Context = getGlobalContext();
109 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
110 cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
112 // Use lazy loading, since we only care about selected global values.
114 std::unique_ptr<Module> M = getLazyIRFileModule(InputFilename, Err, Context);
117 Err.print(argv[0], errs());
121 // Use SetVector to avoid duplicates.
122 SetVector<GlobalValue *> GVs;
124 // Figure out which aliases we should extract.
125 for (size_t i = 0, e = ExtractAliases.size(); i != e; ++i) {
126 GlobalAlias *GA = M->getNamedAlias(ExtractAliases[i]);
128 errs() << argv[0] << ": program doesn't contain alias named '"
129 << ExtractAliases[i] << "'!\n";
135 // Extract aliases via regular expression matching.
136 for (size_t i = 0, e = ExtractRegExpAliases.size(); i != e; ++i) {
138 Regex RegEx(ExtractRegExpAliases[i]);
139 if (!RegEx.isValid(Error)) {
140 errs() << argv[0] << ": '" << ExtractRegExpAliases[i] << "' "
141 "invalid regex: " << Error;
144 for (Module::alias_iterator GA = M->alias_begin(), E = M->alias_end();
146 if (RegEx.match(GA->getName())) {
152 errs() << argv[0] << ": program doesn't contain global named '"
153 << ExtractRegExpAliases[i] << "'!\n";
158 // Figure out which globals we should extract.
159 for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
160 GlobalValue *GV = M->getNamedGlobal(ExtractGlobals[i]);
162 errs() << argv[0] << ": program doesn't contain global named '"
163 << ExtractGlobals[i] << "'!\n";
169 // Extract globals via regular expression matching.
170 for (size_t i = 0, e = ExtractRegExpGlobals.size(); i != e; ++i) {
172 Regex RegEx(ExtractRegExpGlobals[i]);
173 if (!RegEx.isValid(Error)) {
174 errs() << argv[0] << ": '" << ExtractRegExpGlobals[i] << "' "
175 "invalid regex: " << Error;
178 for (auto &GV : M->globals()) {
179 if (RegEx.match(GV.getName())) {
185 errs() << argv[0] << ": program doesn't contain global named '"
186 << ExtractRegExpGlobals[i] << "'!\n";
191 // Figure out which functions we should extract.
192 for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
193 GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
195 errs() << argv[0] << ": program doesn't contain function named '"
196 << ExtractFuncs[i] << "'!\n";
201 // Extract functions via regular expression matching.
202 for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
204 StringRef RegExStr = ExtractRegExpFuncs[i];
205 Regex RegEx(RegExStr);
206 if (!RegEx.isValid(Error)) {
207 errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
208 "invalid regex: " << Error;
211 for (Module::iterator F = M->begin(), E = M->end(); F != E;
213 if (RegEx.match(F->getName())) {
219 errs() << argv[0] << ": program doesn't contain global named '"
220 << ExtractRegExpFuncs[i] << "'!\n";
225 // Materialize requisite global values.
227 for (size_t i = 0, e = GVs.size(); i != e; ++i) {
228 GlobalValue *GV = GVs[i];
229 if (std::error_code EC = GV->materialize()) {
230 errs() << argv[0] << ": error reading input: " << EC.message() << "\n";
235 // Deleting. Materialize every GV that's *not* in GVs.
236 SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
237 for (auto &G : M->globals()) {
238 if (!GVSet.count(&G)) {
239 if (std::error_code EC = G.materialize()) {
240 errs() << argv[0] << ": error reading input: " << EC.message()
247 if (!GVSet.count(&F)) {
248 if (std::error_code EC = F.materialize()) {
249 errs() << argv[0] << ": error reading input: " << EC.message()
257 // In addition to deleting all other functions, we also want to spiff it
258 // up a little bit. Do this now.
259 legacy::PassManager Passes;
261 std::vector<GlobalValue*> Gvs(GVs.begin(), GVs.end());
263 Passes.add(createGVExtractionPass(Gvs, DeleteFn));
265 Passes.add(createGlobalDCEPass()); // Delete unreachable globals
266 Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
267 Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
270 tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
272 errs() << EC.message() << '\n';
278 createPrintModulePass(Out.os(), "", PreserveAssemblyUseListOrder));
279 else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
280 Passes.add(createBitcodeWriterPass(Out.os(), PreserveBitcodeUseListOrder));
282 Passes.run(*M.get());