Does a variable in source code match an IR `alloca` instruction?

// here code
int a = 5;
int main() {
    int b = 4;
    return foo(a, b);
}

// here IR
@a = dso_local global i32 5, align 4

; Function Attrs: noinline nounwind optnone sspstrong uwtable
define dso_local i32 @main() #0 {
  %1 = alloca i32, align 4  //  int local_a;
  %2 = alloca i32, align 4  // int b;
  store i32 0, i32* %1, align 4  // local_a = 0;
  store i32 4, i32* %2, align 4  // b = 4;
  %3 = load i32, i32* @a, align 4  // read value of a from memory
  %4 = load i32, i32* %2, align 4  //  read value of b from memory
  %5 = call i32 @foo(i32 %3, i32 %4)  // foo(a, b)
  ret i32 %5  // return foo(a, b)
}

So, in a function, each a used variable match an alloca instruction?

Clang will create an alloca for each local variable, yes. It may also create them for other reasons so not every alloca has a local variable.

Also, optimizations will quickly remove many of these alloca instructions so be careful how you rely on them.

1 Like