02/25/2021 » White paper on adding custom RISC-V Instructions to QEMU by Hugh O’Keeffe

White Paper on adding Custom RISC-V
Instructions to QEMU

February 22nd, 2021 – Limerick, Ireland.

QEMU is a “Quick EMUlator” providing software-based emulation of core architectures including RISC-V and Arm. QEMU supports standard ISAs (e.g., RV32I, RV64I) and can be extended to include custom instructions. This white paper shows how to add a unique custom instruction to QEMU and debug it in Ashling’s RiscFree™ IDE .

Requirements

Adding a custom instruction requires modifying QEMU source and rebuilding. You’ll need familiarity with:

  • RISC-V instruction set and architecture
  • C programming language and build tools

Overview

The process on Windows™ with MSYS2 involves :

  1. Install MSYS2 and required QEMU packages
  2. Download QEMU v5.0.0 sources
  3. Build baseline QEMU (RV32I target)
  4. Modify QEMU source to add custom instruction
  5. Rebuild QEMU and integrate with RiscFree™
  6. Build and debug an application using the new instruction in RiscFree™

Example Custom Instruction: BITCNT

The custom R-type instruction BITCNT counts total set bits in two registers :

BITCNT  dest-t0, src1-t1, src2-t2

// Example:
A2 = 0x00003000
A3 = 0xF000000F
BITCNT A1, A2, A3
// A1 = 0x0000000A (10 bits set)

Modifying QEMU

Add encoding in insn32.decode :

BITCNT   0100000 ..... ..... 111 ..... 0110011 @r

Implement translator in trans_rvi.inc.c :

static bool trans_bitcnt(DisasContext *ctx, arg_bitcnt *a) {
    // Count bits in rs1 + rs2 and store in rd
    ...
    return true;
}

Rebuild QEMU and replace qemu-system-riscv32.exe in the RiscFree installation .

Debugging in RiscFree™

Use inline assembly to test the instruction :

asm(".word 0x40D675B3"); // bitcnt a1, a2, a3

Set breakpoints, step execution, and observe register updates (e.g., a1 = 0x0A after BITCNT executes). Figures in the paper show RiscFree™ capturing the instruction execution .

Conclusion

QEMU can be extended to support custom RISC-V instructions, allowing validation and debug before silicon implementation. Ashling’s RiscFree™ IDE integrates seamlessly, enabling developers to simulate and debug custom ISA extensions .

More Information

For details, contact Hugh O’Keeffe (hugh.okeeffe@ashling.com) or visit Ashling’s services pages: Compilers, IDEs, Simulators | Tools-as-a-Service™ (TaaS) .

All trademarks, logos and brand names are the property of their respective owners.