As title, why does main() have variable 'retval' but not used? And local func test() doesn't have any variable named 'retval'.
"hello.c"
#include <stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
"hello.ll"
@.str = private unnamed_addr constant [13 x i8] c"hello world\0A\00", align 1
; Function Attrs: noinline nounwind optnone
define dso_local i32 @main() #0 {
entry:
%retval = alloca i32, align 4 // why does it have this pattern?
store i32 0, i32* %retval, align 4
%call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([13 x i8], [13 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
declare dso_local i32 @printf(i8*, ...) #1
normal func comparing:
"hello_func.c"
#include <stdio.h>
int test()
{
printf("hello world\n");
return 0;
}
"hello_func.ll"
@.str = private unnamed_addr constant [13 x i8] c"hello world\0A\00", align 1
; Function Attrs: noinline nounwind optnone
define dso_local i32 @test() #0 {
entry: // there is no pattern named retval
%call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([13 x i8], [13 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
declare dso_local i32 @printf(i8*, ...) #1
The reason retval
is unused is described here.
Clang creates this variable to hold the return value of any given non-void function except in special cases. And one of those special cases occurs when the function has a single return statement that returns an llvm Constant.
I guess the reason the variable was still retained for the main function has to do with the fact that main according to the C standard should by default return 0.