Code Generation/Example 4: Difference between revisions

From Wiki**3

< Code Generation
Line 31: Line 31:
; int ix = lo is NOT an assignment
; int ix = lo is NOT an assignment
LOCAL +8
LOCAL +8
LOAD ; read lo
LDINT ; read lo
LOCAL -4
LOCAL -4
STORE ; write to ix
STINT ; write to ix


ALIGN
ALIGN
LABEL whiletest
LABEL whiletest
LOCAL -4
LOCAL -4
LOAD ; read ix
LDINT ; read ix
LOCAL +12
LOCAL +12
LOAD ; read hi
LDINT ; read hi
LT
LT
JZ whileend
JZ whileend
Line 49: Line 49:


LOCAL -4
LOCAL -4
LOAD     ; second printf arg: read ix
LDINT     ; second printf arg: read ix


; put string literal in read-only memory
; put string literal in read-only memory
Line 55: Line 55:
ALIGN
ALIGN
LABEL strlit
LABEL strlit
STR "%d\n"
SSTRING "%d\n"
; now get the address of the string literal (strlit)
; now get the address of the string literal (strlit)
TEXT
TEXT
Line 67: Line 67:


; get printf return value
; get printf return value
PUSH
LDFVAL32


; get rid of return value (printf used as instruction)
; get rid of return value (printf used as instruction)
Line 74: Line 74:
; increment ix
; increment ix
LOCAL -4
LOCAL -4
LOAD ; read ix
LDINT ; read ix
DUP
DUP32
INT 1
INT 1
ADD
ADD
LOCAL -4
LOCAL -4
STORE ; ix = ix + 1
STINT ; ix = ix + 1


; trash old value of ix
; trash old value of ix
Line 95: Line 95:
; prepare return value
; prepare return value
LOCAL -4
LOCAL -4
LOAD ; read ix
LDINT ; read ix


; put it in the accumulator (register) to conform with Cdecl
; put it in the accumulator (register) to conform with Cdecl
POP
STFVAL32


LEAVE  ; release stack frame
LEAVE  ; release stack frame

Revision as of 22:33, 1 May 2018

The Original Code

Consider the following C function:

<c> extern int printf(const char *format, ...); int printlist(int lo, int hi) {

 int ix = lo;
 while (ix < hi) {
   printf("%d\n", ix);
   ix++;
 }
 return ix;

} </c>

Postfix Code

The Postfix code for the above function is as follows:

Postfix code
{{{2}}}

Compiling and Running

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

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