1

So I'm doing a little experimenting with the compiler (I'm to that point in my C++ 'career') and I noticed that a call to _rotl gets compiled/assembled directly; by that, I mean that instead of the assembly performing a call, the (albeit only 2) opcodes are seemingly cut/pasted directly where the call is.

What is the reasoning behind this? I believe the term is "inline function" but I could be mistaken.

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145

3 Answers3

6

It is not an inline function, it is an intrinsic function. Designed to take advantage of specific capabilities of the target processor. It gets inlined unconditionally and without otherwise declaring the function inline, typically producing only a single machine code instruction. In the case of _rotl(), using the x86 ROL instruction.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

The inline keyword in C++ suggests the compiler to make certain function (usually short) inline, to reduce overhead caused by call assembly command (processor instruction).

However, it's only a suggestion, so other short functions which aren't explicitly marked inline can be inlined too, and it can also ignore your request for inline'ing, especially if the function is quite large.

The inline'ing operation itself basically copies the body of the function in every place it's used, without the need to call it.

You can always google about it and find some more information.

EDIT: The inlining usually happens only/mostly with the optimizations turned on; try turning them on and off and comparing the disassembly.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
  • 1
    All modern compilers in use today ignore human advice on inlining as it is generally wrong. Unless forced to follow the human input they use their own heuristics instead. – Martin York May 19 '12 at 17:14
  • Inline keyword can be read by humans, though, and can sometimes improve readability of code (i guess). – Bartek Banachewicz May 19 '12 at 19:49
  • I would argue that it decreases readability as arises expectations. You should only use inline where it is required (when it is need by the linker to remove multiple copies). http://stackoverflow.com/q/1759300/14065 – Martin York May 19 '12 at 21:02
1

Inlining is done for efficiency purposes. Firstly, it saves the cost of a call by essentially inserting the function 'in-line'. That is, making a copy of that function and inserting it where the call originally was. Secondly, the code to be executed is closer together which helps caching because of spatial locality.

Functions are typically inlined if they are being called in a loop, where this overhead becomes more significant. You can use the inline keyword to hint to the compiler that you want a function inlined, but there is no obligation for the compiler to do so. You can use compiler specific keywords to force inlines sometimes. For example, __forceinline with VC++.

Mike Kwan
  • 24,123
  • 12
  • 63
  • 96