llvm-extract.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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/ManagedStatic.h"
  25. #include "llvm/Support/PrettyStackTrace.h"
  26. #include "llvm/Support/Regex.h"
  27. #include "llvm/Support/Signals.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. // ExtractFuncs - The functions to extract from the module.
  46. static cl::list<std::string>
  47. ExtractFuncs("func", cl::desc("Specify function to extract"),
  48. cl::ZeroOrMore, cl::value_desc("function"));
  49. // ExtractRegExpFuncs - The functions, matched via regular expression, to
  50. // extract from the module.
  51. static cl::list<std::string>
  52. ExtractRegExpFuncs("rfunc", cl::desc("Specify function(s) to extract using a "
  53. "regular expression"),
  54. cl::ZeroOrMore, cl::value_desc("rfunction"));
  55. // ExtractAlias - The alias to extract from the module.
  56. static cl::list<std::string>
  57. ExtractAliases("alias", cl::desc("Specify alias to extract"),
  58. cl::ZeroOrMore, cl::value_desc("alias"));
  59. // ExtractRegExpAliases - The aliases, matched via regular expression, to
  60. // extract from the module.
  61. static cl::list<std::string>
  62. ExtractRegExpAliases("ralias", cl::desc("Specify alias(es) to extract using a "
  63. "regular expression"),
  64. cl::ZeroOrMore, cl::value_desc("ralias"));
  65. // ExtractGlobals - The globals to extract from the module.
  66. static cl::list<std::string>
  67. ExtractGlobals("glob", cl::desc("Specify global to extract"),
  68. cl::ZeroOrMore, cl::value_desc("global"));
  69. // ExtractRegExpGlobals - The globals, matched via regular expression, to
  70. // extract from the module...
  71. static cl::list<std::string>
  72. ExtractRegExpGlobals("rglob", cl::desc("Specify global(s) to extract using a "
  73. "regular expression"),
  74. cl::ZeroOrMore, cl::value_desc("rglobal"));
  75. static cl::opt<bool>
  76. OutputAssembly("S",
  77. cl::desc("Write output as LLVM assembly"), cl::Hidden);
  78. int main(int argc, char **argv) {
  79. // Print a stack trace if we signal out.
  80. sys::PrintStackTraceOnErrorSignal();
  81. PrettyStackTraceProgram X(argc, argv);
  82. LLVMContext &Context = getGlobalContext();
  83. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  84. cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
  85. // Use lazy loading, since we only care about selected global values.
  86. SMDiagnostic Err;
  87. std::unique_ptr<Module> M;
  88. M.reset(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 (Module::global_iterator GV = M->global_begin(),
  147. E = M->global_end(); GV != E; GV++) {
  148. if (RegEx.match(GV->getName())) {
  149. GVs.insert(&*GV);
  150. match = true;
  151. }
  152. }
  153. if (!match) {
  154. errs() << argv[0] << ": program doesn't contain global named '"
  155. << ExtractRegExpGlobals[i] << "'!\n";
  156. return 1;
  157. }
  158. }
  159. // Figure out which functions we should extract.
  160. for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
  161. GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
  162. if (!GV) {
  163. errs() << argv[0] << ": program doesn't contain function named '"
  164. << ExtractFuncs[i] << "'!\n";
  165. return 1;
  166. }
  167. GVs.insert(GV);
  168. }
  169. // Extract functions via regular expression matching.
  170. for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
  171. std::string Error;
  172. StringRef RegExStr = ExtractRegExpFuncs[i];
  173. Regex RegEx(RegExStr);
  174. if (!RegEx.isValid(Error)) {
  175. errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
  176. "invalid regex: " << Error;
  177. }
  178. bool match = false;
  179. for (Module::iterator F = M->begin(), E = M->end(); F != E;
  180. F++) {
  181. if (RegEx.match(F->getName())) {
  182. GVs.insert(&*F);
  183. match = true;
  184. }
  185. }
  186. if (!match) {
  187. errs() << argv[0] << ": program doesn't contain global named '"
  188. << ExtractRegExpFuncs[i] << "'!\n";
  189. return 1;
  190. }
  191. }
  192. // Materialize requisite global values.
  193. if (!DeleteFn)
  194. for (size_t i = 0, e = GVs.size(); i != e; ++i) {
  195. GlobalValue *GV = GVs[i];
  196. if (GV->isMaterializable()) {
  197. std::string ErrInfo;
  198. if (GV->Materialize(&ErrInfo)) {
  199. errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
  200. return 1;
  201. }
  202. }
  203. }
  204. else {
  205. // Deleting. Materialize every GV that's *not* in GVs.
  206. SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
  207. for (Module::global_iterator I = M->global_begin(), E = M->global_end();
  208. I != E; ++I) {
  209. GlobalVariable *G = I;
  210. if (!GVSet.count(G) && G->isMaterializable()) {
  211. std::string ErrInfo;
  212. if (G->Materialize(&ErrInfo)) {
  213. errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
  214. return 1;
  215. }
  216. }
  217. }
  218. for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
  219. Function *F = I;
  220. if (!GVSet.count(F) && F->isMaterializable()) {
  221. std::string ErrInfo;
  222. if (F->Materialize(&ErrInfo)) {
  223. errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
  224. return 1;
  225. }
  226. }
  227. }
  228. }
  229. // In addition to deleting all other functions, we also want to spiff it
  230. // up a little bit. Do this now.
  231. PassManager Passes;
  232. Passes.add(new DataLayoutPass(M.get())); // Use correct DataLayout
  233. std::vector<GlobalValue*> Gvs(GVs.begin(), GVs.end());
  234. Passes.add(createGVExtractionPass(Gvs, DeleteFn));
  235. if (!DeleteFn)
  236. Passes.add(createGlobalDCEPass()); // Delete unreachable globals
  237. Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
  238. Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
  239. std::string ErrorInfo;
  240. tool_output_file Out(OutputFilename.c_str(), ErrorInfo, sys::fs::F_None);
  241. if (!ErrorInfo.empty()) {
  242. errs() << ErrorInfo << '\n';
  243. return 1;
  244. }
  245. if (OutputAssembly)
  246. Passes.add(createPrintModulePass(Out.os()));
  247. else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
  248. Passes.add(createBitcodeWriterPass(Out.os()));
  249. Passes.run(*M.get());
  250. // Declare success.
  251. Out.keep();
  252. return 0;
  253. }