sw

sw

RISC-V Assembly Reference

lyszt.net covers sw 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

sw takes a value from a register and writes it to memory, the opposite of lw. The name stands for store word, and a word is 32 bits. Loads move data from memory into registers so it can be worked on, and stores send results back out. The two instructions make up the load, compute and store cycle of RISC-V, because arithmetic happens only in registers.

The syntax of sw appears below. The operand order differs from most instructions.

sw rs2, offset(rs1)

rs2 holds the value to write. The second operand, offset(rs1), gives the destination address in memory: the address in base register rs1 plus a small constant offset, the same addressing lw uses. The line below writes the value in t1 to the address held in t0.

sw t1, 0(t0)

sw leaves every register unchanged. Its effect falls entirely on memory, while nearly every other instruction writes a register.

The RISC-V manual states that sw, sh and sb store 32-bit, 16-bit and 8-bit values from the low bits of register rs2 to memory. The effective address is register rs1 plus the sign-extended 12-bit offset. Loads and stores at naturally aligned addresses never raise an alignment error, and the manual guarantees they execute atomically, as one indivisible step.

Stores save results into arrays and variables, and a function uses them to place values in its scratch space on the stack. A store overwrites all 4 bytes at the target address. The example writes 99 into a labeled spot in memory, replacing what was there. Memory holds that value until another store overwrites it, unlike a register.

Example

la t0, slot
li t1, 99
sw t1, 0(t0)   # memory at slot now holds 99