PowerPC -- Sign extension problem |
The sign extension problem is straight forward.
Examine the following code sequence. At the end of the code sequence, what will be in the PowerPC registers R4 and R5?
FIRST: .equ 0x12345678 SECOND: .equ 0x12348765
ADDI R4, 0, FIRST@l # Lower 16 bits ADDIS R4, R4, FIRST@h # Higher 16 bits
ADDI R5, 0, SECOND@l # Lower 16 bits ADDIS R5, R5, SECOND@h # Higher 16 bits
Register R4 will be what you expect (0x12345678) but R5 will not be 0x12348765. What will it be? Work out the value in register R5 by looking up the details of the instructions ADDI and ADDIS.
The problem is associated with the fact that the PowerPC ADDI instruction is directed towards manipulating a 16-bit value within a 32-bit register. It involves sign extension. This means that after instruction
ADDI R4, 0, FIRST@l # Lower 16 bits
R4 will be 0x00005678 (that's 0x5678 sign extended to 32 bits). If you now perform
ADDIS R4, R4, FIRST@h # Higher 16 bits
you will get the expected R4 value of 0x12345678.
However after
ADDI R5, 0, SECOND@l # Lower 16 bits
R5 will be 0xFFFF8765 (that's 0x8765 sign extended to 32 bits). If you now perform
ADDIS R5, R5, SECOND@h # Higher 16 bits
you will get R5 = 0xFFFF8765 + 0x12340000 = 0x12338765. Not what you expected!
To solve this problem, you should use the @ha rather than @h assembler directive when handling 32 bit constants. The @ha directive takes into account this "off by one" problem. See for example the stack initialization procedure using the __INIT_STACK variable in file crt0.s.
Thus we have the following correct code sequence
FIRST: .equ 0x12345678 SECOND: .equ 0x12348765
ADDIS R4, 0, FIRST@ha # Higher 16 bits, possibly adjusted ADDIS R4, R4, FIRST@l # Lower 16 bits
ADDI R5, 0, SECOND@ha # Higher 16 bits, possibly adjusted ADDIS R5, R4, SECOND@l # Lower 16 bits
Keep the @h directive when you just want to manipulate the top 16 bits of a value. Real life
Note:- Although corrected in later editions, students who have purchased a "used" copy of the 1st printing of the 4th edition of HVZ will find code with this sign extension problem.
![]() |
Last modified: July 07, 1996 10:07 PM by M. Smith.
Copyright -- M. R. Smith