What you practice
Trap and interrupt integration (4.6). Integrate trap and interrupt handling by redirecting the PC to mtvec on a trap and restoring it from mepc on MRET. It is in Trap/IRQ integration top — Part 4 · CSR, Trap & IRQ Interface of the RISC-V RV32I Core Masterclass.
The RV32I core is Verilog you simulate in the browser IDE. Verilator runs the program; the waveform shows PC, the instruction, and the register write.
What you will learn
You will learn to integrate trap and interrupt handling into the RV32I pipeline by redirecting the program counter to the mtvec vector on a trap and restoring it from mepc on MRET.
Learning objectives
- Connect the
rv32i_pcunit to the trap mux logic indesign.sv. - Implement the next-PC selection logic for normal execution, traps, and
MRET. - Verify trap redirection and return behavior using the testbench.
Theory
The program counter (PC) must update based on the current execution context. Normal execution increments the PC by 4 bytes. A trap (ECALL or IRQ) redirects the PC to the base address stored in the mtvec CSR. The MRET instruction restores the PC from the mepc CSR. The next_pc logic selects the correct source using a priority mux.
| Condition | Source | Action |
|---|---|---|
trap_enter | mtvec | Redirect PC to trap vector base. |
mret | mepc | Return from trap to saved PC. |
| Default | pc + 4 | Sequential instruction fetch. |
Practice
- Open RtlStudio and select this chapter.
- Open
student/rtl/design.svin the editor. - Locate the
u_pcinstance and replace the__TODO__[0]placeholders with the correct port connections (clk,rst_n,next_pc,pc). - Replace the entire
__TODO__[0]with the signal name for each port as indicated in the comments. - Open
student/tb/tb_top.svto review the stimulus sequence. - Run Simulation from the sidebar.
- Check the Log panel for
INFO:lines andPASS.
Summary
You implemented the next-PC multiplexer logic to handle trap redirection and return sequences. The design correctly saves the program counter to mepc and jumps to mtvec upon trap entry. It also restores the execution flow from mepc when the mret instruction is executed. This integration ensures proper exception handling within the RV32I pipeline.
© 2026 RtlStudio. Licensed under CC BY-NC-ND 4.0. Commercial use and modifications by third parties are not permitted.
Run it in the Verilog IDE
- Open the RV32I lesson in the IDE. Fetch, decode, and execute are source you can simulate.
- Run Verilator and watch PC, the instruction, and the register write on the waveform.
- Treat a program printout as done only after the ISA step this lesson names matches the wave.
- Change the RTL in the editor, rerun Verilator, and read the waveform again in the same tab.
The lesson is done when the simulation matches Trap and interrupt integration. Change the source, run the Verilog simulator again, and read the waveform without leaving the IDE. Simulation guide · Yosys guide.