blob: 6c2e364be448c96c948231bd07df54589eda3190 [file] [log] [blame]
Peter Collingbournecb6b9202016-11-29 21:54:33 +00001//===-- 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
16#include "llvm/Bitcode/BitcodeReader.h"
17#include "llvm/Bitcode/BitcodeWriter.h"
18#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/Error.h"
20#include "llvm/Support/FileSystem.h"
21#include "llvm/Support/ToolOutputFile.h"
22
23using namespace llvm;
24
25static cl::opt<bool>
26 BinaryExtract("b", cl::desc("Whether to perform binary extraction"));
27
28static cl::opt<std::string> OutputFilename("o", cl::Required,
29 cl::desc("Output filename"),
30 cl::value_desc("filename"));
31
32static cl::opt<std::string>
33 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
34
35static cl::opt<unsigned> ModuleIndex("n", cl::Required,
36 cl::desc("Index of module to extract"),
37 cl::value_desc("index"));
38
39int main(int argc, char **argv) {
40 cl::ParseCommandLineOptions(argc, argv, "Module extractor");
41
42 ExitOnError ExitOnErr("llvm-modextract: error: ");
43
44 std::unique_ptr<MemoryBuffer> MB =
45 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
46 std::vector<BitcodeModule> Ms = ExitOnErr(getBitcodeModuleList(*MB));
47
48 LLVMContext Context;
49 if (ModuleIndex >= Ms.size()) {
50 errs() << "llvm-modextract: error: module index out of range; bitcode file "
51 "contains "
52 << Ms.size() << " module(s)\n";
53 return 1;
54 }
55
56 std::error_code EC;
57 std::unique_ptr<tool_output_file> Out(
58 new tool_output_file(OutputFilename, EC, sys::fs::F_None));
59 ExitOnErr(errorCodeToError(EC));
60
61 if (BinaryExtract) {
62 SmallVector<char, 0> Header;
63 BitcodeWriter Writer(Header);
64 Out->os() << Header << Ms[ModuleIndex].getBuffer();
Peter Collingbourne85c2184a2016-12-01 23:13:11 +000065 Out->keep();
Peter Collingbournecb6b9202016-11-29 21:54:33 +000066 return 0;
67 }
68
69 std::unique_ptr<Module> M = ExitOnErr(Ms[ModuleIndex].parseModule(Context));
70 WriteBitcodeToFile(M.get(), Out->os());
71
Peter Collingbourne85c2184a2016-12-01 23:13:11 +000072 Out->keep();
Peter Collingbournecb6b9202016-11-29 21:54:33 +000073 return 0;
74}