llvm-extract.cpp 12 KB

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