How can I get variable name of GEP, and use it to create a if then instruction?

I am a beginner in llvm ir, and now I am doing a llvm transform pass to add some code in C program, but I have some trouble in it.
The source C code is

void foo(int i) {
    a[i] = -1;
}

and its llvm ir is:

define void @foo(i32 noundef %0) #0 {
  %2 = alloca i32, align 4
  store i32 %0, ptr %2, align 4
  
  %3 = load i32, ptr %2, align 4
  %4 = sext i32 %3 to i64
  %5 = getelementptr inbounds [10 x i32], ptr @a, i64 0, i64 %4
  store i32 -1, ptr %5, align 4
  ret void
}

now i want to get the variable i, and build an if then instruction, which looks like:

void foo(int i) {
    a[i] = -1;
    if (i > 5)
        // do some things
}

My question is that how can I get the variable i and build an if statement in llvm ir? now I just know use llvm built-in function SplitBlockAndInsertIfThen to create an if…then… statement, but how can I get i first? Waiting for someone to answer my question, or give an idea, sincerely!

You can’t. Either write your transformation in such a way that it doesn’t need to know about variable names (because they’re meaningless, what matters are data and control flow) or transform the Clang AST.

Oh, thank you for replying me, I output all the operands of GEP and get i, which is sext i32 %3 to i64, is this meaningless?
Am I supposed to trace back to the instruction that allocates memory for the variable i,just like the first ir instruction %2 which uses allocate and give name to %2

Thank a lot, but could you explain more clearly, or provide some learning materials? :sob: :sob: :sob:

The variable i is the first argument of the function foo. In the IR you posted it would translate to %0. If you have access to the llvm function then you can use the getArg function on it.

e.g.

llvm::Function *FuncFoo = ...somehow get the function foo
llvm::Argument *FirstArg = FuncFoo ->getArg(0);

LLVM: llvm::Function Class Reference

On another note i is not sext i32 %3 to i64, i is %0 see this example for the difference: Compiler Explorer

1 Like

Oh, thank you! I understand what you said :+1: