llvm-extract.cpp 10 KB

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