assemblymipscpu-registersmips32spim

how to empty all the registers already used, to restart the program in MIPS?


I am new to MIPS and I have an assignment for uni. I have a program(game) in Mips, and I am trying to write a function to restart the game after finishing. I already have my restart function but the problem is that I have to clear all the registers I've used before. does anyone know how I can do for clearing in the fastest and easiest way?(I have 740lines of code,That's why i am asking for easiest and fastest.)


Solution

  • Registers can't be "empty", they always hold some value in their 32 bits. There is no metadata anywhere outside them that indicates which registers have / haven't been written.

    You don't need to do anything special. Non-buggy code in the rest of your program should already assume any register holds garbage (not necessarily zeros) if it hasn't written to it. (Or done something like a system call, which would get the simulator to put a useful value in a register.)

    Think of registers as being like local variables in C. Like int a0, a1, t0, t1; not int a0=0, a1=0, etc. That's why you write loops like for(t0=5 ; t0!=0 ; t0--), where the first access is a write (assigning a 5 to the variable / register). In asm that means li $t0, 5 before the loop. If you didn't, your loop would run some unknown number of iterations, depending on whatever previous code left in $t0. (In C, it's undefined behaviour or at least an unspecified value to read an uninitialized local variable. In practice you get some garbage from somewhere, because C compiles to asm, and in asm for real CPUs, every register and memory location always has a value.)

    (In some senses, global variables are a better analogy since all code uses the same registers for different purposes at different times. But since you don't want to read whatever garbage some previous function left in them, it makes equal sense to consider the separate life-times as separate local variables.)


    If you did want to zero some registers, obviously you just write instructions like

    li  $a0, 0
    li  $t0, 0        # work-around for buggy code that assumes registers are zeroed
    ...
    j  main