llvm-modextract.cpp 2.6 KB

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