Quantcast
Channel: Understanding assembly instructions for a function summing three ints of an std::array - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Understanding assembly instructions for a function summing three ints of an std::array

$
0
0

I have the following c++ function which simply sums the three elements of the given input array.

#include <array>using namespace std;int square(array<int, 3> ar) {    int res = 0;    for(int idx = 0; idx < ar.size(); idx++){        res += ar[idx];    }    return res;}

This code compiled with Clang (gcc and icc produce the same code) and the compiler flag -O3 produces the following x86-64 assembly

sum(std::array<int, 3ul>):        mov     rax, rdi        shr     rax, 32        add     eax, edi        add     eax, esi        ret

My current interpretation of the assembly is that the following happens:

  1. 64 bits are moved from the 64 bit input register rdi into the 64 bit output register rax. This corresponds to 32 bit ints.
  2. shr shifts the contents of rax by 32 bits thus keeping only the first 32 bit int contained in rdi.
  3. the contents of the 32 bit input register edi are added to the 32 bit output register eax
  4. the contents of the second 32 bit input register esi are added to eax
  5. eax is returned

I am however left with some questions:

  1. Can the computer simply shift between 32 and 64 bit registers as is done in the first two instructions?
  2. Shouldn't the use of shr result in the first int being added two times because the second int is shifted out? (Does this have to do with endianes?)

As an extra note: the compiler produces the same assembly instructions when supplied with a range based for loop.

#include <array>using namespace std;int sum(array<int, 3> ar) {    int res = 0;    for(const auto& in: ar){        res += in;    }    return res;}

You can find the example here: https://godbolt.org/z/s3fera7ca


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images