Skip to content

[RISCV][MachineScheduler] RISCV backend mis-schedules rdcycle instruction leading to incorrect cycle count #130033

Open
@jupiter-zzp

Description

@jupiter-zzp

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions