llvm-extract.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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/LLVMContext.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/IRReader/IRReader.h"
  22. #include "llvm/PassManager.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/FileSystem.h"
  25. #include "llvm/Support/ManagedStatic.h"
  26. #include "llvm/Support/PrettyStackTrace.h"
  27. #include "llvm/Support/Regex.h"
  28. #include "llvm/Support/Signals.h"
  29. #include "llvm/Support/SourceMgr.h"
  30. #include "llvm/Support/SystemUtils.h"
  31. #include "llvm/Support/ToolOutputFile.h"
  32. #include "llvm/Transforms/IPO.h"
  33. #include <memory>
  34. using namespace llvm;
  35. // InputFilename - The filename to read from.
  36. static cl::opt<std::string>
  37. InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
  38. cl::init("-"), cl::value_desc("filename"));
  39. static cl::opt<std::string>
  40. OutputFilename("o", cl::desc("Specify output filename"),
  41. cl::value_desc("filename"), cl::init("-"));
  42. static cl::opt<bool>
  43. Force("f", cl::desc("Enable binary output on terminals"));
  44. static cl::opt<bool>
  45. DeleteFn("delete", cl::desc("Delete specified Globals from Module"));
  46. // ExtractFuncs - The functions to extract from the module.
  47. static cl::list<std::string>
  48. ExtractFuncs("func", cl::desc("Specify function to extract"),
  49. cl::ZeroOrMore, cl::value_desc("function"));
  50. // ExtractRegExpFuncs - The functions, matched via regular expression, to
  51. // extract from the module.
  52. static cl::list<std::string>
  53. ExtractRegExpFuncs("rfunc", cl::desc("Specify function(s) to extract using a "
  54. "regular expression"),
  55. cl::ZeroOrMore, cl::value_desc("rfunction"));
  56. // ExtractAlias - The alias to extract from the module.
  57. static cl::list<std::string>
  58. ExtractAliases("alias", cl::desc("Specify alias to extract"),
  59. cl::ZeroOrMore, cl::value_desc("alias"));
  60. // ExtractRegExpAliases - The aliases, matched via regular expression, to
  61. // extract from the module.
  62. static cl::list<std::string>
  63. ExtractRegExpAliases("ralias", cl::desc("Specify alias(es) to extract using a "
  64. "regular expression"),
  65. cl::ZeroOrMore, cl::value_desc("ralias"));
  66. // ExtractGlobals - The globals to extract from the module.
  67. static cl::list<std::string>
  68. ExtractGlobals("glob", cl::desc("Specify global to extract"),
  69. cl::ZeroOrMore, cl::value_desc("global"));
  70. // ExtractRegExpGlobals - The globals, matched via regular expression, to
  71. // extract from the module...
  72. static cl::list<std::string>
  73. ExtractRegExpGlobals("rglob", cl::desc("Specify global(s) to extract using a "
  74. "regular expression"),
  75. cl::ZeroOrMore, cl::value_desc("rglobal"));
  76. static cl::opt<bool>
  77. OutputAssembly("S",
  78. cl::desc("Write output as LLVM assembly"), cl::Hidden);
  79. int main(int argc, char **argv) {
  80. // Print a stack trace if we signal out.
  81. sys::PrintStackTraceOnErrorSignal();
  82. PrettyStackTraceProgram X(argc, argv);
  83. LLVMContext &Context = getGlobalContext();
  84. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  85. cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
  86. // Use lazy loading, since we only care about selected global values.
  87. SMDiagnostic Err;
  88. std::unique_ptr<Module> M = getLazyIRFileModule(InputFilename, Err, Context);
  89. if (!M.get()) {
  90. Err.print(argv[0], errs());
  91. return 1;
  92. }
  93. // Use SetVector to avoid duplicates.
  94. SetVector<GlobalValue *> GVs;
  95. // Figure out which aliases we should extract.
  96. for (size_t i = 0, e = ExtractAliases.size(); i != e; ++i) {
  97. GlobalAlias *GA = M->getNamedAlias(ExtractAliases[i]);
  98. if (!GA) {
  99. errs() << argv[0] << ": program doesn't contain alias named '"
  100. << ExtractAliases[i] << "'!\n";
  101. return 1;
  102. }
  103. GVs.insert(GA);
  104. }
  105. // Extract aliases via regular expression matching.
  106. for (size_t i = 0, e = ExtractRegExpAliases.size(); i != e; ++i) {
  107. std::string Error;
  108. Regex RegEx(ExtractRegExpAliases[i]);
  109. if (!RegEx.isValid(Error)) {
  110. errs() << argv[0] << ": '" << ExtractRegExpAliases[i] << "' "
  111. "invalid regex: " << Error;
  112. }
  113. bool match = false;
  114. for (Module::alias_iterator GA = M->alias_begin(), E = M->alias_end();
  115. GA != E; GA++) {
  116. if (RegEx.match(GA->getName())) {
  117. GVs.insert(&*GA);
  118. match = true;
  119. }
  120. }
  121. if (!match) {
  122. errs() << argv[0] << ": program doesn't contain global named '"
  123. << ExtractRegExpAliases[i] << "'!\n";
  124. return 1;
  125. }
  126. }
  127. // Figure out which globals we should extract.
  128. for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
  129. GlobalValue *GV = M->getNamedGlobal(ExtractGlobals[i]);
  130. if (!GV) {
  131. errs() << argv[0] << ": program doesn't contain global named '"
  132. << ExtractGlobals[i] << "'!\n";
  133. return 1;
  134. }
  135. GVs.insert(GV);
  136. }
  137. // Extract globals via regular expression matching.
  138. for (size_t i = 0, e = ExtractRegExpGlobals.size(); i != e; ++i) {
  139. std::string Error;
  140. Regex RegEx(ExtractRegExpGlobals[i]);
  141. if (!RegEx.isValid(Error)) {
  142. errs() << argv[0] << ": '" << ExtractRegExpGlobals[i] << "' "
  143. "invalid regex: " << Error;
  144. }
  145. bool match = false;
  146. for (auto &GV : M->globals()) {
  147. if (RegEx.match(GV.getName())) {
  148. GVs.insert(&GV);
  149. match = true;
  150. }
  151. }
  152. if (!match) {
  153. errs() << argv[0] << ": program doesn't contain global named '"
  154. << ExtractRegExpGlobals[i] << "'!\n";
  155. return 1;
  156. }
  157. }
  158. // Figure out which functions we should extract.
  159. for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
  160. GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
  161. if (!GV) {
  162. errs() << argv[0] << ": program doesn't contain function named '"
  163. << ExtractFuncs[i] << "'!\n";
  164. return 1;
  165. }
  166. GVs.insert(GV);
  167. }
  168. // Extract functions via regular expression matching.
  169. for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
  170. std::string Error;
  171. StringRef RegExStr = ExtractRegExpFuncs[i];
  172. Regex RegEx(RegExStr);
  173. if (!RegEx.isValid(Error)) {
  174. errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
  175. "invalid regex: " << Error;
  176. }
  177. bool match = false;
  178. for (Module::iterator F = M->begin(), E = M->end(); F != E;
  179. F++) {
  180. if (RegEx.match(F->getName())) {
  181. GVs.insert(&*F);
  182. match = true;
  183. }
  184. }
  185. if (!match) {
  186. errs() << argv[0] << ": program doesn't contain global named '"
  187. << ExtractRegExpFuncs[i] << "'!\n";
  188. return 1;
  189. }
  190. }
  191. // Materialize requisite global values.
  192. if (!DeleteFn)
  193. for (size_t i = 0, e = GVs.size(); i != e; ++i) {
  194. GlobalValue *GV = GVs[i];
  195. if (GV->isMaterializable()) {
  196. std::string ErrInfo;
  197. if (GV->Materialize(&ErrInfo)) {
  198. errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
  199. return 1;
  200. }
  201. }
  202. }
  203. else {
  204. // Deleting. Materialize every GV that's *not* in GVs.
  205. SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
  206. for (auto &G : M->globals()) {
  207. if (!GVSet.count(&G) && G.isMaterializable()) {
  208. std::string ErrInfo;
  209. if (G.Materialize(&ErrInfo)) {
  210. errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
  211. return 1;
  212. }
  213. }
  214. }
  215. for (auto &F : *M) {
  216. if (!GVSet.count(&F) && F.isMaterializable()) {
  217. std::string ErrInfo;
  218. if (F.Materialize(&ErrInfo)) {
  219. errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
  220. return 1;
  221. }
  222. }
  223. }
  224. }
  225. // In addition to deleting all other functions, we also want to spiff it
  226. // up a little bit. Do this now.
  227. PassManager Passes;
  228. Passes.add(new DataLayoutPass()); // Use correct DataLayout
  229. std::vector<GlobalValue*> Gvs(GVs.begin(), GVs.end());
  230. Passes.add(createGVExtractionPass(Gvs, DeleteFn));
  231. if (!DeleteFn)
  232. Passes.add(createGlobalDCEPass()); // Delete unreachable globals
  233. Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
  234. Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
  235. std::error_code EC;
  236. tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
  237. if (EC) {
  238. errs() << EC.message() << '\n';
  239. return 1;
  240. }
  241. if (OutputAssembly)
  242. Passes.add(createPrintModulePass(Out.os()));
  243. else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
  244. Passes.add(createBitcodeWriterPass(Out.os()));
  245. Passes.run(*M.get());
  246. // Declare success.
  247. Out.keep();
  248. return 0;
  249. }