Tuesday, 15 March 2011

compiler construction - C++ CPU Register Usage -


In C ++, local variables are always allocated on the stack. Stack is a part of the approved memory that can be captured on your application. That memory is kept in your RAM (if the disk is not swapped) Now, do the C ++ compilers always create a codec code that stores local variables on the stack?

For example, the following simple code:

  int foo (int n) {return ++ n; }  

In the MIP codeer code, it may look like this:

  foo: addi $ v0, $ a0, 1 ​​junr $ ra < / Code> 

As you can see, I did not need to use the stack for n. Will the C ++ compiler recognize, and directly use the CPU's registers?

Edit: Wow, thanks for your almost immediate and comprehensive answers! Function body of the foo return ++ n; , not back n ++; Must be . :)

Disclaimer: I do not know MIPS, but I know some X86, and I think The principle should be same ..

In the General Function Call Convention, the compiler will push the value of n to the function on the stack to pass foo . However, there is a fastcoll convention, which you can use to use GCC to provide value through registers. (MSWC also has this option, but I'm not sure what its syntax is.)

test.cpp:

  int Foo1 Int n) {return ++ n; } Int foo2 (int n) __attribute __ ((fastcoll)); Int foo2 (Int N) {Return ++ N; }  

compiled with the above G ++ -O3-fomit-frame-pointer -c test.cpp , give me the foo1 To get:

  mov eax, dword ptr [esp + 0x4] add eX, 0x1 rt  

As you can see, from this stack Values ​​reads in.

and here foo2 :

  lia ax, [ecx + 0x1] ret  

now Makes the value directly from the register.

Of course, if you inline the function, regardless of your calling calling conference, the compiler will do a simple extra work in the body of your large function. But when you can not underscore it, then this is going to happen.

DISCLAIMER 2: I am not saying that you should constantly give a second guess to the compiler. This is probably not practical and necessary in most cases but assume that it does not prepare the correct code.

Edit 1: If you are talking about plain local variables (not about function arguments), yes, compiler will allocate them to registers or piles In the form it sees fit.

Edit 2: It appears that the conference is architecture-specific, and will pass on the first four arguments on the MIG stack, as Richard Pennington has said in his reply. So in your case you do not need to specify additional attributes (which is actually an x86-specific feature.)


No comments:

Post a Comment