Code Generation/Exercise 15

From Wiki**3

< Code Generation

Problema

Considere o seguinte código C++ (assuma que ponteiros e int ocupam 32 bits e que double ocupa 64 bits).

extern int swap(int *a, int *b);
int gcd(int a, int b) {
  static int temp = 0;
  if (temp) temp = swap(&a, &b);
  while (1) {
    a = a % b;
    if (a == 0) break;
    b = b % a;
    if (b == 0) return a;
  }
  return b;
}

Código Postfix (não optimizado)

O código Postfix correspondente ao código C++ é o seguinte (agradece-se a comunicação de questões relativas a este código).

Código Postfix
EXTERN swap

TEXT
GLOBAL gcd, FUNC
LABEL  gcd
ENTER 0 ; a@+8 b@+12
DATA
LABEL temp
SINT 0

TEXT

ADDR temp
LDINT
JZ if1end
LOCAL +12 ; &b
LOCAL +8  ; &a
CALL swap
TRASH 8
LDFVAL32
DUP32
ADDR temp
STINT
TRASH 4
LABEL if1end

LABEL whiletest
INT 1
JZ whileend

LOCAL +8
LDINT ; a
LOCAL +12
LDINT ; b
MOD
DUP32
LOCAL +8
STINT
TRASH 4

LOCAL +8
LDINT
INT 0
EQ
JZ if2end
JMP whileend
LABEL if2end

LOCAL +12
LDINT ; b
LOCAL +8
LDINT ; a
MOD
DUP32
LOCAL +12
STINT
TRASH 4

LOCAL +12
LDINT
INT 0
EQ
JZ if3end
LOCAL +8
LDINT ; a
STFVAL32
LEAVE
RET
LABEL if3end

JMP whiletest
LABEL whileend

LOCAL +12
LDINT
STFVAL32
LEAVE
RET

Compiling and Running

Para compilar o código Postfix directamente, pode ser utilizada a ferramenta pf2asm (assumindo uma arquitectura de 32 bits):

pf2asm code.pf
yasm -felf32 code.asm