Generating IR from clang using classes

时间秒杀一切 提交于 2021-01-29 10:00:39

问题


I am trying to generate LLVM IR using clang classes I am pretty new at this and so far I've used this code as a reference which is in turn copied from Method to create LLVM IR

The above link is pretty old and I did change my code here and there according to the new signatures

#include <clang/CodeGen/CodeGenAction.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/CompilerInvocation.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <llvm/ADT/IntrusiveRefCntPtr.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>



using namespace std;
using namespace clang;

clang::CodeGenAction * getAction(void)
{

    llvm::LLVMContext *llvmcx;
    static llvm::LLVMContext MyGlobalContext;
    llvmcx = &MyGlobalContext;
    // Path to the C file
    string inputPath = "test.c";


    // Arguments to pass to the clang frontend
    vector<const char *> args;
    args.push_back(inputPath.c_str());

    // The compiler invocation needs a DiagnosticsEngine so it can report problems
    llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> opt(new clang::DiagnosticOptions());
    clang::DiagnosticConsumer *client(new DiagnosticConsumer());
    llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID(new clang::DiagnosticIDs());
    clang::DiagnosticsEngine Diags(DiagID, opt, client);

    // Create the compiler invocation
    shared_ptr<clang::CompilerInvocation> CI(new clang::CompilerInvocation());
    clang::CompilerInvocation::CreateFromArgs(*CI, &args[0], &args[0] + args.size(),Diags);

    // Create the compiler instance
    clang::CompilerInstance Clang;
    Clang.setInvocation(CI);

    // Get ready to report problems
    Clang.createDiagnostics(&Diags.getDiagnosticOptions());
    if (!Clang.hasDiagnostics())
          return NULL;
    // Create an action and make the compiler instance carry it out
    clang::CodeGenAction *Act = new clang::EmitLLVMOnlyAction(llvmcx);
    if (!Clang.ExecuteAction(*Act))
        return NULL;

    return Act;
}

int main(void)
{
    clang::CodeGenAction* Act = getAction();

    Grab the module built by the EmitLLVMOnlyAction
    auto module = Act->takeModule();

    // Print all functions in the module
    for (llvm::Module::FunctionListType::iterator i = module->getFunctionList().begin(); i != module->getFunctionList().end(); ++i)
        printf("%s\n", i->getName().str().c_str());

    return 0;
}

But getAction() returns NULL. Any idea as to where I am going wrong?

来源:https://stackoverflow.com/questions/60316529/generating-ir-from-clang-using-classes

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