Chapter 02 4
Chapter 02 4
66
Note that upper- and lowercase letters differ by exactly 32; this observation can lead to shortcuts in checking or changing
upper- and lowercase. Values not shown include formatting characters. For example, 8 represents a backspace, 9
represents a tab character, and 13 represents a carriage return. Another useful value is 0 for null, the value the
programming language C uses to mark the end of a string.
67
Byte/Halfword/Word Operations
n RISC-V byte/halfword/word load/store
n Load byte/halfword/word: Sign extend to 32 bits in rd
n lb rd, offset(rs1)
n lh rd, offset(rs1)
n lw rd, offset(rs1)
n Load byte/halfword/word unsigned: Zero extend to 32 bits in rd
n lbu rd, offset(rs1)
n lhu rd, offset(rs1)
n lwu rd, offset(rs1)
n Store byte/halfword/word: Store rightmost 8/16/32 bits
n sb rs2, offset(rs1)
n sh rs2, offset(rs1)
n sw rs2, offset(rs1)
68
32-bit Constants
n Most constants are small
n 12-bit immediate is sufficient
n For the occasional 32-bit constant
lui rd, constant
n Copies 20-bit constant to bits [31:12] of rd
n Clears bits [11:0] of rd to 0
lui x19, 976 // 0x003D0
0000 0000 0011 1101 0000 0000 0000 0000
69
Branch Addressing
n Branch instructions specify
n Opcode, two registers, target address
n Most branch targets are near branch
n Forward or backward
n SB format:
imm imm
[10:5] rs2 rs1 funct3 [4:1] opcode
imm[12] imm[11]
n PC-relative addressing
n Target address = PC + immediate × 2
70
Jump Addressing
n Jump and link (jal) target uses 20-bit
immediate for larger range
n UJ format:
imm[10:1] imm[19:12] rd opcode
5 bits 7 bits
imm[20] imm[11]
71
72
73
74
75
76
77
78
Synchronization in RISC-V
n Load reserved: lr.w rd,(rs1)
n Load from address in rs1 to rd
n Place reservation on memory address
n Store conditional: sc.w rd,(rs1),rs2
n Store from rs2 to address in rs1
n Succeeds if location not changed since the lr.w
n Returns 0 in rd
n Fails if location is changed
n Returns non-zero value in rd
79
Synchronization in RISC-V
n Example 1: atomic swap (to test/set lock variable)
again: lr.w x10,(x20)
sc.w x11,(x20),x23 // X11 = status
bne x11,x0,again // branch if store failed
addi x23,x10,0 // X23 = loaded value
n Example 2: lock
addi x12,x0,1 // copy locked value
again: lr.w x10,(x20) // read lock
bne x10,x0,again // check if it is 0 yet
sc.w x11,(x20),x12 // attempt to store
bne x11,x0,again // branch if fails
n Unlock:
sw x0,0(x20) // free lock
80