gpt4 book ai didi

c++ - 从 LLVM 添加到 C++ lambda 的映射

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:16:10 27 4
gpt4 key购买 nike

我有一组包装 C++ 方法调用的 lambda,我想用 LLVM 调用它们。我的尝试似乎遗漏了一些东西,即使在声明了类型并将全局映射添加到 lambda 之后,我仍然收到 LLVM 错误。重现我尝试的最小代码是:

#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/Interpreter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/TargetSelect.h"

using namespace llvm;

int main() {

InitializeNativeTarget();

LLVMContext Context;

std::unique_ptr<Module> Owner = make_unique<Module>("SomeModule", Context);
Module *M = Owner.get();

FunctionType *lambdaFT = FunctionType::get(Type::getInt32Ty(Context), false);
Function *lambdaFN = Function::Create(lambdaFT, Function::ExternalLinkage, "lambda", Owner.get());
//this is what the original question had
//auto lambdaBody = []() { return 100; };
//this is an edit after Johannes Schaub's answer
int32_t ( *lambdaBody)() = +[]() { return 100; };

Function *mainF = cast<Function>(M->getOrInsertFunction("main", Type::getInt32Ty(Context), (Type *) 0));

BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", mainF);
IRBuilder<> builder(BB);

CallInst *lambdaRes = builder.CreateCall(lambdaFN, std::vector<Value *>(), "lambdaRetVar");
builder.CreateRet(lambdaRes);

ExecutionEngine *EE = EngineBuilder(std::move(Owner)).create();
EE->addGlobalMapping(lambdaFN, &lambdaBody);

outs() << "We just constructed this LLVM module:\n\n" << *M;
outs() << "\n\nRunning main: ";

std::vector<GenericValue> noargs;
GenericValue gv = EE->runFunction(mainF, noargs);

outs() << "Result: " << gv.IntVal << "\n";
llvm_shutdown();
delete EE;
return 0;
}

这导致输出:

We just constructed this LLVM module:

; ModuleID = 'SomeModule'

declare i32 @lambda()

define i32 @main() {
EntryBlock:
%lambdaRetVar = call i32 @lambda()
ret i32 %lambdaRetVar
}

Running main:
LLVM ERROR: Tried to execute an unknown external function: lambda

我做错了什么?使用 LLVM 3.7.0(标签不存在)

最佳答案

您的 lambda 主体是一个类。您必须传递其函数调用运算符的地址,这可以通过将其转换为函数指针来实现:auto lambdaBody = +[]() { return 100; };并将其作为 void* 传递: EE->addGlobalMapping(lambdaFN, reinterpret_cast<void*>(lambdaBody)); .

关于c++ - 从 LLVM 添加到 C++ lambda 的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33328562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com