Registers

Registers

Registers: the CPU's hands

First, what is a bit? A bit is a single 0 or 1, the smallest unit of information a computer can store. Put 32 of them together and you have a 32-bit number, which can count from 0 up to about 4 billion. Every register and every memory slot in RISC-V holds one 32-bit number.

A register is a small storage slot inside the processor that holds one 32-bit number. RISC-V provides 32 registers. Because they sit in the processor core, registers are much faster to use than main memory, by orders of magnitude. A few of them will cover most of what you write: t0 through t2 (temporary values), a0 through a2 (arguments and results), zero (always 0), sp (stack pointer), and ra (return address).

ℹ
The Simulator tab shows each register as its value changes while the program runs. Watching that view is the quickest way to get a feel for how the registers behave.
Your first program: print 42
# Print the number 42, then exit.
# a7 picks the service and a0 carries the value.
li a7, 1 # service 1 = print integer
li a0, 42 # the value to print
ecall # do it
li a7, 10 # service 10 = exit
ecall

stands for load immediate, and it places a constant into a register. selects service 1, which prints an integer. puts the number to print into a0. passes control to the system, which prints the value in a0. Then selects the exit service, and ends the program. Press Run, then change 42 and run the program again.

Program execution
0x400000li a7, 1
0x400004li a0, 42
0x400008ecall
0x40000cli a7, 10
0x400010ecall
a71
a0—
output—
pc0x400000

Setting a7 to 1 makes the next ecall print a number.

The figure below follows the five lines above as the simulator executes them. Each line carries the address it occupies once the program is loaded, and the addresses are four bytes apart because every RISC-V instruction is four bytes wide. The box labeled pc, short for program counter, holds the address of the line currently highlighted. That number is all the processor knows about its position in the program: it fetches the instruction at the address in the program counter, executes it, then adds four to the program counter to reach the next instruction. A register receives its value when the on its line executes, and the output appears only when the first runs.