windows 下搭建 LLVM3.0 编译构建环境,需要先安装 msys 和 mingw,同时需要去 llvm 官网下载源代码并编译。本文主要记录 LLVM的工程搭建,通过Makefile来组织工程文件。
MakeFile 的编写并不复杂,重点是通过 llvm-config 获取 LLVM 的编译器参数。具体 Makefile 如下:
复制CC = g++
LD = g++
SRCS = $(wildcard *.cpp)
OBJS = $(patsubst %cpp, %o, $(SRCS))
# -I指定头文件目录
INCLUDE = -I/usr/local/include
# -L指定库文件目录,-l指定静态库名字(去掉文件名中的lib前缀和.a后缀)
LIB = -L/usr/local/lib `llvm-config --libs`
LIB += -lws2_32 -lm -lstdc++ -lole32 -lmingwex -lpthread -limagehlp -lgcc -lpsapi -lshell32 -lmoldnamed -lgw32c -lkernel32 -lwinmm -ladvapi32 -luser32
# 开启编译warning和设置优化等级
CFLAGS = -g -Wall -O2 `llvm-config --cflags`
TARGET = jit
.PHONY:all clean
all: $(TARGET)
# 链接时候指定库文件目录及库文件名
$(TARGET): $(OBJS)
$(LD) -g -o $@ $^ $(LIB)
# 编译时候指定头文件目录
%.o:%.cpp
$(CC) -c $^ $(INCLUDE) $(CFLAGS)
clean:
rm -f $(OBJS) $(TARGET)
run:
./$(TARGET).exe
在 Makefile 同级目录下,新建一个 main.cpp 文件,编写一些基本的 LLVM 代码:
复制#include "llvm/Analysis/Verifier.h" //检验模块,校验函数
#include "llvm/Module.h" // 一个源文件的抽象
#include "llvm/Target/TargetData.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/LLVMContext.h" // 公共的数据结构,用来关联模块
#include "llvm/PassManager.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/IRBuilder.h" // 指令生成器
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ManagedStatic.h"
#include <iostream>
using namespace std;
namespace llvm {
class BasicBlock;
class ExecutionEngine;
class Function;
class FunctionPassManager;
class Module;
class PointerType;
class StructType;
class Value;
class LLVMContext;
}
int main(void) {
LLVMContext *llvmContext = new LLVMContext();
Module *module = new Module("ir_global", *llvmContext);
IRBuilder <> irBuilder(*llvmContext);
//int a = 10;
module->getOrInsertGlobal("a", irBuilder.getInt32Ty());
GlobalVariable *a = module->getNamedGlobal("a");
a->setInitializer(irBuilder.getInt32(10));
module->dump(); //print IR
return 0;
}
使用 make命令编译,make run运行,结果如下:
复制; ModuleID = 'ir_global'
@a = global i32 10
至此,windows 下的 LLVM3.0 工程,我们就搭建好了。