Extracting LLVM::Module from LLVM::ModuleRef

别说谁变了你拦得住时间么 提交于 2019-12-11 08:32:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!