Code Generation/Example 4: Difference between revisions
From Wiki**3
< Code Generation
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 | ||
LOCAL +8 | |||
LOAD ; read lo | |||
LOCAL -4 | |||
STORE ; write to ix | |||
ALIGN | ALIGN | ||
LABEL whiletest | LABEL whiletest | ||
LOCAL -4 | |||
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 | ||
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 | ||
LOCAL -4 | |||
LOAD ; read ix | |||
DUP | DUP | ||
INT 1 | INT 1 | ||
ADD | ADD | ||
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 | ||
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 07: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