问题
I'm trying to build a simple bitcode reader (rather than a dedicated pass, in order to be able to debug more easily) and I have some problems extracting the module. Here's what I have inside main:
LLVMModuleRef module;
char *message = nullptr;
LLVMMemoryBufferRef memoryBuffer;
LLVMCreateMemoryBufferWithContentsOfFile(
argv[1],
&memoryBuffer,
&message);
LLVMParseBitcode2(memoryBuffer,&module);
// for (auto func:module->getFunctionList())
{
/* ... */
}
How can I extract Module from LLVMModuleRef? Surely I'm missing something trivial here.
回答1:
Why are you mixing C and C++ APIs?
If you want to work with llvm::Module
, I assume you are coding in C++, so just use C++ API to parse the bitcode:
#include "llvm/IRReader/IRReader.h"
SMDiagnostic Err;
LLVMContext ctx;
unique_ptr<Module> M = parseIRFile(path, Err, ctx);
if (!M) {
Err.print("Error loading bitcode", errs());
}
回答2:
I'm attaching a complete copy-paste solution here too, hoping it will of some use to someone.
Here is my main.cpp
file:
/**********************/
/* LLVM INCLUDE FILES */
/**********************/
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/IR/LLVMContext.h"
/**************/
/* NAMESPACES */
/**************/
using namespace std;
using namespace llvm;
int main(int argc, char **argv)
{
LLVMContext ctx;
SMDiagnostic Err;
unique_ptr<Module> M = parseIRFile(argv[1],Err,ctx);
if (M)
{
Module *module = M.get();
for (auto
func = module->begin();
func != module->end();
func++)
{
errs() << func->getName() << "\n";
}
}
return 0;
}
And here is my CMakeLists.txt
file:
################
# PROJECT NAME #
################
project(my_bc_reader)
#########################
# CMAKE MINIMUM VERSION #
#########################
cmake_minimum_required(VERSION 3.4.3)
####################
# LLVM INSTALL DIR #
####################
set(LLVM_INSTALL_DIR "~/GIT/llvm-6.0.0/build" CACHE STRING "An LLVM install directory.")
###############
# MODULE PATH #
###############
list(APPEND CMAKE_MODULE_PATH ${LLVM_INSTALL_DIR}/lib/cmake/llvm)
################
# INCLUDE LLVM #
################
include(LLVMConfig)
###########
# ADD SRC #
###########
add_executable(my_bc_reader ~/Downloads/main.cpp)
################
# INCLUDE DIRS #
################
target_include_directories(my_bc_reader PUBLIC ${LLVM_INCLUDE_DIRS})
#############
# LINK LIBS #
#############
target_link_libraries(my_bc_reader PUBLIC LLVMIRReader)
And then simply:
$ ./my_bc_reader ./some_input.bc
来源:https://stackoverflow.com/questions/53361390/extracting-llvmmodule-from-llvmmoduleref