【问题标题】:Facing issue in taking llvm ir file via command line argument通过命令行参数获取 llvm ir 文件时面临的问题
【发布时间】:2018-08-12 06:29:32
【问题描述】:

我正在编写程序 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 world\n");
  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++ hello.cpp -I /tmp/llvm/include/ -std=c++11 input.bc 表示你正在尝试编译两个文件hello.cpp和input.bc,你有吗输入.bc? .bc 也是位代码文件在 llvm 位代码的上下文中,而 g++ 本身并不支持它,可能再次检查它是不是“clang”并且我猜有些标志丢失了。
  • @ChiragPatel,是的,我有 input.bc 通过 clang 转换 input.c 然后 llvm-as 。那么你能告诉我编译 hello.cpp 的方法是什么,它将 inpput.bc 作为命令行参数?
  • 可能在阅读您的 c++ 代码后尝试,g++ hello.cpp -o hello 然后 ./hello input.bc.
  • @ChiragPatel,我试过了:g++ main.cpp -I /tmp/llvm/include/ -std=c++11 但它显示了同样的错误:collect2: error: ld returned 1 exit status
  • main.cpp???是新文件吗?

标签: c++ c++11 llvm llvm-ir


【解决方案1】:

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

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

运行:./hello input.bc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    相关资源
    最近更新 更多