<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/130033>130033</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [RISCV][MachineScheduler] RISCV backend mis-schedules rdcycle instruction leading to incorrect cycle count
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          jupiter-zzp
      </td>
    </tr>
</table>

<pre>
    https://godbolt.org/z/GfPenPv3f
I've found an issue with the RISCV backend in LLVM's instruction scheduling. The rdcycle instruction is being scheduled incorrectly, which results in an incorrect cycle count calculation.

A small case is:
```
#include <stdio.h>

int test(int a[]) {
  unsigned long begin_cycle, end_cycle;
  __asm volatile("rdcycle %0"
                    : "=r"(begin_cycle) \
                    : \
                    : "memory");
  
  int res = 0;
  for (int i = 0; i < 4; i++) {
    res += a[i];
  }

  __asm volatile("rdcycle %0"
                    : "=r"(end_cycle) \
                    : \
                    : "memory");

  printf("cycle = %ld\n", end_cycle - begin_cycle);
  return res;
}
```
Compiled with `-O3`:
```
test:
        addi    sp, sp, -16
        sd      ra, 8(sp)
 sd      s0, 0(sp)
        rdcycle a1
        lw      a2, 0(a0)
 lw      a3, 4(a0)
        lw      a4, 8(a0)
        lw      a0, 12(a0)
 rdcycle a5
        add     a2, a2, a3
        add     a0, a0, a4
 addw    s0, a0, a2
        sub     a1, a5, a1
.Lpcrel_hi0:
 auipc   a0, %pcrel_hi(.L.str)
        addi    a0, a0, %pcrel_lo(.Lpcrel_hi0)
        call    printf
        mv      a0, s0
 ld      ra, 8(sp)
        ld      s0, 0(sp)
        addi    sp, sp, 16
 ret
```
The second `rdcycle` instruction is scheduled and cycle count of the for loop is wrong.
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJy0VtGO4yYU_ZqbFxQLQ5zED3nwJE210qy66lb7OsJAYr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