Skip to content

Conversation

@expertamateur
Copy link

refactor(isa/riscv32): 使用 X-Macro 重构指令译码器,提升代码清晰度

本次提交对 RISC-V 的指令译码器进行了一次深度的架构重构,旨在解决旧有实现的可维护性、扩展性以及代码清晰度问题。

旧代码在 INSTPAT 宏中统一使用了 src1, src2 这样含义模糊的通用变量名。这使得指令的执行逻辑可读性很差,无法一眼看出变量究竟是源寄存器的值,还是用于访存的基地址。除此以外,zimmshamt 等操作数的译码逻辑也和标准的 I 类型指令不同,需要专门实现。而新的架构让添加这些不同的译码逻辑变得前所未有的方便。

为了解决这些问题,新的设计引入了 X-Macro 技术,将译码器改造为一个模块化、声明式的分发系统:

  • 通过 code_type_list X-Macro 在一个统一的位置集中定义所有指令格式,并为操作数赋予了更具描述性的名称,如 vrs1 (value of rs1), vrs2, shamt 等。
  • 利用宏为每种指令格式自动生成类型安全的 struct,其成员名即为这些描述性名称。
  • 将不同操作数的解析逻辑解耦为独立的、可复用的宏模块(如 Dvrs1, DimmI)。

值得注意的是,本次重构利用了在 #131 号 PR 中引入的 BIT_CAST 宏,在不同译码结构体之间进行安全的类型转换。因此,本 PR 应在 #131 号 PR 之后合入

总而言之,这次重构不仅提升了译码器的可扩展性和可维护性,更重要的是,通过用 vrs1 等清晰的命名代替 src1,使得指令的执行逻辑变得更加自明 (self-documenting),极大地提升了代码的可读性,为后续的开发和维护打下了坚实的基础。

…ype safety

This commit refactors the instruction operand decoding logic to support distinct, modular logic for each type of operand (e.g., vrs1, imm, rd).

The previous implementation's monolithic `switch` statement was becoming difficult to maintain. The core issue was that it failed to distinguish between the different decoding procedures required for different operands:
- `vrs1`/`vrs2` need to read from the register file.
- `imm` has multiple complex formats (I, U, S-type) that require different bit manipulations.
- Future operands like `shamt` would involve simple bit extraction.

This new design uses an X-Macro (`INST_TYPE_LIST`) to create a dispatch system. It separates the *definition* of an instruction format (a list of operand types) from the *implementation* of each operand's specific decoding logic (encapsulated in `Dvrs1`, `Dimm`, etc., macros).

This approach makes the decoder significantly more extensible. Adding a new instruction format or even a new type of operand is now a much cleaner and less error-prone process.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant