hello llvm
安装:
win10/11下,使用wsl安装ubuntu。
之后在wsl中安装llvm。针对ubuntu,有专门的源配置网站:https://apt.llvm.org/
使用命令可以安装:bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)"
再使用apt install llvm可以进行安装。
查看llvm版本:llvm-as --version
这台机器上安装了两个版本,14和18,可能14是用apt安装的,18是用bash命令安装的。
编译命令 clang hello.c
clang++ hello.cc
使用了llvm的头文件时,需要设置头文件目录和链接选项,可以使用llvm-config
具体用法:
clang++ hello.cc `llvm-config --cxxflags --ldflags --libs core`
llvm不同版本之间api不完全兼容,因此需要看每个版本的文档,14版本的llvm ir 生成代码可以看:
https://releases.llvm.org/14.0.0/docs/tutorial/MyFirstLanguageFrontend/LangImpl03.html
教程:
https://blog.csdn.net/qq_42570601/article/details/107771289
生成一个简单的比较大小函数并执行的例子:
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/IR/Type.h"
#include <iostream>
#include <stdio.h>
using namespace llvm;
int main() {
static LLVMContext context;
Module *module = new Module("test", context);
// Function max
SmallVector<Type *, 2> functionArgs;
functionArgs.push_back(Type::getInt32Ty(context));
functionArgs.push_back(Type::getInt32Ty(context));
Type *returnType = Type::getInt32Ty(context);
FunctionType *max_type = FunctionType::get(returnType, functionArgs, false);
Function *max_fun = Function::Create(max_type, Function::ExternalLinkage, "max", module);
Function::arg_iterator argsIT = max_fun->arg_begin();
Value *arg_a = argsIT++;
arg_a->setName("a");
Value *arg_b = argsIT++;
arg_b->setName("b");
BasicBlock *entry_max = BasicBlock::Create(context, "entry", max_fun);
IRBuilder<> builder_max(entry_max);
Value *cmp_value = builder_max.CreateICmpSGT(arg_a, arg_b);
BasicBlock *if_then = BasicBlock::Create(context, "if_then", max_fun);
IRBuilder<> builder_then(if_then);
BasicBlock *if_else = BasicBlock::Create(context, "if_else", max_fun);
IRBuilder<> builder_else(if_else);
builder_max.CreateCondBr(cmp_value, if_then, if_else);
builder_then.CreateRet(arg_a);
builder_else.CreateRet(arg_b);
// Function main
FunctionType *main_type = FunctionType::get(Type::getInt32Ty(context), false);
Function *main_fun = Function::Create(main_type, Function::ExternalLinkage, "main", module);
BasicBlock *entry_main = BasicBlock::Create(context, "entry", main_fun);
IRBuilder<> builder_main(entry_main);
Value *a_value = ConstantInt::get(Type::getInt32Ty(context), -10);
Value *b_value = ConstantInt::get(Type::getInt32Ty(context), 20);
std::vector<Value *> putargs;
putargs.push_back(a_value);
putargs.push_back(b_value);
ArrayRef<Value *> argsRef(putargs);
Value *ret = builder_main.CreateCall(max_fun, argsRef);
builder_main.CreateRet(ret);
module->dump();
return 0;
}
浙公网安备 33010602011771号