(已修改)
参考书:《Getting Started with LLVM Core Libraries》
参考链接:https://www.ibm.com/developerworks/opensource/library/os-createcompilerllvm1/index.html
这是一个简单的例子构建IR
一、源代码:
主要参考上面的链接,略有修改,基于LLVM9.0,一段简短的代码创建一段IR。
最后使用dump 查看创建的IR。
Xcode调试:
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/Bitcode/BitcodeReader.h>
#include <llvm/Bitcode/BitcodeWriter.h>
#include <llvm/Support/ToolOutputFile.h>
#include "llvm/IR/IRBuilder.h"
using namespace llvm;
int main() {
LLVMContext Context;
Module *mod = new Module("sum.ll", Context);
IRBuilder<> builder(Context);
FunctionType *ft = FunctionType::get(builder.getInt32Ty(),false);
Function *mainfunc = Function::Create(ft, Function::ExternalLinkage, "main", mod);
BasicBlock *entry = BasicBlock::Create(Context,"entrypoint",mainfunc);
builder.SetInsertPoint(entry);
Value *helloWorld = builder.CreateGlobalStringPtr("hello world!\n");
std::vector<Type*> putsargs;
putsargs.push_back(builder.getInt8Ty()->getPointerTo());
ArrayRef<Type*> argsRef(putsargs);
FunctionType *putsType = FunctionType::get(builder.getInt32Ty(),argsRef,false);
FunctionCallee putsFunc = mod->getOrInsertFunction("puts", putsType);
builder.CreateCall(putsFunc,helloWorld);
ConstantInt *zero = ConstantInt::get(IntegerType::getInt32Ty(Context), 0);
builder.CreateRet(zero);
mod->dump();
return 0;
}
网友评论