0

I am learning about assembly code. Here is a piece of code I do not fully understand

0: move %rdi, %rax
3: jmp  8 <loop + 0x8>
5: sar  %rax
8: test %rax, %rax
b: jg   5 <loop + 0x5>
d: repz retq

So a CPU runs line 0 first, then it jumps to line 8 from line 3. Assuming line b runs, the execution jumps to line 5. My question is how the execution jumps from line 5 to line d? I would assume there is another jmp code after line 5 so that the execution can jump to line d, but I do not see it.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Quan Zhou
  • 307
  • 1
  • 12

1 Answers1

0

Well, I think I understand the execution flow. After line 5, the execution would run 8 and b again before running d. It is essentially a loop, not a conditional flow.

Quan Zhou
  • 307
  • 1
  • 12
  • Yes, most backwards conditional branches are the bottoms of loops. [Why are loops always compiled into "do...while" style (tail jump)?](https://stackoverflow.com/q/47783926) This could possibly be compiler output from `gcc -O1`, although for a really weird / inefficient function that's equivalent to `return x>0 ? 0 : x;`. I guess GCC's optimizer wouldn't look for that simplification because most programmers would avoid writing a C version of that loop in the first place. Ah, but at least `gcc -O2` and higher is able to avoid a `test` in the loop: https://godbolt.org/z/K5r77rK67 – Peter Cordes Dec 10 '21 at 06:14