Search code examples
assemblymipsinstructions

Alternative for sw MIPS instruction


What is an alternative to save a word from register into RAM? For example i can explain lw command as lui, ori. How could be 4 Bytes stored into RAM without using sw?


Solution

  • First of all, lui/ori construct a value in a register from an immediate, without accessing data memory. They're not in any way equivalent to lw. Perhaps you're thinking of li, which is a pseudo-instruction for lui and/or ori. Only load instructions can access memory; immediate ALU instructions take data from the instruction itself but that doesn't really count.


    MIPS provides pairs of instructions for loading/storing the left and right parts of an unaligned word. The stores are SWL (left) and SWR (store word right).

    Their effect depends on the endian mode of your MIPS (it support big and little endian). MARS simulates a MIPS in little-endian mode.

    In little-endian mode, SWL $t1, buf stores the high byte of $t1 to the first byte of buf, for an aligned buf.

    In little-endian mode, on an address that is aligned (like sw requires1), SWR acts like SW, storing all 4 bytes.

    These instructions are interesting because they can modify 1 to 4 bytes in a word. Including 3 bytes, which you can't do with one sb (byte) or sh (half-word).


    http://db.cs.duke.edu/courses/fall02/cps104/homework/lwswlr.html explains how to use the SPARC instructions of the same name. I think MIPS (in big-endian mode) would be the same, and MIPS in little-endian mode like MARS simulates is like that but reversed.

    So in big-endian mode, I think swl is equivalent to sw for aligned addresses, but I haven't tested.


    Footnote 1: MIPS32R6 removed LWL/R, and requires LW to support unaligned store / load. Wikipedia doesn't mention stores for that, only loads.

    See also https://www.linux-mips.org/wiki/Alignment: Linux MIPS has a kernel option to emulate unaligned load/store instead of delivering SIGBUS on unaligned LW or SW.