Function inlining

Function inlining is performed when a request has been made to the compiler to perform optimization on the code . The compiler will try (its important to remember that ,it is a request made to the compiler, not an order) and insert the complete body of the function in every place in the code where that function is used so as to eliminate the time overhead when the function is called . We could get an idea of function inlining by peeping into the assembly code generated by the compiler .

We do this with the help of a small program :

int sqr(int x)
return x*x;

printf("%d\n", sqr(10));

We have the program written in a file  ‘pgm.c’

Do :

$: cc -S pgm.c

We could now view the assembly code generated by the compiler


$: less pgm.s

I found out the following lines in the ‘main’ function of ‘ pgm.s ‘

movl    $10, (%esp)
call    sqr

You would have the idea cleared up

The constant ’10 ‘  is stored in the stack , and the call to the function ‘sqr ‘ is made . The result of squaring up 10 is performed in the function ‘sqr’ . This obviously would create overheads for invoking the function .

Now consider the case where you have requested the compiler to perform all optimizations on your code .

$ :cc -S -O3 pgm.c

Now have a look into your assembly code .

$ :less pgm.s

Now just have a look into the your ‘main’ function and find out what you see where you had seen the previous two lines that i did mention above .

You would just find a singe line corresponding to those two lines which you had found in your assembly code that was not optimized .

This is what i found ,

movl    $100, 4(%esp)

The final value that you obtain after finding the square of 10 ( i.e 100 ) is has been moved into the stack , but where is the call to the function ‘sqr’ ?

You have just seen ‘ function inlining ‘. The function body had been inserted at the point where the function was used and the value ‘100 ‘ calculated at compile time instead of performing the calculation at run time .This saves a lot of time that would have been required to calculate the value of ‘100’ by making a call to the function at run time .Performing function inlining avoids this .


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s