To add a new instruction to RISCV, we must add it to our compiler (riscv-gnu-toolchain for now) and whatever simulator/emulator we're using (spike for now).
First we follow the steps from Spike's setup page:
- Describe the instruction's functional behavior in the package
riscv-isa-sim, inriscv-isa-sim/riscv/insns/.h.
Examine other instructions in that directory as a starting point. - Add the opcode and opcode mask to
riscv-opcodes/opcodes. You can pick any open opcode, and there are several formats to choose from. Pick the type that fits your needs (source/destination registers, use of an immediate, etc.).riscv-opcodes/opcodesshows how two instructions,tagenforceandsettagwere inserted. - Run
make installinriscv-opcodes. - This should have installed the opcode/masks necessary for your new instructions to all the proper header files.
At the very least, check that a match and mask for your instruction have been generated and placed inriscv-isa-sim/riscv/encoding.h,riscv-gnu-toolchain/binutils/include/opcode/riscv-opc.h, andriscv-gnu-toolchain/gcc/gcc/config/riscv/riscv-opc.h.
If your instruction interacts with thespikeproxy kernel, also checkriscv-pk/pk/encoding.h. - Finally, add structs for this instruction in the
riscv_builtin_opcodesarray inriscv-gnu-toolchain/binutils/opcodes/riscv-opc.h.
The easiest way to do this is to find an existing instruction with the same instruction type as yours, and copy the formatting, replacingMATCH's andMASK's appropriately. As far as the strange letters signifying arguments go, this is currently how I understand them:d= usesrds= usesrs1t= usesrs2j= usesimmediate12-i-typeinstructions (also ‘o’?)u= usesimmediate20-u-typeinstructions (shifted down)a= usesimmediate20-uj-typeinstructionsp= usesimmediate12-sb-typeinstructionsq= usesimmediate12-s-typeinstructionsd= usesimmediate20-u-typeinstructions (unshifted)z= uses zero register (always loads 0, stores do nothing)
Now, we need to add support for decoding this instruction to Spike:
6. In riscv-isa-sim/spike_main/disasm.cc, add a DEFINE_$TYPE call for your instruction, replacing $ with the appropriate instruction format (this should match the instruction format you used in riscv-opcodes/opcodes).
For uj-type instructions, you'll have to add the instruction manually, as there is no DEFINE macro available.
7. Give it a try! Try compiling a small program and running it in spike with your new instruction
(declared via __asm__ or __asm__ volatile).