0

I have written a simple C++ function which only does a simple modulo operation with number 1022. I notice that there are two instructions in the assembly I don't understand. Here is the screenshot of the code: enter image description here

As I know, eax will hold the return value. But what I don't understand is that after executing line 16, eax and edx will hold the same value, why does line 17 exist, which seems not to be necessary?

Here is the godbolt link. https://godbolt.org/z/o9TTK3hYr

Kidsunbo
  • 1,024
  • 1
  • 11
  • 21
  • 5
    Compile with optimizations enabled: `-O2`. This is a left over from unoptimized code. – Aki Suihkonen Dec 22 '21 at 06:06
  • If you build without optimization enabled the compiler might not generate the best code. :) – Some programmer dude Dec 22 '21 at 06:06
  • Yeah I know if I put -O2 tag, the compiler will generate much clean code and maybe some tricky code. But I am just a little curious why compiler will generate such weird thing in debug mode. – Kidsunbo Dec 22 '21 at 06:09
  • 3
    I can only speculate: the compiler might use a code generator that expects the remainder to be placed on `edx`, just like `idiv` puts it there. `mod` would need `mov edx, eax` and `return result` would need `mov eax, edx`. The instruction level optimizer would probably then form a graph from the emitted instructions and collapse tautologies, remove memory accesses and such. Strength reduction has apparently already been done. – Aki Suihkonen Dec 22 '21 at 06:27
  • 4
    Basically a duplicate of [Why does clang produce inefficient asm with -O0 (for this simple floating point sum)?](https://stackoverflow.com/q/53366394) - you told it not to optimize, so it didn't, and didn't clean up redundant operations in its internal representation of program logic, however they got there. Also, I notice that you didn't even mention *which* compiler in your question, so I assume you aren't interested in the GCC internals of GIMPLE and RTL that lead to this, although if you are you should use Godbolt's GIMPLE dump window to look at the compiler's internal representation. – Peter Cordes Dec 22 '21 at 06:47

0 Answers0