addi
lyszt.net covers addi and other RISC-V instructions in more detail.
Encoding format
Description
addi adds a constant to a register. The name stands for add immediate. An immediate is a constant value written into the instruction itself rather than read from a register. Use it when one of the numbers is fixed when you write the program, such as adding 1 to a counter.
The form of addi is shown below. It reads the value in source register rs1, adds the constant imm, and writes the result to destination register rd.
addi rd, rs1, imm
The next line reads t0, adds one, and writes the result back, so t0 = t0 + 1.
addi t0, t0, 1
The constant occupies 12 bits and is signed, giving a range of -2048 to 2047. The assembler rejects larger values. For a bigger constant, load it into a register with li first. A negative constant makes addi subtract as well, which is why RISC-V has no separate subtract-immediate instruction. The next line counts down.
addi t0, t0, -1
The RISC-V manual calls the constant a sign-extended 12-bit immediate. It states that arithmetic overflow is ignored, so the result keeps only its low XLEN bits, where XLEN is the register width in bits, 32 here. When the sign of the constant is known, one branch after the addition checks for signed overflow. The two lines below handle the common case of adding a positive constant.
addi t0, t1, +imm blt t0, t1, overflow
Programs use addi for counters, for moving a pointer to the next item and for reserving space on the stack. The example adds 1 to advance a counter and adds -16 to reserve 16 bytes of working memory, which is how a function that needs working space usually begins.
Example
addi t0, t0, 1 # t0++ addi sp, sp, -16 # reserve 16 bytes of stack
References
- [1]RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture. Version 20260120. Section 2.4.1, Integer Register-Immediate Instructions, pages 28 to 29.
- [2]RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture. Version 20260120. Section 2.4, Integer Computational Instructions, page 27.
