通过命令行参数获取llvm ir文件时面临问题

Facing issue in taking llvm ir file via command line argument

本文关键字:文件 问题 ir llvm 命令行 参数 获取      更新时间:2023-10-16

我正在编写程序hello.cpp引用LLVM核心库入门手册第3章的示例。

我想将LLVM IR文件input.bc作为命令行参数。但我不知道该怎么做。我正在尝试:g++ hello.cpp -I /tmp/llvm/include/ -std=c++11 input.bc它显示错误:

input.bc: file not recognized: File format not recognized     
collect2: error: ld returned 1 exit status

这是我的源代码hello.cpp

#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
static cl::opt<std::string>
FileName(cl::Positional, cl::desc("Bitcode file"), cl::Required);
int main(int argc, char** argv)
{
cl::ParseCommandLineOptions(argc, argv, "LLVM hello worldn");
LLVMContext context;
ErrorOr<std::unique_ptr<MemoryBuffer>> mb = MemoryBuffer::getFile(FileName);
if (std::error_code ec = mb.getError()) {
errs() << ec.message();
return -1;
}
//  ErrorOr<Module *> m = parseBitcodeFile(mb->get(), context);
//  if (std::error_code ec = m.getError()) {
Expected<std::unique_ptr<Module>> m = parseBitcodeFile(mb->get()->getMemBufferRef(), context);
if (std::error_code ec = errorToErrorCode(m.takeError())) {
errs() << "Error reading bitcode: " << ec.message() << "n";
return -1;
}
for (Module::const_iterator I = (*m)->getFunctionList().begin(),
E = (*m)->getFunctionList().end(); I != E; ++I) {
if (!I->isDeclaration()) {
outs() << I->getName() << " has " << I->size() << " basic blocks.n";
}
}
return 0;
}

终于我得到了答案。我需要在编译时指定库和编译器标志。

编译: g++ -std=c++11 -I/tmp/llvm/include/llvm-config --cxxflagshello.cpp -o hellollvm-config --ldflags --libs --system-libs

要运行: ./hello input.bc