Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MSVC use the stack needlessly when returning a small struct in a register?

I compiled the following code on MSVC 2013, x64, Release build with /02:

struct Point
{
    int x;
    int y;
};

Point xUnit()
{
    Point p;
    p.x = 1;
    p.y = 0;
    return p;
}

The generated assembly code for xUnit() is:

mov QWORD PTR p$[rsp], 1
mov rax, QWORD PTR p$[rsp]
ret 0

Why does it write to the stack and then immediately read back into rax to return?

I would have expected:

mov rax, 1
ret 0
like image 983
japreiss Avatar asked Jan 19 '15 18:01

japreiss


1 Answers

X86 version seems to do well (that is generate "mov eax,1").

My guess is that X86 and X64 versions are separate code bases and optimization found in one target is not necessarily present in the other.

like image 52
vektor_proc Avatar answered Nov 03 '22 07:11

vektor_proc