1 //===- llvm-cat.cpp - LLVM module concatenation utility -------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This program is for testing features that rely on multi-module bitcode files.
10 // It takes a list of input modules and uses them to create a multi-module
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/Bitcode/BitcodeReader.h"
17 #include "llvm/Bitcode/BitcodeWriter.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IRReader/IRReader.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
30 #include <system_error>
35 cl::OptionCategory
CatCategory("llvm-cat Options");
38 BinaryCat("b", cl::desc("Whether to perform binary concatenation"),
39 cl::cat(CatCategory
));
41 static cl::opt
<std::string
> OutputFilename("o", cl::Required
,
42 cl::desc("Output filename"),
43 cl::value_desc("filename"),
44 cl::cat(CatCategory
));
46 static cl::list
<std::string
> InputFilenames(cl::Positional
,
47 cl::desc("<input files>"),
48 cl::cat(CatCategory
));
50 int main(int argc
, char **argv
) {
51 cl::HideUnrelatedOptions(CatCategory
);
52 cl::ParseCommandLineOptions(argc
, argv
, "Module concatenation");
54 ExitOnError
ExitOnErr("llvm-cat: ");
57 SmallVector
<char, 0> Buffer
;
58 BitcodeWriter
Writer(Buffer
);
60 for (const auto &InputFilename
: InputFilenames
) {
61 std::unique_ptr
<MemoryBuffer
> MB
= ExitOnErr(
62 errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename
)));
63 std::vector
<BitcodeModule
> Mods
= ExitOnErr(getBitcodeModuleList(*MB
));
64 for (auto &BitcodeMod
: Mods
) {
65 llvm::append_range(Buffer
, BitcodeMod
.getBuffer());
66 Writer
.copyStrtab(BitcodeMod
.getStrtab());
70 // The string table does not own strings added to it, some of which are
71 // owned by the modules; keep them alive until we write the string table.
72 std::vector
<std::unique_ptr
<Module
>> OwnedMods
;
73 for (const auto &InputFilename
: InputFilenames
) {
75 std::unique_ptr
<Module
> M
= parseIRFile(InputFilename
, Err
, Context
);
77 Err
.print(argv
[0], errs());
80 Writer
.writeModule(*M
);
81 OwnedMods
.push_back(std::move(M
));
87 raw_fd_ostream
OS(OutputFilename
, EC
, sys::fs::OpenFlags::OF_None
);
89 errs() << argv
[0] << ": cannot open " << OutputFilename
<< " for writing: "
94 OS
.write(Buffer
.data(), Buffer
.size());