rep stosd and stuff
[ia32rtools.git] / tools / translate.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include "my_assert.h"
7 #include "my_str.h"
8
9 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
10 #define IS(w, y) !strcmp(w, y)
11
12 #include "protoparse.h"
13
14 const char *asmfn;
15 static int asmln;
16
17 #define anote(fmt, ...) \
18         printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
19 #define awarn(fmt, ...) \
20         printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
21 #define aerr(fmt, ...) do { \
22         printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
23   fcloseall(); \
24         exit(1); \
25 } while (0)
26
27 enum op_flags {
28   OPF_RMD    = (1 << 0), /* removed or optimized out */
29   OPF_DATA   = (1 << 1), /* data processing - writes to dst opr */
30   OPF_FLAGS  = (1 << 2), /* sets flags */
31   OPF_JMP    = (1 << 3), /* branches, ret and call */
32   OPF_CC     = (1 << 4), /* uses flags */
33   OPF_TAIL   = (1 << 5), /* ret or tail call */
34   OPF_REP    = (1 << 6), /* prefixed by rep */
35 };
36
37 enum op_op {
38         OP_INVAL,
39         OP_NOP,
40         OP_PUSH,
41         OP_POP,
42         OP_MOV,
43         OP_LEA,
44         OP_MOVZX,
45         OP_MOVSX,
46         OP_NOT,
47         OP_CDQ,
48         OP_STOS,
49         OP_RET,
50         OP_ADD,
51         OP_SUB,
52         OP_AND,
53         OP_OR,
54         OP_XOR,
55         OP_SHL,
56         OP_SHR,
57         OP_SAR,
58         OP_ADC,
59         OP_SBB,
60         OP_INC,
61         OP_DEC,
62         OP_NEG,
63         OP_MUL,
64         OP_IMUL,
65         OP_DIV,
66         OP_IDIV,
67         OP_TEST,
68         OP_CMP,
69         OP_CALL,
70         OP_JMP,
71         OP_JO,
72         OP_JNO,
73         OP_JC,
74         OP_JNC,
75         OP_JZ,
76         OP_JNZ,
77         OP_JBE,
78         OP_JA,
79         OP_JS,
80         OP_JNS,
81         OP_JP,
82         OP_JNP,
83         OP_JL,
84         OP_JGE,
85         OP_JLE,
86         OP_JG,
87 };
88
89 enum opr_type {
90   OPT_UNSPEC,
91   OPT_REG,
92   OPT_REGMEM,
93   OPT_LABEL,
94   OPT_OFFSET,
95   OPT_CONST,
96 };
97
98 enum opr_lenmod {
99         OPLM_UNSPEC,
100         OPLM_BYTE,
101         OPLM_WORD,
102         OPLM_DWORD,
103 };
104
105 #define MAX_OPERANDS 3
106
107 struct parsed_opr {
108   enum opr_type type;
109   enum opr_lenmod lmod;
110   int reg;
111   unsigned int val;
112   char name[256];
113 };
114
115 struct parsed_op {
116   enum op_op op;
117   struct parsed_opr operand[MAX_OPERANDS];
118   unsigned int flags;
119   int operand_cnt;
120   int regmask_src;        // all referensed regs
121   int regmask_dst;
122   int pfomask;            // flagop: parsed_flag_op that can't be delayed
123   int argmask;            // push: args that are altered before call
124   int cc_scratch;         // scratch storage during analysis
125   int bt_i;               // branch target (for branches)
126   struct parsed_op *lrl;  // label reference list entry
127   void *datap;
128 };
129
130 // datap:
131 // OP_CALL - ptr to parsed_proto
132 // (OPF_CC) - point to corresponding (OPF_FLAGS)
133
134 struct parsed_equ {
135   char name[64];
136   enum opr_lenmod lmod;
137   int offset;
138 };
139
140 #define MAX_OPS 1024
141
142 static struct parsed_op ops[MAX_OPS];
143 static struct parsed_equ *g_eqs;
144 static int g_eqcnt;
145 static char g_labels[MAX_OPS][32];
146 static struct parsed_op *g_label_refs[MAX_OPS];
147 static struct parsed_proto g_func_pp;
148 static char g_func[256];
149 static char g_comment[256];
150 static int g_bp_frame;
151 static int g_bp_stack;
152 #define ferr(op_, fmt, ...) do { \
153   printf("error:%s:#%ld: '%s': " fmt, g_func, (op_) - ops, \
154     dump_op(op_), ##__VA_ARGS__); \
155   fcloseall(); \
156   exit(1); \
157 } while (0)
158
159 #define MAX_REGS 8
160
161 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
162 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
163 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
164 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
165
166 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
167
168 // possible basic comparison types (without inversion)
169 enum parsed_flag_op {
170   PFO_O,  // 0 OF=1
171   PFO_C,  // 2 CF=1
172   PFO_Z,  // 4 ZF=1
173   PFO_BE, // 6 CF=1||ZF=1
174   PFO_S,  // 8 SF=1
175   PFO_P,  // a PF=1
176   PFO_L,  // c SF!=OF
177   PFO_LE, // e ZF=1||SF!=OF
178 };
179
180 static const char *parsed_flag_op_names[] = {
181   "o", "c", "z", "be", "s", "p", "l", "le"
182 };
183
184 static int char_array_i(const char *array[], size_t len, const char *s)
185 {
186   int i;
187
188   for (i = 0; i < len; i++)
189     if (IS(s, array[i]))
190       return i;
191
192   return -1;
193 }
194
195 static void printf_number(char *buf, size_t buf_size, long number)
196 {
197   // output in C-friendly form
198   snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
199 }
200
201 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
202 {
203   int reg;
204
205   reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
206   if (reg >= 0) {
207     *reg_lmod = OPLM_DWORD;
208     return reg;
209   }
210   reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
211   if (reg >= 0) {
212     *reg_lmod = OPLM_WORD;
213     return reg;
214   }
215   reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
216   if (reg >= 0) {
217     *reg_lmod = OPLM_BYTE;
218     return reg;
219   }
220   reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
221   if (reg >= 0) {
222     *reg_lmod = OPLM_BYTE;
223     return reg;
224   }
225
226   return -1;
227 }
228
229 static long parse_number(const char *number)
230 {
231   int len = strlen(number);
232   const char *p = number;
233   char *endp = NULL;
234   int neg = 0;
235   int bad;
236   long ret;
237
238   if (*p == '-') {
239     neg = 1;
240     p++;
241   }
242   if (len > 1 && *p == '0')
243     p++;
244   if (number[len - 1] == 'h') {
245     ret = strtol(p, &endp, 16);
246     bad = (*endp != 'h');
247   }
248   else {
249     ret = strtol(p, &endp, 10);
250     bad = (*endp != 0);
251   }
252   if (bad)
253     aerr("number parsing failed\n");
254   if (neg)
255     ret = -ret;
256   return ret;
257 }
258
259 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
260 {
261   enum opr_lenmod lmod;
262   char cvtbuf[256];
263   char *d = cvtbuf;
264   char *s = name;
265   char w[64];
266   long number;
267   int reg;
268   int c = 0;
269
270   *d = 0;
271
272   while (*s != 0) {
273     d += strlen(d);
274     while (my_isblank(*s))
275       s++;
276     for (; my_issep(*s); d++, s++)
277       *d = *s;
278     while (my_isblank(*s))
279       s++;
280     *d = 0;
281
282     // skip 'ds:' prefix
283     if (!strncmp(s, "ds:", 3))
284       s += 3;
285
286     s = next_idt(w, sizeof(w), s);
287     if (w[0] == 0)
288       break;
289     c++;
290
291     reg = parse_reg(&lmod, w);
292     if (reg >= 0) {
293       *regmask |= 1 << reg;
294       goto pass;
295     }
296
297     if ('0' <= w[0] && w[0] <= '9') {
298       number = parse_number(w);
299       printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
300       continue;
301     }
302
303     // probably some label/identifier - pass
304
305 pass:
306     snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
307   }
308
309   if (need_c_cvt)
310     strcpy(name, cvtbuf);
311
312   return c;
313 }
314
315 static int guess_lmod_from_name(struct parsed_opr *opr)
316 {
317   if (!strncmp(opr->name, "dword_", 6)) {
318     opr->lmod = OPLM_DWORD;
319     return 1;
320   }
321   if (!strncmp(opr->name, "word_", 5)) {
322     opr->lmod = OPLM_WORD;
323     return 1;
324   }
325   if (!strncmp(opr->name, "byte_", 5)) {
326     opr->lmod = OPLM_BYTE;
327     return 1;
328   }
329   return 0;
330 }
331
332 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
333   int *regmask)
334 {
335   opr->type = OPT_REG;
336   opr->reg = reg;
337   opr->lmod = lmod;
338   *regmask |= 1 << reg;
339 }
340
341 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name);
342
343 static int parse_operand(struct parsed_opr *opr,
344   int *regmask, int *regmask_indirect,
345         char words[16][256], int wordc, int w, unsigned int op_flags)
346 {
347   enum opr_lenmod tmplmod;
348   int ret, len;
349   long number;
350   int i;
351
352         if (w >= wordc)
353                 aerr("parse_operand w %d, wordc %d\n", w, wordc);
354
355         opr->reg = xUNSPEC;
356
357         for (i = w; i < wordc; i++) {
358                 len = strlen(words[i]);
359                 if (words[i][len - 1] == ',') {
360                         words[i][len - 1] = 0;
361                         wordc = i + 1;
362                         break;
363                 }
364         }
365
366         if (op_flags & OPF_JMP) {
367                 const char *label;
368
369                 if (wordc - w == 3 && IS(words[w + 1], "ptr"))
370                         label = words[w + 2];
371                 else if (wordc - w == 2 && IS(words[w], "short"))
372                         label = words[w + 1];
373                 else if (wordc - w == 1)
374                         label = words[w];
375                 else
376                         aerr("jump parse error");
377
378                 opr->type = OPT_LABEL;
379                 strcpy(opr->name, label);
380                 return wordc;
381         }
382
383         if (wordc - w >= 3) {
384                 if (IS(words[w + 1], "ptr")) {
385                         if (IS(words[w], "dword"))
386                                 opr->lmod = OPLM_DWORD;
387                         else if (IS(words[w], "word"))
388                                 opr->lmod = OPLM_WORD;
389                         else if (IS(words[w], "byte"))
390                                 opr->lmod = OPLM_BYTE;
391                         else
392                                 aerr("type parsing failed\n");
393                         w += 2;
394                 }
395         }
396
397         if (wordc - w == 2 && IS(words[w], "offset")) {
398                 opr->type = OPT_OFFSET;
399                 strcpy(opr->name, words[w + 1]);
400                 return wordc;
401         }
402
403   if (wordc - w != 1)
404     aerr("parse_operand 1 word expected\n");
405
406   strcpy(opr->name, words[w]);
407
408   if (words[w][0] == '[') {
409     opr->type = OPT_REGMEM;
410     ret = sscanf(words[w], "[%[^]]]", opr->name);
411     if (ret != 1)
412       aerr("[] parse failure\n");
413
414     parse_indmode(opr->name, regmask_indirect, 1);
415     if (opr->lmod == OPLM_UNSPEC && !strncmp(opr->name, "ebp+", 4)) {
416       // might be an equ
417       struct parsed_equ *eq = equ_find(NULL, opr->name + 4);
418       if (eq)
419         opr->lmod = eq->lmod;
420     }
421     return wordc;
422   }
423   else if (strchr(words[w], '[')) {
424     // label[reg] form
425     opr->type = OPT_REGMEM;
426     if (opr->lmod == OPLM_UNSPEC)
427       guess_lmod_from_name(opr);
428     parse_indmode(strchr(words[w], '['), regmask_indirect, 0);
429     return wordc;
430   }
431   else if (('0' <= words[w][0] && words[w][0] <= '9')
432     || words[w][0] == '-')
433   {
434     number = parse_number(words[w]);
435     opr->type = OPT_CONST;
436     opr->val = number;
437     printf_number(opr->name, sizeof(opr->name), number);
438     return wordc;
439   }
440
441   ret = parse_reg(&tmplmod, opr->name);
442   if (ret >= 0) {
443     setup_reg_opr(opr, ret, tmplmod, regmask);
444     return wordc;
445   }
446
447   // most likely var in data segment
448   opr->type = OPT_LABEL;
449   if (opr->lmod == OPLM_UNSPEC)
450     guess_lmod_from_name(opr);
451   if (opr->lmod != OPLM_UNSPEC)
452     return wordc;
453
454   // TODO: scan data seg to determine type?
455   return wordc;
456 }
457
458 static const struct {
459   const char *name;
460   unsigned int flags;
461 } pref_table[] = {
462   { "rep",    OPF_REP },
463 };
464
465 static const struct {
466   const char *name;
467   enum op_op op;
468   unsigned int minopr;
469   unsigned int maxopr;
470   unsigned int flags;
471 } op_table[] = {
472   { "nop",  OP_NOP,    0, 0, 0 },
473   { "push", OP_PUSH,   1, 1, 0 },
474   { "pop",  OP_POP,    1, 1, OPF_DATA },
475   { "mov" , OP_MOV,    2, 2, OPF_DATA },
476   { "lea",  OP_LEA,    2, 2, OPF_DATA },
477   { "movzx",OP_MOVZX,  2, 2, OPF_DATA },
478   { "movsx",OP_MOVSX,  2, 2, OPF_DATA },
479   { "not",  OP_NOT,    1, 1, OPF_DATA },
480   { "cdq",  OP_CDQ,    0, 0, OPF_DATA },
481   { "stosb",OP_STOS,   0, 0, OPF_DATA },
482   { "stosw",OP_STOS,   0, 0, OPF_DATA },
483   { "stosd",OP_STOS,   0, 0, OPF_DATA },
484   { "add",  OP_ADD,    2, 2, OPF_DATA|OPF_FLAGS },
485   { "sub",  OP_SUB,    2, 2, OPF_DATA|OPF_FLAGS },
486   { "and",  OP_AND,    2, 2, OPF_DATA|OPF_FLAGS },
487   { "or",   OP_OR,     2, 2, OPF_DATA|OPF_FLAGS },
488   { "xor",  OP_XOR,    2, 2, OPF_DATA|OPF_FLAGS },
489   { "shl",  OP_SHL,    2, 2, OPF_DATA|OPF_FLAGS },
490   { "shr",  OP_SHR,    2, 2, OPF_DATA|OPF_FLAGS },
491   { "sal",  OP_SHL,    2, 2, OPF_DATA|OPF_FLAGS },
492   { "sar",  OP_SAR,    2, 2, OPF_DATA|OPF_FLAGS },
493   { "adc",  OP_ADC,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
494   { "sbb",  OP_SBB,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
495   { "inc",  OP_INC,    1, 1, OPF_DATA|OPF_FLAGS },
496   { "dec",  OP_DEC,    1, 1, OPF_DATA|OPF_FLAGS },
497   { "neg",  OP_NEG,    1, 1, OPF_DATA|OPF_FLAGS },
498   { "mul",  OP_MUL,    1, 1, OPF_DATA|OPF_FLAGS },
499   { "imul", OP_IMUL,   1, 3, OPF_DATA|OPF_FLAGS },
500   { "div",  OP_DIV,    1, 1, OPF_DATA|OPF_FLAGS },
501   { "idiv", OP_IDIV,   1, 1, OPF_DATA|OPF_FLAGS },
502   { "test", OP_TEST,   2, 2, OPF_FLAGS },
503   { "cmp",  OP_CMP,    2, 2, OPF_FLAGS },
504   { "retn", OP_RET,    0, 1, OPF_JMP|OPF_TAIL },
505   { "call", OP_CALL,   1, 1, OPF_JMP|OPF_FLAGS },
506   { "jmp",  OP_JMP,    1, 1, OPF_JMP },
507   { "jo",   OP_JO,     1, 1, OPF_JMP|OPF_CC }, // 70 OF=1
508   { "jno",  OP_JNO,    1, 1, OPF_JMP|OPF_CC }, // 71 OF=0
509   { "jc",   OP_JC,     1, 1, OPF_JMP|OPF_CC }, // 72 CF=1
510   { "jb",   OP_JC,     1, 1, OPF_JMP|OPF_CC }, // 72
511   { "jnc",  OP_JNC,    1, 1, OPF_JMP|OPF_CC }, // 73 CF=0
512   { "jnb",  OP_JNC,    1, 1, OPF_JMP|OPF_CC }, // 73
513   { "jae",  OP_JNC,    1, 1, OPF_JMP|OPF_CC }, // 73
514   { "jz",   OP_JZ,     1, 1, OPF_JMP|OPF_CC }, // 74 ZF=1
515   { "je",   OP_JZ,     1, 1, OPF_JMP|OPF_CC }, // 74
516   { "jnz",  OP_JNZ,    1, 1, OPF_JMP|OPF_CC }, // 75 ZF=0
517   { "jne",  OP_JNZ,    1, 1, OPF_JMP|OPF_CC }, // 75
518   { "jbe",  OP_JBE,    1, 1, OPF_JMP|OPF_CC }, // 76 CF=1 || ZF=1
519   { "jna",  OP_JBE,    1, 1, OPF_JMP|OPF_CC }, // 76
520   { "ja",   OP_JA,     1, 1, OPF_JMP|OPF_CC }, // 77 CF=0 && ZF=0
521   { "jnbe", OP_JA,     1, 1, OPF_JMP|OPF_CC }, // 77
522   { "js",   OP_JS,     1, 1, OPF_JMP|OPF_CC }, // 78 SF=1
523   { "jns",  OP_JNS,    1, 1, OPF_JMP|OPF_CC }, // 79 SF=0
524   { "jp",   OP_JP,     1, 1, OPF_JMP|OPF_CC }, // 7a PF=1
525   { "jpe",  OP_JP,     1, 1, OPF_JMP|OPF_CC }, // 7a
526   { "jnp",  OP_JNP,    1, 1, OPF_JMP|OPF_CC }, // 7b PF=0
527   { "jpo",  OP_JNP,    1, 1, OPF_JMP|OPF_CC }, // 7b
528   { "jl",   OP_JL,     1, 1, OPF_JMP|OPF_CC }, // 7c SF!=OF
529   { "jnge", OP_JL,     1, 1, OPF_JMP|OPF_CC }, // 7c
530   { "jge",  OP_JGE,    1, 1, OPF_JMP|OPF_CC }, // 7d SF=OF
531   { "jnl",  OP_JGE,    1, 1, OPF_JMP|OPF_CC }, // 7d
532   { "jle",  OP_JLE,    1, 1, OPF_JMP|OPF_CC }, // 7e ZF=1 || SF!=OF
533   { "jng",  OP_JLE,    1, 1, OPF_JMP|OPF_CC }, // 7e
534   { "jg",   OP_JG,     1, 1, OPF_JMP|OPF_CC }, // 7f ZF=0 && SF=OF
535   { "jnle", OP_JG,     1, 1, OPF_JMP|OPF_CC }, // 7f
536   { "seto",   OP_JO,   1, 1, OPF_DATA|OPF_CC },
537   { "setno",  OP_JNO,  1, 1, OPF_DATA|OPF_CC },
538   { "setc",   OP_JC,   1, 1, OPF_DATA|OPF_CC },
539   { "setb",   OP_JC,   1, 1, OPF_DATA|OPF_CC },
540   { "setnc",  OP_JNC,  1, 1, OPF_DATA|OPF_CC },
541   { "setae",  OP_JNC,  1, 1, OPF_DATA|OPF_CC },
542   { "setz",   OP_JZ,   1, 1, OPF_DATA|OPF_CC },
543   { "sete",   OP_JZ,   1, 1, OPF_DATA|OPF_CC },
544   { "setnz",  OP_JNZ,  1, 1, OPF_DATA|OPF_CC },
545   { "setne",  OP_JNZ,  1, 1, OPF_DATA|OPF_CC },
546   { "setbe",  OP_JBE,  1, 1, OPF_DATA|OPF_CC },
547   { "setna",  OP_JBE,  1, 1, OPF_DATA|OPF_CC },
548   { "seta",   OP_JA,   1, 1, OPF_DATA|OPF_CC },
549   { "setnbe", OP_JA,   1, 1, OPF_DATA|OPF_CC },
550   { "sets",   OP_JS,   1, 1, OPF_DATA|OPF_CC },
551   { "setns",  OP_JNS,  1, 1, OPF_DATA|OPF_CC },
552   { "setp",   OP_JP,   1, 1, OPF_DATA|OPF_CC },
553   { "setpe",  OP_JP,   1, 1, OPF_DATA|OPF_CC },
554   { "setnp",  OP_JNP,  1, 1, OPF_DATA|OPF_CC },
555   { "setpo",  OP_JNP,  1, 1, OPF_DATA|OPF_CC },
556   { "setl",   OP_JL,   1, 1, OPF_DATA|OPF_CC },
557   { "setnge", OP_JL,   1, 1, OPF_DATA|OPF_CC },
558   { "setge",  OP_JGE,  1, 1, OPF_DATA|OPF_CC },
559   { "setnl",  OP_JGE,  1, 1, OPF_DATA|OPF_CC },
560   { "setle",  OP_JLE,  1, 1, OPF_DATA|OPF_CC },
561   { "setng",  OP_JLE,  1, 1, OPF_DATA|OPF_CC },
562   { "setg",   OP_JG,   1, 1, OPF_DATA|OPF_CC },
563   { "setnle", OP_JG,   1, 1, OPF_DATA|OPF_CC },
564 };
565
566 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
567 {
568   enum opr_lenmod lmod;
569   int prefix_flags = 0;
570   int regmask_ind;
571   int regmask;
572   int op_w = 0;
573   int opr = 0;
574   int w = 0;
575   int i;
576
577   for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
578     if (IS(words[w], pref_table[i].name)) {
579       prefix_flags = pref_table[i].flags;
580       break;
581     }
582   }
583
584   if (prefix_flags) {
585     if (wordc <= 1)
586       aerr("lone prefix: '%s'\n", words[0]);
587     w++;
588   }
589
590   op_w = w;
591   for (i = 0; i < ARRAY_SIZE(op_table); i++) {
592     if (IS(words[w], op_table[i].name))
593       break;
594   }
595
596   if (i == ARRAY_SIZE(op_table))
597     aerr("unhandled op: '%s'\n", words[0]);
598   w++;
599
600   op->op = op_table[i].op;
601   op->flags = op_table[i].flags | prefix_flags;
602   op->regmask_src = op->regmask_dst = 0;
603
604   for (opr = 0; opr < op_table[i].minopr; opr++) {
605     regmask = regmask_ind = 0;
606     w = parse_operand(&op->operand[opr], &regmask, &regmask_ind,
607       words, wordc, w, op->flags);
608
609     if (opr == 0 && (op->flags & OPF_DATA))
610       op->regmask_dst = regmask;
611     // for now, mark dst as src too
612     op->regmask_src |= regmask | regmask_ind;
613   }
614
615   for (; w < wordc && opr < op_table[i].maxopr; opr++) {
616     w = parse_operand(&op->operand[opr],
617       &op->regmask_src, &op->regmask_src,
618       words, wordc, w, op->flags);
619   }
620
621   if (w < wordc)
622     aerr("parse_op %s incomplete: %d/%d\n",
623       words[0], w, wordc);
624
625   // special cases
626   op->operand_cnt = opr;
627   if (!strncmp(op_table[i].name, "set", 3))
628     op->operand[0].lmod = OPLM_BYTE;
629
630   // ops with implicit argumets
631   switch (op->op) {
632   case OP_CDQ:
633     op->operand_cnt = 2;
634     setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
635     setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
636     break;
637
638   case OP_STOS:
639     if (op->operand_cnt != 0)
640       break;
641     if      (IS(words[op_w], "stosb"))
642       lmod = OPLM_BYTE;
643     else if (IS(words[op_w], "stosw"))
644       lmod = OPLM_WORD;
645     else if (IS(words[op_w], "stosd"))
646       lmod = OPLM_DWORD;
647     op->operand_cnt = 3;
648     setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_dst);
649     setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_dst);
650     setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
651     break;
652
653   case OP_IMUL:
654     if (op->operand_cnt != 1)
655       break;
656     // fallthrough
657   case OP_MUL:
658     // singleop mul
659     op->regmask_dst = (1 << xDX) | (1 << xAX);
660     op->regmask_src |= (1 << xAX);
661     if (op->operand[0].lmod == OPLM_UNSPEC)
662       op->operand[0].lmod = OPLM_DWORD;
663     break;
664
665   case OP_DIV:
666   case OP_IDIV:
667     // we could set up operands for edx:eax, but there is no real need to
668     // (see is_opr_modified())
669     regmask = (1 << xDX) | (1 << xAX);
670     op->regmask_dst = regmask;
671     op->regmask_src |= regmask;
672     if (op->operand[0].lmod == OPLM_UNSPEC)
673       op->operand[0].lmod = OPLM_DWORD;
674     break;
675
676   case OP_SHL:
677   case OP_SHR:
678   case OP_SAR:
679     if (op->operand[1].lmod == OPLM_UNSPEC)
680       op->operand[1].lmod = OPLM_BYTE;
681     break;
682
683   default:
684     break;
685   }
686 }
687
688 static const char *op_name(enum op_op op)
689 {
690   int i;
691
692   for (i = 0; i < ARRAY_SIZE(op_table); i++)
693     if (op_table[i].op == op)
694       return op_table[i].name;
695
696   return "???";
697 }
698
699 // debug
700 static const char *dump_op(struct parsed_op *po)
701 {
702   static char out[128];
703   char *p = out;
704   int i;
705
706   snprintf(out, sizeof(out), "%s", op_name(po->op));
707   for (i = 0; i < po->operand_cnt; i++) {
708     p += strlen(p);
709     if (i > 0)
710       *p++ = ',';
711     snprintf(p, sizeof(out) - (p - out),
712       po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
713       po->operand[i].name);
714   }
715
716   return out;
717 }
718
719 static const char *opr_name(struct parsed_op *po, int opr_num)
720 {
721   if (opr_num >= po->operand_cnt)
722     ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
723   return po->operand[opr_num].name;
724 }
725
726 static unsigned int opr_const(struct parsed_op *po, int opr_num)
727 {
728   if (opr_num >= po->operand_cnt)
729     ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
730   if (po->operand[opr_num].type != OPT_CONST)
731     ferr(po, "opr %d: const expected\n", opr_num);
732   return po->operand[opr_num].val;
733 }
734
735 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
736 {
737   if ((unsigned int)popr->reg >= MAX_REGS)
738     ferr(po, "invalid reg: %d\n", popr->reg);
739   return regs_r32[popr->reg];
740 }
741
742 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name)
743 {
744   int i;
745
746   for (i = 0; i < g_eqcnt; i++)
747     if (IS(g_eqs[i].name, name))
748       break;
749   if (i >= g_eqcnt) {
750     if (po != NULL)
751       ferr(po, "unresolved equ name: '%s'\n", name);
752     return NULL;
753   }
754
755   return &g_eqs[i];
756 }
757
758 static void bg_frame_access(struct parsed_op *po, enum opr_lenmod lmod,
759   char *buf, size_t buf_size, const char *bp_arg,
760   int is_src, int is_lea)
761 {
762   const char *prefix = "";
763   struct parsed_equ *eq;
764   int i, arg_i, arg_s;
765   int sf_ofs;
766
767   snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
768
769   eq = equ_find(po, bp_arg);
770
771   if (eq->offset >= 0) {
772     arg_i = eq->offset / 4 - 2;
773     if (arg_i < 0 || arg_i >= g_func_pp.argc_stack)
774       ferr(po, "offset %d doesn't map to any arg\n", eq->offset);
775
776     for (i = arg_s = 0; i < g_func_pp.argc; i++) {
777       if (g_func_pp.arg[i].reg != NULL)
778         continue;
779       if (arg_s == arg_i)
780         break;
781       arg_s++;
782     }
783     if (i == g_func_pp.argc)
784       ferr(po, "arg %d not in prototype?\n", arg_i);
785     if (is_lea)
786       ferr(po, "lea to arg?\n");
787
788     snprintf(buf, buf_size, "%sa%d", is_src ? "(u32)" : "", i + 1);
789   }
790   else {
791     if (g_bp_stack == 0)
792       ferr(po, "bp_stack access after it was not detected\n");
793
794     sf_ofs = g_bp_stack + eq->offset;
795     if (sf_ofs < 0)
796       ferr(po, "bp_stack offset %d/%d\n", eq->offset, g_bp_stack);
797
798     if (is_lea)
799       prefix = "(u32)&";
800
801     switch (lmod)
802     {
803     case OPLM_BYTE:
804       snprintf(buf, buf_size, "%ssf.b[%d]", prefix, sf_ofs);
805       break;
806     case OPLM_WORD:
807       snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
808       break;
809     case OPLM_DWORD:
810       snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
811       break;
812     default:
813       ferr(po, "bp_stack bad lmod: %d\n", lmod);
814     }
815   }
816 }
817
818 static char *out_src_opr(char *buf, size_t buf_size,
819         struct parsed_op *po, struct parsed_opr *popr, int is_lea)
820 {
821   const char *cast = "";
822   char tmp1[256], tmp2[256];
823   char expr[256];
824   int ret;
825
826   switch (popr->type) {
827   case OPT_REG:
828     if (is_lea)
829       ferr(po, "lea from reg?\n");
830
831     switch (popr->lmod) {
832     case OPLM_DWORD:
833       snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
834       break;
835     case OPLM_WORD:
836       snprintf(buf, buf_size, "(u16)%s", opr_reg_p(po, popr));
837       break;
838     case OPLM_BYTE:
839       if (popr->name[1] == 'h') // XXX..
840         snprintf(buf, buf_size, "(u8)(%s >> 8)", opr_reg_p(po, popr));
841       else
842         snprintf(buf, buf_size, "(u8)%s", opr_reg_p(po, popr));
843       break;
844     default:
845       ferr(po, "invalid src lmod: %d\n", popr->lmod);
846     }
847     break;
848
849   case OPT_REGMEM:
850     if (g_bp_frame && !strncmp(popr->name, "ebp+", 4)) {
851       bg_frame_access(po, popr->lmod, buf, buf_size,
852         popr->name + 4, 1, is_lea);
853       break;
854     }
855
856     strcpy(expr, popr->name);
857     if (strchr(expr, '[')) {
858       // special case: '[' can only be left for label[reg] form
859       ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
860       if (ret != 2)
861         ferr(po, "parse failure for '%s'\n", expr);
862       snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
863     }
864
865     // XXX: do we need more parsing?
866     if (is_lea) {
867       snprintf(buf, buf_size, "%s", expr);
868       break;
869     }
870
871     switch (popr->lmod) {
872     case OPLM_DWORD:
873       cast = "*(u32 *)";
874       break;
875     case OPLM_WORD:
876       cast = "*(u16 *)";
877       break;
878     case OPLM_BYTE:
879       cast = "*(u8 *)";
880       break;
881     default:
882       ferr(po, "invalid lmod: %d\n", popr->lmod);
883     }
884     snprintf(buf, buf_size, "%s(%s)", cast, expr);
885     break;
886
887   case OPT_LABEL:
888     if (is_lea)
889       snprintf(buf, buf_size, "(u32)&%s", popr->name);
890     else
891       snprintf(buf, buf_size, "(u32)%s", popr->name);
892     break;
893
894   case OPT_OFFSET:
895     if (is_lea)
896       ferr(po, "lea an offset?\n");
897     snprintf(buf, buf_size, "(u32)&%s", popr->name);
898     break;
899
900   case OPT_CONST:
901     if (is_lea)
902       ferr(po, "lea from const?\n");
903
904     printf_number(buf, buf_size, popr->val);
905     break;
906
907   default:
908     ferr(po, "invalid src type: %d\n", popr->type);
909   }
910
911   return buf;
912 }
913
914 static char *out_dst_opr(char *buf, size_t buf_size,
915         struct parsed_op *po, struct parsed_opr *popr)
916 {
917   switch (popr->type) {
918   case OPT_REG:
919     switch (popr->lmod) {
920     case OPLM_DWORD:
921       snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
922       break;
923     case OPLM_WORD:
924       // ugh..
925       snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
926       break;
927     case OPLM_BYTE:
928       // ugh..
929       if (popr->name[1] == 'h') // XXX..
930         snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
931       else
932         snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
933       break;
934     default:
935       ferr(po, "invalid dst lmod: %d\n", popr->lmod);
936     }
937     break;
938
939   case OPT_REGMEM:
940     if (g_bp_frame && !strncmp(popr->name, "ebp+", 4)) {
941       bg_frame_access(po, popr->lmod, buf, buf_size,
942         popr->name + 4, 0, 0);
943       break;
944     }
945
946     return out_src_opr(buf, buf_size, po, popr, 0);
947
948   default:
949     ferr(po, "invalid dst type: %d\n", popr->type);
950   }
951
952   return buf;
953 }
954
955 static const char *lmod_cast_u(struct parsed_op *po,
956   enum opr_lenmod lmod)
957 {
958   switch (lmod) {
959   case OPLM_DWORD:
960     return "";
961   case OPLM_WORD:
962     return "(u16)";
963   case OPLM_BYTE:
964     return "(u8)";
965   default:
966     ferr(po, "invalid lmod: %d\n", lmod);
967     return "(_invalid_)";
968   }
969 }
970
971 static const char *lmod_cast_s(struct parsed_op *po,
972   enum opr_lenmod lmod)
973 {
974   switch (lmod) {
975   case OPLM_DWORD:
976     return "(s32)";
977   case OPLM_WORD:
978     return "(s16)";
979   case OPLM_BYTE:
980     return "(s8)";
981   default:
982     ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
983     return "(_invalid_)";
984   }
985 }
986
987 static const char *lmod_cast(struct parsed_op *po,
988   enum opr_lenmod lmod, int is_signed)
989 {
990   return is_signed ?
991     lmod_cast_s(po, lmod) :
992     lmod_cast_u(po, lmod);
993 }
994
995 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
996 {
997   switch (lmod) {
998   case OPLM_DWORD:
999     return 4;
1000   case OPLM_WORD:
1001     return 2;
1002   case OPLM_BYTE:
1003     return 1;
1004   default:
1005     ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1006     return 0;
1007   }
1008 }
1009
1010 static enum parsed_flag_op split_cond(struct parsed_op *po,
1011   enum op_op op, int *is_inv)
1012 {
1013   *is_inv = 0;
1014
1015   switch (op) {
1016   case OP_JO:
1017     return PFO_O;
1018   case OP_JC:
1019     return PFO_C;
1020   case OP_JZ:
1021     return PFO_Z;
1022   case OP_JBE:
1023     return PFO_BE;
1024   case OP_JS:
1025     return PFO_S;
1026   case OP_JP:
1027     return PFO_P;
1028   case OP_JL:
1029     return PFO_L;
1030   case OP_JLE:
1031     return PFO_LE;
1032
1033   case OP_JNO:
1034     *is_inv = 1;
1035     return PFO_O;
1036   case OP_JNC:
1037     *is_inv = 1;
1038     return PFO_C;
1039   case OP_JNZ:
1040     *is_inv = 1;
1041     return PFO_Z;
1042   case OP_JA:
1043     *is_inv = 1;
1044     return PFO_BE;
1045   case OP_JNS:
1046     *is_inv = 1;
1047     return PFO_S;
1048   case OP_JNP:
1049     *is_inv = 1;
1050     return PFO_P;
1051   case OP_JGE:
1052     *is_inv = 1;
1053     return PFO_L;
1054   case OP_JG:
1055     *is_inv = 1;
1056     return PFO_LE;
1057
1058   case OP_ADC:
1059   case OP_SBB:
1060     return PFO_C;
1061
1062   default:
1063     ferr(po, "split_cond: bad op %d\n", op);
1064     return -1;
1065   }
1066 }
1067
1068 static void out_test_for_cc(char *buf, size_t buf_size,
1069   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1070   enum opr_lenmod lmod, const char *expr)
1071 {
1072   const char *cast, *scast;
1073
1074   cast = lmod_cast_u(po, lmod);
1075   scast = lmod_cast_s(po, lmod);
1076
1077   switch (pfo) {
1078   case PFO_Z:
1079   case PFO_BE: // CF=1||ZF=1; CF=0
1080     snprintf(buf, buf_size, "(%s%s %s 0)",
1081       cast, expr, is_inv ? "!=" : "==");
1082     break;
1083
1084   case PFO_S:
1085   case PFO_L: // SF!=OF; OF=0
1086     snprintf(buf, buf_size, "(%s%s %s 0)",
1087       scast, expr, is_inv ? ">=" : "<");
1088     break;
1089
1090   case PFO_LE: // ZF=1||SF!=OF; OF=0
1091     snprintf(buf, buf_size, "(%s%s %s 0)",
1092       scast, expr, is_inv ? ">" : "<=");
1093     break;
1094
1095   default:
1096     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1097   }
1098 }
1099
1100 static void out_cmp_for_cc(char *buf, size_t buf_size,
1101   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1102   enum opr_lenmod lmod, const char *expr1, const char *expr2)
1103 {
1104   const char *cast, *scast;
1105
1106   cast = lmod_cast_u(po, lmod);
1107   scast = lmod_cast_s(po, lmod);
1108
1109   switch (pfo) {
1110   case PFO_C:
1111     // note: must be unsigned compare
1112     snprintf(buf, buf_size, "(%s%s %s %s%s)",
1113       cast, expr1, is_inv ? ">=" : "<", cast, expr2);
1114     break;
1115
1116   case PFO_Z:
1117     snprintf(buf, buf_size, "(%s%s %s %s%s)",
1118       cast, expr1, is_inv ? "!=" : "==", cast, expr2);
1119     break;
1120
1121   case PFO_BE: // !a
1122     // note: must be unsigned compare
1123     snprintf(buf, buf_size, "(%s%s %s %s%s)",
1124       cast, expr1, is_inv ? ">" : "<=", cast, expr2);
1125     break;
1126
1127   // note: must be signed compare
1128   case PFO_S:
1129     snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1130       scast, expr1, expr2, is_inv ? ">=" : "<");
1131     break;
1132
1133   case PFO_L: // !ge
1134     snprintf(buf, buf_size, "(%s%s %s %s%s)",
1135       scast, expr1, is_inv ? ">=" : "<", scast, expr2);
1136     break;
1137
1138   case PFO_LE:
1139     snprintf(buf, buf_size, "(%s%s %s %s%s)",
1140       scast, expr1, is_inv ? ">" : "<=", scast, expr2);
1141     break;
1142
1143   default:
1144     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1145   }
1146 }
1147
1148 static void out_cmp_test(char *buf, size_t buf_size,
1149   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1150 {
1151   char buf1[256], buf2[256], buf3[256];
1152
1153   if (po->op == OP_TEST) {
1154     if (IS(opr_name(po, 0), opr_name(po, 1))) {
1155       out_src_opr(buf3, sizeof(buf3), po, &po->operand[0], 0);
1156     }
1157     else {
1158       out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], 0);
1159       out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 0);
1160       snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1161     }
1162     out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1163       po->operand[0].lmod, buf3);
1164   }
1165   else if (po->op == OP_CMP) {
1166     out_src_opr(buf2, sizeof(buf2), po, &po->operand[0], 0);
1167     out_src_opr(buf3, sizeof(buf3), po, &po->operand[1], 0);
1168     out_cmp_for_cc(buf, buf_size, po, pfo, is_inv,
1169       po->operand[0].lmod, buf2, buf3);
1170   }
1171   else
1172     ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1173 }
1174
1175 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1176         struct parsed_opr *popr2)
1177 {
1178   if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1179     ferr(po, "missing lmod for both operands\n");
1180
1181   if (popr1->lmod == OPLM_UNSPEC)
1182     popr1->lmod = popr2->lmod;
1183   else if (popr2->lmod == OPLM_UNSPEC)
1184     popr2->lmod = popr1->lmod;
1185   else if (popr1->lmod != popr2->lmod)
1186     ferr(po, "conflicting lmods: %d vs %d\n", popr1->lmod, popr2->lmod);
1187 }
1188
1189 static const char *op_to_c(struct parsed_op *po)
1190 {
1191   switch (po->op)
1192   {
1193     case OP_ADD:
1194     case OP_ADC:
1195       return "+";
1196     case OP_SUB:
1197     case OP_SBB:
1198       return "-";
1199     case OP_AND:
1200       return "&";
1201     case OP_OR:
1202       return "|";
1203     case OP_XOR:
1204       return "^";
1205     case OP_SHL:
1206       return "<<";
1207     case OP_SHR:
1208       return ">>";
1209     case OP_MUL:
1210     case OP_IMUL:
1211       return "*";
1212     default:
1213       ferr(po, "op_to_c was supplied with %d\n", po->op);
1214   }
1215 }
1216
1217 static int scan_for_pop(int i, int opcnt, const char *reg,
1218   int magic, int do_patch)
1219 {
1220   struct parsed_op *po;
1221   int ret = 0;
1222
1223   for (; i < opcnt; i++) {
1224     po = &ops[i];
1225     if (po->cc_scratch == magic)
1226       break; // already checked
1227     po->cc_scratch = magic;
1228
1229     if (po->flags & OPF_TAIL)
1230       return -1; // deadend
1231
1232     if (po->flags & OPF_RMD)
1233       continue;
1234
1235     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1236       if (po->bt_i < 0) {
1237         ferr(po, "dead branch\n");
1238         return -1;
1239       }
1240
1241       if (po->flags & OPF_CC) {
1242         ret |= scan_for_pop(po->bt_i, opcnt, reg, magic, do_patch);
1243         if (ret < 0)
1244           return ret; // dead end
1245       }
1246       else {
1247         i = po->bt_i - 1;
1248       }
1249       continue;
1250     }
1251
1252     if (po->op == OP_POP && po->operand[0].type == OPT_REG
1253         && IS(po->operand[0].name, reg))
1254     {
1255       if (do_patch)
1256         po->flags |= OPF_RMD;
1257       return 1;
1258     }
1259   }
1260
1261   return ret;
1262 }
1263
1264 // scan for pop starting from 'ret' op (all paths)
1265 static int scan_for_pop_ret(int i, int opcnt, const char *reg, int do_patch)
1266 {
1267   int found = 0;
1268   int j;
1269
1270   for (; i < opcnt; i++) {
1271     if (!(ops[i].flags & OPF_TAIL))
1272       continue;
1273
1274     for (j = i - 1; j >= 0; j--) {
1275       if (ops[j].flags & OPF_RMD)
1276         continue;
1277       if (ops[j].flags & OPF_JMP)
1278         return -1;
1279
1280       if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
1281           && IS(ops[j].operand[0].name, reg))
1282       {
1283         found = 1;
1284         if (do_patch)
1285           ops[j].flags |= OPF_RMD;
1286         break;
1287       }
1288
1289       if (g_labels[j][0] != 0)
1290         return -1;
1291     }
1292   }
1293
1294   return found ? 0 : -1;
1295 }
1296
1297 // is operand 'opr modified' by parsed_op 'po'?
1298 static int is_opr_modified(const struct parsed_opr *opr,
1299   const struct parsed_op *po)
1300 {
1301   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
1302     return 0;
1303
1304   if (opr->type == OPT_REG && po->operand[0].type == OPT_REG) {
1305     if (po->regmask_dst & (1 << opr->reg))
1306       return 1;
1307     else
1308       return 0;
1309   }
1310
1311   return IS(po->operand[0].name, opr->name);
1312 }
1313
1314 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
1315 static int is_any_opr_modified(const struct parsed_op *po_test,
1316   const struct parsed_op *po)
1317 {
1318   int i;
1319
1320   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
1321     return 0;
1322
1323   if (po_test->regmask_src & po->regmask_dst)
1324     return 1;
1325
1326   for (i = 0; i < po_test->operand_cnt; i++)
1327     if (IS(po_test->operand[i].name, po->operand[0].name))
1328       return 1;
1329
1330   return 0;
1331 }
1332
1333 // scan for any po_test operand modification in range given
1334 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt)
1335 {
1336   for (; i < opcnt; i++) {
1337     if (is_any_opr_modified(po_test, &ops[i]))
1338       return i;
1339   }
1340
1341   return -1;
1342 }
1343
1344 // scan for po_test operand[0] modification in range given
1345 static int scan_for_mod_opr0(struct parsed_op *po_test,
1346   int i, int opcnt)
1347 {
1348   for (; i < opcnt; i++) {
1349     if (is_opr_modified(&po_test->operand[0], &ops[i]))
1350       return i;
1351   }
1352
1353   return -1;
1354 }
1355
1356 static int scan_for_flag_set(int i)
1357 {
1358   for (; i >= 0; i--) {
1359     if (ops[i].flags & OPF_FLAGS)
1360       return i;
1361
1362     if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
1363       return -1;
1364     if (g_labels[i][0] != 0)
1365       return -1;
1366   }
1367
1368   return -1;
1369 }
1370
1371 // scan back for cdq, if anything modifies edx, fail
1372 static int scan_for_cdq_edx(int i)
1373 {
1374   for (; i >= 0; i--) {
1375     if (ops[i].op == OP_CDQ)
1376       return i;
1377
1378     if (ops[i].regmask_dst & (1 << xDX))
1379       return -1;
1380     if (g_labels[i][0] != 0)
1381       return -1;
1382   }
1383
1384   return -1;
1385 }
1386
1387 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
1388 {
1389   struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
1390   struct parsed_opr *last_arith_dst = NULL;
1391   char buf1[256], buf2[256], buf3[256];
1392   struct parsed_proto *pp, *pp_tmp;
1393   const char *tmpname;
1394   enum parsed_flag_op pfo;
1395   int save_arg_vars = 0;
1396   int cmp_result_vars = 0;
1397   int need_mul_var = 0;
1398   int had_decl = 0;
1399   int regmask_arg = 0;
1400   int regmask = 0;
1401   int pfomask = 0;
1402   int no_output;
1403   int dummy;
1404   int arg;
1405   int i, j;
1406   int reg;
1407   int ret;
1408
1409   g_bp_frame = g_bp_stack = 0;
1410
1411   ret = proto_parse(fhdr, funcn, &g_func_pp);
1412   if (ret)
1413     ferr(ops, "proto_parse failed for '%s'\n", funcn);
1414
1415   fprintf(fout, "%s %s(", g_func_pp.ret_type, funcn);
1416   for (i = 0; i < g_func_pp.argc; i++) {
1417     if (i > 0)
1418       fprintf(fout, ", ");
1419     fprintf(fout, "%s a%d", g_func_pp.arg[i].type, i + 1);
1420   }
1421   fprintf(fout, ")\n{\n");
1422
1423   // pass1:
1424   // - handle ebp frame, remove ops related to it
1425   if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
1426       && ops[1].op == OP_MOV
1427       && IS(opr_name(&ops[1], 0), "ebp")
1428       && IS(opr_name(&ops[1], 1), "esp"))
1429   {
1430     int ecx_push = 0;
1431
1432     g_bp_frame = 1;
1433     ops[0].flags |= OPF_RMD;
1434     ops[1].flags |= OPF_RMD;
1435
1436     if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
1437       g_bp_stack = opr_const(&ops[2], 1);
1438       ops[2].flags |= OPF_RMD;
1439     }
1440     else {
1441       // another way msvc builds stack frame..
1442       i = 2;
1443       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
1444         g_bp_stack += 4;
1445         ops[i].flags |= OPF_RMD;
1446         ecx_push++;
1447         i++;
1448       }
1449     }
1450
1451     i = 2;
1452     do {
1453       for (; i < opcnt; i++)
1454         if (ops[i].op == OP_RET)
1455           break;
1456       if (ops[i - 1].op != OP_POP || !IS(opr_name(&ops[i - 1], 0), "ebp"))
1457         ferr(&ops[i - 1], "'pop ebp' expected\n");
1458       ops[i - 1].flags |= OPF_RMD;
1459
1460       if (g_bp_stack != 0) {
1461         if (ops[i - 2].op != OP_MOV
1462             || !IS(opr_name(&ops[i - 2], 0), "esp")
1463             || !IS(opr_name(&ops[i - 2], 1), "ebp"))
1464         {
1465           ferr(&ops[i - 2], "esp restore expected\n");
1466         }
1467         ops[i - 2].flags |= OPF_RMD;
1468
1469         if (ecx_push && ops[i - 3].op == OP_POP
1470           && IS(opr_name(&ops[i - 3], 0), "ecx"))
1471         {
1472           ferr(&ops[i - 3], "unexpected ecx pop\n");
1473         }
1474       }
1475
1476       i++;
1477     } while (i < opcnt);
1478   }
1479
1480   // pass2:
1481   // - resolve all branches
1482   for (i = 0; i < opcnt; i++) {
1483     po = &ops[i];
1484     po->bt_i = -1;
1485
1486     if ((po->flags & OPF_RMD) || !(po->flags & OPF_JMP)
1487         || po->op == OP_CALL || po->op == OP_RET)
1488       continue;
1489
1490     for (j = 0; j < opcnt; j++) {
1491       if (g_labels[j][0] && IS(po->operand[0].name, g_labels[j])) {
1492         po->bt_i = j;
1493         po->lrl = g_label_refs[j];
1494         g_label_refs[j] = po;
1495         break;
1496       }
1497     }
1498
1499     if (po->bt_i == -1) {
1500       // assume tail call
1501       po->op = OP_CALL;
1502       po->flags |= OPF_TAIL;
1503     }
1504   }
1505
1506   // pass3:
1507   // - find POPs for PUSHes, rm both
1508   // - scan for all used registers
1509   // - find flag set ops for their users
1510   // - process calls
1511   for (i = 0; i < opcnt; i++) {
1512     po = &ops[i];
1513     if (po->flags & OPF_RMD)
1514       continue;
1515
1516     if (po->op == OP_PUSH && po->operand[0].type == OPT_REG) {
1517       if (po->operand[0].reg < 0)
1518         ferr(po, "reg not set for push?\n");
1519       if (!(regmask & (1 << po->operand[0].reg))) { // reg save
1520         ret = scan_for_pop(i + 1, opcnt,
1521                 po->operand[0].name, i + opcnt, 0);
1522         if (ret == 1) {
1523           po->flags |= OPF_RMD;
1524           scan_for_pop(i + 1, opcnt, po->operand[0].name,
1525             i + opcnt * 2, 1);
1526           continue;
1527         }
1528         ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
1529         if (ret == 0) {
1530           po->flags |= OPF_RMD;
1531           scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 1);
1532           continue;
1533         }
1534       }
1535     }
1536
1537     regmask |= po->regmask_src | po->regmask_dst;
1538
1539     if (po->flags & OPF_CC)
1540     {
1541       ret = scan_for_flag_set(i - 1);
1542       if (ret < 0)
1543         ferr(po, "unable to trace flag setter\n");
1544
1545       tmp_op = &ops[ret]; // flag setter
1546       pfo = split_cond(po, po->op, &dummy);
1547       pfomask = 0;
1548
1549       // to get nicer code, we try to delay test and cmp;
1550       // if we can't because of operand modification, or if we
1551       // have math op, make it calculate flags explicitly
1552       if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
1553         if (scan_for_mod(tmp_op, ret + 1, i) >= 0)
1554           pfomask = 1 << pfo;
1555       }
1556       else {
1557         if ((pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
1558             || scan_for_mod_opr0(tmp_op, ret + 1, i) >= 0)
1559           pfomask = 1 << pfo;
1560       }
1561       if (pfomask) {
1562         tmp_op->pfomask |= pfomask;
1563         cmp_result_vars |= pfomask;
1564         po->datap = tmp_op;
1565       }
1566
1567       if (po->op == OP_ADC || po->op == OP_SBB)
1568         cmp_result_vars |= 1 << PFO_C;
1569     }
1570     else if (po->op == OP_CALL)
1571     {
1572       pp = malloc(sizeof(*pp));
1573       my_assert_not(pp, NULL);
1574       tmpname = opr_name(&ops[i], 0);
1575       ret = proto_parse(fhdr, tmpname, pp);
1576       if (ret)
1577         ferr(po, "proto_parse failed for '%s'\n", tmpname);
1578
1579       for (arg = 0; arg < pp->argc; arg++)
1580         if (pp->arg[arg].reg == NULL)
1581           break;
1582
1583       for (j = i - 1; j >= 0 && arg < pp->argc; j--) {
1584         if (ops[j].op == OP_CALL) {
1585           pp_tmp = ops[j].datap;
1586           if (pp_tmp == NULL)
1587             ferr(po, "arg collect hit unparsed call\n");
1588           if (pp_tmp->argc_stack > 0)
1589             ferr(po, "arg collect hit '%s' with %d stack args\n",
1590               opr_name(&ops[j], 0), pp_tmp->argc_stack);
1591         }
1592         else if ((ops[j].flags & OPF_TAIL)
1593             || (ops[j].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1594         {
1595           break;
1596         }
1597
1598         if (ops[j].op == OP_PUSH) {
1599           pp->arg[arg].datap = &ops[j];
1600           ret = scan_for_mod(&ops[j], j + 1, i);
1601           if (ret >= 0) {
1602             // mark this push as one that needs operand saving
1603             ops[j].argmask |= 1 << arg;
1604             save_arg_vars |= 1 << arg;
1605           }
1606           else
1607             ops[j].flags |= OPF_RMD;
1608
1609           // next arg
1610           for (arg++; arg < pp->argc; arg++)
1611             if (pp->arg[arg].reg == NULL)
1612               break;
1613         }
1614
1615         if (g_labels[j][0] != 0) {
1616           if (j > 0 && ((ops[j - 1].flags & OPF_TAIL)
1617             || (ops[j - 1].flags & (OPF_JMP|OPF_CC)) == OPF_JMP))
1618           {
1619             // follow the branch in reverse
1620             if (g_label_refs[j] == NULL)
1621               ferr(po, "no refs for '%s'?\n", g_labels[j]);
1622             if (g_label_refs[j]->lrl != NULL)
1623               ferr(po, "unhandled multiple fefs to '%s'\n", g_labels[j]);
1624             j = (g_label_refs[j] - ops) + 1;
1625             continue;
1626           }
1627           break;
1628         }
1629       }
1630       if (arg < pp->argc)
1631         ferr(po, "arg collect failed for '%s'\n", tmpname);
1632       po->datap = pp;
1633     }
1634     else if (po->op == OP_MUL
1635       || (po->op == OP_IMUL && po->operand_cnt == 1))
1636     {
1637       need_mul_var = 1;
1638     }
1639   }
1640
1641   // declare stack frame
1642   if (g_bp_stack)
1643     fprintf(fout, "  union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
1644       (g_bp_stack + 3) / 4, (g_bp_stack + 1) / 2, g_bp_stack);
1645
1646   // declare arg-registers
1647   for (i = 0; i < g_func_pp.argc; i++) {
1648     if (g_func_pp.arg[i].reg != NULL) {
1649       reg = char_array_i(regs_r32,
1650               ARRAY_SIZE(regs_r32), g_func_pp.arg[i].reg);
1651       if (reg < 0)
1652         ferr(ops, "arg '%s' is not a reg?\n", g_func_pp.arg[i].reg);
1653
1654       regmask_arg |= 1 << reg;
1655       fprintf(fout, "  u32 %s = (u32)a%d;\n",
1656         g_func_pp.arg[i].reg, i + 1);
1657       had_decl = 1;
1658     }
1659   }
1660
1661   // declare other regs - special case for eax
1662   if (!((regmask | regmask_arg) & 1) && !IS(g_func_pp.ret_type, "void")) {
1663     fprintf(fout, "  u32 eax = 0;\n");
1664     had_decl = 1;
1665   }
1666
1667   regmask &= ~regmask_arg;
1668   if (g_bp_frame)
1669     regmask &= ~(1 << xBP);
1670   if (regmask) {
1671     for (reg = 0; reg < 8; reg++) {
1672       if (regmask & (1 << reg)) {
1673         fprintf(fout, "  u32 %s;\n", regs_r32[reg]);
1674         had_decl = 1;
1675       }
1676     }
1677   }
1678
1679   if (save_arg_vars) {
1680     for (reg = 0; reg < 32; reg++) {
1681       if (save_arg_vars & (1 << reg)) {
1682         fprintf(fout, "  u32 s_a%d;\n", reg + 1);
1683         had_decl = 1;
1684       }
1685     }
1686   }
1687
1688   if (cmp_result_vars) {
1689     for (i = 0; i < 8; i++) {
1690       if (cmp_result_vars & (1 << i)) {
1691         fprintf(fout, "  u32 cond_%s;\n", parsed_flag_op_names[i]);
1692         had_decl = 1;
1693       }
1694     }
1695   }
1696
1697   if (need_mul_var) {
1698     fprintf(fout, "  u64 mul_tmp;\n");
1699     had_decl = 1;
1700   }
1701
1702   if (had_decl)
1703     fprintf(fout, "\n");
1704
1705   // output ops
1706   for (i = 0; i < opcnt; i++)
1707   {
1708     if (g_labels[i][0] != 0)
1709       fprintf(fout, "\n%s:\n", g_labels[i]);
1710
1711     po = &ops[i];
1712     if (po->flags & OPF_RMD)
1713       continue;
1714
1715     no_output = 0;
1716
1717     #define assert_operand_cnt(n_) \
1718       if (po->operand_cnt != n_) \
1719         ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
1720
1721     // conditional/flag using op?
1722     if (po->flags & OPF_CC)
1723     {
1724       int is_delayed = 0;
1725       int is_inv = 0;
1726
1727       pfo = split_cond(po, po->op, &is_inv);
1728
1729       // we go through all this trouble to avoid using parsed_flag_op,
1730       // which makes generated code much nicer
1731       if (delayed_flag_op != NULL)
1732       {
1733         out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
1734         is_delayed = 1;
1735       }
1736       else if (last_arith_dst != NULL
1737         && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P))
1738       {
1739         out_src_opr(buf3, sizeof(buf3), po, last_arith_dst, 0);
1740         out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
1741           last_arith_dst->lmod, buf3);
1742         is_delayed = 1;
1743       }
1744       else if (po->datap != NULL) {
1745         // use preprocessed results
1746         tmp_op = po->datap;
1747         if (!tmp_op || !(tmp_op->pfomask & (1 << pfo)))
1748           ferr(po, "not prepared for pfo %d\n", pfo);
1749
1750         // note: is_inv was not yet applied
1751         snprintf(buf1, sizeof(buf1), "(%scond_%s)",
1752           is_inv ? "!" : "", parsed_flag_op_names[pfo]);
1753       }
1754       else {
1755         ferr(po, "all methods of finding comparison failed\n");
1756       }
1757  
1758       if (po->flags & OPF_JMP) {
1759         fprintf(fout, "  if %s\n", buf1);
1760       }
1761       else if (po->op == OP_ADC || po->op == OP_SBB) {
1762         if (is_delayed)
1763           fprintf(fout, "  cond_%s = %s;\n",
1764             parsed_flag_op_names[pfo], buf1);
1765       }
1766       else if (po->flags & OPF_DATA) { // SETcc
1767         out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
1768         fprintf(fout, "  %s = %s;", buf2, buf1);
1769       }
1770       else {
1771         ferr(po, "unhandled conditional op\n");
1772       }
1773     }
1774
1775     pfomask = po->pfomask;
1776
1777     switch (po->op)
1778     {
1779       case OP_MOV:
1780         assert_operand_cnt(2);
1781         propagate_lmod(po, &po->operand[0], &po->operand[1]);
1782         fprintf(fout, "  %s = %s;",
1783             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
1784             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 0));
1785         break;
1786
1787       case OP_LEA:
1788         assert_operand_cnt(2);
1789         po->operand[1].lmod = OPLM_DWORD; // always
1790         fprintf(fout, "  %s = %s;",
1791             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
1792             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 1));
1793         break;
1794
1795       case OP_MOVZX:
1796         assert_operand_cnt(2);
1797         fprintf(fout, "  %s = %s;",
1798             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
1799             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 0));
1800         break;
1801
1802       case OP_MOVSX:
1803         assert_operand_cnt(2);
1804         switch (po->operand[1].lmod) {
1805         case OPLM_BYTE:
1806           strcpy(buf3, "(s8)");
1807           break;
1808         case OPLM_WORD:
1809           strcpy(buf3, "(s16)");
1810           break;
1811         default:
1812           ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
1813         }
1814         fprintf(fout, "  %s = %s%s;",
1815             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
1816             buf3,
1817             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 0));
1818         break;
1819
1820       case OP_NOT:
1821         assert_operand_cnt(1);
1822         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
1823         fprintf(fout, "  %s = ~%s;", buf1, buf1);
1824         break;
1825
1826       case OP_CDQ:
1827         assert_operand_cnt(2);
1828         fprintf(fout, "  %s = (s32)%s >> 31;",
1829             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
1830             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 0));
1831         strcpy(g_comment, "cdq");
1832         break;
1833
1834       case OP_STOS:
1835         // assumes DF=0
1836         assert_operand_cnt(3);
1837         if (po->flags & OPF_REP) {
1838           fprintf(fout, "  for (; ecx != 0; ecx--, edi += %d)\n",
1839             lmod_bytes(po, po->operand[0].lmod));
1840           fprintf(fout, "    *(u32 *)edi = eax;");
1841           strcpy(g_comment, "rep stos");
1842         }
1843         else {
1844           fprintf(fout, "    *(u32 *)edi = eax; edi += %d;",
1845             lmod_bytes(po, po->operand[0].lmod));
1846           strcpy(g_comment, "stos");
1847         }
1848         break;
1849
1850       // arithmetic w/flags
1851       case OP_ADD:
1852       case OP_SUB:
1853       case OP_AND:
1854       case OP_OR:
1855         propagate_lmod(po, &po->operand[0], &po->operand[1]);
1856         // fallthrough
1857       case OP_SHL:
1858       case OP_SHR:
1859       dualop_arith:
1860         assert_operand_cnt(2);
1861         fprintf(fout, "  %s %s= %s;",
1862             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
1863             op_to_c(po),
1864             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 0));
1865         last_arith_dst = &po->operand[0];
1866         delayed_flag_op = NULL;
1867         break;
1868
1869       case OP_XOR:
1870         assert_operand_cnt(2);
1871         propagate_lmod(po, &po->operand[0], &po->operand[1]);
1872         if (IS(opr_name(po, 0), opr_name(po, 1))) {
1873           // special case for XOR
1874           fprintf(fout, "  %s = 0;",
1875             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
1876           last_arith_dst = &po->operand[0];
1877           delayed_flag_op = NULL;
1878           break;
1879         }
1880         goto dualop_arith;
1881
1882       case OP_SAR:
1883         assert_operand_cnt(2);
1884         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
1885         fprintf(fout, "  %s = %s%s >> %s;", buf1,
1886           lmod_cast_s(po, po->operand[0].lmod), buf1,
1887           out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 0));
1888         last_arith_dst = &po->operand[0];
1889         delayed_flag_op = NULL;
1890         break;
1891
1892       case OP_ADC:
1893       case OP_SBB:
1894         assert_operand_cnt(2);
1895         propagate_lmod(po, &po->operand[0], &po->operand[1]);
1896         fprintf(fout, "  %s %s= %s + cond_c;",
1897             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
1898             op_to_c(po),
1899             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], 0));
1900         last_arith_dst = &po->operand[0];
1901         delayed_flag_op = NULL;
1902         break;
1903
1904       case OP_INC:
1905       case OP_DEC:
1906         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
1907         strcpy(buf2, po->op == OP_INC ? "++" : "--");
1908         fprintf(fout, "  %s%s;", buf1, buf2);
1909         last_arith_dst = &po->operand[0];
1910         delayed_flag_op = NULL;
1911         break;
1912
1913       case OP_NEG:
1914         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
1915         out_src_opr(buf2, sizeof(buf2), po, &po->operand[0], 0);
1916         fprintf(fout, "  %s = -%s%s;", buf1,
1917           lmod_cast_s(po, po->operand[0].lmod), buf2);
1918         last_arith_dst = &po->operand[0];
1919         delayed_flag_op = NULL;
1920         if (pfomask & (1 << PFO_C)) {
1921           fprintf(fout, "\n  cond_c = (%s != 0);", buf1);
1922           pfomask &= ~(1 << PFO_C);
1923         }
1924         break;
1925
1926       case OP_IMUL:
1927         if (po->operand_cnt == 2)
1928           goto dualop_arith;
1929         if (po->operand_cnt == 3)
1930           ferr(po, "TODO imul3\n");
1931         // fallthrough
1932       case OP_MUL:
1933         assert_operand_cnt(1);
1934         strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
1935         fprintf(fout, "  mul_tmp = %seax * %s%s;\n", buf1, buf1,
1936           out_src_opr(buf2, sizeof(buf2), po, &po->operand[0], 0));
1937         fprintf(fout, "  edx = mul_tmp >> 32;\n");
1938         fprintf(fout, "  eax = mul_tmp;");
1939         last_arith_dst = NULL;
1940         delayed_flag_op = NULL;
1941         break;
1942
1943       case OP_DIV:
1944       case OP_IDIV:
1945         assert_operand_cnt(1);
1946         if (po->operand[0].lmod != OPLM_DWORD)
1947           ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
1948
1949         // 32bit division is common, look for it
1950         if (scan_for_cdq_edx(i - 1) >= 0) {
1951           out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], 0);
1952           strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
1953             po->op == OP_IDIV));
1954           fprintf(fout, "  edx = %seax %% %s%s;\n", buf2, buf2, buf1);
1955           fprintf(fout, "  eax = %seax / %s%s;", buf2, buf2, buf1);
1956         }
1957         else
1958           ferr(po, "TODO 64bit divident\n");
1959         last_arith_dst = NULL;
1960         delayed_flag_op = NULL;
1961         break;
1962
1963       case OP_TEST:
1964       case OP_CMP:
1965         propagate_lmod(po, &po->operand[0], &po->operand[1]);
1966         if (pfomask != 0) {
1967           for (j = 0; j < 8; j++) {
1968             if (pfomask & (1 << j)) {
1969               out_cmp_test(buf1, sizeof(buf1), po, j, 0);
1970               fprintf(fout, "  cond_%s = %s;",
1971                 parsed_flag_op_names[j], buf1);
1972             }
1973           }
1974           pfomask = 0;
1975         }
1976         else
1977           no_output = 1;
1978         delayed_flag_op = po;
1979         break;
1980
1981       // note: we reuse OP_Jcc for SETcc, only flags differ
1982       case OP_JO ... OP_JG:
1983         if (po->flags & OPF_JMP)
1984           fprintf(fout, "    goto %s;", po->operand[0].name);
1985         // else SETcc - should already be handled
1986         break;
1987
1988       case OP_JMP:
1989         assert_operand_cnt(1);
1990         if (po->operand[0].type != OPT_LABEL)
1991           ferr(po, "unhandled call type\n");
1992
1993         fprintf(fout, "  goto %s;", po->operand[0].name);
1994         break;
1995
1996       case OP_CALL:
1997         assert_operand_cnt(1);
1998         if (po->operand[0].type != OPT_LABEL)
1999           ferr(po, "unhandled call type\n");
2000
2001         pp = po->datap;
2002         if (pp == NULL)
2003           ferr(po, "NULL pp\n");
2004
2005         fprintf(fout, "  ");
2006         if (!IS(pp->ret_type, "void")) {
2007           if (po->flags & OPF_TAIL)
2008             fprintf(fout, "return ");
2009           else
2010             fprintf(fout, "eax = ");
2011           if (strchr(pp->ret_type, '*'))
2012             fprintf(fout, "(u32)");
2013         }
2014
2015         fprintf(fout, "%s(", opr_name(po, 0));
2016         for (arg = 0; arg < pp->argc; arg++) {
2017           if (arg > 0)
2018             fprintf(fout, ", ");
2019
2020           if (strchr(pp->arg[arg].type, '*'))
2021             fprintf(fout, "(%s)", pp->arg[arg].type);
2022
2023           if (pp->arg[arg].reg != NULL) {
2024             fprintf(fout, "%s", pp->arg[arg].reg);
2025             continue;
2026           }
2027
2028           // stack arg
2029           tmp_op = pp->arg[arg].datap;
2030           if (tmp_op == NULL)
2031             ferr(po, "parsed_op missing for arg%d\n", arg);
2032           if (tmp_op->argmask) {
2033             fprintf(fout, "s_a%d", arg + 1);
2034           }
2035           else {
2036             fprintf(fout, "%s",
2037               out_src_opr(buf1, sizeof(buf1),
2038                 tmp_op, &tmp_op->operand[0], 0));
2039           }
2040         }
2041         fprintf(fout, ");");
2042
2043         if (po->flags & OPF_TAIL) {
2044           strcpy(g_comment, "tailcall");
2045           if (IS(pp->ret_type, "void"))
2046             fprintf(fout, "\n  return;");
2047         }
2048         delayed_flag_op = NULL;
2049         last_arith_dst = NULL;
2050         break;
2051
2052       case OP_RET:
2053         if (IS(g_func_pp.ret_type, "void"))
2054           fprintf(fout, "  return;");
2055         else
2056           fprintf(fout, "  return eax;");
2057         break;
2058
2059       case OP_PUSH:
2060         if (po->argmask) {
2061           // special case - saved func arg
2062           for (j = 0; j < 32; j++) {
2063             if (po->argmask & (1 << j)) {
2064               fprintf(fout, "  s_a%d = %s;", j + 1,
2065                   out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], 0));
2066             }
2067           }
2068           break;
2069         }
2070         ferr(po, "push encountered\n");
2071         break;
2072
2073       case OP_POP:
2074         ferr(po, "pop encountered\n");
2075         break;
2076
2077       case OP_NOP:
2078         break;
2079
2080       default:
2081         no_output = 1;
2082         ferr(po, "unhandled op type %d, flags %x\n",
2083           po->op, po->flags);
2084         break;
2085     }
2086
2087     if (g_comment[0] != 0) {
2088       fprintf(fout, "  // %s", g_comment);
2089       g_comment[0] = 0;
2090       no_output = 0;
2091     }
2092     if (!no_output)
2093       fprintf(fout, "\n");
2094
2095     if (pfomask != 0)
2096         ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
2097
2098     // see is delayed flag stuff is still valid
2099     if (delayed_flag_op != NULL && delayed_flag_op != po) {
2100       if (is_any_opr_modified(delayed_flag_op, po))
2101         delayed_flag_op = NULL;
2102     }
2103
2104     if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
2105       if (is_opr_modified(last_arith_dst, po))
2106         last_arith_dst = NULL;
2107     }
2108   }
2109
2110   fprintf(fout, "}\n\n");
2111
2112   // cleanup
2113   for (i = 0; i < opcnt; i++) {
2114     if (ops[i].op == OP_CALL) {
2115       pp = ops[i].datap;
2116       if (pp) {
2117         proto_release(pp);
2118         free(pp);
2119       }
2120     }
2121   }
2122   proto_release(&g_func_pp);
2123 }
2124
2125 int main(int argc, char *argv[])
2126 {
2127   FILE *fout, *fasm, *fhdr;
2128   char line[256];
2129   char words[16][256];
2130   int in_func = 0;
2131   int skip_warned = 0;
2132   int eq_alloc;
2133   int pi = 0;
2134   int len;
2135   char *p;
2136   int wordc;
2137
2138   if (argc != 4) {
2139     printf("usage:\n%s <.c> <.asm> <hdrf>\n",
2140       argv[0]);
2141     return 1;
2142   }
2143
2144   hdrfn = argv[3];
2145   fhdr = fopen(hdrfn, "r");
2146   my_assert_not(fhdr, NULL);
2147
2148   asmfn = argv[2];
2149   fasm = fopen(asmfn, "r");
2150   my_assert_not(fasm, NULL);
2151
2152   fout = fopen(argv[1], "w");
2153   my_assert_not(fout, NULL);
2154
2155   eq_alloc = 128;
2156   g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
2157   my_assert_not(g_eqs, NULL);
2158
2159   while (fgets(line, sizeof(line), fasm))
2160   {
2161     asmln++;
2162
2163     p = sskip(line);
2164     if (*p == 0 || *p == ';')
2165       continue;
2166
2167     memset(words, 0, sizeof(words));
2168     for (wordc = 0; wordc < 16; wordc++) {
2169       p = sskip(next_word(words[wordc], sizeof(words[0]), p));
2170       if (*p == 0 || *p == ';') {
2171         wordc++;
2172         break;
2173       }
2174     }
2175
2176     if (wordc == 0) {
2177       // shouldn't happen
2178       awarn("wordc == 0?\n");
2179       continue;
2180     }
2181
2182     // don't care about this:
2183     if (words[0][0] == '.'
2184         || IS(words[0], "include")
2185         || IS(words[0], "assume") || IS(words[1], "segment")
2186         || IS(words[0], "align"))
2187     {
2188       continue;
2189     }
2190
2191     if (IS(words[1], "proc")) {
2192       if (in_func)
2193         aerr("proc '%s' while in_func '%s'?\n",
2194           words[0], g_func);
2195       strcpy(g_func, words[0]);
2196       in_func = 1;
2197       continue;
2198     }
2199
2200     if (IS(words[1], "endp")) {
2201       if (!in_func)
2202         aerr("endp '%s' while not in_func?\n", words[0]);
2203       if (!IS(g_func, words[0]))
2204         aerr("endp '%s' while in_func '%s'?\n",
2205           words[0], g_func);
2206       gen_func(fout, fhdr, g_func, pi);
2207       in_func = 0;
2208       skip_warned = 0;
2209       g_func[0] = 0;
2210       if (pi != 0) {
2211         memset(&ops, 0, pi * sizeof(ops[0]));
2212         memset(g_labels, 0, pi * sizeof(g_labels[0]));
2213         memset(g_label_refs, 0, pi * sizeof(g_label_refs[0]));
2214         pi = 0;
2215       }
2216       g_eqcnt = 0;
2217       continue;
2218     }
2219
2220     if (IS(words[1], "=")) {
2221       if (wordc != 5)
2222         aerr("unhandled equ, wc=%d\n", wordc);
2223       if (g_eqcnt >= eq_alloc) {
2224         eq_alloc *= 2;
2225         g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
2226         my_assert_not(g_eqs, NULL);
2227       }
2228
2229       len = strlen(words[0]);
2230       if (len > sizeof(g_eqs[0].name) - 1)
2231         aerr("equ name too long: %d\n", len);
2232       strcpy(g_eqs[g_eqcnt].name, words[0]);
2233
2234       if (!IS(words[3], "ptr"))
2235         aerr("unhandled equ\n");
2236       if (IS(words[2], "dword"))
2237         g_eqs[g_eqcnt].lmod = OPLM_DWORD;
2238       else if (IS(words[2], "word"))
2239         g_eqs[g_eqcnt].lmod = OPLM_WORD;
2240       else if (IS(words[2], "byte"))
2241         g_eqs[g_eqcnt].lmod = OPLM_BYTE;
2242       else
2243         aerr("bad lmod: '%s'\n", words[2]);
2244
2245       g_eqs[g_eqcnt].offset = parse_number(words[4]);
2246       g_eqcnt++;
2247       continue;
2248     }
2249
2250     if (pi >= ARRAY_SIZE(ops))
2251       aerr("too many ops\n");
2252
2253     p = strchr(words[0], ':');
2254     if (p != NULL) {
2255       len = p - words[0];
2256       if (len > sizeof(g_labels[0]) - 1)
2257         aerr("label too long: %d\n", len);
2258       if (g_labels[pi][0] != 0)
2259         aerr("dupe label?\n");
2260       memcpy(g_labels[pi], words[0], len);
2261       g_labels[pi][len] = 0;
2262       continue;
2263     }
2264
2265     if (!in_func) {
2266       if (!skip_warned && g_labels[pi][0] != 0) {
2267         anote("skipping from '%s'\n", g_labels[pi]);
2268         skip_warned = 1;
2269       }
2270       g_labels[pi][0] = 0;
2271       continue;
2272     }
2273
2274     parse_op(&ops[pi], words, wordc);
2275     pi++;
2276   }
2277
2278   fclose(fout);
2279   fclose(fasm);
2280   fclose(fhdr);
2281
2282   return 0;
2283 }
2284
2285 // vim:ts=2:shiftwidth=2:expandtab