Path: blob/main/contrib/llvm-project/llvm/tools/llvm-modextract/llvm-modextract.cpp
35258 views
//===-- llvm-modextract.cpp - LLVM module extractor utility ---------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This program is for testing features that rely on multi-module bitcode files.9// It takes a multi-module bitcode file, extracts one of the modules and writes10// it to the output file.11//12//===----------------------------------------------------------------------===//1314#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/MemoryBuffer.h"20#include "llvm/Support/ToolOutputFile.h"21#include "llvm/Support/WithColor.h"2223using namespace llvm;2425static cl::OptionCategory ModextractCategory("Modextract Options");2627static cl::opt<bool>28BinaryExtract("b", cl::desc("Whether to perform binary extraction"),29cl::cat(ModextractCategory));3031static cl::opt<std::string> OutputFilename("o", cl::Required,32cl::desc("Output filename"),33cl::value_desc("filename"),34cl::cat(ModextractCategory));3536static cl::opt<std::string> InputFilename(cl::Positional,37cl::desc("<input bitcode>"),38cl::init("-"),39cl::cat(ModextractCategory));4041static cl::opt<unsigned> ModuleIndex("n", cl::Required,42cl::desc("Index of module to extract"),43cl::value_desc("index"),44cl::cat(ModextractCategory));4546int main(int argc, char **argv) {47cl::HideUnrelatedOptions({&ModextractCategory, &getColorCategory()});48cl::ParseCommandLineOptions(argc, argv, "Module extractor");4950ExitOnError ExitOnErr("llvm-modextract: error: ");5152std::unique_ptr<MemoryBuffer> MB =53ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));54std::vector<BitcodeModule> Ms = ExitOnErr(getBitcodeModuleList(*MB));5556LLVMContext Context;57if (ModuleIndex >= Ms.size()) {58errs() << "llvm-modextract: error: module index out of range; bitcode file "59"contains "60<< Ms.size() << " module(s)\n";61return 1;62}6364std::error_code EC;65std::unique_ptr<ToolOutputFile> Out(66new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));67ExitOnErr(errorCodeToError(EC));6869if (BinaryExtract) {70SmallVector<char, 0> Result;71BitcodeWriter Writer(Result);72Result.append(Ms[ModuleIndex].getBuffer().begin(),73Ms[ModuleIndex].getBuffer().end());74Writer.copyStrtab(Ms[ModuleIndex].getStrtab());75Out->os() << Result;76Out->keep();77return 0;78}7980std::unique_ptr<Module> M = ExitOnErr(Ms[ModuleIndex].parseModule(Context));81WriteBitcodeToFile(*M, Out->os());8283Out->keep();84return 0;85}868788