LLVM IR 三部曲之二 --- 創(chuàng)建IR

前言

上一篇文章我們講了IR的基本語法規(guī)則,這篇文章我們講一下,如何手動去生成IR!
生成IR有以下幾種方式:
1、通過c++直接使用Instructions.h文件中的命令來生成IR
2、使用llvm提供的c接口來生成IR LLVM官方文檔
3、使用IRBuilder來生成IR IRBuilder官方文檔
三種方式,其實(shí)這三種方式,最復(fù)雜的就在于如何創(chuàng)建IR中的命令,我們查閱2、3中的文檔時會發(fā)現(xiàn),LLVM提供分API大部分都是創(chuàng)建Instruction的。
我們分別就1、3方式給出示例(2大家自己看文檔吧),教實(shí)現(xiàn)一個IR生成器。

1、直接使用Instructions.h中的命令

這種方式可以讓我們清楚的看到IR每一步的實(shí)現(xiàn)過程,方便我們學(xué)習(xí)如何生成IR。

1)來實(shí)現(xiàn)一個sum函數(shù):(代碼中我做了詳細(xì)的注解)
//1、創(chuàng)建module
Module *createLLVMModule() {
    LLVMContext context ;
    Module *module = new Module("haoyuTestLLVMIR",context);
    { //設(shè)置datalayout和三元組
        module ->setDataLayout("e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128");
        module ->setTargetTriple("x86_64-apple-macosx10.14.0");
    }
    //2、創(chuàng)建函數(shù)的類型(指定返回值類型、參數(shù)類型及數(shù)量、是否有可變參數(shù))
    SmallVector<Type *, 2>FunctionArgs;
    //各種類型都是通過get方法來構(gòu)造對應(yīng)的實(shí)例
    FunctionArgs.push_back(IntegerType::get(module->getContext(), 32)); //32為整型參數(shù)Tina及到vector數(shù)組中
    FunctionArgs.push_back(IntegerType::get(module->getContext(), 32));

    IntegerType *returnType = IntegerType::get(module->getContext(), 32);//返回值類型
    FunctionType *funcType = FunctionType::get(returnType, FunctionArgs, /*isVarArg*/ false);

    //3、創(chuàng)建一個函數(shù)
    // LinkageType是globalValue類下的一個鏈接類型,所有全局變量、函數(shù)都有一個鏈接類型
    // GlobalValue::ExternalLinkage 表示該函數(shù)可以被其他模塊引用。
    Function *customFunc = Function::Create(funcType, GlobalValue::ExternalLinkage, /* 函數(shù)名 = */"haoyuSum", module);
    customFunc->setCallingConv(CallingConv::C); //CallingConv類是一個枚舉類,定義了所有的函數(shù)調(diào)用公約!文檔上有說明。

    //4、存儲參數(shù)(獲取參數(shù)的引用)
    Function::arg_iterator argsIT = customFunc->arg_begin();
    Value *param1 = argsIT ++;
    param1->setName("a");

    Value *param2 = argsIT ++;
    param2->setName("b");

    //5、創(chuàng)建基本塊(需要制定其所屬的function)
    BasicBlock *entryBlock = BasicBlock::Create(module->getContext(),"entry",customFunc,0);

    //6、添加指令,兩種方式:1、直接使用具體的指令 2、使用IRBuilder(需要重點(diǎn)研究)
    //6.1)直接使用指令方式(便于呈現(xiàn)原始接口)
    //指令:alloca指令使用(操作變量必須用到指針,同OC是一個道理)
    AllocaInst *ptrA = new AllocaInst(/*要創(chuàng)建的內(nèi)存空間的類型*/ IntegerType::get(module->getContext(), 32),/*地址空間*/module->getDataLayout().getAllocaAddrSpace(),/*名稱*/"a.addr",/*BasicBlock*/entryBlock);
    ptrA->setAlignment(Align(4)); //4字節(jié)對齊的32位元素

    AllocaInst *ptrB = new AllocaInst(/*要創(chuàng)建的內(nèi)存空間的類型*/ IntegerType::get(module->getContext(), 32),/*地址空間*/module->getDataLayout().getAllocaAddrSpace(),/*名稱*/"a.addr",/*BasicBlock*/entryBlock);
    ptrB->setAlignment(Align(4));

    //7、使用store命令
    StoreInst *st0 = new StoreInst(param1,ptrA,/* 指定是否是靜態(tài)存儲區(qū) */false,entryBlock);
    st0->setAlignment(Align(4));
    StoreInst *st1 = new StoreInst(param2,ptrB,/* 指定是否是靜態(tài)存儲區(qū) */false,entryBlock);
    st1->setAlignment(Align(4));

    //8、使用load命令
    LoadInst *ld0 = new LoadInst(/*類型*/IntegerType::get(context, 32), ptrA, /*名稱*/"",false, entryBlock);
    ld0->setAlignment(Align(4));
    LoadInst *ld1 = new LoadInst(/*類型*/IntegerType::get(context, 32), ptrB, /*名稱*/"",false, entryBlock);
    ld1->setAlignment(Align(4));

    //9、添加操作
    BinaryOperator *addRes = BinaryOperator::Create(Instruction::Add, ld0, ld1, "add", entryBlock);
    //10、設(shè)置返回值
    ReturnInst::Create(module->getContext(), addRes, entryBlock);
    
    //11、校驗(yàn)生成的IR
    bool Result = llvm::verifyModule(*module);
    if(Result) {
        std::cout << "IR校驗(yàn)通過" << std::endl;
    }
    module->dump();
    return module;
}

dump一下結(jié)果是:

; ModuleID = 'haoyuTestLLVMIR'
source_filename = "haoyuTestLLVMIR"
target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.14.0"

define i32 @haoyuSum(i32 %a, i32 %b) {
entry:
  %a.addr = alloca i32, align 4
  %a.addr1 = alloca i32, align 4
  store i32 %a, i32* %a.addr, align 4
  store i32 %b, i32* %a.addr1, align 4
  %0 = load i32, i32* %a.addr, align 4
  %1 = load i32, i32* %a.addr1, align 4
  %add = add i32 %0, %1
  ret i32 %add
}

2)創(chuàng)建一個while函數(shù)的IR

C++原始代碼如下:

int whileTest() {
    int a = 10,i = 20;
    while (i < 10) {
        i=i+1;
        a=a*2;
    }
    return 0;
}

我們IR生成代碼:(代碼中同樣做了詳細(xì)解釋)

void customWhileIR () {
    LLVMContext context ;
    Module *module = new Module("haoyuWhile",context);
    IRBuilder<> builder(context);
    //創(chuàng)建void函數(shù)
    FunctionType *funcType = FunctionType::get(builder.getVoidTy(),false);
    Function *customFunc = Function::Create(funcType, Function::ExternalLinkage, "whileTest",module);
    //創(chuàng)建最外層函數(shù)的basic
    BasicBlock *entryBlock = BasicBlock::Create(module->getContext(),"entry",customFunc,0);
    //創(chuàng)建br用的basicblock
    BasicBlock *BB1 = BasicBlock::Create(module->getContext(),"label1",customFunc,0);
    BasicBlock *BB2 = BasicBlock::Create(module->getContext(),"label2",customFunc,0);
    BasicBlock *BB3 = BasicBlock::Create(module->getContext(),"label3",customFunc,0);
    //添加Instruction
    // 1) alloca指令
    AllocaInst *ptr1 = new AllocaInst(/*要創(chuàng)建的內(nèi)存空間的類型*/ IntegerType::get(module->getContext(), 32),/*地址空間*/module->getDataLayout().getAllocaAddrSpace(),/*名稱*/"1",/*BasicBlock*/entryBlock);
    AllocaInst *ptr2 = new AllocaInst(builder.getInt32Ty(),module->getDataLayout().getAllocaAddrSpace(),"2",entryBlock);
    AllocaInst *ptr3 = new AllocaInst(builder.getInt32Ty(),module->getDataLayout().getAllocaAddrSpace(),"3",entryBlock);
    // 2) store指令
    auto *IntType = builder.getInt32Ty();
    StoreInst *st1 = new StoreInst(ConstantInt::get(IntType,0),ptr1,entryBlock);
    StoreInst *st2 = new StoreInst(ConstantInt::get(IntType,10),ptr2,entryBlock);
    StoreInst *st3 = new StoreInst(ConstantInt::get(IntType, 20),ptr3,false,entryBlock);
    //3)br指令
    BranchInst::Create(BB1,entryBlock);

    //2.1)設(shè)置BB1
    //load指令
    LoadInst *load1 = new LoadInst(IntegerType::get(context, 32), ptr3, /*名稱*/"",false, BB1);
    //icmp指令
    ICmpInst *icmp = new ICmpInst(*BB1,ICmpInst::ICMP_SLT,load1,ConstantInt::get(IntType,10) );
    //br
    BranchInst::Create(BB2,BB3,icmp,BB1); //!!!:- 如果使用 BranchInst::Create(BB2,BB3,icmp) 這個構(gòu)造函數(shù)會觸發(fā)ICmp的assert

    //2.2)設(shè)置BB2
    //load指令
    LoadInst *load8 = new LoadInst(IntegerType::get(context, 32), ptr3, /*名稱*/"",false, BB2);
    Instruction *add9 = BinaryOperator::Create(Instruction::Add, load8, ConstantInt::get(IntType, 1), "add", BB2);
    StoreInst *stBB2 = new StoreInst(add9,ptr3,BB2);
    LoadInst *load10 = new LoadInst(IntegerType::get(context, 32), ptr2, /*名稱*/"",false, BB2);
    Instruction *mul11 = BinaryOperator::Create(Instruction::Mul, load10, ConstantInt::get(IntType, 2), "MUL", BB2);
    StoreInst *stBB3 = new StoreInst(mul11, ptr2,BB2);
    BranchInst::Create(BB1,entryBlock);
//
//    //2.3)設(shè)置BB3
    ReturnInst::Create(context,ConstantInt::get(IntType, 0),BB3);
    
    module->dump();
    
    
}

最終生產(chǎn)能的IR如下:

; ModuleID = 'haoyuWhile'
source_filename = "haoyuWhile"

define void @whileTest() {
entry:
  %"1" = alloca i32
  %"2" = alloca i32
  %"3" = alloca i32
  store i32 0, i32* %"1"
  store i32 10, i32* %"2"
  store i32 20, i32* %"3"
  br label %label1
  br label %label1

label1:                                           ; preds = %entry, %entry
  %0 = load i32, i32* %"3"
  %1 = icmp slt i32 %0, 10
  br i1 %1, label %label2, label %label3

label2:                                           ; preds = %label1
  %2 = load i32, i32* %"3"
  %add = add i32 %2, 1
  store i32 %add, i32* %"3"
  %3 = load i32, i32* %"2"
  %MUL = mul i32 %3, 2
  store i32 %MUL, i32* %"2"

label3:                                           ; preds = %label1
  ret i32 0
}

上面的結(jié)果是跟我們之前一篇文章中的while生成IR是一樣的,可以參考下。

另外在編寫IR生成代碼時,可能遇到很多命令不知道該如何使用,一個Tip是:去LLVM工程中搜索相關(guān)的示例,看一下官方是如何使用的

2、使用IRBuilder來生成IR

IRBuilder是LLVM中專門提供用來生產(chǎn)Instruction命令的,對比上一種方式,使用IRBuilder會更加方便,它提供了更加友好的封裝,省去了我們直接一個個手動調(diào)用原始命令的繁瑣和枯燥!
下面是一段生成代碼,同樣在代碼中給出詳細(xì)注釋:

void createIRWithIRBuilder() {
    LLVMContext Context;
    Module *mod = new Module("sum.ll", Context);
    
    //1、創(chuàng)建IRBuilder
    IRBuilder<> builder(Context);
    //2、創(chuàng)建main函數(shù)
    FunctionType *ft = FunctionType::get(builder.getInt32Ty(),false);
    Function *mainfunc = Function::Create(ft, Function::ExternalLinkage, "main", mod);
    //到此為止之創(chuàng)建了main函數(shù),但是函數(shù)體內(nèi)的包含的Instruction沒有添加,因此需要添加。
    
    //3、創(chuàng)建基本塊(這個基本塊是空的無內(nèi)容)
    BasicBlock *entry = BasicBlock::Create(Context,"entrypoint",mainfunc);
    
    //4、設(shè)置插入點(diǎn):插入點(diǎn)設(shè)置成相應(yīng)BasicBlock,<#后面用builder創(chuàng)建的指令都會追加到這個BasicBlock里了#>
    //!!!: - 理解:上面的方式是通過直接往BasicBloock中添加Instruction方式來構(gòu)造基本的basicBlock,這里借助IRBuilder方式,往basicBlock中添加命令。
    builder.SetInsertPoint(entry);
    
    //5、添加全局字符串(IR中字符串全部為全局變量,使用數(shù)據(jù)序列來表示,每個元素是一個char類型)
    Value *helloWorld = builder.CreateGlobalStringPtr("hello world!\n");
    //6、創(chuàng)建put函數(shù)
    //1)指定函數(shù)參數(shù)類型,裝在一個數(shù)組中`
    std::vector<Type*> putsargs;
    putsargs.push_back(builder.getInt8Ty()->getPointerTo());
    ArrayRef<Type*>  argsRef(putsargs);
    //2)指定函數(shù)返回值類型
    FunctionType *putsType = FunctionType::get(builder.getInt32Ty(),argsRef,false);
    //3)創(chuàng)建“函數(shù)調(diào)用”,而不是創(chuàng)建函數(shù)
    FunctionCallee putsFunc = mod->getOrInsertFunction("puts", putsType);
    
    //7、調(diào)用函數(shù)(<#理解:通過createXXX創(chuàng)建出來的所有指令都在SetInsertPoint后面#>)
    builder.CreateCall(putsFunc,helloWorld); //這是創(chuàng)建方法的指令
    
    //8、創(chuàng)建返回ret指令
    ConstantInt *zero = ConstantInt::get(IntegerType::getInt32Ty(Context), 0);
    builder.CreateRet(zero);
    
    //9、驗(yàn)證。這一步待定!
    llvm::VerifierAnalysis::Result Res;
    Res.IRBroken = llvm::verifyModule(*mod, &dbgs(), &Res.DebugInfoBroken);

    mod->dump();
 
}

生成IR如下:

; ModuleID = 'sum.ll'
source_filename = "sum.ll"

@0 = private unnamed_addr constant [14 x i8] c"hello world!\0A\00", align 1

define i32 @main() {
entrypoint:
  %0 = call i32 @puts(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @0, i32 0, i32 0))
  ret i32 0
}

declare i32 @puts(i8* %0)

綜上示例,例舉了生成IR的幾種方式,以及一些常用命令的使用,更加復(fù)雜的IR編寫,需要在開發(fā)時查閱上面給出的文檔。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容