llvm-modextract.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //===-- llvm-modextract.cpp - LLVM module extractor 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 program is for testing features that rely on multi-module bitcode files.
  11. // It takes a multi-module bitcode file, extracts one of the modules and writes
  12. // it to the output file.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Bitcode/BitcodeReader.h"
  16. #include "llvm/Bitcode/BitcodeWriter.h"
  17. #include "llvm/Support/CommandLine.h"
  18. #include "llvm/Support/Error.h"
  19. #include "llvm/Support/FileSystem.h"
  20. #include "llvm/Support/ToolOutputFile.h"
  21. using namespace llvm;
  22. static cl::opt<bool>
  23. BinaryExtract("b", cl::desc("Whether to perform binary extraction"));
  24. static cl::opt<std::string> OutputFilename("o", cl::Required,
  25. cl::desc("Output filename"),
  26. cl::value_desc("filename"));
  27. static cl::opt<std::string>
  28. InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
  29. static cl::opt<unsigned> ModuleIndex("n", cl::Required,
  30. cl::desc("Index of module to extract"),
  31. cl::value_desc("index"));
  32. int main(int argc, char **argv) {
  33. cl::ParseCommandLineOptions(argc, argv, "Module extractor");
  34. ExitOnError ExitOnErr("llvm-modextract: error: ");
  35. std::unique_ptr<MemoryBuffer> MB =
  36. ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
  37. std::vector<BitcodeModule> Ms = ExitOnErr(getBitcodeModuleList(*MB));
  38. LLVMContext Context;
  39. if (ModuleIndex >= Ms.size()) {
  40. errs() << "llvm-modextract: error: module index out of range; bitcode file "
  41. "contains "
  42. << Ms.size() << " module(s)\n";
  43. return 1;
  44. }
  45. std::error_code EC;
  46. std::unique_ptr<ToolOutputFile> Out(
  47. new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
  48. ExitOnErr(errorCodeToError(EC));
  49. if (BinaryExtract) {
  50. SmallVector<char, 0> Result;
  51. BitcodeWriter Writer(Result);
  52. Result.append(Ms[ModuleIndex].getBuffer().begin(),
  53. Ms[ModuleIndex].getBuffer().end());
  54. Writer.copyStrtab(Ms[ModuleIndex].getStrtab());
  55. Out->os() << Result;
  56. Out->keep();
  57. return 0;
  58. }
  59. std::unique_ptr<Module> M = ExitOnErr(Ms[ModuleIndex].parseModule(Context));
  60. WriteBitcodeToFile(M.get(), Out->os());
  61. Out->keep();
  62. return 0;
  63. }