llvm pass: How to insert a variable using existing variable value

蓝咒 提交于 2019-12-06 11:56:14

问题


I defined int a = 5; in the source code, and I transform the source to LLVM IR:

%a = alloca i32, align 4
store i32 5, i32* %a, align 4

I want to insert int b = a; by writing a pass. I compile int a=5; int b=a into LLVM IR, it load "a" first, then store it. I also checked the doxygen, in which the LoadInst is LoadInst (Value *Ptr, const Twine &NameStr, Instruction *InsertBefore) Still, I don't know how to get the Value of "a".

How to get a variable value?


回答1:


In LLVM IR the sequence

int a = 5;
int b = a;

without any optimization, is translated as

%a = alloca i32, align 4
%b = alloca i32, align 4
store i32 5, i32* %a, align 4
%0 = load i32* %a, align 4
store i32 %0, i32* %b, align 4

This corresponds to two AllocaInsts, two StoreInsts and a LoadInst as follows

warning: untested/uncompiled pseudocode ahead

ConstantInt* const_int_5 = ConstantInt::get(llvmContext, APInt(32, StringRef("5"), 10));

AllocaInst* a_alloc = new AllocaInst(IntegerType::get(llvmContext, 32), "a");
AllocaInst* b_alloc = new AllocaInst(IntegerType::get(llvmContext, 32), "b");
StoreInst* store_5 = new StoreInst(const_int_5, a_alloc, false);
LoadInst* load_from_a = new LoadInst(a_alloc, "", false);
StoreInst* store_b = new StoreInst(load_from_a, b_alloc, false);

You're probably being confused since the instruction is the value in LLVM API thanks to a well-designed inheritance hierarchy.



来源:https://stackoverflow.com/questions/26325698/llvm-pass-how-to-insert-a-variable-using-existing-variable-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!