Finding nearest store to a variable

Hey guys ,

I have question : How to find nearest store to a alloca variable in LLVM ?

I tried to write a LLVM pass for the following C++ program -

#include <stdio.h>
int main()
{
int a ;
int datasize;

datasize = 5;
datasize=10; // most recent definition for the (useless) “datasize=datasize” below.

datasize = datasize;

// Just for verification of result. should be 10.
printf(“value=%d”,a+datasize);
return a+datasize;

}

//==================

I wrote the following LLVM Function Pass for it ( Have not included unecessary details )

for(Function::iterator BB = F.begin() ; BB != F.end() ; ++BB)
{
for(BasicBlock::iterator I = BB->begin(); I != BB->end() ; ++I)
{
if(StoreInst* st = dyn_cast(I))
{
User* user1 = st;
std::string str = user1 ->getOperand(1)->getName();

// it is a store to datasize
if(str=="datasize)
{
Use& use1 = user1->getOperandUse(0) ;

// trying to find nearest assignment/store for this.
Value* v = use1 .get();
errs() << *v << “\n” ;

// this means that it was datasize = datasize
// since it is translated to the following in IR -

// %0 = load i32, i32* %datasize, align 4
// store i32 %0, i32* %datasize, align 4

if(LoadInst* loadInst = dyn_cast(v))
{
User* user2= loadInst ;
Use& use2= user21->getOperandUse(0);

// find nearest defiinion/store
Value* v2 = use2.get();

errs() << “found nearest definiton” << *v2 << “\n” ;
}
}

}

}

}

//===========================================

The result I get -

i32 5 ----------------> ignore,not useful
i32 10 ------------------> ignore,not useful
%0 = load i32, i32* %datasize, align 4
found nearest %datasize = alloca i32, align 4

My Issue : The nearest “def” found for the usage of datasize=datasize is an

alloca instruction while I wanted to find the IR -
store i32 10, i32* %datasize, align 4

(In C++ - "datasize=10" instruction. as seen below).

// … c++ code

datasize = 5;
datasize=10; // most recent definition for the (useless) “datasize=datasize” below.

datasize = datasize;

// … C++ code

Thank you for keeping patience and reading uptil here.
My Question : Can anyone explain how I can find the nearest store to a variable in LLVM IR ?

Thanks,

Malhar

Don’t. You are trying to solve a problem that is the main reason that SSA form was created, without using SSA form. If you really insist on duplicating all of the analysis that LLVM can do for you in constructing SSA form, I suggest that you start reading about dominance frontier construction and go from there.

David