Reputation: 353
I learned that 'subi' isn't needed in RISC-V ISA and the immediate field represents a two's complement integer to do the operation altogether.
My question is, if the immediate part can be represented as a negative number then could we also represent addresses as a negative integer?
Upvotes: 0
Views: 5020
Reputation: 26646
Can address be negative in the immediate field of the RISC-V I-Type?
The immediate field doesn't really store addresses — it is too short to do that. It stores medium-small integers, and is signed extended in usage so that it can hold positive and negative integers.
I learned that 'subi' isn't needed in RICS_V ISA and the immediate field represents a two's complement integer to do the operation altogether.
Yes. The immediate field is indeed sign extended to 32 (or 64) bits before usage, so we can add a negative immediate instead of subtracting a positive immediate.
My question is, if the immediate part can be represented as a negative number then could we also represent addresses as a negative integer?
The latter item doesn't follow from the former.
The memory system has an address bus which is just an ordered array of bits. There is no consideration of sign or negative values on the address bus — the MSB is treated as higher magnitude rather than as sign bit. Thus, we consider addresses to be unsigned numbers.
However, there's nothing to stop you from interpreting (e.g. printing) a memory address as a signed integer.
2's complement representation for signed numbers means that the same bit patterns arise when adding, multiplying, subtracting or comparing signed numbers as for doing the same operations using unsigned numbers. Because the bit patterns of the results are the same, the real difference is in determining overflow, since signed numbers and unsigned numbers overflow differently.
We should use unsigned arithmetic for addresses, because unsigned has the proper overflow criteria: A value of all 1's is a large positive number, that if incremented, overflows and becomes 0.
By contrast, if we use signed arithmetic for addresses, we will not get overflow when going from all 1's to 0, even though we should. Further, we will get an overflow when we shouldn't, if we add 1 to 01111...111 yielding 10000...000.
Note that in many cases we don't bother checking for overflow especially with addresses and pointer arithmetic. If the program is correct, then when computing the address of some memory that we know exists, the calculation will not overflow. So, it is important to verify whether your memory allocations succeed.
Upvotes: 2