Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value for llvm::ConstantInt

Tags:

c++

c

llvm

clang

I'm playing around with LLVM. I thought about changing value of a constant in the intermediate code. However, for the class llvm::ConstantInt, I don't see a setvalue function. Any idea how can I modify value of a constant in the IR code?

like image 252
MetallicPriest Avatar asked Feb 08 '12 15:02

MetallicPriest


1 Answers

ConstantInt is a factory, isn't it? Class has the get method to construct new constant:

     /* ... return a ConstantInt for the given value. */
00069   static Constant *get(Type *Ty, uint64_t V, bool isSigned = false);

So, I think, you can't modify existing ConstantInt. If you want to modify IR, you should try to change pointer to argument (change the IR itself, but not the constant object).

May be you want something like this (please remember, I have zero experience with LLVM; and I'm almost sure example is incorrect).

Instruction *I = /* your argument */;
/* check that instruction is of needed format, e.g: */
if (I->getOpcode() == Instruction::Add) {
   /* read the first operand of instruction */
   Value *oldvalue = I->getOperand(0);

   /* construct new constant; here 0x1234 is used as value */
   Value *newvalue = ConstantInt::get(oldValue->getType(), 0x1234); 

   /* replace operand with new value */
   I->setOperand(0, newvalue);
}

To "modify" a constant alone there is a solution (increment and decrement are illustrated):

 /// AddOne - Add one to a ConstantInt.
 static Constant *AddOne(Constant *C) {
   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
 }

 /// SubOne - Subtract one from a ConstantInt.
 static Constant *SubOne(ConstantInt *C) {
   return ConstantInt::get(C->getContext(), C->getValue()-1);
 }

PS, Constant.h has important comment in the begging about creating and non-deleting of Constants http://llvm.org/docs/doxygen/html/Constant_8h_source.html

00035 /// Note that Constants are immutable (once created they never change) 
00036 /// and are fully shared by structural equivalence.  This means that two 
00037 /// structurally equivalent constants will always have the same address.  
00038 /// Constants are created on demand as needed and never deleted: thus clients 
00039 /// don't have to worry about the lifetime of the objects.
00040 /// @brief LLVM Constant Representation
like image 129
osgx Avatar answered Oct 10 '22 10:10

osgx