1

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
  • What version of clang are you using? – droptop Sep 18 '21 at 09:35
  • `main` is special in C in that the C standard specifies it returns zero if program control flows to its closing `}`. I expect `%retval` is part of how the compiler implements this. – Eric Postpischil Sep 18 '21 at 10:10
  • Does this answer your question? [Why does LLVM allocate a redundant variable?](https://stackoverflow.com/questions/59610063/why-does-llvm-allocate-a-redundant-variable) – arnt Sep 18 '21 at 11:28

1 Answers1

0

The reason retvalis unused is answered 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 specification returns 0 by default.

droptop
  • 1,372
  • 13
  • 24