llvm-extract.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. //===- llvm-extract.cpp - LLVM function extraction utility ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This utility changes the input module to only contain a single function,
  10. // which is primarily used for debugging transformations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/SetVector.h"
  14. #include "llvm/ADT/SmallPtrSet.h"
  15. #include "llvm/Bitcode/BitcodeWriterPass.h"
  16. #include "llvm/IR/DataLayout.h"
  17. #include "llvm/IR/IRPrintingPasses.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/IR/LLVMContext.h"
  20. #include "llvm/IR/LegacyPassManager.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/IRReader/IRReader.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/Error.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include "llvm/Support/InitLLVM.h"
  27. #include "llvm/Support/Regex.h"
  28. #include "llvm/Support/SourceMgr.h"
  29. #include "llvm/Support/SystemUtils.h"
  30. #include "llvm/Support/ToolOutputFile.h"
  31. #include "llvm/Transforms/IPO.h"
  32. #include <memory>
  33. using namespace llvm;
  34. cl::OptionCategory ExtractCat("llvm-extract Options");
  35. // InputFilename - The filename to read from.
  36. static cl::opt<std::string> InputFilename(cl::Positional,
  37. cl::desc("<input bitcode file>"),
  38. cl::init("-"),
  39. cl::value_desc("filename"));
  40. static cl::opt<std::string> OutputFilename("o",
  41. cl::desc("Specify output filename"),
  42. cl::value_desc("filename"),
  43. cl::init("-"), cl::cat(ExtractCat));
  44. static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"),
  45. cl::cat(ExtractCat));
  46. static cl::opt<bool> DeleteFn("delete",
  47. cl::desc("Delete specified Globals from Module"),
  48. cl::cat(ExtractCat));
  49. static cl::opt<bool>
  50. Recursive("recursive", cl::desc("Recursively extract all called functions"),
  51. cl::cat(ExtractCat));
  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"),
  56. cl::cat(ExtractCat));
  57. // ExtractRegExpFuncs - The functions, matched via regular expression, to
  58. // extract from the module.
  59. static cl::list<std::string>
  60. ExtractRegExpFuncs("rfunc",
  61. cl::desc("Specify function(s) to extract using a "
  62. "regular expression"),
  63. cl::ZeroOrMore, cl::value_desc("rfunction"),
  64. cl::cat(ExtractCat));
  65. // ExtractBlocks - The blocks to extract from the module.
  66. static cl::list<std::string> ExtractBlocks(
  67. "bb", cl::desc("Specify <function, basic block> pairs to extract"),
  68. cl::ZeroOrMore, cl::value_desc("function:bb"), cl::cat(ExtractCat));
  69. // ExtractAlias - The alias to extract from the module.
  70. static cl::list<std::string>
  71. ExtractAliases("alias", cl::desc("Specify alias to extract"),
  72. cl::ZeroOrMore, cl::value_desc("alias"),
  73. cl::cat(ExtractCat));
  74. // ExtractRegExpAliases - The aliases, matched via regular expression, to
  75. // extract from the module.
  76. static cl::list<std::string>
  77. ExtractRegExpAliases("ralias",
  78. cl::desc("Specify alias(es) to extract using a "
  79. "regular expression"),
  80. cl::ZeroOrMore, cl::value_desc("ralias"),
  81. cl::cat(ExtractCat));
  82. // ExtractGlobals - The globals to extract from the module.
  83. static cl::list<std::string>
  84. ExtractGlobals("glob", cl::desc("Specify global to extract"),
  85. cl::ZeroOrMore, cl::value_desc("global"),
  86. cl::cat(ExtractCat));
  87. // ExtractRegExpGlobals - The globals, matched via regular expression, to
  88. // extract from the module...
  89. static cl::list<std::string>
  90. ExtractRegExpGlobals("rglob",
  91. cl::desc("Specify global(s) to extract using a "
  92. "regular expression"),
  93. cl::ZeroOrMore, cl::value_desc("rglobal"),
  94. cl::cat(ExtractCat));
  95. static cl::opt<bool> OutputAssembly("S",
  96. cl::desc("Write output as LLVM assembly"),
  97. cl::Hidden, cl::cat(ExtractCat));
  98. static cl::opt<bool> PreserveBitcodeUseListOrder(
  99. "preserve-bc-uselistorder",
  100. cl::desc("Preserve use-list order when writing LLVM bitcode."),
  101. cl::init(true), cl::Hidden, cl::cat(ExtractCat));
  102. static cl::opt<bool> PreserveAssemblyUseListOrder(
  103. "preserve-ll-uselistorder",
  104. cl::desc("Preserve use-list order when writing LLVM assembly."),
  105. cl::init(false), cl::Hidden, cl::cat(ExtractCat));
  106. int main(int argc, char **argv) {
  107. InitLLVM X(argc, argv);
  108. LLVMContext Context;
  109. cl::HideUnrelatedOptions(ExtractCat);
  110. cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
  111. // Use lazy loading, since we only care about selected global values.
  112. SMDiagnostic Err;
  113. std::unique_ptr<Module> M = getLazyIRFileModule(InputFilename, Err, Context);
  114. if (!M.get()) {
  115. Err.print(argv[0], errs());
  116. return 1;
  117. }
  118. // Use SetVector to avoid duplicates.
  119. SetVector<GlobalValue *> GVs;
  120. // Figure out which aliases we should extract.
  121. for (size_t i = 0, e = ExtractAliases.size(); i != e; ++i) {
  122. GlobalAlias *GA = M->getNamedAlias(ExtractAliases[i]);
  123. if (!GA) {
  124. errs() << argv[0] << ": program doesn't contain alias named '"
  125. << ExtractAliases[i] << "'!\n";
  126. return 1;
  127. }
  128. GVs.insert(GA);
  129. }
  130. // Extract aliases via regular expression matching.
  131. for (size_t i = 0, e = ExtractRegExpAliases.size(); i != e; ++i) {
  132. std::string Error;
  133. Regex RegEx(ExtractRegExpAliases[i]);
  134. if (!RegEx.isValid(Error)) {
  135. errs() << argv[0] << ": '" << ExtractRegExpAliases[i] << "' "
  136. "invalid regex: " << Error;
  137. }
  138. bool match = false;
  139. for (Module::alias_iterator GA = M->alias_begin(), E = M->alias_end();
  140. GA != E; GA++) {
  141. if (RegEx.match(GA->getName())) {
  142. GVs.insert(&*GA);
  143. match = true;
  144. }
  145. }
  146. if (!match) {
  147. errs() << argv[0] << ": program doesn't contain global named '"
  148. << ExtractRegExpAliases[i] << "'!\n";
  149. return 1;
  150. }
  151. }
  152. // Figure out which globals we should extract.
  153. for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
  154. GlobalValue *GV = M->getNamedGlobal(ExtractGlobals[i]);
  155. if (!GV) {
  156. errs() << argv[0] << ": program doesn't contain global named '"
  157. << ExtractGlobals[i] << "'!\n";
  158. return 1;
  159. }
  160. GVs.insert(GV);
  161. }
  162. // Extract globals via regular expression matching.
  163. for (size_t i = 0, e = ExtractRegExpGlobals.size(); i != e; ++i) {
  164. std::string Error;
  165. Regex RegEx(ExtractRegExpGlobals[i]);
  166. if (!RegEx.isValid(Error)) {
  167. errs() << argv[0] << ": '" << ExtractRegExpGlobals[i] << "' "
  168. "invalid regex: " << Error;
  169. }
  170. bool match = false;
  171. for (auto &GV : M->globals()) {
  172. if (RegEx.match(GV.getName())) {
  173. GVs.insert(&GV);
  174. match = true;
  175. }
  176. }
  177. if (!match) {
  178. errs() << argv[0] << ": program doesn't contain global named '"
  179. << ExtractRegExpGlobals[i] << "'!\n";
  180. return 1;
  181. }
  182. }
  183. // Figure out which functions we should extract.
  184. for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
  185. GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
  186. if (!GV) {
  187. errs() << argv[0] << ": program doesn't contain function named '"
  188. << ExtractFuncs[i] << "'!\n";
  189. return 1;
  190. }
  191. GVs.insert(GV);
  192. }
  193. // Extract functions via regular expression matching.
  194. for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
  195. std::string Error;
  196. StringRef RegExStr = ExtractRegExpFuncs[i];
  197. Regex RegEx(RegExStr);
  198. if (!RegEx.isValid(Error)) {
  199. errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
  200. "invalid regex: " << Error;
  201. }
  202. bool match = false;
  203. for (Module::iterator F = M->begin(), E = M->end(); F != E;
  204. F++) {
  205. if (RegEx.match(F->getName())) {
  206. GVs.insert(&*F);
  207. match = true;
  208. }
  209. }
  210. if (!match) {
  211. errs() << argv[0] << ": program doesn't contain global named '"
  212. << ExtractRegExpFuncs[i] << "'!\n";
  213. return 1;
  214. }
  215. }
  216. // Figure out which BasicBlocks we should extract.
  217. SmallVector<SmallVector<BasicBlock *, 16>, 4> GroupOfBBs;
  218. for (StringRef StrPair : ExtractBlocks) {
  219. auto BBInfo = StrPair.split(':');
  220. // Get the function.
  221. Function *F = M->getFunction(BBInfo.first);
  222. if (!F) {
  223. errs() << argv[0] << ": program doesn't contain a function named '"
  224. << BBInfo.first << "'!\n";
  225. return 1;
  226. }
  227. // Do not materialize this function.
  228. GVs.insert(F);
  229. // Get the basic blocks.
  230. SmallVector<BasicBlock *, 16> BBs;
  231. SmallVector<StringRef, 16> BBNames;
  232. BBInfo.second.split(BBNames, ';', /*MaxSplit=*/-1,
  233. /*KeepEmpty=*/false);
  234. for (StringRef BBName : BBNames) {
  235. auto Res = llvm::find_if(*F, [&](const BasicBlock &BB) {
  236. return BB.getName().equals(BBName);
  237. });
  238. if (Res == F->end()) {
  239. errs() << argv[0] << ": function " << F->getName()
  240. << " doesn't contain a basic block named '" << BBInfo.second
  241. << "'!\n";
  242. return 1;
  243. }
  244. BBs.push_back(&*Res);
  245. }
  246. GroupOfBBs.push_back(BBs);
  247. }
  248. // Use *argv instead of argv[0] to work around a wrong GCC warning.
  249. ExitOnError ExitOnErr(std::string(*argv) + ": error reading input: ");
  250. if (Recursive) {
  251. std::vector<llvm::Function *> Workqueue;
  252. for (GlobalValue *GV : GVs) {
  253. if (auto *F = dyn_cast<Function>(GV)) {
  254. Workqueue.push_back(F);
  255. }
  256. }
  257. while (!Workqueue.empty()) {
  258. Function *F = &*Workqueue.back();
  259. Workqueue.pop_back();
  260. ExitOnErr(F->materialize());
  261. for (auto &BB : *F) {
  262. for (auto &I : BB) {
  263. CallBase *CB = dyn_cast<CallBase>(&I);
  264. if (!CB)
  265. continue;
  266. Function *CF = CB->getCalledFunction();
  267. if (!CF)
  268. continue;
  269. if (CF->isDeclaration() || GVs.count(CF))
  270. continue;
  271. GVs.insert(CF);
  272. Workqueue.push_back(CF);
  273. }
  274. }
  275. }
  276. }
  277. auto Materialize = [&](GlobalValue &GV) { ExitOnErr(GV.materialize()); };
  278. // Materialize requisite global values.
  279. if (!DeleteFn) {
  280. for (size_t i = 0, e = GVs.size(); i != e; ++i)
  281. Materialize(*GVs[i]);
  282. } else {
  283. // Deleting. Materialize every GV that's *not* in GVs.
  284. SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
  285. for (auto &F : *M) {
  286. if (!GVSet.count(&F))
  287. Materialize(F);
  288. }
  289. }
  290. {
  291. std::vector<GlobalValue *> Gvs(GVs.begin(), GVs.end());
  292. legacy::PassManager Extract;
  293. Extract.add(createGVExtractionPass(Gvs, DeleteFn));
  294. Extract.run(*M);
  295. // Now that we have all the GVs we want, mark the module as fully
  296. // materialized.
  297. // FIXME: should the GVExtractionPass handle this?
  298. ExitOnErr(M->materializeAll());
  299. }
  300. // Extract the specified basic blocks from the module and erase the existing
  301. // functions.
  302. if (!ExtractBlocks.empty()) {
  303. legacy::PassManager PM;
  304. PM.add(createBlockExtractorPass(GroupOfBBs, true));
  305. PM.run(*M);
  306. }
  307. // In addition to deleting all other functions, we also want to spiff it
  308. // up a little bit. Do this now.
  309. legacy::PassManager Passes;
  310. if (!DeleteFn)
  311. Passes.add(createGlobalDCEPass()); // Delete unreachable globals
  312. Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
  313. Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
  314. std::error_code EC;
  315. ToolOutputFile Out(OutputFilename, EC, sys::fs::OF_None);
  316. if (EC) {
  317. errs() << EC.message() << '\n';
  318. return 1;
  319. }
  320. if (OutputAssembly)
  321. Passes.add(
  322. createPrintModulePass(Out.os(), "", PreserveAssemblyUseListOrder));
  323. else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
  324. Passes.add(createBitcodeWriterPass(Out.os(), PreserveBitcodeUseListOrder));
  325. Passes.run(*M.get());
  326. // Declare success.
  327. Out.keep();
  328. return 0;
  329. }