Difference between revisions of "Code Generation/Example 1"

From Wiki**3

< Code Generation
(Postfix Code)
Line 2: Line 2:
  
 
Consider the following C function:
 
Consider the following C function:
<c>
+
<source lang="c">
 
int main() {
 
int main() {
 
   int n = 45, i = 0, j = 1, *seg = &i;
 
   int n = 45, i = 0, j = 1, *seg = &i;
Line 11: Line 11:
 
   return 0;
 
   return 0;
 
}
 
}
</c>
+
</source>
  
 
== Postfix Code ==
 
== Postfix Code ==
Line 17: Line 17:
 
The Postfix code for the above function is as follows:
 
The Postfix code for the above function is as follows:
 
{{CollapsedCode|Postfix code|
 
{{CollapsedCode|Postfix code|
<asm>
+
<source lang="asm">
 
TEXT
 
TEXT
 
ALIGN
 
ALIGN
Line 82: Line 82:
 
LEAVE
 
LEAVE
 
RET
 
RET
</asm>
+
</source>
 
}}
 
}}
  
 
[[category:Compiladores]]
 
[[category:Compiladores]]
 
[[category:Ensino]]
 
[[category:Ensino]]

Revision as of 13:31, 12 February 2019

The Original Code

Consider the following C function:

int main() {
  int n = 45, i = 0, j = 1, *seg = &i;
  while (n-- > 0) {
    print(*seg = i + j);
    seg = (seg == &i) ? &j : &i;
  }
  return 0;
}

Postfix Code

The Postfix code for the above function is as follows:

Postfix code
TEXT
ALIGN
GLOBAL "main",FUNC
LABEL "main"
ENTER 16    ; n@-4, i@-8, j@-12, seg@-16

;-- initialization:
INT 45
LOCA -4          ; n = 45
INT 0
LOCA -8          ; i = 0
INT 1
LOCA -12         ; j = 1
LOCAL -8         ; &i
LOCA -16         ; seg = &i

;-- while cycle:
ALIGN
LABEL "while"
LOCV -4          ; n
DUP32              ; n (because of n--)
INT 1
SUB              ; n-1
LOCA -4          ; n = n-1
INT 0
GT               ; n > 0 (n before decrement)
JZ "endwhile"
LOCV -8          ; i
LOCV -12         ; j
ADD              ; i+j
DUP32              ; same value (for assignment)
LOCV -16         ; seg
STINT            ; *seg = i+j
CALL "print"     ; we assume that "print" does not return any value
TRASH 4          ; trash argument (int)

;-- compute trenary operator's value
LOCV -16         ; seg
LOCAL -8         ; &i
EQ               ; seg == &i
JZ "false3"      ; jump to "false" expression of trenary operator
LOCAL -12        ; &j
JMP "end3"       ; jump to end of trenary operator

ALIGN
LABEL "false3"
LOCAL -8         ; &i

ALIGN
LABEL "end3"
DUP32              ; trenary operator's value (duplicated because of assignment)
LOCA -16         ; seg = (seg == &i) ? &j : &i
TRASH 4          ; trash assignment's value, since we used it as an instruction

JMP "while"      ; restart while cycle

ALIGN
LABEL "endwhile"

;-- rest of function
INT 0
STFVAL32              ; return value is 0
LEAVE
RET