What is the "relationship" between addi and subi?

Niklas R. picture Niklas R. · Aug 16, 2012 · Viewed 18.1k times · Source

I'm supposed to answer this question. After some research it says that add and sub have the same opcode and differ only in the functional field. Is this the answer or something else?

Update

It's available in the Nios II CPU manual:

subi
subtract immediate
Operation: rB ← rA – σ (IMMED)
Assembler Syntax: subi rB, rA, IMMED
Example: subi r8, r8, 4
Description: Sign-extends the immediate value IMMED to 32 bits, subtracts it from the value of rA and then
            stores the result in rB.
Usage: The maximum allowed value of IMMED is 32768. The minimum allowed value is
–32767.
Pseudo-instruction:
© March 2009
subi is implemented as addi rB, rA, -IMMED

Answer

paxdiablo picture paxdiablo · Aug 16, 2012

I'm unaware that MIPS even has a proper subi instruction (though some environments may implement a macro for it).

Since you're subtracting an immediate value, you can just provide the negation of it to the addi instruction:

addi $r1, $r2, -42     ; equivalent to subi $r1, $r2, 42

The immediate operand is a two's complement value which means it's perfectly capable of being a negative number and the way that two's complement works means that you can add a negative number in an unsigned manner and that gives the same result as subtracting (since you wrap around).

For example, -42 in 16-bit two's complement is the unsigned value 65494. When you add 50 and 65494 wrapping around at 65536, you end up with:

     50
+ 65494 (ie, -42)
  -----
  65544 (overflow, so
- 65536  we wrap at 64K)
  -----
      8 (identical to "50 - 42")