贡献者: 待更新
一个简陋的生成 LLVM IR 文本的 C++ 程序
std::string generateIR() {
return R"(
define i32 @add(i32 %a, i32 %b) {
entry:
%sum = add i32 %a, %b
ret i32 %sum
}
)";
}
一个直接使用 LLVM IR API 生成 LLVM IR 的 C++ 程序
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Function.h"
// 创建模块和IR构建器
auto context = std::make_unique<llvm::LLVMContext>();
auto module = std::make_unique<llvm::Module>("my_jit", *context);
llvm::IRBuilder<> builder(*context);
// 创建函数
llvm::FunctionType *funcType = llvm::FunctionType::get(
builder.getInt32Ty(),
{builder.getInt32Ty(), builder.getInt32Ty()}, false);
llvm::Function *func = llvm::Function::Create(
funcType, llvm::Function::ExternalLinkage,
"add", module.get());
// 创建基本块和生成代码
llvm::BasicBlock *entry = llvm::BasicBlock::Create(
*context, "entry", func);
builder.SetInsertPoint(entry);
llvm::Value *arg1 = func->getArg(0);
llvm::Value *arg2 = func->arg_begin() + 1;
llvm::Value *sum = builder.CreateAdd(arg1, arg2, "sum");
builder.CreateRet(sum);