risc-v

Definition

lui (RISC-V)

Loads a 20-bit immediate value into the upper 20 bits of a register, zeroing the lower 12 bits.

lui a, imm

Equivalent C code:

a = imm << 12

Examples

Example 1

How to realise the following C code in RISC-V, given that there’s no move instruction?

int a = 0xFEDC8765;

Solution: Use the lui instruction:

# s0 = a
lui s0, 0xFEDC8
addi s0, s0, 0x765

Example 2

How to realise the following C code in RISC-V when the lower 12 bits would be interpreted as a negative immediate?

int a = 0xFEDC8EAB;

Solution: Since addi sign-extends its 12-bit immediate, the lower part 0xEAB cannot be added as a positive value. Its highest bit is 1, so it is interpreted as the negative value -341. Therefore, the upper 20 bits loaded by lui must be increased by one in advance.

# s0 = 0xFEDC9000
lui s0, 0xFEDC9
 
# s0 = 0xFEDC9000 + 0xFFFFFEAB
#    = 0xFEDC8EAB
addi s0, s0, -341

Here, lui s0, 0xFEDC9 first loads 0xFEDC9000. Then addi adds -341, whose 12-bit two’s complement representation is 0xEAB. Because addi sign-extends this value before addition, the final result becomes exactly 0xFEDC8EAB.