Luleå University of Technology
LTU courses · MIPS assembly · C · Rust
D0013E.
Programming a computer from the bottom up. I wrote a recursive string decoder in MIPS assembly, made it run on a pipelined CPU, exposed it to interrupts, built a tiny kernel that switches between three programs on a timer, and finally wrote the same decoder again in C and in Rust to compare what the compilers make of it.
Course labs
decode and a pseudo-random codgen in MIPS assembly. Every local of decode lives on the stack at a fixed offset from the frame pointer, and codgen counts zero bits with the x &= x - 1 trick, since MIPS here has no multiply or divide.SYSCALL. Wrote the exception handler in kernel space: read the cause from CP0, check the service code, write to the I/O port, return with RFE.$gp and $sp in a process control block, and resumes the next one, round robin.no_std bare-metal build for a big-endian MIPS target with its own panic handler and linker script.Interactive demos
The decoder from the labs, ported line for line from my lab4.c. Each call to
decode calls itself on the rest of the words first, so the recursion goes all
the way down before a single letter is written. Then the characters appear from the end
of the string back to the start as the calls return.
- 0
- calls to codgen
- 0
- deepest recursion
- 0 B
- stack at the deepest point
Each call to decode puts a 32-byte frame on the stack: the return address, the old frame pointer, the two pointers and the four locals x, y, m and r.
The lab gives a test seed, 0x66e26625, and the first five values codgen must return for it. Run my codgen on it and compare.
My cycle counts from SyncRim. A 5-stage pipeline should finish about 4 times faster than the single-cycle model the lab compares against, but mine came out at 3.470.
no pipeline
pipelined
timer interrupts
one key press
A model of my lab 3b kernel. Each program thinks it has the CPU to itself and prints its
characters through SYSCALL. Every 1000 cycles or so the timer interrupts, and
the kernel saves the running program and switches to the next one. Cycle counts are
approximate, the switching works the same way as the real kernel.
| PC | $gp | $sp |
|---|
My code from the labs, as handed in.
What I learned
Drawing the stack frame for every function before writing it, with the frame pointer as a fixed anchor, is what made a recursive function in assembly manageable.
Delay slots and load-use bubbles meant my code needed small, careful changes to run at all on the pipelined CPU, and the speed-up depends on how the code is written, not just on the hardware.
For a program not to notice it was paused, the kernel must save every register it could have touched and put each one back exactly. Missing a single register breaks a program that did nothing wrong.
Writing the decoder in assembly, C and Rust showed what a compiler does for me. In Rust I had to use wrapping arithmetic on purpose, because plain addition panics on overflow in a debug build.