LLVM:即时编译的简单示例 [英] LLVM: simple example of a just-in-time compilation

查看:100
本文介绍了LLVM:即时编译的简单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习LLVM并尝试编译一个简单的函数:

I'm learning LLVM and trying to compile a simple function:

int sum(int a, int b) {
    return a+b;
};

在飞行中.

所以这是我到目前为止的代码:

So here's the code I have so far:

#include <string>
#include <vector>
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Verifier.h"

using namespace llvm;

static LLVMContext &Context = getGlobalContext();
static std::unique_ptr<Module> MyModule = make_unique<Module>("my compiler", Context);

Function *createFunc(IRBuilder<> &Builder, std::string Name) {
    std::vector<Type*> Integers(2, Builder.getInt32Ty());
    auto *funcType = FunctionType::get(Builder.getInt32Ty(), Integers, false);
    auto *fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, MyModule.get());
    return fooFunc;
};

int main(int argc, char* argv[]) {
    static IRBuilder<> Builder(Context);
    auto *fooFunc = createFunc(Builder, "sum");
    auto *entry = BasicBlock::Create(Context, "entry", fooFunc);
    Builder.SetInsertPoint(entry);

    // Fill the function body
    auto args = fooFunc->arg_begin();
    Value *arg1 = &(*args);
    args = std::next(args);
    Value *arg2 = &(*args);
    auto *sum = Builder.CreateAdd(arg1, arg2, "tmp");
    Builder.CreateRet(sum);
    verifyFunction(*fooFunc);

    // TODO: compile and run it
    MyModule->dump();
    return 0;
}

这会编译,当我运行它时,我会得到预期的输出:

This compiles and when I run it I get the expected output:

; ModuleID = 'my compiler'

define i32 @sum(i32, i32) {
entry:
  %tmp = add i32 %0, %1
  ret i32 %tmp
}

就像在教程中一样.

但是现在我想编译此函数并从C ++运行它.我正在寻找最简单的方法来做这样的事情:

But now I want to compile this function and run it from C++. I'm looking for the easiest way to do something like that:

auto compiledStuff = ...;
auto compiledFn = (int (*)(int, int))compiledStuff;
auto result = compiledFn(3, 8);

我一直在研究官方万花筒教程,但是JIT教程确实很复杂,而且看起来专注于优化和惰性,而我仍然不知道如何轻松地编译模块并从中调用函数.

I've been digging through the official Kaleidoscope tutorial but the JIT tutorial is really complicated and seems to focus on optimizations and laziness while I still can't figure out how to easily compile a module and call a function from it.

有帮助吗?

推荐答案

因此,我深入了KaleidoscopeJIT,并检索了最重要的部分.首先请注意,我正在使用 llvm-4.0 .由于没有意识到4.0和更低版本之间确实不兼容,我遇到了很多问题.

So, I've digged through the KaleidoscopeJIT and retrieved the most important pieces. First of all note that I'm using llvm-4.0. I've had lots of issues by not realizing how really incompatible 4.0 and lower versions are.

该代码可与C ++ 11一起使用.我正在使用带有以下编译标志的 clang ++-4.0 :

The code works with C++11. I'm using clang++-4.0 with following compilation flags:

llvm-config-4.0 --cxxflags --ldflags --system-libs --libs core engine

现在是整个代码:

#include <string>
#include <vector>
#include <iostream>
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Verifier.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/ExecutionEngine/RuntimeDyld.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
#include "llvm/ExecutionEngine/JITSymbol.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Mangler.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/TargetSelect.h"

using namespace llvm;
typedef orc::ObjectLinkingLayer<> ObjLayerT;
typedef orc::IRCompileLayer<ObjLayerT> CompileLayerT;

static LLVMContext Context;
static auto MyModule = make_unique<Module>("my compiler", Context);

Function *createFunc(IRBuilder<> &Builder, std::string Name) {
    std::vector<Type*> Integers(2, Builder.getInt32Ty());
    auto *funcType = FunctionType::get(Builder.getInt32Ty(), Integers, false);
    auto *fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, MyModule.get());
    return fooFunc;
};

void updateBody(Function *fooFunc, IRBuilder<> &Builder) {
    auto *entry = BasicBlock::Create(Context, "entry", fooFunc);
    Builder.SetInsertPoint(entry);
    auto args = fooFunc->arg_begin();
    Value *arg1 = &(*args);
    args = std::next(args);
    Value *arg2 = &(*args);
    auto *sum = Builder.CreateAdd(arg1, arg2, "tmp");
    Builder.CreateRet(sum);
};

int main(int argc, char* argv[]) {
    // Prepare the module
    static IRBuilder<> Builder(Context);
    auto *fooFunc = createFunc(Builder, "sum");
    updateBody(fooFunc, Builder);
    verifyFunction(*fooFunc);

    // Initilaze native target
    InitializeNativeTarget();
    InitializeNativeTargetAsmPrinter();
    InitializeNativeTargetAsmParser();

    // Prepare jit layer
    ObjLayerT ObjectLayer;
    std::unique_ptr<TargetMachine> TM(EngineBuilder().selectTarget());
    DataLayout DL(TM->createDataLayout());
    CompileLayerT CompileLayer(ObjectLayer, orc::SimpleCompiler(*TM));
    auto Resolver = orc::createLambdaResolver(
        [&](const std::string &Name) {
            if (auto Sym = CompileLayer.findSymbol(Name, false))
                return Sym;
            return JITSymbol(nullptr);
        },
        [](const std::string &S) { return nullptr; }
    );

    // Add MyModule to the jit layer
    std::vector<std::unique_ptr<Module>> Modules;
    Modules.push_back(std::move(MyModule));
    CompileLayer.addModuleSet(
        std::move(Modules),
        make_unique<SectionMemoryManager>(),
        std::move(Resolver)
    );

    // Retrieve the foo symbol
    std::string MangledName;
    raw_string_ostream MangledNameStream(MangledName);
    Mangler::getNameWithPrefix(MangledNameStream, "sum", DL);
    auto Sym = CompileLayer.findSymbol(MangledNameStream.str(), true);

    // Cast to function
    auto func = (int(*)(int, int))Sym.getAddress();

    // Try it
    std::cout << func(5, 7) << std::endl;

    return 0;
}

我不确定是否需要所有包含,但无论如何它都像一个魅力.尽管我期待有关如何改进它的任何评论. :)

I'm not sure if all includes are needed but anyway it works like a charm. Although I'm looking forward for any comment on how to improve it. :)

这篇关于LLVM:即时编译的简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆