Given an instruction, how to get the previous one

Hey altruists,

I have an instruction given and I want to go to the previous instruction of this one. I want to know how do I do that? I came across these functions here: Functions: LLVM/Clang 14.x documentation


I want to know how to use this LLVMGetPreviousInstruction
The previous instruction might be in a different block.

Thanks,
Md

Do you want/need to use the C-API? Also, there is not necessarily one previous instruction, could be multiple, do you want all of them?

Thank you for your reply. I am sorry I didn’t explain my purpose in detail.
Basically what I want to do is add a piece of logging code to my IR file. Suppose, I have the following code,

int test_ifctrl()
{
  unsigned int a = 0;
  
  if (a == 0) {
    a++; // a = 1
  }
  
  return a;
}

Now the IR of this file will look like this,

  ...
  %0 = load i32* %a, align 4
  %cmp = icmp eq i32 %0, 0
  br i1 %cmp, label %if.then, label %if.end

; <label>:3:                                      ; preds = %0
  %1 = load i32* %a, align 4
  %inc = add i32 %1, 1
  store i32 %inc, i32* %a, align 4
  br label %if.end
  ...

I just want to get that condition a==0 and add a log which will be a simple line where this condition will be documented. For now, we can consider adding a print function that will simply print the condition there.

That if.then is triggered by the last instruction of the previous block. And the condition is present to the immediate instruction before that. So, I need to get those two instructions at first and then add a print function in the llvm IR, which will print that condition.

Kindly assist me in completing this task.

I think you’ll have to handle this yourself by checking if the starting instruction is the first in its block. If so, you need to iterate over the predecessor blocks.