0

Screen-Shot-2022-05-29-at-2-14-09-PM.png

In question iv.

Does my first instruction successfully negate the register i? Does my second instruction complete the problem?

sdev
  • 85
  • 6
  • Single-step it in a debugger (e.g. MARS) and try it yourself. Or read the same duplicate as your last question, [About negate a sign-integer in mips?](https://stackoverflow.com/q/53568440), which already explains that this works. I'm not sure why you think subtracting from zero might not work, or why you asked this after getting a link to that existing Q&A on [your previous question](https://stackoverflow.com/questions/72420074/mips-assembly-confused-with-negative-register). – Peter Cordes May 29 '22 at 19:15
  • `sub` will fault with integer overflow if `i = INT_MIN` since you use `sub` instead of `subu` and MIPS is a 2's complement machine, but in that case `1 - i` would also have faulted (signed overflow is undefined behaviour in C++). So this is I think a fully valid implementation of that C snippet. – Peter Cordes May 29 '22 at 19:17

1 Answers1

1

Yes, that works!


The use of $t2 is unnecessary in this instruction sequence, as the first instruction can simply put the result directly back in $t0, since $t0 is going to be updated anyway, and you need only -i after that point, but no longer need the original value of i itself.

Generally, it is good to reduce the number of registers used for small code sequences like this, since there are larger contexts in which we can run out of registers.


To me it would have been more natural to do:

li $t2, 1
sub $t0, $t2, $t0

Of course, that does require a 2nd register (no way to eliminate it), so to one measure, your code sequence (modified to use $t0 only) is more optimal.

Erik Eidt
  • 23,049
  • 2
  • 29
  • 53
  • Indeed, `1 - i` is how compilers do it, since that has instruction-level parallelism while `(-1) + 1` doesn't. The querent's previous question (https://stackoverflow.com/questions/72420074/mips-assembly-confused-with-negative-register) already had a Godbolt link in comments showing `return -i` vs. `return 1-i`, and was closed as a duplicate of of [About negate a sign-integer in mips?](https://stackoverflow.com/q/53568440) which also already explained that subtract-from-zero is correct for negation. This seems like another near-exact duplicate; this question doesn't ask anything new. – Peter Cordes May 29 '22 at 19:10