Clang generates local store in LLVM IR -


i'm learning llvm ir through clang , found out c function like:

int inc(int x) {   return x+1; } 

generates ir (optimizations turned off):

define i32 @inc(i32 %x) #0 { entry:   %x.addr = alloca i32, align 4   store i32 %x, i32* %x.addr, align 4   %0 = load i32, i32* %x.addr, align 4   %add = add nsw i32 %0, 1   ret i32 %add } 

my question know why allocates in first place local (x.addr) store, load it.

because unoptimized code. clang (the frontend) doesn't spend (almost any?) time figuring out how make code emits optimal. leaves backend optimizations (llvm). local variables "on stack" in unoptimized mode, means alloca. means x has addressable location, may or may not used later. without optimizations compiler not know whether it's going used, conservatively generates addresable location anyway.

int inc(int x) {   x = x + 1;   int* px = &x;   return x; } 

now clang emits:

define i32 @inc(i32 %x) #0 { entry:   %x.addr = alloca i32, align 4   %px = alloca i32*, align 8   store i32 %x, i32* %x.addr, align 4   %0 = load i32, i32* %x.addr, align 4   %add = add nsw i32 %0, 1   store i32 %add, i32* %x.addr, align 4   store i32* %x.addr, i32** %px, align 8   %1 = load i32, i32* %x.addr, align 4   ret i32 %1 } 

see address %x.addr being used pointer now?

of course if run through optimizer get:

define i32 @inc(i32 %x) #0 { entry:   %add = add nsw i32 %x, 1   ret i32 %add } 

which more in line you'd expect compiler.


Comments