Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a large function that is only called once be inline? [closed]

A friend wrote a function, about 300 lines of code, and asked me how to turn it to be inline.

I told him it's too big, and will result in instruction enflation. Then I thought, but he calls this function only once. So, there's no downside.

It feels wrong. Is it wrong?

like image 533
Elad Weiss Avatar asked Dec 08 '22 22:12

Elad Weiss


1 Answers

Gcc does this optimization. When a static function is only called once it gets inlined. It doesn't do this with external functions because it can't determine who calls the function.

You can check the assembler by going here:

https://gcc.godbolt.org/

First with an extern function:

#include <stdio.h>

extern int test(int x);

int main() {
  int x = test(10);

  printf("%d\n", x);
}

int test(int x)
{
  volatile int y = x;
  for (int i = 0; i < 10; i++)
    y++;
  for (int i = 0; i < 10; i++)
    y++;

  return y;
}

The assembler output of main() with -O optimization as compiler flag:

main:
        subq    $8, %rsp
        movl    $10, %edi
        call    test(int)
        movl    %eax, %esi
        movl    $.LC0, %edi
        movl    $0, %eax
        call    printf
        movl    $0, %eax
        addq    $8, %rsp
        ret

You can see that test is called and the return value in EAX is stored in $0.

Now make test static and observe that the call to test dissappears and the code is inlined.

like image 100
Serve Laurijssen Avatar answered Feb 15 '23 22:02

Serve Laurijssen