Difference between revisions of "Code Generation/Example 3"

From Wiki**3

< Code Generation
(The Original Code)
(Postfix Code)
Line 59: Line 59:
 
;; if test
 
;; if test
 
LOCV 8 ; x
 
LOCV 8 ; x
LOVC -8 ; i
+
LOCV -8 ; i
 
INT 4
 
INT 4
 
MUL
 
MUL

Revision as of 11:57, 2 May 2013

The Original Code

Consider the following C function:

<c> int *click(int *x, int dim) {

 int *res, i;
 for (i = dim-2, res = x+dim-1; i >= 0; i--)
   if (x[i] > *res) res = &x[i];
 return res;

} </c>

Postfix Code

The Postfix code for the above function is as follows:

<asm> TEXT ALIGN GLOBL click, FUNC LABEL click ENTER 8  ;-- x@+8 dim@+12 res@-4 i@-8

for init
i = dim-2

LOCV 12 INT 2 SUB DUP LOCA -8 TRASH 4

res = x + dim - 1

LOCV 8 LOCV 12 INT 4 MUL ADD INT 1 INT 4 MUL SUB DUP LOCA -4 TRASH 4

for test

ALIGN LABEL for LOCV -8 INT 0 GE JZ forend

for block
if test

LOCV 8 ; x LOCV -8 ; i INT 4 MUL ADD ; x+i LOAD ; x[i] = *(x+i)

LOCV -4 ; res LOAD ; *res

GT JZ ifend

if block

LOCV 8 ; x LOVC -8 ; i INT 4 MUL ADD ; x+i = &x[i] DUP LOCA -4 ; res = &x[i] TRASH 4

ALIGN LABEL ifend

for increment

ALIGN LABEL forincr LOCV -8 ; i DUP INT 1 SUB LOCA -8 TRASH 4

for jump to cycle

JMP for

ALIGN LABEL forend

return

LOCV -4 ; res

POP LEAVE RET </asm>

Compiling and Running

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

  • pf2asm click.pf
  • yasm -felf click.asm