IR code modification/transformation

Hi,

I have a question about the llvm passes.

I'm iterating over a basicblock and I can get an instruction and print it.
Now, I want to iterate over the instruction and be able to modify the values of the instruction.

For example, if my instruction is an add "<result> = add i32 4, %var" I want to transform it in a sub "<result> = sub i32 4, %var".

I looked up on getOperands() and getAllMetadata() and some others methods, but none work.

Can you help me with that please?

Thx

Hi,

So it sounds like you need to replace the ADD instruction with a SUB, right?

Look at replaceAllUsesWith(), that should do what you want.

James

Don't try to modify an add instruction to turn it into a sub instruction.
Just insert a new sub instruction (inserting it before the add),
replace all uses of the add with the sub, then erase the add.
Something like this:

Hi Rinaldini Julien,

I'm iterating over a basicblock and I can get an instruction and print it.
Now, I want to iterate over the instruction and be able to modify the values of the instruction.

For example, if my instruction is an add "<result> = add i32 4, %var" I want to transform it in a sub "<result> = sub i32 4, %var".

create the new sub instruction (insert it before the add), and do:
   AddInst->replaceAllUsesWith(SubInst);
You can then erase the add instruction.

Ciao, Duncan.

Re-adding the list, below message was sent to me alone:

Thx for all answers...

I'll try that. But in a long term what I want to do will be a bit more complicated... It was just an example. In this case, the goal is to replace all add with sub that return the same result, like:

var = var + 2 will become:

y = 1234 - (1234-2)
var = var + y

So I want to read all parameters of the instruction, like the var name, the number, the type,...

Parameters (operands): Add->getOperand(n) (for n = 0, 1, ... ,
Add->getNumOperands()).
A few other "parameters" like nuw/nsw/exact can be accessed as
Add->hasNoUnsignedWrap()/setHasNoUnsignedWrap() and friends.

Var name: Add->getName() / Add->setName().
Can efficiently be transfered to the new instruction with Sub->takeName(Add).
The number is automatically assigned if it doesn't have a name. I'm
not sure if there's an easy way to determine it other than printing it
to a (string)stream and parsing the result.

The type is usually automatically determined from the operands, but
can be accessed as Add->getType(), which is inherited from Value too.

Most of these methods are inherited from the User or Value superclasses.

Ok, thx a lot for all information... This help me a lot!