Difference between revisions of "Code Generation/Exercise 6"

From Wiki**3

< Code Generation
(Postfix Code)
(Postfix Code)
Line 19: Line 19:
  
 
The Postfix code for the above function is as follows:  
 
The Postfix code for the above function is as follows:  
 
+
{{CollapsedCode|Postfix code|
 
<asm>
 
<asm>
 
TEXT
 
TEXT
Line 106: Line 106:
 
RET
 
RET
 
</asm>
 
</asm>
 +
}}
  
 
== Compiling and Running ==
 
== Compiling and Running ==

Revision as of 09:32, 9 May 2017

The Original Code

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:

Postfix code

<asm> TEXT ALIGN GLOBL powmod, FUNC LABEL powmod ENTER 12 INT 1 LOCAL -4 STORE INT 0 LOCAL -8 STORE LOCAL +8 LOAD LOCAL -12 STORE

ALIGN LABEL while LOCAL +12 LOAD LOCAL -8 LOAD SHTRU INT 0 GT JZ while_end

LOCAL +12 LOAD LOCAL -8 LOAD SHTRU INT 1 AND INT 1 EQ JZ if_end

LOCAL -4 LOAD LOCAL -12 LOAD MUL LOCAL +16 LOAD MOD DUP LOCAL -4 STORE TRASH 4

ALIGN LABEL if_end

LOCAL -12 LOAD LOCAL -12 LOAD MUL LOCAL +16 LOAD MOD DUP LOCAL -12 STORE TRASH 4

LOCAL -8 LOAD DUP INT 1 ADD LOCAL -8 STORE TRASH 4

JMP while LABEL while_end

LOCAL -4 LOAD POP LEAVE RET </asm>

Compiling and Running

To compile the Postfix code directly, pf2asm can be used:

pf2asm powmod.pf
yasm -felf powmod.asm