- A few more fixes to get pointers to structures working correctly.
[coreboot.git] / util / romcc / romcc.c
1 #include <stdarg.h>
2 #include <errno.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <limits.h>
13
14 #define DEBUG_ERROR_MESSAGES 0
15 #define DEBUG_COLOR_GRAPH 0
16 #define DEBUG_SCC 0
17 #define DEBUG_CONSISTENCY 2
18
19 #warning "FIXME boundary cases with small types in larger registers"
20 #warning "FIXME give clear error messages about unused variables"
21
22 /*  Control flow graph of a loop without goto.
23  * 
24  *        AAA
25  *   +---/
26  *  /
27  * / +--->CCC
28  * | |    / \
29  * | |  DDD EEE    break;
30  * | |    \    \
31  * | |    FFF   \
32  *  \|    / \    \
33  *   |\ GGG HHH   |   continue;
34  *   | \  \   |   |
35  *   |  \ III |  /
36  *   |   \ | /  / 
37  *   |    vvv  /  
38  *   +----BBB /   
39  *         | /
40  *         vv
41  *        JJJ
42  *
43  * 
44  *             AAA
45  *     +-----+  |  +----+
46  *     |      \ | /     |
47  *     |       BBB  +-+ |
48  *     |       / \ /  | |
49  *     |     CCC JJJ / /
50  *     |     / \    / / 
51  *     |   DDD EEE / /  
52  *     |    |   +-/ /
53  *     |   FFF     /    
54  *     |   / \    /     
55  *     | GGG HHH /      
56  *     |  |   +-/
57  *     | III
58  *     +--+ 
59  *
60  * 
61  * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
62  * DFup(Z)    = { Y <- DF(Z) | idom(Y) != X }
63  *
64  *
65  * [] == DFlocal(X) U DF(X)
66  * () == DFup(X)
67  *
68  * Dominator graph of the same nodes.
69  *
70  *           AAA     AAA: [ ] ()
71  *          /   \
72  *        BBB    JJJ BBB: [ JJJ ] ( JJJ )  JJJ: [ ] ()
73  *         |
74  *        CCC        CCC: [ ] ( BBB, JJJ )
75  *        / \
76  *     DDD   EEE     DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
77  *      |
78  *     FFF           FFF: [ ] ( BBB )
79  *     / \         
80  *  GGG   HHH        GGG: [ ] ( BBB ) HHH: [ BBB ] ()
81  *   |
82  *  III              III: [ BBB ] ()
83  *
84  *
85  * BBB and JJJ are definitely the dominance frontier.
86  * Where do I place phi functions and how do I make that decision.
87  *   
88  */
89 static void die(char *fmt, ...)
90 {
91         va_list args;
92
93         va_start(args, fmt);
94         vfprintf(stderr, fmt, args);
95         va_end(args);
96         fflush(stdout);
97         fflush(stderr);
98         exit(1);
99 }
100
101 #define MALLOC_STRONG_DEBUG
102 static void *xmalloc(size_t size, const char *name)
103 {
104         void *buf;
105         buf = malloc(size);
106         if (!buf) {
107                 die("Cannot malloc %ld bytes to hold %s: %s\n",
108                         size + 0UL, name, strerror(errno));
109         }
110         return buf;
111 }
112
113 static void *xcmalloc(size_t size, const char *name)
114 {
115         void *buf;
116         buf = xmalloc(size, name);
117         memset(buf, 0, size);
118         return buf;
119 }
120
121 static void xfree(const void *ptr)
122 {
123         free((void *)ptr);
124 }
125
126 static char *xstrdup(const char *str)
127 {
128         char *new;
129         int len;
130         len = strlen(str);
131         new = xmalloc(len + 1, "xstrdup string");
132         memcpy(new, str, len);
133         new[len] = '\0';
134         return new;
135 }
136
137 static void xchdir(const char *path)
138 {
139         if (chdir(path) != 0) {
140                 die("chdir to %s failed: %s\n",
141                         path, strerror(errno));
142         }
143 }
144
145 static int exists(const char *dirname, const char *filename)
146 {
147         int does_exist = 1;
148         xchdir(dirname);
149         if (access(filename, O_RDONLY) < 0) {
150                 if ((errno != EACCES) && (errno != EROFS)) {
151                         does_exist = 0;
152                 }
153         }
154         return does_exist;
155 }
156
157
158 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
159 {
160         int fd;
161         char *buf;
162         off_t size, progress;
163         ssize_t result;
164         struct stat stats;
165         
166         if (!filename) {
167                 *r_size = 0;
168                 return 0;
169         }
170         xchdir(dirname);
171         fd = open(filename, O_RDONLY);
172         if (fd < 0) {
173                 die("Cannot open '%s' : %s\n",
174                         filename, strerror(errno));
175         }
176         result = fstat(fd, &stats);
177         if (result < 0) {
178                 die("Cannot stat: %s: %s\n",
179                         filename, strerror(errno));
180         }
181         size = stats.st_size;
182         *r_size = size +1;
183         buf = xmalloc(size +2, filename);
184         buf[size] = '\n'; /* Make certain the file is newline terminated */
185         buf[size+1] = '\0'; /* Null terminate the file for good measure */
186         progress = 0;
187         while(progress < size) {
188                 result = read(fd, buf + progress, size - progress);
189                 if (result < 0) {
190                         if ((errno == EINTR) || (errno == EAGAIN))
191                                 continue;
192                         die("read on %s of %ld bytes failed: %s\n",
193                                 filename, (size - progress)+ 0UL, strerror(errno));
194                 }
195                 progress += result;
196         }
197         result = close(fd);
198         if (result < 0) {
199                 die("Close of %s failed: %s\n",
200                         filename, strerror(errno));
201         }
202         return buf;
203 }
204
205 /* Long on the destination platform */
206 typedef unsigned long ulong_t;
207 typedef long long_t;
208
209 struct file_state {
210         struct file_state *prev;
211         const char *basename;
212         char *dirname;
213         char *buf;
214         off_t size;
215         char *pos;
216         int line;
217         char *line_start;
218         int report_line;
219         const char *report_name;
220         const char *report_dir;
221 };
222 struct hash_entry;
223 struct token {
224         int tok;
225         struct hash_entry *ident;
226         int str_len;
227         union {
228                 ulong_t integer;
229                 const char *str;
230         } val;
231 };
232
233 /* I have two classes of types:
234  * Operational types.
235  * Logical types.  (The type the C standard says the operation is of)
236  *
237  * The operational types are:
238  * chars
239  * shorts
240  * ints
241  * longs
242  *
243  * floats
244  * doubles
245  * long doubles
246  *
247  * pointer
248  */
249
250
251 /* Machine model.
252  * No memory is useable by the compiler.
253  * There is no floating point support.
254  * All operations take place in general purpose registers.
255  * There is one type of general purpose register.
256  * Unsigned longs are stored in that general purpose register.
257  */
258
259 /* Operations on general purpose registers.
260  */
261
262 #define OP_SMUL       0
263 #define OP_UMUL       1
264 #define OP_SDIV       2
265 #define OP_UDIV       3
266 #define OP_SMOD       4
267 #define OP_UMOD       5
268 #define OP_ADD        6
269 #define OP_SUB        7
270 #define OP_SL         8
271 #define OP_USR        9
272 #define OP_SSR       10 
273 #define OP_AND       11 
274 #define OP_XOR       12
275 #define OP_OR        13
276 #define OP_POS       14 /* Dummy positive operator don't use it */
277 #define OP_NEG       15
278 #define OP_INVERT    16
279                      
280 #define OP_EQ        20
281 #define OP_NOTEQ     21
282 #define OP_SLESS     22
283 #define OP_ULESS     23
284 #define OP_SMORE     24
285 #define OP_UMORE     25
286 #define OP_SLESSEQ   26
287 #define OP_ULESSEQ   27
288 #define OP_SMOREEQ   28
289 #define OP_UMOREEQ   29
290                      
291 #define OP_LFALSE    30  /* Test if the expression is logically false */
292 #define OP_LTRUE     31  /* Test if the expression is logcially true */
293
294 #define OP_LOAD      32
295 #define OP_STORE     33
296
297 #define OP_NOOP      34
298
299 #define OP_MIN_CONST 50
300 #define OP_MAX_CONST 59
301 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
302 #define OP_INTCONST  50
303 #define OP_BLOBCONST 51
304 /* For OP_BLOBCONST ->type holds the layout and size
305  * information.  u.blob holds a pointer to the raw binary
306  * data for the constant initializer.
307  */
308 #define OP_ADDRCONST 52
309 /* For OP_ADDRCONST ->type holds the type.
310  * MISC(0) holds the reference to the static variable.
311  * ->u.cval holds an offset from that value.
312  */
313
314 #define OP_WRITE     60 
315 /* OP_WRITE moves one pseudo register to another.
316  * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
317  * RHS(0) holds the psuedo to move.
318  */
319
320 #define OP_READ      61
321 /* OP_READ reads the value of a variable and makes
322  * it available for the pseudo operation.
323  * Useful for things like def-use chains.
324  * RHS(0) holds points to the triple to read from.
325  */
326 #define OP_COPY      62
327 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
328  */
329 #define OP_PIECE     63
330 /* OP_PIECE returns one piece of a instruction that returns a structure.
331  * MISC(0) is the instruction
332  * u.cval is the LHS piece of the instruction to return.
333  */
334 #define OP_ASM       64
335 /* OP_ASM holds a sequence of assembly instructions, the result
336  * of a C asm directive.
337  * RHS(x) holds input value x to the assembly sequence.
338  * LHS(x) holds the output value x from the assembly sequence.
339  * u.blob holds the string of assembly instructions.
340  */
341
342 #define OP_DEREF     65
343 /* OP_DEREF generates an lvalue from a pointer.
344  * RHS(0) holds the pointer value.
345  * OP_DEREF serves as a place holder to indicate all necessary
346  * checks have been done to indicate a value is an lvalue.
347  */
348 #define OP_DOT       66
349 /* OP_DOT references a submember of a structure lvalue.
350  * RHS(0) holds the lvalue.
351  * ->u.field holds the name of the field we want.
352  *
353  * Not seen outside of expressions.
354  */
355 #define OP_VAL       67
356 /* OP_VAL returns the value of a subexpression of the current expression.
357  * Useful for operators that have side effects.
358  * RHS(0) holds the expression.
359  * MISC(0) holds the subexpression of RHS(0) that is the
360  * value of the expression.
361  *
362  * Not seen outside of expressions.
363  */
364 #define OP_LAND      68
365 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
366  * Not seen outside of expressions.
367  */
368 #define OP_LOR       69
369 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
370  * Not seen outside of expressions.
371  */
372 #define OP_COND      70
373 /* OP_CODE performas a C ? : operation. 
374  * RHS(0) holds the test.
375  * RHS(1) holds the expression to evaluate if the test returns true.
376  * RHS(2) holds the expression to evaluate if the test returns false.
377  * Not seen outside of expressions.
378  */
379 #define OP_COMMA     71
380 /* OP_COMMA performacs a C comma operation.
381  * That is RHS(0) is evaluated, then RHS(1)
382  * and the value of RHS(1) is returned.
383  * Not seen outside of expressions.
384  */
385
386 #define OP_CALL      72
387 /* OP_CALL performs a procedure call. 
388  * MISC(0) holds a pointer to the OP_LIST of a function
389  * RHS(x) holds argument x of a function
390  * 
391  * Currently not seen outside of expressions.
392  */
393 #define OP_VAL_VEC   74
394 /* OP_VAL_VEC is an array of triples that are either variable
395  * or values for a structure or an array.
396  * RHS(x) holds element x of the vector.
397  * triple->type->elements holds the size of the vector.
398  */
399
400 /* statements */
401 #define OP_LIST      80
402 /* OP_LIST Holds a list of statements, and a result value.
403  * RHS(0) holds the list of statements.
404  * MISC(0) holds the value of the statements.
405  */
406
407 #define OP_BRANCH    81 /* branch */
408 /* For branch instructions
409  * TARG(0) holds the branch target.
410  * RHS(0) if present holds the branch condition.
411  * ->next holds where to branch to if the branch is not taken.
412  * The branch target can only be a decl...
413  */
414
415 #define OP_LABEL     83
416 /* OP_LABEL is a triple that establishes an target for branches.
417  * ->use is the list of all branches that use this label.
418  */
419
420 #define OP_ADECL     84 
421 /* OP_DECL is a triple that establishes an lvalue for assignments.
422  * ->use is a list of statements that use the variable.
423  */
424
425 #define OP_SDECL     85
426 /* OP_SDECL is a triple that establishes a variable of static
427  * storage duration.
428  * ->use is a list of statements that use the variable.
429  * MISC(0) holds the initializer expression.
430  */
431
432
433 #define OP_PHI       86
434 /* OP_PHI is a triple used in SSA form code.  
435  * It is used when multiple code paths merge and a variable needs
436  * a single assignment from any of those code paths.
437  * The operation is a cross between OP_DECL and OP_WRITE, which
438  * is what OP_PHI is geneared from.
439  * 
440  * RHS(x) points to the value from code path x
441  * The number of RHS entries is the number of control paths into the block
442  * in which OP_PHI resides.  The elements of the array point to point
443  * to the variables OP_PHI is derived from.
444  *
445  * MISC(0) holds a pointer to the orginal OP_DECL node.
446  */
447
448 /* Architecture specific instructions */
449 #define OP_CMP         100
450 #define OP_TEST        101
451 #define OP_SET_EQ      102
452 #define OP_SET_NOTEQ   103
453 #define OP_SET_SLESS   104
454 #define OP_SET_ULESS   105
455 #define OP_SET_SMORE   106
456 #define OP_SET_UMORE   107
457 #define OP_SET_SLESSEQ 108
458 #define OP_SET_ULESSEQ 109
459 #define OP_SET_SMOREEQ 110
460 #define OP_SET_UMOREEQ 111
461
462 #define OP_JMP         112
463 #define OP_JMP_EQ      113
464 #define OP_JMP_NOTEQ   114
465 #define OP_JMP_SLESS   115
466 #define OP_JMP_ULESS   116
467 #define OP_JMP_SMORE   117
468 #define OP_JMP_UMORE   118
469 #define OP_JMP_SLESSEQ 119
470 #define OP_JMP_ULESSEQ 120
471 #define OP_JMP_SMOREEQ 121
472 #define OP_JMP_UMOREEQ 122
473
474 /* Builtin operators that it is just simpler to use the compiler for */
475 #define OP_INB         130
476 #define OP_INW         131
477 #define OP_INL         132
478 #define OP_OUTB        133
479 #define OP_OUTW        134
480 #define OP_OUTL        135
481 #define OP_BSF         136
482 #define OP_BSR         137
483 #define OP_RDMSR       138
484 #define OP_WRMSR       139
485 #define OP_HLT         140
486
487 struct op_info {
488         const char *name;
489         unsigned flags;
490 #define PURE   1
491 #define IMPURE 2
492 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
493 #define DEF    4
494 #define BLOCK  8 /* Triple stores the current block */
495         unsigned char lhs, rhs, misc, targ;
496 };
497
498 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
499         .name = (NAME), \
500         .flags = (FLAGS), \
501         .lhs = (LHS), \
502         .rhs = (RHS), \
503         .misc = (MISC), \
504         .targ = (TARG), \
505          }
506 static const struct op_info table_ops[] = {
507 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
508 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
509 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
510 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
511 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
512 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
513 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
514 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
515 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
516 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
517 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
518 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
519 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
520 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
521 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
522 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
523 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
524
525 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
526 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
527 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
528 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
529 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
530 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
531 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
532 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
533 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
534 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
535 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
536 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
537
538 [OP_LOAD       ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "load"),
539 [OP_STORE      ] = OP( 1,  1, 0, 0, IMPURE | BLOCK , "store"),
540
541 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK, "noop"),
542
543 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
544 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE, "blobconst"),
545 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
546
547 [OP_WRITE      ] = OP( 1,  1, 0, 0, PURE | BLOCK, "write"),
548 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
549 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
550 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF, "piece"),
551 [OP_ASM        ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
552 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"), 
553 [OP_DOT        ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "dot"),
554
555 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
556 [OP_LAND       ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "land"),
557 [OP_LOR        ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "lor"),
558 [OP_COND       ] = OP( 0,  3, 0, 0, 0 | DEF | BLOCK, "cond"),
559 [OP_COMMA      ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "comma"),
560 /* Call is special most it can stand in for anything so it depends on context */
561 [OP_CALL       ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
562 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
563 [OP_VAL_VEC    ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
564
565 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF, "list"),
566 /* The number of targets for OP_BRANCH depends on context */
567 [OP_BRANCH     ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
568 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "label"),
569 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "adecl"),
570 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK, "sdecl"),
571 /* The number of RHS elements of OP_PHI depend upon context */
572 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
573
574 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
575 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
576 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
577 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
578 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
579 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
580 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
581 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
582 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
583 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
584 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
585 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
586 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK, "jmp"),
587 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_eq"),
588 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_noteq"),
589 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_sless"),
590 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_uless"),
591 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smore"),
592 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umore"),
593 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
594 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
595 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
596 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
597
598 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
599 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
600 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
601 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
602 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
603 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
604 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
605 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
606 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
607 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
608 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
609 };
610 #undef OP
611 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
612
613 static const char *tops(int index) 
614 {
615         static const char unknown[] = "unknown op";
616         if (index < 0) {
617                 return unknown;
618         }
619         if (index > OP_MAX) {
620                 return unknown;
621         }
622         return table_ops[index].name;
623 }
624
625 struct asm_info;
626 struct triple;
627 struct block;
628 struct triple_set {
629         struct triple_set *next;
630         struct triple *member;
631 };
632
633 #define MAX_LHS  15
634 #define MAX_RHS  15
635 #define MAX_MISC 15
636 #define MAX_TARG 15
637
638 struct occurance {
639         int count;
640         const char *filename;
641         const char *function;
642         int line;
643         int col;
644         struct occurance *parent;
645 };
646 struct triple {
647         struct triple *next, *prev;
648         struct triple_set *use;
649         struct type *type;
650         unsigned char op;
651         unsigned char template_id;
652         unsigned short sizes;
653 #define TRIPLE_LHS(SIZES)  (((SIZES) >>  0) & 0x0f)
654 #define TRIPLE_RHS(SIZES)  (((SIZES) >>  4) & 0x0f)
655 #define TRIPLE_MISC(SIZES) (((SIZES) >>  8) & 0x0f)
656 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
657 #define TRIPLE_SIZE(SIZES) \
658         ((((SIZES) >> 0) & 0x0f) + \
659         (((SIZES) >>  4) & 0x0f) + \
660         (((SIZES) >>  8) & 0x0f) + \
661         (((SIZES) >> 12) & 0x0f))
662 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
663         ((((LHS) & 0x0f) <<  0) | \
664         (((RHS) & 0x0f)  <<  4) | \
665         (((MISC) & 0x0f) <<  8) | \
666         (((TARG) & 0x0f) << 12))
667 #define TRIPLE_LHS_OFF(SIZES)  (0)
668 #define TRIPLE_RHS_OFF(SIZES)  (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
669 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
670 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
671 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
672 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
673 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
674 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
675         unsigned id; /* A scratch value and finally the register */
676 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
677 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
678 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
679         struct occurance *occurance;
680         union {
681                 ulong_t cval;
682                 struct block  *block;
683                 void *blob;
684                 struct hash_entry *field;
685                 struct asm_info *ainfo;
686         } u;
687         struct triple *param[2];
688 };
689
690 struct reg_info {
691         unsigned reg;
692         unsigned regcm;
693 };
694 struct ins_template {
695         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
696 };
697
698 struct asm_info {
699         struct ins_template tmpl;
700         char *str;
701 };
702
703 struct block_set {
704         struct block_set *next;
705         struct block *member;
706 };
707 struct block {
708         struct block *work_next;
709         struct block *left, *right;
710         struct triple *first, *last;
711         int users;
712         struct block_set *use;
713         struct block_set *idominates;
714         struct block_set *domfrontier;
715         struct block *idom;
716         struct block_set *ipdominates;
717         struct block_set *ipdomfrontier;
718         struct block *ipdom;
719         int vertex;
720         
721 };
722
723 struct symbol {
724         struct symbol *next;
725         struct hash_entry *ident;
726         struct triple *def;
727         struct type *type;
728         int scope_depth;
729 };
730
731 struct macro {
732         struct hash_entry *ident;
733         char *buf;
734         int buf_len;
735 };
736
737 struct hash_entry {
738         struct hash_entry *next;
739         const char *name;
740         int name_len;
741         int tok;
742         struct macro *sym_define;
743         struct symbol *sym_label;
744         struct symbol *sym_struct;
745         struct symbol *sym_ident;
746 };
747
748 #define HASH_TABLE_SIZE 2048
749
750 struct compile_state {
751         const char *label_prefix;
752         const char *ofilename;
753         FILE *output;
754         struct triple *vars;
755         struct file_state *file;
756         struct occurance *last_occurance;
757         const char *function;
758         struct token token[4];
759         struct hash_entry *hash_table[HASH_TABLE_SIZE];
760         struct hash_entry *i_continue;
761         struct hash_entry *i_break;
762         int scope_depth;
763         int if_depth, if_value;
764         int macro_line;
765         struct file_state *macro_file;
766         struct triple *main_function;
767         struct block *first_block, *last_block;
768         int last_vertex;
769         int cpu;
770         int debug;
771         int optimize;
772 };
773
774 /* visibility global/local */
775 /* static/auto duration */
776 /* typedef, register, inline */
777 #define STOR_SHIFT         0
778 #define STOR_MASK     0x000f
779 /* Visibility */
780 #define STOR_GLOBAL   0x0001
781 /* Duration */
782 #define STOR_PERM     0x0002
783 /* Storage specifiers */
784 #define STOR_AUTO     0x0000
785 #define STOR_STATIC   0x0002
786 #define STOR_EXTERN   0x0003
787 #define STOR_REGISTER 0x0004
788 #define STOR_TYPEDEF  0x0008
789 #define STOR_INLINE   0x000c
790
791 #define QUAL_SHIFT         4
792 #define QUAL_MASK     0x0070
793 #define QUAL_NONE     0x0000
794 #define QUAL_CONST    0x0010
795 #define QUAL_VOLATILE 0x0020
796 #define QUAL_RESTRICT 0x0040
797
798 #define TYPE_SHIFT         8
799 #define TYPE_MASK     0x1f00
800 #define TYPE_INTEGER(TYPE)    (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
801 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
802 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
803 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
804 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
805 #define TYPE_RANK(TYPE)       ((TYPE) & ~0x0100)
806 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
807 #define TYPE_DEFAULT  0x0000
808 #define TYPE_VOID     0x0100
809 #define TYPE_CHAR     0x0200
810 #define TYPE_UCHAR    0x0300
811 #define TYPE_SHORT    0x0400
812 #define TYPE_USHORT   0x0500
813 #define TYPE_INT      0x0600
814 #define TYPE_UINT     0x0700
815 #define TYPE_LONG     0x0800
816 #define TYPE_ULONG    0x0900
817 #define TYPE_LLONG    0x0a00 /* long long */
818 #define TYPE_ULLONG   0x0b00
819 #define TYPE_FLOAT    0x0c00
820 #define TYPE_DOUBLE   0x0d00
821 #define TYPE_LDOUBLE  0x0e00 /* long double */
822 #define TYPE_STRUCT   0x1000
823 #define TYPE_ENUM     0x1100
824 #define TYPE_POINTER  0x1200 
825 /* For TYPE_POINTER:
826  * type->left holds the type pointed to.
827  */
828 #define TYPE_FUNCTION 0x1300 
829 /* For TYPE_FUNCTION:
830  * type->left holds the return type.
831  * type->right holds the...
832  */
833 #define TYPE_PRODUCT  0x1400
834 /* TYPE_PRODUCT is a basic building block when defining structures
835  * type->left holds the type that appears first in memory.
836  * type->right holds the type that appears next in memory.
837  */
838 #define TYPE_OVERLAP  0x1500
839 /* TYPE_OVERLAP is a basic building block when defining unions
840  * type->left and type->right holds to types that overlap
841  * each other in memory.
842  */
843 #define TYPE_ARRAY    0x1600
844 /* TYPE_ARRAY is a basic building block when definitng arrays.
845  * type->left holds the type we are an array of.
846  * type-> holds the number of elements.
847  */
848
849 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
850
851 struct type {
852         unsigned int type;
853         struct type *left, *right;
854         ulong_t elements;
855         struct hash_entry *field_ident;
856         struct hash_entry *type_ident;
857 };
858
859 #define MAX_REGISTERS      75
860 #define MAX_REG_EQUIVS     16
861 #define REGISTER_BITS      16
862 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
863 #define TEMPLATE_BITS      6
864 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
865 #define MAX_REGC           12
866 #define REG_UNSET          0
867 #define REG_UNNEEDED       1
868 #define REG_VIRT0          (MAX_REGISTERS + 0)
869 #define REG_VIRT1          (MAX_REGISTERS + 1)
870 #define REG_VIRT2          (MAX_REGISTERS + 2)
871 #define REG_VIRT3          (MAX_REGISTERS + 3)
872 #define REG_VIRT4          (MAX_REGISTERS + 4)
873 #define REG_VIRT5          (MAX_REGISTERS + 5)
874 #define REG_VIRT6          (MAX_REGISTERS + 5)
875 #define REG_VIRT7          (MAX_REGISTERS + 5)
876 #define REG_VIRT8          (MAX_REGISTERS + 5)
877 #define REG_VIRT9          (MAX_REGISTERS + 5)
878
879 /* Provision for 8 register classes */
880 #define REG_SHIFT  0
881 #define REGC_SHIFT REGISTER_BITS
882 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
883 #define REG_MASK (MAX_VIRT_REGISTERS -1)
884 #define ID_REG(ID)              ((ID) & REG_MASK)
885 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
886 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
887 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
888 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
889                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
890
891 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
892 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
893 static void arch_reg_equivs(
894         struct compile_state *state, unsigned *equiv, int reg);
895 static int arch_select_free_register(
896         struct compile_state *state, char *used, int classes);
897 static unsigned arch_regc_size(struct compile_state *state, int class);
898 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
899 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
900 static const char *arch_reg_str(int reg);
901 static struct reg_info arch_reg_constraint(
902         struct compile_state *state, struct type *type, const char *constraint);
903 static struct reg_info arch_reg_clobber(
904         struct compile_state *state, const char *clobber);
905 static struct reg_info arch_reg_lhs(struct compile_state *state, 
906         struct triple *ins, int index);
907 static struct reg_info arch_reg_rhs(struct compile_state *state, 
908         struct triple *ins, int index);
909 static struct triple *transform_to_arch_instruction(
910         struct compile_state *state, struct triple *ins);
911
912
913
914 #define DEBUG_ABORT_ON_ERROR    0x0001
915 #define DEBUG_INTERMEDIATE_CODE 0x0002
916 #define DEBUG_CONTROL_FLOW      0x0004
917 #define DEBUG_BASIC_BLOCKS      0x0008
918 #define DEBUG_FDOMINATORS       0x0010
919 #define DEBUG_RDOMINATORS       0x0020
920 #define DEBUG_TRIPLES           0x0040
921 #define DEBUG_INTERFERENCE      0x0080
922 #define DEBUG_ARCH_CODE         0x0100
923 #define DEBUG_CODE_ELIMINATION  0x0200
924 #define DEBUG_INSERTED_COPIES   0x0400
925
926 #define GLOBAL_SCOPE_DEPTH   1
927 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
928
929 static void compile_file(struct compile_state *old_state, const char *filename, int local);
930
931 static void do_cleanup(struct compile_state *state)
932 {
933         if (state->output) {
934                 fclose(state->output);
935                 unlink(state->ofilename);
936         }
937 }
938
939 static int get_col(struct file_state *file)
940 {
941         int col;
942         char *ptr, *end;
943         ptr = file->line_start;
944         end = file->pos;
945         for(col = 0; ptr < end; ptr++) {
946                 if (*ptr != '\t') {
947                         col++;
948                 } 
949                 else {
950                         col = (col & ~7) + 8;
951                 }
952         }
953         return col;
954 }
955
956 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
957 {
958         int col;
959         if (triple) {
960                 struct occurance *spot;
961                 spot = triple->occurance;
962                 while(spot->parent) {
963                         spot = spot->parent;
964                 }
965                 fprintf(fp, "%s:%d.%d: ", 
966                         spot->filename, spot->line, spot->col);
967                 return;
968         }
969         if (!state->file) {
970                 return;
971         }
972         col = get_col(state->file);
973         fprintf(fp, "%s:%d.%d: ", 
974                 state->file->report_name, state->file->report_line, col);
975 }
976
977 static void __internal_error(struct compile_state *state, struct triple *ptr, 
978         char *fmt, ...)
979 {
980         va_list args;
981         va_start(args, fmt);
982         loc(stderr, state, ptr);
983         if (ptr) {
984                 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
985         }
986         fprintf(stderr, "Internal compiler error: ");
987         vfprintf(stderr, fmt, args);
988         fprintf(stderr, "\n");
989         va_end(args);
990         do_cleanup(state);
991         abort();
992 }
993
994
995 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
996         char *fmt, ...)
997 {
998         va_list args;
999         va_start(args, fmt);
1000         loc(stderr, state, ptr);
1001         fprintf(stderr, "Internal compiler warning: ");
1002         vfprintf(stderr, fmt, args);
1003         fprintf(stderr, "\n");
1004         va_end(args);
1005 }
1006
1007
1008
1009 static void __error(struct compile_state *state, struct triple *ptr, 
1010         char *fmt, ...)
1011 {
1012         va_list args;
1013         va_start(args, fmt);
1014         loc(stderr, state, ptr);
1015         vfprintf(stderr, fmt, args);
1016         va_end(args);
1017         fprintf(stderr, "\n");
1018         do_cleanup(state);
1019         if (state->debug & DEBUG_ABORT_ON_ERROR) {
1020                 abort();
1021         }
1022         exit(1);
1023 }
1024
1025 static void __warning(struct compile_state *state, struct triple *ptr, 
1026         char *fmt, ...)
1027 {
1028         va_list args;
1029         va_start(args, fmt);
1030         loc(stderr, state, ptr);
1031         fprintf(stderr, "warning: "); 
1032         vfprintf(stderr, fmt, args);
1033         fprintf(stderr, "\n");
1034         va_end(args);
1035 }
1036
1037 #if DEBUG_ERROR_MESSAGES 
1038 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1039 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1040 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1041 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1042 #else
1043 #  define internal_error __internal_error
1044 #  define internal_warning __internal_warning
1045 #  define error __error
1046 #  define warning __warning
1047 #endif
1048 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1049
1050 static void valid_op(struct compile_state *state, int op)
1051 {
1052         char *fmt = "invalid op: %d";
1053         if (op >= OP_MAX) {
1054                 internal_error(state, 0, fmt, op);
1055         }
1056         if (op < 0) {
1057                 internal_error(state, 0, fmt, op);
1058         }
1059 }
1060
1061 static void valid_ins(struct compile_state *state, struct triple *ptr)
1062 {
1063         valid_op(state, ptr->op);
1064 }
1065
1066 static void process_trigraphs(struct compile_state *state)
1067 {
1068         char *src, *dest, *end;
1069         struct file_state *file;
1070         file = state->file;
1071         src = dest = file->buf;
1072         end = file->buf + file->size;
1073         while((end - src) >= 3) {
1074                 if ((src[0] == '?') && (src[1] == '?')) {
1075                         int c = -1;
1076                         switch(src[2]) {
1077                         case '=': c = '#'; break;
1078                         case '/': c = '\\'; break;
1079                         case '\'': c = '^'; break;
1080                         case '(': c = '['; break;
1081                         case ')': c = ']'; break;
1082                         case '!': c = '!'; break;
1083                         case '<': c = '{'; break;
1084                         case '>': c = '}'; break;
1085                         case '-': c = '~'; break;
1086                         }
1087                         if (c != -1) {
1088                                 *dest++ = c;
1089                                 src += 3;
1090                         }
1091                         else {
1092                                 *dest++ = *src++;
1093                         }
1094                 }
1095                 else {
1096                         *dest++ = *src++;
1097                 }
1098         }
1099         while(src != end) {
1100                 *dest++ = *src++;
1101         }
1102         file->size = dest - file->buf;
1103 }
1104
1105 static void splice_lines(struct compile_state *state)
1106 {
1107         char *src, *dest, *end;
1108         struct file_state *file;
1109         file = state->file;
1110         src = dest = file->buf;
1111         end = file->buf + file->size;
1112         while((end - src) >= 2) {
1113                 if ((src[0] == '\\') && (src[1] == '\n')) {
1114                         src += 2;
1115                 }
1116                 else {
1117                         *dest++ = *src++;
1118                 }
1119         }
1120         while(src != end) {
1121                 *dest++ = *src++;
1122         }
1123         file->size = dest - file->buf;
1124 }
1125
1126 static struct type void_type;
1127 static void use_triple(struct triple *used, struct triple *user)
1128 {
1129         struct triple_set **ptr, *new;
1130         if (!used)
1131                 return;
1132         if (!user)
1133                 return;
1134         ptr = &used->use;
1135         while(*ptr) {
1136                 if ((*ptr)->member == user) {
1137                         return;
1138                 }
1139                 ptr = &(*ptr)->next;
1140         }
1141         /* Append new to the head of the list, 
1142          * copy_func and rename_block_variables
1143          * depends on this.
1144          */
1145         new = xcmalloc(sizeof(*new), "triple_set");
1146         new->member = user;
1147         new->next   = used->use;
1148         used->use   = new;
1149 }
1150
1151 static void unuse_triple(struct triple *used, struct triple *unuser)
1152 {
1153         struct triple_set *use, **ptr;
1154         if (!used) {
1155                 return;
1156         }
1157         ptr = &used->use;
1158         while(*ptr) {
1159                 use = *ptr;
1160                 if (use->member == unuser) {
1161                         *ptr = use->next;
1162                         xfree(use);
1163                 }
1164                 else {
1165                         ptr = &use->next;
1166                 }
1167         }
1168 }
1169
1170 static void push_triple(struct triple *used, struct triple *user)
1171 {
1172         struct triple_set *new;
1173         if (!used)
1174                 return;
1175         if (!user)
1176                 return;
1177         /* Append new to the head of the list,
1178          * it's the only sensible behavoir for a stack.
1179          */
1180         new = xcmalloc(sizeof(*new), "triple_set");
1181         new->member = user;
1182         new->next   = used->use;
1183         used->use   = new;
1184 }
1185
1186 static void pop_triple(struct triple *used, struct triple *unuser)
1187 {
1188         struct triple_set *use, **ptr;
1189         ptr = &used->use;
1190         while(*ptr) {
1191                 use = *ptr;
1192                 if (use->member == unuser) {
1193                         *ptr = use->next;
1194                         xfree(use);
1195                         /* Only free one occurance from the stack */
1196                         return;
1197                 }
1198                 else {
1199                         ptr = &use->next;
1200                 }
1201         }
1202 }
1203
1204 static void put_occurance(struct occurance *occurance)
1205 {
1206         occurance->count -= 1;
1207         if (occurance->count <= 0) {
1208                 if (occurance->parent) {
1209                         put_occurance(occurance->parent);
1210                 }
1211                 xfree(occurance);
1212         }
1213 }
1214
1215 static void get_occurance(struct occurance *occurance)
1216 {
1217         occurance->count += 1;
1218 }
1219
1220
1221 static struct occurance *new_occurance(struct compile_state *state)
1222 {
1223         struct occurance *result, *last;
1224         const char *filename;
1225         const char *function;
1226         int line, col;
1227
1228         function = "";
1229         filename = 0;
1230         line = 0;
1231         col  = 0;
1232         if (state->file) {
1233                 filename = state->file->report_name;
1234                 line     = state->file->report_line;
1235                 col      = get_col(state->file);
1236         }
1237         if (state->function) {
1238                 function = state->function;
1239         }
1240         last = state->last_occurance;
1241         if (last &&
1242                 (last->col == col) &&
1243                 (last->line == line) &&
1244                 (last->function == function) &&
1245                 (strcmp(last->filename, filename) == 0)) {
1246                 get_occurance(last);
1247                 return last;
1248         }
1249         if (last) {
1250                 state->last_occurance = 0;
1251                 put_occurance(last);
1252         }
1253         result = xmalloc(sizeof(*result), "occurance");
1254         result->count    = 2;
1255         result->filename = filename;
1256         result->function = function;
1257         result->line     = line;
1258         result->col      = col;
1259         result->parent   = 0;
1260         state->last_occurance = result;
1261         return result;
1262 }
1263
1264 static struct occurance *inline_occurance(struct compile_state *state,
1265         struct occurance *new, struct occurance *orig)
1266 {
1267         struct occurance *result, *last;
1268         last = state->last_occurance;
1269         if (last &&
1270                 (last->parent   == orig) &&
1271                 (last->col      == new->col) &&
1272                 (last->line     == new->line) &&
1273                 (last->function == new->function) &&
1274                 (last->filename == new->filename)) {
1275                 get_occurance(last);
1276                 return last;
1277         }
1278         if (last) {
1279                 state->last_occurance = 0;
1280                 put_occurance(last);
1281         }
1282         get_occurance(orig);
1283         result = xmalloc(sizeof(*result), "occurance");
1284         result->count    = 2;
1285         result->filename = new->filename;
1286         result->function = new->function;
1287         result->line     = new->line;
1288         result->col      = new->col;
1289         result->parent   = orig;
1290         state->last_occurance = result;
1291         return result;
1292 }
1293         
1294
1295 static struct occurance dummy_occurance = {
1296         .count    = 2,
1297         .filename = __FILE__,
1298         .function = "",
1299         .line     = __LINE__,
1300         .col      = 0,
1301         .parent   = 0,
1302 };
1303
1304 /* The zero triple is used as a place holder when we are removing pointers
1305  * from a triple.  Having allows certain sanity checks to pass even
1306  * when the original triple that was pointed to is gone.
1307  */
1308 static struct triple zero_triple = {
1309         .next      = &zero_triple,
1310         .prev      = &zero_triple,
1311         .use       = 0,
1312         .op        = OP_INTCONST,
1313         .sizes     = TRIPLE_SIZES(0, 0, 0, 0),
1314         .id        = -1, /* An invalid id */
1315         .u = { .cval   = 0, },
1316         .occurance = &dummy_occurance,
1317         .param { [0] = 0, [1] = 0, },
1318 };
1319
1320
1321 static unsigned short triple_sizes(struct compile_state *state,
1322         int op, struct type *type, int lhs_wanted, int rhs_wanted)
1323 {
1324         int lhs, rhs, misc, targ;
1325         valid_op(state, op);
1326         lhs = table_ops[op].lhs;
1327         rhs = table_ops[op].rhs;
1328         misc = table_ops[op].misc;
1329         targ = table_ops[op].targ;
1330         
1331         
1332         if (op == OP_CALL) {
1333                 struct type *param;
1334                 rhs = 0;
1335                 param = type->right;
1336                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1337                         rhs++;
1338                         param = param->right;
1339                 }
1340                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1341                         rhs++;
1342                 }
1343                 lhs = 0;
1344                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1345                         lhs = type->left->elements;
1346                 }
1347         }
1348         else if (op == OP_VAL_VEC) {
1349                 rhs = type->elements;
1350         }
1351         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1352                 rhs = rhs_wanted;
1353         }
1354         else if (op == OP_ASM) {
1355                 rhs = rhs_wanted;
1356                 lhs = lhs_wanted;
1357         }
1358         if ((rhs < 0) || (rhs > MAX_RHS)) {
1359                 internal_error(state, 0, "bad rhs");
1360         }
1361         if ((lhs < 0) || (lhs > MAX_LHS)) {
1362                 internal_error(state, 0, "bad lhs");
1363         }
1364         if ((misc < 0) || (misc > MAX_MISC)) {
1365                 internal_error(state, 0, "bad misc");
1366         }
1367         if ((targ < 0) || (targ > MAX_TARG)) {
1368                 internal_error(state, 0, "bad targs");
1369         }
1370         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1371 }
1372
1373 static struct triple *alloc_triple(struct compile_state *state, 
1374         int op, struct type *type, int lhs, int rhs,
1375         struct occurance *occurance)
1376 {
1377         size_t size, sizes, extra_count, min_count;
1378         struct triple *ret;
1379         sizes = triple_sizes(state, op, type, lhs, rhs);
1380
1381         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1382         extra_count = TRIPLE_SIZE(sizes);
1383         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1384
1385         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1386         ret = xcmalloc(size, "tripple");
1387         ret->op        = op;
1388         ret->sizes     = sizes;
1389         ret->type      = type;
1390         ret->next      = ret;
1391         ret->prev      = ret;
1392         ret->occurance = occurance;
1393         return ret;
1394 }
1395
1396 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1397 {
1398         struct triple *dup;
1399         int src_lhs, src_rhs, src_size;
1400         src_lhs = TRIPLE_LHS(src->sizes);
1401         src_rhs = TRIPLE_RHS(src->sizes);
1402         src_size = TRIPLE_SIZE(src->sizes);
1403         get_occurance(src->occurance);
1404         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1405                 src->occurance);
1406         memcpy(dup, src, sizeof(*src));
1407         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1408         return dup;
1409 }
1410
1411 static struct triple *new_triple(struct compile_state *state, 
1412         int op, struct type *type, int lhs, int rhs)
1413 {
1414         struct triple *ret;
1415         struct occurance *occurance;
1416         occurance = new_occurance(state);
1417         ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1418         return ret;
1419 }
1420
1421 static struct triple *build_triple(struct compile_state *state, 
1422         int op, struct type *type, struct triple *left, struct triple *right,
1423         struct occurance *occurance)
1424 {
1425         struct triple *ret;
1426         size_t count;
1427         ret = alloc_triple(state, op, type, -1, -1, occurance);
1428         count = TRIPLE_SIZE(ret->sizes);
1429         if (count > 0) {
1430                 ret->param[0] = left;
1431         }
1432         if (count > 1) {
1433                 ret->param[1] = right;
1434         }
1435         return ret;
1436 }
1437
1438 static struct triple *triple(struct compile_state *state, 
1439         int op, struct type *type, struct triple *left, struct triple *right)
1440 {
1441         struct triple *ret;
1442         size_t count;
1443         ret = new_triple(state, op, type, -1, -1);
1444         count = TRIPLE_SIZE(ret->sizes);
1445         if (count >= 1) {
1446                 ret->param[0] = left;
1447         }
1448         if (count >= 2) {
1449                 ret->param[1] = right;
1450         }
1451         return ret;
1452 }
1453
1454 static struct triple *branch(struct compile_state *state, 
1455         struct triple *targ, struct triple *test)
1456 {
1457         struct triple *ret;
1458         ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1459         if (test) {
1460                 RHS(ret, 0) = test;
1461         }
1462         TARG(ret, 0) = targ;
1463         /* record the branch target was used */
1464         if (!targ || (targ->op != OP_LABEL)) {
1465                 internal_error(state, 0, "branch not to label");
1466                 use_triple(targ, ret);
1467         }
1468         return ret;
1469 }
1470
1471
1472 static void insert_triple(struct compile_state *state,
1473         struct triple *first, struct triple *ptr)
1474 {
1475         if (ptr) {
1476                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1477                         internal_error(state, ptr, "expression already used");
1478                 }
1479                 ptr->next       = first;
1480                 ptr->prev       = first->prev;
1481                 ptr->prev->next = ptr;
1482                 ptr->next->prev = ptr;
1483                 if ((ptr->prev->op == OP_BRANCH) && 
1484                         TRIPLE_RHS(ptr->prev->sizes)) {
1485                         unuse_triple(first, ptr->prev);
1486                         use_triple(ptr, ptr->prev);
1487                 }
1488         }
1489 }
1490
1491 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1492 {
1493         /* This function is used to determine if u.block 
1494          * is utilized to store the current block number.
1495          */
1496         int stores_block;
1497         valid_ins(state, ins);
1498         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1499         return stores_block;
1500 }
1501
1502 static struct block *block_of_triple(struct compile_state *state, 
1503         struct triple *ins)
1504 {
1505         struct triple *first;
1506         first = RHS(state->main_function, 0);
1507         while(ins != first && !triple_stores_block(state, ins)) {
1508                 if (ins == ins->prev) {
1509                         internal_error(state, 0, "ins == ins->prev?");
1510                 }
1511                 ins = ins->prev;
1512         }
1513         if (!triple_stores_block(state, ins)) {
1514                 internal_error(state, ins, "Cannot find block");
1515         }
1516         return ins->u.block;
1517 }
1518
1519 static struct triple *pre_triple(struct compile_state *state,
1520         struct triple *base,
1521         int op, struct type *type, struct triple *left, struct triple *right)
1522 {
1523         struct block *block;
1524         struct triple *ret;
1525         /* If I am an OP_PIECE jump to the real instruction */
1526         if (base->op == OP_PIECE) {
1527                 base = MISC(base, 0);
1528         }
1529         block = block_of_triple(state, base);
1530         get_occurance(base->occurance);
1531         ret = build_triple(state, op, type, left, right, base->occurance);
1532         if (triple_stores_block(state, ret)) {
1533                 ret->u.block = block;
1534         }
1535         insert_triple(state, base, ret);
1536         if (block->first == base) {
1537                 block->first = ret;
1538         }
1539         return ret;
1540 }
1541
1542 static struct triple *post_triple(struct compile_state *state,
1543         struct triple *base,
1544         int op, struct type *type, struct triple *left, struct triple *right)
1545 {
1546         struct block *block;
1547         struct triple *ret;
1548         int zlhs;
1549         /* If I am an OP_PIECE jump to the real instruction */
1550         if (base->op == OP_PIECE) {
1551                 base = MISC(base, 0);
1552         }
1553         /* If I have a left hand side skip over it */
1554         zlhs = TRIPLE_LHS(base->sizes);
1555         if (zlhs && (base->op != OP_WRITE) && (base->op != OP_STORE)) {
1556                 base = LHS(base, zlhs - 1);
1557         }
1558
1559         block = block_of_triple(state, base);
1560         get_occurance(base->occurance);
1561         ret = build_triple(state, op, type, left, right, base->occurance);
1562         if (triple_stores_block(state, ret)) {
1563                 ret->u.block = block;
1564         }
1565         insert_triple(state, base->next, ret);
1566         if (block->last == base) {
1567                 block->last = ret;
1568         }
1569         return ret;
1570 }
1571
1572 static struct triple *label(struct compile_state *state)
1573 {
1574         /* Labels don't get a type */
1575         struct triple *result;
1576         result = triple(state, OP_LABEL, &void_type, 0, 0);
1577         return result;
1578 }
1579
1580 static void display_triple(FILE *fp, struct triple *ins)
1581 {
1582         struct occurance *ptr;
1583         const char *reg;
1584         char pre, post;
1585         pre = post = ' ';
1586         if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1587                 pre = '^';
1588         }
1589         if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1590                 post = 'v';
1591         }
1592         reg = arch_reg_str(ID_REG(ins->id));
1593         if (ins->op == OP_INTCONST) {
1594                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx>         ",
1595                         ins, pre, post, reg, ins->template_id, tops(ins->op), 
1596                         ins->u.cval);
1597         }
1598         else if (ins->op == OP_ADDRCONST) {
1599                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1600                         ins, pre, post, reg, ins->template_id, tops(ins->op), 
1601                         MISC(ins, 0), ins->u.cval);
1602         }
1603         else {
1604                 int i, count;
1605                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s", 
1606                         ins, pre, post, reg, ins->template_id, tops(ins->op));
1607                 count = TRIPLE_SIZE(ins->sizes);
1608                 for(i = 0; i < count; i++) {
1609                         fprintf(fp, " %-10p", ins->param[i]);
1610                 }
1611                 for(; i < 2; i++) {
1612                         fprintf(fp, "           ");
1613                 }
1614         }
1615         fprintf(fp, " @");
1616         for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1617                 fprintf(fp, " %s,%s:%d.%d",
1618                         ptr->function, 
1619                         ptr->filename,
1620                         ptr->line, 
1621                         ptr->col);
1622         }
1623         fprintf(fp, "\n");
1624         fflush(fp);
1625 }
1626
1627 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1628 {
1629         /* Does the triple have no side effects.
1630          * I.e. Rexecuting the triple with the same arguments 
1631          * gives the same value.
1632          */
1633         unsigned pure;
1634         valid_ins(state, ins);
1635         pure = PURE_BITS(table_ops[ins->op].flags);
1636         if ((pure != PURE) && (pure != IMPURE)) {
1637                 internal_error(state, 0, "Purity of %s not known\n",
1638                         tops(ins->op));
1639         }
1640         return pure == PURE;
1641 }
1642
1643 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1644 {
1645         /* This function is used to determine which triples need
1646          * a register.
1647          */
1648         int is_branch;
1649         valid_ins(state, ins);
1650         is_branch = (table_ops[ins->op].targ != 0);
1651         return is_branch;
1652 }
1653
1654 static int triple_is_def(struct compile_state *state, struct triple *ins)
1655 {
1656         /* This function is used to determine which triples need
1657          * a register.
1658          */
1659         int is_def;
1660         valid_ins(state, ins);
1661         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1662         return is_def;
1663 }
1664
1665 static struct triple **triple_iter(struct compile_state *state,
1666         size_t count, struct triple **vector,
1667         struct triple *ins, struct triple **last)
1668 {
1669         struct triple **ret;
1670         ret = 0;
1671         if (count) {
1672                 if (!last) {
1673                         ret = vector;
1674                 }
1675                 else if ((last >= vector) && (last < (vector + count - 1))) {
1676                         ret = last + 1;
1677                 }
1678         }
1679         return ret;
1680         
1681 }
1682
1683 static struct triple **triple_lhs(struct compile_state *state,
1684         struct triple *ins, struct triple **last)
1685 {
1686         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1687                 ins, last);
1688 }
1689
1690 static struct triple **triple_rhs(struct compile_state *state,
1691         struct triple *ins, struct triple **last)
1692 {
1693         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1694                 ins, last);
1695 }
1696
1697 static struct triple **triple_misc(struct compile_state *state,
1698         struct triple *ins, struct triple **last)
1699 {
1700         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1701                 ins, last);
1702 }
1703
1704 static struct triple **triple_targ(struct compile_state *state,
1705         struct triple *ins, struct triple **last)
1706 {
1707         size_t count;
1708         struct triple **ret, **vector;
1709         ret = 0;
1710         count = TRIPLE_TARG(ins->sizes);
1711         vector = &TARG(ins, 0);
1712         if (count) {
1713                 if (!last) {
1714                         ret = vector;
1715                 }
1716                 else if ((last >= vector) && (last < (vector + count - 1))) {
1717                         ret = last + 1;
1718                 }
1719                 else if ((last == (vector + count - 1)) && 
1720                         TRIPLE_RHS(ins->sizes)) {
1721                         ret = &ins->next;
1722                 }
1723         }
1724         return ret;
1725 }
1726
1727
1728 static void verify_use(struct compile_state *state,
1729         struct triple *user, struct triple *used)
1730 {
1731         int size, i;
1732         size = TRIPLE_SIZE(user->sizes);
1733         for(i = 0; i < size; i++) {
1734                 if (user->param[i] == used) {
1735                         break;
1736                 }
1737         }
1738         if (triple_is_branch(state, user)) {
1739                 if (user->next == used) {
1740                         i = -1;
1741                 }
1742         }
1743         if (i == size) {
1744                 internal_error(state, user, "%s(%p) does not use %s(%p)",
1745                         tops(user->op), user, tops(used->op), used);
1746         }
1747 }
1748
1749 static int find_rhs_use(struct compile_state *state, 
1750         struct triple *user, struct triple *used)
1751 {
1752         struct triple **param;
1753         int size, i;
1754         verify_use(state, user, used);
1755         size = TRIPLE_RHS(user->sizes);
1756         param = &RHS(user, 0);
1757         for(i = 0; i < size; i++) {
1758                 if (param[i] == used) {
1759                         return i;
1760                 }
1761         }
1762         return -1;
1763 }
1764
1765 static void free_triple(struct compile_state *state, struct triple *ptr)
1766 {
1767         size_t size;
1768         size = sizeof(*ptr) - sizeof(ptr->param) +
1769                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1770         ptr->prev->next = ptr->next;
1771         ptr->next->prev = ptr->prev;
1772         if (ptr->use) {
1773                 internal_error(state, ptr, "ptr->use != 0");
1774         }
1775         put_occurance(ptr->occurance);
1776         memset(ptr, -1, size);
1777         xfree(ptr);
1778 }
1779
1780 static void release_triple(struct compile_state *state, struct triple *ptr)
1781 {
1782         struct triple_set *set, *next;
1783         struct triple **expr;
1784         /* Remove ptr from use chains where it is the user */
1785         expr = triple_rhs(state, ptr, 0);
1786         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1787                 if (*expr) {
1788                         unuse_triple(*expr, ptr);
1789                 }
1790         }
1791         expr = triple_lhs(state, ptr, 0);
1792         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1793                 if (*expr) {
1794                         unuse_triple(*expr, ptr);
1795                 }
1796         }
1797         expr = triple_misc(state, ptr, 0);
1798         for(; expr; expr = triple_misc(state, ptr, expr)) {
1799                 if (*expr) {
1800                         unuse_triple(*expr, ptr);
1801                 }
1802         }
1803         expr = triple_targ(state, ptr, 0);
1804         for(; expr; expr = triple_targ(state, ptr, expr)) {
1805                 if (*expr) {
1806                         unuse_triple(*expr, ptr);
1807                 }
1808         }
1809         /* Reomve ptr from use chains where it is used */
1810         for(set = ptr->use; set; set = next) {
1811                 next = set->next;
1812                 expr = triple_rhs(state, set->member, 0);
1813                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1814                         if (*expr == ptr) {
1815                                 *expr = &zero_triple;
1816                         }
1817                 }
1818                 expr = triple_lhs(state, set->member, 0);
1819                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1820                         if (*expr == ptr) {
1821                                 *expr = &zero_triple;
1822                         }
1823                 }
1824                 expr = triple_misc(state, set->member, 0);
1825                 for(; expr; expr = triple_misc(state, set->member, expr)) {
1826                         if (*expr == ptr) {
1827                                 *expr = &zero_triple;
1828                         }
1829                 }
1830                 expr = triple_targ(state, set->member, 0);
1831                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1832                         if (*expr == ptr) {
1833                                 *expr = &zero_triple;
1834                         }
1835                 }
1836                 unuse_triple(ptr, set->member);
1837         }
1838         free_triple(state, ptr);
1839 }
1840
1841 static void print_triple(struct compile_state *state, struct triple *ptr);
1842
1843 #define TOK_UNKNOWN     0
1844 #define TOK_SPACE       1
1845 #define TOK_SEMI        2
1846 #define TOK_LBRACE      3
1847 #define TOK_RBRACE      4
1848 #define TOK_COMMA       5
1849 #define TOK_EQ          6
1850 #define TOK_COLON       7
1851 #define TOK_LBRACKET    8
1852 #define TOK_RBRACKET    9
1853 #define TOK_LPAREN      10
1854 #define TOK_RPAREN      11
1855 #define TOK_STAR        12
1856 #define TOK_DOTS        13
1857 #define TOK_MORE        14
1858 #define TOK_LESS        15
1859 #define TOK_TIMESEQ     16
1860 #define TOK_DIVEQ       17
1861 #define TOK_MODEQ       18
1862 #define TOK_PLUSEQ      19
1863 #define TOK_MINUSEQ     20
1864 #define TOK_SLEQ        21
1865 #define TOK_SREQ        22
1866 #define TOK_ANDEQ       23
1867 #define TOK_XOREQ       24
1868 #define TOK_OREQ        25
1869 #define TOK_EQEQ        26
1870 #define TOK_NOTEQ       27
1871 #define TOK_QUEST       28
1872 #define TOK_LOGOR       29
1873 #define TOK_LOGAND      30
1874 #define TOK_OR          31
1875 #define TOK_AND         32
1876 #define TOK_XOR         33
1877 #define TOK_LESSEQ      34
1878 #define TOK_MOREEQ      35
1879 #define TOK_SL          36
1880 #define TOK_SR          37
1881 #define TOK_PLUS        38
1882 #define TOK_MINUS       39
1883 #define TOK_DIV         40
1884 #define TOK_MOD         41
1885 #define TOK_PLUSPLUS    42
1886 #define TOK_MINUSMINUS  43
1887 #define TOK_BANG        44
1888 #define TOK_ARROW       45
1889 #define TOK_DOT         46
1890 #define TOK_TILDE       47
1891 #define TOK_LIT_STRING  48
1892 #define TOK_LIT_CHAR    49
1893 #define TOK_LIT_INT     50
1894 #define TOK_LIT_FLOAT   51
1895 #define TOK_MACRO       52
1896 #define TOK_CONCATENATE 53
1897
1898 #define TOK_IDENT       54
1899 #define TOK_STRUCT_NAME 55
1900 #define TOK_ENUM_CONST  56
1901 #define TOK_TYPE_NAME   57
1902
1903 #define TOK_AUTO        58
1904 #define TOK_BREAK       59
1905 #define TOK_CASE        60
1906 #define TOK_CHAR        61
1907 #define TOK_CONST       62
1908 #define TOK_CONTINUE    63
1909 #define TOK_DEFAULT     64
1910 #define TOK_DO          65
1911 #define TOK_DOUBLE      66
1912 #define TOK_ELSE        67
1913 #define TOK_ENUM        68
1914 #define TOK_EXTERN      69
1915 #define TOK_FLOAT       70
1916 #define TOK_FOR         71
1917 #define TOK_GOTO        72
1918 #define TOK_IF          73
1919 #define TOK_INLINE      74
1920 #define TOK_INT         75
1921 #define TOK_LONG        76
1922 #define TOK_REGISTER    77
1923 #define TOK_RESTRICT    78
1924 #define TOK_RETURN      79
1925 #define TOK_SHORT       80
1926 #define TOK_SIGNED      81
1927 #define TOK_SIZEOF      82
1928 #define TOK_STATIC      83
1929 #define TOK_STRUCT      84
1930 #define TOK_SWITCH      85
1931 #define TOK_TYPEDEF     86
1932 #define TOK_UNION       87
1933 #define TOK_UNSIGNED    88
1934 #define TOK_VOID        89
1935 #define TOK_VOLATILE    90
1936 #define TOK_WHILE       91
1937 #define TOK_ASM         92
1938 #define TOK_ATTRIBUTE   93
1939 #define TOK_ALIGNOF     94
1940 #define TOK_FIRST_KEYWORD TOK_AUTO
1941 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1942
1943 #define TOK_DEFINE      100
1944 #define TOK_UNDEF       101
1945 #define TOK_INCLUDE     102
1946 #define TOK_LINE        103
1947 #define TOK_ERROR       104
1948 #define TOK_WARNING     105
1949 #define TOK_PRAGMA      106
1950 #define TOK_IFDEF       107
1951 #define TOK_IFNDEF      108
1952 #define TOK_ELIF        109
1953 #define TOK_ENDIF       110
1954
1955 #define TOK_FIRST_MACRO TOK_DEFINE
1956 #define TOK_LAST_MACRO  TOK_ENDIF
1957          
1958 #define TOK_EOF         111
1959
1960 static const char *tokens[] = {
1961 [TOK_UNKNOWN     ] = "unknown",
1962 [TOK_SPACE       ] = ":space:",
1963 [TOK_SEMI        ] = ";",
1964 [TOK_LBRACE      ] = "{",
1965 [TOK_RBRACE      ] = "}",
1966 [TOK_COMMA       ] = ",",
1967 [TOK_EQ          ] = "=",
1968 [TOK_COLON       ] = ":",
1969 [TOK_LBRACKET    ] = "[",
1970 [TOK_RBRACKET    ] = "]",
1971 [TOK_LPAREN      ] = "(",
1972 [TOK_RPAREN      ] = ")",
1973 [TOK_STAR        ] = "*",
1974 [TOK_DOTS        ] = "...",
1975 [TOK_MORE        ] = ">",
1976 [TOK_LESS        ] = "<",
1977 [TOK_TIMESEQ     ] = "*=",
1978 [TOK_DIVEQ       ] = "/=",
1979 [TOK_MODEQ       ] = "%=",
1980 [TOK_PLUSEQ      ] = "+=",
1981 [TOK_MINUSEQ     ] = "-=",
1982 [TOK_SLEQ        ] = "<<=",
1983 [TOK_SREQ        ] = ">>=",
1984 [TOK_ANDEQ       ] = "&=",
1985 [TOK_XOREQ       ] = "^=",
1986 [TOK_OREQ        ] = "|=",
1987 [TOK_EQEQ        ] = "==",
1988 [TOK_NOTEQ       ] = "!=",
1989 [TOK_QUEST       ] = "?",
1990 [TOK_LOGOR       ] = "||",
1991 [TOK_LOGAND      ] = "&&",
1992 [TOK_OR          ] = "|",
1993 [TOK_AND         ] = "&",
1994 [TOK_XOR         ] = "^",
1995 [TOK_LESSEQ      ] = "<=",
1996 [TOK_MOREEQ      ] = ">=",
1997 [TOK_SL          ] = "<<",
1998 [TOK_SR          ] = ">>",
1999 [TOK_PLUS        ] = "+",
2000 [TOK_MINUS       ] = "-",
2001 [TOK_DIV         ] = "/",
2002 [TOK_MOD         ] = "%",
2003 [TOK_PLUSPLUS    ] = "++",
2004 [TOK_MINUSMINUS  ] = "--",
2005 [TOK_BANG        ] = "!",
2006 [TOK_ARROW       ] = "->",
2007 [TOK_DOT         ] = ".",
2008 [TOK_TILDE       ] = "~",
2009 [TOK_LIT_STRING  ] = ":string:",
2010 [TOK_IDENT       ] = ":ident:",
2011 [TOK_TYPE_NAME   ] = ":typename:",
2012 [TOK_LIT_CHAR    ] = ":char:",
2013 [TOK_LIT_INT     ] = ":integer:",
2014 [TOK_LIT_FLOAT   ] = ":float:",
2015 [TOK_MACRO       ] = "#",
2016 [TOK_CONCATENATE ] = "##",
2017
2018 [TOK_AUTO        ] = "auto",
2019 [TOK_BREAK       ] = "break",
2020 [TOK_CASE        ] = "case",
2021 [TOK_CHAR        ] = "char",
2022 [TOK_CONST       ] = "const",
2023 [TOK_CONTINUE    ] = "continue",
2024 [TOK_DEFAULT     ] = "default",
2025 [TOK_DO          ] = "do",
2026 [TOK_DOUBLE      ] = "double",
2027 [TOK_ELSE        ] = "else",
2028 [TOK_ENUM        ] = "enum",
2029 [TOK_EXTERN      ] = "extern",
2030 [TOK_FLOAT       ] = "float",
2031 [TOK_FOR         ] = "for",
2032 [TOK_GOTO        ] = "goto",
2033 [TOK_IF          ] = "if",
2034 [TOK_INLINE      ] = "inline",
2035 [TOK_INT         ] = "int",
2036 [TOK_LONG        ] = "long",
2037 [TOK_REGISTER    ] = "register",
2038 [TOK_RESTRICT    ] = "restrict",
2039 [TOK_RETURN      ] = "return",
2040 [TOK_SHORT       ] = "short",
2041 [TOK_SIGNED      ] = "signed",
2042 [TOK_SIZEOF      ] = "sizeof",
2043 [TOK_STATIC      ] = "static",
2044 [TOK_STRUCT      ] = "struct",
2045 [TOK_SWITCH      ] = "switch",
2046 [TOK_TYPEDEF     ] = "typedef",
2047 [TOK_UNION       ] = "union",
2048 [TOK_UNSIGNED    ] = "unsigned",
2049 [TOK_VOID        ] = "void",
2050 [TOK_VOLATILE    ] = "volatile",
2051 [TOK_WHILE       ] = "while",
2052 [TOK_ASM         ] = "asm",
2053 [TOK_ATTRIBUTE   ] = "__attribute__",
2054 [TOK_ALIGNOF     ] = "__alignof__",
2055
2056 [TOK_DEFINE      ] = "define",
2057 [TOK_UNDEF       ] = "undef",
2058 [TOK_INCLUDE     ] = "include",
2059 [TOK_LINE        ] = "line",
2060 [TOK_ERROR       ] = "error",
2061 [TOK_WARNING     ] = "warning",
2062 [TOK_PRAGMA      ] = "pragma",
2063 [TOK_IFDEF       ] = "ifdef",
2064 [TOK_IFNDEF      ] = "ifndef",
2065 [TOK_ELIF        ] = "elif",
2066 [TOK_ENDIF       ] = "endif",
2067
2068 [TOK_EOF         ] = "EOF",
2069 };
2070
2071 static unsigned int hash(const char *str, int str_len)
2072 {
2073         unsigned int hash;
2074         const char *end;
2075         end = str + str_len;
2076         hash = 0;
2077         for(; str < end; str++) {
2078                 hash = (hash *263) + *str;
2079         }
2080         hash = hash & (HASH_TABLE_SIZE -1);
2081         return hash;
2082 }
2083
2084 static struct hash_entry *lookup(
2085         struct compile_state *state, const char *name, int name_len)
2086 {
2087         struct hash_entry *entry;
2088         unsigned int index;
2089         index = hash(name, name_len);
2090         entry = state->hash_table[index];
2091         while(entry && 
2092                 ((entry->name_len != name_len) ||
2093                         (memcmp(entry->name, name, name_len) != 0))) {
2094                 entry = entry->next;
2095         }
2096         if (!entry) {
2097                 char *new_name;
2098                 /* Get a private copy of the name */
2099                 new_name = xmalloc(name_len + 1, "hash_name");
2100                 memcpy(new_name, name, name_len);
2101                 new_name[name_len] = '\0';
2102
2103                 /* Create a new hash entry */
2104                 entry = xcmalloc(sizeof(*entry), "hash_entry");
2105                 entry->next = state->hash_table[index];
2106                 entry->name = new_name;
2107                 entry->name_len = name_len;
2108
2109                 /* Place the new entry in the hash table */
2110                 state->hash_table[index] = entry;
2111         }
2112         return entry;
2113 }
2114
2115 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2116 {
2117         struct hash_entry *entry;
2118         entry = tk->ident;
2119         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2120                 (entry->tok == TOK_ENUM_CONST) ||
2121                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
2122                         (entry->tok <= TOK_LAST_KEYWORD)))) {
2123                 tk->tok = entry->tok;
2124         }
2125 }
2126
2127 static void ident_to_macro(struct compile_state *state, struct token *tk)
2128 {
2129         struct hash_entry *entry;
2130         entry = tk->ident;
2131         if (entry && 
2132                 (entry->tok >= TOK_FIRST_MACRO) &&
2133                 (entry->tok <= TOK_LAST_MACRO)) {
2134                 tk->tok = entry->tok;
2135         }
2136 }
2137
2138 static void hash_keyword(
2139         struct compile_state *state, const char *keyword, int tok)
2140 {
2141         struct hash_entry *entry;
2142         entry = lookup(state, keyword, strlen(keyword));
2143         if (entry && entry->tok != TOK_UNKNOWN) {
2144                 die("keyword %s already hashed", keyword);
2145         }
2146         entry->tok  = tok;
2147 }
2148
2149 static void symbol(
2150         struct compile_state *state, struct hash_entry *ident,
2151         struct symbol **chain, struct triple *def, struct type *type)
2152 {
2153         struct symbol *sym;
2154         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2155                 error(state, 0, "%s already defined", ident->name);
2156         }
2157         sym = xcmalloc(sizeof(*sym), "symbol");
2158         sym->ident = ident;
2159         sym->def   = def;
2160         sym->type  = type;
2161         sym->scope_depth = state->scope_depth;
2162         sym->next = *chain;
2163         *chain    = sym;
2164 }
2165
2166 static void label_symbol(struct compile_state *state, 
2167         struct hash_entry *ident, struct triple *label)
2168 {
2169         struct symbol *sym;
2170         if (ident->sym_label) {
2171                 error(state, 0, "label %s already defined", ident->name);
2172         }
2173         sym = xcmalloc(sizeof(*sym), "label");
2174         sym->ident = ident;
2175         sym->def   = label;
2176         sym->type  = &void_type;
2177         sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2178         sym->next  = 0;
2179         ident->sym_label = sym;
2180 }
2181
2182 static void start_scope(struct compile_state *state)
2183 {
2184         state->scope_depth++;
2185 }
2186
2187 static void end_scope_syms(struct symbol **chain, int depth)
2188 {
2189         struct symbol *sym, *next;
2190         sym = *chain;
2191         while(sym && (sym->scope_depth == depth)) {
2192                 next = sym->next;
2193                 xfree(sym);
2194                 sym = next;
2195         }
2196         *chain = sym;
2197 }
2198
2199 static void end_scope(struct compile_state *state)
2200 {
2201         int i;
2202         int depth;
2203         /* Walk through the hash table and remove all symbols
2204          * in the current scope. 
2205          */
2206         depth = state->scope_depth;
2207         for(i = 0; i < HASH_TABLE_SIZE; i++) {
2208                 struct hash_entry *entry;
2209                 entry = state->hash_table[i];
2210                 while(entry) {
2211                         end_scope_syms(&entry->sym_label,  depth);
2212                         end_scope_syms(&entry->sym_struct, depth);
2213                         end_scope_syms(&entry->sym_ident,  depth);
2214                         entry = entry->next;
2215                 }
2216         }
2217         state->scope_depth = depth - 1;
2218 }
2219
2220 static void register_keywords(struct compile_state *state)
2221 {
2222         hash_keyword(state, "auto",          TOK_AUTO);
2223         hash_keyword(state, "break",         TOK_BREAK);
2224         hash_keyword(state, "case",          TOK_CASE);
2225         hash_keyword(state, "char",          TOK_CHAR);
2226         hash_keyword(state, "const",         TOK_CONST);
2227         hash_keyword(state, "continue",      TOK_CONTINUE);
2228         hash_keyword(state, "default",       TOK_DEFAULT);
2229         hash_keyword(state, "do",            TOK_DO);
2230         hash_keyword(state, "double",        TOK_DOUBLE);
2231         hash_keyword(state, "else",          TOK_ELSE);
2232         hash_keyword(state, "enum",          TOK_ENUM);
2233         hash_keyword(state, "extern",        TOK_EXTERN);
2234         hash_keyword(state, "float",         TOK_FLOAT);
2235         hash_keyword(state, "for",           TOK_FOR);
2236         hash_keyword(state, "goto",          TOK_GOTO);
2237         hash_keyword(state, "if",            TOK_IF);
2238         hash_keyword(state, "inline",        TOK_INLINE);
2239         hash_keyword(state, "int",           TOK_INT);
2240         hash_keyword(state, "long",          TOK_LONG);
2241         hash_keyword(state, "register",      TOK_REGISTER);
2242         hash_keyword(state, "restrict",      TOK_RESTRICT);
2243         hash_keyword(state, "return",        TOK_RETURN);
2244         hash_keyword(state, "short",         TOK_SHORT);
2245         hash_keyword(state, "signed",        TOK_SIGNED);
2246         hash_keyword(state, "sizeof",        TOK_SIZEOF);
2247         hash_keyword(state, "static",        TOK_STATIC);
2248         hash_keyword(state, "struct",        TOK_STRUCT);
2249         hash_keyword(state, "switch",        TOK_SWITCH);
2250         hash_keyword(state, "typedef",       TOK_TYPEDEF);
2251         hash_keyword(state, "union",         TOK_UNION);
2252         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
2253         hash_keyword(state, "void",          TOK_VOID);
2254         hash_keyword(state, "volatile",      TOK_VOLATILE);
2255         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
2256         hash_keyword(state, "while",         TOK_WHILE);
2257         hash_keyword(state, "asm",           TOK_ASM);
2258         hash_keyword(state, "__asm__",       TOK_ASM);
2259         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2260         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
2261 }
2262
2263 static void register_macro_keywords(struct compile_state *state)
2264 {
2265         hash_keyword(state, "define",        TOK_DEFINE);
2266         hash_keyword(state, "undef",         TOK_UNDEF);
2267         hash_keyword(state, "include",       TOK_INCLUDE);
2268         hash_keyword(state, "line",          TOK_LINE);
2269         hash_keyword(state, "error",         TOK_ERROR);
2270         hash_keyword(state, "warning",       TOK_WARNING);
2271         hash_keyword(state, "pragma",        TOK_PRAGMA);
2272         hash_keyword(state, "ifdef",         TOK_IFDEF);
2273         hash_keyword(state, "ifndef",        TOK_IFNDEF);
2274         hash_keyword(state, "elif",          TOK_ELIF);
2275         hash_keyword(state, "endif",         TOK_ENDIF);
2276 }
2277
2278 static int spacep(int c)
2279 {
2280         int ret = 0;
2281         switch(c) {
2282         case ' ':
2283         case '\t':
2284         case '\f':
2285         case '\v':
2286         case '\r':
2287         case '\n':
2288                 ret = 1;
2289                 break;
2290         }
2291         return ret;
2292 }
2293
2294 static int digitp(int c)
2295 {
2296         int ret = 0;
2297         switch(c) {
2298         case '0': case '1': case '2': case '3': case '4': 
2299         case '5': case '6': case '7': case '8': case '9':
2300                 ret = 1;
2301                 break;
2302         }
2303         return ret;
2304 }
2305 static int digval(int c)
2306 {
2307         int val = -1;
2308         if ((c >= '0') && (c <= '9')) {
2309                 val = c - '0';
2310         }
2311         return val;
2312 }
2313
2314 static int hexdigitp(int c)
2315 {
2316         int ret = 0;
2317         switch(c) {
2318         case '0': case '1': case '2': case '3': case '4': 
2319         case '5': case '6': case '7': case '8': case '9':
2320         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2321         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2322                 ret = 1;
2323                 break;
2324         }
2325         return ret;
2326 }
2327 static int hexdigval(int c) 
2328 {
2329         int val = -1;
2330         if ((c >= '0') && (c <= '9')) {
2331                 val = c - '0';
2332         }
2333         else if ((c >= 'A') && (c <= 'F')) {
2334                 val = 10 + (c - 'A');
2335         }
2336         else if ((c >= 'a') && (c <= 'f')) {
2337                 val = 10 + (c - 'a');
2338         }
2339         return val;
2340 }
2341
2342 static int octdigitp(int c)
2343 {
2344         int ret = 0;
2345         switch(c) {
2346         case '0': case '1': case '2': case '3': 
2347         case '4': case '5': case '6': case '7':
2348                 ret = 1;
2349                 break;
2350         }
2351         return ret;
2352 }
2353 static int octdigval(int c)
2354 {
2355         int val = -1;
2356         if ((c >= '0') && (c <= '7')) {
2357                 val = c - '0';
2358         }
2359         return val;
2360 }
2361
2362 static int letterp(int c)
2363 {
2364         int ret = 0;
2365         switch(c) {
2366         case 'a': case 'b': case 'c': case 'd': case 'e':
2367         case 'f': case 'g': case 'h': case 'i': case 'j':
2368         case 'k': case 'l': case 'm': case 'n': case 'o':
2369         case 'p': case 'q': case 'r': case 's': case 't':
2370         case 'u': case 'v': case 'w': case 'x': case 'y':
2371         case 'z':
2372         case 'A': case 'B': case 'C': case 'D': case 'E':
2373         case 'F': case 'G': case 'H': case 'I': case 'J':
2374         case 'K': case 'L': case 'M': case 'N': case 'O':
2375         case 'P': case 'Q': case 'R': case 'S': case 'T':
2376         case 'U': case 'V': case 'W': case 'X': case 'Y':
2377         case 'Z':
2378         case '_':
2379                 ret = 1;
2380                 break;
2381         }
2382         return ret;
2383 }
2384
2385 static int char_value(struct compile_state *state,
2386         const signed char **strp, const signed char *end)
2387 {
2388         const signed char *str;
2389         int c;
2390         str = *strp;
2391         c = *str++;
2392         if ((c == '\\') && (str < end)) {
2393                 switch(*str) {
2394                 case 'n':  c = '\n'; str++; break;
2395                 case 't':  c = '\t'; str++; break;
2396                 case 'v':  c = '\v'; str++; break;
2397                 case 'b':  c = '\b'; str++; break;
2398                 case 'r':  c = '\r'; str++; break;
2399                 case 'f':  c = '\f'; str++; break;
2400                 case 'a':  c = '\a'; str++; break;
2401                 case '\\': c = '\\'; str++; break;
2402                 case '?':  c = '?';  str++; break;
2403                 case '\'': c = '\''; str++; break;
2404                 case '"':  c = '"';  break;
2405                 case 'x': 
2406                         c = 0;
2407                         str++;
2408                         while((str < end) && hexdigitp(*str)) {
2409                                 c <<= 4;
2410                                 c += hexdigval(*str);
2411                                 str++;
2412                         }
2413                         break;
2414                 case '0': case '1': case '2': case '3': 
2415                 case '4': case '5': case '6': case '7':
2416                         c = 0;
2417                         while((str < end) && octdigitp(*str)) {
2418                                 c <<= 3;
2419                                 c += octdigval(*str);
2420                                 str++;
2421                         }
2422                         break;
2423                 default:
2424                         error(state, 0, "Invalid character constant");
2425                         break;
2426                 }
2427         }
2428         *strp = str;
2429         return c;
2430 }
2431
2432 static char *after_digits(char *ptr, char *end)
2433 {
2434         while((ptr < end) && digitp(*ptr)) {
2435                 ptr++;
2436         }
2437         return ptr;
2438 }
2439
2440 static char *after_octdigits(char *ptr, char *end)
2441 {
2442         while((ptr < end) && octdigitp(*ptr)) {
2443                 ptr++;
2444         }
2445         return ptr;
2446 }
2447
2448 static char *after_hexdigits(char *ptr, char *end)
2449 {
2450         while((ptr < end) && hexdigitp(*ptr)) {
2451                 ptr++;
2452         }
2453         return ptr;
2454 }
2455
2456 static void save_string(struct compile_state *state, 
2457         struct token *tk, char *start, char *end, const char *id)
2458 {
2459         char *str;
2460         int str_len;
2461         /* Create a private copy of the string */
2462         str_len = end - start + 1;
2463         str = xmalloc(str_len + 1, id);
2464         memcpy(str, start, str_len);
2465         str[str_len] = '\0';
2466
2467         /* Store the copy in the token */
2468         tk->val.str = str;
2469         tk->str_len = str_len;
2470 }
2471 static void next_token(struct compile_state *state, int index)
2472 {
2473         struct file_state *file;
2474         struct token *tk;
2475         char *token;
2476         int c, c1, c2, c3;
2477         char *tokp, *end;
2478         int tok;
2479 next_token:
2480         file = state->file;
2481         tk = &state->token[index];
2482         tk->str_len = 0;
2483         tk->ident = 0;
2484         token = tokp = file->pos;
2485         end = file->buf + file->size;
2486         tok = TOK_UNKNOWN;
2487         c = -1;
2488         if (tokp < end) {
2489                 c = *tokp;
2490         }
2491         c1 = -1;
2492         if ((tokp + 1) < end) {
2493                 c1 = tokp[1];
2494         }
2495         c2 = -1;
2496         if ((tokp + 2) < end) {
2497                 c2 = tokp[2];
2498         }
2499         c3 = -1;
2500         if ((tokp + 3) < end) {
2501                 c3 = tokp[3];
2502         }
2503         if (tokp >= end) {
2504                 tok = TOK_EOF;
2505                 tokp = end;
2506         }
2507         /* Whitespace */
2508         else if (spacep(c)) {
2509                 tok = TOK_SPACE;
2510                 while ((tokp < end) && spacep(c)) {
2511                         if (c == '\n') {
2512                                 file->line++;
2513                                 file->report_line++;
2514                                 file->line_start = tokp + 1;
2515                         }
2516                         c = *(++tokp);
2517                 }
2518                 if (!spacep(c)) {
2519                         tokp--;
2520                 }
2521         }
2522         /* EOL Comments */
2523         else if ((c == '/') && (c1 == '/')) {
2524                 tok = TOK_SPACE;
2525                 for(tokp += 2; tokp < end; tokp++) {
2526                         c = *tokp;
2527                         if (c == '\n') {
2528                                 file->line++;
2529                                 file->report_line++;
2530                                 file->line_start = tokp +1;
2531                                 break;
2532                         }
2533                 }
2534         }
2535         /* Comments */
2536         else if ((c == '/') && (c1 == '*')) {
2537                 int line;
2538                 char *line_start;
2539                 line = file->line;
2540                 line_start = file->line_start;
2541                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2542                         c = *tokp;
2543                         if (c == '\n') {
2544                                 line++;
2545                                 line_start = tokp +1;
2546                         }
2547                         else if ((c == '*') && (tokp[1] == '/')) {
2548                                 tok = TOK_SPACE;
2549                                 tokp += 1;
2550                                 break;
2551                         }
2552                 }
2553                 if (tok == TOK_UNKNOWN) {
2554                         error(state, 0, "unterminated comment");
2555                 }
2556                 file->report_line += line - file->line;
2557                 file->line = line;
2558                 file->line_start = line_start;
2559         }
2560         /* string constants */
2561         else if ((c == '"') ||
2562                 ((c == 'L') && (c1 == '"'))) {
2563                 int line;
2564                 char *line_start;
2565                 int wchar;
2566                 line = file->line;
2567                 line_start = file->line_start;
2568                 wchar = 0;
2569                 if (c == 'L') {
2570                         wchar = 1;
2571                         tokp++;
2572                 }
2573                 for(tokp += 1; tokp < end; tokp++) {
2574                         c = *tokp;
2575                         if (c == '\n') {
2576                                 line++;
2577                                 line_start = tokp + 1;
2578                         }
2579                         else if ((c == '\\') && (tokp +1 < end)) {
2580                                 tokp++;
2581                         }
2582                         else if (c == '"') {
2583                                 tok = TOK_LIT_STRING;
2584                                 break;
2585                         }
2586                 }
2587                 if (tok == TOK_UNKNOWN) {
2588                         error(state, 0, "unterminated string constant");
2589                 }
2590                 if (line != file->line) {
2591                         warning(state, 0, "multiline string constant");
2592                 }
2593                 file->report_line += line - file->line;
2594                 file->line = line;
2595                 file->line_start = line_start;
2596
2597                 /* Save the string value */
2598                 save_string(state, tk, token, tokp, "literal string");
2599         }
2600         /* character constants */
2601         else if ((c == '\'') ||
2602                 ((c == 'L') && (c1 == '\''))) {
2603                 int line;
2604                 char *line_start;
2605                 int wchar;
2606                 line = file->line;
2607                 line_start = file->line_start;
2608                 wchar = 0;
2609                 if (c == 'L') {
2610                         wchar = 1;
2611                         tokp++;
2612                 }
2613                 for(tokp += 1; tokp < end; tokp++) {
2614                         c = *tokp;
2615                         if (c == '\n') {
2616                                 line++;
2617                                 line_start = tokp + 1;
2618                         }
2619                         else if ((c == '\\') && (tokp +1 < end)) {
2620                                 tokp++;
2621                         }
2622                         else if (c == '\'') {
2623                                 tok = TOK_LIT_CHAR;
2624                                 break;
2625                         }
2626                 }
2627                 if (tok == TOK_UNKNOWN) {
2628                         error(state, 0, "unterminated character constant");
2629                 }
2630                 if (line != file->line) {
2631                         warning(state, 0, "multiline character constant");
2632                 }
2633                 file->report_line += line - file->line;
2634                 file->line = line;
2635                 file->line_start = line_start;
2636
2637                 /* Save the character value */
2638                 save_string(state, tk, token, tokp, "literal character");
2639         }
2640         /* integer and floating constants 
2641          * Integer Constants
2642          * {digits}
2643          * 0[Xx]{hexdigits}
2644          * 0{octdigit}+
2645          * 
2646          * Floating constants
2647          * {digits}.{digits}[Ee][+-]?{digits}
2648          * {digits}.{digits}
2649          * {digits}[Ee][+-]?{digits}
2650          * .{digits}[Ee][+-]?{digits}
2651          * .{digits}
2652          */
2653         
2654         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2655                 char *next, *new;
2656                 int is_float;
2657                 is_float = 0;
2658                 if (c != '.') {
2659                         next = after_digits(tokp, end);
2660                 }
2661                 else {
2662                         next = tokp;
2663                 }
2664                 if (next[0] == '.') {
2665                         new = after_digits(next, end);
2666                         is_float = (new != next);
2667                         next = new;
2668                 }
2669                 if ((next[0] == 'e') || (next[0] == 'E')) {
2670                         if (((next + 1) < end) && 
2671                                 ((next[1] == '+') || (next[1] == '-'))) {
2672                                 next++;
2673                         }
2674                         new = after_digits(next, end);
2675                         is_float = (new != next);
2676                         next = new;
2677                 }
2678                 if (is_float) {
2679                         tok = TOK_LIT_FLOAT;
2680                         if ((next < end) && (
2681                                 (next[0] == 'f') ||
2682                                 (next[0] == 'F') ||
2683                                 (next[0] == 'l') ||
2684                                 (next[0] == 'L'))
2685                                 ) {
2686                                 next++;
2687                         }
2688                 }
2689                 if (!is_float && digitp(c)) {
2690                         tok = TOK_LIT_INT;
2691                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2692                                 next = after_hexdigits(tokp + 2, end);
2693                         }
2694                         else if (c == '0') {
2695                                 next = after_octdigits(tokp, end);
2696                         }
2697                         else {
2698                                 next = after_digits(tokp, end);
2699                         }
2700                         /* crazy integer suffixes */
2701                         if ((next < end) && 
2702                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2703                                 next++;
2704                                 if ((next < end) &&
2705                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2706                                         next++;
2707                                 }
2708                         }
2709                         else if ((next < end) &&
2710                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2711                                 next++;
2712                                 if ((next < end) && 
2713                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2714                                         next++;
2715                                 }
2716                         }
2717                 }
2718                 tokp = next - 1;
2719
2720                 /* Save the integer/floating point value */
2721                 save_string(state, tk, token, tokp, "literal number");
2722         }
2723         /* identifiers */
2724         else if (letterp(c)) {
2725                 tok = TOK_IDENT;
2726                 for(tokp += 1; tokp < end; tokp++) {
2727                         c = *tokp;
2728                         if (!letterp(c) && !digitp(c)) {
2729                                 break;
2730                         }
2731                 }
2732                 tokp -= 1;
2733                 tk->ident = lookup(state, token, tokp +1 - token);
2734         }
2735         /* C99 alternate macro characters */
2736         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2737                 tokp += 3; 
2738                 tok = TOK_CONCATENATE; 
2739         }
2740         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2741         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2742         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2743         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2744         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2745         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2746         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2747         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2748         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2749         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2750         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2751         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2752         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2753         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2754         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2755         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2756         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2757         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2758         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2759         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2760         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2761         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2762         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2763         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2764         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2765         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2766         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2767         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2768         else if (c == ';') { tok = TOK_SEMI; }
2769         else if (c == '{') { tok = TOK_LBRACE; }
2770         else if (c == '}') { tok = TOK_RBRACE; }
2771         else if (c == ',') { tok = TOK_COMMA; }
2772         else if (c == '=') { tok = TOK_EQ; }
2773         else if (c == ':') { tok = TOK_COLON; }
2774         else if (c == '[') { tok = TOK_LBRACKET; }
2775         else if (c == ']') { tok = TOK_RBRACKET; }
2776         else if (c == '(') { tok = TOK_LPAREN; }
2777         else if (c == ')') { tok = TOK_RPAREN; }
2778         else if (c == '*') { tok = TOK_STAR; }
2779         else if (c == '>') { tok = TOK_MORE; }
2780         else if (c == '<') { tok = TOK_LESS; }
2781         else if (c == '?') { tok = TOK_QUEST; }
2782         else if (c == '|') { tok = TOK_OR; }
2783         else if (c == '&') { tok = TOK_AND; }
2784         else if (c == '^') { tok = TOK_XOR; }
2785         else if (c == '+') { tok = TOK_PLUS; }
2786         else if (c == '-') { tok = TOK_MINUS; }
2787         else if (c == '/') { tok = TOK_DIV; }
2788         else if (c == '%') { tok = TOK_MOD; }
2789         else if (c == '!') { tok = TOK_BANG; }
2790         else if (c == '.') { tok = TOK_DOT; }
2791         else if (c == '~') { tok = TOK_TILDE; }
2792         else if (c == '#') { tok = TOK_MACRO; }
2793         if (tok == TOK_MACRO) {
2794                 /* Only match preprocessor directives at the start of a line */
2795                 char *ptr;
2796                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2797                         ;
2798                 if (ptr != tokp) {
2799                         tok = TOK_UNKNOWN;
2800                 }
2801         }
2802         if (tok == TOK_UNKNOWN) {
2803                 error(state, 0, "unknown token");
2804         }
2805
2806         file->pos = tokp + 1;
2807         tk->tok = tok;
2808         if (tok == TOK_IDENT) {
2809                 ident_to_keyword(state, tk);
2810         }
2811         /* Don't return space tokens. */
2812         if (tok == TOK_SPACE) {
2813                 goto next_token;
2814         }
2815 }
2816
2817 static void compile_macro(struct compile_state *state, struct token *tk)
2818 {
2819         struct file_state *file;
2820         struct hash_entry *ident;
2821         ident = tk->ident;
2822         file = xmalloc(sizeof(*file), "file_state");
2823         file->basename = xstrdup(tk->ident->name);
2824         file->dirname = xstrdup("");
2825         file->size = ident->sym_define->buf_len;
2826         file->buf = xmalloc(file->size +2,  file->basename);
2827         memcpy(file->buf, ident->sym_define->buf, file->size);
2828         file->buf[file->size] = '\n';
2829         file->buf[file->size + 1] = '\0';
2830         file->pos = file->buf;
2831         file->line_start = file->pos;
2832         file->line = 1;
2833         file->report_line = 1;
2834         file->report_name = file->basename;
2835         file->report_dir  = file->dirname;
2836         file->prev = state->file;
2837         state->file = file;
2838 }
2839
2840
2841 static int mpeek(struct compile_state *state, int index)
2842 {
2843         struct token *tk;
2844         int rescan;
2845         tk = &state->token[index + 1];
2846         if (tk->tok == -1) {
2847                 next_token(state, index + 1);
2848         }
2849         do {
2850                 rescan = 0;
2851                 if ((tk->tok == TOK_EOF) && 
2852                         (state->file != state->macro_file) &&
2853                         (state->file->prev)) {
2854                         struct file_state *file = state->file;
2855                         state->file = file->prev;
2856                         /* file->basename is used keep it */
2857                         if (file->report_dir != file->dirname) {
2858                                 xfree(file->report_dir);
2859                         }
2860                         xfree(file->dirname);
2861                         xfree(file->buf);
2862                         xfree(file);
2863                         next_token(state, index + 1);
2864                         rescan = 1;
2865                 }
2866                 else if (tk->ident && tk->ident->sym_define) {
2867                         compile_macro(state, tk);
2868                         next_token(state, index + 1);
2869                         rescan = 1;
2870                 }
2871         } while(rescan);
2872         /* Don't show the token on the next line */
2873         if (state->macro_line < state->macro_file->line) {
2874                 return TOK_EOF;
2875         }
2876         return state->token[index +1].tok;
2877 }
2878
2879 static void meat(struct compile_state *state, int index, int tok)
2880 {
2881         int next_tok;
2882         int i;
2883         next_tok = mpeek(state, index);
2884         if (next_tok != tok) {
2885                 const char *name1, *name2;
2886                 name1 = tokens[next_tok];
2887                 name2 = "";
2888                 if (next_tok == TOK_IDENT) {
2889                         name2 = state->token[index + 1].ident->name;
2890                 }
2891                 error(state, 0, "found %s %s expected %s", 
2892                         name1, name2, tokens[tok]);
2893         }
2894         /* Free the old token value */
2895         if (state->token[index].str_len) {
2896                 memset((void *)(state->token[index].val.str), -1, 
2897                         state->token[index].str_len);
2898                 xfree(state->token[index].val.str);
2899         }
2900         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2901                 state->token[i] = state->token[i + 1];
2902         }
2903         memset(&state->token[i], 0, sizeof(state->token[i]));
2904         state->token[i].tok = -1;
2905 }
2906
2907 static long_t mcexpr(struct compile_state *state, int index);
2908
2909 static long_t mprimary_expr(struct compile_state *state, int index)
2910 {
2911         long_t val;
2912         int tok;
2913         tok = mpeek(state, index);
2914         while(state->token[index + 1].ident && 
2915                 state->token[index + 1].ident->sym_define) {
2916                 meat(state, index, tok);
2917                 compile_macro(state, &state->token[index]);
2918                 tok = mpeek(state, index);
2919         }
2920         switch(tok) {
2921         case TOK_LPAREN:
2922                 meat(state, index, TOK_LPAREN);
2923                 val = mcexpr(state, index);
2924                 meat(state, index, TOK_RPAREN);
2925                 break;
2926         case TOK_LIT_INT:
2927         {
2928                 char *end;
2929                 meat(state, index, TOK_LIT_INT);
2930                 errno = 0;
2931                 val = strtol(state->token[index].val.str, &end, 0);
2932                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2933                         (errno == ERANGE)) {
2934                         error(state, 0, "Integer constant to large");
2935                 }
2936                 break;
2937         }
2938         default:
2939                 meat(state, index, TOK_LIT_INT);
2940                 val = 0;
2941         }
2942         return val;
2943 }
2944 static long_t munary_expr(struct compile_state *state, int index)
2945 {
2946         long_t val;
2947         switch(mpeek(state, index)) {
2948         case TOK_PLUS:
2949                 meat(state, index, TOK_PLUS);
2950                 val = munary_expr(state, index);
2951                 val = + val;
2952                 break;
2953         case TOK_MINUS:
2954                 meat(state, index, TOK_MINUS);
2955                 val = munary_expr(state, index);
2956                 val = - val;
2957                 break;
2958         case TOK_TILDE:
2959                 meat(state, index, TOK_BANG);
2960                 val = munary_expr(state, index);
2961                 val = ~ val;
2962                 break;
2963         case TOK_BANG:
2964                 meat(state, index, TOK_BANG);
2965                 val = munary_expr(state, index);
2966                 val = ! val;
2967                 break;
2968         default:
2969                 val = mprimary_expr(state, index);
2970                 break;
2971         }
2972         return val;
2973         
2974 }
2975 static long_t mmul_expr(struct compile_state *state, int index)
2976 {
2977         long_t val;
2978         int done;
2979         val = munary_expr(state, index);
2980         do {
2981                 long_t right;
2982                 done = 0;
2983                 switch(mpeek(state, index)) {
2984                 case TOK_STAR:
2985                         meat(state, index, TOK_STAR);
2986                         right = munary_expr(state, index);
2987                         val = val * right;
2988                         break;
2989                 case TOK_DIV:
2990                         meat(state, index, TOK_DIV);
2991                         right = munary_expr(state, index);
2992                         val = val / right;
2993                         break;
2994                 case TOK_MOD:
2995                         meat(state, index, TOK_MOD);
2996                         right = munary_expr(state, index);
2997                         val = val % right;
2998                         break;
2999                 default:
3000                         done = 1;
3001                         break;
3002                 }
3003         } while(!done);
3004
3005         return val;
3006 }
3007
3008 static long_t madd_expr(struct compile_state *state, int index)
3009 {
3010         long_t val;
3011         int done;
3012         val = mmul_expr(state, index);
3013         do {
3014                 long_t right;
3015                 done = 0;
3016                 switch(mpeek(state, index)) {
3017                 case TOK_PLUS:
3018                         meat(state, index, TOK_PLUS);
3019                         right = mmul_expr(state, index);
3020                         val = val + right;
3021                         break;
3022                 case TOK_MINUS:
3023                         meat(state, index, TOK_MINUS);
3024                         right = mmul_expr(state, index);
3025                         val = val - right;
3026                         break;
3027                 default:
3028                         done = 1;
3029                         break;
3030                 }
3031         } while(!done);
3032
3033         return val;
3034 }
3035
3036 static long_t mshift_expr(struct compile_state *state, int index)
3037 {
3038         long_t val;
3039         int done;
3040         val = madd_expr(state, index);
3041         do {
3042                 long_t right;
3043                 done = 0;
3044                 switch(mpeek(state, index)) {
3045                 case TOK_SL:
3046                         meat(state, index, TOK_SL);
3047                         right = madd_expr(state, index);
3048                         val = val << right;
3049                         break;
3050                 case TOK_SR:
3051                         meat(state, index, TOK_SR);
3052                         right = madd_expr(state, index);
3053                         val = val >> right;
3054                         break;
3055                 default:
3056                         done = 1;
3057                         break;
3058                 }
3059         } while(!done);
3060
3061         return val;
3062 }
3063
3064 static long_t mrel_expr(struct compile_state *state, int index)
3065 {
3066         long_t val;
3067         int done;
3068         val = mshift_expr(state, index);
3069         do {
3070                 long_t right;
3071                 done = 0;
3072                 switch(mpeek(state, index)) {
3073                 case TOK_LESS:
3074                         meat(state, index, TOK_LESS);
3075                         right = mshift_expr(state, index);
3076                         val = val < right;
3077                         break;
3078                 case TOK_MORE:
3079                         meat(state, index, TOK_MORE);
3080                         right = mshift_expr(state, index);
3081                         val = val > right;
3082                         break;
3083                 case TOK_LESSEQ:
3084                         meat(state, index, TOK_LESSEQ);
3085                         right = mshift_expr(state, index);
3086                         val = val <= right;
3087                         break;
3088                 case TOK_MOREEQ:
3089                         meat(state, index, TOK_MOREEQ);
3090                         right = mshift_expr(state, index);
3091                         val = val >= right;
3092                         break;
3093                 default:
3094                         done = 1;
3095                         break;
3096                 }
3097         } while(!done);
3098         return val;
3099 }
3100
3101 static long_t meq_expr(struct compile_state *state, int index)
3102 {
3103         long_t val;
3104         int done;
3105         val = mrel_expr(state, index);
3106         do {
3107                 long_t right;
3108                 done = 0;
3109                 switch(mpeek(state, index)) {
3110                 case TOK_EQEQ:
3111                         meat(state, index, TOK_EQEQ);
3112                         right = mrel_expr(state, index);
3113                         val = val == right;
3114                         break;
3115                 case TOK_NOTEQ:
3116                         meat(state, index, TOK_NOTEQ);
3117                         right = mrel_expr(state, index);
3118                         val = val != right;
3119                         break;
3120                 default:
3121                         done = 1;
3122                         break;
3123                 }
3124         } while(!done);
3125         return val;
3126 }
3127
3128 static long_t mand_expr(struct compile_state *state, int index)
3129 {
3130         long_t val;
3131         val = meq_expr(state, index);
3132         if (mpeek(state, index) == TOK_AND) {
3133                 long_t right;
3134                 meat(state, index, TOK_AND);
3135                 right = meq_expr(state, index);
3136                 val = val & right;
3137         }
3138         return val;
3139 }
3140
3141 static long_t mxor_expr(struct compile_state *state, int index)
3142 {
3143         long_t val;
3144         val = mand_expr(state, index);
3145         if (mpeek(state, index) == TOK_XOR) {
3146                 long_t right;
3147                 meat(state, index, TOK_XOR);
3148                 right = mand_expr(state, index);
3149                 val = val ^ right;
3150         }
3151         return val;
3152 }
3153
3154 static long_t mor_expr(struct compile_state *state, int index)
3155 {
3156         long_t val;
3157         val = mxor_expr(state, index);
3158         if (mpeek(state, index) == TOK_OR) {
3159                 long_t right;
3160                 meat(state, index, TOK_OR);
3161                 right = mxor_expr(state, index);
3162                 val = val | right;
3163         }
3164         return val;
3165 }
3166
3167 static long_t mland_expr(struct compile_state *state, int index)
3168 {
3169         long_t val;
3170         val = mor_expr(state, index);
3171         if (mpeek(state, index) == TOK_LOGAND) {
3172                 long_t right;
3173                 meat(state, index, TOK_LOGAND);
3174                 right = mor_expr(state, index);
3175                 val = val && right;
3176         }
3177         return val;
3178 }
3179 static long_t mlor_expr(struct compile_state *state, int index)
3180 {
3181         long_t val;
3182         val = mland_expr(state, index);
3183         if (mpeek(state, index) == TOK_LOGOR) {
3184                 long_t right;
3185                 meat(state, index, TOK_LOGOR);
3186                 right = mland_expr(state, index);
3187                 val = val || right;
3188         }
3189         return val;
3190 }
3191
3192 static long_t mcexpr(struct compile_state *state, int index)
3193 {
3194         return mlor_expr(state, index);
3195 }
3196 static void preprocess(struct compile_state *state, int index)
3197 {
3198         /* Doing much more with the preprocessor would require
3199          * a parser and a major restructuring.
3200          * Postpone that for later.
3201          */
3202         struct file_state *file;
3203         struct token *tk;
3204         int line;
3205         int tok;
3206         
3207         file = state->file;
3208         tk = &state->token[index];
3209         state->macro_line = line = file->line;
3210         state->macro_file = file;
3211
3212         next_token(state, index);
3213         ident_to_macro(state, tk);
3214         if (tk->tok == TOK_IDENT) {
3215                 error(state, 0, "undefined preprocessing directive `%s'",
3216                         tk->ident->name);
3217         }
3218         switch(tk->tok) {
3219         case TOK_LIT_INT:
3220         {
3221                 int override_line;
3222                 override_line = strtoul(tk->val.str, 0, 10);
3223                 next_token(state, index);
3224                 /* I have a cpp line marker parse it */
3225                 if (tk->tok == TOK_LIT_STRING) {
3226                         const char *token, *base;
3227                         char *name, *dir;
3228                         int name_len, dir_len;
3229                         name = xmalloc(tk->str_len, "report_name");
3230                         token = tk->val.str + 1;
3231                         base = strrchr(token, '/');
3232                         name_len = tk->str_len -2;
3233                         if (base != 0) {
3234                                 dir_len = base - token;
3235                                 base++;
3236                                 name_len -= base - token;
3237                         } else {
3238                                 dir_len = 0;
3239                                 base = token;
3240                         }
3241                         memcpy(name, base, name_len);
3242                         name[name_len] = '\0';
3243                         dir = xmalloc(dir_len + 1, "report_dir");
3244                         memcpy(dir, token, dir_len);
3245                         dir[dir_len] = '\0';
3246                         file->report_line = override_line - 1;
3247                         file->report_name = name;
3248                         file->report_dir = dir;
3249                 }
3250         }
3251                 break;
3252         case TOK_LINE:
3253                 meat(state, index, TOK_LINE);
3254                 meat(state, index, TOK_LIT_INT);
3255                 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3256                 if (mpeek(state, index) == TOK_LIT_STRING) {
3257                         const char *token, *base;
3258                         char *name, *dir;
3259                         int name_len, dir_len;
3260                         meat(state, index, TOK_LIT_STRING);
3261                         name = xmalloc(tk->str_len, "report_name");
3262                         token = tk->val.str + 1;
3263                         name_len = tk->str_len - 2;
3264                         if (base != 0) {
3265                                 dir_len = base - token;
3266                                 base++;
3267                                 name_len -= base - token;
3268                         } else {
3269                                 dir_len = 0;
3270                                 base = token;
3271                         }
3272                         memcpy(name, base, name_len);
3273                         name[name_len] = '\0';
3274                         dir = xmalloc(dir_len + 1, "report_dir");
3275                         memcpy(dir, token, dir_len);
3276                         dir[dir_len] = '\0';
3277                         file->report_name = name;
3278                         file->report_dir = dir;
3279                 }
3280                 break;
3281         case TOK_UNDEF:
3282         case TOK_PRAGMA:
3283                 if (state->if_value < 0) {
3284                         break;
3285                 }
3286                 warning(state, 0, "Ignoring preprocessor directive: %s", 
3287                         tk->ident->name);
3288                 break;
3289         case TOK_ELIF:
3290                 error(state, 0, "#elif not supported");
3291 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3292                 if (state->if_depth == 0) {
3293                         error(state, 0, "#elif without #if");
3294                 }
3295                 /* If the #if was taken the #elif just disables the following code */
3296                 if (state->if_value >= 0) {
3297                         state->if_value = - state->if_value;
3298                 }
3299                 /* If the previous #if was not taken see if the #elif enables the 
3300                  * trailing code.
3301                  */
3302                 else if ((state->if_value < 0) && 
3303                         (state->if_depth == - state->if_value))
3304                 {
3305                         if (mcexpr(state, index) != 0) {
3306                                 state->if_value = state->if_depth;
3307                         }
3308                         else {
3309                                 state->if_value = - state->if_depth;
3310                         }
3311                 }
3312                 break;
3313         case TOK_IF:
3314                 state->if_depth++;
3315                 if (state->if_value < 0) {
3316                         break;
3317                 }
3318                 if (mcexpr(state, index) != 0) {
3319                         state->if_value = state->if_depth;
3320                 }
3321                 else {
3322                         state->if_value = - state->if_depth;
3323                 }
3324                 break;
3325         case TOK_IFNDEF:
3326                 state->if_depth++;
3327                 if (state->if_value < 0) {
3328                         break;
3329                 }
3330                 next_token(state, index);
3331                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3332                         error(state, 0, "Invalid macro name");
3333                 }
3334                 if (tk->ident->sym_define == 0) {
3335                         state->if_value = state->if_depth;
3336                 } 
3337                 else {
3338                         state->if_value = - state->if_depth;
3339                 }
3340                 break;
3341         case TOK_IFDEF:
3342                 state->if_depth++;
3343                 if (state->if_value < 0) {
3344                         break;
3345                 }
3346                 next_token(state, index);
3347                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3348                         error(state, 0, "Invalid macro name");
3349                 }
3350                 if (tk->ident->sym_define != 0) {
3351                         state->if_value = state->if_depth;
3352                 }
3353                 else {
3354                         state->if_value = - state->if_depth;
3355                 }
3356                 break;
3357         case TOK_ELSE:
3358                 if (state->if_depth == 0) {
3359                         error(state, 0, "#else without #if");
3360                 }
3361                 if ((state->if_value >= 0) ||
3362                         ((state->if_value < 0) && 
3363                                 (state->if_depth == -state->if_value)))
3364                 {
3365                         state->if_value = - state->if_value;
3366                 }
3367                 break;
3368         case TOK_ENDIF:
3369                 if (state->if_depth == 0) {
3370                         error(state, 0, "#endif without #if");
3371                 }
3372                 if ((state->if_value >= 0) ||
3373                         ((state->if_value < 0) &&
3374                                 (state->if_depth == -state->if_value))) 
3375                 {
3376                         state->if_value = state->if_depth - 1;
3377                 }
3378                 state->if_depth--;
3379                 break;
3380         case TOK_DEFINE:
3381         {
3382                 struct hash_entry *ident;
3383                 struct macro *macro;
3384                 char *ptr;
3385                 
3386                 if (state->if_value < 0) /* quit early when #if'd out */
3387                         break;
3388
3389                 meat(state, index, TOK_IDENT);
3390                 ident = tk->ident;
3391                 
3392
3393                 if (*file->pos == '(') {
3394 #warning "FIXME macros with arguments not supported"
3395                         error(state, 0, "Macros with arguments not supported");
3396                 }
3397
3398                 /* Find the end of the line to get an estimate of
3399                  * the macro's length.
3400                  */
3401                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
3402                         ;
3403
3404                 if (ident->sym_define != 0) {
3405                         error(state, 0, "macro %s already defined\n", ident->name);
3406                 }
3407                 macro = xmalloc(sizeof(*macro), "macro");
3408                 macro->ident = ident;
3409                 macro->buf_len = ptr - file->pos +1;
3410                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3411
3412                 memcpy(macro->buf, file->pos, macro->buf_len);
3413                 macro->buf[macro->buf_len] = '\n';
3414                 macro->buf[macro->buf_len +1] = '\0';
3415
3416                 ident->sym_define = macro;
3417                 break;
3418         }
3419         case TOK_ERROR:
3420         {
3421                 char *end;
3422                 int len;
3423                 /* Find the end of the line */
3424                 for(end = file->pos; *end != '\n'; end++)
3425                         ;
3426                 len = (end - file->pos);
3427                 if (state->if_value >= 0) {
3428                         error(state, 0, "%*.*s", len, len, file->pos);
3429                 }
3430                 file->pos = end;
3431                 break;
3432         }
3433         case TOK_WARNING:
3434         {
3435                 char *end;
3436                 int len;
3437                 /* Find the end of the line */
3438                 for(end = file->pos; *end != '\n'; end++)
3439                         ;
3440                 len = (end - file->pos);
3441                 if (state->if_value >= 0) {
3442                         warning(state, 0, "%*.*s", len, len, file->pos);
3443                 }
3444                 file->pos = end;
3445                 break;
3446         }
3447         case TOK_INCLUDE:
3448         {
3449                 char *name;
3450                 char *ptr;
3451                 int local;
3452                 local = 0;
3453                 name = 0;
3454                 next_token(state, index);
3455                 if (tk->tok == TOK_LIT_STRING) {
3456                         const char *token;
3457                         int name_len;
3458                         name = xmalloc(tk->str_len, "include");
3459                         token = tk->val.str +1;
3460                         name_len = tk->str_len -2;
3461                         if (*token == '"') {
3462                                 token++;
3463                                 name_len--;
3464                         }
3465                         memcpy(name, token, name_len);
3466                         name[name_len] = '\0';
3467                         local = 1;
3468                 }
3469                 else if (tk->tok == TOK_LESS) {
3470                         char *start, *end;
3471                         start = file->pos;
3472                         for(end = start; *end != '\n'; end++) {
3473                                 if (*end == '>') {
3474                                         break;
3475                                 }
3476                         }
3477                         if (*end == '\n') {
3478                                 error(state, 0, "Unterminated included directive");
3479                         }
3480                         name = xmalloc(end - start + 1, "include");
3481                         memcpy(name, start, end - start);
3482                         name[end - start] = '\0';
3483                         file->pos = end +1;
3484                         local = 0;
3485                 }
3486                 else {
3487                         error(state, 0, "Invalid include directive");
3488                 }
3489                 /* Error if there are any characters after the include */
3490                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3491                         switch(*ptr) {
3492                         case ' ':
3493                         case '\t':
3494                         case '\v':
3495                                 break;
3496                         default:
3497                                 error(state, 0, "garbage after include directive");
3498                         }
3499                 }
3500                 if (state->if_value >= 0) {
3501                         compile_file(state, name, local);
3502                 }
3503                 xfree(name);
3504                 next_token(state, index);
3505                 return;
3506         }
3507         default:
3508                 /* Ignore # without a following ident */
3509                 if (tk->tok == TOK_IDENT) {
3510                         error(state, 0, "Invalid preprocessor directive: %s", 
3511                                 tk->ident->name);
3512                 }
3513                 break;
3514         }
3515         /* Consume the rest of the macro line */
3516         do {
3517                 tok = mpeek(state, index);
3518                 meat(state, index, tok);
3519         } while(tok != TOK_EOF);
3520         return;
3521 }
3522
3523 static void token(struct compile_state *state, int index)
3524 {
3525         struct file_state *file;
3526         struct token *tk;
3527         int rescan;
3528
3529         tk = &state->token[index];
3530         next_token(state, index);
3531         do {
3532                 rescan = 0;
3533                 file = state->file;
3534                 if (tk->tok == TOK_EOF && file->prev) {
3535                         state->file = file->prev;
3536                         /* file->basename is used keep it */
3537                         xfree(file->dirname);
3538                         xfree(file->buf);
3539                         xfree(file);
3540                         next_token(state, index);
3541                         rescan = 1;
3542                 }
3543                 else if (tk->tok == TOK_MACRO) {
3544                         preprocess(state, index);
3545                         rescan = 1;
3546                 }
3547                 else if (tk->ident && tk->ident->sym_define) {
3548                         compile_macro(state, tk);
3549                         next_token(state, index);
3550                         rescan = 1;
3551                 }
3552                 else if (state->if_value < 0) {
3553                         next_token(state, index);
3554                         rescan = 1;
3555                 }
3556         } while(rescan);
3557 }
3558
3559 static int peek(struct compile_state *state)
3560 {
3561         if (state->token[1].tok == -1) {
3562                 token(state, 1);
3563         }
3564         return state->token[1].tok;
3565 }
3566
3567 static int peek2(struct compile_state *state)
3568 {
3569         if (state->token[1].tok == -1) {
3570                 token(state, 1);
3571         }
3572         if (state->token[2].tok == -1) {
3573                 token(state, 2);
3574         }
3575         return state->token[2].tok;
3576 }
3577
3578 static void eat(struct compile_state *state, int tok)
3579 {
3580         int next_tok;
3581         int i;
3582         next_tok = peek(state);
3583         if (next_tok != tok) {
3584                 const char *name1, *name2;
3585                 name1 = tokens[next_tok];
3586                 name2 = "";
3587                 if (next_tok == TOK_IDENT) {
3588                         name2 = state->token[1].ident->name;
3589                 }
3590                 error(state, 0, "\tfound %s %s expected %s",
3591                         name1, name2 ,tokens[tok]);
3592         }
3593         /* Free the old token value */
3594         if (state->token[0].str_len) {
3595                 xfree((void *)(state->token[0].val.str));
3596         }
3597         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3598                 state->token[i] = state->token[i + 1];
3599         }
3600         memset(&state->token[i], 0, sizeof(state->token[i]));
3601         state->token[i].tok = -1;
3602 }
3603
3604 #warning "FIXME do not hardcode the include paths"
3605 static char *include_paths[] = {
3606         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3607         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3608         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3609         0
3610 };
3611
3612 static void compile_file(struct compile_state *state, const char *filename, int local)
3613 {
3614         char cwd[4096];
3615         const char *subdir, *base;
3616         int subdir_len;
3617         struct file_state *file;
3618         char *basename;
3619         file = xmalloc(sizeof(*file), "file_state");
3620
3621         base = strrchr(filename, '/');
3622         subdir = filename;
3623         if (base != 0) {
3624                 subdir_len = base - filename;
3625                 base++;
3626         }
3627         else {
3628                 base = filename;
3629                 subdir_len = 0;
3630         }
3631         basename = xmalloc(strlen(base) +1, "basename");
3632         strcpy(basename, base);
3633         file->basename = basename;
3634
3635         if (getcwd(cwd, sizeof(cwd)) == 0) {
3636                 die("cwd buffer to small");
3637         }
3638         
3639         if (subdir[0] == '/') {
3640                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3641                 memcpy(file->dirname, subdir, subdir_len);
3642                 file->dirname[subdir_len] = '\0';
3643         }
3644         else {
3645                 char *dir;
3646                 int dirlen;
3647                 char **path;
3648                 /* Find the appropriate directory... */
3649                 dir = 0;
3650                 if (!state->file && exists(cwd, filename)) {
3651                         dir = cwd;
3652                 }
3653                 if (local && state->file && exists(state->file->dirname, filename)) {
3654                         dir = state->file->dirname;
3655                 }
3656                 for(path = include_paths; !dir && *path; path++) {
3657                         if (exists(*path, filename)) {
3658                                 dir = *path;
3659                         }
3660                 }
3661                 if (!dir) {
3662                         error(state, 0, "Cannot find `%s'\n", filename);
3663                 }
3664                 dirlen = strlen(dir);
3665                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3666                 memcpy(file->dirname, dir, dirlen);
3667                 file->dirname[dirlen] = '/';
3668                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3669                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3670         }
3671         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3672         xchdir(cwd);
3673
3674         file->pos = file->buf;
3675         file->line_start = file->pos;
3676         file->line = 1;
3677
3678         file->report_line = 1;
3679         file->report_name = file->basename;
3680         file->report_dir  = file->dirname;
3681
3682         file->prev = state->file;
3683         state->file = file;
3684         
3685         process_trigraphs(state);
3686         splice_lines(state);
3687 }
3688
3689 /* Type helper functions */
3690
3691 static struct type *new_type(
3692         unsigned int type, struct type *left, struct type *right)
3693 {
3694         struct type *result;
3695         result = xmalloc(sizeof(*result), "type");
3696         result->type = type;
3697         result->left = left;
3698         result->right = right;
3699         result->field_ident = 0;
3700         result->type_ident = 0;
3701         return result;
3702 }
3703
3704 static struct type *clone_type(unsigned int specifiers, struct type *old)
3705 {
3706         struct type *result;
3707         result = xmalloc(sizeof(*result), "type");
3708         memcpy(result, old, sizeof(*result));
3709         result->type &= TYPE_MASK;
3710         result->type |= specifiers;
3711         return result;
3712 }
3713
3714 #define SIZEOF_SHORT 2
3715 #define SIZEOF_INT   4
3716 #define SIZEOF_LONG  (sizeof(long_t))
3717
3718 #define ALIGNOF_SHORT 2
3719 #define ALIGNOF_INT   4
3720 #define ALIGNOF_LONG  (sizeof(long_t))
3721
3722 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3723 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3724 static inline ulong_t mask_uint(ulong_t x)
3725 {
3726         if (SIZEOF_INT < SIZEOF_LONG) {
3727                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3728                 x &= mask;
3729         }
3730         return x;
3731 }
3732 #define MASK_UINT(X)      (mask_uint(X))
3733 #define MASK_ULONG(X)    (X)
3734
3735 static struct type void_type   = { .type  = TYPE_VOID };
3736 static struct type char_type   = { .type  = TYPE_CHAR };
3737 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3738 static struct type short_type  = { .type  = TYPE_SHORT };
3739 static struct type ushort_type = { .type  = TYPE_USHORT };
3740 static struct type int_type    = { .type  = TYPE_INT };
3741 static struct type uint_type   = { .type  = TYPE_UINT };
3742 static struct type long_type   = { .type  = TYPE_LONG };
3743 static struct type ulong_type  = { .type  = TYPE_ULONG };
3744
3745 static struct triple *variable(struct compile_state *state, struct type *type)
3746 {
3747         struct triple *result;
3748         if ((type->type & STOR_MASK) != STOR_PERM) {
3749                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3750                         result = triple(state, OP_ADECL, type, 0, 0);
3751                 } else {
3752                         struct type *field;
3753                         struct triple **vector;
3754                         ulong_t index;
3755                         result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3756                         vector = &result->param[0];
3757
3758                         field = type->left;
3759                         index = 0;
3760                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3761                                 vector[index] = variable(state, field->left);
3762                                 field = field->right;
3763                                 index++;
3764                         }
3765                         vector[index] = variable(state, field);
3766                 }
3767         }
3768         else {
3769                 result = triple(state, OP_SDECL, type, 0, 0);
3770         }
3771         return result;
3772 }
3773
3774 static void stor_of(FILE *fp, struct type *type)
3775 {
3776         switch(type->type & STOR_MASK) {
3777         case STOR_AUTO:
3778                 fprintf(fp, "auto ");
3779                 break;
3780         case STOR_STATIC:
3781                 fprintf(fp, "static ");
3782                 break;
3783         case STOR_EXTERN:
3784                 fprintf(fp, "extern ");
3785                 break;
3786         case STOR_REGISTER:
3787                 fprintf(fp, "register ");
3788                 break;
3789         case STOR_TYPEDEF:
3790                 fprintf(fp, "typedef ");
3791                 break;
3792         case STOR_INLINE:
3793                 fprintf(fp, "inline ");
3794                 break;
3795         }
3796 }
3797 static void qual_of(FILE *fp, struct type *type)
3798 {
3799         if (type->type & QUAL_CONST) {
3800                 fprintf(fp, " const");
3801         }
3802         if (type->type & QUAL_VOLATILE) {
3803                 fprintf(fp, " volatile");
3804         }
3805         if (type->type & QUAL_RESTRICT) {
3806                 fprintf(fp, " restrict");
3807         }
3808 }
3809
3810 static void name_of(FILE *fp, struct type *type)
3811 {
3812         stor_of(fp, type);
3813         switch(type->type & TYPE_MASK) {
3814         case TYPE_VOID:
3815                 fprintf(fp, "void");
3816                 qual_of(fp, type);
3817                 break;
3818         case TYPE_CHAR:
3819                 fprintf(fp, "signed char");
3820                 qual_of(fp, type);
3821                 break;
3822         case TYPE_UCHAR:
3823                 fprintf(fp, "unsigned char");
3824                 qual_of(fp, type);
3825                 break;
3826         case TYPE_SHORT:
3827                 fprintf(fp, "signed short");
3828                 qual_of(fp, type);
3829                 break;
3830         case TYPE_USHORT:
3831                 fprintf(fp, "unsigned short");
3832                 qual_of(fp, type);
3833                 break;
3834         case TYPE_INT:
3835                 fprintf(fp, "signed int");
3836                 qual_of(fp, type);
3837                 break;
3838         case TYPE_UINT:
3839                 fprintf(fp, "unsigned int");
3840                 qual_of(fp, type);
3841                 break;
3842         case TYPE_LONG:
3843                 fprintf(fp, "signed long");
3844                 qual_of(fp, type);
3845                 break;
3846         case TYPE_ULONG:
3847                 fprintf(fp, "unsigned long");
3848                 qual_of(fp, type);
3849                 break;
3850         case TYPE_POINTER:
3851                 name_of(fp, type->left);
3852                 fprintf(fp, " * ");
3853                 qual_of(fp, type);
3854                 break;
3855         case TYPE_PRODUCT:
3856         case TYPE_OVERLAP:
3857                 name_of(fp, type->left);
3858                 fprintf(fp, ", ");
3859                 name_of(fp, type->right);
3860                 break;
3861         case TYPE_ENUM:
3862                 fprintf(fp, "enum %s", type->type_ident->name);
3863                 qual_of(fp, type);
3864                 break;
3865         case TYPE_STRUCT:
3866                 fprintf(fp, "struct %s", type->type_ident->name);
3867                 qual_of(fp, type);
3868                 break;
3869         case TYPE_FUNCTION:
3870         {
3871                 name_of(fp, type->left);
3872                 fprintf(fp, " (*)(");
3873                 name_of(fp, type->right);
3874                 fprintf(fp, ")");
3875                 break;
3876         }
3877         case TYPE_ARRAY:
3878                 name_of(fp, type->left);
3879                 fprintf(fp, " [%ld]", type->elements);
3880                 break;
3881         default:
3882                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3883                 break;
3884         }
3885 }
3886
3887 static size_t align_of(struct compile_state *state, struct type *type)
3888 {
3889         size_t align;
3890         align = 0;
3891         switch(type->type & TYPE_MASK) {
3892         case TYPE_VOID:
3893                 align = 1;
3894                 break;
3895         case TYPE_CHAR:
3896         case TYPE_UCHAR:
3897                 align = 1;
3898                 break;
3899         case TYPE_SHORT:
3900         case TYPE_USHORT:
3901                 align = ALIGNOF_SHORT;
3902                 break;
3903         case TYPE_INT:
3904         case TYPE_UINT:
3905         case TYPE_ENUM:
3906                 align = ALIGNOF_INT;
3907                 break;
3908         case TYPE_LONG:
3909         case TYPE_ULONG:
3910         case TYPE_POINTER:
3911                 align = ALIGNOF_LONG;
3912                 break;
3913         case TYPE_PRODUCT:
3914         case TYPE_OVERLAP:
3915         {
3916                 size_t left_align, right_align;
3917                 left_align  = align_of(state, type->left);
3918                 right_align = align_of(state, type->right);
3919                 align = (left_align >= right_align) ? left_align : right_align;
3920                 break;
3921         }
3922         case TYPE_ARRAY:
3923                 align = align_of(state, type->left);
3924                 break;
3925         case TYPE_STRUCT:
3926                 align = align_of(state, type->left);
3927                 break;
3928         default:
3929                 error(state, 0, "alignof not yet defined for type\n");
3930                 break;
3931         }
3932         return align;
3933 }
3934
3935 static size_t needed_padding(size_t offset, size_t align)
3936 {
3937         size_t padding;
3938         padding = 0;
3939         if (offset % align) {
3940                 padding = align - (offset % align);
3941         }
3942         return padding;
3943 }
3944 static size_t size_of(struct compile_state *state, struct type *type)
3945 {
3946         size_t size;
3947         size = 0;
3948         switch(type->type & TYPE_MASK) {
3949         case TYPE_VOID:
3950                 size = 0;
3951                 break;
3952         case TYPE_CHAR:
3953         case TYPE_UCHAR:
3954                 size = 1;
3955                 break;
3956         case TYPE_SHORT:
3957         case TYPE_USHORT:
3958                 size = SIZEOF_SHORT;
3959                 break;
3960         case TYPE_INT:
3961         case TYPE_UINT:
3962         case TYPE_ENUM:
3963                 size = SIZEOF_INT;
3964                 break;
3965         case TYPE_LONG:
3966         case TYPE_ULONG:
3967         case TYPE_POINTER:
3968                 size = SIZEOF_LONG;
3969                 break;
3970         case TYPE_PRODUCT:
3971         {
3972                 size_t align, pad;
3973                 size = 0;
3974                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3975                         align = align_of(state, type->left);
3976                         pad = needed_padding(size, align);
3977                         size = size + pad + size_of(state, type->left);
3978                         type = type->right;
3979                 }
3980                 align = align_of(state, type);
3981                 pad = needed_padding(size, align);
3982                 size = size + pad + sizeof(type);
3983                 break;
3984         }
3985         case TYPE_OVERLAP:
3986         {
3987                 size_t size_left, size_right;
3988                 size_left = size_of(state, type->left);
3989                 size_right = size_of(state, type->right);
3990                 size = (size_left >= size_right)? size_left : size_right;
3991                 break;
3992         }
3993         case TYPE_ARRAY:
3994                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3995                         internal_error(state, 0, "Invalid array type");
3996                 } else {
3997                         size = size_of(state, type->left) * type->elements;
3998                 }
3999                 break;
4000         case TYPE_STRUCT:
4001                 size = size_of(state, type->left);
4002                 break;
4003         default:
4004                 error(state, 0, "sizeof not yet defined for type\n");
4005                 break;
4006         }
4007         return size;
4008 }
4009
4010 static size_t field_offset(struct compile_state *state, 
4011         struct type *type, struct hash_entry *field)
4012 {
4013         size_t size, align;
4014         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4015                 internal_error(state, 0, "field_offset only works on structures");
4016         }
4017         size = 0;
4018         type = type->left;
4019         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4020                 align = align_of(state, type->left);
4021                 size += needed_padding(size, align);
4022                 if (type->left->field_ident == field) {
4023                         type = type->left;
4024                         break;
4025                 }
4026                 size += size_of(state, type->left);
4027                 type = type->right;
4028         }
4029         align = align_of(state, type);
4030         size += needed_padding(size, align);
4031         if (type->field_ident != field) {
4032                 error(state, 0, "member %s not present", field->name);
4033         }
4034         return size;
4035 }
4036
4037 static struct type *field_type(struct compile_state *state, 
4038         struct type *type, struct hash_entry *field)
4039 {
4040         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4041                 internal_error(state, 0, "field_type only works on structures");
4042         }
4043         type = type->left;
4044         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4045                 if (type->left->field_ident == field) {
4046                         type = type->left;
4047                         break;
4048                 }
4049                 type = type->right;
4050         }
4051         if (type->field_ident != field) {
4052                 error(state, 0, "member %s not present", field->name);
4053         }
4054         return type;
4055 }
4056
4057 static struct type *next_field(struct compile_state *state,
4058         struct type *type, struct type *prev_member) 
4059 {
4060         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4061                 internal_error(state, 0, "next_field only works on structures");
4062         }
4063         type = type->left;
4064         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4065                 if (!prev_member) {
4066                         type = type->left;
4067                         break;
4068                 }
4069                 if (type->left == prev_member) {
4070                         prev_member = 0;
4071                 }
4072                 type = type->right;
4073         }
4074         if (type == prev_member) {
4075                 prev_member = 0;
4076         }
4077         if (prev_member) {
4078                 internal_error(state, 0, "prev_member %s not present", 
4079                         prev_member->field_ident->name);
4080         }
4081         return type;
4082 }
4083
4084 static struct triple *struct_field(struct compile_state *state,
4085         struct triple *decl, struct hash_entry *field)
4086 {
4087         struct triple **vector;
4088         struct type *type;
4089         ulong_t index;
4090         type = decl->type;
4091         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4092                 return decl;
4093         }
4094         if (decl->op != OP_VAL_VEC) {
4095                 internal_error(state, 0, "Invalid struct variable");
4096         }
4097         if (!field) {
4098                 internal_error(state, 0, "Missing structure field");
4099         }
4100         type = type->left;
4101         vector = &RHS(decl, 0);
4102         index = 0;
4103         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4104                 if (type->left->field_ident == field) {
4105                         type = type->left;
4106                         break;
4107                 }
4108                 index += 1;
4109                 type = type->right;
4110         }
4111         if (type->field_ident != field) {
4112                 internal_error(state, 0, "field %s not found?", field->name);
4113         }
4114         return vector[index];
4115 }
4116
4117 static void arrays_complete(struct compile_state *state, struct type *type)
4118 {
4119         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4120                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4121                         error(state, 0, "array size not specified");
4122                 }
4123                 arrays_complete(state, type->left);
4124         }
4125 }
4126
4127 static unsigned int do_integral_promotion(unsigned int type)
4128 {
4129         type &= TYPE_MASK;
4130         if (TYPE_INTEGER(type) && 
4131                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4132                 type = TYPE_INT;
4133         }
4134         return type;
4135 }
4136
4137 static unsigned int do_arithmetic_conversion(
4138         unsigned int left, unsigned int right)
4139 {
4140         left &= TYPE_MASK;
4141         right &= TYPE_MASK;
4142         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4143                 return TYPE_LDOUBLE;
4144         }
4145         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4146                 return TYPE_DOUBLE;
4147         }
4148         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4149                 return TYPE_FLOAT;
4150         }
4151         left = do_integral_promotion(left);
4152         right = do_integral_promotion(right);
4153         /* If both operands have the same size done */
4154         if (left == right) {
4155                 return left;
4156         }
4157         /* If both operands have the same signedness pick the larger */
4158         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4159                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4160         }
4161         /* If the signed type can hold everything use it */
4162         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4163                 return left;
4164         }
4165         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4166                 return right;
4167         }
4168         /* Convert to the unsigned type with the same rank as the signed type */
4169         else if (TYPE_SIGNED(left)) {
4170                 return TYPE_MKUNSIGNED(left);
4171         }
4172         else {
4173                 return TYPE_MKUNSIGNED(right);
4174         }
4175 }
4176
4177 /* see if two types are the same except for qualifiers */
4178 static int equiv_types(struct type *left, struct type *right)
4179 {
4180         unsigned int type;
4181         /* Error if the basic types do not match */
4182         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4183                 return 0;
4184         }
4185         type = left->type & TYPE_MASK;
4186         /* if the basic types match and it is an arithmetic type we are done */
4187         if (TYPE_ARITHMETIC(type)) {
4188                 return 1;
4189         }
4190         /* If it is a pointer type recurse and keep testing */
4191         if (type == TYPE_POINTER) {
4192                 return equiv_types(left->left, right->left);
4193         }
4194         else if (type == TYPE_ARRAY) {
4195                 return (left->elements == right->elements) &&
4196                         equiv_types(left->left, right->left);
4197         }
4198         /* test for struct/union equality */
4199         else if (type == TYPE_STRUCT) {
4200                 return left->type_ident == right->type_ident;
4201         }
4202         /* Test for equivalent functions */
4203         else if (type == TYPE_FUNCTION) {
4204                 return equiv_types(left->left, right->left) &&
4205                         equiv_types(left->right, right->right);
4206         }
4207         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4208         else if (type == TYPE_PRODUCT) {
4209                 return equiv_types(left->left, right->left) &&
4210                         equiv_types(left->right, right->right);
4211         }
4212         /* We should see TYPE_OVERLAP */
4213         else {
4214                 return 0;
4215         }
4216 }
4217
4218 static int equiv_ptrs(struct type *left, struct type *right)
4219 {
4220         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4221                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4222                 return 0;
4223         }
4224         return equiv_types(left->left, right->left);
4225 }
4226
4227 static struct type *compatible_types(struct type *left, struct type *right)
4228 {
4229         struct type *result;
4230         unsigned int type, qual_type;
4231         /* Error if the basic types do not match */
4232         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4233                 return 0;
4234         }
4235         type = left->type & TYPE_MASK;
4236         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4237         result = 0;
4238         /* if the basic types match and it is an arithmetic type we are done */
4239         if (TYPE_ARITHMETIC(type)) {
4240                 result = new_type(qual_type, 0, 0);
4241         }
4242         /* If it is a pointer type recurse and keep testing */
4243         else if (type == TYPE_POINTER) {
4244                 result = compatible_types(left->left, right->left);
4245                 if (result) {
4246                         result = new_type(qual_type, result, 0);
4247                 }
4248         }
4249         /* test for struct/union equality */
4250         else if (type == TYPE_STRUCT) {
4251                 if (left->type_ident == right->type_ident) {
4252                         result = left;
4253                 }
4254         }
4255         /* Test for equivalent functions */
4256         else if (type == TYPE_FUNCTION) {
4257                 struct type *lf, *rf;
4258                 lf = compatible_types(left->left, right->left);
4259                 rf = compatible_types(left->right, right->right);
4260                 if (lf && rf) {
4261                         result = new_type(qual_type, lf, rf);
4262                 }
4263         }
4264         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4265         else if (type == TYPE_PRODUCT) {
4266                 struct type *lf, *rf;
4267                 lf = compatible_types(left->left, right->left);
4268                 rf = compatible_types(left->right, right->right);
4269                 if (lf && rf) {
4270                         result = new_type(qual_type, lf, rf);
4271                 }
4272         }
4273         else {
4274                 /* Nothing else is compatible */
4275         }
4276         return result;
4277 }
4278
4279 static struct type *compatible_ptrs(struct type *left, struct type *right)
4280 {
4281         struct type *result;
4282         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4283                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4284                 return 0;
4285         }
4286         result = compatible_types(left->left, right->left);
4287         if (result) {
4288                 unsigned int qual_type;
4289                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4290                 result = new_type(qual_type, result, 0);
4291         }
4292         return result;
4293         
4294 }
4295 static struct triple *integral_promotion(
4296         struct compile_state *state, struct triple *def)
4297 {
4298         struct type *type;
4299         type = def->type;
4300         /* As all operations are carried out in registers
4301          * the values are converted on load I just convert
4302          * logical type of the operand.
4303          */
4304         if (TYPE_INTEGER(type->type)) {
4305                 unsigned int int_type;
4306                 int_type = type->type & ~TYPE_MASK;
4307                 int_type |= do_integral_promotion(type->type);
4308                 if (int_type != type->type) {
4309                         def->type = new_type(int_type, 0, 0);
4310                 }
4311         }
4312         return def;
4313 }
4314
4315
4316 static void arithmetic(struct compile_state *state, struct triple *def)
4317 {
4318         if (!TYPE_ARITHMETIC(def->type->type)) {
4319                 error(state, 0, "arithmetic type expexted");
4320         }
4321 }
4322
4323 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4324 {
4325         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4326                 error(state, def, "pointer or arithmetic type expected");
4327         }
4328 }
4329
4330 static int is_integral(struct triple *ins)
4331 {
4332         return TYPE_INTEGER(ins->type->type);
4333 }
4334
4335 static void integral(struct compile_state *state, struct triple *def)
4336 {
4337         if (!is_integral(def)) {
4338                 error(state, 0, "integral type expected");
4339         }
4340 }
4341
4342
4343 static void bool(struct compile_state *state, struct triple *def)
4344 {
4345         if (!TYPE_ARITHMETIC(def->type->type) &&
4346                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4347                 error(state, 0, "arithmetic or pointer type expected");
4348         }
4349 }
4350
4351 static int is_signed(struct type *type)
4352 {
4353         return !!TYPE_SIGNED(type->type);
4354 }
4355
4356 /* Is this value located in a register otherwise it must be in memory */
4357 static int is_in_reg(struct compile_state *state, struct triple *def)
4358 {
4359         int in_reg;
4360         if (def->op == OP_ADECL) {
4361                 in_reg = 1;
4362         }
4363         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4364                 in_reg = 0;
4365         }
4366         else if (def->op == OP_VAL_VEC) {
4367                 in_reg = is_in_reg(state, RHS(def, 0));
4368         }
4369         else if (def->op == OP_DOT) {
4370                 in_reg = is_in_reg(state, RHS(def, 0));
4371         }
4372         else {
4373                 internal_error(state, 0, "unknown expr storage location");
4374                 in_reg = -1;
4375         }
4376         return in_reg;
4377 }
4378
4379 /* Is this a stable variable location otherwise it must be a temporary */
4380 static int is_stable(struct compile_state *state, struct triple *def)
4381 {
4382         int ret;
4383         ret = 0;
4384         if (!def) {
4385                 return 0;
4386         }
4387         if ((def->op == OP_ADECL) || 
4388                 (def->op == OP_SDECL) || 
4389                 (def->op == OP_DEREF) ||
4390                 (def->op == OP_BLOBCONST)) {
4391                 ret = 1;
4392         }
4393         else if (def->op == OP_DOT) {
4394                 ret = is_stable(state, RHS(def, 0));
4395         }
4396         else if (def->op == OP_VAL_VEC) {
4397                 struct triple **vector;
4398                 ulong_t i;
4399                 ret = 1;
4400                 vector = &RHS(def, 0);
4401                 for(i = 0; i < def->type->elements; i++) {
4402                         if (!is_stable(state, vector[i])) {
4403                                 ret = 0;
4404                                 break;
4405                         }
4406                 }
4407         }
4408         return ret;
4409 }
4410
4411 static int is_lvalue(struct compile_state *state, struct triple *def)
4412 {
4413         int ret;
4414         ret = 1;
4415         if (!def) {
4416                 return 0;
4417         }
4418         if (!is_stable(state, def)) {
4419                 return 0;
4420         }
4421         if (def->op == OP_DOT) {
4422                 ret = is_lvalue(state, RHS(def, 0));
4423         }
4424         return ret;
4425 }
4426
4427 static void clvalue(struct compile_state *state, struct triple *def)
4428 {
4429         if (!def) {
4430                 internal_error(state, def, "nothing where lvalue expected?");
4431         }
4432         if (!is_lvalue(state, def)) { 
4433                 error(state, def, "lvalue expected");
4434         }
4435 }
4436 static void lvalue(struct compile_state *state, struct triple *def)
4437 {
4438         clvalue(state, def);
4439         if (def->type->type & QUAL_CONST) {
4440                 error(state, def, "modifable lvalue expected");
4441         }
4442 }
4443
4444 static int is_pointer(struct triple *def)
4445 {
4446         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4447 }
4448
4449 static void pointer(struct compile_state *state, struct triple *def)
4450 {
4451         if (!is_pointer(def)) {
4452                 error(state, def, "pointer expected");
4453         }
4454 }
4455
4456 static struct triple *int_const(
4457         struct compile_state *state, struct type *type, ulong_t value)
4458 {
4459         struct triple *result;
4460         switch(type->type & TYPE_MASK) {
4461         case TYPE_CHAR:
4462         case TYPE_INT:   case TYPE_UINT:
4463         case TYPE_LONG:  case TYPE_ULONG:
4464                 break;
4465         default:
4466                 internal_error(state, 0, "constant for unkown type");
4467         }
4468         result = triple(state, OP_INTCONST, type, 0, 0);
4469         result->u.cval = value;
4470         return result;
4471 }
4472
4473
4474 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4475         struct triple *expr, struct type *type, ulong_t offset)
4476 {
4477         struct triple *result;
4478         clvalue(state, expr);
4479
4480         result = 0;
4481         if (expr->op == OP_ADECL) {
4482                 error(state, expr, "address of auto variables not supported");
4483         }
4484         else if (expr->op == OP_SDECL) {
4485                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4486                 MISC(result, 0) = expr;
4487                 result->u.cval = offset;
4488         }
4489         else if (expr->op == OP_DEREF) {
4490                 result = triple(state, OP_ADD, type,
4491                         RHS(expr, 0),
4492                         int_const(state, &ulong_type, offset));
4493         }
4494         return result;
4495 }
4496
4497 static struct triple *mk_addr_expr(
4498         struct compile_state *state, struct triple *expr, ulong_t offset)
4499 {
4500         struct type *type;
4501         
4502         type = new_type(
4503                 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4504                 expr->type, 0);
4505
4506         return do_mk_addr_expr(state, expr, type, offset);
4507 }
4508
4509 static struct triple *mk_deref_expr(
4510         struct compile_state *state, struct triple *expr)
4511 {
4512         struct type *base_type;
4513         pointer(state, expr);
4514         base_type = expr->type->left;
4515         return triple(state, OP_DEREF, base_type, expr, 0);
4516 }
4517
4518 static struct triple *deref_field(
4519         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4520 {
4521         struct triple *result;
4522         struct type *type, *member;
4523         if (!field) {
4524                 internal_error(state, 0, "No field passed to deref_field");
4525         }
4526         result = 0;
4527         type = expr->type;
4528         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4529                 error(state, 0, "request for member %s in something not a struct or union",
4530                         field->name);
4531         }
4532         member = field_type(state, type, field);
4533         if ((type->type & STOR_MASK) == STOR_PERM) {
4534                 /* Do the pointer arithmetic to get a deref the field */
4535                 ulong_t offset;
4536                 offset = field_offset(state, type, field);
4537                 result = do_mk_addr_expr(state, expr, member, offset);
4538                 result = mk_deref_expr(state, result);
4539         }
4540         else {
4541                 /* Find the variable for the field I want. */
4542                 result = triple(state, OP_DOT, member, expr, 0);
4543                 result->u.field = field;
4544         }
4545         return result;
4546 }
4547
4548 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4549 {
4550         int op;
4551         if  (!def) {
4552                 return 0;
4553         }
4554         if (!is_stable(state, def)) {
4555                 return def;
4556         }
4557         /* Tranform an array to a pointer to the first element */
4558 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4559         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4560                 struct type *type;
4561                 struct triple *result;
4562                 type = new_type(
4563                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4564                         def->type->left, 0);
4565                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4566                 MISC(result, 0) = def;
4567                 return result;
4568         }
4569         if (is_in_reg(state, def)) {
4570                 op = OP_READ;
4571         } else {
4572                 op = OP_LOAD;
4573         }
4574         return triple(state, op, def->type, def, 0);
4575 }
4576
4577 static void write_compatible(struct compile_state *state,
4578         struct type *dest, struct type *rval)
4579 {
4580         int compatible = 0;
4581         /* Both operands have arithmetic type */
4582         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4583                 compatible = 1;
4584         }
4585         /* One operand is a pointer and the other is a pointer to void */
4586         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4587                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4588                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4589                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4590                 compatible = 1;
4591         }
4592         /* If both types are the same without qualifiers we are good */
4593         else if (equiv_ptrs(dest, rval)) {
4594                 compatible = 1;
4595         }
4596         /* test for struct/union equality  */
4597         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4598                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4599                 (dest->type_ident == rval->type_ident)) {
4600                 compatible = 1;
4601         }
4602         if (!compatible) {
4603                 error(state, 0, "Incompatible types in assignment");
4604         }
4605 }
4606
4607 static struct triple *write_expr(
4608         struct compile_state *state, struct triple *dest, struct triple *rval)
4609 {
4610         struct triple *def;
4611         int op;
4612
4613         def = 0;
4614         if (!rval) {
4615                 internal_error(state, 0, "missing rval");
4616         }
4617
4618         if (rval->op == OP_LIST) {
4619                 internal_error(state, 0, "expression of type OP_LIST?");
4620         }
4621         if (!is_lvalue(state, dest)) {
4622                 internal_error(state, 0, "writing to a non lvalue?");
4623         }
4624         if (dest->type->type & QUAL_CONST) {
4625                 internal_error(state, 0, "modifable lvalue expexted");
4626         }
4627
4628         write_compatible(state, dest->type, rval->type);
4629
4630         /* Now figure out which assignment operator to use */
4631         op = -1;
4632         if (is_in_reg(state, dest)) {
4633                 op = OP_WRITE;
4634         } else {
4635                 op = OP_STORE;
4636         }
4637         def = triple(state, op, dest->type, dest, rval);
4638         return def;
4639 }
4640
4641 static struct triple *init_expr(
4642         struct compile_state *state, struct triple *dest, struct triple *rval)
4643 {
4644         struct triple *def;
4645
4646         def = 0;
4647         if (!rval) {
4648                 internal_error(state, 0, "missing rval");
4649         }
4650         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4651                 rval = read_expr(state, rval);
4652                 def = write_expr(state, dest, rval);
4653         }
4654         else {
4655                 /* Fill in the array size if necessary */
4656                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4657                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4658                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4659                                 dest->type->elements = rval->type->elements;
4660                         }
4661                 }
4662                 if (!equiv_types(dest->type, rval->type)) {
4663                         error(state, 0, "Incompatible types in inializer");
4664                 }
4665                 MISC(dest, 0) = rval;
4666                 insert_triple(state, dest, rval);
4667                 rval->id |= TRIPLE_FLAG_FLATTENED;
4668                 use_triple(MISC(dest, 0), dest);
4669         }
4670         return def;
4671 }
4672
4673 struct type *arithmetic_result(
4674         struct compile_state *state, struct triple *left, struct triple *right)
4675 {
4676         struct type *type;
4677         /* Sanity checks to ensure I am working with arithmetic types */
4678         arithmetic(state, left);
4679         arithmetic(state, right);
4680         type = new_type(
4681                 do_arithmetic_conversion(
4682                         left->type->type, 
4683                         right->type->type), 0, 0);
4684         return type;
4685 }
4686
4687 struct type *ptr_arithmetic_result(
4688         struct compile_state *state, struct triple *left, struct triple *right)
4689 {
4690         struct type *type;
4691         /* Sanity checks to ensure I am working with the proper types */
4692         ptr_arithmetic(state, left);
4693         arithmetic(state, right);
4694         if (TYPE_ARITHMETIC(left->type->type) && 
4695                 TYPE_ARITHMETIC(right->type->type)) {
4696                 type = arithmetic_result(state, left, right);
4697         }
4698         else if (TYPE_PTR(left->type->type)) {
4699                 type = left->type;
4700         }
4701         else {
4702                 internal_error(state, 0, "huh?");
4703                 type = 0;
4704         }
4705         return type;
4706 }
4707
4708
4709 /* boolean helper function */
4710
4711 static struct triple *ltrue_expr(struct compile_state *state, 
4712         struct triple *expr)
4713 {
4714         switch(expr->op) {
4715         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4716         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4717         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4718                 /* If the expression is already boolean do nothing */
4719                 break;
4720         default:
4721                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4722                 break;
4723         }
4724         return expr;
4725 }
4726
4727 static struct triple *lfalse_expr(struct compile_state *state, 
4728         struct triple *expr)
4729 {
4730         return triple(state, OP_LFALSE, &int_type, expr, 0);
4731 }
4732
4733 static struct triple *cond_expr(
4734         struct compile_state *state, 
4735         struct triple *test, struct triple *left, struct triple *right)
4736 {
4737         struct triple *def;
4738         struct type *result_type;
4739         unsigned int left_type, right_type;
4740         bool(state, test);
4741         left_type = left->type->type;
4742         right_type = right->type->type;
4743         result_type = 0;
4744         /* Both operands have arithmetic type */
4745         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4746                 result_type = arithmetic_result(state, left, right);
4747         }
4748         /* Both operands have void type */
4749         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4750                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4751                 result_type = &void_type;
4752         }
4753         /* pointers to the same type... */
4754         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4755                 ;
4756         }
4757         /* Both operands are pointers and left is a pointer to void */
4758         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4759                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4760                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4761                 result_type = right->type;
4762         }
4763         /* Both operands are pointers and right is a pointer to void */
4764         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4765                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4766                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4767                 result_type = left->type;
4768         }
4769         if (!result_type) {
4770                 error(state, 0, "Incompatible types in conditional expression");
4771         }
4772         /* Cleanup and invert the test */
4773         test = lfalse_expr(state, read_expr(state, test));
4774         def = new_triple(state, OP_COND, result_type, 0, 3);
4775         def->param[0] = test;
4776         def->param[1] = left;
4777         def->param[2] = right;
4778         return def;
4779 }
4780
4781
4782 static int expr_depth(struct compile_state *state, struct triple *ins)
4783 {
4784         int count;
4785         count = 0;
4786         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4787                 count = 0;
4788         }
4789         else if (ins->op == OP_DEREF) {
4790                 count = expr_depth(state, RHS(ins, 0)) - 1;
4791         }
4792         else if (ins->op == OP_VAL) {
4793                 count = expr_depth(state, RHS(ins, 0)) - 1;
4794         }
4795         else if (ins->op == OP_COMMA) {
4796                 int ldepth, rdepth;
4797                 ldepth = expr_depth(state, RHS(ins, 0));
4798                 rdepth = expr_depth(state, RHS(ins, 1));
4799                 count = (ldepth >= rdepth)? ldepth : rdepth;
4800         }
4801         else if (ins->op == OP_CALL) {
4802                 /* Don't figure the depth of a call just guess it is huge */
4803                 count = 1000;
4804         }
4805         else {
4806                 struct triple **expr;
4807                 expr = triple_rhs(state, ins, 0);
4808                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4809                         if (*expr) {
4810                                 int depth;
4811                                 depth = expr_depth(state, *expr);
4812                                 if (depth > count) {
4813                                         count = depth;
4814                                 }
4815                         }
4816                 }
4817         }
4818         return count + 1;
4819 }
4820
4821 static struct triple *flatten(
4822         struct compile_state *state, struct triple *first, struct triple *ptr);
4823
4824 static struct triple *flatten_generic(
4825         struct compile_state *state, struct triple *first, struct triple *ptr)
4826 {
4827         struct rhs_vector {
4828                 int depth;
4829                 struct triple **ins;
4830         } vector[MAX_RHS];
4831         int i, rhs, lhs;
4832         /* Only operations with just a rhs should come here */
4833         rhs = TRIPLE_RHS(ptr->sizes);
4834         lhs = TRIPLE_LHS(ptr->sizes);
4835         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4836                 internal_error(state, ptr, "unexpected args for: %d %s",
4837                         ptr->op, tops(ptr->op));
4838         }
4839         /* Find the depth of the rhs elements */
4840         for(i = 0; i < rhs; i++) {
4841                 vector[i].ins = &RHS(ptr, i);
4842                 vector[i].depth = expr_depth(state, *vector[i].ins);
4843         }
4844         /* Selection sort the rhs */
4845         for(i = 0; i < rhs; i++) {
4846                 int j, max = i;
4847                 for(j = i + 1; j < rhs; j++ ) {
4848                         if (vector[j].depth > vector[max].depth) {
4849                                 max = j;
4850                         }
4851                 }
4852                 if (max != i) {
4853                         struct rhs_vector tmp;
4854                         tmp = vector[i];
4855                         vector[i] = vector[max];
4856                         vector[max] = tmp;
4857                 }
4858         }
4859         /* Now flatten the rhs elements */
4860         for(i = 0; i < rhs; i++) {
4861                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4862                 use_triple(*vector[i].ins, ptr);
4863         }
4864         
4865         /* Now flatten the lhs elements */
4866         for(i = 0; i < lhs; i++) {
4867                 struct triple **ins = &LHS(ptr, i);
4868                 *ins = flatten(state, first, *ins);
4869                 use_triple(*ins, ptr);
4870         }
4871         return ptr;
4872 }
4873
4874 static struct triple *flatten_land(
4875         struct compile_state *state, struct triple *first, struct triple *ptr)
4876 {
4877         struct triple *left, *right;
4878         struct triple *val, *test, *jmp, *label1, *end;
4879
4880         /* Find the triples */
4881         left = RHS(ptr, 0);
4882         right = RHS(ptr, 1);
4883
4884         /* Generate the needed triples */
4885         end = label(state);
4886
4887         /* Thread the triples together */
4888         val          = flatten(state, first, variable(state, ptr->type));
4889         left         = flatten(state, first, write_expr(state, val, left));
4890         test         = flatten(state, first, 
4891                 lfalse_expr(state, read_expr(state, val)));
4892         jmp          = flatten(state, first, branch(state, end, test));
4893         label1       = flatten(state, first, label(state));
4894         right        = flatten(state, first, write_expr(state, val, right));
4895         TARG(jmp, 0) = flatten(state, first, end); 
4896         
4897         /* Now give the caller something to chew on */
4898         return read_expr(state, val);
4899 }
4900
4901 static struct triple *flatten_lor(
4902         struct compile_state *state, struct triple *first, struct triple *ptr)
4903 {
4904         struct triple *left, *right;
4905         struct triple *val, *jmp, *label1, *end;
4906
4907         /* Find the triples */
4908         left = RHS(ptr, 0);
4909         right = RHS(ptr, 1);
4910
4911         /* Generate the needed triples */
4912         end = label(state);
4913
4914         /* Thread the triples together */
4915         val          = flatten(state, first, variable(state, ptr->type));
4916         left         = flatten(state, first, write_expr(state, val, left));
4917         jmp          = flatten(state, first, branch(state, end, left));
4918         label1       = flatten(state, first, label(state));
4919         right        = flatten(state, first, write_expr(state, val, right));
4920         TARG(jmp, 0) = flatten(state, first, end);
4921        
4922         
4923         /* Now give the caller something to chew on */
4924         return read_expr(state, val);
4925 }
4926
4927 static struct triple *flatten_cond(
4928         struct compile_state *state, struct triple *first, struct triple *ptr)
4929 {
4930         struct triple *test, *left, *right;
4931         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4932
4933         /* Find the triples */
4934         test = RHS(ptr, 0);
4935         left = RHS(ptr, 1);
4936         right = RHS(ptr, 2);
4937
4938         /* Generate the needed triples */
4939         end = label(state);
4940         middle = label(state);
4941
4942         /* Thread the triples together */
4943         val           = flatten(state, first, variable(state, ptr->type));
4944         test          = flatten(state, first, test);
4945         jmp1          = flatten(state, first, branch(state, middle, test));
4946         label1        = flatten(state, first, label(state));
4947         left          = flatten(state, first, left);
4948         mv1           = flatten(state, first, write_expr(state, val, left));
4949         jmp2          = flatten(state, first, branch(state, end, 0));
4950         TARG(jmp1, 0) = flatten(state, first, middle);
4951         right         = flatten(state, first, right);
4952         mv2           = flatten(state, first, write_expr(state, val, right));
4953         TARG(jmp2, 0) = flatten(state, first, end);
4954         
4955         /* Now give the caller something to chew on */
4956         return read_expr(state, val);
4957 }
4958
4959 struct triple *copy_func(struct compile_state *state, struct triple *ofunc, 
4960         struct occurance *base_occurance)
4961 {
4962         struct triple *nfunc;
4963         struct triple *nfirst, *ofirst;
4964         struct triple *new, *old;
4965
4966 #if 0
4967         fprintf(stdout, "\n");
4968         loc(stdout, state, 0);
4969         fprintf(stdout, "\n__________ copy_func _________\n");
4970         print_triple(state, ofunc);
4971         fprintf(stdout, "__________ copy_func _________ done\n\n");
4972 #endif
4973
4974         /* Make a new copy of the old function */
4975         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4976         nfirst = 0;
4977         ofirst = old = RHS(ofunc, 0);
4978         do {
4979                 struct triple *new;
4980                 struct occurance *occurance;
4981                 int old_lhs, old_rhs;
4982                 old_lhs = TRIPLE_LHS(old->sizes);
4983                 old_rhs = TRIPLE_RHS(old->sizes);
4984                 occurance = inline_occurance(state, base_occurance, old->occurance);
4985                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4986                         occurance);
4987                 if (!triple_stores_block(state, new)) {
4988                         memcpy(&new->u, &old->u, sizeof(new->u));
4989                 }
4990                 if (!nfirst) {
4991                         RHS(nfunc, 0) = nfirst = new;
4992                 }
4993                 else {
4994                         insert_triple(state, nfirst, new);
4995                 }
4996                 new->id |= TRIPLE_FLAG_FLATTENED;
4997                 
4998                 /* During the copy remember new as user of old */
4999                 use_triple(old, new);
5000
5001                 /* Populate the return type if present */
5002                 if (old == MISC(ofunc, 0)) {
5003                         MISC(nfunc, 0) = new;
5004                 }
5005                 old = old->next;
5006         } while(old != ofirst);
5007
5008         /* Make a second pass to fix up any unresolved references */
5009         old = ofirst;
5010         new = nfirst;
5011         do {
5012                 struct triple **oexpr, **nexpr;
5013                 int count, i;
5014                 /* Lookup where the copy is, to join pointers */
5015                 count = TRIPLE_SIZE(old->sizes);
5016                 for(i = 0; i < count; i++) {
5017                         oexpr = &old->param[i];
5018                         nexpr = &new->param[i];
5019                         if (!*nexpr && *oexpr && (*oexpr)->use) {
5020                                 *nexpr = (*oexpr)->use->member;
5021                                 if (*nexpr == old) {
5022                                         internal_error(state, 0, "new == old?");
5023                                 }
5024                                 use_triple(*nexpr, new);
5025                         }
5026                         if (!*nexpr && *oexpr) {
5027                                 internal_error(state, 0, "Could not copy %d\n", i);
5028                         }
5029                 }
5030                 old = old->next;
5031                 new = new->next;
5032         } while((old != ofirst) && (new != nfirst));
5033         
5034         /* Make a third pass to cleanup the extra useses */
5035         old = ofirst;
5036         new = nfirst;
5037         do {
5038                 unuse_triple(old, new);
5039                 old = old->next;
5040                 new = new->next;
5041         } while ((old != ofirst) && (new != nfirst));
5042         return nfunc;
5043 }
5044
5045 static struct triple *flatten_call(
5046         struct compile_state *state, struct triple *first, struct triple *ptr)
5047 {
5048         /* Inline the function call */
5049         struct type *ptype;
5050         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5051         struct triple *end, *nend;
5052         int pvals, i;
5053
5054         /* Find the triples */
5055         ofunc = MISC(ptr, 0);
5056         if (ofunc->op != OP_LIST) {
5057                 internal_error(state, 0, "improper function");
5058         }
5059         nfunc = copy_func(state, ofunc, ptr->occurance);
5060         nfirst = RHS(nfunc, 0)->next;
5061         /* Prepend the parameter reading into the new function list */
5062         ptype = nfunc->type->right;
5063         param = RHS(nfunc, 0)->next;
5064         pvals = TRIPLE_RHS(ptr->sizes);
5065         for(i = 0; i < pvals; i++) {
5066                 struct type *atype;
5067                 struct triple *arg;
5068                 atype = ptype;
5069                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5070                         atype = ptype->left;
5071                 }
5072                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5073                         param = param->next;
5074                 }
5075                 arg = RHS(ptr, i);
5076                 flatten(state, nfirst, write_expr(state, param, arg));
5077                 ptype = ptype->right;
5078                 param = param->next;
5079         }
5080         result = 0;
5081         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5082                 result = read_expr(state, MISC(nfunc,0));
5083         }
5084 #if 0
5085         fprintf(stdout, "\n");
5086         loc(stdout, state, 0);
5087         fprintf(stdout, "\n__________ flatten_call _________\n");
5088         print_triple(state, nfunc);
5089         fprintf(stdout, "__________ flatten_call _________ done\n\n");
5090 #endif
5091
5092         /* Get rid of the extra triples */
5093         nfirst = RHS(nfunc, 0)->next;
5094         free_triple(state, RHS(nfunc, 0));
5095         RHS(nfunc, 0) = 0;
5096         free_triple(state, nfunc);
5097
5098         /* Append the new function list onto the return list */
5099         end = first->prev;
5100         nend = nfirst->prev;
5101         end->next    = nfirst;
5102         nfirst->prev = end;
5103         nend->next   = first;
5104         first->prev  = nend;
5105
5106         return result;
5107 }
5108
5109 static struct triple *flatten(
5110         struct compile_state *state, struct triple *first, struct triple *ptr)
5111 {
5112         struct triple *orig_ptr;
5113         if (!ptr)
5114                 return 0;
5115         do {
5116                 orig_ptr = ptr;
5117                 /* Only flatten triples once */
5118                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5119                         return ptr;
5120                 }
5121                 switch(ptr->op) {
5122                 case OP_WRITE:
5123                 case OP_STORE:
5124                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5125                         LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
5126                         use_triple(LHS(ptr, 0), ptr);
5127                         use_triple(RHS(ptr, 0), ptr);
5128                         break;
5129                 case OP_COMMA:
5130                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5131                         ptr = RHS(ptr, 1);
5132                         break;
5133                 case OP_VAL:
5134                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5135                         return MISC(ptr, 0);
5136                         break;
5137                 case OP_LAND:
5138                         ptr = flatten_land(state, first, ptr);
5139                         break;
5140                 case OP_LOR:
5141                         ptr = flatten_lor(state, first, ptr);
5142                         break;
5143                 case OP_COND:
5144                         ptr = flatten_cond(state, first, ptr);
5145                         break;
5146                 case OP_CALL:
5147                         ptr = flatten_call(state, first, ptr);
5148                         break;
5149                 case OP_READ:
5150                 case OP_LOAD:
5151                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5152                         use_triple(RHS(ptr, 0), ptr);
5153                         break;
5154                 case OP_BRANCH:
5155                         use_triple(TARG(ptr, 0), ptr);
5156                         if (TRIPLE_RHS(ptr->sizes)) {
5157                                 use_triple(RHS(ptr, 0), ptr);
5158                                 if (ptr->next != ptr) {
5159                                         use_triple(ptr->next, ptr);
5160                                 }
5161                         }
5162                         break;
5163                 case OP_BLOBCONST:
5164                         insert_triple(state, first, ptr);
5165                         ptr->id |= TRIPLE_FLAG_FLATTENED;
5166                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5167                         use_triple(MISC(ptr, 0), ptr);
5168                         break;
5169                 case OP_DEREF:
5170                         /* Since OP_DEREF is just a marker delete it when I flatten it */
5171                         ptr = RHS(ptr, 0);
5172                         RHS(orig_ptr, 0) = 0;
5173                         free_triple(state, orig_ptr);
5174                         break;
5175                 case OP_DOT:
5176                 {
5177                         struct triple *base;
5178                         base = RHS(ptr, 0);
5179                         if (base->op == OP_DEREF) {
5180                                 struct triple *left;
5181                                 ulong_t offset;
5182                                 offset = field_offset(state, base->type, ptr->u.field);
5183                                 left = RHS(base, 0);
5184                                 ptr = triple(state, OP_ADD, left->type, 
5185                                         read_expr(state, left),
5186                                         int_const(state, &ulong_type, offset));
5187                                 free_triple(state, base);
5188                         }
5189                         else if (base->op == OP_VAL_VEC) {
5190                                 base = flatten(state, first, base);
5191                                 ptr = struct_field(state, base, ptr->u.field);
5192                         }
5193                         break;
5194                 }
5195                 case OP_PIECE:
5196                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5197                         use_triple(MISC(ptr, 0), ptr);
5198                         use_triple(ptr, MISC(ptr, 0));
5199                         break;
5200                 case OP_ADDRCONST:
5201                 case OP_SDECL:
5202                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5203                         use_triple(MISC(ptr, 0), ptr);
5204                         break;
5205                 case OP_ADECL:
5206                         break;
5207                 default:
5208                         /* Flatten the easy cases we don't override */
5209                         ptr = flatten_generic(state, first, ptr);
5210                         break;
5211                 }
5212         } while(ptr && (ptr != orig_ptr));
5213         if (ptr) {
5214                 insert_triple(state, first, ptr);
5215                 ptr->id |= TRIPLE_FLAG_FLATTENED;
5216         }
5217         return ptr;
5218 }
5219
5220 static void release_expr(struct compile_state *state, struct triple *expr)
5221 {
5222         struct triple *head;
5223         head = label(state);
5224         flatten(state, head, expr);
5225         while(head->next != head) {
5226                 release_triple(state, head->next);
5227         }
5228         free_triple(state, head);
5229 }
5230
5231 static int replace_rhs_use(struct compile_state *state,
5232         struct triple *orig, struct triple *new, struct triple *use)
5233 {
5234         struct triple **expr;
5235         int found;
5236         found = 0;
5237         expr = triple_rhs(state, use, 0);
5238         for(;expr; expr = triple_rhs(state, use, expr)) {
5239                 if (*expr == orig) {
5240                         *expr = new;
5241                         found = 1;
5242                 }
5243         }
5244         if (found) {
5245                 unuse_triple(orig, use);
5246                 use_triple(new, use);
5247         }
5248         return found;
5249 }
5250
5251 static int replace_lhs_use(struct compile_state *state,
5252         struct triple *orig, struct triple *new, struct triple *use)
5253 {
5254         struct triple **expr;
5255         int found;
5256         found = 0;
5257         expr = triple_lhs(state, use, 0);
5258         for(;expr; expr = triple_lhs(state, use, expr)) {
5259                 if (*expr == orig) {
5260                         *expr = new;
5261                         found = 1;
5262                 }
5263         }
5264         if (found) {
5265                 unuse_triple(orig, use);
5266                 use_triple(new, use);
5267         }
5268         return found;
5269 }
5270
5271 static void propogate_use(struct compile_state *state,
5272         struct triple *orig, struct triple *new)
5273 {
5274         struct triple_set *user, *next;
5275         for(user = orig->use; user; user = next) {
5276                 struct triple *use;
5277                 int found;
5278                 next = user->next;
5279                 use = user->member;
5280                 found = 0;
5281                 found |= replace_rhs_use(state, orig, new, use);
5282                 found |= replace_lhs_use(state, orig, new, use);
5283                 if (!found) {
5284                         internal_error(state, use, "use without use");
5285                 }
5286         }
5287         if (orig->use) {
5288                 internal_error(state, orig, "used after propogate_use");
5289         }
5290 }
5291
5292 /*
5293  * Code generators
5294  * ===========================
5295  */
5296
5297 static struct triple *mk_add_expr(
5298         struct compile_state *state, struct triple *left, struct triple *right)
5299 {
5300         struct type *result_type;
5301         /* Put pointer operands on the left */
5302         if (is_pointer(right)) {
5303                 struct triple *tmp;
5304                 tmp = left;
5305                 left = right;
5306                 right = tmp;
5307         }
5308         left  = read_expr(state, left);
5309         right = read_expr(state, right);
5310         result_type = ptr_arithmetic_result(state, left, right);
5311         if (is_pointer(left)) {
5312                 right = triple(state, 
5313                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5314                         &ulong_type, 
5315                         right, 
5316                         int_const(state, &ulong_type, 
5317                                 size_of(state, left->type->left)));
5318         }
5319         return triple(state, OP_ADD, result_type, left, right);
5320 }
5321
5322 static struct triple *mk_sub_expr(
5323         struct compile_state *state, struct triple *left, struct triple *right)
5324 {
5325         struct type *result_type;
5326         result_type = ptr_arithmetic_result(state, left, right);
5327         left  = read_expr(state, left);
5328         right = read_expr(state, right);
5329         if (is_pointer(left)) {
5330                 right = triple(state, 
5331                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5332                         &ulong_type, 
5333                         right, 
5334                         int_const(state, &ulong_type, 
5335                                 size_of(state, left->type->left)));
5336         }
5337         return triple(state, OP_SUB, result_type, left, right);
5338 }
5339
5340 static struct triple *mk_pre_inc_expr(
5341         struct compile_state *state, struct triple *def)
5342 {
5343         struct triple *val;
5344         lvalue(state, def);
5345         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5346         return triple(state, OP_VAL, def->type,
5347                 write_expr(state, def, val),
5348                 val);
5349 }
5350
5351 static struct triple *mk_pre_dec_expr(
5352         struct compile_state *state, struct triple *def)
5353 {
5354         struct triple *val;
5355         lvalue(state, def);
5356         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5357         return triple(state, OP_VAL, def->type,
5358                 write_expr(state, def, val),
5359                 val);
5360 }
5361
5362 static struct triple *mk_post_inc_expr(
5363         struct compile_state *state, struct triple *def)
5364 {
5365         struct triple *val;
5366         lvalue(state, def);
5367         val = read_expr(state, def);
5368         return triple(state, OP_VAL, def->type,
5369                 write_expr(state, def,
5370                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
5371                 , val);
5372 }
5373
5374 static struct triple *mk_post_dec_expr(
5375         struct compile_state *state, struct triple *def)
5376 {
5377         struct triple *val;
5378         lvalue(state, def);
5379         val = read_expr(state, def);
5380         return triple(state, OP_VAL, def->type, 
5381                 write_expr(state, def,
5382                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5383                 , val);
5384 }
5385
5386 static struct triple *mk_subscript_expr(
5387         struct compile_state *state, struct triple *left, struct triple *right)
5388 {
5389         left  = read_expr(state, left);
5390         right = read_expr(state, right);
5391         if (!is_pointer(left) && !is_pointer(right)) {
5392                 error(state, left, "subscripted value is not a pointer");
5393         }
5394         return mk_deref_expr(state, mk_add_expr(state, left, right));
5395 }
5396
5397 /*
5398  * Compile time evaluation
5399  * ===========================
5400  */
5401 static int is_const(struct triple *ins)
5402 {
5403         return IS_CONST_OP(ins->op);
5404 }
5405
5406 static int constants_equal(struct compile_state *state, 
5407         struct triple *left, struct triple *right)
5408 {
5409         int equal;
5410         if (!is_const(left) || !is_const(right)) {
5411                 equal = 0;
5412         }
5413         else if (left->op != right->op) {
5414                 equal = 0;
5415         }
5416         else if (!equiv_types(left->type, right->type)) {
5417                 equal = 0;
5418         }
5419         else {
5420                 equal = 0;
5421                 switch(left->op) {
5422                 case OP_INTCONST:
5423                         if (left->u.cval == right->u.cval) {
5424                                 equal = 1;
5425                         }
5426                         break;
5427                 case OP_BLOBCONST:
5428                 {
5429                         size_t lsize, rsize;
5430                         lsize = size_of(state, left->type);
5431                         rsize = size_of(state, right->type);
5432                         if (lsize != rsize) {
5433                                 break;
5434                         }
5435                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5436                                 equal = 1;
5437                         }
5438                         break;
5439                 }
5440                 case OP_ADDRCONST:
5441                         if ((MISC(left, 0) == MISC(right, 0)) &&
5442                                 (left->u.cval == right->u.cval)) {
5443                                 equal = 1;
5444                         }
5445                         break;
5446                 default:
5447                         internal_error(state, left, "uknown constant type");
5448                         break;
5449                 }
5450         }
5451         return equal;
5452 }
5453
5454 static int is_zero(struct triple *ins)
5455 {
5456         return is_const(ins) && (ins->u.cval == 0);
5457 }
5458
5459 static int is_one(struct triple *ins)
5460 {
5461         return is_const(ins) && (ins->u.cval == 1);
5462 }
5463
5464 static long_t bsr(ulong_t value)
5465 {
5466         int i;
5467         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5468                 ulong_t mask;
5469                 mask = 1;
5470                 mask <<= i;
5471                 if (value & mask) {
5472                         return i;
5473                 }
5474         }
5475         return -1;
5476 }
5477
5478 static long_t bsf(ulong_t value)
5479 {
5480         int i;
5481         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5482                 ulong_t mask;
5483                 mask = 1;
5484                 mask <<= 1;
5485                 if (value & mask) {
5486                         return i;
5487                 }
5488         }
5489         return -1;
5490 }
5491
5492 static long_t log2(ulong_t value)
5493 {
5494         return bsr(value);
5495 }
5496
5497 static long_t tlog2(struct triple *ins)
5498 {
5499         return log2(ins->u.cval);
5500 }
5501
5502 static int is_pow2(struct triple *ins)
5503 {
5504         ulong_t value, mask;
5505         long_t log;
5506         if (!is_const(ins)) {
5507                 return 0;
5508         }
5509         value = ins->u.cval;
5510         log = log2(value);
5511         if (log == -1) {
5512                 return 0;
5513         }
5514         mask = 1;
5515         mask <<= log;
5516         return  ((value & mask) == value);
5517 }
5518
5519 static ulong_t read_const(struct compile_state *state,
5520         struct triple *ins, struct triple **expr)
5521 {
5522         struct triple *rhs;
5523         rhs = *expr;
5524         switch(rhs->type->type &TYPE_MASK) {
5525         case TYPE_CHAR:   
5526         case TYPE_SHORT:
5527         case TYPE_INT:
5528         case TYPE_LONG:
5529         case TYPE_UCHAR:   
5530         case TYPE_USHORT:  
5531         case TYPE_UINT:
5532         case TYPE_ULONG:
5533         case TYPE_POINTER:
5534                 break;
5535         default:
5536                 internal_error(state, rhs, "bad type to read_const\n");
5537                 break;
5538         }
5539         return rhs->u.cval;
5540 }
5541
5542 static long_t read_sconst(struct triple *ins, struct triple **expr)
5543 {
5544         struct triple *rhs;
5545         rhs = *expr;
5546         return (long_t)(rhs->u.cval);
5547 }
5548
5549 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5550 {
5551         struct triple **expr;
5552         expr = triple_rhs(state, ins, 0);
5553         for(;expr;expr = triple_rhs(state, ins, expr)) {
5554                 if (*expr) {
5555                         unuse_triple(*expr, ins);
5556                         *expr = 0;
5557                 }
5558         }
5559 }
5560
5561 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5562 {
5563         struct triple **expr;
5564         expr = triple_lhs(state, ins, 0);
5565         for(;expr;expr = triple_lhs(state, ins, expr)) {
5566                 unuse_triple(*expr, ins);
5567                 *expr = 0;
5568         }
5569 }
5570
5571 static void check_lhs(struct compile_state *state, struct triple *ins)
5572 {
5573         struct triple **expr;
5574         expr = triple_lhs(state, ins, 0);
5575         for(;expr;expr = triple_lhs(state, ins, expr)) {
5576                 internal_error(state, ins, "unexpected lhs");
5577         }
5578         
5579 }
5580 static void check_targ(struct compile_state *state, struct triple *ins)
5581 {
5582         struct triple **expr;
5583         expr = triple_targ(state, ins, 0);
5584         for(;expr;expr = triple_targ(state, ins, expr)) {
5585                 internal_error(state, ins, "unexpected targ");
5586         }
5587 }
5588
5589 static void wipe_ins(struct compile_state *state, struct triple *ins)
5590 {
5591         /* Becareful which instructions you replace the wiped
5592          * instruction with, as there are not enough slots
5593          * in all instructions to hold all others.
5594          */
5595         check_targ(state, ins);
5596         unuse_rhs(state, ins);
5597         unuse_lhs(state, ins);
5598 }
5599
5600 static void mkcopy(struct compile_state *state, 
5601         struct triple *ins, struct triple *rhs)
5602 {
5603         wipe_ins(state, ins);
5604         ins->op = OP_COPY;
5605         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5606         RHS(ins, 0) = rhs;
5607         use_triple(RHS(ins, 0), ins);
5608 }
5609
5610 static void mkconst(struct compile_state *state, 
5611         struct triple *ins, ulong_t value)
5612 {
5613         if (!is_integral(ins) && !is_pointer(ins)) {
5614                 internal_error(state, ins, "unknown type to make constant\n");
5615         }
5616         wipe_ins(state, ins);
5617         ins->op = OP_INTCONST;
5618         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5619         ins->u.cval = value;
5620 }
5621
5622 static void mkaddr_const(struct compile_state *state,
5623         struct triple *ins, struct triple *sdecl, ulong_t value)
5624 {
5625         wipe_ins(state, ins);
5626         ins->op = OP_ADDRCONST;
5627         ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5628         MISC(ins, 0) = sdecl;
5629         ins->u.cval = value;
5630         use_triple(sdecl, ins);
5631 }
5632
5633 /* Transform multicomponent variables into simple register variables */
5634 static void flatten_structures(struct compile_state *state)
5635 {
5636         struct triple *ins, *first;
5637         first = RHS(state->main_function, 0);
5638         ins = first;
5639         /* Pass one expand structure values into valvecs.
5640          */
5641         ins = first;
5642         do {
5643                 struct triple *next;
5644                 next = ins->next;
5645                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5646                         if (ins->op == OP_VAL_VEC) {
5647                                 /* Do nothing */
5648                         }
5649                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5650                                 struct triple *def, **vector;
5651                                 struct type *tptr;
5652                                 int op;
5653                                 ulong_t i;
5654
5655                                 op = ins->op;
5656                                 def = RHS(ins, 0);
5657                                 get_occurance(ins->occurance);
5658                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5659                                         ins->occurance);
5660
5661                                 vector = &RHS(next, 0);
5662                                 tptr = next->type->left;
5663                                 for(i = 0; i < next->type->elements; i++) {
5664                                         struct triple *sfield;
5665                                         struct type *mtype;
5666                                         mtype = tptr;
5667                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5668                                                 mtype = mtype->left;
5669                                         }
5670                                         sfield = deref_field(state, def, mtype->field_ident);
5671                                         
5672                                         vector[i] = triple(
5673                                                 state, op, mtype, sfield, 0);
5674                                         put_occurance(vector[i]->occurance);
5675                                         get_occurance(next->occurance);
5676                                         vector[i]->occurance = next->occurance;
5677                                         tptr = tptr->right;
5678                                 }
5679                                 propogate_use(state, ins, next);
5680                                 flatten(state, ins, next);
5681                                 free_triple(state, ins);
5682                         }
5683                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5684                                 struct triple *src, *dst, **vector;
5685                                 struct type *tptr;
5686                                 int op;
5687                                 ulong_t i;
5688
5689                                 op = ins->op;
5690                                 src = RHS(ins, 0);
5691                                 dst = LHS(ins, 0);
5692                                 get_occurance(ins->occurance);
5693                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5694                                         ins->occurance);
5695                                 
5696                                 vector = &RHS(next, 0);
5697                                 tptr = next->type->left;
5698                                 for(i = 0; i < ins->type->elements; i++) {
5699                                         struct triple *dfield, *sfield;
5700                                         struct type *mtype;
5701                                         mtype = tptr;
5702                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5703                                                 mtype = mtype->left;
5704                                         }
5705                                         sfield = deref_field(state, src, mtype->field_ident);
5706                                         dfield = deref_field(state, dst, mtype->field_ident);
5707                                         vector[i] = triple(
5708                                                 state, op, mtype, dfield, sfield);
5709                                         put_occurance(vector[i]->occurance);
5710                                         get_occurance(next->occurance);
5711                                         vector[i]->occurance = next->occurance;
5712                                         tptr = tptr->right;
5713                                 }
5714                                 propogate_use(state, ins, next);
5715                                 flatten(state, ins, next);
5716                                 free_triple(state, ins);
5717                         }
5718                 }
5719                 ins = next;
5720         } while(ins != first);
5721         /* Pass two flatten the valvecs.
5722          */
5723         ins = first;
5724         do {
5725                 struct triple *next;
5726                 next = ins->next;
5727                 if (ins->op == OP_VAL_VEC) {
5728                         release_triple(state, ins);
5729                 } 
5730                 ins = next;
5731         } while(ins != first);
5732         /* Pass three verify the state and set ->id to 0.
5733          */
5734         ins = first;
5735         do {
5736                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5737                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5738                         internal_error(state, ins, "STRUCT_TYPE remains?");
5739                 }
5740                 if (ins->op == OP_DOT) {
5741                         internal_error(state, ins, "OP_DOT remains?");
5742                 }
5743                 if (ins->op == OP_VAL_VEC) {
5744                         internal_error(state, ins, "OP_VAL_VEC remains?");
5745                 }
5746                 ins = ins->next;
5747         } while(ins != first);
5748 }
5749
5750 /* For those operations that cannot be simplified */
5751 static void simplify_noop(struct compile_state *state, struct triple *ins)
5752 {
5753         return;
5754 }
5755
5756 static void simplify_smul(struct compile_state *state, struct triple *ins)
5757 {
5758         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5759                 struct triple *tmp;
5760                 tmp = RHS(ins, 0);
5761                 RHS(ins, 0) = RHS(ins, 1);
5762                 RHS(ins, 1) = tmp;
5763         }
5764         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5765                 long_t left, right;
5766                 left  = read_sconst(ins, &RHS(ins, 0));
5767                 right = read_sconst(ins, &RHS(ins, 1));
5768                 mkconst(state, ins, left * right);
5769         }
5770         else if (is_zero(RHS(ins, 1))) {
5771                 mkconst(state, ins, 0);
5772         }
5773         else if (is_one(RHS(ins, 1))) {
5774                 mkcopy(state, ins, RHS(ins, 0));
5775         }
5776         else if (is_pow2(RHS(ins, 1))) {
5777                 struct triple *val;
5778                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5779                 ins->op = OP_SL;
5780                 insert_triple(state, ins, val);
5781                 unuse_triple(RHS(ins, 1), ins);
5782                 use_triple(val, ins);
5783                 RHS(ins, 1) = val;
5784         }
5785 }
5786
5787 static void simplify_umul(struct compile_state *state, struct triple *ins)
5788 {
5789         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5790                 struct triple *tmp;
5791                 tmp = RHS(ins, 0);
5792                 RHS(ins, 0) = RHS(ins, 1);
5793                 RHS(ins, 1) = tmp;
5794         }
5795         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5796                 ulong_t left, right;
5797                 left  = read_const(state, ins, &RHS(ins, 0));
5798                 right = read_const(state, ins, &RHS(ins, 1));
5799                 mkconst(state, ins, left * right);
5800         }
5801         else if (is_zero(RHS(ins, 1))) {
5802                 mkconst(state, ins, 0);
5803         }
5804         else if (is_one(RHS(ins, 1))) {
5805                 mkcopy(state, ins, RHS(ins, 0));
5806         }
5807         else if (is_pow2(RHS(ins, 1))) {
5808                 struct triple *val;
5809                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5810                 ins->op = OP_SL;
5811                 insert_triple(state, ins, val);
5812                 unuse_triple(RHS(ins, 1), ins);
5813                 use_triple(val, ins);
5814                 RHS(ins, 1) = val;
5815         }
5816 }
5817
5818 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5819 {
5820         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5821                 long_t left, right;
5822                 left  = read_sconst(ins, &RHS(ins, 0));
5823                 right = read_sconst(ins, &RHS(ins, 1));
5824                 mkconst(state, ins, left / right);
5825         }
5826         else if (is_zero(RHS(ins, 0))) {
5827                 mkconst(state, ins, 0);
5828         }
5829         else if (is_zero(RHS(ins, 1))) {
5830                 error(state, ins, "division by zero");
5831         }
5832         else if (is_one(RHS(ins, 1))) {
5833                 mkcopy(state, ins, RHS(ins, 0));
5834         }
5835         else if (is_pow2(RHS(ins, 1))) {
5836                 struct triple *val;
5837                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5838                 ins->op = OP_SSR;
5839                 insert_triple(state, ins, val);
5840                 unuse_triple(RHS(ins, 1), ins);
5841                 use_triple(val, ins);
5842                 RHS(ins, 1) = val;
5843         }
5844 }
5845
5846 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5847 {
5848         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5849                 ulong_t left, right;
5850                 left  = read_const(state, ins, &RHS(ins, 0));
5851                 right = read_const(state, ins, &RHS(ins, 1));
5852                 mkconst(state, ins, left / right);
5853         }
5854         else if (is_zero(RHS(ins, 0))) {
5855                 mkconst(state, ins, 0);
5856         }
5857         else if (is_zero(RHS(ins, 1))) {
5858                 error(state, ins, "division by zero");
5859         }
5860         else if (is_one(RHS(ins, 1))) {
5861                 mkcopy(state, ins, RHS(ins, 0));
5862         }
5863         else if (is_pow2(RHS(ins, 1))) {
5864                 struct triple *val;
5865                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5866                 ins->op = OP_USR;
5867                 insert_triple(state, ins, val);
5868                 unuse_triple(RHS(ins, 1), ins);
5869                 use_triple(val, ins);
5870                 RHS(ins, 1) = val;
5871         }
5872 }
5873
5874 static void simplify_smod(struct compile_state *state, struct triple *ins)
5875 {
5876         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5877                 long_t left, right;
5878                 left  = read_const(state, ins, &RHS(ins, 0));
5879                 right = read_const(state, ins, &RHS(ins, 1));
5880                 mkconst(state, ins, left % right);
5881         }
5882         else if (is_zero(RHS(ins, 0))) {
5883                 mkconst(state, ins, 0);
5884         }
5885         else if (is_zero(RHS(ins, 1))) {
5886                 error(state, ins, "division by zero");
5887         }
5888         else if (is_one(RHS(ins, 1))) {
5889                 mkconst(state, ins, 0);
5890         }
5891         else if (is_pow2(RHS(ins, 1))) {
5892                 struct triple *val;
5893                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5894                 ins->op = OP_AND;
5895                 insert_triple(state, ins, val);
5896                 unuse_triple(RHS(ins, 1), ins);
5897                 use_triple(val, ins);
5898                 RHS(ins, 1) = val;
5899         }
5900 }
5901 static void simplify_umod(struct compile_state *state, struct triple *ins)
5902 {
5903         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5904                 ulong_t left, right;
5905                 left  = read_const(state, ins, &RHS(ins, 0));
5906                 right = read_const(state, ins, &RHS(ins, 1));
5907                 mkconst(state, ins, left % right);
5908         }
5909         else if (is_zero(RHS(ins, 0))) {
5910                 mkconst(state, ins, 0);
5911         }
5912         else if (is_zero(RHS(ins, 1))) {
5913                 error(state, ins, "division by zero");
5914         }
5915         else if (is_one(RHS(ins, 1))) {
5916                 mkconst(state, ins, 0);
5917         }
5918         else if (is_pow2(RHS(ins, 1))) {
5919                 struct triple *val;
5920                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5921                 ins->op = OP_AND;
5922                 insert_triple(state, ins, val);
5923                 unuse_triple(RHS(ins, 1), ins);
5924                 use_triple(val, ins);
5925                 RHS(ins, 1) = val;
5926         }
5927 }
5928
5929 static void simplify_add(struct compile_state *state, struct triple *ins)
5930 {
5931         /* start with the pointer on the left */
5932         if (is_pointer(RHS(ins, 1))) {
5933                 struct triple *tmp;
5934                 tmp = RHS(ins, 0);
5935                 RHS(ins, 0) = RHS(ins, 1);
5936                 RHS(ins, 1) = tmp;
5937         }
5938         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5939                 if (!is_pointer(RHS(ins, 0))) {
5940                         ulong_t left, right;
5941                         left  = read_const(state, ins, &RHS(ins, 0));
5942                         right = read_const(state, ins, &RHS(ins, 1));
5943                         mkconst(state, ins, left + right);
5944                 }
5945                 else /* op == OP_ADDRCONST */ {
5946                         struct triple *sdecl;
5947                         ulong_t left, right;
5948                         sdecl = MISC(RHS(ins, 0), 0);
5949                         left  = RHS(ins, 0)->u.cval;
5950                         right = RHS(ins, 1)->u.cval;
5951                         mkaddr_const(state, ins, sdecl, left + right);
5952                 }
5953         }
5954         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5955                 struct triple *tmp;
5956                 tmp = RHS(ins, 1);
5957                 RHS(ins, 1) = RHS(ins, 0);
5958                 RHS(ins, 0) = tmp;
5959         }
5960 }
5961
5962 static void simplify_sub(struct compile_state *state, struct triple *ins)
5963 {
5964         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5965                 if (!is_pointer(RHS(ins, 0))) {
5966                         ulong_t left, right;
5967                         left  = read_const(state, ins, &RHS(ins, 0));
5968                         right = read_const(state, ins, &RHS(ins, 1));
5969                         mkconst(state, ins, left - right);
5970                 }
5971                 else /* op == OP_ADDRCONST */ {
5972                         struct triple *sdecl;
5973                         ulong_t left, right;
5974                         sdecl = MISC(RHS(ins, 0), 0);
5975                         left  = RHS(ins, 0)->u.cval;
5976                         right = RHS(ins, 1)->u.cval;
5977                         mkaddr_const(state, ins, sdecl, left - right);
5978                 }
5979         }
5980 }
5981
5982 static void simplify_sl(struct compile_state *state, struct triple *ins)
5983 {
5984         if (is_const(RHS(ins, 1))) {
5985                 ulong_t right;
5986                 right = read_const(state, ins, &RHS(ins, 1));
5987                 if (right >= (size_of(state, ins->type)*8)) {
5988                         warning(state, ins, "left shift count >= width of type");
5989                 }
5990         }
5991         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5992                 ulong_t left, right;
5993                 left  = read_const(state, ins, &RHS(ins, 0));
5994                 right = read_const(state, ins, &RHS(ins, 1));
5995                 mkconst(state, ins,  left << right);
5996         }
5997 }
5998
5999 static void simplify_usr(struct compile_state *state, struct triple *ins)
6000 {
6001         if (is_const(RHS(ins, 1))) {
6002                 ulong_t right;
6003                 right = read_const(state, ins, &RHS(ins, 1));
6004                 if (right >= (size_of(state, ins->type)*8)) {
6005                         warning(state, ins, "right shift count >= width of type");
6006                 }
6007         }
6008         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6009                 ulong_t left, right;
6010                 left  = read_const(state, ins, &RHS(ins, 0));
6011                 right = read_const(state, ins, &RHS(ins, 1));
6012                 mkconst(state, ins, left >> right);
6013         }
6014 }
6015
6016 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6017 {
6018         if (is_const(RHS(ins, 1))) {
6019                 ulong_t right;
6020                 right = read_const(state, ins, &RHS(ins, 1));
6021                 if (right >= (size_of(state, ins->type)*8)) {
6022                         warning(state, ins, "right shift count >= width of type");
6023                 }
6024         }
6025         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6026                 long_t left, right;
6027                 left  = read_sconst(ins, &RHS(ins, 0));
6028                 right = read_sconst(ins, &RHS(ins, 1));
6029                 mkconst(state, ins, left >> right);
6030         }
6031 }
6032
6033 static void simplify_and(struct compile_state *state, struct triple *ins)
6034 {
6035         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6036                 ulong_t left, right;
6037                 left  = read_const(state, ins, &RHS(ins, 0));
6038                 right = read_const(state, ins, &RHS(ins, 1));
6039                 mkconst(state, ins, left & right);
6040         }
6041 }
6042
6043 static void simplify_or(struct compile_state *state, struct triple *ins)
6044 {
6045         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6046                 ulong_t left, right;
6047                 left  = read_const(state, ins, &RHS(ins, 0));
6048                 right = read_const(state, ins, &RHS(ins, 1));
6049                 mkconst(state, ins, left | right);
6050         }
6051 }
6052
6053 static void simplify_xor(struct compile_state *state, struct triple *ins)
6054 {
6055         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6056                 ulong_t left, right;
6057                 left  = read_const(state, ins, &RHS(ins, 0));
6058                 right = read_const(state, ins, &RHS(ins, 1));
6059                 mkconst(state, ins, left ^ right);
6060         }
6061 }
6062
6063 static void simplify_pos(struct compile_state *state, struct triple *ins)
6064 {
6065         if (is_const(RHS(ins, 0))) {
6066                 mkconst(state, ins, RHS(ins, 0)->u.cval);
6067         }
6068         else {
6069                 mkcopy(state, ins, RHS(ins, 0));
6070         }
6071 }
6072
6073 static void simplify_neg(struct compile_state *state, struct triple *ins)
6074 {
6075         if (is_const(RHS(ins, 0))) {
6076                 ulong_t left;
6077                 left = read_const(state, ins, &RHS(ins, 0));
6078                 mkconst(state, ins, -left);
6079         }
6080         else if (RHS(ins, 0)->op == OP_NEG) {
6081                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6082         }
6083 }
6084
6085 static void simplify_invert(struct compile_state *state, struct triple *ins)
6086 {
6087         if (is_const(RHS(ins, 0))) {
6088                 ulong_t left;
6089                 left = read_const(state, ins, &RHS(ins, 0));
6090                 mkconst(state, ins, ~left);
6091         }
6092 }
6093
6094 static void simplify_eq(struct compile_state *state, struct triple *ins)
6095 {
6096         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6097                 ulong_t left, right;
6098                 left  = read_const(state, ins, &RHS(ins, 0));
6099                 right = read_const(state, ins, &RHS(ins, 1));
6100                 mkconst(state, ins, left == right);
6101         }
6102         else if (RHS(ins, 0) == RHS(ins, 1)) {
6103                 mkconst(state, ins, 1);
6104         }
6105 }
6106
6107 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6108 {
6109         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6110                 ulong_t left, right;
6111                 left  = read_const(state, ins, &RHS(ins, 0));
6112                 right = read_const(state, ins, &RHS(ins, 1));
6113                 mkconst(state, ins, left != right);
6114         }
6115         else if (RHS(ins, 0) == RHS(ins, 1)) {
6116                 mkconst(state, ins, 0);
6117         }
6118 }
6119
6120 static void simplify_sless(struct compile_state *state, struct triple *ins)
6121 {
6122         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6123                 long_t left, right;
6124                 left  = read_sconst(ins, &RHS(ins, 0));
6125                 right = read_sconst(ins, &RHS(ins, 1));
6126                 mkconst(state, ins, left < right);
6127         }
6128         else if (RHS(ins, 0) == RHS(ins, 1)) {
6129                 mkconst(state, ins, 0);
6130         }
6131 }
6132
6133 static void simplify_uless(struct compile_state *state, struct triple *ins)
6134 {
6135         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6136                 ulong_t left, right;
6137                 left  = read_const(state, ins, &RHS(ins, 0));
6138                 right = read_const(state, ins, &RHS(ins, 1));
6139                 mkconst(state, ins, left < right);
6140         }
6141         else if (is_zero(RHS(ins, 0))) {
6142                 mkconst(state, ins, 1);
6143         }
6144         else if (RHS(ins, 0) == RHS(ins, 1)) {
6145                 mkconst(state, ins, 0);
6146         }
6147 }
6148
6149 static void simplify_smore(struct compile_state *state, struct triple *ins)
6150 {
6151         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6152                 long_t left, right;
6153                 left  = read_sconst(ins, &RHS(ins, 0));
6154                 right = read_sconst(ins, &RHS(ins, 1));
6155                 mkconst(state, ins, left > right);
6156         }
6157         else if (RHS(ins, 0) == RHS(ins, 1)) {
6158                 mkconst(state, ins, 0);
6159         }
6160 }
6161
6162 static void simplify_umore(struct compile_state *state, struct triple *ins)
6163 {
6164         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6165                 ulong_t left, right;
6166                 left  = read_const(state, ins, &RHS(ins, 0));
6167                 right = read_const(state, ins, &RHS(ins, 1));
6168                 mkconst(state, ins, left > right);
6169         }
6170         else if (is_zero(RHS(ins, 1))) {
6171                 mkconst(state, ins, 1);
6172         }
6173         else if (RHS(ins, 0) == RHS(ins, 1)) {
6174                 mkconst(state, ins, 0);
6175         }
6176 }
6177
6178
6179 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6180 {
6181         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6182                 long_t left, right;
6183                 left  = read_sconst(ins, &RHS(ins, 0));
6184                 right = read_sconst(ins, &RHS(ins, 1));
6185                 mkconst(state, ins, left <= right);
6186         }
6187         else if (RHS(ins, 0) == RHS(ins, 1)) {
6188                 mkconst(state, ins, 1);
6189         }
6190 }
6191
6192 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6193 {
6194         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6195                 ulong_t left, right;
6196                 left  = read_const(state, ins, &RHS(ins, 0));
6197                 right = read_const(state, ins, &RHS(ins, 1));
6198                 mkconst(state, ins, left <= right);
6199         }
6200         else if (is_zero(RHS(ins, 0))) {
6201                 mkconst(state, ins, 1);
6202         }
6203         else if (RHS(ins, 0) == RHS(ins, 1)) {
6204                 mkconst(state, ins, 1);
6205         }
6206 }
6207
6208 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6209 {
6210         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6211                 long_t left, right;
6212                 left  = read_sconst(ins, &RHS(ins, 0));
6213                 right = read_sconst(ins, &RHS(ins, 1));
6214                 mkconst(state, ins, left >= right);
6215         }
6216         else if (RHS(ins, 0) == RHS(ins, 1)) {
6217                 mkconst(state, ins, 1);
6218         }
6219 }
6220
6221 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6222 {
6223         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6224                 ulong_t left, right;
6225                 left  = read_const(state, ins, &RHS(ins, 0));
6226                 right = read_const(state, ins, &RHS(ins, 1));
6227                 mkconst(state, ins, left >= right);
6228         }
6229         else if (is_zero(RHS(ins, 1))) {
6230                 mkconst(state, ins, 1);
6231         }
6232         else if (RHS(ins, 0) == RHS(ins, 1)) {
6233                 mkconst(state, ins, 1);
6234         }
6235 }
6236
6237 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6238 {
6239         if (is_const(RHS(ins, 0))) {
6240                 ulong_t left;
6241                 left = read_const(state, ins, &RHS(ins, 0));
6242                 mkconst(state, ins, left == 0);
6243         }
6244         /* Otherwise if I am the only user... */
6245         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6246                 int need_copy = 1;
6247                 /* Invert a boolean operation */
6248                 switch(RHS(ins, 0)->op) {
6249                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
6250                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
6251                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
6252                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
6253                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
6254                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
6255                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
6256                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
6257                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
6258                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
6259                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
6260                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
6261                 default:
6262                         need_copy = 0;
6263                         break;
6264                 }
6265                 if (need_copy) {
6266                         mkcopy(state, ins, RHS(ins, 0));
6267                 }
6268         }
6269 }
6270
6271 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6272 {
6273         if (is_const(RHS(ins, 0))) {
6274                 ulong_t left;
6275                 left = read_const(state, ins, &RHS(ins, 0));
6276                 mkconst(state, ins, left != 0);
6277         }
6278         else switch(RHS(ins, 0)->op) {
6279         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
6280         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
6281         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6282                 mkcopy(state, ins, RHS(ins, 0));
6283         }
6284
6285 }
6286
6287 static void simplify_copy(struct compile_state *state, struct triple *ins)
6288 {
6289         if (is_const(RHS(ins, 0))) {
6290                 switch(RHS(ins, 0)->op) {
6291                 case OP_INTCONST:
6292                 {
6293                         ulong_t left;
6294                         left = read_const(state, ins, &RHS(ins, 0));
6295                         mkconst(state, ins, left);
6296                         break;
6297                 }
6298                 case OP_ADDRCONST:
6299                 {
6300                         struct triple *sdecl;
6301                         ulong_t offset;
6302                         sdecl  = MISC(RHS(ins, 0), 0);
6303                         offset = RHS(ins, 0)->u.cval;
6304                         mkaddr_const(state, ins, sdecl, offset);
6305                         break;
6306                 }
6307                 default:
6308                         internal_error(state, ins, "uknown constant");
6309                         break;
6310                 }
6311         }
6312 }
6313
6314 static void simplify_branch(struct compile_state *state, struct triple *ins)
6315 {
6316         struct block *block;
6317         if (ins->op != OP_BRANCH) {
6318                 internal_error(state, ins, "not branch");
6319         }
6320         if (ins->use != 0) {
6321                 internal_error(state, ins, "branch use");
6322         }
6323 #warning "FIXME implement simplify branch."
6324         /* The challenge here with simplify branch is that I need to 
6325          * make modifications to the control flow graph as well
6326          * as to the branch instruction itself.
6327          */
6328         block = ins->u.block;
6329         
6330         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6331                 struct triple *targ;
6332                 ulong_t value;
6333                 value = read_const(state, ins, &RHS(ins, 0));
6334                 unuse_triple(RHS(ins, 0), ins);
6335                 targ = TARG(ins, 0);
6336                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6337                 if (value) {
6338                         unuse_triple(ins->next, ins);
6339                         TARG(ins, 0) = targ;
6340                 }
6341                 else {
6342                         unuse_triple(targ, ins);
6343                         TARG(ins, 0) = ins->next;
6344                 }
6345 #warning "FIXME handle the case of making a branch unconditional"
6346         }
6347         if (TARG(ins, 0) == ins->next) {
6348                 unuse_triple(ins->next, ins);
6349                 if (TRIPLE_RHS(ins->sizes)) {
6350                         unuse_triple(RHS(ins, 0), ins);
6351                         unuse_triple(ins->next, ins);
6352                 }
6353                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6354                 ins->op = OP_NOOP;
6355                 if (ins->use) {
6356                         internal_error(state, ins, "noop use != 0");
6357                 }
6358 #warning "FIXME handle the case of killing a branch"
6359         }
6360 }
6361
6362 static void simplify_phi(struct compile_state *state, struct triple *ins)
6363 {
6364         struct triple **expr;
6365         ulong_t value;
6366         expr = triple_rhs(state, ins, 0);
6367         if (!*expr || !is_const(*expr)) {
6368                 return;
6369         }
6370         value = read_const(state, ins, expr);
6371         for(;expr;expr = triple_rhs(state, ins, expr)) {
6372                 if (!*expr || !is_const(*expr)) {
6373                         return;
6374                 }
6375                 if (value != read_const(state, ins, expr)) {
6376                         return;
6377                 }
6378         }
6379         mkconst(state, ins, value);
6380 }
6381
6382
6383 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6384 {
6385         if (is_const(RHS(ins, 0))) {
6386                 ulong_t left;
6387                 left = read_const(state, ins, &RHS(ins, 0));
6388                 mkconst(state, ins, bsf(left));
6389         }
6390 }
6391
6392 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6393 {
6394         if (is_const(RHS(ins, 0))) {
6395                 ulong_t left;
6396                 left = read_const(state, ins, &RHS(ins, 0));
6397                 mkconst(state, ins, bsr(left));
6398         }
6399 }
6400
6401
6402 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6403 static const simplify_t table_simplify[] = {
6404 #if 0
6405 #define simplify_smul     simplify_noop
6406 #define simplify_umul     simplify_noop
6407 #define simplify_sdiv     simplify_noop
6408 #define simplify_udiv     simplify_noop
6409 #define simplify_smod     simplify_noop
6410 #define simplify_umod     simplify_noop
6411 #endif
6412 #if 0
6413 #define simplify_add      simplify_noop
6414 #define simplify_sub      simplify_noop
6415 #endif
6416 #if 0
6417 #define simplify_sl       simplify_noop
6418 #define simplify_usr      simplify_noop
6419 #define simplify_ssr      simplify_noop
6420 #endif
6421 #if 0
6422 #define simplify_and      simplify_noop
6423 #define simplify_xor      simplify_noop
6424 #define simplify_or       simplify_noop
6425 #endif
6426 #if 0
6427 #define simplify_pos      simplify_noop
6428 #define simplify_neg      simplify_noop
6429 #define simplify_invert   simplify_noop
6430 #endif
6431
6432 #if 0
6433 #define simplify_eq       simplify_noop
6434 #define simplify_noteq    simplify_noop
6435 #endif
6436 #if 0
6437 #define simplify_sless    simplify_noop
6438 #define simplify_uless    simplify_noop
6439 #define simplify_smore    simplify_noop
6440 #define simplify_umore    simplify_noop
6441 #endif
6442 #if 0
6443 #define simplify_slesseq  simplify_noop
6444 #define simplify_ulesseq  simplify_noop
6445 #define simplify_smoreeq  simplify_noop
6446 #define simplify_umoreeq  simplify_noop
6447 #endif
6448 #if 0
6449 #define simplify_lfalse   simplify_noop
6450 #endif
6451 #if 0
6452 #define simplify_ltrue    simplify_noop
6453 #endif
6454
6455 #if 0
6456 #define simplify_copy     simplify_noop
6457 #endif
6458
6459 #if 0
6460 #define simplify_branch   simplify_noop
6461 #endif
6462
6463 #if 0
6464 #define simplify_phi      simplify_noop
6465 #endif
6466
6467 #if 0
6468 #define simplify_bsf      simplify_noop
6469 #define simplify_bsr      simplify_noop
6470 #endif
6471
6472 [OP_SMUL       ] = simplify_smul,
6473 [OP_UMUL       ] = simplify_umul,
6474 [OP_SDIV       ] = simplify_sdiv,
6475 [OP_UDIV       ] = simplify_udiv,
6476 [OP_SMOD       ] = simplify_smod,
6477 [OP_UMOD       ] = simplify_umod,
6478 [OP_ADD        ] = simplify_add,
6479 [OP_SUB        ] = simplify_sub,
6480 [OP_SL         ] = simplify_sl,
6481 [OP_USR        ] = simplify_usr,
6482 [OP_SSR        ] = simplify_ssr,
6483 [OP_AND        ] = simplify_and,
6484 [OP_XOR        ] = simplify_xor,
6485 [OP_OR         ] = simplify_or,
6486 [OP_POS        ] = simplify_pos,
6487 [OP_NEG        ] = simplify_neg,
6488 [OP_INVERT     ] = simplify_invert,
6489
6490 [OP_EQ         ] = simplify_eq,
6491 [OP_NOTEQ      ] = simplify_noteq,
6492 [OP_SLESS      ] = simplify_sless,
6493 [OP_ULESS      ] = simplify_uless,
6494 [OP_SMORE      ] = simplify_smore,
6495 [OP_UMORE      ] = simplify_umore,
6496 [OP_SLESSEQ    ] = simplify_slesseq,
6497 [OP_ULESSEQ    ] = simplify_ulesseq,
6498 [OP_SMOREEQ    ] = simplify_smoreeq,
6499 [OP_UMOREEQ    ] = simplify_umoreeq,
6500 [OP_LFALSE     ] = simplify_lfalse,
6501 [OP_LTRUE      ] = simplify_ltrue,
6502
6503 [OP_LOAD       ] = simplify_noop,
6504 [OP_STORE      ] = simplify_noop,
6505
6506 [OP_NOOP       ] = simplify_noop,
6507
6508 [OP_INTCONST   ] = simplify_noop,
6509 [OP_BLOBCONST  ] = simplify_noop,
6510 [OP_ADDRCONST  ] = simplify_noop,
6511
6512 [OP_WRITE      ] = simplify_noop,
6513 [OP_READ       ] = simplify_noop,
6514 [OP_COPY       ] = simplify_copy,
6515 [OP_PIECE      ] = simplify_noop,
6516 [OP_ASM        ] = simplify_noop,
6517
6518 [OP_DOT        ] = simplify_noop,
6519 [OP_VAL_VEC    ] = simplify_noop,
6520
6521 [OP_LIST       ] = simplify_noop,
6522 [OP_BRANCH     ] = simplify_branch,
6523 [OP_LABEL      ] = simplify_noop,
6524 [OP_ADECL      ] = simplify_noop,
6525 [OP_SDECL      ] = simplify_noop,
6526 [OP_PHI        ] = simplify_phi,
6527
6528 [OP_INB        ] = simplify_noop,
6529 [OP_INW        ] = simplify_noop,
6530 [OP_INL        ] = simplify_noop,
6531 [OP_OUTB       ] = simplify_noop,
6532 [OP_OUTW       ] = simplify_noop,
6533 [OP_OUTL       ] = simplify_noop,
6534 [OP_BSF        ] = simplify_bsf,
6535 [OP_BSR        ] = simplify_bsr,
6536 [OP_RDMSR      ] = simplify_noop,
6537 [OP_WRMSR      ] = simplify_noop,                    
6538 [OP_HLT        ] = simplify_noop,
6539 };
6540
6541 static void simplify(struct compile_state *state, struct triple *ins)
6542 {
6543         int op;
6544         simplify_t do_simplify;
6545         do {
6546                 op = ins->op;
6547                 do_simplify = 0;
6548                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6549                         do_simplify = 0;
6550                 }
6551                 else {
6552                         do_simplify = table_simplify[op];
6553                 }
6554                 if (!do_simplify) {
6555                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6556                                 op, tops(op));
6557                         return;
6558                 }
6559                 do_simplify(state, ins);
6560         } while(ins->op != op);
6561 }
6562
6563 static void simplify_all(struct compile_state *state)
6564 {
6565         struct triple *ins, *first;
6566         first = RHS(state->main_function, 0);
6567         ins = first;
6568         do {
6569                 simplify(state, ins);
6570                 ins = ins->next;
6571         } while(ins != first);
6572 }
6573
6574 /*
6575  * Builtins....
6576  * ============================
6577  */
6578
6579 static void register_builtin_function(struct compile_state *state,
6580         const char *name, int op, struct type *rtype, ...)
6581 {
6582         struct type *ftype, *atype, *param, **next;
6583         struct triple *def, *arg, *result, *work, *last, *first;
6584         struct hash_entry *ident;
6585         struct file_state file;
6586         int parameters;
6587         int name_len;
6588         va_list args;
6589         int i;
6590
6591         /* Dummy file state to get debug handling right */
6592         memset(&file, 0, sizeof(file));
6593         file.basename = "<built-in>";
6594         file.line = 1;
6595         file.report_line = 1;
6596         file.report_name = file.basename;
6597         file.prev = state->file;
6598         state->file = &file;
6599         state->function = name;
6600
6601         /* Find the Parameter count */
6602         valid_op(state, op);
6603         parameters = table_ops[op].rhs;
6604         if (parameters < 0 ) {
6605                 internal_error(state, 0, "Invalid builtin parameter count");
6606         }
6607
6608         /* Find the function type */
6609         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6610         next = &ftype->right;
6611         va_start(args, rtype);
6612         for(i = 0; i < parameters; i++) {
6613                 atype = va_arg(args, struct type *);
6614                 if (!*next) {
6615                         *next = atype;
6616                 } else {
6617                         *next = new_type(TYPE_PRODUCT, *next, atype);
6618                         next = &((*next)->right);
6619                 }
6620         }
6621         if (!*next) {
6622                 *next = &void_type;
6623         }
6624         va_end(args);
6625
6626         /* Generate the needed triples */
6627         def = triple(state, OP_LIST, ftype, 0, 0);
6628         first = label(state);
6629         RHS(def, 0) = first;
6630
6631         /* Now string them together */
6632         param = ftype->right;
6633         for(i = 0; i < parameters; i++) {
6634                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6635                         atype = param->left;
6636                 } else {
6637                         atype = param;
6638                 }
6639                 arg = flatten(state, first, variable(state, atype));
6640                 param = param->right;
6641         }
6642         result = 0;
6643         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6644                 result = flatten(state, first, variable(state, rtype));
6645         }
6646         MISC(def, 0) = result;
6647         work = new_triple(state, op, rtype, -1, parameters);
6648         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6649                 RHS(work, i) = read_expr(state, arg);
6650         }
6651         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6652                 struct triple *val;
6653                 /* Populate the LHS with the target registers */
6654                 work = flatten(state, first, work);
6655                 work->type = &void_type;
6656                 param = rtype->left;
6657                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6658                         internal_error(state, 0, "Invalid result type");
6659                 }
6660                 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6661                 for(i = 0; i < rtype->elements; i++) {
6662                         struct triple *piece;
6663                         atype = param;
6664                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6665                                 atype = param->left;
6666                         }
6667                         if (!TYPE_ARITHMETIC(atype->type) &&
6668                                 !TYPE_PTR(atype->type)) {
6669                                 internal_error(state, 0, "Invalid lhs type");
6670                         }
6671                         piece = triple(state, OP_PIECE, atype, work, 0);
6672                         piece->u.cval = i;
6673                         LHS(work, i) = piece;
6674                         RHS(val, i) = piece;
6675                 }
6676                 work = val;
6677         }
6678         if (result) {
6679                 work = write_expr(state, result, work);
6680         }
6681         work = flatten(state, first, work);
6682         last = flatten(state, first, label(state));
6683         name_len = strlen(name);
6684         ident = lookup(state, name, name_len);
6685         symbol(state, ident, &ident->sym_ident, def, ftype);
6686         
6687         state->file = file.prev;
6688         state->function = 0;
6689 #if 0
6690         fprintf(stdout, "\n");
6691         loc(stdout, state, 0);
6692         fprintf(stdout, "\n__________ builtin_function _________\n");
6693         print_triple(state, def);
6694         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6695 #endif
6696 }
6697
6698 static struct type *partial_struct(struct compile_state *state,
6699         const char *field_name, struct type *type, struct type *rest)
6700 {
6701         struct hash_entry *field_ident;
6702         struct type *result;
6703         int field_name_len;
6704
6705         field_name_len = strlen(field_name);
6706         field_ident = lookup(state, field_name, field_name_len);
6707
6708         result = clone_type(0, type);
6709         result->field_ident = field_ident;
6710
6711         if (rest) {
6712                 result = new_type(TYPE_PRODUCT, result, rest);
6713         }
6714         return result;
6715 }
6716
6717 static struct type *register_builtin_type(struct compile_state *state,
6718         const char *name, struct type *type)
6719 {
6720         struct hash_entry *ident;
6721         int name_len;
6722
6723         name_len = strlen(name);
6724         ident = lookup(state, name, name_len);
6725         
6726         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6727                 ulong_t elements = 0;
6728                 struct type *field;
6729                 type = new_type(TYPE_STRUCT, type, 0);
6730                 field = type->left;
6731                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6732                         elements++;
6733                         field = field->right;
6734                 }
6735                 elements++;
6736                 symbol(state, ident, &ident->sym_struct, 0, type);
6737                 type->type_ident = ident;
6738                 type->elements = elements;
6739         }
6740         symbol(state, ident, &ident->sym_ident, 0, type);
6741         ident->tok = TOK_TYPE_NAME;
6742         return type;
6743 }
6744
6745
6746 static void register_builtins(struct compile_state *state)
6747 {
6748         struct type *msr_type;
6749
6750         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6751                 &ushort_type);
6752         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6753                 &ushort_type);
6754         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6755                 &ushort_type);
6756
6757         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6758                 &uchar_type, &ushort_type);
6759         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6760                 &ushort_type, &ushort_type);
6761         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6762                 &uint_type, &ushort_type);
6763         
6764         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6765                 &int_type);
6766         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6767                 &int_type);
6768
6769         msr_type = register_builtin_type(state, "__builtin_msr_t",
6770                 partial_struct(state, "lo", &ulong_type,
6771                 partial_struct(state, "hi", &ulong_type, 0)));
6772
6773         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6774                 &ulong_type);
6775         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6776                 &ulong_type, &ulong_type, &ulong_type);
6777         
6778         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6779                 &void_type);
6780 }
6781
6782 static struct type *declarator(
6783         struct compile_state *state, struct type *type, 
6784         struct hash_entry **ident, int need_ident);
6785 static void decl(struct compile_state *state, struct triple *first);
6786 static struct type *specifier_qualifier_list(struct compile_state *state);
6787 static int isdecl_specifier(int tok);
6788 static struct type *decl_specifiers(struct compile_state *state);
6789 static int istype(int tok);
6790 static struct triple *expr(struct compile_state *state);
6791 static struct triple *assignment_expr(struct compile_state *state);
6792 static struct type *type_name(struct compile_state *state);
6793 static void statement(struct compile_state *state, struct triple *fist);
6794
6795 static struct triple *call_expr(
6796         struct compile_state *state, struct triple *func)
6797 {
6798         struct triple *def;
6799         struct type *param, *type;
6800         ulong_t pvals, index;
6801
6802         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6803                 error(state, 0, "Called object is not a function");
6804         }
6805         if (func->op != OP_LIST) {
6806                 internal_error(state, 0, "improper function");
6807         }
6808         eat(state, TOK_LPAREN);
6809         /* Find the return type without any specifiers */
6810         type = clone_type(0, func->type->left);
6811         def = new_triple(state, OP_CALL, func->type, -1, -1);
6812         def->type = type;
6813
6814         pvals = TRIPLE_RHS(def->sizes);
6815         MISC(def, 0) = func;
6816
6817         param = func->type->right;
6818         for(index = 0; index < pvals; index++) {
6819                 struct triple *val;
6820                 struct type *arg_type;
6821                 val = read_expr(state, assignment_expr(state));
6822                 arg_type = param;
6823                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6824                         arg_type = param->left;
6825                 }
6826                 write_compatible(state, arg_type, val->type);
6827                 RHS(def, index) = val;
6828                 if (index != (pvals - 1)) {
6829                         eat(state, TOK_COMMA);
6830                         param = param->right;
6831                 }
6832         }
6833         eat(state, TOK_RPAREN);
6834         return def;
6835 }
6836
6837
6838 static struct triple *character_constant(struct compile_state *state)
6839 {
6840         struct triple *def;
6841         struct token *tk;
6842         const signed char *str, *end;
6843         int c;
6844         int str_len;
6845         eat(state, TOK_LIT_CHAR);
6846         tk = &state->token[0];
6847         str = tk->val.str + 1;
6848         str_len = tk->str_len - 2;
6849         if (str_len <= 0) {
6850                 error(state, 0, "empty character constant");
6851         }
6852         end = str + str_len;
6853         c = char_value(state, &str, end);
6854         if (str != end) {
6855                 error(state, 0, "multibyte character constant not supported");
6856         }
6857         def = int_const(state, &char_type, (ulong_t)((long_t)c));
6858         return def;
6859 }
6860
6861 static struct triple *string_constant(struct compile_state *state)
6862 {
6863         struct triple *def;
6864         struct token *tk;
6865         struct type *type;
6866         const signed char *str, *end;
6867         signed char *buf, *ptr;
6868         int str_len;
6869
6870         buf = 0;
6871         type = new_type(TYPE_ARRAY, &char_type, 0);
6872         type->elements = 0;
6873         /* The while loop handles string concatenation */
6874         do {
6875                 eat(state, TOK_LIT_STRING);
6876                 tk = &state->token[0];
6877                 str = tk->val.str + 1;
6878                 str_len = tk->str_len - 2;
6879                 if (str_len < 0) {
6880                         error(state, 0, "negative string constant length");
6881                 }
6882                 end = str + str_len;
6883                 ptr = buf;
6884                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6885                 memcpy(buf, ptr, type->elements);
6886                 ptr = buf + type->elements;
6887                 do {
6888                         *ptr++ = char_value(state, &str, end);
6889                 } while(str < end);
6890                 type->elements = ptr - buf;
6891         } while(peek(state) == TOK_LIT_STRING);
6892         *ptr = '\0';
6893         type->elements += 1;
6894         def = triple(state, OP_BLOBCONST, type, 0, 0);
6895         def->u.blob = buf;
6896         return def;
6897 }
6898
6899
6900 static struct triple *integer_constant(struct compile_state *state)
6901 {
6902         struct triple *def;
6903         unsigned long val;
6904         struct token *tk;
6905         char *end;
6906         int u, l, decimal;
6907         struct type *type;
6908
6909         eat(state, TOK_LIT_INT);
6910         tk = &state->token[0];
6911         errno = 0;
6912         decimal = (tk->val.str[0] != '0');
6913         val = strtoul(tk->val.str, &end, 0);
6914         if ((val == ULONG_MAX) && (errno == ERANGE)) {
6915                 error(state, 0, "Integer constant to large");
6916         }
6917         u = l = 0;
6918         if ((*end == 'u') || (*end == 'U')) {
6919                 u = 1;
6920                         end++;
6921         }
6922         if ((*end == 'l') || (*end == 'L')) {
6923                 l = 1;
6924                 end++;
6925         }
6926         if ((*end == 'u') || (*end == 'U')) {
6927                 u = 1;
6928                 end++;
6929         }
6930         if (*end) {
6931                 error(state, 0, "Junk at end of integer constant");
6932         }
6933         if (u && l)  {
6934                 type = &ulong_type;
6935         }
6936         else if (l) {
6937                 type = &long_type;
6938                 if (!decimal && (val > LONG_MAX)) {
6939                         type = &ulong_type;
6940                 }
6941         }
6942         else if (u) {
6943                 type = &uint_type;
6944                 if (val > UINT_MAX) {
6945                         type = &ulong_type;
6946                 }
6947         }
6948         else {
6949                 type = &int_type;
6950                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6951                         type = &uint_type;
6952                 }
6953                 else if (!decimal && (val > LONG_MAX)) {
6954                         type = &ulong_type;
6955                 }
6956                 else if (val > INT_MAX) {
6957                         type = &long_type;
6958                 }
6959         }
6960         def = int_const(state, type, val);
6961         return def;
6962 }
6963
6964 static struct triple *primary_expr(struct compile_state *state)
6965 {
6966         struct triple *def;
6967         int tok;
6968         tok = peek(state);
6969         switch(tok) {
6970         case TOK_IDENT:
6971         {
6972                 struct hash_entry *ident;
6973                 /* Here ident is either:
6974                  * a varable name
6975                  * a function name
6976                  * an enumeration constant.
6977                  */
6978                 eat(state, TOK_IDENT);
6979                 ident = state->token[0].ident;
6980                 if (!ident->sym_ident) {
6981                         error(state, 0, "%s undeclared", ident->name);
6982                 }
6983                 def = ident->sym_ident->def;
6984                 break;
6985         }
6986         case TOK_ENUM_CONST:
6987                 /* Here ident is an enumeration constant */
6988                 eat(state, TOK_ENUM_CONST);
6989                 def = 0;
6990                 FINISHME();
6991                 break;
6992         case TOK_LPAREN:
6993                 eat(state, TOK_LPAREN);
6994                 def = expr(state);
6995                 eat(state, TOK_RPAREN);
6996                 break;
6997         case TOK_LIT_INT:
6998                 def = integer_constant(state);
6999                 break;
7000         case TOK_LIT_FLOAT:
7001                 eat(state, TOK_LIT_FLOAT);
7002                 error(state, 0, "Floating point constants not supported");
7003                 def = 0;
7004                 FINISHME();
7005                 break;
7006         case TOK_LIT_CHAR:
7007                 def = character_constant(state);
7008                 break;
7009         case TOK_LIT_STRING:
7010                 def = string_constant(state);
7011                 break;
7012         default:
7013                 def = 0;
7014                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7015         }
7016         return def;
7017 }
7018
7019 static struct triple *postfix_expr(struct compile_state *state)
7020 {
7021         struct triple *def;
7022         int postfix;
7023         def = primary_expr(state);
7024         do {
7025                 struct triple *left;
7026                 int tok;
7027                 postfix = 1;
7028                 left = def;
7029                 switch((tok = peek(state))) {
7030                 case TOK_LBRACKET:
7031                         eat(state, TOK_LBRACKET);
7032                         def = mk_subscript_expr(state, left, expr(state));
7033                         eat(state, TOK_RBRACKET);
7034                         break;
7035                 case TOK_LPAREN:
7036                         def = call_expr(state, def);
7037                         break;
7038                 case TOK_DOT:
7039                 {
7040                         struct hash_entry *field;
7041                         eat(state, TOK_DOT);
7042                         eat(state, TOK_IDENT);
7043                         field = state->token[0].ident;
7044                         def = deref_field(state, def, field);
7045                         break;
7046                 }
7047                 case TOK_ARROW:
7048                 {
7049                         struct hash_entry *field;
7050                         eat(state, TOK_ARROW);
7051                         eat(state, TOK_IDENT);
7052                         field = state->token[0].ident;
7053                         def = mk_deref_expr(state, read_expr(state, def));
7054                         def = deref_field(state, def, field);
7055                         break;
7056                 }
7057                 case TOK_PLUSPLUS:
7058                         eat(state, TOK_PLUSPLUS);
7059                         def = mk_post_inc_expr(state, left);
7060                         break;
7061                 case TOK_MINUSMINUS:
7062                         eat(state, TOK_MINUSMINUS);
7063                         def = mk_post_dec_expr(state, left);
7064                         break;
7065                 default:
7066                         postfix = 0;
7067                         break;
7068                 }
7069         } while(postfix);
7070         return def;
7071 }
7072
7073 static struct triple *cast_expr(struct compile_state *state);
7074
7075 static struct triple *unary_expr(struct compile_state *state)
7076 {
7077         struct triple *def, *right;
7078         int tok;
7079         switch((tok = peek(state))) {
7080         case TOK_PLUSPLUS:
7081                 eat(state, TOK_PLUSPLUS);
7082                 def = mk_pre_inc_expr(state, unary_expr(state));
7083                 break;
7084         case TOK_MINUSMINUS:
7085                 eat(state, TOK_MINUSMINUS);
7086                 def = mk_pre_dec_expr(state, unary_expr(state));
7087                 break;
7088         case TOK_AND:
7089                 eat(state, TOK_AND);
7090                 def = mk_addr_expr(state, cast_expr(state), 0);
7091                 break;
7092         case TOK_STAR:
7093                 eat(state, TOK_STAR);
7094                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7095                 break;
7096         case TOK_PLUS:
7097                 eat(state, TOK_PLUS);
7098                 right = read_expr(state, cast_expr(state));
7099                 arithmetic(state, right);
7100                 def = integral_promotion(state, right);
7101                 break;
7102         case TOK_MINUS:
7103                 eat(state, TOK_MINUS);
7104                 right = read_expr(state, cast_expr(state));
7105                 arithmetic(state, right);
7106                 def = integral_promotion(state, right);
7107                 def = triple(state, OP_NEG, def->type, def, 0);
7108                 break;
7109         case TOK_TILDE:
7110                 eat(state, TOK_TILDE);
7111                 right = read_expr(state, cast_expr(state));
7112                 integral(state, right);
7113                 def = integral_promotion(state, right);
7114                 def = triple(state, OP_INVERT, def->type, def, 0);
7115                 break;
7116         case TOK_BANG:
7117                 eat(state, TOK_BANG);
7118                 right = read_expr(state, cast_expr(state));
7119                 bool(state, right);
7120                 def = lfalse_expr(state, right);
7121                 break;
7122         case TOK_SIZEOF:
7123         {
7124                 struct type *type;
7125                 int tok1, tok2;
7126                 eat(state, TOK_SIZEOF);
7127                 tok1 = peek(state);
7128                 tok2 = peek2(state);
7129                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7130                         eat(state, TOK_LPAREN);
7131                         type = type_name(state);
7132                         eat(state, TOK_RPAREN);
7133                 }
7134                 else {
7135                         struct triple *expr;
7136                         expr = unary_expr(state);
7137                         type = expr->type;
7138                         release_expr(state, expr);
7139                 }
7140                 def = int_const(state, &ulong_type, size_of(state, type));
7141                 break;
7142         }
7143         case TOK_ALIGNOF:
7144         {
7145                 struct type *type;
7146                 int tok1, tok2;
7147                 eat(state, TOK_ALIGNOF);
7148                 tok1 = peek(state);
7149                 tok2 = peek2(state);
7150                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7151                         eat(state, TOK_LPAREN);
7152                         type = type_name(state);
7153                         eat(state, TOK_RPAREN);
7154                 }
7155                 else {
7156                         struct triple *expr;
7157                         expr = unary_expr(state);
7158                         type = expr->type;
7159                         release_expr(state, expr);
7160                 }
7161                 def = int_const(state, &ulong_type, align_of(state, type));
7162                 break;
7163         }
7164         default:
7165                 def = postfix_expr(state);
7166                 break;
7167         }
7168         return def;
7169 }
7170
7171 static struct triple *cast_expr(struct compile_state *state)
7172 {
7173         struct triple *def;
7174         int tok1, tok2;
7175         tok1 = peek(state);
7176         tok2 = peek2(state);
7177         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7178                 struct type *type;
7179                 eat(state, TOK_LPAREN);
7180                 type = type_name(state);
7181                 eat(state, TOK_RPAREN);
7182                 def = read_expr(state, cast_expr(state));
7183                 def = triple(state, OP_COPY, type, def, 0);
7184         }
7185         else {
7186                 def = unary_expr(state);
7187         }
7188         return def;
7189 }
7190
7191 static struct triple *mult_expr(struct compile_state *state)
7192 {
7193         struct triple *def;
7194         int done;
7195         def = cast_expr(state);
7196         do {
7197                 struct triple *left, *right;
7198                 struct type *result_type;
7199                 int tok, op, sign;
7200                 done = 0;
7201                 switch(tok = (peek(state))) {
7202                 case TOK_STAR:
7203                 case TOK_DIV:
7204                 case TOK_MOD:
7205                         left = read_expr(state, def);
7206                         arithmetic(state, left);
7207
7208                         eat(state, tok);
7209
7210                         right = read_expr(state, cast_expr(state));
7211                         arithmetic(state, right);
7212
7213                         result_type = arithmetic_result(state, left, right);
7214                         sign = is_signed(result_type);
7215                         op = -1;
7216                         switch(tok) {
7217                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7218                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
7219                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
7220                         }
7221                         def = triple(state, op, result_type, left, right);
7222                         break;
7223                 default:
7224                         done = 1;
7225                         break;
7226                 }
7227         } while(!done);
7228         return def;
7229 }
7230
7231 static struct triple *add_expr(struct compile_state *state)
7232 {
7233         struct triple *def;
7234         int done;
7235         def = mult_expr(state);
7236         do {
7237                 done = 0;
7238                 switch( peek(state)) {
7239                 case TOK_PLUS:
7240                         eat(state, TOK_PLUS);
7241                         def = mk_add_expr(state, def, mult_expr(state));
7242                         break;
7243                 case TOK_MINUS:
7244                         eat(state, TOK_MINUS);
7245                         def = mk_sub_expr(state, def, mult_expr(state));
7246                         break;
7247                 default:
7248                         done = 1;
7249                         break;
7250                 }
7251         } while(!done);
7252         return def;
7253 }
7254
7255 static struct triple *shift_expr(struct compile_state *state)
7256 {
7257         struct triple *def;
7258         int done;
7259         def = add_expr(state);
7260         do {
7261                 struct triple *left, *right;
7262                 int tok, op;
7263                 done = 0;
7264                 switch((tok = peek(state))) {
7265                 case TOK_SL:
7266                 case TOK_SR:
7267                         left = read_expr(state, def);
7268                         integral(state, left);
7269                         left = integral_promotion(state, left);
7270
7271                         eat(state, tok);
7272
7273                         right = read_expr(state, add_expr(state));
7274                         integral(state, right);
7275                         right = integral_promotion(state, right);
7276                         
7277                         op = (tok == TOK_SL)? OP_SL : 
7278                                 is_signed(left->type)? OP_SSR: OP_USR;
7279
7280                         def = triple(state, op, left->type, left, right);
7281                         break;
7282                 default:
7283                         done = 1;
7284                         break;
7285                 }
7286         } while(!done);
7287         return def;
7288 }
7289
7290 static struct triple *relational_expr(struct compile_state *state)
7291 {
7292 #warning "Extend relational exprs to work on more than arithmetic types"
7293         struct triple *def;
7294         int done;
7295         def = shift_expr(state);
7296         do {
7297                 struct triple *left, *right;
7298                 struct type *arg_type;
7299                 int tok, op, sign;
7300                 done = 0;
7301                 switch((tok = peek(state))) {
7302                 case TOK_LESS:
7303                 case TOK_MORE:
7304                 case TOK_LESSEQ:
7305                 case TOK_MOREEQ:
7306                         left = read_expr(state, def);
7307                         arithmetic(state, left);
7308
7309                         eat(state, tok);
7310
7311                         right = read_expr(state, shift_expr(state));
7312                         arithmetic(state, right);
7313
7314                         arg_type = arithmetic_result(state, left, right);
7315                         sign = is_signed(arg_type);
7316                         op = -1;
7317                         switch(tok) {
7318                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
7319                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
7320                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7321                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7322                         }
7323                         def = triple(state, op, &int_type, left, right);
7324                         break;
7325                 default:
7326                         done = 1;
7327                         break;
7328                 }
7329         } while(!done);
7330         return def;
7331 }
7332
7333 static struct triple *equality_expr(struct compile_state *state)
7334 {
7335 #warning "Extend equality exprs to work on more than arithmetic types"
7336         struct triple *def;
7337         int done;
7338         def = relational_expr(state);
7339         do {
7340                 struct triple *left, *right;
7341                 int tok, op;
7342                 done = 0;
7343                 switch((tok = peek(state))) {
7344                 case TOK_EQEQ:
7345                 case TOK_NOTEQ:
7346                         left = read_expr(state, def);
7347                         arithmetic(state, left);
7348                         eat(state, tok);
7349                         right = read_expr(state, relational_expr(state));
7350                         arithmetic(state, right);
7351                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7352                         def = triple(state, op, &int_type, left, right);
7353                         break;
7354                 default:
7355                         done = 1;
7356                         break;
7357                 }
7358         } while(!done);
7359         return def;
7360 }
7361
7362 static struct triple *and_expr(struct compile_state *state)
7363 {
7364         struct triple *def;
7365         def = equality_expr(state);
7366         while(peek(state) == TOK_AND) {
7367                 struct triple *left, *right;
7368                 struct type *result_type;
7369                 left = read_expr(state, def);
7370                 integral(state, left);
7371                 eat(state, TOK_AND);
7372                 right = read_expr(state, equality_expr(state));
7373                 integral(state, right);
7374                 result_type = arithmetic_result(state, left, right);
7375                 def = triple(state, OP_AND, result_type, left, right);
7376         }
7377         return def;
7378 }
7379
7380 static struct triple *xor_expr(struct compile_state *state)
7381 {
7382         struct triple *def;
7383         def = and_expr(state);
7384         while(peek(state) == TOK_XOR) {
7385                 struct triple *left, *right;
7386                 struct type *result_type;
7387                 left = read_expr(state, def);
7388                 integral(state, left);
7389                 eat(state, TOK_XOR);
7390                 right = read_expr(state, and_expr(state));
7391                 integral(state, right);
7392                 result_type = arithmetic_result(state, left, right);
7393                 def = triple(state, OP_XOR, result_type, left, right);
7394         }
7395         return def;
7396 }
7397
7398 static struct triple *or_expr(struct compile_state *state)
7399 {
7400         struct triple *def;
7401         def = xor_expr(state);
7402         while(peek(state) == TOK_OR) {
7403                 struct triple *left, *right;
7404                 struct type *result_type;
7405                 left = read_expr(state, def);
7406                 integral(state, left);
7407                 eat(state, TOK_OR);
7408                 right = read_expr(state, xor_expr(state));
7409                 integral(state, right);
7410                 result_type = arithmetic_result(state, left, right);
7411                 def = triple(state, OP_OR, result_type, left, right);
7412         }
7413         return def;
7414 }
7415
7416 static struct triple *land_expr(struct compile_state *state)
7417 {
7418         struct triple *def;
7419         def = or_expr(state);
7420         while(peek(state) == TOK_LOGAND) {
7421                 struct triple *left, *right;
7422                 left = read_expr(state, def);
7423                 bool(state, left);
7424                 eat(state, TOK_LOGAND);
7425                 right = read_expr(state, or_expr(state));
7426                 bool(state, right);
7427
7428                 def = triple(state, OP_LAND, &int_type,
7429                         ltrue_expr(state, left),
7430                         ltrue_expr(state, right));
7431         }
7432         return def;
7433 }
7434
7435 static struct triple *lor_expr(struct compile_state *state)
7436 {
7437         struct triple *def;
7438         def = land_expr(state);
7439         while(peek(state) == TOK_LOGOR) {
7440                 struct triple *left, *right;
7441                 left = read_expr(state, def);
7442                 bool(state, left);
7443                 eat(state, TOK_LOGOR);
7444                 right = read_expr(state, land_expr(state));
7445                 bool(state, right);
7446                 
7447                 def = triple(state, OP_LOR, &int_type,
7448                         ltrue_expr(state, left),
7449                         ltrue_expr(state, right));
7450         }
7451         return def;
7452 }
7453
7454 static struct triple *conditional_expr(struct compile_state *state)
7455 {
7456         struct triple *def;
7457         def = lor_expr(state);
7458         if (peek(state) == TOK_QUEST) {
7459                 struct triple *test, *left, *right;
7460                 bool(state, def);
7461                 test = ltrue_expr(state, read_expr(state, def));
7462                 eat(state, TOK_QUEST);
7463                 left = read_expr(state, expr(state));
7464                 eat(state, TOK_COLON);
7465                 right = read_expr(state, conditional_expr(state));
7466
7467                 def = cond_expr(state, test, left, right);
7468         }
7469         return def;
7470 }
7471
7472 static struct triple *eval_const_expr(
7473         struct compile_state *state, struct triple *expr)
7474 {
7475         struct triple *def;
7476         if (is_const(expr)) {
7477                 def = expr;
7478         } 
7479         else {
7480                 /* If we don't start out as a constant simplify into one */
7481                 struct triple *head, *ptr;
7482                 head = label(state); /* dummy initial triple */
7483                 flatten(state, head, expr);
7484                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7485                         simplify(state, ptr);
7486                 }
7487                 /* Remove the constant value the tail of the list */
7488                 def = head->prev;
7489                 def->prev->next = def->next;
7490                 def->next->prev = def->prev;
7491                 def->next = def->prev = def;
7492                 if (!is_const(def)) {
7493                         error(state, 0, "Not a constant expression");
7494                 }
7495                 /* Free the intermediate expressions */
7496                 while(head->next != head) {
7497                         release_triple(state, head->next);
7498                 }
7499                 free_triple(state, head);
7500         }
7501         return def;
7502 }
7503
7504 static struct triple *constant_expr(struct compile_state *state)
7505 {
7506         return eval_const_expr(state, conditional_expr(state));
7507 }
7508
7509 static struct triple *assignment_expr(struct compile_state *state)
7510 {
7511         struct triple *def, *left, *right;
7512         int tok, op, sign;
7513         /* The C grammer in K&R shows assignment expressions
7514          * only taking unary expressions as input on their
7515          * left hand side.  But specifies the precedence of
7516          * assignemnt as the lowest operator except for comma.
7517          *
7518          * Allowing conditional expressions on the left hand side
7519          * of an assignement results in a grammar that accepts
7520          * a larger set of statements than standard C.   As long
7521          * as the subset of the grammar that is standard C behaves
7522          * correctly this should cause no problems.
7523          * 
7524          * For the extra token strings accepted by the grammar
7525          * none of them should produce a valid lvalue, so they
7526          * should not produce functioning programs.
7527          *
7528          * GCC has this bug as well, so surprises should be minimal.
7529          */
7530         def = conditional_expr(state);
7531         left = def;
7532         switch((tok = peek(state))) {
7533         case TOK_EQ:
7534                 lvalue(state, left);
7535                 eat(state, TOK_EQ);
7536                 def = write_expr(state, left, 
7537                         read_expr(state, assignment_expr(state)));
7538                 break;
7539         case TOK_TIMESEQ:
7540         case TOK_DIVEQ:
7541         case TOK_MODEQ:
7542                 lvalue(state, left);
7543                 arithmetic(state, left);
7544                 eat(state, tok);
7545                 right = read_expr(state, assignment_expr(state));
7546                 arithmetic(state, right);
7547
7548                 sign = is_signed(left->type);
7549                 op = -1;
7550                 switch(tok) {
7551                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7552                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7553                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7554                 }
7555                 def = write_expr(state, left,
7556                         triple(state, op, left->type, 
7557                                 read_expr(state, left), right));
7558                 break;
7559         case TOK_PLUSEQ:
7560                 lvalue(state, left);
7561                 eat(state, TOK_PLUSEQ);
7562                 def = write_expr(state, left,
7563                         mk_add_expr(state, left, assignment_expr(state)));
7564                 break;
7565         case TOK_MINUSEQ:
7566                 lvalue(state, left);
7567                 eat(state, TOK_MINUSEQ);
7568                 def = write_expr(state, left,
7569                         mk_sub_expr(state, left, assignment_expr(state)));
7570                 break;
7571         case TOK_SLEQ:
7572         case TOK_SREQ:
7573         case TOK_ANDEQ:
7574         case TOK_XOREQ:
7575         case TOK_OREQ:
7576                 lvalue(state, left);
7577                 integral(state, left);
7578                 eat(state, tok);
7579                 right = read_expr(state, assignment_expr(state));
7580                 integral(state, right);
7581                 right = integral_promotion(state, right);
7582                 sign = is_signed(left->type);
7583                 op = -1;
7584                 switch(tok) {
7585                 case TOK_SLEQ:  op = OP_SL; break;
7586                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7587                 case TOK_ANDEQ: op = OP_AND; break;
7588                 case TOK_XOREQ: op = OP_XOR; break;
7589                 case TOK_OREQ:  op = OP_OR; break;
7590                 }
7591                 def = write_expr(state, left,
7592                         triple(state, op, left->type, 
7593                                 read_expr(state, left), right));
7594                 break;
7595         }
7596         return def;
7597 }
7598
7599 static struct triple *expr(struct compile_state *state)
7600 {
7601         struct triple *def;
7602         def = assignment_expr(state);
7603         while(peek(state) == TOK_COMMA) {
7604                 struct triple *left, *right;
7605                 left = def;
7606                 eat(state, TOK_COMMA);
7607                 right = assignment_expr(state);
7608                 def = triple(state, OP_COMMA, right->type, left, right);
7609         }
7610         return def;
7611 }
7612
7613 static void expr_statement(struct compile_state *state, struct triple *first)
7614 {
7615         if (peek(state) != TOK_SEMI) {
7616                 flatten(state, first, expr(state));
7617         }
7618         eat(state, TOK_SEMI);
7619 }
7620
7621 static void if_statement(struct compile_state *state, struct triple *first)
7622 {
7623         struct triple *test, *jmp1, *jmp2, *middle, *end;
7624
7625         jmp1 = jmp2 = middle = 0;
7626         eat(state, TOK_IF);
7627         eat(state, TOK_LPAREN);
7628         test = expr(state);
7629         bool(state, test);
7630         /* Cleanup and invert the test */
7631         test = lfalse_expr(state, read_expr(state, test));
7632         eat(state, TOK_RPAREN);
7633         /* Generate the needed pieces */
7634         middle = label(state);
7635         jmp1 = branch(state, middle, test);
7636         /* Thread the pieces together */
7637         flatten(state, first, test);
7638         flatten(state, first, jmp1);
7639         flatten(state, first, label(state));
7640         statement(state, first);
7641         if (peek(state) == TOK_ELSE) {
7642                 eat(state, TOK_ELSE);
7643                 /* Generate the rest of the pieces */
7644                 end = label(state);
7645                 jmp2 = branch(state, end, 0);
7646                 /* Thread them together */
7647                 flatten(state, first, jmp2);
7648                 flatten(state, first, middle);
7649                 statement(state, first);
7650                 flatten(state, first, end);
7651         }
7652         else {
7653                 flatten(state, first, middle);
7654         }
7655 }
7656
7657 static void for_statement(struct compile_state *state, struct triple *first)
7658 {
7659         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7660         struct triple *label1, *label2, *label3;
7661         struct hash_entry *ident;
7662
7663         eat(state, TOK_FOR);
7664         eat(state, TOK_LPAREN);
7665         head = test = tail = jmp1 = jmp2 = 0;
7666         if (peek(state) != TOK_SEMI) {
7667                 head = expr(state);
7668         } 
7669         eat(state, TOK_SEMI);
7670         if (peek(state) != TOK_SEMI) {
7671                 test = expr(state);
7672                 bool(state, test);
7673                 test = ltrue_expr(state, read_expr(state, test));
7674         }
7675         eat(state, TOK_SEMI);
7676         if (peek(state) != TOK_RPAREN) {
7677                 tail = expr(state);
7678         }
7679         eat(state, TOK_RPAREN);
7680         /* Generate the needed pieces */
7681         label1 = label(state);
7682         label2 = label(state);
7683         label3 = label(state);
7684         if (test) {
7685                 jmp1 = branch(state, label3, 0);
7686                 jmp2 = branch(state, label1, test);
7687         }
7688         else {
7689                 jmp2 = branch(state, label1, 0);
7690         }
7691         end = label(state);
7692         /* Remember where break and continue go */
7693         start_scope(state);
7694         ident = state->i_break;
7695         symbol(state, ident, &ident->sym_ident, end, end->type);
7696         ident = state->i_continue;
7697         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7698         /* Now include the body */
7699         flatten(state, first, head);
7700         flatten(state, first, jmp1);
7701         flatten(state, first, label1);
7702         statement(state, first);
7703         flatten(state, first, label2);
7704         flatten(state, first, tail);
7705         flatten(state, first, label3);
7706         flatten(state, first, test);
7707         flatten(state, first, jmp2);
7708         flatten(state, first, end);
7709         /* Cleanup the break/continue scope */
7710         end_scope(state);
7711 }
7712
7713 static void while_statement(struct compile_state *state, struct triple *first)
7714 {
7715         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7716         struct hash_entry *ident;
7717         eat(state, TOK_WHILE);
7718         eat(state, TOK_LPAREN);
7719         test = expr(state);
7720         bool(state, test);
7721         test = ltrue_expr(state, read_expr(state, test));
7722         eat(state, TOK_RPAREN);
7723         /* Generate the needed pieces */
7724         label1 = label(state);
7725         label2 = label(state);
7726         jmp1 = branch(state, label2, 0);
7727         jmp2 = branch(state, label1, test);
7728         end = label(state);
7729         /* Remember where break and continue go */
7730         start_scope(state);
7731         ident = state->i_break;
7732         symbol(state, ident, &ident->sym_ident, end, end->type);
7733         ident = state->i_continue;
7734         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7735         /* Thread them together */
7736         flatten(state, first, jmp1);
7737         flatten(state, first, label1);
7738         statement(state, first);
7739         flatten(state, first, label2);
7740         flatten(state, first, test);
7741         flatten(state, first, jmp2);
7742         flatten(state, first, end);
7743         /* Cleanup the break/continue scope */
7744         end_scope(state);
7745 }
7746
7747 static void do_statement(struct compile_state *state, struct triple *first)
7748 {
7749         struct triple *label1, *label2, *test, *end;
7750         struct hash_entry *ident;
7751         eat(state, TOK_DO);
7752         /* Generate the needed pieces */
7753         label1 = label(state);
7754         label2 = label(state);
7755         end = label(state);
7756         /* Remember where break and continue go */
7757         start_scope(state);
7758         ident = state->i_break;
7759         symbol(state, ident, &ident->sym_ident, end, end->type);
7760         ident = state->i_continue;
7761         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7762         /* Now include the body */
7763         flatten(state, first, label1);
7764         statement(state, first);
7765         /* Cleanup the break/continue scope */
7766         end_scope(state);
7767         /* Eat the rest of the loop */
7768         eat(state, TOK_WHILE);
7769         eat(state, TOK_LPAREN);
7770         test = read_expr(state, expr(state));
7771         bool(state, test);
7772         eat(state, TOK_RPAREN);
7773         eat(state, TOK_SEMI);
7774         /* Thread the pieces together */
7775         test = ltrue_expr(state, test);
7776         flatten(state, first, label2);
7777         flatten(state, first, test);
7778         flatten(state, first, branch(state, label1, test));
7779         flatten(state, first, end);
7780 }
7781
7782
7783 static void return_statement(struct compile_state *state, struct triple *first)
7784 {
7785         struct triple *jmp, *mv, *dest, *var, *val;
7786         int last;
7787         eat(state, TOK_RETURN);
7788
7789 #warning "FIXME implement a more general excess branch elimination"
7790         val = 0;
7791         /* If we have a return value do some more work */
7792         if (peek(state) != TOK_SEMI) {
7793                 val = read_expr(state, expr(state));
7794         }
7795         eat(state, TOK_SEMI);
7796
7797         /* See if this last statement in a function */
7798         last = ((peek(state) == TOK_RBRACE) && 
7799                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7800
7801         /* Find the return variable */
7802         var = MISC(state->main_function, 0);
7803         /* Find the return destination */
7804         dest = RHS(state->main_function, 0)->prev;
7805         mv = jmp = 0;
7806         /* If needed generate a jump instruction */
7807         if (!last) {
7808                 jmp = branch(state, dest, 0);
7809         }
7810         /* If needed generate an assignment instruction */
7811         if (val) {
7812                 mv = write_expr(state, var, val);
7813         }
7814         /* Now put the code together */
7815         if (mv) {
7816                 flatten(state, first, mv);
7817                 flatten(state, first, jmp);
7818         }
7819         else if (jmp) {
7820                 flatten(state, first, jmp);
7821         }
7822 }
7823
7824 static void break_statement(struct compile_state *state, struct triple *first)
7825 {
7826         struct triple *dest;
7827         eat(state, TOK_BREAK);
7828         eat(state, TOK_SEMI);
7829         if (!state->i_break->sym_ident) {
7830                 error(state, 0, "break statement not within loop or switch");
7831         }
7832         dest = state->i_break->sym_ident->def;
7833         flatten(state, first, branch(state, dest, 0));
7834 }
7835
7836 static void continue_statement(struct compile_state *state, struct triple *first)
7837 {
7838         struct triple *dest;
7839         eat(state, TOK_CONTINUE);
7840         eat(state, TOK_SEMI);
7841         if (!state->i_continue->sym_ident) {
7842                 error(state, 0, "continue statement outside of a loop");
7843         }
7844         dest = state->i_continue->sym_ident->def;
7845         flatten(state, first, branch(state, dest, 0));
7846 }
7847
7848 static void goto_statement(struct compile_state *state, struct triple *first)
7849 {
7850         struct hash_entry *ident;
7851         eat(state, TOK_GOTO);
7852         eat(state, TOK_IDENT);
7853         ident = state->token[0].ident;
7854         if (!ident->sym_label) {
7855                 /* If this is a forward branch allocate the label now,
7856                  * it will be flattend in the appropriate location later.
7857                  */
7858                 struct triple *ins;
7859                 ins = label(state);
7860                 label_symbol(state, ident, ins);
7861         }
7862         eat(state, TOK_SEMI);
7863
7864         flatten(state, first, branch(state, ident->sym_label->def, 0));
7865 }
7866
7867 static void labeled_statement(struct compile_state *state, struct triple *first)
7868 {
7869         struct triple *ins;
7870         struct hash_entry *ident;
7871         eat(state, TOK_IDENT);
7872
7873         ident = state->token[0].ident;
7874         if (ident->sym_label && ident->sym_label->def) {
7875                 ins = ident->sym_label->def;
7876                 put_occurance(ins->occurance);
7877                 ins->occurance = new_occurance(state);
7878         }
7879         else {
7880                 ins = label(state);
7881                 label_symbol(state, ident, ins);
7882         }
7883         if (ins->id & TRIPLE_FLAG_FLATTENED) {
7884                 error(state, 0, "label %s already defined", ident->name);
7885         }
7886         flatten(state, first, ins);
7887
7888         eat(state, TOK_COLON);
7889         statement(state, first);
7890 }
7891
7892 static void switch_statement(struct compile_state *state, struct triple *first)
7893 {
7894         FINISHME();
7895         eat(state, TOK_SWITCH);
7896         eat(state, TOK_LPAREN);
7897         expr(state);
7898         eat(state, TOK_RPAREN);
7899         statement(state, first);
7900         error(state, 0, "switch statements are not implemented");
7901         FINISHME();
7902 }
7903
7904 static void case_statement(struct compile_state *state, struct triple *first)
7905 {
7906         FINISHME();
7907         eat(state, TOK_CASE);
7908         constant_expr(state);
7909         eat(state, TOK_COLON);
7910         statement(state, first);
7911         error(state, 0, "case statements are not implemented");
7912         FINISHME();
7913 }
7914
7915 static void default_statement(struct compile_state *state, struct triple *first)
7916 {
7917         FINISHME();
7918         eat(state, TOK_DEFAULT);
7919         eat(state, TOK_COLON);
7920         statement(state, first);
7921         error(state, 0, "default statements are not implemented");
7922         FINISHME();
7923 }
7924
7925 static void asm_statement(struct compile_state *state, struct triple *first)
7926 {
7927         struct asm_info *info;
7928         struct {
7929                 struct triple *constraint;
7930                 struct triple *expr;
7931         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7932         struct triple *def, *asm_str;
7933         int out, in, clobbers, more, colons, i;
7934
7935         eat(state, TOK_ASM);
7936         /* For now ignore the qualifiers */
7937         switch(peek(state)) {
7938         case TOK_CONST:
7939                 eat(state, TOK_CONST);
7940                 break;
7941         case TOK_VOLATILE:
7942                 eat(state, TOK_VOLATILE);
7943                 break;
7944         }
7945         eat(state, TOK_LPAREN);
7946         asm_str = string_constant(state);
7947
7948         colons = 0;
7949         out = in = clobbers = 0;
7950         /* Outputs */
7951         if ((colons == 0) && (peek(state) == TOK_COLON)) {
7952                 eat(state, TOK_COLON);
7953                 colons++;
7954                 more = (peek(state) == TOK_LIT_STRING);
7955                 while(more) {
7956                         struct triple *var;
7957                         struct triple *constraint;
7958                         char *str;
7959                         more = 0;
7960                         if (out > MAX_LHS) {
7961                                 error(state, 0, "Maximum output count exceeded.");
7962                         }
7963                         constraint = string_constant(state);
7964                         str = constraint->u.blob;
7965                         if (str[0] != '=') {
7966                                 error(state, 0, "Output constraint does not start with =");
7967                         }
7968                         constraint->u.blob = str + 1;
7969                         eat(state, TOK_LPAREN);
7970                         var = conditional_expr(state);
7971                         eat(state, TOK_RPAREN);
7972
7973                         lvalue(state, var);
7974                         out_param[out].constraint = constraint;
7975                         out_param[out].expr       = var;
7976                         if (peek(state) == TOK_COMMA) {
7977                                 eat(state, TOK_COMMA);
7978                                 more = 1;
7979                         }
7980                         out++;
7981                 }
7982         }
7983         /* Inputs */
7984         if ((colons == 1) && (peek(state) == TOK_COLON)) {
7985                 eat(state, TOK_COLON);
7986                 colons++;
7987                 more = (peek(state) == TOK_LIT_STRING);
7988                 while(more) {
7989                         struct triple *val;
7990                         struct triple *constraint;
7991                         char *str;
7992                         more = 0;
7993                         if (in > MAX_RHS) {
7994                                 error(state, 0, "Maximum input count exceeded.");
7995                         }
7996                         constraint = string_constant(state);
7997                         str = constraint->u.blob;
7998                         if (digitp(str[0] && str[1] == '\0')) {
7999                                 int val;
8000                                 val = digval(str[0]);
8001                                 if ((val < 0) || (val >= out)) {
8002                                         error(state, 0, "Invalid input constraint %d", val);
8003                                 }
8004                         }
8005                         eat(state, TOK_LPAREN);
8006                         val = conditional_expr(state);
8007                         eat(state, TOK_RPAREN);
8008
8009                         in_param[in].constraint = constraint;
8010                         in_param[in].expr       = val;
8011                         if (peek(state) == TOK_COMMA) {
8012                                 eat(state, TOK_COMMA);
8013                                 more = 1;
8014                         }
8015                         in++;
8016                 }
8017         }
8018
8019         /* Clobber */
8020         if ((colons == 2) && (peek(state) == TOK_COLON)) {
8021                 eat(state, TOK_COLON);
8022                 colons++;
8023                 more = (peek(state) == TOK_LIT_STRING);
8024                 while(more) {
8025                         struct triple *clobber;
8026                         more = 0;
8027                         if ((clobbers + out) > MAX_LHS) {
8028                                 error(state, 0, "Maximum clobber limit exceeded.");
8029                         }
8030                         clobber = string_constant(state);
8031                         eat(state, TOK_RPAREN);
8032
8033                         clob_param[clobbers].constraint = clobber;
8034                         if (peek(state) == TOK_COMMA) {
8035                                 eat(state, TOK_COMMA);
8036                                 more = 1;
8037                         }
8038                         clobbers++;
8039                 }
8040         }
8041         eat(state, TOK_RPAREN);
8042         eat(state, TOK_SEMI);
8043
8044
8045         info = xcmalloc(sizeof(*info), "asm_info");
8046         info->str = asm_str->u.blob;
8047         free_triple(state, asm_str);
8048
8049         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8050         def->u.ainfo = info;
8051
8052         /* Find the register constraints */
8053         for(i = 0; i < out; i++) {
8054                 struct triple *constraint;
8055                 constraint = out_param[i].constraint;
8056                 info->tmpl.lhs[i] = arch_reg_constraint(state, 
8057                         out_param[i].expr->type, constraint->u.blob);
8058                 free_triple(state, constraint);
8059         }
8060         for(; i - out < clobbers; i++) {
8061                 struct triple *constraint;
8062                 constraint = clob_param[i - out].constraint;
8063                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8064                 free_triple(state, constraint);
8065         }
8066         for(i = 0; i < in; i++) {
8067                 struct triple *constraint;
8068                 const char *str;
8069                 constraint = in_param[i].constraint;
8070                 str = constraint->u.blob;
8071                 if (digitp(str[0]) && str[1] == '\0') {
8072                         struct reg_info cinfo;
8073                         int val;
8074                         val = digval(str[0]);
8075                         cinfo.reg = info->tmpl.lhs[val].reg;
8076                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8077                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
8078                         if (cinfo.reg == REG_UNSET) {
8079                                 cinfo.reg = REG_VIRT0 + val;
8080                         }
8081                         if (cinfo.regcm == 0) {
8082                                 error(state, 0, "No registers for %d", val);
8083                         }
8084                         info->tmpl.lhs[val] = cinfo;
8085                         info->tmpl.rhs[i]   = cinfo;
8086                                 
8087                 } else {
8088                         info->tmpl.rhs[i] = arch_reg_constraint(state, 
8089                                 in_param[i].expr->type, str);
8090                 }
8091                 free_triple(state, constraint);
8092         }
8093
8094         /* Now build the helper expressions */
8095         for(i = 0; i < in; i++) {
8096                 RHS(def, i) = read_expr(state,in_param[i].expr);
8097         }
8098         flatten(state, first, def);
8099         for(i = 0; i < out; i++) {
8100                 struct triple *piece;
8101                 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8102                 piece->u.cval = i;
8103                 LHS(def, i) = piece;
8104                 flatten(state, first,
8105                         write_expr(state, out_param[i].expr, piece));
8106         }
8107         for(; i - out < clobbers; i++) {
8108                 struct triple *piece;
8109                 piece = triple(state, OP_PIECE, &void_type, def, 0);
8110                 piece->u.cval = i;
8111                 LHS(def, i) = piece;
8112                 flatten(state, first, piece);
8113         }
8114 }
8115
8116
8117 static int isdecl(int tok)
8118 {
8119         switch(tok) {
8120         case TOK_AUTO:
8121         case TOK_REGISTER:
8122         case TOK_STATIC:
8123         case TOK_EXTERN:
8124         case TOK_TYPEDEF:
8125         case TOK_CONST:
8126         case TOK_RESTRICT:
8127         case TOK_VOLATILE:
8128         case TOK_VOID:
8129         case TOK_CHAR:
8130         case TOK_SHORT:
8131         case TOK_INT:
8132         case TOK_LONG:
8133         case TOK_FLOAT:
8134         case TOK_DOUBLE:
8135         case TOK_SIGNED:
8136         case TOK_UNSIGNED:
8137         case TOK_STRUCT:
8138         case TOK_UNION:
8139         case TOK_ENUM:
8140         case TOK_TYPE_NAME: /* typedef name */
8141                 return 1;
8142         default:
8143                 return 0;
8144         }
8145 }
8146
8147 static void compound_statement(struct compile_state *state, struct triple *first)
8148 {
8149         eat(state, TOK_LBRACE);
8150         start_scope(state);
8151
8152         /* statement-list opt */
8153         while (peek(state) != TOK_RBRACE) {
8154                 statement(state, first);
8155         }
8156         end_scope(state);
8157         eat(state, TOK_RBRACE);
8158 }
8159
8160 static void statement(struct compile_state *state, struct triple *first)
8161 {
8162         int tok;
8163         tok = peek(state);
8164         if (tok == TOK_LBRACE) {
8165                 compound_statement(state, first);
8166         }
8167         else if (tok == TOK_IF) {
8168                 if_statement(state, first); 
8169         }
8170         else if (tok == TOK_FOR) {
8171                 for_statement(state, first);
8172         }
8173         else if (tok == TOK_WHILE) {
8174                 while_statement(state, first);
8175         }
8176         else if (tok == TOK_DO) {
8177                 do_statement(state, first);
8178         }
8179         else if (tok == TOK_RETURN) {
8180                 return_statement(state, first);
8181         }
8182         else if (tok == TOK_BREAK) {
8183                 break_statement(state, first);
8184         }
8185         else if (tok == TOK_CONTINUE) {
8186                 continue_statement(state, first);
8187         }
8188         else if (tok == TOK_GOTO) {
8189                 goto_statement(state, first);
8190         }
8191         else if (tok == TOK_SWITCH) {
8192                 switch_statement(state, first);
8193         }
8194         else if (tok == TOK_ASM) {
8195                 asm_statement(state, first);
8196         }
8197         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8198                 labeled_statement(state, first); 
8199         }
8200         else if (tok == TOK_CASE) {
8201                 case_statement(state, first);
8202         }
8203         else if (tok == TOK_DEFAULT) {
8204                 default_statement(state, first);
8205         }
8206         else if (isdecl(tok)) {
8207                 /* This handles C99 intermixing of statements and decls */
8208                 decl(state, first);
8209         }
8210         else {
8211                 expr_statement(state, first);
8212         }
8213 }
8214
8215 static struct type *param_decl(struct compile_state *state)
8216 {
8217         struct type *type;
8218         struct hash_entry *ident;
8219         /* Cheat so the declarator will know we are not global */
8220         start_scope(state); 
8221         ident = 0;
8222         type = decl_specifiers(state);
8223         type = declarator(state, type, &ident, 0);
8224         type->field_ident = ident;
8225         end_scope(state);
8226         return type;
8227 }
8228
8229 static struct type *param_type_list(struct compile_state *state, struct type *type)
8230 {
8231         struct type *ftype, **next;
8232         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8233         next = &ftype->right;
8234         while(peek(state) == TOK_COMMA) {
8235                 eat(state, TOK_COMMA);
8236                 if (peek(state) == TOK_DOTS) {
8237                         eat(state, TOK_DOTS);
8238                         error(state, 0, "variadic functions not supported");
8239                 }
8240                 else {
8241                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8242                         next = &((*next)->right);
8243                 }
8244         }
8245         return ftype;
8246 }
8247
8248
8249 static struct type *type_name(struct compile_state *state)
8250 {
8251         struct type *type;
8252         type = specifier_qualifier_list(state);
8253         /* abstract-declarator (may consume no tokens) */
8254         type = declarator(state, type, 0, 0);
8255         return type;
8256 }
8257
8258 static struct type *direct_declarator(
8259         struct compile_state *state, struct type *type, 
8260         struct hash_entry **ident, int need_ident)
8261 {
8262         struct type *outer;
8263         int op;
8264         outer = 0;
8265         arrays_complete(state, type);
8266         switch(peek(state)) {
8267         case TOK_IDENT:
8268                 eat(state, TOK_IDENT);
8269                 if (!ident) {
8270                         error(state, 0, "Unexpected identifier found");
8271                 }
8272                 /* The name of what we are declaring */
8273                 *ident = state->token[0].ident;
8274                 break;
8275         case TOK_LPAREN:
8276                 eat(state, TOK_LPAREN);
8277                 outer = declarator(state, type, ident, need_ident);
8278                 eat(state, TOK_RPAREN);
8279                 break;
8280         default:
8281                 if (need_ident) {
8282                         error(state, 0, "Identifier expected");
8283                 }
8284                 break;
8285         }
8286         do {
8287                 op = 1;
8288                 arrays_complete(state, type);
8289                 switch(peek(state)) {
8290                 case TOK_LPAREN:
8291                         eat(state, TOK_LPAREN);
8292                         type = param_type_list(state, type);
8293                         eat(state, TOK_RPAREN);
8294                         break;
8295                 case TOK_LBRACKET:
8296                 {
8297                         unsigned int qualifiers;
8298                         struct triple *value;
8299                         value = 0;
8300                         eat(state, TOK_LBRACKET);
8301                         if (peek(state) != TOK_RBRACKET) {
8302                                 value = constant_expr(state);
8303                                 integral(state, value);
8304                         }
8305                         eat(state, TOK_RBRACKET);
8306
8307                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8308                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8309                         if (value) {
8310                                 type->elements = value->u.cval;
8311                                 free_triple(state, value);
8312                         } else {
8313                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8314                                 op = 0;
8315                         }
8316                 }
8317                         break;
8318                 default:
8319                         op = 0;
8320                         break;
8321                 }
8322         } while(op);
8323         if (outer) {
8324                 struct type *inner;
8325                 arrays_complete(state, type);
8326                 FINISHME();
8327                 for(inner = outer; inner->left; inner = inner->left)
8328                         ;
8329                 inner->left = type;
8330                 type = outer;
8331         }
8332         return type;
8333 }
8334
8335 static struct type *declarator(
8336         struct compile_state *state, struct type *type, 
8337         struct hash_entry **ident, int need_ident)
8338 {
8339         while(peek(state) == TOK_STAR) {
8340                 eat(state, TOK_STAR);
8341                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8342         }
8343         type = direct_declarator(state, type, ident, need_ident);
8344         return type;
8345 }
8346
8347
8348 static struct type *typedef_name(
8349         struct compile_state *state, unsigned int specifiers)
8350 {
8351         struct hash_entry *ident;
8352         struct type *type;
8353         eat(state, TOK_TYPE_NAME);
8354         ident = state->token[0].ident;
8355         type = ident->sym_ident->type;
8356         specifiers |= type->type & QUAL_MASK;
8357         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
8358                 (type->type & (STOR_MASK | QUAL_MASK))) {
8359                 type = clone_type(specifiers, type);
8360         }
8361         return type;
8362 }
8363
8364 static struct type *enum_specifier(
8365         struct compile_state *state, unsigned int specifiers)
8366 {
8367         int tok;
8368         struct type *type;
8369         type = 0;
8370         FINISHME();
8371         eat(state, TOK_ENUM);
8372         tok = peek(state);
8373         if (tok == TOK_IDENT) {
8374                 eat(state, TOK_IDENT);
8375         }
8376         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8377                 eat(state, TOK_LBRACE);
8378                 do {
8379                         eat(state, TOK_IDENT);
8380                         if (peek(state) == TOK_EQ) {
8381                                 eat(state, TOK_EQ);
8382                                 constant_expr(state);
8383                         }
8384                         if (peek(state) == TOK_COMMA) {
8385                                 eat(state, TOK_COMMA);
8386                         }
8387                 } while(peek(state) != TOK_RBRACE);
8388                 eat(state, TOK_RBRACE);
8389         }
8390         FINISHME();
8391         return type;
8392 }
8393
8394 #if 0
8395 static struct type *struct_declarator(
8396         struct compile_state *state, struct type *type, struct hash_entry **ident)
8397 {
8398         int tok;
8399 #warning "struct_declarator is complicated because of bitfields, kill them?"
8400         tok = peek(state);
8401         if (tok != TOK_COLON) {
8402                 type = declarator(state, type, ident, 1);
8403         }
8404         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8405                 eat(state, TOK_COLON);
8406                 constant_expr(state);
8407         }
8408         FINISHME();
8409         return type;
8410 }
8411 #endif
8412
8413 static struct type *struct_or_union_specifier(
8414         struct compile_state *state, unsigned int spec)
8415 {
8416         struct type *struct_type;
8417         struct hash_entry *ident;
8418         unsigned int type_join;
8419         int tok;
8420         struct_type = 0;
8421         ident = 0;
8422         switch(peek(state)) {
8423         case TOK_STRUCT:
8424                 eat(state, TOK_STRUCT);
8425                 type_join = TYPE_PRODUCT;
8426                 break;
8427         case TOK_UNION:
8428                 eat(state, TOK_UNION);
8429                 type_join = TYPE_OVERLAP;
8430                 error(state, 0, "unions not yet supported\n");
8431                 break;
8432         default:
8433                 eat(state, TOK_STRUCT);
8434                 type_join = TYPE_PRODUCT;
8435                 break;
8436         }
8437         tok = peek(state);
8438         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8439                 eat(state, tok);
8440                 ident = state->token[0].ident;
8441         }
8442         if (!ident || (peek(state) == TOK_LBRACE)) {
8443                 ulong_t elements;
8444                 elements = 0;
8445                 eat(state, TOK_LBRACE);
8446                 do {
8447                         struct type *base_type;
8448                         struct type **next;
8449                         int done;
8450                         base_type = specifier_qualifier_list(state);
8451                         next = &struct_type;
8452                         do {
8453                                 struct type *type;
8454                                 struct hash_entry *fident;
8455                                 done = 1;
8456                                 type = declarator(state, base_type, &fident, 1);
8457                                 elements++;
8458                                 if (peek(state) == TOK_COMMA) {
8459                                         done = 0;
8460                                         eat(state, TOK_COMMA);
8461                                 }
8462                                 type = clone_type(0, type);
8463                                 type->field_ident = fident;
8464                                 if (*next) {
8465                                         *next = new_type(type_join, *next, type);
8466                                         next = &((*next)->right);
8467                                 } else {
8468                                         *next = type;
8469                                 }
8470                         } while(!done);
8471                         eat(state, TOK_SEMI);
8472                 } while(peek(state) != TOK_RBRACE);
8473                 eat(state, TOK_RBRACE);
8474                 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8475                 struct_type->type_ident = ident;
8476                 struct_type->elements = elements;
8477                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8478         }
8479         if (ident && ident->sym_struct) {
8480                 struct_type = clone_type(spec,  ident->sym_struct->type);
8481         }
8482         else if (ident && !ident->sym_struct) {
8483                 error(state, 0, "struct %s undeclared", ident->name);
8484         }
8485         return struct_type;
8486 }
8487
8488 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8489 {
8490         unsigned int specifiers;
8491         switch(peek(state)) {
8492         case TOK_AUTO:
8493                 eat(state, TOK_AUTO);
8494                 specifiers = STOR_AUTO;
8495                 break;
8496         case TOK_REGISTER:
8497                 eat(state, TOK_REGISTER);
8498                 specifiers = STOR_REGISTER;
8499                 break;
8500         case TOK_STATIC:
8501                 eat(state, TOK_STATIC);
8502                 specifiers = STOR_STATIC;
8503                 break;
8504         case TOK_EXTERN:
8505                 eat(state, TOK_EXTERN);
8506                 specifiers = STOR_EXTERN;
8507                 break;
8508         case TOK_TYPEDEF:
8509                 eat(state, TOK_TYPEDEF);
8510                 specifiers = STOR_TYPEDEF;
8511                 break;
8512         default:
8513                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8514                         specifiers = STOR_STATIC;
8515                 }
8516                 else {
8517                         specifiers = STOR_AUTO;
8518                 }
8519         }
8520         return specifiers;
8521 }
8522
8523 static unsigned int function_specifier_opt(struct compile_state *state)
8524 {
8525         /* Ignore the inline keyword */
8526         unsigned int specifiers;
8527         specifiers = 0;
8528         switch(peek(state)) {
8529         case TOK_INLINE:
8530                 eat(state, TOK_INLINE);
8531                 specifiers = STOR_INLINE;
8532         }
8533         return specifiers;
8534 }
8535
8536 static unsigned int type_qualifiers(struct compile_state *state)
8537 {
8538         unsigned int specifiers;
8539         int done;
8540         done = 0;
8541         specifiers = QUAL_NONE;
8542         do {
8543                 switch(peek(state)) {
8544                 case TOK_CONST:
8545                         eat(state, TOK_CONST);
8546                         specifiers = QUAL_CONST;
8547                         break;
8548                 case TOK_VOLATILE:
8549                         eat(state, TOK_VOLATILE);
8550                         specifiers = QUAL_VOLATILE;
8551                         break;
8552                 case TOK_RESTRICT:
8553                         eat(state, TOK_RESTRICT);
8554                         specifiers = QUAL_RESTRICT;
8555                         break;
8556                 default:
8557                         done = 1;
8558                         break;
8559                 }
8560         } while(!done);
8561         return specifiers;
8562 }
8563
8564 static struct type *type_specifier(
8565         struct compile_state *state, unsigned int spec)
8566 {
8567         struct type *type;
8568         type = 0;
8569         switch(peek(state)) {
8570         case TOK_VOID:
8571                 eat(state, TOK_VOID);
8572                 type = new_type(TYPE_VOID | spec, 0, 0);
8573                 break;
8574         case TOK_CHAR:
8575                 eat(state, TOK_CHAR);
8576                 type = new_type(TYPE_CHAR | spec, 0, 0);
8577                 break;
8578         case TOK_SHORT:
8579                 eat(state, TOK_SHORT);
8580                 if (peek(state) == TOK_INT) {
8581                         eat(state, TOK_INT);
8582                 }
8583                 type = new_type(TYPE_SHORT | spec, 0, 0);
8584                 break;
8585         case TOK_INT:
8586                 eat(state, TOK_INT);
8587                 type = new_type(TYPE_INT | spec, 0, 0);
8588                 break;
8589         case TOK_LONG:
8590                 eat(state, TOK_LONG);
8591                 switch(peek(state)) {
8592                 case TOK_LONG:
8593                         eat(state, TOK_LONG);
8594                         error(state, 0, "long long not supported");
8595                         break;
8596                 case TOK_DOUBLE:
8597                         eat(state, TOK_DOUBLE);
8598                         error(state, 0, "long double not supported");
8599                         break;
8600                 case TOK_INT:
8601                         eat(state, TOK_INT);
8602                         type = new_type(TYPE_LONG | spec, 0, 0);
8603                         break;
8604                 default:
8605                         type = new_type(TYPE_LONG | spec, 0, 0);
8606                         break;
8607                 }
8608                 break;
8609         case TOK_FLOAT:
8610                 eat(state, TOK_FLOAT);
8611                 error(state, 0, "type float not supported");
8612                 break;
8613         case TOK_DOUBLE:
8614                 eat(state, TOK_DOUBLE);
8615                 error(state, 0, "type double not supported");
8616                 break;
8617         case TOK_SIGNED:
8618                 eat(state, TOK_SIGNED);
8619                 switch(peek(state)) {
8620                 case TOK_LONG:
8621                         eat(state, TOK_LONG);
8622                         switch(peek(state)) {
8623                         case TOK_LONG:
8624                                 eat(state, TOK_LONG);
8625                                 error(state, 0, "type long long not supported");
8626                                 break;
8627                         case TOK_INT:
8628                                 eat(state, TOK_INT);
8629                                 type = new_type(TYPE_LONG | spec, 0, 0);
8630                                 break;
8631                         default:
8632                                 type = new_type(TYPE_LONG | spec, 0, 0);
8633                                 break;
8634                         }
8635                         break;
8636                 case TOK_INT:
8637                         eat(state, TOK_INT);
8638                         type = new_type(TYPE_INT | spec, 0, 0);
8639                         break;
8640                 case TOK_SHORT:
8641                         eat(state, TOK_SHORT);
8642                         type = new_type(TYPE_SHORT | spec, 0, 0);
8643                         break;
8644                 case TOK_CHAR:
8645                         eat(state, TOK_CHAR);
8646                         type = new_type(TYPE_CHAR | spec, 0, 0);
8647                         break;
8648                 default:
8649                         type = new_type(TYPE_INT | spec, 0, 0);
8650                         break;
8651                 }
8652                 break;
8653         case TOK_UNSIGNED:
8654                 eat(state, TOK_UNSIGNED);
8655                 switch(peek(state)) {
8656                 case TOK_LONG:
8657                         eat(state, TOK_LONG);
8658                         switch(peek(state)) {
8659                         case TOK_LONG:
8660                                 eat(state, TOK_LONG);
8661                                 error(state, 0, "unsigned long long not supported");
8662                                 break;
8663                         case TOK_INT:
8664                                 eat(state, TOK_INT);
8665                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8666                                 break;
8667                         default:
8668                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8669                                 break;
8670                         }
8671                         break;
8672                 case TOK_INT:
8673                         eat(state, TOK_INT);
8674                         type = new_type(TYPE_UINT | spec, 0, 0);
8675                         break;
8676                 case TOK_SHORT:
8677                         eat(state, TOK_SHORT);
8678                         type = new_type(TYPE_USHORT | spec, 0, 0);
8679                         break;
8680                 case TOK_CHAR:
8681                         eat(state, TOK_CHAR);
8682                         type = new_type(TYPE_UCHAR | spec, 0, 0);
8683                         break;
8684                 default:
8685                         type = new_type(TYPE_UINT | spec, 0, 0);
8686                         break;
8687                 }
8688                 break;
8689                 /* struct or union specifier */
8690         case TOK_STRUCT:
8691         case TOK_UNION:
8692                 type = struct_or_union_specifier(state, spec);
8693                 break;
8694                 /* enum-spefifier */
8695         case TOK_ENUM:
8696                 type = enum_specifier(state, spec);
8697                 break;
8698                 /* typedef name */
8699         case TOK_TYPE_NAME:
8700                 type = typedef_name(state, spec);
8701                 break;
8702         default:
8703                 error(state, 0, "bad type specifier %s", 
8704                         tokens[peek(state)]);
8705                 break;
8706         }
8707         return type;
8708 }
8709
8710 static int istype(int tok)
8711 {
8712         switch(tok) {
8713         case TOK_CONST:
8714         case TOK_RESTRICT:
8715         case TOK_VOLATILE:
8716         case TOK_VOID:
8717         case TOK_CHAR:
8718         case TOK_SHORT:
8719         case TOK_INT:
8720         case TOK_LONG:
8721         case TOK_FLOAT:
8722         case TOK_DOUBLE:
8723         case TOK_SIGNED:
8724         case TOK_UNSIGNED:
8725         case TOK_STRUCT:
8726         case TOK_UNION:
8727         case TOK_ENUM:
8728         case TOK_TYPE_NAME:
8729                 return 1;
8730         default:
8731                 return 0;
8732         }
8733 }
8734
8735
8736 static struct type *specifier_qualifier_list(struct compile_state *state)
8737 {
8738         struct type *type;
8739         unsigned int specifiers = 0;
8740
8741         /* type qualifiers */
8742         specifiers |= type_qualifiers(state);
8743
8744         /* type specifier */
8745         type = type_specifier(state, specifiers);
8746
8747         return type;
8748 }
8749
8750 static int isdecl_specifier(int tok)
8751 {
8752         switch(tok) {
8753                 /* storage class specifier */
8754         case TOK_AUTO:
8755         case TOK_REGISTER:
8756         case TOK_STATIC:
8757         case TOK_EXTERN:
8758         case TOK_TYPEDEF:
8759                 /* type qualifier */
8760         case TOK_CONST:
8761         case TOK_RESTRICT:
8762         case TOK_VOLATILE:
8763                 /* type specifiers */
8764         case TOK_VOID:
8765         case TOK_CHAR:
8766         case TOK_SHORT:
8767         case TOK_INT:
8768         case TOK_LONG:
8769         case TOK_FLOAT:
8770         case TOK_DOUBLE:
8771         case TOK_SIGNED:
8772         case TOK_UNSIGNED:
8773                 /* struct or union specifier */
8774         case TOK_STRUCT:
8775         case TOK_UNION:
8776                 /* enum-spefifier */
8777         case TOK_ENUM:
8778                 /* typedef name */
8779         case TOK_TYPE_NAME:
8780                 /* function specifiers */
8781         case TOK_INLINE:
8782                 return 1;
8783         default:
8784                 return 0;
8785         }
8786 }
8787
8788 static struct type *decl_specifiers(struct compile_state *state)
8789 {
8790         struct type *type;
8791         unsigned int specifiers;
8792         /* I am overly restrictive in the arragement of specifiers supported.
8793          * C is overly flexible in this department it makes interpreting
8794          * the parse tree difficult.
8795          */
8796         specifiers = 0;
8797
8798         /* storage class specifier */
8799         specifiers |= storage_class_specifier_opt(state);
8800
8801         /* function-specifier */
8802         specifiers |= function_specifier_opt(state);
8803
8804         /* type qualifier */
8805         specifiers |= type_qualifiers(state);
8806
8807         /* type specifier */
8808         type = type_specifier(state, specifiers);
8809         return type;
8810 }
8811
8812 struct field_info {
8813         struct type *type;
8814         size_t offset;
8815 };
8816
8817 static struct field_info designator(struct compile_state *state, struct type *type)
8818 {
8819         int tok;
8820         struct field_info info;
8821         info.offset = ~0U;
8822         info.type = 0;
8823         do {
8824                 switch(peek(state)) {
8825                 case TOK_LBRACKET:
8826                 {
8827                         struct triple *value;
8828                         if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8829                                 error(state, 0, "Array designator not in array initializer");
8830                         }
8831                         eat(state, TOK_LBRACKET);
8832                         value = constant_expr(state);
8833                         eat(state, TOK_RBRACKET);
8834
8835                         info.type = type->left;
8836                         info.offset = value->u.cval * size_of(state, info.type);
8837                         break;
8838                 }
8839                 case TOK_DOT:
8840                 {
8841                         struct hash_entry *field;
8842                         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
8843                                 error(state, 0, "Struct designator not in struct initializer");
8844                         }
8845                         eat(state, TOK_DOT);
8846                         eat(state, TOK_IDENT);
8847                         field = state->token[0].ident;
8848                         info.offset = field_offset(state, type, field);
8849                         info.type   = field_type(state, type, field);
8850                         break;
8851                 }
8852                 default:
8853                         error(state, 0, "Invalid designator");
8854                 }
8855                 tok = peek(state);
8856         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8857         eat(state, TOK_EQ);
8858         return info;
8859 }
8860
8861 static struct triple *initializer(
8862         struct compile_state *state, struct type *type)
8863 {
8864         struct triple *result;
8865         if (peek(state) != TOK_LBRACE) {
8866                 result = assignment_expr(state);
8867         }
8868         else {
8869                 int comma;
8870                 size_t max_offset;
8871                 struct field_info info;
8872                 void *buf;
8873                 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
8874                         ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
8875                         internal_error(state, 0, "unknown initializer type");
8876                 }
8877                 info.offset = 0;
8878                 info.type = type->left;
8879                 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8880                         info.type = next_field(state, type, 0);
8881                 }
8882                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8883                         max_offset = 0;
8884                 } else {
8885                         max_offset = size_of(state, type);
8886                 }
8887                 buf = xcmalloc(max_offset, "initializer");
8888                 eat(state, TOK_LBRACE);
8889                 do {
8890                         struct triple *value;
8891                         struct type *value_type;
8892                         size_t value_size;
8893                         void *dest;
8894                         int tok;
8895                         comma = 0;
8896                         tok = peek(state);
8897                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8898                                 info = designator(state, type);
8899                         }
8900                         if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
8901                                 (info.offset >= max_offset)) {
8902                                 error(state, 0, "element beyond bounds");
8903                         }
8904                         value_type = info.type;
8905                         value = eval_const_expr(state, initializer(state, value_type));
8906                         value_size = size_of(state, value_type);
8907                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8908                                 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8909                                 (max_offset <= info.offset)) {
8910                                 void *old_buf;
8911                                 size_t old_size;
8912                                 old_buf = buf;
8913                                 old_size = max_offset;
8914                                 max_offset = info.offset + value_size;
8915                                 buf = xmalloc(max_offset, "initializer");
8916                                 memcpy(buf, old_buf, old_size);
8917                                 xfree(old_buf);
8918                         }
8919                         dest = ((char *)buf) + info.offset;
8920                         if (value->op == OP_BLOBCONST) {
8921                                 memcpy(dest, value->u.blob, value_size);
8922                         }
8923                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8924                                 *((uint8_t *)dest) = value->u.cval & 0xff;
8925                         }
8926                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8927                                 *((uint16_t *)dest) = value->u.cval & 0xffff;
8928                         }
8929                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8930                                 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
8931                         }
8932                         else {
8933                                 internal_error(state, 0, "unhandled constant initializer");
8934                         }
8935                         free_triple(state, value);
8936                         if (peek(state) == TOK_COMMA) {
8937                                 eat(state, TOK_COMMA);
8938                                 comma = 1;
8939                         }
8940                         info.offset += value_size;
8941                         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8942                                 info.type = next_field(state, type, info.type);
8943                                 info.offset = field_offset(state, type, 
8944                                         info.type->field_ident);
8945                         }
8946                 } while(comma && (peek(state) != TOK_RBRACE));
8947                 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8948                         ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
8949                         type->elements = max_offset / size_of(state, type->left);
8950                 }
8951                 eat(state, TOK_RBRACE);
8952                 result = triple(state, OP_BLOBCONST, type, 0, 0);
8953                 result->u.blob = buf;
8954         }
8955         return result;
8956 }
8957
8958 static void resolve_branches(struct compile_state *state)
8959 {
8960         /* Make a second pass and finish anything outstanding
8961          * with respect to branches.  The only outstanding item
8962          * is to see if there are goto to labels that have not
8963          * been defined and to error about them.
8964          */
8965         int i;
8966         for(i = 0; i < HASH_TABLE_SIZE; i++) {
8967                 struct hash_entry *entry;
8968                 for(entry = state->hash_table[i]; entry; entry = entry->next) {
8969                         struct triple *ins;
8970                         if (!entry->sym_label) {
8971                                 continue;
8972                         }
8973                         ins = entry->sym_label->def;
8974                         if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
8975                                 error(state, ins, "label `%s' used but not defined",
8976                                         entry->name);
8977                         }
8978                 }
8979         }
8980 }
8981
8982 static struct triple *function_definition(
8983         struct compile_state *state, struct type *type)
8984 {
8985         struct triple *def, *tmp, *first, *end;
8986         struct hash_entry *ident;
8987         struct type *param;
8988         int i;
8989         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8990                 error(state, 0, "Invalid function header");
8991         }
8992
8993         /* Verify the function type */
8994         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
8995                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8996                 (type->right->field_ident == 0)) {
8997                 error(state, 0, "Invalid function parameters");
8998         }
8999         param = type->right;
9000         i = 0;
9001         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9002                 i++;
9003                 if (!param->left->field_ident) {
9004                         error(state, 0, "No identifier for parameter %d\n", i);
9005                 }
9006                 param = param->right;
9007         }
9008         i++;
9009         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9010                 error(state, 0, "No identifier for paramter %d\n", i);
9011         }
9012         
9013         /* Get a list of statements for this function. */
9014         def = triple(state, OP_LIST, type, 0, 0);
9015
9016         /* Start a new scope for the passed parameters */
9017         start_scope(state);
9018
9019         /* Put a label at the very start of a function */
9020         first = label(state);
9021         RHS(def, 0) = first;
9022
9023         /* Put a label at the very end of a function */
9024         end = label(state);
9025         flatten(state, first, end);
9026
9027         /* Walk through the parameters and create symbol table entries
9028          * for them.
9029          */
9030         param = type->right;
9031         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9032                 ident = param->left->field_ident;
9033                 tmp = variable(state, param->left);
9034                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9035                 flatten(state, end, tmp);
9036                 param = param->right;
9037         }
9038         if ((param->type & TYPE_MASK) != TYPE_VOID) {
9039                 /* And don't forget the last parameter */
9040                 ident = param->field_ident;
9041                 tmp = variable(state, param);
9042                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9043                 flatten(state, end, tmp);
9044         }
9045         /* Add a variable for the return value */
9046         MISC(def, 0) = 0;
9047         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9048                 /* Remove all type qualifiers from the return type */
9049                 tmp = variable(state, clone_type(0, type->left));
9050                 flatten(state, end, tmp);
9051                 /* Remember where the return value is */
9052                 MISC(def, 0) = tmp;
9053         }
9054
9055         /* Remember which function I am compiling.
9056          * Also assume the last defined function is the main function.
9057          */
9058         state->main_function = def;
9059
9060         /* Now get the actual function definition */
9061         compound_statement(state, end);
9062
9063         /* Finish anything unfinished with branches */
9064         resolve_branches(state);
9065
9066         /* Remove the parameter scope */
9067         end_scope(state);
9068
9069 #if 0
9070         fprintf(stdout, "\n");
9071         loc(stdout, state, 0);
9072         fprintf(stdout, "\n__________ function_definition _________\n");
9073         print_triple(state, def);
9074         fprintf(stdout, "__________ function_definition _________ done\n\n");
9075 #endif
9076
9077         return def;
9078 }
9079
9080 static struct triple *do_decl(struct compile_state *state, 
9081         struct type *type, struct hash_entry *ident)
9082 {
9083         struct triple *def;
9084         def = 0;
9085         /* Clean up the storage types used */
9086         switch (type->type & STOR_MASK) {
9087         case STOR_AUTO:
9088         case STOR_STATIC:
9089                 /* These are the good types I am aiming for */
9090                 break;
9091         case STOR_REGISTER:
9092                 type->type &= ~STOR_MASK;
9093                 type->type |= STOR_AUTO;
9094                 break;
9095         case STOR_EXTERN:
9096                 type->type &= ~STOR_MASK;
9097                 type->type |= STOR_STATIC;
9098                 break;
9099         case STOR_TYPEDEF:
9100                 if (!ident) {
9101                         error(state, 0, "typedef without name");
9102                 }
9103                 symbol(state, ident, &ident->sym_ident, 0, type);
9104                 ident->tok = TOK_TYPE_NAME;
9105                 return 0;
9106                 break;
9107         default:
9108                 internal_error(state, 0, "Undefined storage class");
9109         }
9110         if (ident && 
9111                 ((type->type & STOR_MASK) == STOR_STATIC) &&
9112                 ((type->type & QUAL_CONST) == 0)) {
9113                 error(state, 0, "non const static variables not supported");
9114         }
9115         if (ident) {
9116                 def = variable(state, type);
9117                 symbol(state, ident, &ident->sym_ident, def, type);
9118         }
9119         return def;
9120 }
9121
9122 static void decl(struct compile_state *state, struct triple *first)
9123 {
9124         struct type *base_type, *type;
9125         struct hash_entry *ident;
9126         struct triple *def;
9127         int global;
9128         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9129         base_type = decl_specifiers(state);
9130         ident = 0;
9131         type = declarator(state, base_type, &ident, 0);
9132         if (global && ident && (peek(state) == TOK_LBRACE)) {
9133                 /* function */
9134                 state->function = ident->name;
9135                 def = function_definition(state, type);
9136                 symbol(state, ident, &ident->sym_ident, def, type);
9137                 state->function = 0;
9138         }
9139         else {
9140                 int done;
9141                 flatten(state, first, do_decl(state, type, ident));
9142                 /* type or variable definition */
9143                 do {
9144                         done = 1;
9145                         if (peek(state) == TOK_EQ) {
9146                                 if (!ident) {
9147                                         error(state, 0, "cannot assign to a type");
9148                                 }
9149                                 eat(state, TOK_EQ);
9150                                 flatten(state, first,
9151                                         init_expr(state, 
9152                                                 ident->sym_ident->def, 
9153                                                 initializer(state, type)));
9154                         }
9155                         arrays_complete(state, type);
9156                         if (peek(state) == TOK_COMMA) {
9157                                 eat(state, TOK_COMMA);
9158                                 ident = 0;
9159                                 type = declarator(state, base_type, &ident, 0);
9160                                 flatten(state, first, do_decl(state, type, ident));
9161                                 done = 0;
9162                         }
9163                 } while(!done);
9164                 eat(state, TOK_SEMI);
9165         }
9166 }
9167
9168 static void decls(struct compile_state *state)
9169 {
9170         struct triple *list;
9171         int tok;
9172         list = label(state);
9173         while(1) {
9174                 tok = peek(state);
9175                 if (tok == TOK_EOF) {
9176                         return;
9177                 }
9178                 if (tok == TOK_SPACE) {
9179                         eat(state, TOK_SPACE);
9180                 }
9181                 decl(state, list);
9182                 if (list->next != list) {
9183                         error(state, 0, "global variables not supported");
9184                 }
9185         }
9186 }
9187
9188 /*
9189  * Data structurs for optimation.
9190  */
9191
9192 static void do_use_block(
9193         struct block *used, struct block_set **head, struct block *user, 
9194         int front)
9195 {
9196         struct block_set **ptr, *new;
9197         if (!used)
9198                 return;
9199         if (!user)
9200                 return;
9201         ptr = head;
9202         while(*ptr) {
9203                 if ((*ptr)->member == user) {
9204                         return;
9205                 }
9206                 ptr = &(*ptr)->next;
9207         }
9208         new = xcmalloc(sizeof(*new), "block_set");
9209         new->member = user;
9210         if (front) {
9211                 new->next = *head;
9212                 *head = new;
9213         }
9214         else {
9215                 new->next = 0;
9216                 *ptr = new;
9217         }
9218 }
9219 static void do_unuse_block(
9220         struct block *used, struct block_set **head, struct block *unuser)
9221 {
9222         struct block_set *use, **ptr;
9223         ptr = head;
9224         while(*ptr) {
9225                 use = *ptr;
9226                 if (use->member == unuser) {
9227                         *ptr = use->next;
9228                         memset(use, -1, sizeof(*use));
9229                         xfree(use);
9230                 }
9231                 else {
9232                         ptr = &use->next;
9233                 }
9234         }
9235 }
9236
9237 static void use_block(struct block *used, struct block *user)
9238 {
9239         /* Append new to the head of the list, print_block
9240          * depends on this.
9241          */
9242         do_use_block(used, &used->use, user, 1); 
9243         used->users++;
9244 }
9245 static void unuse_block(struct block *used, struct block *unuser)
9246 {
9247         do_unuse_block(used, &used->use, unuser); 
9248         used->users--;
9249 }
9250
9251 static void idom_block(struct block *idom, struct block *user)
9252 {
9253         do_use_block(idom, &idom->idominates, user, 0);
9254 }
9255
9256 static void unidom_block(struct block *idom, struct block *unuser)
9257 {
9258         do_unuse_block(idom, &idom->idominates, unuser);
9259 }
9260
9261 static void domf_block(struct block *block, struct block *domf)
9262 {
9263         do_use_block(block, &block->domfrontier, domf, 0);
9264 }
9265
9266 static void undomf_block(struct block *block, struct block *undomf)
9267 {
9268         do_unuse_block(block, &block->domfrontier, undomf);
9269 }
9270
9271 static void ipdom_block(struct block *ipdom, struct block *user)
9272 {
9273         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9274 }
9275
9276 static void unipdom_block(struct block *ipdom, struct block *unuser)
9277 {
9278         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9279 }
9280
9281 static void ipdomf_block(struct block *block, struct block *ipdomf)
9282 {
9283         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9284 }
9285
9286 static void unipdomf_block(struct block *block, struct block *unipdomf)
9287 {
9288         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9289 }
9290
9291
9292
9293 static int do_walk_triple(struct compile_state *state,
9294         struct triple *ptr, int depth,
9295         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
9296 {
9297         int result;
9298         result = cb(state, ptr, depth);
9299         if ((result == 0) && (ptr->op == OP_LIST)) {
9300                 struct triple *list;
9301                 list = ptr;
9302                 ptr = RHS(list, 0);
9303                 do {
9304                         result = do_walk_triple(state, ptr, depth + 1, cb);
9305                         if (ptr->next->prev != ptr) {
9306                                 internal_error(state, ptr->next, "bad prev");
9307                         }
9308                         ptr = ptr->next;
9309                         
9310                 } while((result == 0) && (ptr != RHS(list, 0)));
9311         }
9312         return result;
9313 }
9314
9315 static int walk_triple(
9316         struct compile_state *state, 
9317         struct triple *ptr, 
9318         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9319 {
9320         return do_walk_triple(state, ptr, 0, cb);
9321 }
9322
9323 static void do_print_prefix(int depth)
9324 {
9325         int i;
9326         for(i = 0; i < depth; i++) {
9327                 printf("  ");
9328         }
9329 }
9330
9331 #define PRINT_LIST 1
9332 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9333 {
9334         int op;
9335         op = ins->op;
9336         if (op == OP_LIST) {
9337 #if !PRINT_LIST
9338                 return 0;
9339 #endif
9340         }
9341         if ((op == OP_LABEL) && (ins->use)) {
9342                 printf("\n%p:\n", ins);
9343         }
9344         do_print_prefix(depth);
9345         display_triple(stdout, ins);
9346
9347         if ((ins->op == OP_BRANCH) && ins->use) {
9348                 internal_error(state, ins, "branch used?");
9349         }
9350 #if 0
9351         {
9352                 struct triple_set *user;
9353                 for(user = ins->use; user; user = user->next) {
9354                         printf("use: %p\n", user->member);
9355                 }
9356         }
9357 #endif
9358         if (triple_is_branch(state, ins)) {
9359                 printf("\n");
9360         }
9361         return 0;
9362 }
9363
9364 static void print_triple(struct compile_state *state, struct triple *ins)
9365 {
9366         walk_triple(state, ins, do_print_triple);
9367 }
9368
9369 static void print_triples(struct compile_state *state)
9370 {
9371         print_triple(state, state->main_function);
9372 }
9373
9374 struct cf_block {
9375         struct block *block;
9376 };
9377 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9378 {
9379         if (!block || (cf[block->vertex].block == block)) {
9380                 return;
9381         }
9382         cf[block->vertex].block = block;
9383         find_cf_blocks(cf, block->left);
9384         find_cf_blocks(cf, block->right);
9385 }
9386
9387 static void print_control_flow(struct compile_state *state)
9388 {
9389         struct cf_block *cf;
9390         int i;
9391         printf("\ncontrol flow\n");
9392         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9393         find_cf_blocks(cf, state->first_block);
9394
9395         for(i = 1; i <= state->last_vertex; i++) {
9396                 struct block *block;
9397                 block = cf[i].block;
9398                 if (!block)
9399                         continue;
9400                 printf("(%p) %d:", block, block->vertex);
9401                 if (block->left) {
9402                         printf(" %d", block->left->vertex);
9403                 }
9404                 if (block->right && (block->right != block->left)) {
9405                         printf(" %d", block->right->vertex);
9406                 }
9407                 printf("\n");
9408         }
9409
9410         xfree(cf);
9411 }
9412
9413
9414 static struct block *basic_block(struct compile_state *state,
9415         struct triple *first)
9416 {
9417         struct block *block;
9418         struct triple *ptr;
9419         int op;
9420         if (first->op != OP_LABEL) {
9421                 internal_error(state, 0, "block does not start with a label");
9422         }
9423         /* See if this basic block has already been setup */
9424         if (first->u.block != 0) {
9425                 return first->u.block;
9426         }
9427         /* Allocate another basic block structure */
9428         state->last_vertex += 1;
9429         block = xcmalloc(sizeof(*block), "block");
9430         block->first = block->last = first;
9431         block->vertex = state->last_vertex;
9432         ptr = first;
9433         do {
9434                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9435                         break;
9436                 }
9437                 block->last = ptr;
9438                 /* If ptr->u is not used remember where the baic block is */
9439                 if (triple_stores_block(state, ptr)) {
9440                         ptr->u.block = block;
9441                 }
9442                 if (ptr->op == OP_BRANCH) {
9443                         break;
9444                 }
9445                 ptr = ptr->next;
9446         } while (ptr != RHS(state->main_function, 0));
9447         if (ptr == RHS(state->main_function, 0))
9448                 return block;
9449         op = ptr->op;
9450         if (op == OP_LABEL) {
9451                 block->left = basic_block(state, ptr);
9452                 block->right = 0;
9453                 use_block(block->left, block);
9454         }
9455         else if (op == OP_BRANCH) {
9456                 block->left = 0;
9457                 /* Trace the branch target */
9458                 block->right = basic_block(state, TARG(ptr, 0));
9459                 use_block(block->right, block);
9460                 /* If there is a test trace the branch as well */
9461                 if (TRIPLE_RHS(ptr->sizes)) {
9462                         block->left = basic_block(state, ptr->next);
9463                         use_block(block->left, block);
9464                 }
9465         }
9466         else {
9467                 internal_error(state, 0, "Bad basic block split");
9468         }
9469         return block;
9470 }
9471
9472
9473 static void walk_blocks(struct compile_state *state,
9474         void (*cb)(struct compile_state *state, struct block *block, void *arg),
9475         void *arg)
9476 {
9477         struct triple *ptr, *first;
9478         struct block *last_block;
9479         last_block = 0;
9480         first = RHS(state->main_function, 0);
9481         ptr = first;
9482         do {
9483                 struct block *block;
9484                 if (ptr->op == OP_LABEL) {
9485                         block = ptr->u.block;
9486                         if (block && (block != last_block)) {
9487                                 cb(state, block, arg);
9488                         }
9489                         last_block = block;
9490                 }
9491                 ptr = ptr->next;
9492         } while(ptr != first);
9493 }
9494
9495 static void print_block(
9496         struct compile_state *state, struct block *block, void *arg)
9497 {
9498         struct triple *ptr;
9499         FILE *fp = arg;
9500
9501         fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n", 
9502                 block, 
9503                 block->vertex,
9504                 block->left, 
9505                 block->left && block->left->use?block->left->use->member : 0,
9506                 block->right, 
9507                 block->right && block->right->use?block->right->use->member : 0);
9508         if (block->first->op == OP_LABEL) {
9509                 fprintf(fp, "%p:\n", block->first);
9510         }
9511         for(ptr = block->first; ; ptr = ptr->next) {
9512                 struct triple_set *user;
9513                 int op = ptr->op;
9514                 
9515                 if (triple_stores_block(state, ptr)) {
9516                         if (ptr->u.block != block) {
9517                                 internal_error(state, ptr, 
9518                                         "Wrong block pointer: %p\n",
9519                                         ptr->u.block);
9520                         }
9521                 }
9522                 if (op == OP_ADECL) {
9523                         for(user = ptr->use; user; user = user->next) {
9524                                 if (!user->member->u.block) {
9525                                         internal_error(state, user->member, 
9526                                                 "Use %p not in a block?\n",
9527                                                 user->member);
9528                                 }
9529                         }
9530                 }
9531                 display_triple(fp, ptr);
9532
9533 #if 0
9534                 for(user = ptr->use; user; user = user->next) {
9535                         fprintf(fp, "use: %p\n", user->member);
9536                 }
9537 #endif
9538
9539                 /* Sanity checks... */
9540                 valid_ins(state, ptr);
9541                 for(user = ptr->use; user; user = user->next) {
9542                         struct triple *use;
9543                         use = user->member;
9544                         valid_ins(state, use);
9545                         if (triple_stores_block(state, user->member) &&
9546                                 !user->member->u.block) {
9547                                 internal_error(state, user->member,
9548                                         "Use %p not in a block?",
9549                                         user->member);
9550                         }
9551                 }
9552
9553                 if (ptr == block->last)
9554                         break;
9555         }
9556         fprintf(fp,"\n");
9557 }
9558
9559
9560 static void print_blocks(struct compile_state *state, FILE *fp)
9561 {
9562         fprintf(fp, "--------------- blocks ---------------\n");
9563         walk_blocks(state, print_block, fp);
9564 }
9565
9566 static void prune_nonblock_triples(struct compile_state *state)
9567 {
9568         struct block *block;
9569         struct triple *first, *ins, *next;
9570         /* Delete the triples not in a basic block */
9571         first = RHS(state->main_function, 0);
9572         block = 0;
9573         ins = first;
9574         do {
9575                 next = ins->next;
9576                 if (ins->op == OP_LABEL) {
9577                         block = ins->u.block;
9578                 }
9579                 if (!block) {
9580                         release_triple(state, ins);
9581                 }
9582                 ins = next;
9583         } while(ins != first);
9584 }
9585
9586 static void setup_basic_blocks(struct compile_state *state)
9587 {
9588         if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9589                 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9590                 internal_error(state, 0, "ins will not store block?");
9591         }
9592         /* Find the basic blocks */
9593         state->last_vertex = 0;
9594         state->first_block = basic_block(state, RHS(state->main_function,0));
9595         /* Delete the triples not in a basic block */
9596         prune_nonblock_triples(state);
9597         /* Find the last basic block */
9598         state->last_block = RHS(state->main_function, 0)->prev->u.block;
9599         if (!state->last_block) {
9600                 internal_error(state, 0, "end not used?");
9601         }
9602         /* Insert an extra unused edge from start to the end 
9603          * This helps with reverse control flow calculations.
9604          */
9605         use_block(state->first_block, state->last_block);
9606         /* If we are debugging print what I have just done */
9607         if (state->debug & DEBUG_BASIC_BLOCKS) {
9608                 print_blocks(state, stdout);
9609                 print_control_flow(state);
9610         }
9611 }
9612
9613 static void free_basic_block(struct compile_state *state, struct block *block)
9614 {
9615         struct block_set *entry, *next;
9616         struct block *child;
9617         if (!block) {
9618                 return;
9619         }
9620         if (block->vertex == -1) {
9621                 return;
9622         }
9623         block->vertex = -1;
9624         if (block->left) {
9625                 unuse_block(block->left, block);
9626         }
9627         if (block->right) {
9628                 unuse_block(block->right, block);
9629         }
9630         if (block->idom) {
9631                 unidom_block(block->idom, block);
9632         }
9633         block->idom = 0;
9634         if (block->ipdom) {
9635                 unipdom_block(block->ipdom, block);
9636         }
9637         block->ipdom = 0;
9638         for(entry = block->use; entry; entry = next) {
9639                 next = entry->next;
9640                 child = entry->member;
9641                 unuse_block(block, child);
9642                 if (child->left == block) {
9643                         child->left = 0;
9644                 }
9645                 if (child->right == block) {
9646                         child->right = 0;
9647                 }
9648         }
9649         for(entry = block->idominates; entry; entry = next) {
9650                 next = entry->next;
9651                 child = entry->member;
9652                 unidom_block(block, child);
9653                 child->idom = 0;
9654         }
9655         for(entry = block->domfrontier; entry; entry = next) {
9656                 next = entry->next;
9657                 child = entry->member;
9658                 undomf_block(block, child);
9659         }
9660         for(entry = block->ipdominates; entry; entry = next) {
9661                 next = entry->next;
9662                 child = entry->member;
9663                 unipdom_block(block, child);
9664                 child->ipdom = 0;
9665         }
9666         for(entry = block->ipdomfrontier; entry; entry = next) {
9667                 next = entry->next;
9668                 child = entry->member;
9669                 unipdomf_block(block, child);
9670         }
9671         if (block->users != 0) {
9672                 internal_error(state, 0, "block still has users");
9673         }
9674         free_basic_block(state, block->left);
9675         block->left = 0;
9676         free_basic_block(state, block->right);
9677         block->right = 0;
9678         memset(block, -1, sizeof(*block));
9679         xfree(block);
9680 }
9681
9682 static void free_basic_blocks(struct compile_state *state)
9683 {
9684         struct triple *first, *ins;
9685         free_basic_block(state, state->first_block);
9686         state->last_vertex = 0;
9687         state->first_block = state->last_block = 0;
9688         first = RHS(state->main_function, 0);
9689         ins = first;
9690         do {
9691                 if (triple_stores_block(state, ins)) {
9692                         ins->u.block = 0;
9693                 }
9694                 ins = ins->next;
9695         } while(ins != first);
9696         
9697 }
9698
9699 struct sdom_block {
9700         struct block *block;
9701         struct sdom_block *sdominates;
9702         struct sdom_block *sdom_next;
9703         struct sdom_block *sdom;
9704         struct sdom_block *label;
9705         struct sdom_block *parent;
9706         struct sdom_block *ancestor;
9707         int vertex;
9708 };
9709
9710
9711 static void unsdom_block(struct sdom_block *block)
9712 {
9713         struct sdom_block **ptr;
9714         if (!block->sdom_next) {
9715                 return;
9716         }
9717         ptr = &block->sdom->sdominates;
9718         while(*ptr) {
9719                 if ((*ptr) == block) {
9720                         *ptr = block->sdom_next;
9721                         return;
9722                 }
9723                 ptr = &(*ptr)->sdom_next;
9724         }
9725 }
9726
9727 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9728 {
9729         unsdom_block(block);
9730         block->sdom = sdom;
9731         block->sdom_next = sdom->sdominates;
9732         sdom->sdominates = block;
9733 }
9734
9735
9736
9737 static int initialize_sdblock(struct sdom_block *sd,
9738         struct block *parent, struct block *block, int vertex)
9739 {
9740         if (!block || (sd[block->vertex].block == block)) {
9741                 return vertex;
9742         }
9743         vertex += 1;
9744         /* Renumber the blocks in a convinient fashion */
9745         block->vertex = vertex;
9746         sd[vertex].block    = block;
9747         sd[vertex].sdom     = &sd[vertex];
9748         sd[vertex].label    = &sd[vertex];
9749         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9750         sd[vertex].ancestor = 0;
9751         sd[vertex].vertex   = vertex;
9752         vertex = initialize_sdblock(sd, block, block->left, vertex);
9753         vertex = initialize_sdblock(sd, block, block->right, vertex);
9754         return vertex;
9755 }
9756
9757 static int initialize_sdpblock(struct sdom_block *sd,
9758         struct block *parent, struct block *block, int vertex)
9759 {
9760         struct block_set *user;
9761         if (!block || (sd[block->vertex].block == block)) {
9762                 return vertex;
9763         }
9764         vertex += 1;
9765         /* Renumber the blocks in a convinient fashion */
9766         block->vertex = vertex;
9767         sd[vertex].block    = block;
9768         sd[vertex].sdom     = &sd[vertex];
9769         sd[vertex].label    = &sd[vertex];
9770         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9771         sd[vertex].ancestor = 0;
9772         sd[vertex].vertex   = vertex;
9773         for(user = block->use; user; user = user->next) {
9774                 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9775         }
9776         return vertex;
9777 }
9778
9779 static void compress_ancestors(struct sdom_block *v)
9780 {
9781         /* This procedure assumes ancestor(v) != 0 */
9782         /* if (ancestor(ancestor(v)) != 0) {
9783          *      compress(ancestor(ancestor(v)));
9784          *      if (semi(label(ancestor(v))) < semi(label(v))) {
9785          *              label(v) = label(ancestor(v));
9786          *      }
9787          *      ancestor(v) = ancestor(ancestor(v));
9788          * }
9789          */
9790         if (!v->ancestor) {
9791                 return;
9792         }
9793         if (v->ancestor->ancestor) {
9794                 compress_ancestors(v->ancestor->ancestor);
9795                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9796                         v->label = v->ancestor->label;
9797                 }
9798                 v->ancestor = v->ancestor->ancestor;
9799         }
9800 }
9801
9802 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9803 {
9804         int i;
9805         /* // step 2 
9806          *  for each v <= pred(w) {
9807          *      u = EVAL(v);
9808          *      if (semi[u] < semi[w] { 
9809          *              semi[w] = semi[u]; 
9810          *      } 
9811          * }
9812          * add w to bucket(vertex(semi[w]));
9813          * LINK(parent(w), w);
9814          *
9815          * // step 3
9816          * for each v <= bucket(parent(w)) {
9817          *      delete v from bucket(parent(w));
9818          *      u = EVAL(v);
9819          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9820          * }
9821          */
9822         for(i = state->last_vertex; i >= 2; i--) {
9823                 struct sdom_block *v, *parent, *next;
9824                 struct block_set *user;
9825                 struct block *block;
9826                 block = sd[i].block;
9827                 parent = sd[i].parent;
9828                 /* Step 2 */
9829                 for(user = block->use; user; user = user->next) {
9830                         struct sdom_block *v, *u;
9831                         v = &sd[user->member->vertex];
9832                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9833                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9834                                 sd[i].sdom = u->sdom;
9835                         }
9836                 }
9837                 sdom_block(sd[i].sdom, &sd[i]);
9838                 sd[i].ancestor = parent;
9839                 /* Step 3 */
9840                 for(v = parent->sdominates; v; v = next) {
9841                         struct sdom_block *u;
9842                         next = v->sdom_next;
9843                         unsdom_block(v);
9844                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9845                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
9846                                 u->block : parent->block;
9847                 }
9848         }
9849 }
9850
9851 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9852 {
9853         int i;
9854         /* // step 2 
9855          *  for each v <= pred(w) {
9856          *      u = EVAL(v);
9857          *      if (semi[u] < semi[w] { 
9858          *              semi[w] = semi[u]; 
9859          *      } 
9860          * }
9861          * add w to bucket(vertex(semi[w]));
9862          * LINK(parent(w), w);
9863          *
9864          * // step 3
9865          * for each v <= bucket(parent(w)) {
9866          *      delete v from bucket(parent(w));
9867          *      u = EVAL(v);
9868          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9869          * }
9870          */
9871         for(i = state->last_vertex; i >= 2; i--) {
9872                 struct sdom_block *u, *v, *parent, *next;
9873                 struct block *block;
9874                 block = sd[i].block;
9875                 parent = sd[i].parent;
9876                 /* Step 2 */
9877                 if (block->left) {
9878                         v = &sd[block->left->vertex];
9879                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9880                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9881                                 sd[i].sdom = u->sdom;
9882                         }
9883                 }
9884                 if (block->right && (block->right != block->left)) {
9885                         v = &sd[block->right->vertex];
9886                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9887                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9888                                 sd[i].sdom = u->sdom;
9889                         }
9890                 }
9891                 sdom_block(sd[i].sdom, &sd[i]);
9892                 sd[i].ancestor = parent;
9893                 /* Step 3 */
9894                 for(v = parent->sdominates; v; v = next) {
9895                         struct sdom_block *u;
9896                         next = v->sdom_next;
9897                         unsdom_block(v);
9898                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9899                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
9900                                 u->block : parent->block;
9901                 }
9902         }
9903 }
9904
9905 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9906 {
9907         int i;
9908         for(i = 2; i <= state->last_vertex; i++) {
9909                 struct block *block;
9910                 block = sd[i].block;
9911                 if (block->idom->vertex != sd[i].sdom->vertex) {
9912                         block->idom = block->idom->idom;
9913                 }
9914                 idom_block(block->idom, block);
9915         }
9916         sd[1].block->idom = 0;
9917 }
9918
9919 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9920 {
9921         int i;
9922         for(i = 2; i <= state->last_vertex; i++) {
9923                 struct block *block;
9924                 block = sd[i].block;
9925                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9926                         block->ipdom = block->ipdom->ipdom;
9927                 }
9928                 ipdom_block(block->ipdom, block);
9929         }
9930         sd[1].block->ipdom = 0;
9931 }
9932
9933         /* Theorem 1:
9934          *   Every vertex of a flowgraph G = (V, E, r) except r has
9935          *   a unique immediate dominator.  
9936          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9937          *   rooted at r, called the dominator tree of G, such that 
9938          *   v dominates w if and only if v is a proper ancestor of w in
9939          *   the dominator tree.
9940          */
9941         /* Lemma 1:  
9942          *   If v and w are vertices of G such that v <= w,
9943          *   than any path from v to w must contain a common ancestor
9944          *   of v and w in T.
9945          */
9946         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
9947         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
9948         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
9949         /* Theorem 2:
9950          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
9951          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
9952          */
9953         /* Theorem 3:
9954          *   Let w != r and let u be a vertex for which sdom(u) is 
9955          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9956          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9957          */
9958         /* Lemma 5:  Let vertices v,w satisfy v -> w.
9959          *           Then v -> idom(w) or idom(w) -> idom(v)
9960          */
9961
9962 static void find_immediate_dominators(struct compile_state *state)
9963 {
9964         struct sdom_block *sd;
9965         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9966          *           vi > w for (1 <= i <= k - 1}
9967          */
9968         /* Theorem 4:
9969          *   For any vertex w != r.
9970          *   sdom(w) = min(
9971          *                 {v|(v,w) <= E  and v < w } U 
9972          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9973          */
9974         /* Corollary 1:
9975          *   Let w != r and let u be a vertex for which sdom(u) is 
9976          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9977          *   Then:
9978          *                   { sdom(w) if sdom(w) = sdom(u),
9979          *        idom(w) = {
9980          *                   { idom(u) otherwise
9981          */
9982         /* The algorithm consists of the following 4 steps.
9983          * Step 1.  Carry out a depth-first search of the problem graph.  
9984          *    Number the vertices from 1 to N as they are reached during
9985          *    the search.  Initialize the variables used in succeeding steps.
9986          * Step 2.  Compute the semidominators of all vertices by applying
9987          *    theorem 4.   Carry out the computation vertex by vertex in
9988          *    decreasing order by number.
9989          * Step 3.  Implicitly define the immediate dominator of each vertex
9990          *    by applying Corollary 1.
9991          * Step 4.  Explicitly define the immediate dominator of each vertex,
9992          *    carrying out the computation vertex by vertex in increasing order
9993          *    by number.
9994          */
9995         /* Step 1 initialize the basic block information */
9996         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9997         initialize_sdblock(sd, 0, state->first_block, 0);
9998 #if 0
9999         sd[1].size  = 0;
10000         sd[1].label = 0;
10001         sd[1].sdom  = 0;
10002 #endif
10003         /* Step 2 compute the semidominators */
10004         /* Step 3 implicitly define the immediate dominator of each vertex */
10005         compute_sdom(state, sd);
10006         /* Step 4 explicitly define the immediate dominator of each vertex */
10007         compute_idom(state, sd);
10008         xfree(sd);
10009 }
10010
10011 static void find_post_dominators(struct compile_state *state)
10012 {
10013         struct sdom_block *sd;
10014         /* Step 1 initialize the basic block information */
10015         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10016
10017         initialize_sdpblock(sd, 0, state->last_block, 0);
10018
10019         /* Step 2 compute the semidominators */
10020         /* Step 3 implicitly define the immediate dominator of each vertex */
10021         compute_spdom(state, sd);
10022         /* Step 4 explicitly define the immediate dominator of each vertex */
10023         compute_ipdom(state, sd);
10024         xfree(sd);
10025 }
10026
10027
10028
10029 static void find_block_domf(struct compile_state *state, struct block *block)
10030 {
10031         struct block *child;
10032         struct block_set *user;
10033         if (block->domfrontier != 0) {
10034                 internal_error(state, block->first, "domfrontier present?");
10035         }
10036         for(user = block->idominates; user; user = user->next) {
10037                 child = user->member;
10038                 if (child->idom != block) {
10039                         internal_error(state, block->first, "bad idom");
10040                 }
10041                 find_block_domf(state, child);
10042         }
10043         if (block->left && block->left->idom != block) {
10044                 domf_block(block, block->left);
10045         }
10046         if (block->right && block->right->idom != block) {
10047                 domf_block(block, block->right);
10048         }
10049         for(user = block->idominates; user; user = user->next) {
10050                 struct block_set *frontier;
10051                 child = user->member;
10052                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10053                         if (frontier->member->idom != block) {
10054                                 domf_block(block, frontier->member);
10055                         }
10056                 }
10057         }
10058 }
10059
10060 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10061 {
10062         struct block *child;
10063         struct block_set *user;
10064         if (block->ipdomfrontier != 0) {
10065                 internal_error(state, block->first, "ipdomfrontier present?");
10066         }
10067         for(user = block->ipdominates; user; user = user->next) {
10068                 child = user->member;
10069                 if (child->ipdom != block) {
10070                         internal_error(state, block->first, "bad ipdom");
10071                 }
10072                 find_block_ipdomf(state, child);
10073         }
10074         if (block->left && block->left->ipdom != block) {
10075                 ipdomf_block(block, block->left);
10076         }
10077         if (block->right && block->right->ipdom != block) {
10078                 ipdomf_block(block, block->right);
10079         }
10080         for(user = block->idominates; user; user = user->next) {
10081                 struct block_set *frontier;
10082                 child = user->member;
10083                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10084                         if (frontier->member->ipdom != block) {
10085                                 ipdomf_block(block, frontier->member);
10086                         }
10087                 }
10088         }
10089 }
10090
10091 static void print_dominated(
10092         struct compile_state *state, struct block *block, void *arg)
10093 {
10094         struct block_set *user;
10095         FILE *fp = arg;
10096
10097         fprintf(fp, "%d:", block->vertex);
10098         for(user = block->idominates; user; user = user->next) {
10099                 fprintf(fp, " %d", user->member->vertex);
10100                 if (user->member->idom != block) {
10101                         internal_error(state, user->member->first, "bad idom");
10102                 }
10103         }
10104         fprintf(fp,"\n");
10105 }
10106
10107 static void print_dominators(struct compile_state *state, FILE *fp)
10108 {
10109         fprintf(fp, "\ndominates\n");
10110         walk_blocks(state, print_dominated, fp);
10111 }
10112
10113
10114 static int print_frontiers(
10115         struct compile_state *state, struct block *block, int vertex)
10116 {
10117         struct block_set *user;
10118
10119         if (!block || (block->vertex != vertex + 1)) {
10120                 return vertex;
10121         }
10122         vertex += 1;
10123
10124         printf("%d:", block->vertex);
10125         for(user = block->domfrontier; user; user = user->next) {
10126                 printf(" %d", user->member->vertex);
10127         }
10128         printf("\n");
10129
10130         vertex = print_frontiers(state, block->left, vertex);
10131         vertex = print_frontiers(state, block->right, vertex);
10132         return vertex;
10133 }
10134 static void print_dominance_frontiers(struct compile_state *state)
10135 {
10136         printf("\ndominance frontiers\n");
10137         print_frontiers(state, state->first_block, 0);
10138         
10139 }
10140
10141 static void analyze_idominators(struct compile_state *state)
10142 {
10143         /* Find the immediate dominators */
10144         find_immediate_dominators(state);
10145         /* Find the dominance frontiers */
10146         find_block_domf(state, state->first_block);
10147         /* If debuging print the print what I have just found */
10148         if (state->debug & DEBUG_FDOMINATORS) {
10149                 print_dominators(state, stdout);
10150                 print_dominance_frontiers(state);
10151                 print_control_flow(state);
10152         }
10153 }
10154
10155
10156
10157 static void print_ipdominated(
10158         struct compile_state *state, struct block *block, void *arg)
10159 {
10160         struct block_set *user;
10161         FILE *fp = arg;
10162
10163         fprintf(fp, "%d:", block->vertex);
10164         for(user = block->ipdominates; user; user = user->next) {
10165                 fprintf(fp, " %d", user->member->vertex);
10166                 if (user->member->ipdom != block) {
10167                         internal_error(state, user->member->first, "bad ipdom");
10168                 }
10169         }
10170         fprintf(fp, "\n");
10171 }
10172
10173 static void print_ipdominators(struct compile_state *state, FILE *fp)
10174 {
10175         fprintf(fp, "\nipdominates\n");
10176         walk_blocks(state, print_ipdominated, fp);
10177 }
10178
10179 static int print_pfrontiers(
10180         struct compile_state *state, struct block *block, int vertex)
10181 {
10182         struct block_set *user;
10183
10184         if (!block || (block->vertex != vertex + 1)) {
10185                 return vertex;
10186         }
10187         vertex += 1;
10188
10189         printf("%d:", block->vertex);
10190         for(user = block->ipdomfrontier; user; user = user->next) {
10191                 printf(" %d", user->member->vertex);
10192         }
10193         printf("\n");
10194         for(user = block->use; user; user = user->next) {
10195                 vertex = print_pfrontiers(state, user->member, vertex);
10196         }
10197         return vertex;
10198 }
10199 static void print_ipdominance_frontiers(struct compile_state *state)
10200 {
10201         printf("\nipdominance frontiers\n");
10202         print_pfrontiers(state, state->last_block, 0);
10203         
10204 }
10205
10206 static void analyze_ipdominators(struct compile_state *state)
10207 {
10208         /* Find the post dominators */
10209         find_post_dominators(state);
10210         /* Find the control dependencies (post dominance frontiers) */
10211         find_block_ipdomf(state, state->last_block);
10212         /* If debuging print the print what I have just found */
10213         if (state->debug & DEBUG_RDOMINATORS) {
10214                 print_ipdominators(state, stdout);
10215                 print_ipdominance_frontiers(state);
10216                 print_control_flow(state);
10217         }
10218 }
10219
10220 static int bdominates(struct compile_state *state,
10221         struct block *dom, struct block *sub)
10222 {
10223         while(sub && (sub != dom)) {
10224                 sub = sub->idom;
10225         }
10226         return sub == dom;
10227 }
10228
10229 static int tdominates(struct compile_state *state,
10230         struct triple *dom, struct triple *sub)
10231 {
10232         struct block *bdom, *bsub;
10233         int result;
10234         bdom = block_of_triple(state, dom);
10235         bsub = block_of_triple(state, sub);
10236         if (bdom != bsub) {
10237                 result = bdominates(state, bdom, bsub);
10238         } 
10239         else {
10240                 struct triple *ins;
10241                 ins = sub;
10242                 while((ins != bsub->first) && (ins != dom)) {
10243                         ins = ins->prev;
10244                 }
10245                 result = (ins == dom);
10246         }
10247         return result;
10248 }
10249
10250 static void insert_phi_operations(struct compile_state *state)
10251 {
10252         size_t size;
10253         struct triple *first;
10254         int *has_already, *work;
10255         struct block *work_list, **work_list_tail;
10256         int iter;
10257         struct triple *var;
10258
10259         size = sizeof(int) * (state->last_vertex + 1);
10260         has_already = xcmalloc(size, "has_already");
10261         work =        xcmalloc(size, "work");
10262         iter = 0;
10263
10264         first = RHS(state->main_function, 0);
10265         for(var = first->next; var != first ; var = var->next) {
10266                 struct block *block;
10267                 struct triple_set *user;
10268                 if ((var->op != OP_ADECL) || !var->use) {
10269                         continue;
10270                 }
10271                 iter += 1;
10272                 work_list = 0;
10273                 work_list_tail = &work_list;
10274                 for(user = var->use; user; user = user->next) {
10275                         if (user->member->op == OP_READ) {
10276                                 continue;
10277                         }
10278                         if (user->member->op != OP_WRITE) {
10279                                 internal_error(state, user->member, 
10280                                         "bad variable access");
10281                         }
10282                         block = user->member->u.block;
10283                         if (!block) {
10284                                 warning(state, user->member, "dead code");
10285                         }
10286                         if (work[block->vertex] >= iter) {
10287                                 continue;
10288                         }
10289                         work[block->vertex] = iter;
10290                         *work_list_tail = block;
10291                         block->work_next = 0;
10292                         work_list_tail = &block->work_next;
10293                 }
10294                 for(block = work_list; block; block = block->work_next) {
10295                         struct block_set *df;
10296                         for(df = block->domfrontier; df; df = df->next) {
10297                                 struct triple *phi;
10298                                 struct block *front;
10299                                 int in_edges;
10300                                 front = df->member;
10301
10302                                 if (has_already[front->vertex] >= iter) {
10303                                         continue;
10304                                 }
10305                                 /* Count how many edges flow into this block */
10306                                 in_edges = front->users;
10307                                 /* Insert a phi function for this variable */
10308                                 get_occurance(front->first->occurance);
10309                                 phi = alloc_triple(
10310                                         state, OP_PHI, var->type, -1, in_edges, 
10311                                         front->first->occurance);
10312                                 phi->u.block = front;
10313                                 MISC(phi, 0) = var;
10314                                 use_triple(var, phi);
10315                                 /* Insert the phi functions immediately after the label */
10316                                 insert_triple(state, front->first->next, phi);
10317                                 if (front->first == front->last) {
10318                                         front->last = front->first->next;
10319                                 }
10320                                 has_already[front->vertex] = iter;
10321
10322                                 /* If necessary plan to visit the basic block */
10323                                 if (work[front->vertex] >= iter) {
10324                                         continue;
10325                                 }
10326                                 work[front->vertex] = iter;
10327                                 *work_list_tail = front;
10328                                 front->work_next = 0;
10329                                 work_list_tail = &front->work_next;
10330                         }
10331                 }
10332         }
10333         xfree(has_already);
10334         xfree(work);
10335 }
10336
10337 /*
10338  * C(V)
10339  * S(V)
10340  */
10341 static void fixup_block_phi_variables(
10342         struct compile_state *state, struct block *parent, struct block *block)
10343 {
10344         struct block_set *set;
10345         struct triple *ptr;
10346         int edge;
10347         if (!parent || !block)
10348                 return;
10349         /* Find the edge I am coming in on */
10350         edge = 0;
10351         for(set = block->use; set; set = set->next, edge++) {
10352                 if (set->member == parent) {
10353                         break;
10354                 }
10355         }
10356         if (!set) {
10357                 internal_error(state, 0, "phi input is not on a control predecessor");
10358         }
10359         for(ptr = block->first; ; ptr = ptr->next) {
10360                 if (ptr->op == OP_PHI) {
10361                         struct triple *var, *val, **slot;
10362                         var = MISC(ptr, 0);
10363                         if (!var) {
10364                                 internal_error(state, ptr, "no var???");
10365                         }
10366                         /* Find the current value of the variable */
10367                         val = var->use->member;
10368                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10369                                 internal_error(state, val, "bad value in phi");
10370                         }
10371                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
10372                                 internal_error(state, ptr, "edges > phi rhs");
10373                         }
10374                         slot = &RHS(ptr, edge);
10375                         if ((*slot != 0) && (*slot != val)) {
10376                                 internal_error(state, ptr, "phi already bound on this edge");
10377                         }
10378                         *slot = val;
10379                         use_triple(val, ptr);
10380                 }
10381                 if (ptr == block->last) {
10382                         break;
10383                 }
10384         }
10385 }
10386
10387
10388 static void rename_block_variables(
10389         struct compile_state *state, struct block *block)
10390 {
10391         struct block_set *user;
10392         struct triple *ptr, *next, *last;
10393         int done;
10394         if (!block)
10395                 return;
10396         last = block->first;
10397         done = 0;
10398         for(ptr = block->first; !done; ptr = next) {
10399                 next = ptr->next;
10400                 if (ptr == block->last) {
10401                         done = 1;
10402                 }
10403                 /* RHS(A) */
10404                 if (ptr->op == OP_READ) {
10405                         struct triple *var, *val;
10406                         var = RHS(ptr, 0);
10407                         unuse_triple(var, ptr);
10408                         if (!var->use) {
10409                                 error(state, ptr, "variable used without being set");
10410                         }
10411                         /* Find the current value of the variable */
10412                         val = var->use->member;
10413                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10414                                 internal_error(state, val, "bad value in read");
10415                         }
10416                         propogate_use(state, ptr, val);
10417                         release_triple(state, ptr);
10418                         continue;
10419                 }
10420                 /* LHS(A) */
10421                 if (ptr->op == OP_WRITE) {
10422                         struct triple *var, *val;
10423                         var = LHS(ptr, 0);
10424                         val = RHS(ptr, 0);
10425                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10426                                 internal_error(state, val, "bad value in write");
10427                         }
10428                         propogate_use(state, ptr, val);
10429                         unuse_triple(var, ptr);
10430                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
10431                         push_triple(var, val);
10432                 }
10433                 if (ptr->op == OP_PHI) {
10434                         struct triple *var;
10435                         var = MISC(ptr, 0);
10436                         /* Push OP_PHI onto a stack of variable uses */
10437                         push_triple(var, ptr);
10438                 }
10439                 last = ptr;
10440         }
10441         block->last = last;
10442
10443         /* Fixup PHI functions in the cf successors */
10444         fixup_block_phi_variables(state, block, block->left);
10445         fixup_block_phi_variables(state, block, block->right);
10446         /* rename variables in the dominated nodes */
10447         for(user = block->idominates; user; user = user->next) {
10448                 rename_block_variables(state, user->member);
10449         }
10450         /* pop the renamed variable stack */
10451         last = block->first;
10452         done = 0;
10453         for(ptr = block->first; !done ; ptr = next) {
10454                 next = ptr->next;
10455                 if (ptr == block->last) {
10456                         done = 1;
10457                 }
10458                 if (ptr->op == OP_WRITE) {
10459                         struct triple *var;
10460                         var = LHS(ptr, 0);
10461                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10462                         pop_triple(var, RHS(ptr, 0));
10463                         release_triple(state, ptr);
10464                         continue;
10465                 }
10466                 if (ptr->op == OP_PHI) {
10467                         struct triple *var;
10468                         var = MISC(ptr, 0);
10469                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10470                         pop_triple(var, ptr);
10471                 }
10472                 last = ptr;
10473         }
10474         block->last = last;
10475 }
10476
10477 static void prune_block_variables(struct compile_state *state,
10478         struct block *block)
10479 {
10480         struct block_set *user;
10481         struct triple *next, *last, *ptr;
10482         int done;
10483         last = block->first;
10484         done = 0;
10485         for(ptr = block->first; !done; ptr = next) {
10486                 next = ptr->next;
10487                 if (ptr == block->last) {
10488                         done = 1;
10489                 }
10490                 if (ptr->op == OP_ADECL) {
10491                         struct triple_set *user, *next;
10492                         for(user = ptr->use; user; user = next) {
10493                                 struct triple *use;
10494                                 next = user->next;
10495                                 use = user->member;
10496                                 if (use->op != OP_PHI) {
10497                                         internal_error(state, use, "decl still used");
10498                                 }
10499                                 if (MISC(use, 0) != ptr) {
10500                                         internal_error(state, use, "bad phi use of decl");
10501                                 }
10502                                 unuse_triple(ptr, use);
10503                                 MISC(use, 0) = 0;
10504                         }
10505                         release_triple(state, ptr);
10506                         continue;
10507                 }
10508                 last = ptr;
10509         }
10510         block->last = last;
10511         for(user = block->idominates; user; user = user->next) {
10512                 prune_block_variables(state, user->member);
10513         }
10514 }
10515
10516 static void transform_to_ssa_form(struct compile_state *state)
10517 {
10518         insert_phi_operations(state);
10519 #if 0
10520         printf("@%s:%d\n", __FILE__, __LINE__);
10521         print_blocks(state, stdout);
10522 #endif
10523         rename_block_variables(state, state->first_block);
10524         prune_block_variables(state, state->first_block);
10525 }
10526
10527
10528 static void clear_vertex(
10529         struct compile_state *state, struct block *block, void *arg)
10530 {
10531         block->vertex = 0;
10532 }
10533
10534 static void mark_live_block(
10535         struct compile_state *state, struct block *block, int *next_vertex)
10536 {
10537         /* See if this is a block that has not been marked */
10538         if (block->vertex != 0) {
10539                 return;
10540         }
10541         block->vertex = *next_vertex;
10542         *next_vertex += 1;
10543         if (triple_is_branch(state, block->last)) {
10544                 struct triple **targ;
10545                 targ = triple_targ(state, block->last, 0);
10546                 for(; targ; targ = triple_targ(state, block->last, targ)) {
10547                         if (!*targ) {
10548                                 continue;
10549                         }
10550                         if (!triple_stores_block(state, *targ)) {
10551                                 internal_error(state, 0, "bad targ");
10552                         }
10553                         mark_live_block(state, (*targ)->u.block, next_vertex);
10554                 }
10555         }
10556         else if (block->last->next != RHS(state->main_function, 0)) {
10557                 struct triple *ins;
10558                 ins = block->last->next;
10559                 if (!triple_stores_block(state, ins)) {
10560                         internal_error(state, 0, "bad block start");
10561                 }
10562                 mark_live_block(state, ins->u.block, next_vertex);
10563         }
10564 }
10565
10566 static void transform_from_ssa_form(struct compile_state *state)
10567 {
10568         /* To get out of ssa form we insert moves on the incoming
10569          * edges to blocks containting phi functions.
10570          */
10571         struct triple *first;
10572         struct triple *phi, *next;
10573         int next_vertex;
10574
10575         /* Walk the control flow to see which blocks remain alive */
10576         walk_blocks(state, clear_vertex, 0);
10577         next_vertex = 1;
10578         mark_live_block(state, state->first_block, &next_vertex);
10579
10580         /* Walk all of the operations to find the phi functions */
10581         first = RHS(state->main_function, 0);
10582         for(phi = first->next; phi != first ; phi = next) {
10583                 struct block_set *set;
10584                 struct block *block;
10585                 struct triple **slot;
10586                 struct triple *var, *read;
10587                 struct triple_set *use, *use_next;
10588                 int edge, used;
10589                 next = phi->next;
10590                 if (phi->op != OP_PHI) {
10591                         continue;
10592                 }
10593                 block = phi->u.block;
10594                 slot  = &RHS(phi, 0);
10595
10596                 /* Forget uses from code in dead blocks */
10597                 for(use = phi->use; use; use = use_next) {
10598                         struct block *ublock;
10599                         struct triple **expr;
10600                         use_next = use->next;
10601                         ublock = block_of_triple(state, use->member);
10602                         if ((use->member == phi) || (ublock->vertex != 0)) {
10603                                 continue;
10604                         }
10605                         expr = triple_rhs(state, use->member, 0);
10606                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
10607                                 if (*expr == phi) {
10608                                         *expr = 0;
10609                                 }
10610                         }
10611                         unuse_triple(phi, use->member);
10612                 }
10613
10614                 /* A variable to replace the phi function */
10615                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10616                 /* A read of the single value that is set into the variable */
10617                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10618                 use_triple(var, read);
10619
10620                 /* Replaces uses of the phi with variable reads */
10621                 propogate_use(state, phi, read);
10622
10623                 /* Walk all of the incoming edges/blocks and insert moves.
10624                  */
10625                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10626                         struct block *eblock;
10627                         struct triple *move;
10628                         struct triple *val;
10629                         eblock = set->member;
10630                         val = slot[edge];
10631                         slot[edge] = 0;
10632                         unuse_triple(val, phi);
10633
10634                         if (!val || (val == &zero_triple) ||
10635                                 (block->vertex == 0) || (eblock->vertex == 0) ||
10636                                 (val == phi) || (val == read)) {
10637                                 continue;
10638                         }
10639                         
10640                         move = post_triple(state, 
10641                                 val, OP_WRITE, phi->type, var, val);
10642                         use_triple(val, move);
10643                         use_triple(var, move);
10644                 }               
10645                 /* See if there are any writers of var */
10646                 used = 0;
10647                 for(use = var->use; use; use = use->next) {
10648                         struct triple **expr;
10649                         expr = triple_lhs(state, use->member, 0);
10650                         for(; expr; expr = triple_lhs(state, use->member, expr)) {
10651                                 if (*expr == var) {
10652                                         used = 1;
10653                                 }
10654                         }
10655                 }
10656                 /* If var is not used free it */
10657                 if (!used) {
10658                         unuse_triple(var, read);
10659                         free_triple(state, read);
10660                         free_triple(state, var);
10661                 }
10662
10663                 /* Release the phi function */
10664                 release_triple(state, phi);
10665         }
10666         
10667 }
10668
10669
10670 /* 
10671  * Register conflict resolution
10672  * =========================================================
10673  */
10674
10675 static struct reg_info find_def_color(
10676         struct compile_state *state, struct triple *def)
10677 {
10678         struct triple_set *set;
10679         struct reg_info info;
10680         info.reg = REG_UNSET;
10681         info.regcm = 0;
10682         if (!triple_is_def(state, def)) {
10683                 return info;
10684         }
10685         info = arch_reg_lhs(state, def, 0);
10686         if (info.reg >= MAX_REGISTERS) {
10687                 info.reg = REG_UNSET;
10688         }
10689         for(set = def->use; set; set = set->next) {
10690                 struct reg_info tinfo;
10691                 int i;
10692                 i = find_rhs_use(state, set->member, def);
10693                 if (i < 0) {
10694                         continue;
10695                 }
10696                 tinfo = arch_reg_rhs(state, set->member, i);
10697                 if (tinfo.reg >= MAX_REGISTERS) {
10698                         tinfo.reg = REG_UNSET;
10699                 }
10700                 if ((tinfo.reg != REG_UNSET) && 
10701                         (info.reg != REG_UNSET) &&
10702                         (tinfo.reg != info.reg)) {
10703                         internal_error(state, def, "register conflict");
10704                 }
10705                 if ((info.regcm & tinfo.regcm) == 0) {
10706                         internal_error(state, def, "regcm conflict %x & %x == 0",
10707                                 info.regcm, tinfo.regcm);
10708                 }
10709                 if (info.reg == REG_UNSET) {
10710                         info.reg = tinfo.reg;
10711                 }
10712                 info.regcm &= tinfo.regcm;
10713         }
10714         if (info.reg >= MAX_REGISTERS) {
10715                 internal_error(state, def, "register out of range");
10716         }
10717         return info;
10718 }
10719
10720 static struct reg_info find_lhs_pre_color(
10721         struct compile_state *state, struct triple *ins, int index)
10722 {
10723         struct reg_info info;
10724         int zlhs, zrhs, i;
10725         zrhs = TRIPLE_RHS(ins->sizes);
10726         zlhs = TRIPLE_LHS(ins->sizes);
10727         if (!zlhs && triple_is_def(state, ins)) {
10728                 zlhs = 1;
10729         }
10730         if (index >= zlhs) {
10731                 internal_error(state, ins, "Bad lhs %d", index);
10732         }
10733         info = arch_reg_lhs(state, ins, index);
10734         for(i = 0; i < zrhs; i++) {
10735                 struct reg_info rinfo;
10736                 rinfo = arch_reg_rhs(state, ins, i);
10737                 if ((info.reg == rinfo.reg) &&
10738                         (rinfo.reg >= MAX_REGISTERS)) {
10739                         struct reg_info tinfo;
10740                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10741                         info.reg = tinfo.reg;
10742                         info.regcm &= tinfo.regcm;
10743                         break;
10744                 }
10745         }
10746         if (info.reg >= MAX_REGISTERS) {
10747                 info.reg = REG_UNSET;
10748         }
10749         return info;
10750 }
10751
10752 static struct reg_info find_rhs_post_color(
10753         struct compile_state *state, struct triple *ins, int index);
10754
10755 static struct reg_info find_lhs_post_color(
10756         struct compile_state *state, struct triple *ins, int index)
10757 {
10758         struct triple_set *set;
10759         struct reg_info info;
10760         struct triple *lhs;
10761 #if 0
10762         fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10763                 ins, index);
10764 #endif
10765         if ((index == 0) && triple_is_def(state, ins)) {
10766                 lhs = ins;
10767         }
10768         else if (index < TRIPLE_LHS(ins->sizes)) {
10769                 lhs = LHS(ins, index);
10770         }
10771         else {
10772                 internal_error(state, ins, "Bad lhs %d", index);
10773                 lhs = 0;
10774         }
10775         info = arch_reg_lhs(state, ins, index);
10776         if (info.reg >= MAX_REGISTERS) {
10777                 info.reg = REG_UNSET;
10778         }
10779         for(set = lhs->use; set; set = set->next) {
10780                 struct reg_info rinfo;
10781                 struct triple *user;
10782                 int zrhs, i;
10783                 user = set->member;
10784                 zrhs = TRIPLE_RHS(user->sizes);
10785                 for(i = 0; i < zrhs; i++) {
10786                         if (RHS(user, i) != lhs) {
10787                                 continue;
10788                         }
10789                         rinfo = find_rhs_post_color(state, user, i);
10790                         if ((info.reg != REG_UNSET) &&
10791                                 (rinfo.reg != REG_UNSET) &&
10792                                 (info.reg != rinfo.reg)) {
10793                                 internal_error(state, ins, "register conflict");
10794                         }
10795                         if ((info.regcm & rinfo.regcm) == 0) {
10796                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
10797                                         info.regcm, rinfo.regcm);
10798                         }
10799                         if (info.reg == REG_UNSET) {
10800                                 info.reg = rinfo.reg;
10801                         }
10802                         info.regcm &= rinfo.regcm;
10803                 }
10804         }
10805 #if 0
10806         fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10807                 ins, index, info.reg, info.regcm);
10808 #endif
10809         return info;
10810 }
10811
10812 static struct reg_info find_rhs_post_color(
10813         struct compile_state *state, struct triple *ins, int index)
10814 {
10815         struct reg_info info, rinfo;
10816         int zlhs, i;
10817 #if 0
10818         fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10819                 ins, index);
10820 #endif
10821         rinfo = arch_reg_rhs(state, ins, index);
10822         zlhs = TRIPLE_LHS(ins->sizes);
10823         if (!zlhs && triple_is_def(state, ins)) {
10824                 zlhs = 1;
10825         }
10826         info = rinfo;
10827         if (info.reg >= MAX_REGISTERS) {
10828                 info.reg = REG_UNSET;
10829         }
10830         for(i = 0; i < zlhs; i++) {
10831                 struct reg_info linfo;
10832                 linfo = arch_reg_lhs(state, ins, i);
10833                 if ((linfo.reg == rinfo.reg) &&
10834                         (linfo.reg >= MAX_REGISTERS)) {
10835                         struct reg_info tinfo;
10836                         tinfo = find_lhs_post_color(state, ins, i);
10837                         if (tinfo.reg >= MAX_REGISTERS) {
10838                                 tinfo.reg = REG_UNSET;
10839                         }
10840                         info.regcm &= linfo.reg;
10841                         info.regcm &= tinfo.regcm;
10842                         if (info.reg != REG_UNSET) {
10843                                 internal_error(state, ins, "register conflict");
10844                         }
10845                         if (info.regcm == 0) {
10846                                 internal_error(state, ins, "regcm conflict");
10847                         }
10848                         info.reg = tinfo.reg;
10849                 }
10850         }
10851 #if 0
10852         fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10853                 ins, index, info.reg, info.regcm);
10854 #endif
10855         return info;
10856 }
10857
10858 static struct reg_info find_lhs_color(
10859         struct compile_state *state, struct triple *ins, int index)
10860 {
10861         struct reg_info pre, post, info;
10862 #if 0
10863         fprintf(stderr, "find_lhs_color(%p, %d)\n",
10864                 ins, index);
10865 #endif
10866         pre = find_lhs_pre_color(state, ins, index);
10867         post = find_lhs_post_color(state, ins, index);
10868         if ((pre.reg != post.reg) &&
10869                 (pre.reg != REG_UNSET) &&
10870                 (post.reg != REG_UNSET)) {
10871                 internal_error(state, ins, "register conflict");
10872         }
10873         info.regcm = pre.regcm & post.regcm;
10874         info.reg = pre.reg;
10875         if (info.reg == REG_UNSET) {
10876                 info.reg = post.reg;
10877         }
10878 #if 0
10879         fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10880                 ins, index, info.reg, info.regcm);
10881 #endif
10882         return info;
10883 }
10884
10885 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10886 {
10887         struct triple_set *entry, *next;
10888         struct triple *out;
10889         struct reg_info info, rinfo;
10890
10891         info = arch_reg_lhs(state, ins, 0);
10892         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10893         use_triple(RHS(out, 0), out);
10894         /* Get the users of ins to use out instead */
10895         for(entry = ins->use; entry; entry = next) {
10896                 int i;
10897                 next = entry->next;
10898                 if (entry->member == out) {
10899                         continue;
10900                 }
10901                 i = find_rhs_use(state, entry->member, ins);
10902                 if (i < 0) {
10903                         continue;
10904                 }
10905                 rinfo = arch_reg_rhs(state, entry->member, i);
10906                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10907                         continue;
10908                 }
10909                 replace_rhs_use(state, ins, out, entry->member);
10910         }
10911         transform_to_arch_instruction(state, out);
10912         return out;
10913 }
10914
10915 static struct triple *pre_copy(
10916         struct compile_state *state, struct triple *ins, int index)
10917 {
10918         /* Carefully insert enough operations so that I can
10919          * enter any operation with a GPR32.
10920          */
10921         struct triple *in;
10922         struct triple **expr;
10923         if (ins->op == OP_PHI) {
10924                 internal_error(state, ins, "pre_copy on a phi?");
10925         }
10926         expr = &RHS(ins, index);
10927         in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10928         unuse_triple(*expr, ins);
10929         *expr = in;
10930         use_triple(RHS(in, 0), in);
10931         use_triple(in, ins);
10932         transform_to_arch_instruction(state, in);
10933         return in;
10934 }
10935
10936
10937 static void insert_copies_to_phi(struct compile_state *state)
10938 {
10939         /* To get out of ssa form we insert moves on the incoming
10940          * edges to blocks containting phi functions.
10941          */
10942         struct triple *first;
10943         struct triple *phi;
10944
10945         /* Walk all of the operations to find the phi functions */
10946         first = RHS(state->main_function, 0);
10947         for(phi = first->next; phi != first ; phi = phi->next) {
10948                 struct block_set *set;
10949                 struct block *block;
10950                 struct triple **slot;
10951                 int edge;
10952                 if (phi->op != OP_PHI) {
10953                         continue;
10954                 }
10955                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10956                 block = phi->u.block;
10957                 slot  = &RHS(phi, 0);
10958                 /* Walk all of the incoming edges/blocks and insert moves.
10959                  */
10960                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10961                         struct block *eblock;
10962                         struct triple *move;
10963                         struct triple *val;
10964                         struct triple *ptr;
10965                         eblock = set->member;
10966                         val = slot[edge];
10967
10968                         if (val == phi) {
10969                                 continue;
10970                         }
10971
10972                         get_occurance(val->occurance);
10973                         move = build_triple(state, OP_COPY, phi->type, val, 0,
10974                                 val->occurance);
10975                         move->u.block = eblock;
10976                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
10977                         use_triple(val, move);
10978                         
10979                         slot[edge] = move;
10980                         unuse_triple(val, phi);
10981                         use_triple(move, phi);
10982
10983                         /* Walk through the block backwards to find
10984                          * an appropriate location for the OP_COPY.
10985                          */
10986                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10987                                 struct triple **expr;
10988                                 if ((ptr == phi) || (ptr == val)) {
10989                                         goto out;
10990                                 }
10991                                 expr = triple_rhs(state, ptr, 0);
10992                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10993                                         if ((*expr) == phi) {
10994                                                 goto out;
10995                                         }
10996                                 }
10997                         }
10998                 out:
10999                         if (triple_is_branch(state, ptr)) {
11000                                 internal_error(state, ptr,
11001                                         "Could not insert write to phi");
11002                         }
11003                         insert_triple(state, ptr->next, move);
11004                         if (eblock->last == ptr) {
11005                                 eblock->last = move;
11006                         }
11007                         transform_to_arch_instruction(state, move);
11008                 }
11009         }
11010 }
11011
11012 struct triple_reg_set {
11013         struct triple_reg_set *next;
11014         struct triple *member;
11015         struct triple *new;
11016 };
11017
11018 struct reg_block {
11019         struct block *block;
11020         struct triple_reg_set *in;
11021         struct triple_reg_set *out;
11022         int vertex;
11023 };
11024
11025 static int do_triple_set(struct triple_reg_set **head, 
11026         struct triple *member, struct triple *new_member)
11027 {
11028         struct triple_reg_set **ptr, *new;
11029         if (!member)
11030                 return 0;
11031         ptr = head;
11032         while(*ptr) {
11033                 if ((*ptr)->member == member) {
11034                         return 0;
11035                 }
11036                 ptr = &(*ptr)->next;
11037         }
11038         new = xcmalloc(sizeof(*new), "triple_set");
11039         new->member = member;
11040         new->new    = new_member;
11041         new->next   = *head;
11042         *head       = new;
11043         return 1;
11044 }
11045
11046 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11047 {
11048         struct triple_reg_set *entry, **ptr;
11049         ptr = head;
11050         while(*ptr) {
11051                 entry = *ptr;
11052                 if (entry->member == member) {
11053                         *ptr = entry->next;
11054                         xfree(entry);
11055                         return;
11056                 }
11057                 else {
11058                         ptr = &entry->next;
11059                 }
11060         }
11061 }
11062
11063 static int in_triple(struct reg_block *rb, struct triple *in)
11064 {
11065         return do_triple_set(&rb->in, in, 0);
11066 }
11067 static void unin_triple(struct reg_block *rb, struct triple *unin)
11068 {
11069         do_triple_unset(&rb->in, unin);
11070 }
11071
11072 static int out_triple(struct reg_block *rb, struct triple *out)
11073 {
11074         return do_triple_set(&rb->out, out, 0);
11075 }
11076 static void unout_triple(struct reg_block *rb, struct triple *unout)
11077 {
11078         do_triple_unset(&rb->out, unout);
11079 }
11080
11081 static int initialize_regblock(struct reg_block *blocks,
11082         struct block *block, int vertex)
11083 {
11084         struct block_set *user;
11085         if (!block || (blocks[block->vertex].block == block)) {
11086                 return vertex;
11087         }
11088         vertex += 1;
11089         /* Renumber the blocks in a convinient fashion */
11090         block->vertex = vertex;
11091         blocks[vertex].block    = block;
11092         blocks[vertex].vertex   = vertex;
11093         for(user = block->use; user; user = user->next) {
11094                 vertex = initialize_regblock(blocks, user->member, vertex);
11095         }
11096         return vertex;
11097 }
11098
11099 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11100         struct reg_block *rb, struct block *suc)
11101 {
11102         /* Read the conditional input set of a successor block
11103          * (i.e. the input to the phi nodes) and place it in the
11104          * current blocks output set.
11105          */
11106         struct block_set *set;
11107         struct triple *ptr;
11108         int edge;
11109         int done, change;
11110         change = 0;
11111         /* Find the edge I am coming in on */
11112         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11113                 if (set->member == rb->block) {
11114                         break;
11115                 }
11116         }
11117         if (!set) {
11118                 internal_error(state, 0, "Not coming on a control edge?");
11119         }
11120         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11121                 struct triple **slot, *expr, *ptr2;
11122                 int out_change, done2;
11123                 done = (ptr == suc->last);
11124                 if (ptr->op != OP_PHI) {
11125                         continue;
11126                 }
11127                 slot = &RHS(ptr, 0);
11128                 expr = slot[edge];
11129                 out_change = out_triple(rb, expr);
11130                 if (!out_change) {
11131                         continue;
11132                 }
11133                 /* If we don't define the variable also plast it
11134                  * in the current blocks input set.
11135                  */
11136                 ptr2 = rb->block->first;
11137                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11138                         if (ptr2 == expr) {
11139                                 break;
11140                         }
11141                         done2 = (ptr2 == rb->block->last);
11142                 }
11143                 if (!done2) {
11144                         continue;
11145                 }
11146                 change |= in_triple(rb, expr);
11147         }
11148         return change;
11149 }
11150
11151 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11152         struct reg_block *rb, struct block *suc)
11153 {
11154         struct triple_reg_set *in_set;
11155         int change;
11156         change = 0;
11157         /* Read the input set of a successor block
11158          * and place it in the current blocks output set.
11159          */
11160         in_set = blocks[suc->vertex].in;
11161         for(; in_set; in_set = in_set->next) {
11162                 int out_change, done;
11163                 struct triple *first, *last, *ptr;
11164                 out_change = out_triple(rb, in_set->member);
11165                 if (!out_change) {
11166                         continue;
11167                 }
11168                 /* If we don't define the variable also place it
11169                  * in the current blocks input set.
11170                  */
11171                 first = rb->block->first;
11172                 last = rb->block->last;
11173                 done = 0;
11174                 for(ptr = first; !done; ptr = ptr->next) {
11175                         if (ptr == in_set->member) {
11176                                 break;
11177                         }
11178                         done = (ptr == last);
11179                 }
11180                 if (!done) {
11181                         continue;
11182                 }
11183                 change |= in_triple(rb, in_set->member);
11184         }
11185         change |= phi_in(state, blocks, rb, suc);
11186         return change;
11187 }
11188
11189
11190 static int use_in(struct compile_state *state, struct reg_block *rb)
11191 {
11192         /* Find the variables we use but don't define and add
11193          * it to the current blocks input set.
11194          */
11195 #warning "FIXME is this O(N^2) algorithm bad?"
11196         struct block *block;
11197         struct triple *ptr;
11198         int done;
11199         int change;
11200         block = rb->block;
11201         change = 0;
11202         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11203                 struct triple **expr;
11204                 done = (ptr == block->first);
11205                 /* The variable a phi function uses depends on the
11206                  * control flow, and is handled in phi_in, not
11207                  * here.
11208                  */
11209                 if (ptr->op == OP_PHI) {
11210                         continue;
11211                 }
11212                 expr = triple_rhs(state, ptr, 0);
11213                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11214                         struct triple *rhs, *test;
11215                         int tdone;
11216                         rhs = *expr;
11217                         if (!rhs) {
11218                                 continue;
11219                         }
11220                         /* See if rhs is defined in this block */
11221                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11222                                 tdone = (test == block->first);
11223                                 if (test == rhs) {
11224                                         rhs = 0;
11225                                         break;
11226                                 }
11227                         }
11228                         /* If I still have a valid rhs add it to in */
11229                         change |= in_triple(rb, rhs);
11230                 }
11231         }
11232         return change;
11233 }
11234
11235 static struct reg_block *compute_variable_lifetimes(
11236         struct compile_state *state)
11237 {
11238         struct reg_block *blocks;
11239         int change;
11240         blocks = xcmalloc(
11241                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11242         initialize_regblock(blocks, state->last_block, 0);
11243         do {
11244                 int i;
11245                 change = 0;
11246                 for(i = 1; i <= state->last_vertex; i++) {
11247                         struct reg_block *rb;
11248                         rb = &blocks[i];
11249                         /* Add the left successor's input set to in */
11250                         if (rb->block->left) {
11251                                 change |= reg_in(state, blocks, rb, rb->block->left);
11252                         }
11253                         /* Add the right successor's input set to in */
11254                         if ((rb->block->right) && 
11255                                 (rb->block->right != rb->block->left)) {
11256                                 change |= reg_in(state, blocks, rb, rb->block->right);
11257                         }
11258                         /* Add use to in... */
11259                         change |= use_in(state, rb);
11260                 }
11261         } while(change);
11262         return blocks;
11263 }
11264
11265 static void free_variable_lifetimes(
11266         struct compile_state *state, struct reg_block *blocks)
11267 {
11268         int i;
11269         /* free in_set && out_set on each block */
11270         for(i = 1; i <= state->last_vertex; i++) {
11271                 struct triple_reg_set *entry, *next;
11272                 struct reg_block *rb;
11273                 rb = &blocks[i];
11274                 for(entry = rb->in; entry ; entry = next) {
11275                         next = entry->next;
11276                         do_triple_unset(&rb->in, entry->member);
11277                 }
11278                 for(entry = rb->out; entry; entry = next) {
11279                         next = entry->next;
11280                         do_triple_unset(&rb->out, entry->member);
11281                 }
11282         }
11283         xfree(blocks);
11284
11285 }
11286
11287 typedef void (*wvl_cb_t)(
11288         struct compile_state *state, 
11289         struct reg_block *blocks, struct triple_reg_set *live, 
11290         struct reg_block *rb, struct triple *ins, void *arg);
11291
11292 static void walk_variable_lifetimes(struct compile_state *state,
11293         struct reg_block *blocks, wvl_cb_t cb, void *arg)
11294 {
11295         int i;
11296         
11297         for(i = 1; i <= state->last_vertex; i++) {
11298                 struct triple_reg_set *live;
11299                 struct triple_reg_set *entry, *next;
11300                 struct triple *ptr, *prev;
11301                 struct reg_block *rb;
11302                 struct block *block;
11303                 int done;
11304
11305                 /* Get the blocks */
11306                 rb = &blocks[i];
11307                 block = rb->block;
11308
11309                 /* Copy out into live */
11310                 live = 0;
11311                 for(entry = rb->out; entry; entry = next) {
11312                         next = entry->next;
11313                         do_triple_set(&live, entry->member, entry->new);
11314                 }
11315                 /* Walk through the basic block calculating live */
11316                 for(done = 0, ptr = block->last; !done; ptr = prev) {
11317                         struct triple **expr;
11318
11319                         prev = ptr->prev;
11320                         done = (ptr == block->first);
11321
11322                         /* Ensure the current definition is in live */
11323                         if (triple_is_def(state, ptr)) {
11324                                 do_triple_set(&live, ptr, 0);
11325                         }
11326
11327                         /* Inform the callback function of what is
11328                          * going on.
11329                          */
11330                          cb(state, blocks, live, rb, ptr, arg);
11331                         
11332                         /* Remove the current definition from live */
11333                         do_triple_unset(&live, ptr);
11334
11335                         /* Add the current uses to live.
11336                          *
11337                          * It is safe to skip phi functions because they do
11338                          * not have any block local uses, and the block
11339                          * output sets already properly account for what
11340                          * control flow depedent uses phi functions do have.
11341                          */
11342                         if (ptr->op == OP_PHI) {
11343                                 continue;
11344                         }
11345                         expr = triple_rhs(state, ptr, 0);
11346                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
11347                                 /* If the triple is not a definition skip it. */
11348                                 if (!*expr || !triple_is_def(state, *expr)) {
11349                                         continue;
11350                                 }
11351                                 do_triple_set(&live, *expr, 0);
11352                         }
11353                 }
11354                 /* Free live */
11355                 for(entry = live; entry; entry = next) {
11356                         next = entry->next;
11357                         do_triple_unset(&live, entry->member);
11358                 }
11359         }
11360 }
11361
11362 static int count_triples(struct compile_state *state)
11363 {
11364         struct triple *first, *ins;
11365         int triples = 0;
11366         first = RHS(state->main_function, 0);
11367         ins = first;
11368         do {
11369                 triples++;
11370                 ins = ins->next;
11371         } while (ins != first);
11372         return triples;
11373 }
11374 struct dead_triple {
11375         struct triple *triple;
11376         struct dead_triple *work_next;
11377         struct block *block;
11378         int color;
11379         int flags;
11380 #define TRIPLE_FLAG_ALIVE 1
11381 };
11382
11383
11384 static void awaken(
11385         struct compile_state *state,
11386         struct dead_triple *dtriple, struct triple **expr,
11387         struct dead_triple ***work_list_tail)
11388 {
11389         struct triple *triple;
11390         struct dead_triple *dt;
11391         if (!expr) {
11392                 return;
11393         }
11394         triple = *expr;
11395         if (!triple) {
11396                 return;
11397         }
11398         if (triple->id <= 0)  {
11399                 internal_error(state, triple, "bad triple id: %d",
11400                         triple->id);
11401         }
11402         if (triple->op == OP_NOOP) {
11403                 internal_warning(state, triple, "awakening noop?");
11404                 return;
11405         }
11406         dt = &dtriple[triple->id];
11407         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11408                 dt->flags |= TRIPLE_FLAG_ALIVE;
11409                 if (!dt->work_next) {
11410                         **work_list_tail = dt;
11411                         *work_list_tail = &dt->work_next;
11412                 }
11413         }
11414 }
11415
11416 static void eliminate_inefectual_code(struct compile_state *state)
11417 {
11418         struct block *block;
11419         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11420         int triples, i;
11421         struct triple *first, *ins;
11422
11423         /* Setup the work list */
11424         work_list = 0;
11425         work_list_tail = &work_list;
11426
11427         first = RHS(state->main_function, 0);
11428
11429         /* Count how many triples I have */
11430         triples = count_triples(state);
11431
11432         /* Now put then in an array and mark all of the triples dead */
11433         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11434         
11435         ins = first;
11436         i = 1;
11437         block = 0;
11438         do {
11439                 if (ins->op == OP_LABEL) {
11440                         block = ins->u.block;
11441                 }
11442                 dtriple[i].triple = ins;
11443                 dtriple[i].block  = block;
11444                 dtriple[i].flags  = 0;
11445                 dtriple[i].color  = ins->id;
11446                 ins->id = i;
11447                 /* See if it is an operation we always keep */
11448 #warning "FIXME handle the case of killing a branch instruction"
11449                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11450                         awaken(state, dtriple, &ins, &work_list_tail);
11451                 }
11452                 i++;
11453                 ins = ins->next;
11454         } while(ins != first);
11455         while(work_list) {
11456                 struct dead_triple *dt;
11457                 struct block_set *user;
11458                 struct triple **expr;
11459                 dt = work_list;
11460                 work_list = dt->work_next;
11461                 if (!work_list) {
11462                         work_list_tail = &work_list;
11463                 }
11464                 /* Wake up the data depencencies of this triple */
11465                 expr = 0;
11466                 do {
11467                         expr = triple_rhs(state, dt->triple, expr);
11468                         awaken(state, dtriple, expr, &work_list_tail);
11469                 } while(expr);
11470                 do {
11471                         expr = triple_lhs(state, dt->triple, expr);
11472                         awaken(state, dtriple, expr, &work_list_tail);
11473                 } while(expr);
11474                 do {
11475                         expr = triple_misc(state, dt->triple, expr);
11476                         awaken(state, dtriple, expr, &work_list_tail);
11477                 } while(expr);
11478                 /* Wake up the forward control dependencies */
11479                 do {
11480                         expr = triple_targ(state, dt->triple, expr);
11481                         awaken(state, dtriple, expr, &work_list_tail);
11482                 } while(expr);
11483                 /* Wake up the reverse control dependencies of this triple */
11484                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11485                         awaken(state, dtriple, &user->member->last, &work_list_tail);
11486                 }
11487         }
11488         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11489                 if ((dt->triple->op == OP_NOOP) && 
11490                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
11491                         internal_error(state, dt->triple, "noop effective?");
11492                 }
11493                 dt->triple->id = dt->color;     /* Restore the color */
11494                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11495 #warning "FIXME handle the case of killing a basic block"
11496                         if (dt->block->first == dt->triple) {
11497                                 continue;
11498                         }
11499                         if (dt->block->last == dt->triple) {
11500                                 dt->block->last = dt->triple->prev;
11501                         }
11502                         release_triple(state, dt->triple);
11503                 }
11504         }
11505         xfree(dtriple);
11506 }
11507
11508
11509 static void insert_mandatory_copies(struct compile_state *state)
11510 {
11511         struct triple *ins, *first;
11512
11513         /* The object is with a minimum of inserted copies,
11514          * to resolve in fundamental register conflicts between
11515          * register value producers and consumers.
11516          * Theoretically we may be greater than minimal when we
11517          * are inserting copies before instructions but that
11518          * case should be rare.
11519          */
11520         first = RHS(state->main_function, 0);
11521         ins = first;
11522         do {
11523                 struct triple_set *entry, *next;
11524                 struct triple *tmp;
11525                 struct reg_info info;
11526                 unsigned reg, regcm;
11527                 int do_post_copy, do_pre_copy;
11528                 tmp = 0;
11529                 if (!triple_is_def(state, ins)) {
11530                         goto next;
11531                 }
11532                 /* Find the architecture specific color information */
11533                 info = arch_reg_lhs(state, ins, 0);
11534                 if (info.reg >= MAX_REGISTERS) {
11535                         info.reg = REG_UNSET;
11536                 }
11537                 
11538                 reg = REG_UNSET;
11539                 regcm = arch_type_to_regcm(state, ins->type);
11540                 do_post_copy = do_pre_copy = 0;
11541
11542                 /* Walk through the uses of ins and check for conflicts */
11543                 for(entry = ins->use; entry; entry = next) {
11544                         struct reg_info rinfo;
11545                         int i;
11546                         next = entry->next;
11547                         i = find_rhs_use(state, entry->member, ins);
11548                         if (i < 0) {
11549                                 continue;
11550                         }
11551                         
11552                         /* Find the users color requirements */
11553                         rinfo = arch_reg_rhs(state, entry->member, i);
11554                         if (rinfo.reg >= MAX_REGISTERS) {
11555                                 rinfo.reg = REG_UNSET;
11556                         }
11557                         
11558                         /* See if I need a pre_copy */
11559                         if (rinfo.reg != REG_UNSET) {
11560                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11561                                         do_pre_copy = 1;
11562                                 }
11563                                 reg = rinfo.reg;
11564                         }
11565                         regcm &= rinfo.regcm;
11566                         regcm = arch_regcm_normalize(state, regcm);
11567                         if (regcm == 0) {
11568                                 do_pre_copy = 1;
11569                         }
11570                 }
11571                 do_post_copy =
11572                         !do_pre_copy &&
11573                         (((info.reg != REG_UNSET) && 
11574                                 (reg != REG_UNSET) &&
11575                                 (info.reg != reg)) ||
11576                         ((info.regcm & regcm) == 0));
11577
11578                 reg = info.reg;
11579                 regcm = info.regcm;
11580                 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11581                 for(entry = ins->use; entry; entry = next) {
11582                         struct reg_info rinfo;
11583                         int i;
11584                         next = entry->next;
11585                         i = find_rhs_use(state, entry->member, ins);
11586                         if (i < 0) {
11587                                 continue;
11588                         }
11589                         
11590                         /* Find the users color requirements */
11591                         rinfo = arch_reg_rhs(state, entry->member, i);
11592                         if (rinfo.reg >= MAX_REGISTERS) {
11593                                 rinfo.reg = REG_UNSET;
11594                         }
11595
11596                         /* Now see if it is time to do the pre_copy */
11597                         if (rinfo.reg != REG_UNSET) {
11598                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11599                                         ((regcm & rinfo.regcm) == 0) ||
11600                                         /* Don't let a mandatory coalesce sneak
11601                                          * into a operation that is marked to prevent
11602                                          * coalescing.
11603                                          */
11604                                         ((reg != REG_UNNEEDED) &&
11605                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11606                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11607                                         ) {
11608                                         if (do_pre_copy) {
11609                                                 struct triple *user;
11610                                                 user = entry->member;
11611                                                 if (RHS(user, i) != ins) {
11612                                                         internal_error(state, user, "bad rhs");
11613                                                 }
11614                                                 tmp = pre_copy(state, user, i);
11615                                                 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11616                                                 continue;
11617                                         } else {
11618                                                 do_post_copy = 1;
11619                                         }
11620                                 }
11621                                 reg = rinfo.reg;
11622                         }
11623                         if ((regcm & rinfo.regcm) == 0) {
11624                                 if (do_pre_copy) {
11625                                         struct triple *user;
11626                                         user = entry->member;
11627                                         if (RHS(user, i) != ins) {
11628                                                 internal_error(state, user, "bad rhs");
11629                                         }
11630                                         tmp = pre_copy(state, user, i);
11631                                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11632                                         continue;
11633                                 } else {
11634                                         do_post_copy = 1;
11635                                 }
11636                         }
11637                         regcm &= rinfo.regcm;
11638                         
11639                 }
11640                 if (do_post_copy) {
11641                         struct reg_info pre, post;
11642                         tmp = post_copy(state, ins);
11643                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11644                         pre = arch_reg_lhs(state, ins, 0);
11645                         post = arch_reg_lhs(state, tmp, 0);
11646                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11647                                 internal_error(state, tmp, "useless copy");
11648                         }
11649                 }
11650         next:
11651                 ins = ins->next;
11652         } while(ins != first);
11653 }
11654
11655
11656 struct live_range_edge;
11657 struct live_range_def;
11658 struct live_range {
11659         struct live_range_edge *edges;
11660         struct live_range_def *defs;
11661 /* Note. The list pointed to by defs is kept in order.
11662  * That is baring splits in the flow control
11663  * defs dominates defs->next wich dominates defs->next->next
11664  * etc.
11665  */
11666         unsigned color;
11667         unsigned classes;
11668         unsigned degree;
11669         unsigned length;
11670         struct live_range *group_next, **group_prev;
11671 };
11672
11673 struct live_range_edge {
11674         struct live_range_edge *next;
11675         struct live_range *node;
11676 };
11677
11678 struct live_range_def {
11679         struct live_range_def *next;
11680         struct live_range_def *prev;
11681         struct live_range *lr;
11682         struct triple *def;
11683         unsigned orig_id;
11684 };
11685
11686 #define LRE_HASH_SIZE 2048
11687 struct lre_hash {
11688         struct lre_hash *next;
11689         struct live_range *left;
11690         struct live_range *right;
11691 };
11692
11693
11694 struct reg_state {
11695         struct lre_hash *hash[LRE_HASH_SIZE];
11696         struct reg_block *blocks;
11697         struct live_range_def *lrd;
11698         struct live_range *lr;
11699         struct live_range *low, **low_tail;
11700         struct live_range *high, **high_tail;
11701         unsigned defs;
11702         unsigned ranges;
11703         int passes, max_passes;
11704 #define MAX_ALLOCATION_PASSES 100
11705 };
11706
11707
11708 static unsigned regc_max_size(struct compile_state *state, int classes)
11709 {
11710         unsigned max_size;
11711         int i;
11712         max_size = 0;
11713         for(i = 0; i < MAX_REGC; i++) {
11714                 if (classes & (1 << i)) {
11715                         unsigned size;
11716                         size = arch_regc_size(state, i);
11717                         if (size > max_size) {
11718                                 max_size = size;
11719                         }
11720                 }
11721         }
11722         return max_size;
11723 }
11724
11725 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11726 {
11727         unsigned equivs[MAX_REG_EQUIVS];
11728         int i;
11729         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11730                 internal_error(state, 0, "invalid register");
11731         }
11732         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11733                 internal_error(state, 0, "invalid register");
11734         }
11735         arch_reg_equivs(state, equivs, reg1);
11736         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11737                 if (equivs[i] == reg2) {
11738                         return 1;
11739                 }
11740         }
11741         return 0;
11742 }
11743
11744 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11745 {
11746         unsigned equivs[MAX_REG_EQUIVS];
11747         int i;
11748         if (reg == REG_UNNEEDED) {
11749                 return;
11750         }
11751         arch_reg_equivs(state, equivs, reg);
11752         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11753                 used[equivs[i]] = 1;
11754         }
11755         return;
11756 }
11757
11758 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11759 {
11760         unsigned equivs[MAX_REG_EQUIVS];
11761         int i;
11762         if (reg == REG_UNNEEDED) {
11763                 return;
11764         }
11765         arch_reg_equivs(state, equivs, reg);
11766         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11767                 used[equivs[i]] += 1;
11768         }
11769         return;
11770 }
11771
11772 static unsigned int hash_live_edge(
11773         struct live_range *left, struct live_range *right)
11774 {
11775         unsigned int hash, val;
11776         unsigned long lval, rval;
11777         lval = ((unsigned long)left)/sizeof(struct live_range);
11778         rval = ((unsigned long)right)/sizeof(struct live_range);
11779         hash = 0;
11780         while(lval) {
11781                 val = lval & 0xff;
11782                 lval >>= 8;
11783                 hash = (hash *263) + val;
11784         }
11785         while(rval) {
11786                 val = rval & 0xff;
11787                 rval >>= 8;
11788                 hash = (hash *263) + val;
11789         }
11790         hash = hash & (LRE_HASH_SIZE - 1);
11791         return hash;
11792 }
11793
11794 static struct lre_hash **lre_probe(struct reg_state *rstate,
11795         struct live_range *left, struct live_range *right)
11796 {
11797         struct lre_hash **ptr;
11798         unsigned int index;
11799         /* Ensure left <= right */
11800         if (left > right) {
11801                 struct live_range *tmp;
11802                 tmp = left;
11803                 left = right;
11804                 right = tmp;
11805         }
11806         index = hash_live_edge(left, right);
11807         
11808         ptr = &rstate->hash[index];
11809         while(*ptr) {
11810                 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
11811                         break;
11812                 }
11813                 ptr = &(*ptr)->next;
11814         }
11815         return ptr;
11816 }
11817
11818 static int interfere(struct reg_state *rstate,
11819         struct live_range *left, struct live_range *right)
11820 {
11821         struct lre_hash **ptr;
11822         ptr = lre_probe(rstate, left, right);
11823         return ptr && *ptr;
11824 }
11825
11826 static void add_live_edge(struct reg_state *rstate, 
11827         struct live_range *left, struct live_range *right)
11828 {
11829         /* FIXME the memory allocation overhead is noticeable here... */
11830         struct lre_hash **ptr, *new_hash;
11831         struct live_range_edge *edge;
11832
11833         if (left == right) {
11834                 return;
11835         }
11836         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11837                 return;
11838         }
11839         /* Ensure left <= right */
11840         if (left > right) {
11841                 struct live_range *tmp;
11842                 tmp = left;
11843                 left = right;
11844                 right = tmp;
11845         }
11846         ptr = lre_probe(rstate, left, right);
11847         if (*ptr) {
11848                 return;
11849         }
11850 #if 0
11851         fprintf(stderr, "new_live_edge(%p, %p)\n",
11852                 left, right);
11853 #endif
11854         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11855         new_hash->next  = *ptr;
11856         new_hash->left  = left;
11857         new_hash->right = right;
11858         *ptr = new_hash;
11859
11860         edge = xmalloc(sizeof(*edge), "live_range_edge");
11861         edge->next   = left->edges;
11862         edge->node   = right;
11863         left->edges  = edge;
11864         left->degree += 1;
11865         
11866         edge = xmalloc(sizeof(*edge), "live_range_edge");
11867         edge->next    = right->edges;
11868         edge->node    = left;
11869         right->edges  = edge;
11870         right->degree += 1;
11871 }
11872
11873 static void remove_live_edge(struct reg_state *rstate,
11874         struct live_range *left, struct live_range *right)
11875 {
11876         struct live_range_edge *edge, **ptr;
11877         struct lre_hash **hptr, *entry;
11878         hptr = lre_probe(rstate, left, right);
11879         if (!hptr || !*hptr) {
11880                 return;
11881         }
11882         entry = *hptr;
11883         *hptr = entry->next;
11884         xfree(entry);
11885
11886         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11887                 edge = *ptr;
11888                 if (edge->node == right) {
11889                         *ptr = edge->next;
11890                         memset(edge, 0, sizeof(*edge));
11891                         xfree(edge);
11892                         right->degree--;
11893                         break;
11894                 }
11895         }
11896         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11897                 edge = *ptr;
11898                 if (edge->node == left) {
11899                         *ptr = edge->next;
11900                         memset(edge, 0, sizeof(*edge));
11901                         xfree(edge);
11902                         left->degree--;
11903                         break;
11904                 }
11905         }
11906 }
11907
11908 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11909 {
11910         struct live_range_edge *edge, *next;
11911         for(edge = range->edges; edge; edge = next) {
11912                 next = edge->next;
11913                 remove_live_edge(rstate, range, edge->node);
11914         }
11915 }
11916
11917 static void transfer_live_edges(struct reg_state *rstate, 
11918         struct live_range *dest, struct live_range *src)
11919 {
11920         struct live_range_edge *edge, *next;
11921         for(edge = src->edges; edge; edge = next) {
11922                 struct live_range *other;
11923                 next = edge->next;
11924                 other = edge->node;
11925                 remove_live_edge(rstate, src, other);
11926                 add_live_edge(rstate, dest, other);
11927         }
11928 }
11929
11930
11931 /* Interference graph...
11932  * 
11933  * new(n) --- Return a graph with n nodes but no edges.
11934  * add(g,x,y) --- Return a graph including g with an between x and y
11935  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11936  *                x and y in the graph g
11937  * degree(g, x) --- Return the degree of the node x in the graph g
11938  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11939  *
11940  * Implement with a hash table && a set of adjcency vectors.
11941  * The hash table supports constant time implementations of add and interfere.
11942  * The adjacency vectors support an efficient implementation of neighbors.
11943  */
11944
11945 /* 
11946  *     +---------------------------------------------------+
11947  *     |         +--------------+                          |
11948  *     v         v              |                          |
11949  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
11950  *
11951  * -- In simplify implment optimistic coloring... (No backtracking)
11952  * -- Implement Rematerialization it is the only form of spilling we can perform
11953  *    Essentially this means dropping a constant from a register because
11954  *    we can regenerate it later.
11955  *
11956  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11957  *     coalesce at phi points...
11958  * --- Bias coloring if at all possible do the coalesing a compile time.
11959  *
11960  *
11961  */
11962
11963 static void different_colored(
11964         struct compile_state *state, struct reg_state *rstate, 
11965         struct triple *parent, struct triple *ins)
11966 {
11967         struct live_range *lr;
11968         struct triple **expr;
11969         lr = rstate->lrd[ins->id].lr;
11970         expr = triple_rhs(state, ins, 0);
11971         for(;expr; expr = triple_rhs(state, ins, expr)) {
11972                 struct live_range *lr2;
11973                 if (!*expr || (*expr == parent) || (*expr == ins)) {
11974                         continue;
11975                 }
11976                 lr2 = rstate->lrd[(*expr)->id].lr;
11977                 if (lr->color == lr2->color) {
11978                         internal_error(state, ins, "live range too big");
11979                 }
11980         }
11981 }
11982
11983
11984 static struct live_range *coalesce_ranges(
11985         struct compile_state *state, struct reg_state *rstate,
11986         struct live_range *lr1, struct live_range *lr2)
11987 {
11988         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11989         unsigned color;
11990         unsigned classes;
11991         if (lr1 == lr2) {
11992                 return lr1;
11993         }
11994         if (!lr1->defs || !lr2->defs) {
11995                 internal_error(state, 0,
11996                         "cannot coalese dead live ranges");
11997         }
11998         if ((lr1->color == REG_UNNEEDED) ||
11999                 (lr2->color == REG_UNNEEDED)) {
12000                 internal_error(state, 0, 
12001                         "cannot coalesce live ranges without a possible color");
12002         }
12003         if ((lr1->color != lr2->color) &&
12004                 (lr1->color != REG_UNSET) &&
12005                 (lr2->color != REG_UNSET)) {
12006                 internal_error(state, lr1->defs->def, 
12007                         "cannot coalesce live ranges of different colors");
12008         }
12009         color = lr1->color;
12010         if (color == REG_UNSET) {
12011                 color = lr2->color;
12012         }
12013         classes = lr1->classes & lr2->classes;
12014         if (!classes) {
12015                 internal_error(state, lr1->defs->def,
12016                         "cannot coalesce live ranges with dissimilar register classes");
12017         }
12018         /* If there is a clear dominate live range put it in lr1,
12019          * For purposes of this test phi functions are
12020          * considered dominated by the definitions that feed into
12021          * them. 
12022          */
12023         if ((lr1->defs->prev->def->op == OP_PHI) ||
12024                 ((lr2->defs->prev->def->op != OP_PHI) &&
12025                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12026                 struct live_range *tmp;
12027                 tmp = lr1;
12028                 lr1 = lr2;
12029                 lr2 = tmp;
12030         }
12031 #if 0
12032         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
12033                 fprintf(stderr, "lr1 post\n");
12034         }
12035         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12036                 fprintf(stderr, "lr1 pre\n");
12037         }
12038         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
12039                 fprintf(stderr, "lr2 post\n");
12040         }
12041         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12042                 fprintf(stderr, "lr2 pre\n");
12043         }
12044 #endif
12045 #if 0
12046         fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12047                 lr1->defs->def,
12048                 lr1->color,
12049                 lr2->defs->def,
12050                 lr2->color);
12051 #endif
12052         
12053         lr1->classes = classes;
12054         /* Append lr2 onto lr1 */
12055 #warning "FIXME should this be a merge instead of a splice?"
12056         /* This FIXME item applies to the correctness of live_range_end 
12057          * and to the necessity of making multiple passes of coalesce_live_ranges.
12058          * A failure to find some coalesce opportunities in coaleace_live_ranges
12059          * does not impact the correct of the compiler just the efficiency with
12060          * which registers are allocated.
12061          */
12062         head = lr1->defs;
12063         mid1 = lr1->defs->prev;
12064         mid2 = lr2->defs;
12065         end  = lr2->defs->prev;
12066         
12067         head->prev = end;
12068         end->next  = head;
12069
12070         mid1->next = mid2;
12071         mid2->prev = mid1;
12072
12073         /* Fixup the live range in the added live range defs */
12074         lrd = head;
12075         do {
12076                 lrd->lr = lr1;
12077                 lrd = lrd->next;
12078         } while(lrd != head);
12079
12080         /* Mark lr2 as free. */
12081         lr2->defs = 0;
12082         lr2->color = REG_UNNEEDED;
12083         lr2->classes = 0;
12084
12085         if (!lr1->defs) {
12086                 internal_error(state, 0, "lr1->defs == 0 ?");
12087         }
12088
12089         lr1->color   = color;
12090         lr1->classes = classes;
12091
12092         /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12093         transfer_live_edges(rstate, lr1, lr2);
12094
12095         return lr1;
12096 }
12097
12098 static struct live_range_def *live_range_head(
12099         struct compile_state *state, struct live_range *lr,
12100         struct live_range_def *last)
12101 {
12102         struct live_range_def *result;
12103         result = 0;
12104         if (last == 0) {
12105                 result = lr->defs;
12106         }
12107         else if (!tdominates(state, lr->defs->def, last->next->def)) {
12108                 result = last->next;
12109         }
12110         return result;
12111 }
12112
12113 static struct live_range_def *live_range_end(
12114         struct compile_state *state, struct live_range *lr,
12115         struct live_range_def *last)
12116 {
12117         struct live_range_def *result;
12118         result = 0;
12119         if (last == 0) {
12120                 result = lr->defs->prev;
12121         }
12122         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12123                 result = last->prev;
12124         }
12125         return result;
12126 }
12127
12128
12129 static void initialize_live_ranges(
12130         struct compile_state *state, struct reg_state *rstate)
12131 {
12132         struct triple *ins, *first;
12133         size_t count, size;
12134         int i, j;
12135
12136         first = RHS(state->main_function, 0);
12137         /* First count how many instructions I have.
12138          */
12139         count = count_triples(state);
12140         /* Potentially I need one live range definitions for each
12141          * instruction, plus an extra for the split routines.
12142          */
12143         rstate->defs = count + 1;
12144         /* Potentially I need one live range for each instruction
12145          * plus an extra for the dummy live range.
12146          */
12147         rstate->ranges = count + 1;
12148         size = sizeof(rstate->lrd[0]) * rstate->defs;
12149         rstate->lrd = xcmalloc(size, "live_range_def");
12150         size = sizeof(rstate->lr[0]) * rstate->ranges;
12151         rstate->lr  = xcmalloc(size, "live_range");
12152
12153         /* Setup the dummy live range */
12154         rstate->lr[0].classes = 0;
12155         rstate->lr[0].color = REG_UNSET;
12156         rstate->lr[0].defs = 0;
12157         i = j = 0;
12158         ins = first;
12159         do {
12160                 /* If the triple is a variable give it a live range */
12161                 if (triple_is_def(state, ins)) {
12162                         struct reg_info info;
12163                         /* Find the architecture specific color information */
12164                         info = find_def_color(state, ins);
12165
12166                         i++;
12167                         rstate->lr[i].defs    = &rstate->lrd[j];
12168                         rstate->lr[i].color   = info.reg;
12169                         rstate->lr[i].classes = info.regcm;
12170                         rstate->lr[i].degree  = 0;
12171                         rstate->lrd[j].lr = &rstate->lr[i];
12172                 } 
12173                 /* Otherwise give the triple the dummy live range. */
12174                 else {
12175                         rstate->lrd[j].lr = &rstate->lr[0];
12176                 }
12177
12178                 /* Initalize the live_range_def */
12179                 rstate->lrd[j].next    = &rstate->lrd[j];
12180                 rstate->lrd[j].prev    = &rstate->lrd[j];
12181                 rstate->lrd[j].def     = ins;
12182                 rstate->lrd[j].orig_id = ins->id;
12183                 ins->id = j;
12184
12185                 j++;
12186                 ins = ins->next;
12187         } while(ins != first);
12188         rstate->ranges = i;
12189         rstate->defs -= 1;
12190
12191         /* Make a second pass to handle achitecture specific register
12192          * constraints.
12193          */
12194         ins = first;
12195         do {
12196                 int zlhs, zrhs, i, j;
12197                 if (ins->id > rstate->defs) {
12198                         internal_error(state, ins, "bad id");
12199                 }
12200                 
12201                 /* Walk through the template of ins and coalesce live ranges */
12202                 zlhs = TRIPLE_LHS(ins->sizes);
12203                 if ((zlhs == 0) && triple_is_def(state, ins)) {
12204                         zlhs = 1;
12205                 }
12206                 zrhs = TRIPLE_RHS(ins->sizes);
12207                 
12208                 for(i = 0; i < zlhs; i++) {
12209                         struct reg_info linfo;
12210                         struct live_range_def *lhs;
12211                         linfo = arch_reg_lhs(state, ins, i);
12212                         if (linfo.reg < MAX_REGISTERS) {
12213                                 continue;
12214                         }
12215                         if (triple_is_def(state, ins)) {
12216                                 lhs = &rstate->lrd[ins->id];
12217                         } else {
12218                                 lhs = &rstate->lrd[LHS(ins, i)->id];
12219                         }
12220                         for(j = 0; j < zrhs; j++) {
12221                                 struct reg_info rinfo;
12222                                 struct live_range_def *rhs;
12223                                 rinfo = arch_reg_rhs(state, ins, j);
12224                                 if (rinfo.reg < MAX_REGISTERS) {
12225                                         continue;
12226                                 }
12227                                 rhs = &rstate->lrd[RHS(ins, i)->id];
12228                                 if (rinfo.reg == linfo.reg) {
12229                                         coalesce_ranges(state, rstate, 
12230                                                 lhs->lr, rhs->lr);
12231                                 }
12232                         }
12233                 }
12234                 ins = ins->next;
12235         } while(ins != first);
12236 }
12237
12238 static void graph_ins(
12239         struct compile_state *state, 
12240         struct reg_block *blocks, struct triple_reg_set *live, 
12241         struct reg_block *rb, struct triple *ins, void *arg)
12242 {
12243         struct reg_state *rstate = arg;
12244         struct live_range *def;
12245         struct triple_reg_set *entry;
12246
12247         /* If the triple is not a definition
12248          * we do not have a definition to add to
12249          * the interference graph.
12250          */
12251         if (!triple_is_def(state, ins)) {
12252                 return;
12253         }
12254         def = rstate->lrd[ins->id].lr;
12255         
12256         /* Create an edge between ins and everything that is
12257          * alive, unless the live_range cannot share
12258          * a physical register with ins.
12259          */
12260         for(entry = live; entry; entry = entry->next) {
12261                 struct live_range *lr;
12262                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12263                         internal_error(state, 0, "bad entry?");
12264                 }
12265                 lr = rstate->lrd[entry->member->id].lr;
12266                 if (def == lr) {
12267                         continue;
12268                 }
12269                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12270                         continue;
12271                 }
12272                 add_live_edge(rstate, def, lr);
12273         }
12274         return;
12275 }
12276
12277 static struct live_range *get_verify_live_range(
12278         struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12279 {
12280         struct live_range *lr;
12281         struct live_range_def *lrd;
12282         int ins_found;
12283         if ((ins->id < 0) || (ins->id > rstate->defs)) {
12284                 internal_error(state, ins, "bad ins?");
12285         }
12286         lr = rstate->lrd[ins->id].lr;
12287         ins_found = 0;
12288         lrd = lr->defs;
12289         do {
12290                 if (lrd->def == ins) {
12291                         ins_found = 1;
12292                 }
12293                 lrd = lrd->next;
12294         } while(lrd != lr->defs);
12295         if (!ins_found) {
12296                 internal_error(state, ins, "ins not in live range");
12297         }
12298         return lr;
12299 }
12300
12301 static void verify_graph_ins(
12302         struct compile_state *state, 
12303         struct reg_block *blocks, struct triple_reg_set *live, 
12304         struct reg_block *rb, struct triple *ins, void *arg)
12305 {
12306         struct reg_state *rstate = arg;
12307         struct triple_reg_set *entry1, *entry2;
12308
12309
12310         /* Compare live against edges and make certain the code is working */
12311         for(entry1 = live; entry1; entry1 = entry1->next) {
12312                 struct live_range *lr1;
12313                 lr1 = get_verify_live_range(state, rstate, entry1->member);
12314                 for(entry2 = live; entry2; entry2 = entry2->next) {
12315                         struct live_range *lr2;
12316                         struct live_range_edge *edge2;
12317                         int lr1_found;
12318                         int lr2_degree;
12319                         if (entry2 == entry1) {
12320                                 continue;
12321                         }
12322                         lr2 = get_verify_live_range(state, rstate, entry2->member);
12323                         if (lr1 == lr2) {
12324                                 internal_error(state, entry2->member, 
12325                                         "live range with 2 values simultaneously alive");
12326                         }
12327                         if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12328                                 continue;
12329                         }
12330                         if (!interfere(rstate, lr1, lr2)) {
12331                                 internal_error(state, entry2->member, 
12332                                         "edges don't interfere?");
12333                         }
12334                                 
12335                         lr1_found = 0;
12336                         lr2_degree = 0;
12337                         for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12338                                 lr2_degree++;
12339                                 if (edge2->node == lr1) {
12340                                         lr1_found = 1;
12341                                 }
12342                         }
12343                         if (lr2_degree != lr2->degree) {
12344                                 internal_error(state, entry2->member,
12345                                         "computed degree: %d does not match reported degree: %d\n",
12346                                         lr2_degree, lr2->degree);
12347                         }
12348                         if (!lr1_found) {
12349                                 internal_error(state, entry2->member, "missing edge");
12350                         }
12351                 }
12352         }
12353         return;
12354 }
12355
12356
12357 static void print_interference_ins(
12358         struct compile_state *state, 
12359         struct reg_block *blocks, struct triple_reg_set *live, 
12360         struct reg_block *rb, struct triple *ins, void *arg)
12361 {
12362         struct reg_state *rstate = arg;
12363         struct live_range *lr;
12364         unsigned id;
12365
12366         lr = rstate->lrd[ins->id].lr;
12367         id = ins->id;
12368         ins->id = rstate->lrd[id].orig_id;
12369         SET_REG(ins->id, lr->color);
12370         display_triple(stdout, ins);
12371         ins->id = id;
12372
12373         if (lr->defs) {
12374                 struct live_range_def *lrd;
12375                 printf("       range:");
12376                 lrd = lr->defs;
12377                 do {
12378                         printf(" %-10p", lrd->def);
12379                         lrd = lrd->next;
12380                 } while(lrd != lr->defs);
12381                 printf("\n");
12382         }
12383         if (live) {
12384                 struct triple_reg_set *entry;
12385                 printf("        live:");
12386                 for(entry = live; entry; entry = entry->next) {
12387                         printf(" %-10p", entry->member);
12388                 }
12389                 printf("\n");
12390         }
12391         if (lr->edges) {
12392                 struct live_range_edge *entry;
12393                 printf("       edges:");
12394                 for(entry = lr->edges; entry; entry = entry->next) {
12395                         struct live_range_def *lrd;
12396                         lrd = entry->node->defs;
12397                         do {
12398                                 printf(" %-10p", lrd->def);
12399                                 lrd = lrd->next;
12400                         } while(lrd != entry->node->defs);
12401                         printf("|");
12402                 }
12403                 printf("\n");
12404         }
12405         if (triple_is_branch(state, ins)) {
12406                 printf("\n");
12407         }
12408         return;
12409 }
12410
12411 static int coalesce_live_ranges(
12412         struct compile_state *state, struct reg_state *rstate)
12413 {
12414         /* At the point where a value is moved from one
12415          * register to another that value requires two
12416          * registers, thus increasing register pressure.
12417          * Live range coaleescing reduces the register
12418          * pressure by keeping a value in one register
12419          * longer.
12420          *
12421          * In the case of a phi function all paths leading
12422          * into it must be allocated to the same register
12423          * otherwise the phi function may not be removed.
12424          *
12425          * Forcing a value to stay in a single register
12426          * for an extended period of time does have
12427          * limitations when applied to non homogenous
12428          * register pool.  
12429          *
12430          * The two cases I have identified are:
12431          * 1) Two forced register assignments may
12432          *    collide.
12433          * 2) Registers may go unused because they
12434          *    are only good for storing the value
12435          *    and not manipulating it.
12436          *
12437          * Because of this I need to split live ranges,
12438          * even outside of the context of coalesced live
12439          * ranges.  The need to split live ranges does
12440          * impose some constraints on live range coalescing.
12441          *
12442          * - Live ranges may not be coalesced across phi
12443          *   functions.  This creates a 2 headed live
12444          *   range that cannot be sanely split.
12445          *
12446          * - phi functions (coalesced in initialize_live_ranges) 
12447          *   are handled as pre split live ranges so we will
12448          *   never attempt to split them.
12449          */
12450         int coalesced;
12451         int i;
12452
12453         coalesced = 0;
12454         for(i = 0; i <= rstate->ranges; i++) {
12455                 struct live_range *lr1;
12456                 struct live_range_def *lrd1;
12457                 lr1 = &rstate->lr[i];
12458                 if (!lr1->defs) {
12459                         continue;
12460                 }
12461                 lrd1 = live_range_end(state, lr1, 0);
12462                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12463                         struct triple_set *set;
12464                         if (lrd1->def->op != OP_COPY) {
12465                                 continue;
12466                         }
12467                         /* Skip copies that are the result of a live range split. */
12468                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12469                                 continue;
12470                         }
12471                         for(set = lrd1->def->use; set; set = set->next) {
12472                                 struct live_range_def *lrd2;
12473                                 struct live_range *lr2, *res;
12474
12475                                 lrd2 = &rstate->lrd[set->member->id];
12476
12477                                 /* Don't coalesce with instructions
12478                                  * that are the result of a live range
12479                                  * split.
12480                                  */
12481                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12482                                         continue;
12483                                 }
12484                                 lr2 = rstate->lrd[set->member->id].lr;
12485                                 if (lr1 == lr2) {
12486                                         continue;
12487                                 }
12488                                 if ((lr1->color != lr2->color) &&
12489                                         (lr1->color != REG_UNSET) &&
12490                                         (lr2->color != REG_UNSET)) {
12491                                         continue;
12492                                 }
12493                                 if ((lr1->classes & lr2->classes) == 0) {
12494                                         continue;
12495                                 }
12496                                 
12497                                 if (interfere(rstate, lr1, lr2)) {
12498                                         continue;
12499                                 }
12500
12501                                 res = coalesce_ranges(state, rstate, lr1, lr2);
12502                                 coalesced += 1;
12503                                 if (res != lr1) {
12504                                         goto next;
12505                                 }
12506                         }
12507                 }
12508         next:
12509                 ;
12510         }
12511         return coalesced;
12512 }
12513
12514
12515 static void fix_coalesce_conflicts(struct compile_state *state,
12516         struct reg_block *blocks, struct triple_reg_set *live,
12517         struct reg_block *rb, struct triple *ins, void *arg)
12518 {
12519         int zlhs, zrhs, i, j;
12520
12521         /* See if we have a mandatory coalesce operation between
12522          * a lhs and a rhs value.  If so and the rhs value is also
12523          * alive then this triple needs to be pre copied.  Otherwise
12524          * we would have two definitions in the same live range simultaneously
12525          * alive.
12526          */
12527         zlhs = TRIPLE_LHS(ins->sizes);
12528         if ((zlhs == 0) && triple_is_def(state, ins)) {
12529                 zlhs = 1;
12530         }
12531         zrhs = TRIPLE_RHS(ins->sizes);
12532         for(i = 0; i < zlhs; i++) {
12533                 struct reg_info linfo;
12534                 linfo = arch_reg_lhs(state, ins, i);
12535                 if (linfo.reg < MAX_REGISTERS) {
12536                         continue;
12537                 }
12538                 for(j = 0; j < zrhs; j++) {
12539                         struct reg_info rinfo;
12540                         struct triple *rhs;
12541                         struct triple_reg_set *set;
12542                         int found;
12543                         found = 0;
12544                         rinfo = arch_reg_rhs(state, ins, j);
12545                         if (rinfo.reg != linfo.reg) {
12546                                 continue;
12547                         }
12548                         rhs = RHS(ins, j);
12549                         for(set = live; set && !found; set = set->next) {
12550                                 if (set->member == rhs) {
12551                                         found = 1;
12552                                 }
12553                         }
12554                         if (found) {
12555                                 struct triple *copy;
12556                                 copy = pre_copy(state, ins, j);
12557                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12558                         }
12559                 }
12560         }
12561         return;
12562 }
12563
12564 static void replace_set_use(struct compile_state *state,
12565         struct triple_reg_set *head, struct triple *orig, struct triple *new)
12566 {
12567         struct triple_reg_set *set;
12568         for(set = head; set; set = set->next) {
12569                 if (set->member == orig) {
12570                         set->member = new;
12571                 }
12572         }
12573 }
12574
12575 static void replace_block_use(struct compile_state *state, 
12576         struct reg_block *blocks, struct triple *orig, struct triple *new)
12577 {
12578         int i;
12579 #warning "WISHLIST visit just those blocks that need it *"
12580         for(i = 1; i <= state->last_vertex; i++) {
12581                 struct reg_block *rb;
12582                 rb = &blocks[i];
12583                 replace_set_use(state, rb->in, orig, new);
12584                 replace_set_use(state, rb->out, orig, new);
12585         }
12586 }
12587
12588 static void color_instructions(struct compile_state *state)
12589 {
12590         struct triple *ins, *first;
12591         first = RHS(state->main_function, 0);
12592         ins = first;
12593         do {
12594                 if (triple_is_def(state, ins)) {
12595                         struct reg_info info;
12596                         info = find_lhs_color(state, ins, 0);
12597                         if (info.reg >= MAX_REGISTERS) {
12598                                 info.reg = REG_UNSET;
12599                         }
12600                         SET_INFO(ins->id, info);
12601                 }
12602                 ins = ins->next;
12603         } while(ins != first);
12604 }
12605
12606 static struct reg_info read_lhs_color(
12607         struct compile_state *state, struct triple *ins, int index)
12608 {
12609         struct reg_info info;
12610         if ((index == 0) && triple_is_def(state, ins)) {
12611                 info.reg   = ID_REG(ins->id);
12612                 info.regcm = ID_REGCM(ins->id);
12613         }
12614         else if (index < TRIPLE_LHS(ins->sizes)) {
12615                 info = read_lhs_color(state, LHS(ins, index), 0);
12616         }
12617         else {
12618                 internal_error(state, ins, "Bad lhs %d", index);
12619                 info.reg = REG_UNSET;
12620                 info.regcm = 0;
12621         }
12622         return info;
12623 }
12624
12625 static struct triple *resolve_tangle(
12626         struct compile_state *state, struct triple *tangle)
12627 {
12628         struct reg_info info, uinfo;
12629         struct triple_set *set, *next;
12630         struct triple *copy;
12631
12632 #warning "WISHLIST recalculate all affected instructions colors"
12633         info = find_lhs_color(state, tangle, 0);
12634         for(set = tangle->use; set; set = next) {
12635                 struct triple *user;
12636                 int i, zrhs;
12637                 next = set->next;
12638                 user = set->member;
12639                 zrhs = TRIPLE_RHS(user->sizes);
12640                 for(i = 0; i < zrhs; i++) {
12641                         if (RHS(user, i) != tangle) {
12642                                 continue;
12643                         }
12644                         uinfo = find_rhs_post_color(state, user, i);
12645                         if (uinfo.reg == info.reg) {
12646                                 copy = pre_copy(state, user, i);
12647                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12648                                 SET_INFO(copy->id, uinfo);
12649                         }
12650                 }
12651         }
12652         copy = 0;
12653         uinfo = find_lhs_pre_color(state, tangle, 0);
12654         if (uinfo.reg == info.reg) {
12655                 struct reg_info linfo;
12656                 copy = post_copy(state, tangle);
12657                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12658                 linfo = find_lhs_color(state, copy, 0);
12659                 SET_INFO(copy->id, linfo);
12660         }
12661         info = find_lhs_color(state, tangle, 0);
12662         SET_INFO(tangle->id, info);
12663         
12664         return copy;
12665 }
12666
12667
12668 static void fix_tangles(struct compile_state *state,
12669         struct reg_block *blocks, struct triple_reg_set *live,
12670         struct reg_block *rb, struct triple *ins, void *arg)
12671 {
12672         int *tangles = arg;
12673         struct triple *tangle;
12674         do {
12675                 char used[MAX_REGISTERS];
12676                 struct triple_reg_set *set;
12677                 tangle = 0;
12678
12679                 /* Find out which registers have multiple uses at this point */
12680                 memset(used, 0, sizeof(used));
12681                 for(set = live; set; set = set->next) {
12682                         struct reg_info info;
12683                         info = read_lhs_color(state, set->member, 0);
12684                         if (info.reg == REG_UNSET) {
12685                                 continue;
12686                         }
12687                         reg_inc_used(state, used, info.reg);
12688                 }
12689                 
12690                 /* Now find the least dominated definition of a register in
12691                  * conflict I have seen so far.
12692                  */
12693                 for(set = live; set; set = set->next) {
12694                         struct reg_info info;
12695                         info = read_lhs_color(state, set->member, 0);
12696                         if (used[info.reg] < 2) {
12697                                 continue;
12698                         }
12699                         /* Changing copies that feed into phi functions
12700                          * is incorrect.
12701                          */
12702                         if (set->member->use && 
12703                                 (set->member->use->member->op == OP_PHI)) {
12704                                 continue;
12705                         }
12706                         if (!tangle || tdominates(state, set->member, tangle)) {
12707                                 tangle = set->member;
12708                         }
12709                 }
12710                 /* If I have found a tangle resolve it */
12711                 if (tangle) {
12712                         struct triple *post_copy;
12713                         (*tangles)++;
12714                         post_copy = resolve_tangle(state, tangle);
12715                         if (post_copy) {
12716                                 replace_block_use(state, blocks, tangle, post_copy);
12717                         }
12718                         if (post_copy && (tangle != ins)) {
12719                                 replace_set_use(state, live, tangle, post_copy);
12720                         }
12721                 }
12722         } while(tangle);
12723         return;
12724 }
12725
12726 static int correct_tangles(
12727         struct compile_state *state, struct reg_block *blocks)
12728 {
12729         int tangles;
12730         tangles = 0;
12731         color_instructions(state);
12732         walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
12733         return tangles;
12734 }
12735
12736 struct least_conflict {
12737         struct reg_state *rstate;
12738         struct live_range *ref_range;
12739         struct triple *ins;
12740         struct triple_reg_set *live;
12741         size_t count;
12742         int constraints;
12743 };
12744 static void least_conflict(struct compile_state *state,
12745         struct reg_block *blocks, struct triple_reg_set *live,
12746         struct reg_block *rb, struct triple *ins, void *arg)
12747 {
12748         struct least_conflict *conflict = arg;
12749         struct live_range_edge *edge;
12750         struct triple_reg_set *set;
12751         size_t count;
12752         int constraints;
12753
12754 #warning "FIXME handle instructions with left hand sides..."
12755         /* Only instructions that introduce a new definition
12756          * can be the conflict instruction.
12757          */
12758         if (!triple_is_def(state, ins)) {
12759                 return;
12760         }
12761
12762         /* See if live ranges at this instruction are a
12763          * strict subset of the live ranges that are in conflict.
12764          */
12765         count = 0;
12766         for(set = live; set; set = set->next) {
12767                 struct live_range *lr;
12768                 lr = conflict->rstate->lrd[set->member->id].lr;
12769                 /* Ignore it if there cannot be an edge between these two nodes */
12770                 if (!arch_regcm_intersect(conflict->ref_range->classes, lr->classes)) {
12771                         continue;
12772                 }
12773                 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12774                         if (edge->node == lr) {
12775                                 break;
12776                         }
12777                 }
12778                 if (!edge && (lr != conflict->ref_range)) {
12779                         return;
12780                 }
12781                 count++;
12782         }
12783         if (count <= 1) {
12784                 return;
12785         }
12786
12787 #if 0
12788         /* See if there is an uncolored member in this subset. 
12789          */
12790          for(set = live; set; set = set->next) {
12791                 struct live_range *lr;
12792                 lr = conflict->rstate->lrd[set->member->id].lr;
12793                 if (lr->color == REG_UNSET) {
12794                         break;
12795                 }
12796         }
12797         if (!set && (conflict->ref_range != REG_UNSET)) {
12798                 return;
12799         }
12800 #endif
12801
12802         /* See if any of the live registers are constrained,
12803          * if not it won't be productive to pick this as
12804          * a conflict instruction.
12805          */
12806         constraints = 0;
12807         for(set = live; set; set = set->next) {
12808                 struct triple_set *uset;
12809                 struct reg_info info;
12810                 unsigned classes;
12811                 unsigned cur_size, size;
12812                 /* Skip this instruction */
12813                 if (set->member == ins) {
12814                         continue;
12815                 }
12816                 /* Find how many registers this value can potentially 
12817                  * be assigned to.
12818                  */
12819                 classes = arch_type_to_regcm(state, set->member->type);
12820                 size = regc_max_size(state, classes);
12821                 
12822                 /* Find how many registers we allow this value to
12823                  * be assigned to.
12824                  */
12825                 info = arch_reg_lhs(state, set->member, 0);
12826                 
12827                 /* If the value does not live in a register it
12828                  * isn't constrained.
12829                  */
12830                 if (info.reg == REG_UNNEEDED) {
12831                         continue;
12832                 }
12833                 
12834                 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12835                         cur_size = regc_max_size(state, info.regcm);
12836                 } else {
12837                         cur_size = 1;
12838                 }
12839
12840                 /* If there is no difference between potential and
12841                  * actual register count there is not a constraint
12842                  */
12843                 if (cur_size >= size) {
12844                         continue;
12845                 }
12846                 
12847                 /* If this live_range feeds into conflict->inds
12848                  * it isn't a constraint we can relieve.
12849                  */
12850                 for(uset = set->member->use; uset; uset = uset->next) {
12851                         if (uset->member == ins) {
12852                                 break;
12853                         }
12854                 }
12855                 if (uset) {
12856                         continue;
12857                 }
12858                 constraints = 1;
12859                 break;
12860         }
12861         /* Don't drop canidates with constraints */
12862         if (conflict->constraints && !constraints) {
12863                 return;
12864         }
12865
12866
12867 #if 0
12868         fprintf(stderr, "conflict ins? %p %s count: %d constraints: %d\n",
12869                 ins, tops(ins->op), count, constraints);
12870 #endif
12871         /* Find the instruction with the largest possible subset of
12872          * conflict ranges and that dominates any other instruction
12873          * with an equal sized set of conflicting ranges.
12874          */
12875         if ((count > conflict->count) ||
12876                 ((count == conflict->count) &&
12877                         tdominates(state, ins, conflict->ins))) {
12878                 struct triple_reg_set *next;
12879                 /* Remember the canidate instruction */
12880                 conflict->ins = ins;
12881                 conflict->count = count;
12882                 conflict->constraints = constraints;
12883                 /* Free the old collection of live registers */
12884                 for(set = conflict->live; set; set = next) {
12885                         next = set->next;
12886                         do_triple_unset(&conflict->live, set->member);
12887                 }
12888                 conflict->live = 0;
12889                 /* Rember the registers that are alive but do not feed
12890                  * into or out of conflict->ins.
12891                  */
12892                 for(set = live; set; set = set->next) {
12893                         struct triple **expr;
12894                         if (set->member == ins) {
12895                                 goto next;
12896                         }
12897                         expr = triple_rhs(state, ins, 0);
12898                         for(;expr; expr = triple_rhs(state, ins, expr)) {
12899                                 if (*expr == set->member) {
12900                                         goto next;
12901                                 }
12902                         }
12903                         expr = triple_lhs(state, ins, 0);
12904                         for(; expr; expr = triple_lhs(state, ins, expr)) {
12905                                 if (*expr == set->member) {
12906                                         goto next;
12907                                 }
12908                         }
12909                         do_triple_set(&conflict->live, set->member, set->new);
12910                 next:
12911                         ;
12912                 }
12913         }
12914         return;
12915 }
12916
12917 static void find_range_conflict(struct compile_state *state,
12918         struct reg_state *rstate, char *used, struct live_range *ref_range,
12919         struct least_conflict *conflict)
12920 {
12921
12922         /* there are 3 kinds ways conflicts can occure.
12923          * 1) the life time of 2 values simply overlap.
12924          * 2) the 2 values feed into the same instruction.
12925          * 3) the 2 values feed into a phi function.
12926          */
12927
12928         /* find the instruction where the problematic conflict comes
12929          * into existance.  that the instruction where all of
12930          * the values are alive, and among such instructions it is
12931          * the least dominated one.
12932          *
12933          * a value is alive an an instruction if either;
12934          * 1) the value defintion dominates the instruction and there
12935          *    is a use at or after that instrction
12936          * 2) the value definition feeds into a phi function in the
12937          *    same block as the instruction.  and the phi function
12938          *    is at or after the instruction.
12939          */
12940         memset(conflict, 0, sizeof(*conflict));
12941         conflict->rstate      = rstate;
12942         conflict->ref_range   = ref_range;
12943         conflict->ins         = 0;
12944         conflict->live        = 0;
12945         conflict->count       = 0;
12946         conflict->constraints = 0;
12947         walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12948
12949         if (!conflict->ins) {
12950                 internal_error(state, ref_range->defs->def, "No conflict ins?");
12951         }
12952         if (!conflict->live) {
12953                 internal_error(state, ref_range->defs->def, "No conflict live?");
12954         }
12955 #if 0
12956         fprintf(stderr, "conflict ins: %p %s count: %d constraints: %d\n", 
12957                 conflict->ins, tops(conflict->ins->op),
12958                 conflict->count, conflict->constraints);
12959 #endif
12960         return;
12961 }
12962
12963 static struct triple *split_constrained_range(struct compile_state *state, 
12964         struct reg_state *rstate, char *used, struct least_conflict *conflict)
12965 {
12966         unsigned constrained_size;
12967         struct triple *new, *constrained;
12968         struct triple_reg_set *cset;
12969         /* Find a range that is having problems because it is
12970          * artificially constrained.
12971          */
12972         constrained_size = ~0;
12973         constrained = 0;
12974         new = 0;
12975         for(cset = conflict->live; cset; cset = cset->next) {
12976                 struct triple_set *set;
12977                 struct reg_info info;
12978                 unsigned classes;
12979                 unsigned cur_size, size;
12980                 /* Skip the live range that starts with conflict->ins */
12981                 if (cset->member == conflict->ins) {
12982                         continue;
12983                 }
12984                 /* Find how many registers this value can potentially
12985                  * be assigned to.
12986                  */
12987                 classes = arch_type_to_regcm(state, cset->member->type);
12988                 size = regc_max_size(state, classes);
12989
12990                 /* Find how many registers we allow this value to
12991                  * be assigned to.
12992                  */
12993                 info = arch_reg_lhs(state, cset->member, 0);
12994
12995                 /* If the register doesn't need a register 
12996                  * splitting it can't help.
12997                  */
12998                 if (info.reg == REG_UNNEEDED) {
12999                         continue;
13000                 }
13001 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
13002                 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
13003                         cur_size = regc_max_size(state, info.regcm);
13004                 } else {
13005                         cur_size = 1;
13006                 }
13007                 /* If this live_range feeds into conflict->ins
13008                  * splitting it is unlikely to help.
13009                  */
13010                 for(set = cset->member->use; set; set = set->next) {
13011                         if (set->member == conflict->ins) {
13012                                 goto next;
13013                         }
13014                 }
13015
13016                 /* If there is no difference between potential and
13017                  * actual register count there is nothing to do.
13018                  */
13019                 if (cur_size >= size) {
13020                         continue;
13021                 }
13022                 /* Of the constrained registers deal with the
13023                  * most constrained one first.
13024                  */
13025                 if (!constrained ||
13026                         (size < constrained_size)) {
13027                         constrained = cset->member;
13028                         constrained_size = size;
13029                 }
13030         next:
13031                 ;
13032         }
13033         if (constrained) {
13034                 new = post_copy(state, constrained);
13035                 new->id |= TRIPLE_FLAG_POST_SPLIT;
13036         }
13037         return new;
13038 }
13039
13040 static int split_ranges(
13041         struct compile_state *state, struct reg_state *rstate, 
13042         char *used, struct live_range *range)
13043 {
13044         struct triple *new;
13045
13046 #if 0
13047         fprintf(stderr, "split_ranges %d %s %p\n", 
13048                 rstate->passes, tops(range->defs->def->op), range->defs->def);
13049 #endif
13050         if ((range->color == REG_UNNEEDED) ||
13051                 (rstate->passes >= rstate->max_passes)) {
13052                 return 0;
13053         }
13054         new = 0;
13055         /* If I can't allocate a register something needs to be split */
13056         if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
13057                 struct least_conflict conflict;
13058
13059 #if 0
13060         fprintf(stderr, "find_range_conflict\n");
13061 #endif
13062                 /* Find where in the set of registers the conflict
13063                  * actually occurs.
13064                  */
13065                 find_range_conflict(state, rstate, used, range, &conflict);
13066
13067                 /* If a range has been artifically constrained split it */
13068                 new = split_constrained_range(state, rstate, used, &conflict);
13069                 
13070                 if (!new) {
13071                 /* Ideally I would split the live range that will not be used
13072                  * for the longest period of time in hopes that this will 
13073                  * (a) allow me to spill a register or
13074                  * (b) allow me to place a value in another register.
13075                  *
13076                  * So far I don't have a test case for this, the resolving
13077                  * of mandatory constraints has solved all of my
13078                  * know issues.  So I have choosen not to write any
13079                  * code until I cat get a better feel for cases where
13080                  * it would be useful to have.
13081                  *
13082                  */
13083 #warning "WISHLIST implement live range splitting..."
13084 #if 0
13085                         print_blocks(state, stderr);
13086                         print_dominators(state, stderr);
13087
13088 #endif
13089                         return 0;
13090                 }
13091         }
13092         if (new) {
13093                 rstate->lrd[rstate->defs].orig_id = new->id;
13094                 new->id = rstate->defs;
13095                 rstate->defs++;
13096 #if 0
13097                 fprintf(stderr, "new: %p old: %s %p\n", 
13098                         new, tops(RHS(new, 0)->op), RHS(new, 0));
13099 #endif
13100 #if 0
13101                 print_blocks(state, stderr);
13102                 print_dominators(state, stderr);
13103
13104 #endif
13105                 return 1;
13106         }
13107         return 0;
13108 }
13109
13110 #if DEBUG_COLOR_GRAPH > 1
13111 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13112 #define cgdebug_flush() fflush(stdout)
13113 #elif DEBUG_COLOR_GRAPH == 1
13114 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13115 #define cgdebug_flush() fflush(stderr)
13116 #else
13117 #define cgdebug_printf(...)
13118 #define cgdebug_flush()
13119 #endif
13120
13121         
13122 static int select_free_color(struct compile_state *state, 
13123         struct reg_state *rstate, struct live_range *range)
13124 {
13125         struct triple_set *entry;
13126         struct live_range_def *lrd;
13127         struct live_range_def *phi;
13128         struct live_range_edge *edge;
13129         char used[MAX_REGISTERS];
13130         struct triple **expr;
13131
13132         /* Instead of doing just the trivial color select here I try
13133          * a few extra things because a good color selection will help reduce
13134          * copies.
13135          */
13136
13137         /* Find the registers currently in use */
13138         memset(used, 0, sizeof(used));
13139         for(edge = range->edges; edge; edge = edge->next) {
13140                 if (edge->node->color == REG_UNSET) {
13141                         continue;
13142                 }
13143                 reg_fill_used(state, used, edge->node->color);
13144         }
13145 #if DEBUG_COLOR_GRAPH > 1
13146         {
13147                 int i;
13148                 i = 0;
13149                 for(edge = range->edges; edge; edge = edge->next) {
13150                         i++;
13151                 }
13152                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
13153                         tops(range->def->op), i, 
13154                         range->def->filename, range->def->line, range->def->col);
13155                 for(i = 0; i < MAX_REGISTERS; i++) {
13156                         if (used[i]) {
13157                                 cgdebug_printf("used: %s\n",
13158                                         arch_reg_str(i));
13159                         }
13160                 }
13161         }       
13162 #endif
13163
13164 #warning "FIXME detect conflicts caused by the source and destination being the same register"
13165
13166         /* If a color is already assigned see if it will work */
13167         if (range->color != REG_UNSET) {
13168                 struct live_range_def *lrd;
13169                 if (!used[range->color]) {
13170                         return 1;
13171                 }
13172                 for(edge = range->edges; edge; edge = edge->next) {
13173                         if (edge->node->color != range->color) {
13174                                 continue;
13175                         }
13176                         warning(state, edge->node->defs->def, "edge: ");
13177                         lrd = edge->node->defs;
13178                         do {
13179                                 warning(state, lrd->def, " %p %s",
13180                                         lrd->def, tops(lrd->def->op));
13181                                 lrd = lrd->next;
13182                         } while(lrd != edge->node->defs);
13183                 }
13184                 lrd = range->defs;
13185                 warning(state, range->defs->def, "def: ");
13186                 do {
13187                         warning(state, lrd->def, " %p %s",
13188                                 lrd->def, tops(lrd->def->op));
13189                         lrd = lrd->next;
13190                 } while(lrd != range->defs);
13191                 internal_error(state, range->defs->def,
13192                         "live range with already used color %s",
13193                         arch_reg_str(range->color));
13194         }
13195
13196         /* If I feed into an expression reuse it's color.
13197          * This should help remove copies in the case of 2 register instructions
13198          * and phi functions.
13199          */
13200         phi = 0;
13201         lrd = live_range_end(state, range, 0);
13202         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13203                 entry = lrd->def->use;
13204                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13205                         struct live_range_def *insd;
13206                         insd = &rstate->lrd[entry->member->id];
13207                         if (insd->lr->defs == 0) {
13208                                 continue;
13209                         }
13210                         if (!phi && (insd->def->op == OP_PHI) &&
13211                                 !interfere(rstate, range, insd->lr)) {
13212                                 phi = insd;
13213                         }
13214                         if ((insd->lr->color == REG_UNSET) ||
13215                                 ((insd->lr->classes & range->classes) == 0) ||
13216                                 (used[insd->lr->color])) {
13217                                 continue;
13218                         }
13219                         if (interfere(rstate, range, insd->lr)) {
13220                                 continue;
13221                         }
13222                         range->color = insd->lr->color;
13223                 }
13224         }
13225         /* If I feed into a phi function reuse it's color or the color
13226          * of something else that feeds into the phi function.
13227          */
13228         if (phi) {
13229                 if (phi->lr->color != REG_UNSET) {
13230                         if (used[phi->lr->color]) {
13231                                 range->color = phi->lr->color;
13232                         }
13233                 }
13234                 else {
13235                         expr = triple_rhs(state, phi->def, 0);
13236                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13237                                 struct live_range *lr;
13238                                 if (!*expr) {
13239                                         continue;
13240                                 }
13241                                 lr = rstate->lrd[(*expr)->id].lr;
13242                                 if ((lr->color == REG_UNSET) || 
13243                                         ((lr->classes & range->classes) == 0) ||
13244                                         (used[lr->color])) {
13245                                         continue;
13246                                 }
13247                                 if (interfere(rstate, range, lr)) {
13248                                         continue;
13249                                 }
13250                                 range->color = lr->color;
13251                         }
13252                 }
13253         }
13254         /* If I don't interfere with a rhs node reuse it's color */
13255         lrd = live_range_head(state, range, 0);
13256         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13257                 expr = triple_rhs(state, lrd->def, 0);
13258                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13259                         struct live_range *lr;
13260                         if (!*expr) {
13261                                 continue;
13262                         }
13263                         lr = rstate->lrd[(*expr)->id].lr;
13264                         if ((lr->color == -1) || 
13265                                 ((lr->classes & range->classes) == 0) ||
13266                                 (used[lr->color])) {
13267                                 continue;
13268                         }
13269                         if (interfere(rstate, range, lr)) {
13270                                 continue;
13271                         }
13272                         range->color = lr->color;
13273                         break;
13274                 }
13275         }
13276         /* If I have not opportunitically picked a useful color
13277          * pick the first color that is free.
13278          */
13279         if (range->color == REG_UNSET) {
13280                 range->color = 
13281                         arch_select_free_register(state, used, range->classes);
13282         }
13283         if (range->color == REG_UNSET) {
13284                 struct live_range_def *lrd;
13285                 int i;
13286                 if (split_ranges(state, rstate, used, range)) {
13287                         return 0;
13288                 }
13289                 for(edge = range->edges; edge; edge = edge->next) {
13290                         warning(state, edge->node->defs->def, "edge reg %s",
13291                                 arch_reg_str(edge->node->color));
13292                         lrd = edge->node->defs;
13293                         do {
13294                                 warning(state, lrd->def, " %s",
13295                                         tops(lrd->def->op));
13296                                 lrd = lrd->next;
13297                         } while(lrd != edge->node->defs);
13298                 }
13299                 warning(state, range->defs->def, "range: ");
13300                 lrd = range->defs;
13301                 do {
13302                         warning(state, lrd->def, " %s",
13303                                 tops(lrd->def->op));
13304                         lrd = lrd->next;
13305                 } while(lrd != range->defs);
13306                         
13307                 warning(state, range->defs->def, "classes: %x",
13308                         range->classes);
13309                 for(i = 0; i < MAX_REGISTERS; i++) {
13310                         if (used[i]) {
13311                                 warning(state, range->defs->def, "used: %s",
13312                                         arch_reg_str(i));
13313                         }
13314                 }
13315 #if DEBUG_COLOR_GRAPH < 2
13316                 error(state, range->defs->def, "too few registers");
13317 #else
13318                 internal_error(state, range->defs->def, "too few registers");
13319 #endif
13320         }
13321         range->classes = arch_reg_regcm(state, range->color);
13322         if (range->color == -1) {
13323                 internal_error(state, range->defs->def, "select_free_color did not?");
13324         }
13325         return 1;
13326 }
13327
13328 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13329 {
13330         int colored;
13331         struct live_range_edge *edge;
13332         struct live_range *range;
13333         if (rstate->low) {
13334                 cgdebug_printf("Lo: ");
13335                 range = rstate->low;
13336                 if (*range->group_prev != range) {
13337                         internal_error(state, 0, "lo: *prev != range?");
13338                 }
13339                 *range->group_prev = range->group_next;
13340                 if (range->group_next) {
13341                         range->group_next->group_prev = range->group_prev;
13342                 }
13343                 if (&range->group_next == rstate->low_tail) {
13344                         rstate->low_tail = range->group_prev;
13345                 }
13346                 if (rstate->low == range) {
13347                         internal_error(state, 0, "low: next != prev?");
13348                 }
13349         }
13350         else if (rstate->high) {
13351                 cgdebug_printf("Hi: ");
13352                 range = rstate->high;
13353                 if (*range->group_prev != range) {
13354                         internal_error(state, 0, "hi: *prev != range?");
13355                 }
13356                 *range->group_prev = range->group_next;
13357                 if (range->group_next) {
13358                         range->group_next->group_prev = range->group_prev;
13359                 }
13360                 if (&range->group_next == rstate->high_tail) {
13361                         rstate->high_tail = range->group_prev;
13362                 }
13363                 if (rstate->high == range) {
13364                         internal_error(state, 0, "high: next != prev?");
13365                 }
13366         }
13367         else {
13368                 return 1;
13369         }
13370         cgdebug_printf(" %d\n", range - rstate->lr);
13371         range->group_prev = 0;
13372         for(edge = range->edges; edge; edge = edge->next) {
13373                 struct live_range *node;
13374                 node = edge->node;
13375                 /* Move nodes from the high to the low list */
13376                 if (node->group_prev && (node->color == REG_UNSET) &&
13377                         (node->degree == regc_max_size(state, node->classes))) {
13378                         if (*node->group_prev != node) {
13379                                 internal_error(state, 0, "move: *prev != node?");
13380                         }
13381                         *node->group_prev = node->group_next;
13382                         if (node->group_next) {
13383                                 node->group_next->group_prev = node->group_prev;
13384                         }
13385                         if (&node->group_next == rstate->high_tail) {
13386                                 rstate->high_tail = node->group_prev;
13387                         }
13388                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13389                         node->group_prev  = rstate->low_tail;
13390                         node->group_next  = 0;
13391                         *rstate->low_tail = node;
13392                         rstate->low_tail  = &node->group_next;
13393                         if (*node->group_prev != node) {
13394                                 internal_error(state, 0, "move2: *prev != node?");
13395                         }
13396                 }
13397                 node->degree -= 1;
13398         }
13399         colored = color_graph(state, rstate);
13400         if (colored) {
13401                 cgdebug_printf("Coloring %d @%s:%d.%d:", 
13402                         range - rstate->lr,
13403                         range->def->filename, range->def->line, range->def->col);
13404                 cgdebug_flush();
13405                 colored = select_free_color(state, rstate, range);
13406                 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13407         }
13408         return colored;
13409 }
13410
13411 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13412 {
13413         struct live_range *lr;
13414         struct live_range_edge *edge;
13415         struct triple *ins, *first;
13416         char used[MAX_REGISTERS];
13417         first = RHS(state->main_function, 0);
13418         ins = first;
13419         do {
13420                 if (triple_is_def(state, ins)) {
13421                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
13422                                 internal_error(state, ins, 
13423                                         "triple without a live range def");
13424                         }
13425                         lr = rstate->lrd[ins->id].lr;
13426                         if (lr->color == REG_UNSET) {
13427                                 internal_error(state, ins,
13428                                         "triple without a color");
13429                         }
13430                         /* Find the registers used by the edges */
13431                         memset(used, 0, sizeof(used));
13432                         for(edge = lr->edges; edge; edge = edge->next) {
13433                                 if (edge->node->color == REG_UNSET) {
13434                                         internal_error(state, 0,
13435                                                 "live range without a color");
13436                         }
13437                                 reg_fill_used(state, used, edge->node->color);
13438                         }
13439                         if (used[lr->color]) {
13440                                 internal_error(state, ins,
13441                                         "triple with already used color");
13442                         }
13443                 }
13444                 ins = ins->next;
13445         } while(ins != first);
13446 }
13447
13448 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13449 {
13450         struct live_range *lr;
13451         struct triple *first, *ins;
13452         first = RHS(state->main_function, 0);
13453         ins = first;
13454         do {
13455                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13456                         internal_error(state, ins, 
13457                                 "triple without a live range");
13458                 }
13459                 lr = rstate->lrd[ins->id].lr;
13460                 SET_REG(ins->id, lr->color);
13461                 ins = ins->next;
13462         } while (ins != first);
13463 }
13464
13465 static void print_interference_block(
13466         struct compile_state *state, struct block *block, void *arg)
13467
13468 {
13469         struct reg_state *rstate = arg;
13470         struct reg_block *rb;
13471         struct triple *ptr;
13472         int phi_present;
13473         int done;
13474         rb = &rstate->blocks[block->vertex];
13475
13476         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
13477                 block, 
13478                 block->vertex,
13479                 block->left, 
13480                 block->left && block->left->use?block->left->use->member : 0,
13481                 block->right, 
13482                 block->right && block->right->use?block->right->use->member : 0);
13483         if (rb->in) {
13484                 struct triple_reg_set *in_set;
13485                 printf("        in:");
13486                 for(in_set = rb->in; in_set; in_set = in_set->next) {
13487                         printf(" %-10p", in_set->member);
13488                 }
13489                 printf("\n");
13490         }
13491         phi_present = 0;
13492         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13493                 done = (ptr == block->last);
13494                 if (ptr->op == OP_PHI) {
13495                         phi_present = 1;
13496                         break;
13497                 }
13498         }
13499         if (phi_present) {
13500                 int edge;
13501                 for(edge = 0; edge < block->users; edge++) {
13502                         printf("     in(%d):", edge);
13503                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13504                                 struct triple **slot;
13505                                 done = (ptr == block->last);
13506                                 if (ptr->op != OP_PHI) {
13507                                         continue;
13508                                 }
13509                                 slot = &RHS(ptr, 0);
13510                                 printf(" %-10p", slot[edge]);
13511                         }
13512                         printf("\n");
13513                 }
13514         }
13515         if (block->first->op == OP_LABEL) {
13516                 printf("%p:\n", block->first);
13517         }
13518         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13519                 struct triple_set *user;
13520                 struct live_range *lr;
13521                 unsigned id;
13522                 int op;
13523                 op = ptr->op;
13524                 done = (ptr == block->last);
13525                 lr = rstate->lrd[ptr->id].lr;
13526                 
13527                 if (triple_stores_block(state, ptr)) {
13528                         if (ptr->u.block != block) {
13529                                 internal_error(state, ptr, 
13530                                         "Wrong block pointer: %p",
13531                                         ptr->u.block);
13532                         }
13533                 }
13534                 if (op == OP_ADECL) {
13535                         for(user = ptr->use; user; user = user->next) {
13536                                 if (!user->member->u.block) {
13537                                         internal_error(state, user->member, 
13538                                                 "Use %p not in a block?",
13539                                                 user->member);
13540                                 }
13541                                 
13542                         }
13543                 }
13544                 id = ptr->id;
13545                 ptr->id = rstate->lrd[id].orig_id;
13546                 SET_REG(ptr->id, lr->color);
13547                 display_triple(stdout, ptr);
13548                 ptr->id = id;
13549
13550                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
13551                         internal_error(state, ptr, "lr has no defs!");
13552                 }
13553
13554                 if (lr->defs) {
13555                         struct live_range_def *lrd;
13556                         printf("       range:");
13557                         lrd = lr->defs;
13558                         do {
13559                                 printf(" %-10p", lrd->def);
13560                                 lrd = lrd->next;
13561                         } while(lrd != lr->defs);
13562                         printf("\n");
13563                 }
13564                 if (lr->edges > 0) {
13565                         struct live_range_edge *edge;
13566                         printf("       edges:");
13567                         for(edge = lr->edges; edge; edge = edge->next) {
13568                                 struct live_range_def *lrd;
13569                                 lrd = edge->node->defs;
13570                                 do {
13571                                         printf(" %-10p", lrd->def);
13572                                         lrd = lrd->next;
13573                                 } while(lrd != edge->node->defs);
13574                                 printf("|");
13575                         }
13576                         printf("\n");
13577                 }
13578                 /* Do a bunch of sanity checks */
13579                 valid_ins(state, ptr);
13580                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
13581                         internal_error(state, ptr, "Invalid triple id: %d",
13582                                 ptr->id);
13583                 }
13584                 for(user = ptr->use; user; user = user->next) {
13585                         struct triple *use;
13586                         struct live_range *ulr;
13587                         use = user->member;
13588                         valid_ins(state, use);
13589                         if ((use->id < 0) || (use->id > rstate->defs)) {
13590                                 internal_error(state, use, "Invalid triple id: %d",
13591                                         use->id);
13592                         }
13593                         ulr = rstate->lrd[user->member->id].lr;
13594                         if (triple_stores_block(state, user->member) &&
13595                                 !user->member->u.block) {
13596                                 internal_error(state, user->member,
13597                                         "Use %p not in a block?",
13598                                         user->member);
13599                         }
13600                 }
13601         }
13602         if (rb->out) {
13603                 struct triple_reg_set *out_set;
13604                 printf("       out:");
13605                 for(out_set = rb->out; out_set; out_set = out_set->next) {
13606                         printf(" %-10p", out_set->member);
13607                 }
13608                 printf("\n");
13609         }
13610         printf("\n");
13611 }
13612
13613 static struct live_range *merge_sort_lr(
13614         struct live_range *first, struct live_range *last)
13615 {
13616         struct live_range *mid, *join, **join_tail, *pick;
13617         size_t size;
13618         size = (last - first) + 1;
13619         if (size >= 2) {
13620                 mid = first + size/2;
13621                 first = merge_sort_lr(first, mid -1);
13622                 mid   = merge_sort_lr(mid, last);
13623                 
13624                 join = 0;
13625                 join_tail = &join;
13626                 /* merge the two lists */
13627                 while(first && mid) {
13628                         if ((first->degree < mid->degree) ||
13629                                 ((first->degree == mid->degree) &&
13630                                         (first->length < mid->length))) {
13631                                 pick = first;
13632                                 first = first->group_next;
13633                                 if (first) {
13634                                         first->group_prev = 0;
13635                                 }
13636                         }
13637                         else {
13638                                 pick = mid;
13639                                 mid = mid->group_next;
13640                                 if (mid) {
13641                                         mid->group_prev = 0;
13642                                 }
13643                         }
13644                         pick->group_next = 0;
13645                         pick->group_prev = join_tail;
13646                         *join_tail = pick;
13647                         join_tail = &pick->group_next;
13648                 }
13649                 /* Splice the remaining list */
13650                 pick = (first)? first : mid;
13651                 *join_tail = pick;
13652                 if (pick) { 
13653                         pick->group_prev = join_tail;
13654                 }
13655         }
13656         else {
13657                 if (!first->defs) {
13658                         first = 0;
13659                 }
13660                 join = first;
13661         }
13662         return join;
13663 }
13664
13665 static void ids_from_rstate(struct compile_state *state, 
13666         struct reg_state *rstate)
13667 {
13668         struct triple *ins, *first;
13669         if (!rstate->defs) {
13670                 return;
13671         }
13672         /* Display the graph if desired */
13673         if (state->debug & DEBUG_INTERFERENCE) {
13674                 print_blocks(state, stdout);
13675                 print_control_flow(state);
13676         }
13677         first = RHS(state->main_function, 0);
13678         ins = first;
13679         do {
13680                 if (ins->id) {
13681                         struct live_range_def *lrd;
13682                         lrd = &rstate->lrd[ins->id];
13683                         ins->id = lrd->orig_id;
13684                 }
13685                 ins = ins->next;
13686         } while(ins != first);
13687 }
13688
13689 static void cleanup_live_edges(struct reg_state *rstate)
13690 {
13691         int i;
13692         /* Free the edges on each node */
13693         for(i = 1; i <= rstate->ranges; i++) {
13694                 remove_live_edges(rstate, &rstate->lr[i]);
13695         }
13696 }
13697
13698 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13699 {
13700         cleanup_live_edges(rstate);
13701         xfree(rstate->lrd);
13702         xfree(rstate->lr);
13703
13704         /* Free the variable lifetime information */
13705         if (rstate->blocks) {
13706                 free_variable_lifetimes(state, rstate->blocks);
13707         }
13708         rstate->defs = 0;
13709         rstate->ranges = 0;
13710         rstate->lrd = 0;
13711         rstate->lr = 0;
13712         rstate->blocks = 0;
13713 }
13714
13715 static void verify_consistency(struct compile_state *state);
13716 static void allocate_registers(struct compile_state *state)
13717 {
13718         struct reg_state rstate;
13719         int colored;
13720
13721         /* Clear out the reg_state */
13722         memset(&rstate, 0, sizeof(rstate));
13723         rstate.max_passes = MAX_ALLOCATION_PASSES;
13724
13725         do {
13726                 struct live_range **point, **next;
13727                 int tangles;
13728                 int coalesced;
13729
13730 #if 0
13731                 fprintf(stderr, "pass: %d\n", rstate.passes);
13732 #endif
13733
13734                 /* Restore ids */
13735                 ids_from_rstate(state, &rstate);
13736
13737                 /* Cleanup the temporary data structures */
13738                 cleanup_rstate(state, &rstate);
13739
13740                 /* Compute the variable lifetimes */
13741                 rstate.blocks = compute_variable_lifetimes(state);
13742
13743                 /* Fix invalid mandatory live range coalesce conflicts */
13744                 walk_variable_lifetimes(
13745                         state, rstate.blocks, fix_coalesce_conflicts, 0);
13746
13747                 /* Fix two simultaneous uses of the same register.
13748                  * In a few pathlogical cases a partial untangle moves
13749                  * the tangle to a part of the graph we won't revisit.
13750                  * So we keep looping until we have no more tangle fixes
13751                  * to apply.
13752                  */
13753                 do {
13754                         tangles = correct_tangles(state, rstate.blocks);
13755                 } while(tangles);
13756
13757                 if (state->debug & DEBUG_INSERTED_COPIES) {
13758                         printf("After resolve_tangles\n");
13759                         print_blocks(state, stdout);
13760                         print_control_flow(state);
13761                 }
13762                 verify_consistency(state);
13763                 
13764                 /* Allocate and initialize the live ranges */
13765                 initialize_live_ranges(state, &rstate);
13766
13767                 /* Note current doing coalescing in a loop appears to 
13768                  * buys me nothing.  The code is left this way in case
13769                  * there is some value in it.  Or if a future bugfix
13770                  *  yields some benefit.
13771                  */
13772                 do {
13773 #if 0
13774                         fprintf(stderr, "coalescing\n");
13775 #endif                  
13776                         /* Remove any previous live edge calculations */
13777                         cleanup_live_edges(&rstate);
13778
13779                         /* Compute the interference graph */
13780                         walk_variable_lifetimes(
13781                                 state, rstate.blocks, graph_ins, &rstate);
13782                         
13783                         /* Display the interference graph if desired */
13784                         if (state->debug & DEBUG_INTERFERENCE) {
13785                                 printf("\nlive variables by block\n");
13786                                 walk_blocks(state, print_interference_block, &rstate);
13787                                 printf("\nlive variables by instruction\n");
13788                                 walk_variable_lifetimes(
13789                                         state, rstate.blocks, 
13790                                         print_interference_ins, &rstate);
13791                         }
13792                         
13793                         coalesced = coalesce_live_ranges(state, &rstate);
13794
13795 #if 0
13796                         fprintf(stderr, "coalesced: %d\n", coalesced);
13797 #endif
13798                 } while(coalesced);
13799
13800 #if DEBUG_CONSISTENCY > 1
13801 # if 0
13802                 fprintf(stderr, "verify_graph_ins...\n");
13803 # endif
13804                 /* Verify the interference graph */
13805                 walk_variable_lifetimes(
13806                         state, rstate.blocks, verify_graph_ins, &rstate);
13807 # if 0
13808                 fprintf(stderr, "verify_graph_ins done\n");
13809 #endif
13810 #endif
13811                         
13812                 /* Build the groups low and high.  But with the nodes
13813                  * first sorted by degree order.
13814                  */
13815                 rstate.low_tail  = &rstate.low;
13816                 rstate.high_tail = &rstate.high;
13817                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13818                 if (rstate.high) {
13819                         rstate.high->group_prev = &rstate.high;
13820                 }
13821                 for(point = &rstate.high; *point; point = &(*point)->group_next)
13822                         ;
13823                 rstate.high_tail = point;
13824                 /* Walk through the high list and move everything that needs
13825                  * to be onto low.
13826                  */
13827                 for(point = &rstate.high; *point; point = next) {
13828                         struct live_range *range;
13829                         next = &(*point)->group_next;
13830                         range = *point;
13831                         
13832                         /* If it has a low degree or it already has a color
13833                          * place the node in low.
13834                          */
13835                         if ((range->degree < regc_max_size(state, range->classes)) ||
13836                                 (range->color != REG_UNSET)) {
13837                                 cgdebug_printf("Lo: %5d degree %5d%s\n", 
13838                                         range - rstate.lr, range->degree,
13839                                         (range->color != REG_UNSET) ? " (colored)": "");
13840                                 *range->group_prev = range->group_next;
13841                                 if (range->group_next) {
13842                                         range->group_next->group_prev = range->group_prev;
13843                                 }
13844                                 if (&range->group_next == rstate.high_tail) {
13845                                         rstate.high_tail = range->group_prev;
13846                                 }
13847                                 range->group_prev  = rstate.low_tail;
13848                                 range->group_next  = 0;
13849                                 *rstate.low_tail   = range;
13850                                 rstate.low_tail    = &range->group_next;
13851                                 next = point;
13852                         }
13853                         else {
13854                                 cgdebug_printf("hi: %5d degree %5d%s\n", 
13855                                         range - rstate.lr, range->degree,
13856                                         (range->color != REG_UNSET) ? " (colored)": "");
13857                         }
13858                 }
13859                 /* Color the live_ranges */
13860                 colored = color_graph(state, &rstate);
13861                 rstate.passes++;
13862         } while (!colored);
13863
13864         /* Verify the graph was properly colored */
13865         verify_colors(state, &rstate);
13866
13867         /* Move the colors from the graph to the triples */
13868         color_triples(state, &rstate);
13869
13870         /* Cleanup the temporary data structures */
13871         cleanup_rstate(state, &rstate);
13872 }
13873
13874 /* Sparce Conditional Constant Propogation
13875  * =========================================
13876  */
13877 struct ssa_edge;
13878 struct flow_block;
13879 struct lattice_node {
13880         unsigned old_id;
13881         struct triple *def;
13882         struct ssa_edge *out;
13883         struct flow_block *fblock;
13884         struct triple *val;
13885         /* lattice high   val && !is_const(val) 
13886          * lattice const  is_const(val)
13887          * lattice low    val == 0
13888          */
13889 };
13890 struct ssa_edge {
13891         struct lattice_node *src;
13892         struct lattice_node *dst;
13893         struct ssa_edge *work_next;
13894         struct ssa_edge *work_prev;
13895         struct ssa_edge *out_next;
13896 };
13897 struct flow_edge {
13898         struct flow_block *src;
13899         struct flow_block *dst;
13900         struct flow_edge *work_next;
13901         struct flow_edge *work_prev;
13902         struct flow_edge *in_next;
13903         struct flow_edge *out_next;
13904         int executable;
13905 };
13906 struct flow_block {
13907         struct block *block;
13908         struct flow_edge *in;
13909         struct flow_edge *out;
13910         struct flow_edge left, right;
13911 };
13912
13913 struct scc_state {
13914         int ins_count;
13915         struct lattice_node *lattice;
13916         struct ssa_edge     *ssa_edges;
13917         struct flow_block   *flow_blocks;
13918         struct flow_edge    *flow_work_list;
13919         struct ssa_edge     *ssa_work_list;
13920 };
13921
13922
13923 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
13924         struct flow_edge *fedge)
13925 {
13926         if (!scc->flow_work_list) {
13927                 scc->flow_work_list = fedge;
13928                 fedge->work_next = fedge->work_prev = fedge;
13929         }
13930         else {
13931                 struct flow_edge *ftail;
13932                 ftail = scc->flow_work_list->work_prev;
13933                 fedge->work_next = ftail->work_next;
13934                 fedge->work_prev = ftail;
13935                 fedge->work_next->work_prev = fedge;
13936                 fedge->work_prev->work_next = fedge;
13937         }
13938 }
13939
13940 static struct flow_edge *scc_next_fedge(
13941         struct compile_state *state, struct scc_state *scc)
13942 {
13943         struct flow_edge *fedge;
13944         fedge = scc->flow_work_list;
13945         if (fedge) {
13946                 fedge->work_next->work_prev = fedge->work_prev;
13947                 fedge->work_prev->work_next = fedge->work_next;
13948                 if (fedge->work_next != fedge) {
13949                         scc->flow_work_list = fedge->work_next;
13950                 } else {
13951                         scc->flow_work_list = 0;
13952                 }
13953         }
13954         return fedge;
13955 }
13956
13957 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13958         struct ssa_edge *sedge)
13959 {
13960         if (!scc->ssa_work_list) {
13961                 scc->ssa_work_list = sedge;
13962                 sedge->work_next = sedge->work_prev = sedge;
13963         }
13964         else {
13965                 struct ssa_edge *stail;
13966                 stail = scc->ssa_work_list->work_prev;
13967                 sedge->work_next = stail->work_next;
13968                 sedge->work_prev = stail;
13969                 sedge->work_next->work_prev = sedge;
13970                 sedge->work_prev->work_next = sedge;
13971         }
13972 }
13973
13974 static struct ssa_edge *scc_next_sedge(
13975         struct compile_state *state, struct scc_state *scc)
13976 {
13977         struct ssa_edge *sedge;
13978         sedge = scc->ssa_work_list;
13979         if (sedge) {
13980                 sedge->work_next->work_prev = sedge->work_prev;
13981                 sedge->work_prev->work_next = sedge->work_next;
13982                 if (sedge->work_next != sedge) {
13983                         scc->ssa_work_list = sedge->work_next;
13984                 } else {
13985                         scc->ssa_work_list = 0;
13986                 }
13987         }
13988         return sedge;
13989 }
13990
13991 static void initialize_scc_state(
13992         struct compile_state *state, struct scc_state *scc)
13993 {
13994         int ins_count, ssa_edge_count;
13995         int ins_index, ssa_edge_index, fblock_index;
13996         struct triple *first, *ins;
13997         struct block *block;
13998         struct flow_block *fblock;
13999
14000         memset(scc, 0, sizeof(*scc));
14001
14002         /* Inialize pass zero find out how much memory we need */
14003         first = RHS(state->main_function, 0);
14004         ins = first;
14005         ins_count = ssa_edge_count = 0;
14006         do {
14007                 struct triple_set *edge;
14008                 ins_count += 1;
14009                 for(edge = ins->use; edge; edge = edge->next) {
14010                         ssa_edge_count++;
14011                 }
14012                 ins = ins->next;
14013         } while(ins != first);
14014 #if DEBUG_SCC
14015         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
14016                 ins_count, ssa_edge_count, state->last_vertex);
14017 #endif
14018         scc->ins_count   = ins_count;
14019         scc->lattice     = 
14020                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
14021         scc->ssa_edges   = 
14022                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
14023         scc->flow_blocks = 
14024                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
14025                         "flow_blocks");
14026
14027         /* Initialize pass one collect up the nodes */
14028         fblock = 0;
14029         block = 0;
14030         ins_index = ssa_edge_index = fblock_index = 0;
14031         ins = first;
14032         do {
14033                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14034                         block = ins->u.block;
14035                         if (!block) {
14036                                 internal_error(state, ins, "label without block");
14037                         }
14038                         fblock_index += 1;
14039                         block->vertex = fblock_index;
14040                         fblock = &scc->flow_blocks[fblock_index];
14041                         fblock->block = block;
14042                 }
14043                 {
14044                         struct lattice_node *lnode;
14045                         ins_index += 1;
14046                         lnode = &scc->lattice[ins_index];
14047                         lnode->def = ins;
14048                         lnode->out = 0;
14049                         lnode->fblock = fblock;
14050                         lnode->val = ins; /* LATTICE HIGH */
14051                         lnode->old_id = ins->id;
14052                         ins->id = ins_index;
14053                 }
14054                 ins = ins->next;
14055         } while(ins != first);
14056         /* Initialize pass two collect up the edges */
14057         block = 0;
14058         fblock = 0;
14059         ins = first;
14060         do {
14061                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14062                         struct flow_edge *fedge, **ftail;
14063                         struct block_set *bedge;
14064                         block = ins->u.block;
14065                         fblock = &scc->flow_blocks[block->vertex];
14066                         fblock->in = 0;
14067                         fblock->out = 0;
14068                         ftail = &fblock->out;
14069                         if (block->left) {
14070                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
14071                                 if (fblock->left.dst->block != block->left) {
14072                                         internal_error(state, 0, "block mismatch");
14073                                 }
14074                                 fblock->left.out_next = 0;
14075                                 *ftail = &fblock->left;
14076                                 ftail = &fblock->left.out_next;
14077                         }
14078                         if (block->right) {
14079                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
14080                                 if (fblock->right.dst->block != block->right) {
14081                                         internal_error(state, 0, "block mismatch");
14082                                 }
14083                                 fblock->right.out_next = 0;
14084                                 *ftail = &fblock->right;
14085                                 ftail = &fblock->right.out_next;
14086                         }
14087                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
14088                                 fedge->src = fblock;
14089                                 fedge->work_next = fedge->work_prev = fedge;
14090                                 fedge->executable = 0;
14091                         }
14092                         ftail = &fblock->in;
14093                         for(bedge = block->use; bedge; bedge = bedge->next) {
14094                                 struct block *src_block;
14095                                 struct flow_block *sfblock;
14096                                 struct flow_edge *sfedge;
14097                                 src_block = bedge->member;
14098                                 sfblock = &scc->flow_blocks[src_block->vertex];
14099                                 sfedge = 0;
14100                                 if (src_block->left == block) {
14101                                         sfedge = &sfblock->left;
14102                                 } else {
14103                                         sfedge = &sfblock->right;
14104                                 }
14105                                 *ftail = sfedge;
14106                                 ftail = &sfedge->in_next;
14107                                 sfedge->in_next = 0;
14108                         }
14109                 }
14110                 {
14111                         struct triple_set *edge;
14112                         struct ssa_edge **stail;
14113                         struct lattice_node *lnode;
14114                         lnode = &scc->lattice[ins->id];
14115                         lnode->out = 0;
14116                         stail = &lnode->out;
14117                         for(edge = ins->use; edge; edge = edge->next) {
14118                                 struct ssa_edge *sedge;
14119                                 ssa_edge_index += 1;
14120                                 sedge = &scc->ssa_edges[ssa_edge_index];
14121                                 *stail = sedge;
14122                                 stail = &sedge->out_next;
14123                                 sedge->src = lnode;
14124                                 sedge->dst = &scc->lattice[edge->member->id];
14125                                 sedge->work_next = sedge->work_prev = sedge;
14126                                 sedge->out_next = 0;
14127                         }
14128                 }
14129                 ins = ins->next;
14130         } while(ins != first);
14131         /* Setup a dummy block 0 as a node above the start node */
14132         {
14133                 struct flow_block *fblock, *dst;
14134                 struct flow_edge *fedge;
14135                 fblock = &scc->flow_blocks[0];
14136                 fblock->block = 0;
14137                 fblock->in = 0;
14138                 fblock->out = &fblock->left;
14139                 dst = &scc->flow_blocks[state->first_block->vertex];
14140                 fedge = &fblock->left;
14141                 fedge->src        = fblock;
14142                 fedge->dst        = dst;
14143                 fedge->work_next  = fedge;
14144                 fedge->work_prev  = fedge;
14145                 fedge->in_next    = fedge->dst->in;
14146                 fedge->out_next   = 0;
14147                 fedge->executable = 0;
14148                 fedge->dst->in = fedge;
14149                 
14150                 /* Initialize the work lists */
14151                 scc->flow_work_list = 0;
14152                 scc->ssa_work_list  = 0;
14153                 scc_add_fedge(state, scc, fedge);
14154         }
14155 #if DEBUG_SCC
14156         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14157                 ins_index, ssa_edge_index, fblock_index);
14158 #endif
14159 }
14160
14161         
14162 static void free_scc_state(
14163         struct compile_state *state, struct scc_state *scc)
14164 {
14165         xfree(scc->flow_blocks);
14166         xfree(scc->ssa_edges);
14167         xfree(scc->lattice);
14168         
14169 }
14170
14171 static struct lattice_node *triple_to_lattice(
14172         struct compile_state *state, struct scc_state *scc, struct triple *ins)
14173 {
14174         if (ins->id <= 0) {
14175                 internal_error(state, ins, "bad id");
14176         }
14177         return &scc->lattice[ins->id];
14178 }
14179
14180 static struct triple *preserve_lval(
14181         struct compile_state *state, struct lattice_node *lnode)
14182 {
14183         struct triple *old;
14184         /* Preserve the original value */
14185         if (lnode->val) {
14186                 old = dup_triple(state, lnode->val);
14187                 if (lnode->val != lnode->def) {
14188                         xfree(lnode->val);
14189                 }
14190                 lnode->val = 0;
14191         } else {
14192                 old = 0;
14193         }
14194         return old;
14195 }
14196
14197 static int lval_changed(struct compile_state *state, 
14198         struct triple *old, struct lattice_node *lnode)
14199 {
14200         int changed;
14201         /* See if the lattice value has changed */
14202         changed = 1;
14203         if (!old && !lnode->val) {
14204                 changed = 0;
14205         }
14206         if (changed && lnode->val && !is_const(lnode->val)) {
14207                 changed = 0;
14208         }
14209         if (changed &&
14210                 lnode->val && old &&
14211                 (memcmp(lnode->val->param, old->param,
14212                         TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14213                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14214                 changed = 0;
14215         }
14216         if (old) {
14217                 xfree(old);
14218         }
14219         return changed;
14220
14221 }
14222
14223 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
14224         struct lattice_node *lnode)
14225 {
14226         struct lattice_node *tmp;
14227         struct triple **slot, *old;
14228         struct flow_edge *fedge;
14229         int index;
14230         if (lnode->def->op != OP_PHI) {
14231                 internal_error(state, lnode->def, "not phi");
14232         }
14233         /* Store the original value */
14234         old = preserve_lval(state, lnode);
14235
14236         /* default to lattice high */
14237         lnode->val = lnode->def;
14238         slot = &RHS(lnode->def, 0);
14239         index = 0;
14240         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14241                 if (!fedge->executable) {
14242                         continue;
14243                 }
14244                 if (!slot[index]) {
14245                         internal_error(state, lnode->def, "no phi value");
14246                 }
14247                 tmp = triple_to_lattice(state, scc, slot[index]);
14248                 /* meet(X, lattice low) = lattice low */
14249                 if (!tmp->val) {
14250                         lnode->val = 0;
14251                 }
14252                 /* meet(X, lattice high) = X */
14253                 else if (!tmp->val) {
14254                         lnode->val = lnode->val;
14255                 }
14256                 /* meet(lattice high, X) = X */
14257                 else if (!is_const(lnode->val)) {
14258                         lnode->val = dup_triple(state, tmp->val);
14259                         lnode->val->type = lnode->def->type;
14260                 }
14261                 /* meet(const, const) = const or lattice low */
14262                 else if (!constants_equal(state, lnode->val, tmp->val)) {
14263                         lnode->val = 0;
14264                 }
14265                 if (!lnode->val) {
14266                         break;
14267                 }
14268         }
14269 #if DEBUG_SCC
14270         fprintf(stderr, "phi: %d -> %s\n",
14271                 lnode->def->id,
14272                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14273 #endif
14274         /* If the lattice value has changed update the work lists. */
14275         if (lval_changed(state, old, lnode)) {
14276                 struct ssa_edge *sedge;
14277                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14278                         scc_add_sedge(state, scc, sedge);
14279                 }
14280         }
14281 }
14282
14283 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14284         struct lattice_node *lnode)
14285 {
14286         int changed;
14287         struct triple *old, *scratch;
14288         struct triple **dexpr, **vexpr;
14289         int count, i;
14290         
14291         /* Store the original value */
14292         old = preserve_lval(state, lnode);
14293
14294         /* Reinitialize the value */
14295         lnode->val = scratch = dup_triple(state, lnode->def);
14296         scratch->id = lnode->old_id;
14297         scratch->next     = scratch;
14298         scratch->prev     = scratch;
14299         scratch->use      = 0;
14300
14301         count = TRIPLE_SIZE(scratch->sizes);
14302         for(i = 0; i < count; i++) {
14303                 dexpr = &lnode->def->param[i];
14304                 vexpr = &scratch->param[i];
14305                 *vexpr = *dexpr;
14306                 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14307                         (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14308                         *dexpr) {
14309                         struct lattice_node *tmp;
14310                         tmp = triple_to_lattice(state, scc, *dexpr);
14311                         *vexpr = (tmp->val)? tmp->val : tmp->def;
14312                 }
14313         }
14314         if (scratch->op == OP_BRANCH) {
14315                 scratch->next = lnode->def->next;
14316         }
14317         /* Recompute the value */
14318 #warning "FIXME see if simplify does anything bad"
14319         /* So far it looks like only the strength reduction
14320          * optimization are things I need to worry about.
14321          */
14322         simplify(state, scratch);
14323         /* Cleanup my value */
14324         if (scratch->use) {
14325                 internal_error(state, lnode->def, "scratch used?");
14326         }
14327         if ((scratch->prev != scratch) ||
14328                 ((scratch->next != scratch) &&
14329                         ((lnode->def->op != OP_BRANCH) ||
14330                                 (scratch->next != lnode->def->next)))) {
14331                 internal_error(state, lnode->def, "scratch in list?");
14332         }
14333         /* undo any uses... */
14334         count = TRIPLE_SIZE(scratch->sizes);
14335         for(i = 0; i < count; i++) {
14336                 vexpr = &scratch->param[i];
14337                 if (*vexpr) {
14338                         unuse_triple(*vexpr, scratch);
14339                 }
14340         }
14341         if (!is_const(scratch)) {
14342                 for(i = 0; i < count; i++) {
14343                         dexpr = &lnode->def->param[i];
14344                         if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14345                                 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14346                                 *dexpr) {
14347                                 struct lattice_node *tmp;
14348                                 tmp = triple_to_lattice(state, scc, *dexpr);
14349                                 if (!tmp->val) {
14350                                         lnode->val = 0;
14351                                 }
14352                         }
14353                 }
14354         }
14355         if (lnode->val && 
14356                 (lnode->val->op == lnode->def->op) &&
14357                 (memcmp(lnode->val->param, lnode->def->param, 
14358                         count * sizeof(lnode->val->param[0])) == 0) &&
14359                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14360                 lnode->val = lnode->def;
14361         }
14362         /* Find the cases that are always lattice lo */
14363         if (lnode->val && 
14364                 triple_is_def(state, lnode->val) &&
14365                 !triple_is_pure(state, lnode->val)) {
14366                 lnode->val = 0;
14367         }
14368         if (lnode->val && 
14369                 (lnode->val->op == OP_SDECL) && 
14370                 (lnode->val != lnode->def)) {
14371                 internal_error(state, lnode->def, "bad sdecl");
14372         }
14373         /* See if the lattice value has changed */
14374         changed = lval_changed(state, old, lnode);
14375         if (lnode->val != scratch) {
14376                 xfree(scratch);
14377         }
14378         return changed;
14379 }
14380
14381 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14382         struct lattice_node *lnode)
14383 {
14384         struct lattice_node *cond;
14385 #if DEBUG_SCC
14386         {
14387                 struct flow_edge *fedge;
14388                 fprintf(stderr, "branch: %d (",
14389                         lnode->def->id);
14390                 
14391                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14392                         fprintf(stderr, " %d", fedge->dst->block->vertex);
14393                 }
14394                 fprintf(stderr, " )");
14395                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14396                         fprintf(stderr, " <- %d",
14397                                 RHS(lnode->def, 0)->id);
14398                 }
14399                 fprintf(stderr, "\n");
14400         }
14401 #endif
14402         if (lnode->def->op != OP_BRANCH) {
14403                 internal_error(state, lnode->def, "not branch");
14404         }
14405         /* This only applies to conditional branches */
14406         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14407                 return;
14408         }
14409         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14410         if (cond->val && !is_const(cond->val)) {
14411 #warning "FIXME do I need to do something here?"
14412                 warning(state, cond->def, "condition not constant?");
14413                 return;
14414         }
14415         if (cond->val == 0) {
14416                 scc_add_fedge(state, scc, cond->fblock->out);
14417                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14418         }
14419         else if (cond->val->u.cval) {
14420                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14421                 
14422         } else {
14423                 scc_add_fedge(state, scc, cond->fblock->out);
14424         }
14425
14426 }
14427
14428 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14429         struct lattice_node *lnode)
14430 {
14431         int changed;
14432
14433         changed = compute_lnode_val(state, scc, lnode);
14434 #if DEBUG_SCC
14435         {
14436                 struct triple **expr;
14437                 fprintf(stderr, "expr: %3d %10s (",
14438                         lnode->def->id, tops(lnode->def->op));
14439                 expr = triple_rhs(state, lnode->def, 0);
14440                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14441                         if (*expr) {
14442                                 fprintf(stderr, " %d", (*expr)->id);
14443                         }
14444                 }
14445                 fprintf(stderr, " ) -> %s\n",
14446                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14447         }
14448 #endif
14449         if (lnode->def->op == OP_BRANCH) {
14450                 scc_visit_branch(state, scc, lnode);
14451
14452         }
14453         else if (changed) {
14454                 struct ssa_edge *sedge;
14455                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14456                         scc_add_sedge(state, scc, sedge);
14457                 }
14458         }
14459 }
14460
14461 static void scc_writeback_values(
14462         struct compile_state *state, struct scc_state *scc)
14463 {
14464         struct triple *first, *ins;
14465         first = RHS(state->main_function, 0);
14466         ins = first;
14467         do {
14468                 struct lattice_node *lnode;
14469                 lnode = triple_to_lattice(state, scc, ins);
14470                 /* Restore id */
14471                 ins->id = lnode->old_id;
14472 #if DEBUG_SCC
14473                 if (lnode->val && !is_const(lnode->val)) {
14474                         warning(state, lnode->def, 
14475                                 "lattice node still high?");
14476                 }
14477 #endif
14478                 if (lnode->val && (lnode->val != ins)) {
14479                         /* See if it something I know how to write back */
14480                         switch(lnode->val->op) {
14481                         case OP_INTCONST:
14482                                 mkconst(state, ins, lnode->val->u.cval);
14483                                 break;
14484                         case OP_ADDRCONST:
14485                                 mkaddr_const(state, ins, 
14486                                         MISC(lnode->val, 0), lnode->val->u.cval);
14487                                 break;
14488                         default:
14489                                 /* By default don't copy the changes,
14490                                  * recompute them in place instead.
14491                                  */
14492                                 simplify(state, ins);
14493                                 break;
14494                         }
14495                         if (is_const(lnode->val) &&
14496                                 !constants_equal(state, lnode->val, ins)) {
14497                                 internal_error(state, 0, "constants not equal");
14498                         }
14499                         /* Free the lattice nodes */
14500                         xfree(lnode->val);
14501                         lnode->val = 0;
14502                 }
14503                 ins = ins->next;
14504         } while(ins != first);
14505 }
14506
14507 static void scc_transform(struct compile_state *state)
14508 {
14509         struct scc_state scc;
14510
14511         initialize_scc_state(state, &scc);
14512
14513         while(scc.flow_work_list || scc.ssa_work_list) {
14514                 struct flow_edge *fedge;
14515                 struct ssa_edge *sedge;
14516                 struct flow_edge *fptr;
14517                 while((fedge = scc_next_fedge(state, &scc))) {
14518                         struct block *block;
14519                         struct triple *ptr;
14520                         struct flow_block *fblock;
14521                         int time;
14522                         int done;
14523                         if (fedge->executable) {
14524                                 continue;
14525                         }
14526                         if (!fedge->dst) {
14527                                 internal_error(state, 0, "fedge without dst");
14528                         }
14529                         if (!fedge->src) {
14530                                 internal_error(state, 0, "fedge without src");
14531                         }
14532                         fedge->executable = 1;
14533                         fblock = fedge->dst;
14534                         block = fblock->block;
14535                         time = 0;
14536                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14537                                 if (fptr->executable) {
14538                                         time++;
14539                                 }
14540                         }
14541 #if DEBUG_SCC
14542                         fprintf(stderr, "vertex: %d time: %d\n", 
14543                                 block->vertex, time);
14544                         
14545 #endif
14546                         done = 0;
14547                         for(ptr = block->first; !done; ptr = ptr->next) {
14548                                 struct lattice_node *lnode;
14549                                 done = (ptr == block->last);
14550                                 lnode = &scc.lattice[ptr->id];
14551                                 if (ptr->op == OP_PHI) {
14552                                         scc_visit_phi(state, &scc, lnode);
14553                                 }
14554                                 else if (time == 1) {
14555                                         scc_visit_expr(state, &scc, lnode);
14556                                 }
14557                         }
14558                         if (fblock->out && !fblock->out->out_next) {
14559                                 scc_add_fedge(state, &scc, fblock->out);
14560                         }
14561                 }
14562                 while((sedge = scc_next_sedge(state, &scc))) {
14563                         struct lattice_node *lnode;
14564                         struct flow_block *fblock;
14565                         lnode = sedge->dst;
14566                         fblock = lnode->fblock;
14567 #if DEBUG_SCC
14568                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14569                                 sedge - scc.ssa_edges,
14570                                 sedge->src->def->id,
14571                                 sedge->dst->def->id);
14572 #endif
14573                         if (lnode->def->op == OP_PHI) {
14574                                 scc_visit_phi(state, &scc, lnode);
14575                         }
14576                         else {
14577                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14578                                         if (fptr->executable) {
14579                                                 break;
14580                                         }
14581                                 }
14582                                 if (fptr) {
14583                                         scc_visit_expr(state, &scc, lnode);
14584                                 }
14585                         }
14586                 }
14587         }
14588         
14589         scc_writeback_values(state, &scc);
14590         free_scc_state(state, &scc);
14591 }
14592
14593
14594 static void transform_to_arch_instructions(struct compile_state *state)
14595 {
14596         struct triple *ins, *first;
14597         first = RHS(state->main_function, 0);
14598         ins = first;
14599         do {
14600                 ins = transform_to_arch_instruction(state, ins);
14601         } while(ins != first);
14602 }
14603
14604 #if DEBUG_CONSISTENCY
14605 static void verify_uses(struct compile_state *state)
14606 {
14607         struct triple *first, *ins;
14608         struct triple_set *set;
14609         first = RHS(state->main_function, 0);
14610         ins = first;
14611         do {
14612                 struct triple **expr;
14613                 expr = triple_rhs(state, ins, 0);
14614                 for(; expr; expr = triple_rhs(state, ins, expr)) {
14615                         struct triple *rhs;
14616                         rhs = *expr;
14617                         for(set = rhs?rhs->use:0; set; set = set->next) {
14618                                 if (set->member == ins) {
14619                                         break;
14620                                 }
14621                         }
14622                         if (!set) {
14623                                 internal_error(state, ins, "rhs not used");
14624                         }
14625                 }
14626                 expr = triple_lhs(state, ins, 0);
14627                 for(; expr; expr = triple_lhs(state, ins, expr)) {
14628                         struct triple *lhs;
14629                         lhs = *expr;
14630                         for(set =  lhs?lhs->use:0; set; set = set->next) {
14631                                 if (set->member == ins) {
14632                                         break;
14633                                 }
14634                         }
14635                         if (!set) {
14636                                 internal_error(state, ins, "lhs not used");
14637                         }
14638                 }
14639                 ins = ins->next;
14640         } while(ins != first);
14641         
14642 }
14643 static void verify_blocks(struct compile_state *state)
14644 {
14645         struct triple *ins;
14646         struct block *block;
14647         block = state->first_block;
14648         if (!block) {
14649                 return;
14650         }
14651         do {
14652                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14653                         if (!triple_stores_block(state, ins)) {
14654                                 continue;
14655                         }
14656                         if (ins->u.block != block) {
14657                                 internal_error(state, ins, "inconsitent block specified");
14658                         }
14659                 }
14660                 if (!triple_stores_block(state, block->last->next)) {
14661                         internal_error(state, block->last->next, 
14662                                 "cannot find next block");
14663                 }
14664                 block = block->last->next->u.block;
14665                 if (!block) {
14666                         internal_error(state, block->last->next,
14667                                 "bad next block");
14668                 }
14669         } while(block != state->first_block);
14670 }
14671
14672 static void verify_domination(struct compile_state *state)
14673 {
14674         struct triple *first, *ins;
14675         struct triple_set *set;
14676         if (!state->first_block) {
14677                 return;
14678         }
14679         
14680         first = RHS(state->main_function, 0);
14681         ins = first;
14682         do {
14683                 for(set = ins->use; set; set = set->next) {
14684                         struct triple **expr;
14685                         if (set->member->op == OP_PHI) {
14686                                 continue;
14687                         }
14688                         /* See if the use is on the righ hand side */
14689                         expr = triple_rhs(state, set->member, 0);
14690                         for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14691                                 if (*expr == ins) {
14692                                         break;
14693                                 }
14694                         }
14695                         if (expr &&
14696                                 !tdominates(state, ins, set->member)) {
14697                                 internal_error(state, set->member, 
14698                                         "non dominated rhs use?");
14699                         }
14700                 }
14701                 ins = ins->next;
14702         } while(ins != first);
14703 }
14704
14705 static void verify_piece(struct compile_state *state)
14706 {
14707         struct triple *first, *ins;
14708         first = RHS(state->main_function, 0);
14709         ins = first;
14710         do {
14711                 struct triple *ptr;
14712                 int lhs, i;
14713                 lhs = TRIPLE_LHS(ins->sizes);
14714                 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14715                         lhs = 0;
14716                 }
14717                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14718                         if (ptr != LHS(ins, i)) {
14719                                 internal_error(state, ins, "malformed lhs on %s",
14720                                         tops(ins->op));
14721                         }
14722                         if (ptr->op != OP_PIECE) {
14723                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
14724                                         tops(ptr->op), i, tops(ins->op));
14725                         }
14726                         if (ptr->u.cval != i) {
14727                                 internal_error(state, ins, "bad u.cval of %d %d expected",
14728                                         ptr->u.cval, i);
14729                         }
14730                 }
14731                 ins = ins->next;
14732         } while(ins != first);
14733 }
14734 static void verify_ins_colors(struct compile_state *state)
14735 {
14736         struct triple *first, *ins;
14737         
14738         first = RHS(state->main_function, 0);
14739         ins = first;
14740         do {
14741                 ins = ins->next;
14742         } while(ins != first);
14743 }
14744 static void verify_consistency(struct compile_state *state)
14745 {
14746         verify_uses(state);
14747         verify_blocks(state);
14748         verify_domination(state);
14749         verify_piece(state);
14750         verify_ins_colors(state);
14751 }
14752 #else 
14753 static void verify_consistency(struct compile_state *state) {}
14754 #endif /* DEBUG_USES */
14755
14756 static void optimize(struct compile_state *state)
14757 {
14758         if (state->debug & DEBUG_TRIPLES) {
14759                 print_triples(state);
14760         }
14761         /* Replace structures with simpler data types */
14762         flatten_structures(state);
14763         if (state->debug & DEBUG_TRIPLES) {
14764                 print_triples(state);
14765         }
14766         verify_consistency(state);
14767         /* Analize the intermediate code */
14768         setup_basic_blocks(state);
14769         analyze_idominators(state);
14770         analyze_ipdominators(state);
14771         /* Transform the code to ssa form */
14772         transform_to_ssa_form(state);
14773         verify_consistency(state);
14774         if (state->debug & DEBUG_CODE_ELIMINATION) {
14775                 fprintf(stdout, "After transform_to_ssa_form\n");
14776                 print_blocks(state, stdout);
14777         }
14778         /* Do strength reduction and simple constant optimizations */
14779         if (state->optimize >= 1) {
14780                 simplify_all(state);
14781         }
14782         verify_consistency(state);
14783         /* Propogate constants throughout the code */
14784         if (state->optimize >= 2) {
14785 #warning "FIXME fix scc_transform"
14786                 scc_transform(state);
14787                 transform_from_ssa_form(state);
14788                 free_basic_blocks(state);
14789                 setup_basic_blocks(state);
14790                 analyze_idominators(state);
14791                 analyze_ipdominators(state);
14792                 transform_to_ssa_form(state);
14793         }
14794         verify_consistency(state);
14795 #warning "WISHLIST implement single use constants (least possible register pressure)"
14796 #warning "WISHLIST implement induction variable elimination"
14797         /* Select architecture instructions and an initial partial
14798          * coloring based on architecture constraints.
14799          */
14800         transform_to_arch_instructions(state);
14801         verify_consistency(state);
14802         if (state->debug & DEBUG_ARCH_CODE) {
14803                 printf("After transform_to_arch_instructions\n");
14804                 print_blocks(state, stdout);
14805                 print_control_flow(state);
14806         }
14807         eliminate_inefectual_code(state);
14808         verify_consistency(state);
14809         if (state->debug & DEBUG_CODE_ELIMINATION) {
14810                 printf("After eliminate_inefectual_code\n");
14811                 print_blocks(state, stdout);
14812                 print_control_flow(state);
14813         }
14814         verify_consistency(state);
14815         /* Color all of the variables to see if they will fit in registers */
14816         insert_copies_to_phi(state);
14817         if (state->debug & DEBUG_INSERTED_COPIES) {
14818                 printf("After insert_copies_to_phi\n");
14819                 print_blocks(state, stdout);
14820                 print_control_flow(state);
14821         }
14822         verify_consistency(state);
14823         insert_mandatory_copies(state);
14824         if (state->debug & DEBUG_INSERTED_COPIES) {
14825                 printf("After insert_mandatory_copies\n");
14826                 print_blocks(state, stdout);
14827                 print_control_flow(state);
14828         }
14829         verify_consistency(state);
14830         allocate_registers(state);
14831         verify_consistency(state);
14832         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14833                 print_blocks(state, stdout);
14834         }
14835         if (state->debug & DEBUG_CONTROL_FLOW) {
14836                 print_control_flow(state);
14837         }
14838         /* Remove the optimization information.
14839          * This is more to check for memory consistency than to free memory.
14840          */
14841         free_basic_blocks(state);
14842 }
14843
14844 static void print_op_asm(struct compile_state *state,
14845         struct triple *ins, FILE *fp)
14846 {
14847         struct asm_info *info;
14848         const char *ptr;
14849         unsigned lhs, rhs, i;
14850         info = ins->u.ainfo;
14851         lhs = TRIPLE_LHS(ins->sizes);
14852         rhs = TRIPLE_RHS(ins->sizes);
14853         /* Don't count the clobbers in lhs */
14854         for(i = 0; i < lhs; i++) {
14855                 if (LHS(ins, i)->type == &void_type) {
14856                         break;
14857                 }
14858         }
14859         lhs = i;
14860         fprintf(fp, "#ASM\n");
14861         fputc('\t', fp);
14862         for(ptr = info->str; *ptr; ptr++) {
14863                 char *next;
14864                 unsigned long param;
14865                 struct triple *piece;
14866                 if (*ptr != '%') {
14867                         fputc(*ptr, fp);
14868                         continue;
14869                 }
14870                 ptr++;
14871                 if (*ptr == '%') {
14872                         fputc('%', fp);
14873                         continue;
14874                 }
14875                 param = strtoul(ptr, &next, 10);
14876                 if (ptr == next) {
14877                         error(state, ins, "Invalid asm template");
14878                 }
14879                 if (param >= (lhs + rhs)) {
14880                         error(state, ins, "Invalid param %%%u in asm template",
14881                                 param);
14882                 }
14883                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14884                 fprintf(fp, "%s", 
14885                         arch_reg_str(ID_REG(piece->id)));
14886                 ptr = next -1;
14887         }
14888         fprintf(fp, "\n#NOT ASM\n");
14889 }
14890
14891
14892 /* Only use the low x86 byte registers.  This allows me
14893  * allocate the entire register when a byte register is used.
14894  */
14895 #define X86_4_8BIT_GPRS 1
14896
14897 /* Recognized x86 cpu variants */
14898 #define BAD_CPU      0
14899 #define CPU_I386     1
14900 #define CPU_P3       2
14901 #define CPU_P4       3
14902 #define CPU_K7       4
14903 #define CPU_K8       5
14904
14905 #define CPU_DEFAULT  CPU_I386
14906
14907 /* The x86 register classes */
14908 #define REGC_FLAGS    0
14909 #define REGC_GPR8     1
14910 #define REGC_GPR16    2
14911 #define REGC_GPR32    3
14912 #define REGC_GPR64    4
14913 #define REGC_MMX      5
14914 #define REGC_XMM      6
14915 #define REGC_GPR32_8  7
14916 #define REGC_GPR16_8  8
14917 #define REGC_IMM32    9
14918 #define REGC_IMM16   10
14919 #define REGC_IMM8    11
14920 #define LAST_REGC  REGC_IMM8
14921 #if LAST_REGC >= MAX_REGC
14922 #error "MAX_REGC is to low"
14923 #endif
14924
14925 /* Register class masks */
14926 #define REGCM_FLAGS   (1 << REGC_FLAGS)
14927 #define REGCM_GPR8    (1 << REGC_GPR8)
14928 #define REGCM_GPR16   (1 << REGC_GPR16)
14929 #define REGCM_GPR32   (1 << REGC_GPR32)
14930 #define REGCM_GPR64   (1 << REGC_GPR64)
14931 #define REGCM_MMX     (1 << REGC_MMX)
14932 #define REGCM_XMM     (1 << REGC_XMM)
14933 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14934 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14935 #define REGCM_IMM32   (1 << REGC_IMM32)
14936 #define REGCM_IMM16   (1 << REGC_IMM16)
14937 #define REGCM_IMM8    (1 << REGC_IMM8)
14938 #define REGCM_ALL     ((1 << (LAST_REGC + 1)) - 1)
14939
14940 /* The x86 registers */
14941 #define REG_EFLAGS  2
14942 #define REGC_FLAGS_FIRST REG_EFLAGS
14943 #define REGC_FLAGS_LAST  REG_EFLAGS
14944 #define REG_AL      3
14945 #define REG_BL      4
14946 #define REG_CL      5
14947 #define REG_DL      6
14948 #define REG_AH      7
14949 #define REG_BH      8
14950 #define REG_CH      9
14951 #define REG_DH      10
14952 #define REGC_GPR8_FIRST  REG_AL
14953 #if X86_4_8BIT_GPRS
14954 #define REGC_GPR8_LAST   REG_DL
14955 #else 
14956 #define REGC_GPR8_LAST   REG_DH
14957 #endif
14958 #define REG_AX     11
14959 #define REG_BX     12
14960 #define REG_CX     13
14961 #define REG_DX     14
14962 #define REG_SI     15
14963 #define REG_DI     16
14964 #define REG_BP     17
14965 #define REG_SP     18
14966 #define REGC_GPR16_FIRST REG_AX
14967 #define REGC_GPR16_LAST  REG_SP
14968 #define REG_EAX    19
14969 #define REG_EBX    20
14970 #define REG_ECX    21
14971 #define REG_EDX    22
14972 #define REG_ESI    23
14973 #define REG_EDI    24
14974 #define REG_EBP    25
14975 #define REG_ESP    26
14976 #define REGC_GPR32_FIRST REG_EAX
14977 #define REGC_GPR32_LAST  REG_ESP
14978 #define REG_EDXEAX 27
14979 #define REGC_GPR64_FIRST REG_EDXEAX
14980 #define REGC_GPR64_LAST  REG_EDXEAX
14981 #define REG_MMX0   28
14982 #define REG_MMX1   29
14983 #define REG_MMX2   30
14984 #define REG_MMX3   31
14985 #define REG_MMX4   32
14986 #define REG_MMX5   33
14987 #define REG_MMX6   34
14988 #define REG_MMX7   35
14989 #define REGC_MMX_FIRST REG_MMX0
14990 #define REGC_MMX_LAST  REG_MMX7
14991 #define REG_XMM0   36
14992 #define REG_XMM1   37
14993 #define REG_XMM2   38
14994 #define REG_XMM3   39
14995 #define REG_XMM4   40
14996 #define REG_XMM5   41
14997 #define REG_XMM6   42
14998 #define REG_XMM7   43
14999 #define REGC_XMM_FIRST REG_XMM0
15000 #define REGC_XMM_LAST  REG_XMM7
15001 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
15002 #define LAST_REG   REG_XMM7
15003
15004 #define REGC_GPR32_8_FIRST REG_EAX
15005 #define REGC_GPR32_8_LAST  REG_EDX
15006 #define REGC_GPR16_8_FIRST REG_AX
15007 #define REGC_GPR16_8_LAST  REG_DX
15008
15009 #define REGC_IMM8_FIRST    -1
15010 #define REGC_IMM8_LAST     -1
15011 #define REGC_IMM16_FIRST   -2
15012 #define REGC_IMM16_LAST    -1
15013 #define REGC_IMM32_FIRST   -4
15014 #define REGC_IMM32_LAST    -1
15015
15016 #if LAST_REG >= MAX_REGISTERS
15017 #error "MAX_REGISTERS to low"
15018 #endif
15019
15020
15021 static unsigned regc_size[LAST_REGC +1] = {
15022         [REGC_FLAGS]   = REGC_FLAGS_LAST   - REGC_FLAGS_FIRST + 1,
15023         [REGC_GPR8]    = REGC_GPR8_LAST    - REGC_GPR8_FIRST + 1,
15024         [REGC_GPR16]   = REGC_GPR16_LAST   - REGC_GPR16_FIRST + 1,
15025         [REGC_GPR32]   = REGC_GPR32_LAST   - REGC_GPR32_FIRST + 1,
15026         [REGC_GPR64]   = REGC_GPR64_LAST   - REGC_GPR64_FIRST + 1,
15027         [REGC_MMX]     = REGC_MMX_LAST     - REGC_MMX_FIRST + 1,
15028         [REGC_XMM]     = REGC_XMM_LAST     - REGC_XMM_FIRST + 1,
15029         [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
15030         [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
15031         [REGC_IMM32]   = 0,
15032         [REGC_IMM16]   = 0,
15033         [REGC_IMM8]    = 0,
15034 };
15035
15036 static const struct {
15037         int first, last;
15038 } regcm_bound[LAST_REGC + 1] = {
15039         [REGC_FLAGS]   = { REGC_FLAGS_FIRST,   REGC_FLAGS_LAST },
15040         [REGC_GPR8]    = { REGC_GPR8_FIRST,    REGC_GPR8_LAST },
15041         [REGC_GPR16]   = { REGC_GPR16_FIRST,   REGC_GPR16_LAST },
15042         [REGC_GPR32]   = { REGC_GPR32_FIRST,   REGC_GPR32_LAST },
15043         [REGC_GPR64]   = { REGC_GPR64_FIRST,   REGC_GPR64_LAST },
15044         [REGC_MMX]     = { REGC_MMX_FIRST,     REGC_MMX_LAST },
15045         [REGC_XMM]     = { REGC_XMM_FIRST,     REGC_XMM_LAST },
15046         [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
15047         [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
15048         [REGC_IMM32]   = { REGC_IMM32_FIRST,   REGC_IMM32_LAST },
15049         [REGC_IMM16]   = { REGC_IMM16_FIRST,   REGC_IMM16_LAST },
15050         [REGC_IMM8]    = { REGC_IMM8_FIRST,    REGC_IMM8_LAST },
15051 };
15052
15053 static int arch_encode_cpu(const char *cpu)
15054 {
15055         struct cpu {
15056                 const char *name;
15057                 int cpu;
15058         } cpus[] = {
15059                 { "i386", CPU_I386 },
15060                 { "p3",   CPU_P3 },
15061                 { "p4",   CPU_P4 },
15062                 { "k7",   CPU_K7 },
15063                 { "k8",   CPU_K8 },
15064                 {  0,     BAD_CPU }
15065         };
15066         struct cpu *ptr;
15067         for(ptr = cpus; ptr->name; ptr++) {
15068                 if (strcmp(ptr->name, cpu) == 0) {
15069                         break;
15070                 }
15071         }
15072         return ptr->cpu;
15073 }
15074
15075 static unsigned arch_regc_size(struct compile_state *state, int class)
15076 {
15077         if ((class < 0) || (class > LAST_REGC)) {
15078                 return 0;
15079         }
15080         return regc_size[class];
15081 }
15082 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
15083 {
15084         /* See if two register classes may have overlapping registers */
15085         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
15086                 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
15087
15088         /* Special case for the immediates */
15089         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15090                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
15091                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15092                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
15093                 return 0;
15094         }
15095         return (regcm1 & regcm2) ||
15096                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
15097 }
15098
15099 static void arch_reg_equivs(
15100         struct compile_state *state, unsigned *equiv, int reg)
15101 {
15102         if ((reg < 0) || (reg > LAST_REG)) {
15103                 internal_error(state, 0, "invalid register");
15104         }
15105         *equiv++ = reg;
15106         switch(reg) {
15107         case REG_AL:
15108 #if X86_4_8BIT_GPRS
15109                 *equiv++ = REG_AH;
15110 #endif
15111                 *equiv++ = REG_AX;
15112                 *equiv++ = REG_EAX;
15113                 *equiv++ = REG_EDXEAX;
15114                 break;
15115         case REG_AH:
15116 #if X86_4_8BIT_GPRS
15117                 *equiv++ = REG_AL;
15118 #endif
15119                 *equiv++ = REG_AX;
15120                 *equiv++ = REG_EAX;
15121                 *equiv++ = REG_EDXEAX;
15122                 break;
15123         case REG_BL:  
15124 #if X86_4_8BIT_GPRS
15125                 *equiv++ = REG_BH;
15126 #endif
15127                 *equiv++ = REG_BX;
15128                 *equiv++ = REG_EBX;
15129                 break;
15130
15131         case REG_BH:
15132 #if X86_4_8BIT_GPRS
15133                 *equiv++ = REG_BL;
15134 #endif
15135                 *equiv++ = REG_BX;
15136                 *equiv++ = REG_EBX;
15137                 break;
15138         case REG_CL:
15139 #if X86_4_8BIT_GPRS
15140                 *equiv++ = REG_CH;
15141 #endif
15142                 *equiv++ = REG_CX;
15143                 *equiv++ = REG_ECX;
15144                 break;
15145
15146         case REG_CH:
15147 #if X86_4_8BIT_GPRS
15148                 *equiv++ = REG_CL;
15149 #endif
15150                 *equiv++ = REG_CX;
15151                 *equiv++ = REG_ECX;
15152                 break;
15153         case REG_DL:
15154 #if X86_4_8BIT_GPRS
15155                 *equiv++ = REG_DH;
15156 #endif
15157                 *equiv++ = REG_DX;
15158                 *equiv++ = REG_EDX;
15159                 *equiv++ = REG_EDXEAX;
15160                 break;
15161         case REG_DH:
15162 #if X86_4_8BIT_GPRS
15163                 *equiv++ = REG_DL;
15164 #endif
15165                 *equiv++ = REG_DX;
15166                 *equiv++ = REG_EDX;
15167                 *equiv++ = REG_EDXEAX;
15168                 break;
15169         case REG_AX:
15170                 *equiv++ = REG_AL;
15171                 *equiv++ = REG_AH;
15172                 *equiv++ = REG_EAX;
15173                 *equiv++ = REG_EDXEAX;
15174                 break;
15175         case REG_BX:
15176                 *equiv++ = REG_BL;
15177                 *equiv++ = REG_BH;
15178                 *equiv++ = REG_EBX;
15179                 break;
15180         case REG_CX:  
15181                 *equiv++ = REG_CL;
15182                 *equiv++ = REG_CH;
15183                 *equiv++ = REG_ECX;
15184                 break;
15185         case REG_DX:  
15186                 *equiv++ = REG_DL;
15187                 *equiv++ = REG_DH;
15188                 *equiv++ = REG_EDX;
15189                 *equiv++ = REG_EDXEAX;
15190                 break;
15191         case REG_SI:  
15192                 *equiv++ = REG_ESI;
15193                 break;
15194         case REG_DI:
15195                 *equiv++ = REG_EDI;
15196                 break;
15197         case REG_BP:
15198                 *equiv++ = REG_EBP;
15199                 break;
15200         case REG_SP:
15201                 *equiv++ = REG_ESP;
15202                 break;
15203         case REG_EAX:
15204                 *equiv++ = REG_AL;
15205                 *equiv++ = REG_AH;
15206                 *equiv++ = REG_AX;
15207                 *equiv++ = REG_EDXEAX;
15208                 break;
15209         case REG_EBX:
15210                 *equiv++ = REG_BL;
15211                 *equiv++ = REG_BH;
15212                 *equiv++ = REG_BX;
15213                 break;
15214         case REG_ECX:
15215                 *equiv++ = REG_CL;
15216                 *equiv++ = REG_CH;
15217                 *equiv++ = REG_CX;
15218                 break;
15219         case REG_EDX:
15220                 *equiv++ = REG_DL;
15221                 *equiv++ = REG_DH;
15222                 *equiv++ = REG_DX;
15223                 *equiv++ = REG_EDXEAX;
15224                 break;
15225         case REG_ESI: 
15226                 *equiv++ = REG_SI;
15227                 break;
15228         case REG_EDI: 
15229                 *equiv++ = REG_DI;
15230                 break;
15231         case REG_EBP: 
15232                 *equiv++ = REG_BP;
15233                 break;
15234         case REG_ESP: 
15235                 *equiv++ = REG_SP;
15236                 break;
15237         case REG_EDXEAX: 
15238                 *equiv++ = REG_AL;
15239                 *equiv++ = REG_AH;
15240                 *equiv++ = REG_DL;
15241                 *equiv++ = REG_DH;
15242                 *equiv++ = REG_AX;
15243                 *equiv++ = REG_DX;
15244                 *equiv++ = REG_EAX;
15245                 *equiv++ = REG_EDX;
15246                 break;
15247         }
15248         *equiv++ = REG_UNSET; 
15249 }
15250
15251 static unsigned arch_avail_mask(struct compile_state *state)
15252 {
15253         unsigned avail_mask;
15254         avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 | 
15255                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
15256                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15257         switch(state->cpu) {
15258         case CPU_P3:
15259         case CPU_K7:
15260                 avail_mask |= REGCM_MMX;
15261                 break;
15262         case CPU_P4:
15263         case CPU_K8:
15264                 avail_mask |= REGCM_MMX | REGCM_XMM;
15265                 break;
15266         }
15267 #if 0
15268         /* Don't enable 8 bit values until I can force both operands
15269          * to be 8bits simultaneously.
15270          */
15271         avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
15272 #endif
15273         return avail_mask;
15274 }
15275
15276 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15277 {
15278         unsigned mask, result;
15279         int class, class2;
15280         result = regcm;
15281         result &= arch_avail_mask(state);
15282
15283         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15284                 if ((result & mask) == 0) {
15285                         continue;
15286                 }
15287                 if (class > LAST_REGC) {
15288                         result &= ~mask;
15289                 }
15290                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15291                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15292                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15293                                 result |= (1 << class2);
15294                         }
15295                 }
15296         }
15297         return result;
15298 }
15299
15300 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15301 {
15302         unsigned mask;
15303         int class;
15304         mask = 0;
15305         for(class = 0; class <= LAST_REGC; class++) {
15306                 if ((reg >= regcm_bound[class].first) &&
15307                         (reg <= regcm_bound[class].last)) {
15308                         mask |= (1 << class);
15309                 }
15310         }
15311         if (!mask) {
15312                 internal_error(state, 0, "reg %d not in any class", reg);
15313         }
15314         return mask;
15315 }
15316
15317 static struct reg_info arch_reg_constraint(
15318         struct compile_state *state, struct type *type, const char *constraint)
15319 {
15320         static const struct {
15321                 char class;
15322                 unsigned int mask;
15323                 unsigned int reg;
15324         } constraints[] = {
15325                 { 'r', REGCM_GPR32, REG_UNSET },
15326                 { 'g', REGCM_GPR32, REG_UNSET },
15327                 { 'p', REGCM_GPR32, REG_UNSET },
15328                 { 'q', REGCM_GPR8,  REG_UNSET },
15329                 { 'Q', REGCM_GPR32_8, REG_UNSET },
15330                 { 'x', REGCM_XMM,   REG_UNSET },
15331                 { 'y', REGCM_MMX,   REG_UNSET },
15332                 { 'a', REGCM_GPR32, REG_EAX },
15333                 { 'b', REGCM_GPR32, REG_EBX },
15334                 { 'c', REGCM_GPR32, REG_ECX },
15335                 { 'd', REGCM_GPR32, REG_EDX },
15336                 { 'D', REGCM_GPR32, REG_EDI },
15337                 { 'S', REGCM_GPR32, REG_ESI },
15338                 { '\0', 0, REG_UNSET },
15339         };
15340         unsigned int regcm;
15341         unsigned int mask, reg;
15342         struct reg_info result;
15343         const char *ptr;
15344         regcm = arch_type_to_regcm(state, type);
15345         reg = REG_UNSET;
15346         mask = 0;
15347         for(ptr = constraint; *ptr; ptr++) {
15348                 int i;
15349                 if (*ptr ==  ' ') {
15350                         continue;
15351                 }
15352                 for(i = 0; constraints[i].class != '\0'; i++) {
15353                         if (constraints[i].class == *ptr) {
15354                                 break;
15355                         }
15356                 }
15357                 if (constraints[i].class == '\0') {
15358                         error(state, 0, "invalid register constraint ``%c''", *ptr);
15359                         break;
15360                 }
15361                 if ((constraints[i].mask & regcm) == 0) {
15362                         error(state, 0, "invalid register class %c specified",
15363                                 *ptr);
15364                 }
15365                 mask |= constraints[i].mask;
15366                 if (constraints[i].reg != REG_UNSET) {
15367                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15368                                 error(state, 0, "Only one register may be specified");
15369                         }
15370                         reg = constraints[i].reg;
15371                 }
15372         }
15373         result.reg = reg;
15374         result.regcm = mask;
15375         return result;
15376 }
15377
15378 static struct reg_info arch_reg_clobber(
15379         struct compile_state *state, const char *clobber)
15380 {
15381         struct reg_info result;
15382         if (strcmp(clobber, "memory") == 0) {
15383                 result.reg = REG_UNSET;
15384                 result.regcm = 0;
15385         }
15386         else if (strcmp(clobber, "%eax") == 0) {
15387                 result.reg = REG_EAX;
15388                 result.regcm = REGCM_GPR32;
15389         }
15390         else if (strcmp(clobber, "%ebx") == 0) {
15391                 result.reg = REG_EBX;
15392                 result.regcm = REGCM_GPR32;
15393         }
15394         else if (strcmp(clobber, "%ecx") == 0) {
15395                 result.reg = REG_ECX;
15396                 result.regcm = REGCM_GPR32;
15397         }
15398         else if (strcmp(clobber, "%edx") == 0) {
15399                 result.reg = REG_EDX;
15400                 result.regcm = REGCM_GPR32;
15401         }
15402         else if (strcmp(clobber, "%esi") == 0) {
15403                 result.reg = REG_ESI;
15404                 result.regcm = REGCM_GPR32;
15405         }
15406         else if (strcmp(clobber, "%edi") == 0) {
15407                 result.reg = REG_EDI;
15408                 result.regcm = REGCM_GPR32;
15409         }
15410         else if (strcmp(clobber, "%ebp") == 0) {
15411                 result.reg = REG_EBP;
15412                 result.regcm = REGCM_GPR32;
15413         }
15414         else if (strcmp(clobber, "%esp") == 0) {
15415                 result.reg = REG_ESP;
15416                 result.regcm = REGCM_GPR32;
15417         }
15418         else if (strcmp(clobber, "cc") == 0) {
15419                 result.reg = REG_EFLAGS;
15420                 result.regcm = REGCM_FLAGS;
15421         }
15422         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
15423                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15424                 result.reg = REG_XMM0 + octdigval(clobber[3]);
15425                 result.regcm = REGCM_XMM;
15426         }
15427         else if ((strncmp(clobber, "mmx", 3) == 0) &&
15428                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15429                 result.reg = REG_MMX0 + octdigval(clobber[3]);
15430                 result.regcm = REGCM_MMX;
15431         }
15432         else {
15433                 error(state, 0, "Invalid register clobber");
15434                 result.reg = REG_UNSET;
15435                 result.regcm = 0;
15436         }
15437         return result;
15438 }
15439
15440 static int do_select_reg(struct compile_state *state, 
15441         char *used, int reg, unsigned classes)
15442 {
15443         unsigned mask;
15444         if (used[reg]) {
15445                 return REG_UNSET;
15446         }
15447         mask = arch_reg_regcm(state, reg);
15448         return (classes & mask) ? reg : REG_UNSET;
15449 }
15450
15451 static int arch_select_free_register(
15452         struct compile_state *state, char *used, int classes)
15453 {
15454         /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
15455          * other types of registers.
15456          */
15457         int i, reg;
15458         reg = REG_UNSET;
15459         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15460                 reg = do_select_reg(state, used, i, classes);
15461         }
15462         for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
15463                 reg = do_select_reg(state, used, i, classes);
15464         }
15465         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15466                 reg = do_select_reg(state, used, i, classes);
15467         }
15468         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15469                 reg = do_select_reg(state, used, i, classes);
15470         }
15471         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15472                 reg = do_select_reg(state, used, i, classes);
15473         }
15474         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15475                 reg = do_select_reg(state, used, i, classes);
15476         }
15477         for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
15478                 reg = do_select_reg(state, used, i, classes);
15479         }
15480         return reg;
15481 }
15482
15483
15484 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
15485 {
15486 #warning "FIXME force types smaller (if legal) before I get here"
15487         unsigned avail_mask;
15488         unsigned mask;
15489         mask = 0;
15490         avail_mask = arch_avail_mask(state);
15491         switch(type->type & TYPE_MASK) {
15492         case TYPE_ARRAY:
15493         case TYPE_VOID: 
15494                 mask = 0; 
15495                 break;
15496         case TYPE_CHAR:
15497         case TYPE_UCHAR:
15498                 mask = REGCM_GPR8 | 
15499                         REGCM_GPR16 | REGCM_GPR16_8 | 
15500                         REGCM_GPR32 | REGCM_GPR32_8 |
15501                         REGCM_GPR64 |
15502                         REGCM_MMX | REGCM_XMM |
15503                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15504                 break;
15505         case TYPE_SHORT:
15506         case TYPE_USHORT:
15507                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
15508                         REGCM_GPR32 | REGCM_GPR32_8 |
15509                         REGCM_GPR64 |
15510                         REGCM_MMX | REGCM_XMM |
15511                         REGCM_IMM32 | REGCM_IMM16;
15512                 break;
15513         case TYPE_INT:
15514         case TYPE_UINT:
15515         case TYPE_LONG:
15516         case TYPE_ULONG:
15517         case TYPE_POINTER:
15518                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
15519                         REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15520                         REGCM_IMM32;
15521                 break;
15522         default:
15523                 internal_error(state, 0, "no register class for type");
15524                 break;
15525         }
15526         mask &= avail_mask;
15527         return mask;
15528 }
15529
15530 static int is_imm32(struct triple *imm)
15531 {
15532         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15533                 (imm->op == OP_ADDRCONST);
15534         
15535 }
15536 static int is_imm16(struct triple *imm)
15537 {
15538         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15539 }
15540 static int is_imm8(struct triple *imm)
15541 {
15542         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15543 }
15544
15545 static int get_imm32(struct triple *ins, struct triple **expr)
15546 {
15547         struct triple *imm;
15548         imm = *expr;
15549         while(imm->op == OP_COPY) {
15550                 imm = RHS(imm, 0);
15551         }
15552         if (!is_imm32(imm)) {
15553                 return 0;
15554         }
15555         unuse_triple(*expr, ins);
15556         use_triple(imm, ins);
15557         *expr = imm;
15558         return 1;
15559 }
15560
15561 static int get_imm8(struct triple *ins, struct triple **expr)
15562 {
15563         struct triple *imm;
15564         imm = *expr;
15565         while(imm->op == OP_COPY) {
15566                 imm = RHS(imm, 0);
15567         }
15568         if (!is_imm8(imm)) {
15569                 return 0;
15570         }
15571         unuse_triple(*expr, ins);
15572         use_triple(imm, ins);
15573         *expr = imm;
15574         return 1;
15575 }
15576
15577 #define TEMPLATE_NOP         0
15578 #define TEMPLATE_INTCONST8   1
15579 #define TEMPLATE_INTCONST32  2
15580 #define TEMPLATE_COPY_REG    3
15581 #define TEMPLATE_COPY_IMM32  4
15582 #define TEMPLATE_COPY_IMM16  5
15583 #define TEMPLATE_COPY_IMM8   6
15584 #define TEMPLATE_PHI         7
15585 #define TEMPLATE_STORE8      8
15586 #define TEMPLATE_STORE16     9
15587 #define TEMPLATE_STORE32    10
15588 #define TEMPLATE_LOAD8      11
15589 #define TEMPLATE_LOAD16     12
15590 #define TEMPLATE_LOAD32     13
15591 #define TEMPLATE_BINARY_REG 14
15592 #define TEMPLATE_BINARY_IMM 15
15593 #define TEMPLATE_SL_CL      16
15594 #define TEMPLATE_SL_IMM     17
15595 #define TEMPLATE_UNARY      18
15596 #define TEMPLATE_CMP_REG    19
15597 #define TEMPLATE_CMP_IMM    20
15598 #define TEMPLATE_TEST       21
15599 #define TEMPLATE_SET        22
15600 #define TEMPLATE_JMP        23
15601 #define TEMPLATE_INB_DX     24
15602 #define TEMPLATE_INB_IMM    25
15603 #define TEMPLATE_INW_DX     26
15604 #define TEMPLATE_INW_IMM    27
15605 #define TEMPLATE_INL_DX     28
15606 #define TEMPLATE_INL_IMM    29
15607 #define TEMPLATE_OUTB_DX    30
15608 #define TEMPLATE_OUTB_IMM   31
15609 #define TEMPLATE_OUTW_DX    32
15610 #define TEMPLATE_OUTW_IMM   33
15611 #define TEMPLATE_OUTL_DX    34
15612 #define TEMPLATE_OUTL_IMM   35
15613 #define TEMPLATE_BSF        36
15614 #define TEMPLATE_RDMSR      37
15615 #define TEMPLATE_WRMSR      38
15616 #define LAST_TEMPLATE       TEMPLATE_WRMSR
15617 #if LAST_TEMPLATE >= MAX_TEMPLATES
15618 #error "MAX_TEMPLATES to low"
15619 #endif
15620
15621 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15622 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15623
15624 static struct ins_template templates[] = {
15625         [TEMPLATE_NOP]      = {},
15626         [TEMPLATE_INTCONST8] = { 
15627                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15628         },
15629         [TEMPLATE_INTCONST32] = { 
15630                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15631         },
15632         [TEMPLATE_COPY_REG] = {
15633                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15634                 .rhs = { [0] = { REG_UNSET, COPY_REGCM }  },
15635         },
15636         [TEMPLATE_COPY_IMM32] = {
15637                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15638                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15639         },
15640         [TEMPLATE_COPY_IMM16] = {
15641                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
15642                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
15643         },
15644         [TEMPLATE_COPY_IMM8] = {
15645                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15646                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15647         },
15648         [TEMPLATE_PHI] = { 
15649                 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
15650                 .rhs = { 
15651                         [ 0] = { REG_VIRT0, COPY_REGCM },
15652                         [ 1] = { REG_VIRT0, COPY_REGCM },
15653                         [ 2] = { REG_VIRT0, COPY_REGCM },
15654                         [ 3] = { REG_VIRT0, COPY_REGCM },
15655                         [ 4] = { REG_VIRT0, COPY_REGCM },
15656                         [ 5] = { REG_VIRT0, COPY_REGCM },
15657                         [ 6] = { REG_VIRT0, COPY_REGCM },
15658                         [ 7] = { REG_VIRT0, COPY_REGCM },
15659                         [ 8] = { REG_VIRT0, COPY_REGCM },
15660                         [ 9] = { REG_VIRT0, COPY_REGCM },
15661                         [10] = { REG_VIRT0, COPY_REGCM },
15662                         [11] = { REG_VIRT0, COPY_REGCM },
15663                         [12] = { REG_VIRT0, COPY_REGCM },
15664                         [13] = { REG_VIRT0, COPY_REGCM },
15665                         [14] = { REG_VIRT0, COPY_REGCM },
15666                         [15] = { REG_VIRT0, COPY_REGCM },
15667                 }, },
15668         [TEMPLATE_STORE8] = {
15669                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15670                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15671         },
15672         [TEMPLATE_STORE16] = {
15673                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15674                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15675         },
15676         [TEMPLATE_STORE32] = {
15677                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15678                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15679         },
15680         [TEMPLATE_LOAD8] = {
15681                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15682                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15683         },
15684         [TEMPLATE_LOAD16] = {
15685                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15686                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15687         },
15688         [TEMPLATE_LOAD32] = {
15689                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15690                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15691         },
15692         [TEMPLATE_BINARY_REG] = {
15693                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15694                 .rhs = { 
15695                         [0] = { REG_VIRT0, REGCM_GPR32 },
15696                         [1] = { REG_UNSET, REGCM_GPR32 },
15697                 },
15698         },
15699         [TEMPLATE_BINARY_IMM] = {
15700                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15701                 .rhs = { 
15702                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15703                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15704                 },
15705         },
15706         [TEMPLATE_SL_CL] = {
15707                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15708                 .rhs = { 
15709                         [0] = { REG_VIRT0, REGCM_GPR32 },
15710                         [1] = { REG_CL, REGCM_GPR8 },
15711                 },
15712         },
15713         [TEMPLATE_SL_IMM] = {
15714                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15715                 .rhs = { 
15716                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15717                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15718                 },
15719         },
15720         [TEMPLATE_UNARY] = {
15721                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15722                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15723         },
15724         [TEMPLATE_CMP_REG] = {
15725                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15726                 .rhs = {
15727                         [0] = { REG_UNSET, REGCM_GPR32 },
15728                         [1] = { REG_UNSET, REGCM_GPR32 },
15729                 },
15730         },
15731         [TEMPLATE_CMP_IMM] = {
15732                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15733                 .rhs = {
15734                         [0] = { REG_UNSET, REGCM_GPR32 },
15735                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15736                 },
15737         },
15738         [TEMPLATE_TEST] = {
15739                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15740                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15741         },
15742         [TEMPLATE_SET] = {
15743                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15744                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15745         },
15746         [TEMPLATE_JMP] = {
15747                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15748         },
15749         [TEMPLATE_INB_DX] = {
15750                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15751                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15752         },
15753         [TEMPLATE_INB_IMM] = {
15754                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15755                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15756         },
15757         [TEMPLATE_INW_DX]  = { 
15758                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15759                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15760         },
15761         [TEMPLATE_INW_IMM] = { 
15762                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15763                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15764         },
15765         [TEMPLATE_INL_DX]  = {
15766                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15767                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15768         },
15769         [TEMPLATE_INL_IMM] = {
15770                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15771                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15772         },
15773         [TEMPLATE_OUTB_DX] = { 
15774                 .rhs = {
15775                         [0] = { REG_AL,  REGCM_GPR8 },
15776                         [1] = { REG_DX, REGCM_GPR16 },
15777                 },
15778         },
15779         [TEMPLATE_OUTB_IMM] = { 
15780                 .rhs = {
15781                         [0] = { REG_AL,  REGCM_GPR8 },  
15782                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15783                 },
15784         },
15785         [TEMPLATE_OUTW_DX] = { 
15786                 .rhs = {
15787                         [0] = { REG_AX,  REGCM_GPR16 },
15788                         [1] = { REG_DX, REGCM_GPR16 },
15789                 },
15790         },
15791         [TEMPLATE_OUTW_IMM] = {
15792                 .rhs = {
15793                         [0] = { REG_AX,  REGCM_GPR16 }, 
15794                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15795                 },
15796         },
15797         [TEMPLATE_OUTL_DX] = { 
15798                 .rhs = {
15799                         [0] = { REG_EAX, REGCM_GPR32 },
15800                         [1] = { REG_DX, REGCM_GPR16 },
15801                 },
15802         },
15803         [TEMPLATE_OUTL_IMM] = { 
15804                 .rhs = {
15805                         [0] = { REG_EAX, REGCM_GPR32 }, 
15806                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15807                 },
15808         },
15809         [TEMPLATE_BSF] = {
15810                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15811                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15812         },
15813         [TEMPLATE_RDMSR] = {
15814                 .lhs = { 
15815                         [0] = { REG_EAX, REGCM_GPR32 },
15816                         [1] = { REG_EDX, REGCM_GPR32 },
15817                 },
15818                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15819         },
15820         [TEMPLATE_WRMSR] = {
15821                 .rhs = {
15822                         [0] = { REG_ECX, REGCM_GPR32 },
15823                         [1] = { REG_EAX, REGCM_GPR32 },
15824                         [2] = { REG_EDX, REGCM_GPR32 },
15825                 },
15826         },
15827 };
15828
15829 static void fixup_branches(struct compile_state *state,
15830         struct triple *cmp, struct triple *use, int jmp_op)
15831 {
15832         struct triple_set *entry, *next;
15833         for(entry = use->use; entry; entry = next) {
15834                 next = entry->next;
15835                 if (entry->member->op == OP_COPY) {
15836                         fixup_branches(state, cmp, entry->member, jmp_op);
15837                 }
15838                 else if (entry->member->op == OP_BRANCH) {
15839                         struct triple *branch, *test;
15840                         struct triple *left, *right;
15841                         left = right = 0;
15842                         left = RHS(cmp, 0);
15843                         if (TRIPLE_RHS(cmp->sizes) > 1) {
15844                                 right = RHS(cmp, 1);
15845                         }
15846                         branch = entry->member;
15847                         test = pre_triple(state, branch,
15848                                 cmp->op, cmp->type, left, right);
15849                         test->template_id = TEMPLATE_TEST; 
15850                         if (cmp->op == OP_CMP) {
15851                                 test->template_id = TEMPLATE_CMP_REG;
15852                                 if (get_imm32(test, &RHS(test, 1))) {
15853                                         test->template_id = TEMPLATE_CMP_IMM;
15854                                 }
15855                         }
15856                         use_triple(RHS(test, 0), test);
15857                         use_triple(RHS(test, 1), test);
15858                         unuse_triple(RHS(branch, 0), branch);
15859                         RHS(branch, 0) = test;
15860                         branch->op = jmp_op;
15861                         branch->template_id = TEMPLATE_JMP;
15862                         use_triple(RHS(branch, 0), branch);
15863                 }
15864         }
15865 }
15866
15867 static void bool_cmp(struct compile_state *state, 
15868         struct triple *ins, int cmp_op, int jmp_op, int set_op)
15869 {
15870         struct triple_set *entry, *next;
15871         struct triple *set;
15872
15873         /* Put a barrier up before the cmp which preceeds the
15874          * copy instruction.  If a set actually occurs this gives
15875          * us a chance to move variables in registers out of the way.
15876          */
15877
15878         /* Modify the comparison operator */
15879         ins->op = cmp_op;
15880         ins->template_id = TEMPLATE_TEST;
15881         if (cmp_op == OP_CMP) {
15882                 ins->template_id = TEMPLATE_CMP_REG;
15883                 if (get_imm32(ins, &RHS(ins, 1))) {
15884                         ins->template_id =  TEMPLATE_CMP_IMM;
15885                 }
15886         }
15887         /* Generate the instruction sequence that will transform the
15888          * result of the comparison into a logical value.
15889          */
15890         set = post_triple(state, ins, set_op, ins->type, ins, 0);
15891         use_triple(ins, set);
15892         set->template_id = TEMPLATE_SET;
15893
15894         for(entry = ins->use; entry; entry = next) {
15895                 next = entry->next;
15896                 if (entry->member == set) {
15897                         continue;
15898                 }
15899                 replace_rhs_use(state, ins, set, entry->member);
15900         }
15901         fixup_branches(state, ins, set, jmp_op);
15902 }
15903
15904 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15905 {
15906         struct triple *next;
15907         int lhs, i;
15908         lhs = TRIPLE_LHS(ins->sizes);
15909         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15910                 if (next != LHS(ins, i)) {
15911                         internal_error(state, ins, "malformed lhs on %s",
15912                                 tops(ins->op));
15913                 }
15914                 if (next->op != OP_PIECE) {
15915                         internal_error(state, ins, "bad lhs op %s at %d on %s",
15916                                 tops(next->op), i, tops(ins->op));
15917                 }
15918                 if (next->u.cval != i) {
15919                         internal_error(state, ins, "bad u.cval of %d %d expected",
15920                                 next->u.cval, i);
15921                 }
15922         }
15923         return next;
15924 }
15925
15926 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15927 {
15928         struct ins_template *template;
15929         struct reg_info result;
15930         int zlhs;
15931         if (ins->op == OP_PIECE) {
15932                 index = ins->u.cval;
15933                 ins = MISC(ins, 0);
15934         }
15935         zlhs = TRIPLE_LHS(ins->sizes);
15936         if (triple_is_def(state, ins)) {
15937                 zlhs = 1;
15938         }
15939         if (index >= zlhs) {
15940                 internal_error(state, ins, "index %d out of range for %s\n",
15941                         index, tops(ins->op));
15942         }
15943         switch(ins->op) {
15944         case OP_ASM:
15945                 template = &ins->u.ainfo->tmpl;
15946                 break;
15947         default:
15948                 if (ins->template_id > LAST_TEMPLATE) {
15949                         internal_error(state, ins, "bad template number %d", 
15950                                 ins->template_id);
15951                 }
15952                 template = &templates[ins->template_id];
15953                 break;
15954         }
15955         result = template->lhs[index];
15956         result.regcm = arch_regcm_normalize(state, result.regcm);
15957         if (result.reg != REG_UNNEEDED) {
15958                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15959         }
15960         if (result.regcm == 0) {
15961                 internal_error(state, ins, "lhs %d regcm == 0", index);
15962         }
15963         return result;
15964 }
15965
15966 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15967 {
15968         struct reg_info result;
15969         struct ins_template *template;
15970         if ((index > TRIPLE_RHS(ins->sizes)) ||
15971                 (ins->op == OP_PIECE)) {
15972                 internal_error(state, ins, "index %d out of range for %s\n",
15973                         index, tops(ins->op));
15974         }
15975         switch(ins->op) {
15976         case OP_ASM:
15977                 template = &ins->u.ainfo->tmpl;
15978                 break;
15979         default:
15980                 if (ins->template_id > LAST_TEMPLATE) {
15981                         internal_error(state, ins, "bad template number %d", 
15982                                 ins->template_id);
15983                 }
15984                 template = &templates[ins->template_id];
15985                 break;
15986         }
15987         result = template->rhs[index];
15988         result.regcm = arch_regcm_normalize(state, result.regcm);
15989         if (result.regcm == 0) {
15990                 internal_error(state, ins, "rhs %d regcm == 0", index);
15991         }
15992         return result;
15993 }
15994
15995 static struct triple *transform_to_arch_instruction(
15996         struct compile_state *state, struct triple *ins)
15997 {
15998         /* Transform from generic 3 address instructions
15999          * to archtecture specific instructions.
16000          * And apply architecture specific constrains to instructions.
16001          * Copies are inserted to preserve the register flexibility
16002          * of 3 address instructions.
16003          */
16004         struct triple *next;
16005         next = ins->next;
16006         switch(ins->op) {
16007         case OP_INTCONST:
16008                 ins->template_id = TEMPLATE_INTCONST32;
16009                 if (ins->u.cval < 256) {
16010                         ins->template_id = TEMPLATE_INTCONST8;
16011                 }
16012                 break;
16013         case OP_ADDRCONST:
16014                 ins->template_id = TEMPLATE_INTCONST32;
16015                 break;
16016         case OP_NOOP:
16017         case OP_SDECL:
16018         case OP_BLOBCONST:
16019         case OP_LABEL:
16020                 ins->template_id = TEMPLATE_NOP;
16021                 break;
16022         case OP_COPY:
16023                 ins->template_id = TEMPLATE_COPY_REG;
16024                 if (is_imm8(RHS(ins, 0))) {
16025                         ins->template_id = TEMPLATE_COPY_IMM8;
16026                 }
16027                 else if (is_imm16(RHS(ins, 0))) {
16028                         ins->template_id = TEMPLATE_COPY_IMM16;
16029                 }
16030                 else if (is_imm32(RHS(ins, 0))) {
16031                         ins->template_id = TEMPLATE_COPY_IMM32;
16032                 }
16033                 else if (is_const(RHS(ins, 0))) {
16034                         internal_error(state, ins, "bad constant passed to copy");
16035                 }
16036                 break;
16037         case OP_PHI:
16038                 ins->template_id = TEMPLATE_PHI;
16039                 break;
16040         case OP_STORE:
16041                 switch(ins->type->type & TYPE_MASK) {
16042                 case TYPE_CHAR:    case TYPE_UCHAR:
16043                         ins->template_id = TEMPLATE_STORE8;
16044                         break;
16045                 case TYPE_SHORT:   case TYPE_USHORT:
16046                         ins->template_id = TEMPLATE_STORE16;
16047                         break;
16048                 case TYPE_INT:     case TYPE_UINT:
16049                 case TYPE_LONG:    case TYPE_ULONG:
16050                 case TYPE_POINTER:
16051                         ins->template_id = TEMPLATE_STORE32;
16052                         break;
16053                 default:
16054                         internal_error(state, ins, "unknown type in store");
16055                         break;
16056                 }
16057                 break;
16058         case OP_LOAD:
16059                 switch(ins->type->type & TYPE_MASK) {
16060                 case TYPE_CHAR:   case TYPE_UCHAR:
16061                         ins->template_id = TEMPLATE_LOAD8;
16062                         break;
16063                 case TYPE_SHORT:
16064                 case TYPE_USHORT:
16065                         ins->template_id = TEMPLATE_LOAD16;
16066                         break;
16067                 case TYPE_INT:
16068                 case TYPE_UINT:
16069                 case TYPE_LONG:
16070                 case TYPE_ULONG:
16071                 case TYPE_POINTER:
16072                         ins->template_id = TEMPLATE_LOAD32;
16073                         break;
16074                 default:
16075                         internal_error(state, ins, "unknown type in load");
16076                         break;
16077                 }
16078                 break;
16079         case OP_ADD:
16080         case OP_SUB:
16081         case OP_AND:
16082         case OP_XOR:
16083         case OP_OR:
16084         case OP_SMUL:
16085                 ins->template_id = TEMPLATE_BINARY_REG;
16086                 if (get_imm32(ins, &RHS(ins, 1))) {
16087                         ins->template_id = TEMPLATE_BINARY_IMM;
16088                 }
16089                 break;
16090         case OP_SL:
16091         case OP_SSR:
16092         case OP_USR:
16093                 ins->template_id = TEMPLATE_SL_CL;
16094                 if (get_imm8(ins, &RHS(ins, 1))) {
16095                         ins->template_id = TEMPLATE_SL_IMM;
16096                 }
16097                 break;
16098         case OP_INVERT:
16099         case OP_NEG:
16100                 ins->template_id = TEMPLATE_UNARY;
16101                 break;
16102         case OP_EQ: 
16103                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
16104                 break;
16105         case OP_NOTEQ:
16106                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16107                 break;
16108         case OP_SLESS:
16109                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16110                 break;
16111         case OP_ULESS:
16112                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16113                 break;
16114         case OP_SMORE:
16115                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16116                 break;
16117         case OP_UMORE:
16118                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16119                 break;
16120         case OP_SLESSEQ:
16121                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16122                 break;
16123         case OP_ULESSEQ:
16124                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16125                 break;
16126         case OP_SMOREEQ:
16127                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16128                 break;
16129         case OP_UMOREEQ:
16130                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16131                 break;
16132         case OP_LTRUE:
16133                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16134                 break;
16135         case OP_LFALSE:
16136                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16137                 break;
16138         case OP_BRANCH:
16139                 if (TRIPLE_RHS(ins->sizes) > 0) {
16140                         internal_error(state, ins, "bad branch test");
16141                 }
16142                 ins->op = OP_JMP;
16143                 ins->template_id = TEMPLATE_NOP;
16144                 break;
16145         case OP_INB:
16146         case OP_INW:
16147         case OP_INL:
16148                 switch(ins->op) {
16149                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16150                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16151                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16152                 }
16153                 if (get_imm8(ins, &RHS(ins, 0))) {
16154                         ins->template_id += 1;
16155                 }
16156                 break;
16157         case OP_OUTB:
16158         case OP_OUTW:
16159         case OP_OUTL:
16160                 switch(ins->op) {
16161                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16162                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16163                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16164                 }
16165                 if (get_imm8(ins, &RHS(ins, 1))) {
16166                         ins->template_id += 1;
16167                 }
16168                 break;
16169         case OP_BSF:
16170         case OP_BSR:
16171                 ins->template_id = TEMPLATE_BSF;
16172                 break;
16173         case OP_RDMSR:
16174                 ins->template_id = TEMPLATE_RDMSR;
16175                 next = after_lhs(state, ins);
16176                 break;
16177         case OP_WRMSR:
16178                 ins->template_id = TEMPLATE_WRMSR;
16179                 break;
16180         case OP_HLT:
16181                 ins->template_id = TEMPLATE_NOP;
16182                 break;
16183         case OP_ASM:
16184                 ins->template_id = TEMPLATE_NOP;
16185                 next = after_lhs(state, ins);
16186                 break;
16187                 /* Already transformed instructions */
16188         case OP_TEST:
16189                 ins->template_id = TEMPLATE_TEST;
16190                 break;
16191         case OP_CMP:
16192                 ins->template_id = TEMPLATE_CMP_REG;
16193                 if (get_imm32(ins, &RHS(ins, 1))) {
16194                         ins->template_id = TEMPLATE_CMP_IMM;
16195                 }
16196                 break;
16197         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16198         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16199         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16200         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16201         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16202                 ins->template_id = TEMPLATE_JMP;
16203                 break;
16204         case OP_SET_EQ:      case OP_SET_NOTEQ:
16205         case OP_SET_SLESS:   case OP_SET_ULESS:
16206         case OP_SET_SMORE:   case OP_SET_UMORE:
16207         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16208         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16209                 ins->template_id = TEMPLATE_SET;
16210                 break;
16211                 /* Unhandled instructions */
16212         case OP_PIECE:
16213         default:
16214                 internal_error(state, ins, "unhandled ins: %d %s\n",
16215                         ins->op, tops(ins->op));
16216                 break;
16217         }
16218         return next;
16219 }
16220
16221 static void generate_local_labels(struct compile_state *state)
16222 {
16223         struct triple *first, *label;
16224         int label_counter;
16225         label_counter = 0;
16226         first = RHS(state->main_function, 0);
16227         label = first;
16228         do {
16229                 if ((label->op == OP_LABEL) || 
16230                         (label->op == OP_SDECL)) {
16231                         if (label->use) {
16232                                 label->u.cval = ++label_counter;
16233                         } else {
16234                                 label->u.cval = 0;
16235                         }
16236                         
16237                 }
16238                 label = label->next;
16239         } while(label != first);
16240 }
16241
16242 static int check_reg(struct compile_state *state, 
16243         struct triple *triple, int classes)
16244 {
16245         unsigned mask;
16246         int reg;
16247         reg = ID_REG(triple->id);
16248         if (reg == REG_UNSET) {
16249                 internal_error(state, triple, "register not set");
16250         }
16251         mask = arch_reg_regcm(state, reg);
16252         if (!(classes & mask)) {
16253                 internal_error(state, triple, "reg %d in wrong class",
16254                         reg);
16255         }
16256         return reg;
16257 }
16258
16259 static const char *arch_reg_str(int reg)
16260 {
16261         static const char *regs[] = {
16262                 "%unset",
16263                 "%unneeded",
16264                 "%eflags",
16265                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16266                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16267                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16268                 "%edx:%eax",
16269                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16270                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
16271                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16272         };
16273         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16274                 reg = 0;
16275         }
16276         return regs[reg];
16277 }
16278
16279
16280 static const char *reg(struct compile_state *state, struct triple *triple,
16281         int classes)
16282 {
16283         int reg;
16284         reg = check_reg(state, triple, classes);
16285         return arch_reg_str(reg);
16286 }
16287
16288 const char *type_suffix(struct compile_state *state, struct type *type)
16289 {
16290         const char *suffix;
16291         switch(size_of(state, type)) {
16292         case 1: suffix = "b"; break;
16293         case 2: suffix = "w"; break;
16294         case 4: suffix = "l"; break;
16295         default:
16296                 internal_error(state, 0, "unknown suffix");
16297                 suffix = 0;
16298                 break;
16299         }
16300         return suffix;
16301 }
16302
16303 static void print_const_val(
16304         struct compile_state *state, struct triple *ins, FILE *fp)
16305 {
16306         switch(ins->op) {
16307         case OP_INTCONST:
16308                 fprintf(fp, " $%ld ", 
16309                         (long_t)(ins->u.cval));
16310                 break;
16311         case OP_ADDRCONST:
16312                 fprintf(fp, " $L%s%lu+%lu ",
16313                         state->label_prefix, 
16314                         MISC(ins, 0)->u.cval,
16315                         ins->u.cval);
16316                 break;
16317         default:
16318                 internal_error(state, ins, "unknown constant type");
16319                 break;
16320         }
16321 }
16322
16323 static void print_binary_op(struct compile_state *state,
16324         const char *op, struct triple *ins, FILE *fp) 
16325 {
16326         unsigned mask;
16327         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16328         if (RHS(ins, 0)->id != ins->id) {
16329                 internal_error(state, ins, "invalid register assignment");
16330         }
16331         if (is_const(RHS(ins, 1))) {
16332                 fprintf(fp, "\t%s ", op);
16333                 print_const_val(state, RHS(ins, 1), fp);
16334                 fprintf(fp, ", %s\n",
16335                         reg(state, RHS(ins, 0), mask));
16336         }
16337         else {
16338                 unsigned lmask, rmask;
16339                 int lreg, rreg;
16340                 lreg = check_reg(state, RHS(ins, 0), mask);
16341                 rreg = check_reg(state, RHS(ins, 1), mask);
16342                 lmask = arch_reg_regcm(state, lreg);
16343                 rmask = arch_reg_regcm(state, rreg);
16344                 mask = lmask & rmask;
16345                 fprintf(fp, "\t%s %s, %s\n",
16346                         op,
16347                         reg(state, RHS(ins, 1), mask),
16348                         reg(state, RHS(ins, 0), mask));
16349         }
16350 }
16351 static void print_unary_op(struct compile_state *state, 
16352         const char *op, struct triple *ins, FILE *fp)
16353 {
16354         unsigned mask;
16355         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16356         fprintf(fp, "\t%s %s\n",
16357                 op,
16358                 reg(state, RHS(ins, 0), mask));
16359 }
16360
16361 static void print_op_shift(struct compile_state *state,
16362         const char *op, struct triple *ins, FILE *fp)
16363 {
16364         unsigned mask;
16365         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16366         if (RHS(ins, 0)->id != ins->id) {
16367                 internal_error(state, ins, "invalid register assignment");
16368         }
16369         if (is_const(RHS(ins, 1))) {
16370                 fprintf(fp, "\t%s ", op);
16371                 print_const_val(state, RHS(ins, 1), fp);
16372                 fprintf(fp, ", %s\n",
16373                         reg(state, RHS(ins, 0), mask));
16374         }
16375         else {
16376                 fprintf(fp, "\t%s %s, %s\n",
16377                         op,
16378                         reg(state, RHS(ins, 1), REGCM_GPR8),
16379                         reg(state, RHS(ins, 0), mask));
16380         }
16381 }
16382
16383 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16384 {
16385         const char *op;
16386         int mask;
16387         int dreg;
16388         mask = 0;
16389         switch(ins->op) {
16390         case OP_INB: op = "inb", mask = REGCM_GPR8; break;
16391         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16392         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16393         default:
16394                 internal_error(state, ins, "not an in operation");
16395                 op = 0;
16396                 break;
16397         }
16398         dreg = check_reg(state, ins, mask);
16399         if (!reg_is_reg(state, dreg, REG_EAX)) {
16400                 internal_error(state, ins, "dst != %%eax");
16401         }
16402         if (is_const(RHS(ins, 0))) {
16403                 fprintf(fp, "\t%s ", op);
16404                 print_const_val(state, RHS(ins, 0), fp);
16405                 fprintf(fp, ", %s\n",
16406                         reg(state, ins, mask));
16407         }
16408         else {
16409                 int addr_reg;
16410                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16411                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16412                         internal_error(state, ins, "src != %%dx");
16413                 }
16414                 fprintf(fp, "\t%s %s, %s\n",
16415                         op, 
16416                         reg(state, RHS(ins, 0), REGCM_GPR16),
16417                         reg(state, ins, mask));
16418         }
16419 }
16420
16421 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16422 {
16423         const char *op;
16424         int mask;
16425         int lreg;
16426         mask = 0;
16427         switch(ins->op) {
16428         case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
16429         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16430         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16431         default:
16432                 internal_error(state, ins, "not an out operation");
16433                 op = 0;
16434                 break;
16435         }
16436         lreg = check_reg(state, RHS(ins, 0), mask);
16437         if (!reg_is_reg(state, lreg, REG_EAX)) {
16438                 internal_error(state, ins, "src != %%eax");
16439         }
16440         if (is_const(RHS(ins, 1))) {
16441                 fprintf(fp, "\t%s %s,", 
16442                         op, reg(state, RHS(ins, 0), mask));
16443                 print_const_val(state, RHS(ins, 1), fp);
16444                 fprintf(fp, "\n");
16445         }
16446         else {
16447                 int addr_reg;
16448                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16449                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16450                         internal_error(state, ins, "dst != %%dx");
16451                 }
16452                 fprintf(fp, "\t%s %s, %s\n",
16453                         op, 
16454                         reg(state, RHS(ins, 0), mask),
16455                         reg(state, RHS(ins, 1), REGCM_GPR16));
16456         }
16457 }
16458
16459 static void print_op_move(struct compile_state *state,
16460         struct triple *ins, FILE *fp)
16461 {
16462         /* op_move is complex because there are many types
16463          * of registers we can move between.
16464          * Because OP_COPY will be introduced in arbitrary locations
16465          * OP_COPY must not affect flags.
16466          */
16467         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
16468         struct triple *dst, *src;
16469         if (ins->op == OP_COPY) {
16470                 src = RHS(ins, 0);
16471                 dst = ins;
16472         }
16473         else if (ins->op == OP_WRITE) {
16474                 dst = LHS(ins, 0);
16475                 src = RHS(ins, 0);
16476         }
16477         else {
16478                 internal_error(state, ins, "unknown move operation");
16479                 src = dst = 0;
16480         }
16481         if (!is_const(src)) {
16482                 int src_reg, dst_reg;
16483                 int src_regcm, dst_regcm;
16484                 src_reg = ID_REG(src->id);
16485                 dst_reg   = ID_REG(dst->id);
16486                 src_regcm = arch_reg_regcm(state, src_reg);
16487                 dst_regcm   = arch_reg_regcm(state, dst_reg);
16488                 /* If the class is the same just move the register */
16489                 if (src_regcm & dst_regcm & 
16490                         (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
16491                         if ((src_reg != dst_reg) || !omit_copy) {
16492                                 fprintf(fp, "\tmov %s, %s\n",
16493                                         reg(state, src, src_regcm),
16494                                         reg(state, dst, dst_regcm));
16495                         }
16496                 }
16497                 /* Move 32bit to 16bit */
16498                 else if ((src_regcm & REGCM_GPR32) &&
16499                         (dst_regcm & REGCM_GPR16)) {
16500                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
16501                         if ((src_reg != dst_reg) || !omit_copy) {
16502                                 fprintf(fp, "\tmovw %s, %s\n",
16503                                         arch_reg_str(src_reg), 
16504                                         arch_reg_str(dst_reg));
16505                         }
16506                 }
16507                 /* Move 32bit to 8bit */
16508                 else if ((src_regcm & REGCM_GPR32_8) &&
16509                         (dst_regcm & REGCM_GPR8))
16510                 {
16511                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
16512                         if ((src_reg != dst_reg) || !omit_copy) {
16513                                 fprintf(fp, "\tmovb %s, %s\n",
16514                                         arch_reg_str(src_reg),
16515                                         arch_reg_str(dst_reg));
16516                         }
16517                 }
16518                 /* Move 16bit to 8bit */
16519                 else if ((src_regcm & REGCM_GPR16_8) &&
16520                         (dst_regcm & REGCM_GPR8))
16521                 {
16522                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16523                         if ((src_reg != dst_reg) || !omit_copy) {
16524                                 fprintf(fp, "\tmovb %s, %s\n",
16525                                         arch_reg_str(src_reg),
16526                                         arch_reg_str(dst_reg));
16527                         }
16528                 }
16529                 /* Move 8/16bit to 16/32bit */
16530                 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) && 
16531                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16532                         const char *op;
16533                         op = is_signed(src->type)? "movsx": "movzx";
16534                         fprintf(fp, "\t%s %s, %s\n",
16535                                 op,
16536                                 reg(state, src, src_regcm),
16537                                 reg(state, dst, dst_regcm));
16538                 }
16539                 /* Move between sse registers */
16540                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16541                         if ((src_reg != dst_reg) || !omit_copy) {
16542                                 fprintf(fp, "\tmovdqa %s, %s\n",
16543                                         reg(state, src, src_regcm),
16544                                         reg(state, dst, dst_regcm));
16545                         }
16546                 }
16547                 /* Move between mmx registers or mmx & sse  registers */
16548                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16549                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16550                         if ((src_reg != dst_reg) || !omit_copy) {
16551                                 fprintf(fp, "\tmovq %s, %s\n",
16552                                         reg(state, src, src_regcm),
16553                                         reg(state, dst, dst_regcm));
16554                         }
16555                 }
16556                 /* Move between 32bit gprs & mmx/sse registers */
16557                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16558                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16559                         fprintf(fp, "\tmovd %s, %s\n",
16560                                 reg(state, src, src_regcm),
16561                                 reg(state, dst, dst_regcm));
16562                 }
16563 #if X86_4_8BIT_GPRS
16564                 /* Move from 8bit gprs to  mmx/sse registers */
16565                 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16566                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16567                         const char *op;
16568                         int mid_reg;
16569                         op = is_signed(src->type)? "movsx":"movzx";
16570                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16571                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16572                                 op,
16573                                 reg(state, src, src_regcm),
16574                                 arch_reg_str(mid_reg),
16575                                 arch_reg_str(mid_reg),
16576                                 reg(state, dst, dst_regcm));
16577                 }
16578                 /* Move from mmx/sse registers and 8bit gprs */
16579                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16580                         (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16581                         int mid_reg;
16582                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16583                         fprintf(fp, "\tmovd %s, %s\n",
16584                                 reg(state, src, src_regcm),
16585                                 arch_reg_str(mid_reg));
16586                 }
16587                 /* Move from 32bit gprs to 16bit gprs */
16588                 else if ((src_regcm & REGCM_GPR32) &&
16589                         (dst_regcm & REGCM_GPR16)) {
16590                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16591                         if ((src_reg != dst_reg) || !omit_copy) {
16592                                 fprintf(fp, "\tmov %s, %s\n",
16593                                         arch_reg_str(src_reg),
16594                                         arch_reg_str(dst_reg));
16595                         }
16596                 }
16597                 /* Move from 32bit gprs to 8bit gprs */
16598                 else if ((src_regcm & REGCM_GPR32) &&
16599                         (dst_regcm & REGCM_GPR8)) {
16600                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16601                         if ((src_reg != dst_reg) || !omit_copy) {
16602                                 fprintf(fp, "\tmov %s, %s\n",
16603                                         arch_reg_str(src_reg),
16604                                         arch_reg_str(dst_reg));
16605                         }
16606                 }
16607                 /* Move from 16bit gprs to 8bit gprs */
16608                 else if ((src_regcm & REGCM_GPR16) &&
16609                         (dst_regcm & REGCM_GPR8)) {
16610                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16611                         if ((src_reg != dst_reg) || !omit_copy) {
16612                                 fprintf(fp, "\tmov %s, %s\n",
16613                                         arch_reg_str(src_reg),
16614                                         arch_reg_str(dst_reg));
16615                         }
16616                 }
16617 #endif /* X86_4_8BIT_GPRS */
16618                 else {
16619                         internal_error(state, ins, "unknown copy type");
16620                 }
16621         }
16622         else {
16623                 fprintf(fp, "\tmov ");
16624                 print_const_val(state, src, fp);
16625                 fprintf(fp, ", %s\n",
16626                         reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16627         }
16628 }
16629
16630 static void print_op_load(struct compile_state *state,
16631         struct triple *ins, FILE *fp)
16632 {
16633         struct triple *dst, *src;
16634         dst = ins;
16635         src = RHS(ins, 0);
16636         if (is_const(src) || is_const(dst)) {
16637                 internal_error(state, ins, "unknown load operation");
16638         }
16639         fprintf(fp, "\tmov (%s), %s\n",
16640                 reg(state, src, REGCM_GPR32),
16641                 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16642 }
16643
16644
16645 static void print_op_store(struct compile_state *state,
16646         struct triple *ins, FILE *fp)
16647 {
16648         struct triple *dst, *src;
16649         dst = LHS(ins, 0);
16650         src = RHS(ins, 0);
16651         if (is_const(src) && (src->op == OP_INTCONST)) {
16652                 long_t value;
16653                 value = (long_t)(src->u.cval);
16654                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16655                         type_suffix(state, src->type),
16656                         value,
16657                         reg(state, dst, REGCM_GPR32));
16658         }
16659         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16660                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16661                         type_suffix(state, src->type),
16662                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16663                         dst->u.cval);
16664         }
16665         else {
16666                 if (is_const(src) || is_const(dst)) {
16667                         internal_error(state, ins, "unknown store operation");
16668                 }
16669                 fprintf(fp, "\tmov%s %s, (%s)\n",
16670                         type_suffix(state, src->type),
16671                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16672                         reg(state, dst, REGCM_GPR32));
16673         }
16674         
16675         
16676 }
16677
16678 static void print_op_smul(struct compile_state *state,
16679         struct triple *ins, FILE *fp)
16680 {
16681         if (!is_const(RHS(ins, 1))) {
16682                 fprintf(fp, "\timul %s, %s\n",
16683                         reg(state, RHS(ins, 1), REGCM_GPR32),
16684                         reg(state, RHS(ins, 0), REGCM_GPR32));
16685         }
16686         else {
16687                 fprintf(fp, "\timul ");
16688                 print_const_val(state, RHS(ins, 1), fp);
16689                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16690         }
16691 }
16692
16693 static void print_op_cmp(struct compile_state *state,
16694         struct triple *ins, FILE *fp)
16695 {
16696         unsigned mask;
16697         int dreg;
16698         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16699         dreg = check_reg(state, ins, REGCM_FLAGS);
16700         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16701                 internal_error(state, ins, "bad dest register for cmp");
16702         }
16703         if (is_const(RHS(ins, 1))) {
16704                 fprintf(fp, "\tcmp ");
16705                 print_const_val(state, RHS(ins, 1), fp);
16706                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16707         }
16708         else {
16709                 unsigned lmask, rmask;
16710                 int lreg, rreg;
16711                 lreg = check_reg(state, RHS(ins, 0), mask);
16712                 rreg = check_reg(state, RHS(ins, 1), mask);
16713                 lmask = arch_reg_regcm(state, lreg);
16714                 rmask = arch_reg_regcm(state, rreg);
16715                 mask = lmask & rmask;
16716                 fprintf(fp, "\tcmp %s, %s\n",
16717                         reg(state, RHS(ins, 1), mask),
16718                         reg(state, RHS(ins, 0), mask));
16719         }
16720 }
16721
16722 static void print_op_test(struct compile_state *state,
16723         struct triple *ins, FILE *fp)
16724 {
16725         unsigned mask;
16726         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16727         fprintf(fp, "\ttest %s, %s\n",
16728                 reg(state, RHS(ins, 0), mask),
16729                 reg(state, RHS(ins, 0), mask));
16730 }
16731
16732 static void print_op_branch(struct compile_state *state,
16733         struct triple *branch, FILE *fp)
16734 {
16735         const char *bop = "j";
16736         if (branch->op == OP_JMP) {
16737                 if (TRIPLE_RHS(branch->sizes) != 0) {
16738                         internal_error(state, branch, "jmp with condition?");
16739                 }
16740                 bop = "jmp";
16741         }
16742         else {
16743                 struct triple *ptr;
16744                 if (TRIPLE_RHS(branch->sizes) != 1) {
16745                         internal_error(state, branch, "jmpcc without condition?");
16746                 }
16747                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16748                 if ((RHS(branch, 0)->op != OP_CMP) &&
16749                         (RHS(branch, 0)->op != OP_TEST)) {
16750                         internal_error(state, branch, "bad branch test");
16751                 }
16752 #warning "FIXME I have observed instructions between the test and branch instructions"
16753                 ptr = RHS(branch, 0);
16754                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16755                         if (ptr->op != OP_COPY) {
16756                                 internal_error(state, branch, "branch does not follow test");
16757                         }
16758                 }
16759                 switch(branch->op) {
16760                 case OP_JMP_EQ:       bop = "jz";  break;
16761                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
16762                 case OP_JMP_SLESS:    bop = "jl";  break;
16763                 case OP_JMP_ULESS:    bop = "jb";  break;
16764                 case OP_JMP_SMORE:    bop = "jg";  break;
16765                 case OP_JMP_UMORE:    bop = "ja";  break;
16766                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
16767                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
16768                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
16769                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
16770                 default:
16771                         internal_error(state, branch, "Invalid branch op");
16772                         break;
16773                 }
16774                 
16775         }
16776         fprintf(fp, "\t%s L%s%lu\n",
16777                 bop, 
16778                 state->label_prefix,
16779                 TARG(branch, 0)->u.cval);
16780 }
16781
16782 static void print_op_set(struct compile_state *state,
16783         struct triple *set, FILE *fp)
16784 {
16785         const char *sop = "set";
16786         if (TRIPLE_RHS(set->sizes) != 1) {
16787                 internal_error(state, set, "setcc without condition?");
16788         }
16789         check_reg(state, RHS(set, 0), REGCM_FLAGS);
16790         if ((RHS(set, 0)->op != OP_CMP) &&
16791                 (RHS(set, 0)->op != OP_TEST)) {
16792                 internal_error(state, set, "bad set test");
16793         }
16794         if (RHS(set, 0)->next != set) {
16795                 internal_error(state, set, "set does not follow test");
16796         }
16797         switch(set->op) {
16798         case OP_SET_EQ:       sop = "setz";  break;
16799         case OP_SET_NOTEQ:    sop = "setnz"; break;
16800         case OP_SET_SLESS:    sop = "setl";  break;
16801         case OP_SET_ULESS:    sop = "setb";  break;
16802         case OP_SET_SMORE:    sop = "setg";  break;
16803         case OP_SET_UMORE:    sop = "seta";  break;
16804         case OP_SET_SLESSEQ:  sop = "setle"; break;
16805         case OP_SET_ULESSEQ:  sop = "setbe"; break;
16806         case OP_SET_SMOREEQ:  sop = "setge"; break;
16807         case OP_SET_UMOREEQ:  sop = "setae"; break;
16808         default:
16809                 internal_error(state, set, "Invalid set op");
16810                 break;
16811         }
16812         fprintf(fp, "\t%s %s\n",
16813                 sop, reg(state, set, REGCM_GPR8));
16814 }
16815
16816 static void print_op_bit_scan(struct compile_state *state, 
16817         struct triple *ins, FILE *fp) 
16818 {
16819         const char *op;
16820         switch(ins->op) {
16821         case OP_BSF: op = "bsf"; break;
16822         case OP_BSR: op = "bsr"; break;
16823         default: 
16824                 internal_error(state, ins, "unknown bit scan");
16825                 op = 0;
16826                 break;
16827         }
16828         fprintf(fp, 
16829                 "\t%s %s, %s\n"
16830                 "\tjnz 1f\n"
16831                 "\tmovl $-1, %s\n"
16832                 "1:\n",
16833                 op,
16834                 reg(state, RHS(ins, 0), REGCM_GPR32),
16835                 reg(state, ins, REGCM_GPR32),
16836                 reg(state, ins, REGCM_GPR32));
16837 }
16838
16839 static void print_const(struct compile_state *state,
16840         struct triple *ins, FILE *fp)
16841 {
16842         switch(ins->op) {
16843         case OP_INTCONST:
16844                 switch(ins->type->type & TYPE_MASK) {
16845                 case TYPE_CHAR:
16846                 case TYPE_UCHAR:
16847                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16848                         break;
16849                 case TYPE_SHORT:
16850                 case TYPE_USHORT:
16851                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16852                         break;
16853                 case TYPE_INT:
16854                 case TYPE_UINT:
16855                 case TYPE_LONG:
16856                 case TYPE_ULONG:
16857                         fprintf(fp, ".int %lu\n", ins->u.cval);
16858                         break;
16859                 default:
16860                         internal_error(state, ins, "Unknown constant type");
16861                 }
16862                 break;
16863         case OP_BLOBCONST:
16864         {
16865                 unsigned char *blob;
16866                 size_t size, i;
16867                 size = size_of(state, ins->type);
16868                 blob = ins->u.blob;
16869                 for(i = 0; i < size; i++) {
16870                         fprintf(fp, ".byte 0x%02x\n",
16871                                 blob[i]);
16872                 }
16873                 break;
16874         }
16875         default:
16876                 internal_error(state, ins, "Unknown constant type");
16877                 break;
16878         }
16879 }
16880
16881 #define TEXT_SECTION ".rom.text"
16882 #define DATA_SECTION ".rom.data"
16883
16884 static void print_sdecl(struct compile_state *state,
16885         struct triple *ins, FILE *fp)
16886 {
16887         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16888         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16889         fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16890         print_const(state, MISC(ins, 0), fp);
16891         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16892                 
16893 }
16894
16895 static void print_instruction(struct compile_state *state,
16896         struct triple *ins, FILE *fp)
16897 {
16898         /* Assumption: after I have exted the register allocator
16899          * everything is in a valid register. 
16900          */
16901         switch(ins->op) {
16902         case OP_ASM:
16903                 print_op_asm(state, ins, fp);
16904                 break;
16905         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
16906         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
16907         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
16908         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
16909         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
16910         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
16911         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
16912         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
16913         case OP_POS:    break;
16914         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
16915         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16916         case OP_INTCONST:
16917         case OP_ADDRCONST:
16918         case OP_BLOBCONST:
16919                 /* Don't generate anything here for constants */
16920         case OP_PHI:
16921                 /* Don't generate anything for variable declarations. */
16922                 break;
16923         case OP_SDECL:
16924                 print_sdecl(state, ins, fp);
16925                 break;
16926         case OP_WRITE: 
16927         case OP_COPY:   
16928                 print_op_move(state, ins, fp);
16929                 break;
16930         case OP_LOAD:
16931                 print_op_load(state, ins, fp);
16932                 break;
16933         case OP_STORE:
16934                 print_op_store(state, ins, fp);
16935                 break;
16936         case OP_SMUL:
16937                 print_op_smul(state, ins, fp);
16938                 break;
16939         case OP_CMP:    print_op_cmp(state, ins, fp); break;
16940         case OP_TEST:   print_op_test(state, ins, fp); break;
16941         case OP_JMP:
16942         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16943         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16944         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16945         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16946         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16947                 print_op_branch(state, ins, fp);
16948                 break;
16949         case OP_SET_EQ:      case OP_SET_NOTEQ:
16950         case OP_SET_SLESS:   case OP_SET_ULESS:
16951         case OP_SET_SMORE:   case OP_SET_UMORE:
16952         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16953         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16954                 print_op_set(state, ins, fp);
16955                 break;
16956         case OP_INB:  case OP_INW:  case OP_INL:
16957                 print_op_in(state, ins, fp); 
16958                 break;
16959         case OP_OUTB: case OP_OUTW: case OP_OUTL:
16960                 print_op_out(state, ins, fp); 
16961                 break;
16962         case OP_BSF:
16963         case OP_BSR:
16964                 print_op_bit_scan(state, ins, fp);
16965                 break;
16966         case OP_RDMSR:
16967                 after_lhs(state, ins);
16968                 fprintf(fp, "\trdmsr\n");
16969                 break;
16970         case OP_WRMSR:
16971                 fprintf(fp, "\twrmsr\n");
16972                 break;
16973         case OP_HLT:
16974                 fprintf(fp, "\thlt\n");
16975                 break;
16976         case OP_LABEL:
16977                 if (!ins->use) {
16978                         return;
16979                 }
16980                 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16981                 break;
16982                 /* Ignore OP_PIECE */
16983         case OP_PIECE:
16984                 break;
16985                 /* Operations I am not yet certain how to handle */
16986         case OP_UMUL:
16987         case OP_SDIV: case OP_UDIV:
16988         case OP_SMOD: case OP_UMOD:
16989                 /* Operations that should never get here */
16990         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
16991         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
16992         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16993         default:
16994                 internal_error(state, ins, "unknown op: %d %s",
16995                         ins->op, tops(ins->op));
16996                 break;
16997         }
16998 }
16999
17000 static void print_instructions(struct compile_state *state)
17001 {
17002         struct triple *first, *ins;
17003         int print_location;
17004         struct occurance *last_occurance;
17005         FILE *fp;
17006         print_location = 1;
17007         last_occurance = 0;
17008         fp = state->output;
17009         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17010         first = RHS(state->main_function, 0);
17011         ins = first;
17012         do {
17013                 if (print_location && 
17014                         last_occurance != ins->occurance) {
17015                         if (!ins->occurance->parent) {
17016                                 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17017                                         ins->occurance->function,
17018                                         ins->occurance->filename,
17019                                         ins->occurance->line,
17020                                         ins->occurance->col);
17021                         }
17022                         else {
17023                                 struct occurance *ptr;
17024                                 fprintf(fp, "\t/*\n");
17025                                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17026                                         fprintf(fp, "\t * %s,%s:%d.%d\n",
17027                                                 ptr->function,
17028                                                 ptr->filename,
17029                                                 ptr->line,
17030                                                 ptr->col);
17031                                 }
17032                                 fprintf(fp, "\t */\n");
17033                                 
17034                         }
17035                         if (last_occurance) {
17036                                 put_occurance(last_occurance);
17037                         }
17038                         get_occurance(ins->occurance);
17039                         last_occurance = ins->occurance;
17040                 }
17041
17042                 print_instruction(state, ins, fp);
17043                 ins = ins->next;
17044         } while(ins != first);
17045         
17046 }
17047 static void generate_code(struct compile_state *state)
17048 {
17049         generate_local_labels(state);
17050         print_instructions(state);
17051         
17052 }
17053
17054 static void print_tokens(struct compile_state *state)
17055 {
17056         struct token *tk;
17057         tk = &state->token[0];
17058         do {
17059 #if 1
17060                 token(state, 0);
17061 #else
17062                 next_token(state, 0);
17063 #endif
17064                 loc(stdout, state, 0);
17065                 printf("%s <- `%s'\n",
17066                         tokens[tk->tok],
17067                         tk->ident ? tk->ident->name :
17068                         tk->str_len ? tk->val.str : "");
17069                 
17070         } while(tk->tok != TOK_EOF);
17071 }
17072
17073 static void compile(const char *filename, const char *ofilename, 
17074         int cpu, int debug, int opt, const char *label_prefix)
17075 {
17076         int i;
17077         struct compile_state state;
17078         memset(&state, 0, sizeof(state));
17079         state.file = 0;
17080         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17081                 memset(&state.token[i], 0, sizeof(state.token[i]));
17082                 state.token[i].tok = -1;
17083         }
17084         /* Remember the debug settings */
17085         state.cpu      = cpu;
17086         state.debug    = debug;
17087         state.optimize = opt;
17088         /* Remember the output filename */
17089         state.ofilename = ofilename;
17090         state.output    = fopen(state.ofilename, "w");
17091         if (!state.output) {
17092                 error(&state, 0, "Cannot open output file %s\n",
17093                         ofilename);
17094         }
17095         /* Remember the label prefix */
17096         state.label_prefix = label_prefix;
17097         /* Prep the preprocessor */
17098         state.if_depth = 0;
17099         state.if_value = 0;
17100         /* register the C keywords */
17101         register_keywords(&state);
17102         /* register the keywords the macro preprocessor knows */
17103         register_macro_keywords(&state);
17104         /* Memorize where some special keywords are. */
17105         state.i_continue = lookup(&state, "continue", 8);
17106         state.i_break    = lookup(&state, "break", 5);
17107         /* Enter the globl definition scope */
17108         start_scope(&state);
17109         register_builtins(&state);
17110         compile_file(&state, filename, 1);
17111 #if 0
17112         print_tokens(&state);
17113 #endif  
17114         decls(&state);
17115         /* Exit the global definition scope */
17116         end_scope(&state);
17117
17118         /* Now that basic compilation has happened 
17119          * optimize the intermediate code 
17120          */
17121         optimize(&state);
17122
17123         generate_code(&state);
17124         if (state.debug) {
17125                 fprintf(stderr, "done\n");
17126         }
17127 }
17128
17129 static void version(void)
17130 {
17131         printf("romcc " VERSION " released " RELEASE_DATE "\n");
17132 }
17133
17134 static void usage(void)
17135 {
17136         version();
17137         printf(
17138                 "Usage: romcc <source>.c\n"
17139                 "Compile a C source file without using ram\n"
17140         );
17141 }
17142
17143 static void arg_error(char *fmt, ...)
17144 {
17145         va_list args;
17146         va_start(args, fmt);
17147         vfprintf(stderr, fmt, args);
17148         va_end(args);
17149         usage();
17150         exit(1);
17151 }
17152
17153 int main(int argc, char **argv)
17154 {
17155         const char *filename;
17156         const char *ofilename;
17157         const char *label_prefix;
17158         int cpu;
17159         int last_argc;
17160         int debug;
17161         int optimize;
17162         cpu = CPU_DEFAULT;
17163         label_prefix = "";
17164         ofilename = "auto.inc";
17165         optimize = 0;
17166         debug = 0;
17167         last_argc = -1;
17168         while((argc > 1) && (argc != last_argc)) {
17169                 last_argc = argc;
17170                 if (strncmp(argv[1], "--debug=", 8) == 0) {
17171                         debug = atoi(argv[1] + 8);
17172                         argv++;
17173                         argc--;
17174                 }
17175                 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17176                         label_prefix= argv[1] + 15;
17177                         argv++;
17178                         argc--;
17179                 }
17180                 else if ((strcmp(argv[1],"-O") == 0) ||
17181                         (strcmp(argv[1], "-O1") == 0)) {
17182                         optimize = 1;
17183                         argv++;
17184                         argc--;
17185                 }
17186                 else if (strcmp(argv[1],"-O2") == 0) {
17187                         optimize = 2;
17188                         argv++;
17189                         argc--;
17190                 }
17191                 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17192                         ofilename = argv[2];
17193                         argv += 2;
17194                         argc -= 2;
17195                 }
17196                 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17197                         cpu = arch_encode_cpu(argv[1] + 6);
17198                         if (cpu == BAD_CPU) {
17199                                 arg_error("Invalid cpu specified: %s\n",
17200                                         argv[1] + 6);
17201                         }
17202                         argv++;
17203                         argc--;
17204                 }
17205         }
17206         if (argc != 2) {
17207                 arg_error("Wrong argument count %d\n", argc);
17208         }
17209         filename = argv[1];
17210         compile(filename, ofilename, cpu, debug, optimize, label_prefix);
17211
17212         return 0;
17213 }