[LLVMdev] problem with replacing an instruction

Jonathan Roelofs jonathan at codesourcery.com
Thu Jun 18 15:23:08 PDT 2015



On 6/18/15 4:09 PM, Frank Winter wrote:
> Hi Jon! I guess it makes sense what you say about invalidating "I". I
> looked through the LLVM manual but could not find anything about
> 'replacing in place'. Can I still iterate over the instructions in a
> basic block like
>
> for (Instruction& I : BB) {
>      if (isa<BitCastInst>(I)) {
>
> and change 'I' in place? I said from the plus side.. How's the pseudo
> code for that?

Just set the bitcast's 0th operand to the new value after you construct 
it. Something like:

for (Instruction& I : BB) {
   if (BitCastInst *BC = dyn_cast<BitCastInst>(&I)) {
      GetElementPtrInst *GEP = GetElementPtrInst::Create(...);
      GEP->insertBefore(BC);
      BC->setOperand(0, GEP);
   }
}


Jon

>
> Frank
>
>
> On 06/18/2015 05:02 PM, Jonathan Roelofs wrote:
>>
>>
>> On 6/18/15 2:40 PM, Frank Winter wrote:
>>> I am trying to change this
>>>
>>> define void @main(float* noalias %arg0, float* noalias %arg1, float*
>>> noalias %arg2) {
>>> entrypoint:
>>>    %0 = bitcast float* %arg1 to <4 x float>*
>>>
>>> intothis
>>>
>>> define void @main(float* noalias %arg0, float* noalias %arg1, float*
>>> noalias %arg2) {
>>> entrypoint:
>>>    %0 = getelementptr float* %arg1, i64 0
>>>    %1 = bitcast float* %0 to <4 x float>*
>>>
>>>
>>> I must be close but the final instruction replacement results in a
>>> segfault.
>>>
>>>
>>>    for (Instruction& I : BB) {
>> I think the problem might be that the iterator here
>>>      if (isa<BitCastInst>(I)) {
>>>        BitCastInst* BCI = dyn_cast<BitCastInst>(&I);
>>>        for (Use& U : I.operands()) {
>>>            Value* V = U.get();
>>>            if (!dyn_cast<Instruction>(V)) {
>>>              // must be a function's argument
>>>              std::vector<llvm::Value*> vect_1;
>>>              vect_1.push_back(Builder->getInt64(0));
>>>              llvm::GetElementPtrInst* gep1 =
>>> llvm::GetElementPtrInst::Create(V, ArrayRef< Value * >(vect_1) );
>>>              BB.getInstList().insert(&I, gep1);
>>>
>>>              llvm::BitCastInst *bci = new BitCastInst (gep1,
>>> BCI->getDestTy() );
>>>              llvm::ReplaceInstWithInst( &I , bci );
>> is being invalidated here because you're deleting the thing that it
>> points at.
>>
>> You can avoid deleting it if you update the bitcast instruction in
>> place instead. On the plus side, that avoids an unnecessary allocation.
>>
>>
>> Jon
>>
>>>            }
>>>         }
>>>      }
>>>   }
>>>
>>> What am I missing?
>>>
>>> Thanks,
>>> Frank
>>>
>>>
>>>
>>>
>>> _______________________________________________
>>> LLVM Developers mailing list
>>> LLVMdev at cs.uiuc.edu         http://llvm.cs.uiuc.edu
>>> http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev
>>
>
>

-- 
Jon Roelofs
jonathan at codesourcery.com
CodeSourcery / Mentor Embedded



More information about the llvm-dev mailing list