|
|
(6 intermediate revisions by the same user not shown) |
Line 1: |
Line 1: |
| == The Original Code ==
| | #REDIRECT [[ist:Code Generation/Exercise 6]] |
| | |
| Consider the following C function:
| |
| | |
| <c>
| |
| int powmod(int base, int exp, int modulus) {
| |
| int accum = 1, i = 0, basepow2 = base;
| |
| while ((exp >> i) > 0) {
| |
| if (((exp >> i) & 1) == 1)
| |
| accum = (accum * basepow2) % modulus;
| |
| basepow2 = (basepow2 * basepow2) % modulus;
| |
| i++;
| |
| }
| |
| return accum;
| |
| }
| |
| </c>
| |
| | |
| == Postfix Code ==
| |
| | |
| The Postfix code for the above function is as follows:
| |
| | |
| <asm>
| |
| TEXT
| |
| ALIGN
| |
| GLOBL powmod, FUNC
| |
| LABEL powmod
| |
| ENTER 12
| |
| INT 1
| |
| LOCA -4
| |
| INT 0
| |
| LOCA -8
| |
| LOCV +8
| |
| LOCA -12
| |
| | |
| ALIGN
| |
| LABEL while
| |
| LOCV +12
| |
| LOCV -8
| |
| SHTRU
| |
| INT 0
| |
| GT
| |
| JZ while_end
| |
| | |
| LOCV +12
| |
| LOCV -8
| |
| SHTRU
| |
| INT 1
| |
| AND
| |
| INT 1
| |
| EQ
| |
| JZ if_end
| |
| | |
| LOCV -4
| |
| LOCV -12
| |
| MUL
| |
| LOCV +16
| |
| MOD
| |
| DUP
| |
| LOCA -4
| |
| TRASH 4
| |
| | |
| ALIGN
| |
| LABEL if_end
| |
| | |
| LOCV -12
| |
| LOCV -12
| |
| MUL
| |
| LOCV +16
| |
| MOD
| |
| DUP
| |
| LOCA -12
| |
| TRASH 4
| |
| | |
| LOCV -8
| |
| DUP
| |
| INT 1
| |
| ADD
| |
| LOCA -8
| |
| TRASH 4
| |
| | |
| JMP while
| |
| LABEL while_end
| |
| | |
| LOCV -4
| |
| POP
| |
| LEAVE
| |
| RET
| |
| </asm>
| |
| | |
| == Compiling and Running ==
| |
| | |
| To compile the Postfix code directly, [[pf2asm]] can be used:
| |
| | |
| * pf2asm gcd.pf
| |
| * yasm -felf gcd.asm
| |
| | |
| [[category:Compilers]]
| |
| [[category:Teaching]]
| |