Difference between revisions of "Code Generation/Example 4"

From Wiki**3

< Code Generation
(Postfix Code)
(Postfix Code)
Line 18: Line 18:
  
 
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>
 
EXTRN printf
 
EXTRN printf
Line 30: Line 30:
  
 
; int ix = lo is NOT an assignment
 
; int ix = lo is NOT an assignment
LOCV +8 ; read lo
+
LOCAL +8
LOCA -4 ; write to ix
+
LOAD ; read lo
 +
LOCAL -4
 +
STORE ; write to ix
  
 
ALIGN
 
ALIGN
 
LABEL whiletest
 
LABEL whiletest
LOCV -4  ; read ix
+
LOCAL -4
LOCV +12 ; read hi
+
LOAD ; read ix
 +
LOCAL +12
 +
LOAD ; read hi
 
LT
 
LT
 
JZ whileend
 
JZ whileend
Line 44: Line 48:
 
; prepare arguments for calling printf
 
; prepare arguments for calling printf
  
LOCV -4    ; second printf arg: read ix
+
LOCAL -4
 +
LOAD     ; second printf arg: read ix
  
 
; put string literal in read-only memory
 
; put string literal in read-only memory
Line 68: Line 73:
  
 
; increment ix
 
; increment ix
LOCV -4 ; read ix
+
LOCAL -4
 +
LOAD ; read ix
 
DUP
 
DUP
 
INT 1
 
INT 1
 
ADD
 
ADD
LOCA -4 ; ix = ix + 1
+
LOCAL -4
 +
STORE ; ix = ix + 1
  
 
; trash old value of ix
 
; trash old value of ix
Line 87: Line 94:
  
 
; prepare return value
 
; prepare return value
LOCV -4 ; read ix
+
LOCAL -4
 +
LOAD ; read ix
  
 
; put it in the accumulator (register) to conform with Cdecl
 
; put it in the accumulator (register) to conform with Cdecl
Line 96: Line 104:
  
 
</asm>
 
</asm>
 +
}}
  
 
== Compiling and Running ==
 
== Compiling and Running ==

Revision as of 09:31, 9 May 2017

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