addi

addi

RISC-V Assembly Reference

lyszt.net covers addi and other RISC-V instructions in more detail.

Encoding format

R
31–25funct7
24–20rs2
19–15rs1
14–12funct3
11–7rd
6–0opcode
I
31–20imm[11:0]
19–15rs1
14–12funct3
11–7rd
6–0opcode
S
31–25imm[11:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:0]
6–0opcode
B
31–25imm[12,10:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:1,11]
6–0opcode
U
31–12imm[31:12]
11–7rd
6–0opcode
J
31–12imm[20,10:1,11,19:12]
11–7rd
6–0opcode

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