- A new test case for romcc
[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 1
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 };
219 struct hash_entry;
220 struct token {
221         int tok;
222         struct hash_entry *ident;
223         int str_len;
224         union {
225                 ulong_t integer;
226                 const char *str;
227         } val;
228 };
229
230 /* I have two classes of types:
231  * Operational types.
232  * Logical types.  (The type the C standard says the operation is of)
233  *
234  * The operational types are:
235  * chars
236  * shorts
237  * ints
238  * longs
239  *
240  * floats
241  * doubles
242  * long doubles
243  *
244  * pointer
245  */
246
247
248 /* Machine model.
249  * No memory is useable by the compiler.
250  * There is no floating point support.
251  * All operations take place in general purpose registers.
252  * There is one type of general purpose register.
253  * Unsigned longs are stored in that general purpose register.
254  */
255
256 /* Operations on general purpose registers.
257  */
258
259 #define OP_SMUL       0
260 #define OP_UMUL       1
261 #define OP_SDIV       2
262 #define OP_UDIV       3
263 #define OP_SMOD       4
264 #define OP_UMOD       5
265 #define OP_ADD        6
266 #define OP_SUB        7
267 #define OP_SL         8
268 #define OP_USR        9
269 #define OP_SSR       10 
270 #define OP_AND       11 
271 #define OP_XOR       12
272 #define OP_OR        13
273 #define OP_POS       14 /* Dummy positive operator don't use it */
274 #define OP_NEG       15
275 #define OP_INVERT    16
276                      
277 #define OP_EQ        20
278 #define OP_NOTEQ     21
279 #define OP_SLESS     22
280 #define OP_ULESS     23
281 #define OP_SMORE     24
282 #define OP_UMORE     25
283 #define OP_SLESSEQ   26
284 #define OP_ULESSEQ   27
285 #define OP_SMOREEQ   28
286 #define OP_UMOREEQ   29
287                      
288 #define OP_LFALSE    30  /* Test if the expression is logically false */
289 #define OP_LTRUE     31  /* Test if the expression is logcially true */
290
291 #define OP_LOAD      32
292 #define OP_STORE     33
293
294 #define OP_NOOP      34
295
296 #define OP_MIN_CONST 50
297 #define OP_MAX_CONST 59
298 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
299 #define OP_INTCONST  50
300 #define OP_BLOBCONST 51
301 /* For OP_BLOBCONST ->type holds the layout and size
302  * information.  u.blob holds a pointer to the raw binary
303  * data for the constant initializer.
304  */
305 #define OP_ADDRCONST 52
306 /* For OP_ADDRCONST ->type holds the type.
307  * MISC(0) holds the reference to the static variable.
308  * ->u.cval holds an offset from that value.
309  */
310
311 #define OP_WRITE     60 
312 /* OP_WRITE moves one pseudo register to another.
313  * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
314  * RHS(0) holds the psuedo to move.
315  */
316
317 #define OP_READ      61
318 /* OP_READ reads the value of a variable and makes
319  * it available for the pseudo operation.
320  * Useful for things like def-use chains.
321  * RHS(0) holds points to the triple to read from.
322  */
323 #define OP_COPY      62
324 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
325  */
326 #define OP_PIECE     63
327 /* OP_PIECE returns one piece of a instruction that returns a structure.
328  * MISC(0) is the instruction
329  * u.cval is the LHS piece of the instruction to return.
330  */
331 #define OP_ASM       64
332 /* OP_ASM holds a sequence of assembly instructions, the result
333  * of a C asm directive.
334  * RHS(x) holds input value x to the assembly sequence.
335  * LHS(x) holds the output value x from the assembly sequence.
336  * u.blob holds the string of assembly instructions.
337  */
338
339 #define OP_DEREF     65
340 /* OP_DEREF generates an lvalue from a pointer.
341  * RHS(0) holds the pointer value.
342  * OP_DEREF serves as a place holder to indicate all necessary
343  * checks have been done to indicate a value is an lvalue.
344  */
345 #define OP_DOT       66
346 /* OP_DOT references a submember of a structure lvalue.
347  * RHS(0) holds the lvalue.
348  * ->u.field holds the name of the field we want.
349  *
350  * Not seen outside of expressions.
351  */
352 #define OP_VAL       67
353 /* OP_VAL returns the value of a subexpression of the current expression.
354  * Useful for operators that have side effects.
355  * RHS(0) holds the expression.
356  * MISC(0) holds the subexpression of RHS(0) that is the
357  * value of the expression.
358  *
359  * Not seen outside of expressions.
360  */
361 #define OP_LAND      68
362 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
363  * Not seen outside of expressions.
364  */
365 #define OP_LOR       69
366 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
367  * Not seen outside of expressions.
368  */
369 #define OP_COND      70
370 /* OP_CODE performas a C ? : operation. 
371  * RHS(0) holds the test.
372  * RHS(1) holds the expression to evaluate if the test returns true.
373  * RHS(2) holds the expression to evaluate if the test returns false.
374  * Not seen outside of expressions.
375  */
376 #define OP_COMMA     71
377 /* OP_COMMA performacs a C comma operation.
378  * That is RHS(0) is evaluated, then RHS(1)
379  * and the value of RHS(1) is returned.
380  * Not seen outside of expressions.
381  */
382
383 #define OP_CALL      72
384 /* OP_CALL performs a procedure call. 
385  * MISC(0) holds a pointer to the OP_LIST of a function
386  * RHS(x) holds argument x of a function
387  * 
388  * Currently not seen outside of expressions.
389  */
390 #define OP_VAL_VEC   74
391 /* OP_VAL_VEC is an array of triples that are either variable
392  * or values for a structure or an array.
393  * RHS(x) holds element x of the vector.
394  * triple->type->elements holds the size of the vector.
395  */
396
397 /* statements */
398 #define OP_LIST      80
399 /* OP_LIST Holds a list of statements, and a result value.
400  * RHS(0) holds the list of statements.
401  * MISC(0) holds the value of the statements.
402  */
403
404 #define OP_BRANCH    81 /* branch */
405 /* For branch instructions
406  * TARG(0) holds the branch target.
407  * RHS(0) if present holds the branch condition.
408  * ->next holds where to branch to if the branch is not taken.
409  * The branch target can only be a decl...
410  */
411
412 #define OP_LABEL     83
413 /* OP_LABEL is a triple that establishes an target for branches.
414  * ->use is the list of all branches that use this label.
415  */
416
417 #define OP_ADECL     84 
418 /* OP_DECL is a triple that establishes an lvalue for assignments.
419  * ->use is a list of statements that use the variable.
420  */
421
422 #define OP_SDECL     85
423 /* OP_SDECL is a triple that establishes a variable of static
424  * storage duration.
425  * ->use is a list of statements that use the variable.
426  * MISC(0) holds the initializer expression.
427  */
428
429
430 #define OP_PHI       86
431 /* OP_PHI is a triple used in SSA form code.  
432  * It is used when multiple code paths merge and a variable needs
433  * a single assignment from any of those code paths.
434  * The operation is a cross between OP_DECL and OP_WRITE, which
435  * is what OP_PHI is geneared from.
436  * 
437  * RHS(x) points to the value from code path x
438  * The number of RHS entries is the number of control paths into the block
439  * in which OP_PHI resides.  The elements of the array point to point
440  * to the variables OP_PHI is derived from.
441  *
442  * MISC(0) holds a pointer to the orginal OP_DECL node.
443  */
444
445 /* Architecture specific instructions */
446 #define OP_CMP         100
447 #define OP_TEST        101
448 #define OP_SET_EQ      102
449 #define OP_SET_NOTEQ   103
450 #define OP_SET_SLESS   104
451 #define OP_SET_ULESS   105
452 #define OP_SET_SMORE   106
453 #define OP_SET_UMORE   107
454 #define OP_SET_SLESSEQ 108
455 #define OP_SET_ULESSEQ 109
456 #define OP_SET_SMOREEQ 110
457 #define OP_SET_UMOREEQ 111
458
459 #define OP_JMP         112
460 #define OP_JMP_EQ      113
461 #define OP_JMP_NOTEQ   114
462 #define OP_JMP_SLESS   115
463 #define OP_JMP_ULESS   116
464 #define OP_JMP_SMORE   117
465 #define OP_JMP_UMORE   118
466 #define OP_JMP_SLESSEQ 119
467 #define OP_JMP_ULESSEQ 120
468 #define OP_JMP_SMOREEQ 121
469 #define OP_JMP_UMOREEQ 122
470
471 /* Builtin operators that it is just simpler to use the compiler for */
472 #define OP_INB         130
473 #define OP_INW         131
474 #define OP_INL         132
475 #define OP_OUTB        133
476 #define OP_OUTW        134
477 #define OP_OUTL        135
478 #define OP_BSF         136
479 #define OP_BSR         137
480 #define OP_RDMSR       138
481 #define OP_WRMSR       139
482 #define OP_HLT         140
483
484 struct op_info {
485         const char *name;
486         unsigned flags;
487 #define PURE   1
488 #define IMPURE 2
489 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
490 #define DEF    4
491 #define BLOCK  8 /* Triple stores the current block */
492         unsigned char lhs, rhs, misc, targ;
493 };
494
495 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
496         .name = (NAME), \
497         .flags = (FLAGS), \
498         .lhs = (LHS), \
499         .rhs = (RHS), \
500         .misc = (MISC), \
501         .targ = (TARG), \
502          }
503 static const struct op_info table_ops[] = {
504 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
505 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
506 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
507 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
508 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
509 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
510 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
511 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
512 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
513 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
514 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
515 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
516 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
517 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
518 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
519 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
520 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
521
522 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
523 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
524 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
525 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
526 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
527 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
528 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
529 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
530 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
531 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
532 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
533 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
534
535 [OP_LOAD       ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "load"),
536 [OP_STORE      ] = OP( 1,  1, 0, 0, IMPURE | BLOCK , "store"),
537
538 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK, "noop"),
539
540 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
541 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE, "blobconst"),
542 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
543
544 [OP_WRITE      ] = OP( 1,  1, 0, 0, PURE | BLOCK, "write"),
545 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
546 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
547 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF, "piece"),
548 [OP_ASM        ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
549 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"), 
550 [OP_DOT        ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "dot"),
551
552 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
553 [OP_LAND       ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "land"),
554 [OP_LOR        ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "lor"),
555 [OP_COND       ] = OP( 0,  3, 0, 0, 0 | DEF | BLOCK, "cond"),
556 [OP_COMMA      ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "comma"),
557 /* Call is special most it can stand in for anything so it depends on context */
558 [OP_CALL       ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
559 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
560 [OP_VAL_VEC    ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
561
562 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF, "list"),
563 /* The number of targets for OP_BRANCH depends on context */
564 [OP_BRANCH     ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
565 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "label"),
566 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "adecl"),
567 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK, "sdecl"),
568 /* The number of RHS elements of OP_PHI depend upon context */
569 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
570
571 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
572 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
573 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
574 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
575 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
576 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
577 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
578 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
579 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
580 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
581 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
582 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
583 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK, "jmp"),
584 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_eq"),
585 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_noteq"),
586 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_sless"),
587 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_uless"),
588 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smore"),
589 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umore"),
590 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
591 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
592 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
593 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
594
595 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
596 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
597 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
598 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
599 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
600 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
601 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
602 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
603 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
604 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
605 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
606 };
607 #undef OP
608 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
609
610 static const char *tops(int index) 
611 {
612         static const char unknown[] = "unknown op";
613         if (index < 0) {
614                 return unknown;
615         }
616         if (index > OP_MAX) {
617                 return unknown;
618         }
619         return table_ops[index].name;
620 }
621
622 struct asm_info;
623 struct triple;
624 struct block;
625 struct triple_set {
626         struct triple_set *next;
627         struct triple *member;
628 };
629
630 #define MAX_LHS  15
631 #define MAX_RHS  15
632 #define MAX_MISC 15
633 #define MAX_TARG 15
634
635 struct triple {
636         struct triple *next, *prev;
637         struct triple_set *use;
638         struct type *type;
639         unsigned char op;
640         unsigned char template_id;
641         unsigned short sizes;
642 #define TRIPLE_LHS(SIZES)  (((SIZES) >>  0) & 0x0f)
643 #define TRIPLE_RHS(SIZES)  (((SIZES) >>  4) & 0x0f)
644 #define TRIPLE_MISC(SIZES) (((SIZES) >>  8) & 0x0f)
645 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
646 #define TRIPLE_SIZE(SIZES) \
647         ((((SIZES) >> 0) & 0x0f) + \
648         (((SIZES) >>  4) & 0x0f) + \
649         (((SIZES) >>  8) & 0x0f) + \
650         (((SIZES) >> 12) & 0x0f))
651 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
652         ((((LHS) & 0x0f) <<  0) | \
653         (((RHS) & 0x0f)  <<  4) | \
654         (((MISC) & 0x0f) <<  8) | \
655         (((TARG) & 0x0f) << 12))
656 #define TRIPLE_LHS_OFF(SIZES)  (0)
657 #define TRIPLE_RHS_OFF(SIZES)  (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
658 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
659 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
660 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
661 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
662 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
663 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
664         unsigned id; /* A scratch value and finally the register */
665 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
666 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
667 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
668         const char *filename;
669         int line;
670         int col;
671         union {
672                 ulong_t cval;
673                 struct block  *block;
674                 void *blob;
675                 struct hash_entry *field;
676                 struct asm_info *ainfo;
677         } u;
678         struct triple *param[2];
679 };
680
681 struct reg_info {
682         unsigned reg;
683         unsigned regcm;
684 };
685 struct ins_template {
686         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
687 };
688
689 struct asm_info {
690         struct ins_template tmpl;
691         char *str;
692 };
693
694 struct block_set {
695         struct block_set *next;
696         struct block *member;
697 };
698 struct block {
699         struct block *work_next;
700         struct block *left, *right;
701         struct triple *first, *last;
702         int users;
703         struct block_set *use;
704         struct block_set *idominates;
705         struct block_set *domfrontier;
706         struct block *idom;
707         struct block_set *ipdominates;
708         struct block_set *ipdomfrontier;
709         struct block *ipdom;
710         int vertex;
711         
712 };
713
714 struct symbol {
715         struct symbol *next;
716         struct hash_entry *ident;
717         struct triple *def;
718         struct type *type;
719         int scope_depth;
720 };
721
722 struct macro {
723         struct hash_entry *ident;
724         char *buf;
725         int buf_len;
726 };
727
728 struct hash_entry {
729         struct hash_entry *next;
730         const char *name;
731         int name_len;
732         int tok;
733         struct macro *sym_define;
734         struct symbol *sym_label;
735         struct symbol *sym_struct;
736         struct symbol *sym_ident;
737 };
738
739 #define HASH_TABLE_SIZE 2048
740
741 struct compile_state {
742         const char *label_prefix;
743         const char *ofilename;
744         FILE *output;
745         struct triple *vars;
746         struct file_state *file;
747         struct token token[4];
748         struct hash_entry *hash_table[HASH_TABLE_SIZE];
749         struct hash_entry *i_continue;
750         struct hash_entry *i_break;
751         int scope_depth;
752         int if_depth, if_value;
753         int macro_line;
754         struct file_state *macro_file;
755         struct triple *main_function;
756         struct block *first_block, *last_block;
757         int last_vertex;
758         int cpu;
759         int debug;
760         int optimize;
761 };
762
763 /* visibility global/local */
764 /* static/auto duration */
765 /* typedef, register, inline */
766 #define STOR_SHIFT         0
767 #define STOR_MASK     0x000f
768 /* Visibility */
769 #define STOR_GLOBAL   0x0001
770 /* Duration */
771 #define STOR_PERM     0x0002
772 /* Storage specifiers */
773 #define STOR_AUTO     0x0000
774 #define STOR_STATIC   0x0002
775 #define STOR_EXTERN   0x0003
776 #define STOR_REGISTER 0x0004
777 #define STOR_TYPEDEF  0x0008
778 #define STOR_INLINE   0x000c
779
780 #define QUAL_SHIFT         4
781 #define QUAL_MASK     0x0070
782 #define QUAL_NONE     0x0000
783 #define QUAL_CONST    0x0010
784 #define QUAL_VOLATILE 0x0020
785 #define QUAL_RESTRICT 0x0040
786
787 #define TYPE_SHIFT         8
788 #define TYPE_MASK     0x1f00
789 #define TYPE_INTEGER(TYPE)    (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
790 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
791 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
792 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
793 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
794 #define TYPE_RANK(TYPE)       ((TYPE) & ~0x0100)
795 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
796 #define TYPE_DEFAULT  0x0000
797 #define TYPE_VOID     0x0100
798 #define TYPE_CHAR     0x0200
799 #define TYPE_UCHAR    0x0300
800 #define TYPE_SHORT    0x0400
801 #define TYPE_USHORT   0x0500
802 #define TYPE_INT      0x0600
803 #define TYPE_UINT     0x0700
804 #define TYPE_LONG     0x0800
805 #define TYPE_ULONG    0x0900
806 #define TYPE_LLONG    0x0a00 /* long long */
807 #define TYPE_ULLONG   0x0b00
808 #define TYPE_FLOAT    0x0c00
809 #define TYPE_DOUBLE   0x0d00
810 #define TYPE_LDOUBLE  0x0e00 /* long double */
811 #define TYPE_STRUCT   0x1000
812 #define TYPE_ENUM     0x1100
813 #define TYPE_POINTER  0x1200 
814 /* For TYPE_POINTER:
815  * type->left holds the type pointed to.
816  */
817 #define TYPE_FUNCTION 0x1300 
818 /* For TYPE_FUNCTION:
819  * type->left holds the return type.
820  * type->right holds the...
821  */
822 #define TYPE_PRODUCT  0x1400
823 /* TYPE_PRODUCT is a basic building block when defining structures
824  * type->left holds the type that appears first in memory.
825  * type->right holds the type that appears next in memory.
826  */
827 #define TYPE_OVERLAP  0x1500
828 /* TYPE_OVERLAP is a basic building block when defining unions
829  * type->left and type->right holds to types that overlap
830  * each other in memory.
831  */
832 #define TYPE_ARRAY    0x1600
833 /* TYPE_ARRAY is a basic building block when definitng arrays.
834  * type->left holds the type we are an array of.
835  * type-> holds the number of elements.
836  */
837
838 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
839
840 struct type {
841         unsigned int type;
842         struct type *left, *right;
843         ulong_t elements;
844         struct hash_entry *field_ident;
845         struct hash_entry *type_ident;
846 };
847
848 #define MAX_REGISTERS      75
849 #define MAX_REG_EQUIVS     16
850 #if 1
851 #define REGISTER_BITS      16
852 #else
853 #define REGISTER_BITS      28
854 #endif
855 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
856 #define TEMPLATE_BITS      6
857 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
858 #define MAX_REGC           12
859 #define REG_UNSET          0
860 #define REG_UNNEEDED       1
861 #define REG_VIRT0          (MAX_REGISTERS + 0)
862 #define REG_VIRT1          (MAX_REGISTERS + 1)
863 #define REG_VIRT2          (MAX_REGISTERS + 2)
864 #define REG_VIRT3          (MAX_REGISTERS + 3)
865 #define REG_VIRT4          (MAX_REGISTERS + 4)
866 #define REG_VIRT5          (MAX_REGISTERS + 5)
867 #define REG_VIRT6          (MAX_REGISTERS + 5)
868 #define REG_VIRT7          (MAX_REGISTERS + 5)
869 #define REG_VIRT8          (MAX_REGISTERS + 5)
870 #define REG_VIRT9          (MAX_REGISTERS + 5)
871
872 /* Provision for 8 register classes */
873 #if 1
874 #define REG_SHIFT  0
875 #define REGC_SHIFT REGISTER_BITS
876 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
877 #define REG_MASK (MAX_VIRT_REGISTERS -1)
878 #define ID_REG(ID)              ((ID) & REG_MASK)
879 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
880 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
881 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
882 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
883                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
884 #else
885 #define REG_MASK (MAX_VIRT_REGISTERS -1)
886 #define ID_REG(ID)              ((ID) & REG_MASK)
887 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
888 #endif
889
890 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
891 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
892 static void arch_reg_equivs(
893         struct compile_state *state, unsigned *equiv, int reg);
894 static int arch_select_free_register(
895         struct compile_state *state, char *used, int classes);
896 static unsigned arch_regc_size(struct compile_state *state, int class);
897 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
898 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
899 static const char *arch_reg_str(int reg);
900 static struct reg_info arch_reg_constraint(
901         struct compile_state *state, struct type *type, const char *constraint);
902 static struct reg_info arch_reg_clobber(
903         struct compile_state *state, const char *clobber);
904 static struct reg_info arch_reg_lhs(struct compile_state *state, 
905         struct triple *ins, int index);
906 static struct reg_info arch_reg_rhs(struct compile_state *state, 
907         struct triple *ins, int index);
908 static struct triple *transform_to_arch_instruction(
909         struct compile_state *state, struct triple *ins);
910
911
912
913 #define DEBUG_ABORT_ON_ERROR    0x0001
914 #define DEBUG_INTERMEDIATE_CODE 0x0002
915 #define DEBUG_CONTROL_FLOW      0x0004
916 #define DEBUG_BASIC_BLOCKS      0x0008
917 #define DEBUG_FDOMINATORS       0x0010
918 #define DEBUG_RDOMINATORS       0x0020
919 #define DEBUG_TRIPLES           0x0040
920 #define DEBUG_INTERFERENCE      0x0080
921 #define DEBUG_ARCH_CODE         0x0100
922 #define DEBUG_CODE_ELIMINATION  0x0200
923 #define DEBUG_INSERTED_COPIES   0x0400
924
925 #define GLOBAL_SCOPE_DEPTH 1
926
927 static void compile_file(struct compile_state *old_state, const char *filename, int local);
928
929 static void do_cleanup(struct compile_state *state)
930 {
931         if (state->output) {
932                 fclose(state->output);
933                 unlink(state->ofilename);
934         }
935 }
936
937 static int get_col(struct file_state *file)
938 {
939         int col;
940         char *ptr, *end;
941         ptr = file->line_start;
942         end = file->pos;
943         for(col = 0; ptr < end; ptr++) {
944                 if (*ptr != '\t') {
945                         col++;
946                 } 
947                 else {
948                         col = (col & ~7) + 8;
949                 }
950         }
951         return col;
952 }
953
954 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
955 {
956         int col;
957         if (triple) {
958                 fprintf(fp, "%s:%d.%d: ", 
959                         triple->filename, triple->line, triple->col);
960                 return;
961         }
962         if (!state->file) {
963                 return;
964         }
965         col = get_col(state->file);
966         fprintf(fp, "%s:%d.%d: ", 
967                 state->file->basename, state->file->line, col);
968 }
969
970 static void __internal_error(struct compile_state *state, struct triple *ptr, 
971         char *fmt, ...)
972 {
973         va_list args;
974         va_start(args, fmt);
975         loc(stderr, state, ptr);
976         if (ptr) {
977                 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
978         }
979         fprintf(stderr, "Internal compiler error: ");
980         vfprintf(stderr, fmt, args);
981         fprintf(stderr, "\n");
982         va_end(args);
983         do_cleanup(state);
984         abort();
985 }
986
987
988 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
989         char *fmt, ...)
990 {
991         va_list args;
992         va_start(args, fmt);
993         loc(stderr, state, ptr);
994         fprintf(stderr, "Internal compiler warning: ");
995         vfprintf(stderr, fmt, args);
996         fprintf(stderr, "\n");
997         va_end(args);
998 }
999
1000
1001
1002 static void __error(struct compile_state *state, struct triple *ptr, 
1003         char *fmt, ...)
1004 {
1005         va_list args;
1006         va_start(args, fmt);
1007         loc(stderr, state, ptr);
1008         vfprintf(stderr, fmt, args);
1009         va_end(args);
1010         fprintf(stderr, "\n");
1011         do_cleanup(state);
1012         if (state->debug & DEBUG_ABORT_ON_ERROR) {
1013                 abort();
1014         }
1015         exit(1);
1016 }
1017
1018 static void __warning(struct compile_state *state, struct triple *ptr, 
1019         char *fmt, ...)
1020 {
1021         va_list args;
1022         va_start(args, fmt);
1023         loc(stderr, state, ptr);
1024         fprintf(stderr, "warning: "); 
1025         vfprintf(stderr, fmt, args);
1026         fprintf(stderr, "\n");
1027         va_end(args);
1028 }
1029
1030 #if DEBUG_ERROR_MESSAGES 
1031 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1032 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1033 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1034 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1035 #else
1036 #  define internal_error __internal_error
1037 #  define internal_warning __internal_warning
1038 #  define error __error
1039 #  define warning __warning
1040 #endif
1041 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1042
1043 static void valid_op(struct compile_state *state, int op)
1044 {
1045         char *fmt = "invalid op: %d";
1046         if (op >= OP_MAX) {
1047                 internal_error(state, 0, fmt, op);
1048         }
1049         if (op < 0) {
1050                 internal_error(state, 0, fmt, op);
1051         }
1052 }
1053
1054 static void valid_ins(struct compile_state *state, struct triple *ptr)
1055 {
1056         valid_op(state, ptr->op);
1057 }
1058
1059 static void process_trigraphs(struct compile_state *state)
1060 {
1061         char *src, *dest, *end;
1062         struct file_state *file;
1063         file = state->file;
1064         src = dest = file->buf;
1065         end = file->buf + file->size;
1066         while((end - src) >= 3) {
1067                 if ((src[0] == '?') && (src[1] == '?')) {
1068                         int c = -1;
1069                         switch(src[2]) {
1070                         case '=': c = '#'; break;
1071                         case '/': c = '\\'; break;
1072                         case '\'': c = '^'; break;
1073                         case '(': c = '['; break;
1074                         case ')': c = ']'; break;
1075                         case '!': c = '!'; break;
1076                         case '<': c = '{'; break;
1077                         case '>': c = '}'; break;
1078                         case '-': c = '~'; break;
1079                         }
1080                         if (c != -1) {
1081                                 *dest++ = c;
1082                                 src += 3;
1083                         }
1084                         else {
1085                                 *dest++ = *src++;
1086                         }
1087                 }
1088                 else {
1089                         *dest++ = *src++;
1090                 }
1091         }
1092         while(src != end) {
1093                 *dest++ = *src++;
1094         }
1095         file->size = dest - file->buf;
1096 }
1097
1098 static void splice_lines(struct compile_state *state)
1099 {
1100         char *src, *dest, *end;
1101         struct file_state *file;
1102         file = state->file;
1103         src = dest = file->buf;
1104         end = file->buf + file->size;
1105         while((end - src) >= 2) {
1106                 if ((src[0] == '\\') && (src[1] == '\n')) {
1107                         src += 2;
1108                 }
1109                 else {
1110                         *dest++ = *src++;
1111                 }
1112         }
1113         while(src != end) {
1114                 *dest++ = *src++;
1115         }
1116         file->size = dest - file->buf;
1117 }
1118
1119 static struct type void_type;
1120 static void use_triple(struct triple *used, struct triple *user)
1121 {
1122         struct triple_set **ptr, *new;
1123         if (!used)
1124                 return;
1125         if (!user)
1126                 return;
1127         ptr = &used->use;
1128         while(*ptr) {
1129                 if ((*ptr)->member == user) {
1130                         return;
1131                 }
1132                 ptr = &(*ptr)->next;
1133         }
1134         /* Append new to the head of the list, 
1135          * copy_func and rename_block_variables
1136          * depends on this.
1137          */
1138         new = xcmalloc(sizeof(*new), "triple_set");
1139         new->member = user;
1140         new->next   = used->use;
1141         used->use   = new;
1142 }
1143
1144 static void unuse_triple(struct triple *used, struct triple *unuser)
1145 {
1146         struct triple_set *use, **ptr;
1147         if (!used) {
1148                 return;
1149         }
1150         ptr = &used->use;
1151         while(*ptr) {
1152                 use = *ptr;
1153                 if (use->member == unuser) {
1154                         *ptr = use->next;
1155                         xfree(use);
1156                 }
1157                 else {
1158                         ptr = &use->next;
1159                 }
1160         }
1161 }
1162
1163 static void push_triple(struct triple *used, struct triple *user)
1164 {
1165         struct triple_set *new;
1166         if (!used)
1167                 return;
1168         if (!user)
1169                 return;
1170         /* Append new to the head of the list,
1171          * it's the only sensible behavoir for a stack.
1172          */
1173         new = xcmalloc(sizeof(*new), "triple_set");
1174         new->member = user;
1175         new->next   = used->use;
1176         used->use   = new;
1177 }
1178
1179 static void pop_triple(struct triple *used, struct triple *unuser)
1180 {
1181         struct triple_set *use, **ptr;
1182         ptr = &used->use;
1183         while(*ptr) {
1184                 use = *ptr;
1185                 if (use->member == unuser) {
1186                         *ptr = use->next;
1187                         xfree(use);
1188                         /* Only free one occurance from the stack */
1189                         return;
1190                 }
1191                 else {
1192                         ptr = &use->next;
1193                 }
1194         }
1195 }
1196
1197
1198 /* The zero triple is used as a place holder when we are removing pointers
1199  * from a triple.  Having allows certain sanity checks to pass even
1200  * when the original triple that was pointed to is gone.
1201  */
1202 static struct triple zero_triple = {
1203         .next     = &zero_triple,
1204         .prev     = &zero_triple,
1205         .use      = 0,
1206         .op       = OP_INTCONST,
1207         .sizes    = TRIPLE_SIZES(0, 0, 0, 0),
1208         .id       = -1, /* An invalid id */
1209         .u = { .cval   = 0, },
1210         .filename = __FILE__,
1211         .line     = __LINE__,
1212         .col      = 0,
1213         .param { [0] = 0, [1] = 0, },
1214 };
1215
1216
1217 static unsigned short triple_sizes(struct compile_state *state,
1218         int op, struct type *type, int lhs_wanted, int rhs_wanted)
1219 {
1220         int lhs, rhs, misc, targ;
1221         valid_op(state, op);
1222         lhs = table_ops[op].lhs;
1223         rhs = table_ops[op].rhs;
1224         misc = table_ops[op].misc;
1225         targ = table_ops[op].targ;
1226         
1227         
1228         if (op == OP_CALL) {
1229                 struct type *param;
1230                 rhs = 0;
1231                 param = type->right;
1232                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1233                         rhs++;
1234                         param = param->right;
1235                 }
1236                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1237                         rhs++;
1238                 }
1239                 lhs = 0;
1240                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1241                         lhs = type->left->elements;
1242                 }
1243         }
1244         else if (op == OP_VAL_VEC) {
1245                 rhs = type->elements;
1246         }
1247         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1248                 rhs = rhs_wanted;
1249         }
1250         else if (op == OP_ASM) {
1251                 rhs = rhs_wanted;
1252                 lhs = lhs_wanted;
1253         }
1254         if ((rhs < 0) || (rhs > MAX_RHS)) {
1255                 internal_error(state, 0, "bad rhs");
1256         }
1257         if ((lhs < 0) || (lhs > MAX_LHS)) {
1258                 internal_error(state, 0, "bad lhs");
1259         }
1260         if ((misc < 0) || (misc > MAX_MISC)) {
1261                 internal_error(state, 0, "bad misc");
1262         }
1263         if ((targ < 0) || (targ > MAX_TARG)) {
1264                 internal_error(state, 0, "bad targs");
1265         }
1266         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1267 }
1268
1269 static struct triple *alloc_triple(struct compile_state *state, 
1270         int op, struct type *type, int lhs, int rhs,
1271         const char *filename, int line, int col)
1272 {
1273         size_t size, sizes, extra_count, min_count;
1274         struct triple *ret;
1275         sizes = triple_sizes(state, op, type, lhs, rhs);
1276
1277         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1278         extra_count = TRIPLE_SIZE(sizes);
1279         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1280
1281         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1282         ret = xcmalloc(size, "tripple");
1283         ret->op       = op;
1284         ret->sizes    = sizes;
1285         ret->type     = type;
1286         ret->next     = ret;
1287         ret->prev     = ret;
1288         ret->filename = filename;
1289         ret->line     = line;
1290         ret->col      = col;
1291         return ret;
1292 }
1293
1294 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1295 {
1296         struct triple *dup;
1297         int src_lhs, src_rhs, src_size;
1298         src_lhs = TRIPLE_LHS(src->sizes);
1299         src_rhs = TRIPLE_RHS(src->sizes);
1300         src_size = TRIPLE_SIZE(src->sizes);
1301         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1302                 src->filename, src->line, src->col);
1303         memcpy(dup, src, sizeof(*src));
1304         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1305         return dup;
1306 }
1307
1308 static struct triple *new_triple(struct compile_state *state, 
1309         int op, struct type *type, int lhs, int rhs)
1310 {
1311         struct triple *ret;
1312         const char *filename;
1313         int line, col;
1314         filename = 0;
1315         line = 0;
1316         col  = 0;
1317         if (state->file) {
1318                 filename = state->file->basename;
1319                 line     = state->file->line;
1320                 col      = get_col(state->file);
1321         }
1322         ret = alloc_triple(state, op, type, lhs, rhs,
1323                 filename, line, col);
1324         return ret;
1325 }
1326
1327 static struct triple *build_triple(struct compile_state *state, 
1328         int op, struct type *type, struct triple *left, struct triple *right,
1329         const char *filename, int line, int col)
1330 {
1331         struct triple *ret;
1332         size_t count;
1333         ret = alloc_triple(state, op, type, -1, -1, filename, line, col);
1334         count = TRIPLE_SIZE(ret->sizes);
1335         if (count > 0) {
1336                 ret->param[0] = left;
1337         }
1338         if (count > 1) {
1339                 ret->param[1] = right;
1340         }
1341         return ret;
1342 }
1343
1344 static struct triple *triple(struct compile_state *state, 
1345         int op, struct type *type, struct triple *left, struct triple *right)
1346 {
1347         struct triple *ret;
1348         size_t count;
1349         ret = new_triple(state, op, type, -1, -1);
1350         count = TRIPLE_SIZE(ret->sizes);
1351         if (count >= 1) {
1352                 ret->param[0] = left;
1353         }
1354         if (count >= 2) {
1355                 ret->param[1] = right;
1356         }
1357         return ret;
1358 }
1359
1360 static struct triple *branch(struct compile_state *state, 
1361         struct triple *targ, struct triple *test)
1362 {
1363         struct triple *ret;
1364         ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1365         if (test) {
1366                 RHS(ret, 0) = test;
1367         }
1368         TARG(ret, 0) = targ;
1369         /* record the branch target was used */
1370         if (!targ || (targ->op != OP_LABEL)) {
1371                 internal_error(state, 0, "branch not to label");
1372                 use_triple(targ, ret);
1373         }
1374         return ret;
1375 }
1376
1377
1378 static void insert_triple(struct compile_state *state,
1379         struct triple *first, struct triple *ptr)
1380 {
1381         if (ptr) {
1382                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1383                         internal_error(state, ptr, "expression already used");
1384                 }
1385                 ptr->next       = first;
1386                 ptr->prev       = first->prev;
1387                 ptr->prev->next = ptr;
1388                 ptr->next->prev = ptr;
1389                 if ((ptr->prev->op == OP_BRANCH) && 
1390                         TRIPLE_RHS(ptr->prev->sizes)) {
1391                         unuse_triple(first, ptr->prev);
1392                         use_triple(ptr, ptr->prev);
1393                 }
1394         }
1395 }
1396
1397 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1398 {
1399         /* This function is used to determine if u.block 
1400          * is utilized to store the current block number.
1401          */
1402         int stores_block;
1403         valid_ins(state, ins);
1404         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1405         return stores_block;
1406 }
1407
1408 static struct block *block_of_triple(struct compile_state *state, 
1409         struct triple *ins)
1410 {
1411         struct triple *first;
1412         first = RHS(state->main_function, 0);
1413         while(ins != first && !triple_stores_block(state, ins)) {
1414                 if (ins == ins->prev) {
1415                         internal_error(state, 0, "ins == ins->prev?");
1416                 }
1417                 ins = ins->prev;
1418         }
1419         if (!triple_stores_block(state, ins)) {
1420                 internal_error(state, ins, "Cannot find block");
1421         }
1422         return ins->u.block;
1423 }
1424
1425 static struct triple *pre_triple(struct compile_state *state,
1426         struct triple *base,
1427         int op, struct type *type, struct triple *left, struct triple *right)
1428 {
1429         struct block *block;
1430         struct triple *ret;
1431         /* If I am an OP_PIECE jump to the real instruction */
1432         if (base->op == OP_PIECE) {
1433                 base = MISC(base, 0);
1434         }
1435         block = block_of_triple(state, base);
1436         ret = build_triple(state, op, type, left, right, 
1437                 base->filename, base->line, base->col);
1438         if (triple_stores_block(state, ret)) {
1439                 ret->u.block = block;
1440         }
1441         insert_triple(state, base, ret);
1442         if (block->first == base) {
1443                 block->first = ret;
1444         }
1445         return ret;
1446 }
1447
1448 static struct triple *post_triple(struct compile_state *state,
1449         struct triple *base,
1450         int op, struct type *type, struct triple *left, struct triple *right)
1451 {
1452         struct block *block;
1453         struct triple *ret;
1454         int zlhs;
1455         /* If I am an OP_PIECE jump to the real instruction */
1456         if (base->op == OP_PIECE) {
1457                 base = MISC(base, 0);
1458         }
1459         /* If I have a left hand side skip over it */
1460         zlhs = TRIPLE_LHS(base->sizes);
1461         if (zlhs && (base->op != OP_WRITE) && (base->op != OP_STORE)) {
1462                 base = LHS(base, zlhs - 1);
1463         }
1464
1465         block = block_of_triple(state, base);
1466         ret = build_triple(state, op, type, left, right, 
1467                 base->filename, base->line, base->col);
1468         if (triple_stores_block(state, ret)) {
1469                 ret->u.block = block;
1470         }
1471         insert_triple(state, base->next, ret);
1472         if (block->last == base) {
1473                 block->last = ret;
1474         }
1475         return ret;
1476 }
1477
1478 static struct triple *label(struct compile_state *state)
1479 {
1480         /* Labels don't get a type */
1481         struct triple *result;
1482         result = triple(state, OP_LABEL, &void_type, 0, 0);
1483         return result;
1484 }
1485
1486 static void display_triple(FILE *fp, struct triple *ins)
1487 {
1488         if (ins->op == OP_INTCONST) {
1489                 fprintf(fp, "(%p) %3d %-2d %-10s <0x%08lx>          @ %s:%d.%d\n",
1490                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op), 
1491                         ins->u.cval,
1492                         ins->filename, ins->line, ins->col);
1493         }
1494         else if (ins->op == OP_ADDRCONST) {
1495                 fprintf(fp, "(%p) %3d %-2d %-10s %-10p <0x%08lx> @ %s:%d.%d\n",
1496                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op), 
1497                         MISC(ins, 0), ins->u.cval,
1498                         ins->filename, ins->line, ins->col);
1499         }
1500         else {
1501                 int i, count;
1502                 fprintf(fp, "(%p) %3d %-2d %-10s", 
1503                         ins, ID_REG(ins->id), ins->template_id, tops(ins->op));
1504                 count = TRIPLE_SIZE(ins->sizes);
1505                 for(i = 0; i < count; i++) {
1506                         fprintf(fp, " %-10p", ins->param[i]);
1507                 }
1508                 for(; i < 2; i++) {
1509                         fprintf(fp, "           ");
1510                 }
1511                 fprintf(fp, " @ %s:%d.%d\n", 
1512                         ins->filename, ins->line, ins->col);
1513         }
1514         fflush(fp);
1515 }
1516
1517 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1518 {
1519         /* Does the triple have no side effects.
1520          * I.e. Rexecuting the triple with the same arguments 
1521          * gives the same value.
1522          */
1523         unsigned pure;
1524         valid_ins(state, ins);
1525         pure = PURE_BITS(table_ops[ins->op].flags);
1526         if ((pure != PURE) && (pure != IMPURE)) {
1527                 internal_error(state, 0, "Purity of %s not known\n",
1528                         tops(ins->op));
1529         }
1530         return pure == PURE;
1531 }
1532
1533 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1534 {
1535         /* This function is used to determine which triples need
1536          * a register.
1537          */
1538         int is_branch;
1539         valid_ins(state, ins);
1540         is_branch = (table_ops[ins->op].targ != 0);
1541         return is_branch;
1542 }
1543
1544 static int triple_is_def(struct compile_state *state, struct triple *ins)
1545 {
1546         /* This function is used to determine which triples need
1547          * a register.
1548          */
1549         int is_def;
1550         valid_ins(state, ins);
1551         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1552         return is_def;
1553 }
1554
1555 static struct triple **triple_iter(struct compile_state *state,
1556         size_t count, struct triple **vector,
1557         struct triple *ins, struct triple **last)
1558 {
1559         struct triple **ret;
1560         ret = 0;
1561         if (count) {
1562                 if (!last) {
1563                         ret = vector;
1564                 }
1565                 else if ((last >= vector) && (last < (vector + count - 1))) {
1566                         ret = last + 1;
1567                 }
1568         }
1569         return ret;
1570         
1571 }
1572
1573 static struct triple **triple_lhs(struct compile_state *state,
1574         struct triple *ins, struct triple **last)
1575 {
1576         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1577                 ins, last);
1578 }
1579
1580 static struct triple **triple_rhs(struct compile_state *state,
1581         struct triple *ins, struct triple **last)
1582 {
1583         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1584                 ins, last);
1585 }
1586
1587 static struct triple **triple_misc(struct compile_state *state,
1588         struct triple *ins, struct triple **last)
1589 {
1590         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1591                 ins, last);
1592 }
1593
1594 static struct triple **triple_targ(struct compile_state *state,
1595         struct triple *ins, struct triple **last)
1596 {
1597         size_t count;
1598         struct triple **ret, **vector;
1599         ret = 0;
1600         count = TRIPLE_TARG(ins->sizes);
1601         vector = &TARG(ins, 0);
1602         if (count) {
1603                 if (!last) {
1604                         ret = vector;
1605                 }
1606                 else if ((last >= vector) && (last < (vector + count - 1))) {
1607                         ret = last + 1;
1608                 }
1609                 else if ((last == (vector + count - 1)) && 
1610                         TRIPLE_RHS(ins->sizes)) {
1611                         ret = &ins->next;
1612                 }
1613         }
1614         return ret;
1615 }
1616
1617
1618 static void verify_use(struct compile_state *state,
1619         struct triple *user, struct triple *used)
1620 {
1621         int size, i;
1622         size = TRIPLE_SIZE(user->sizes);
1623         for(i = 0; i < size; i++) {
1624                 if (user->param[i] == used) {
1625                         break;
1626                 }
1627         }
1628         if (triple_is_branch(state, user)) {
1629                 if (user->next == used) {
1630                         i = -1;
1631                 }
1632         }
1633         if (i == size) {
1634                 internal_error(state, user, "%s(%p) does not use %s(%p)",
1635                         tops(user->op), user, tops(used->op), used);
1636         }
1637 }
1638
1639 static int find_rhs_use(struct compile_state *state, 
1640         struct triple *user, struct triple *used)
1641 {
1642         struct triple **param;
1643         int size, i;
1644         verify_use(state, user, used);
1645         size = TRIPLE_RHS(user->sizes);
1646         param = &RHS(user, 0);
1647         for(i = 0; i < size; i++) {
1648                 if (param[i] == used) {
1649                         return i;
1650                 }
1651         }
1652         return -1;
1653 }
1654
1655 static void free_triple(struct compile_state *state, struct triple *ptr)
1656 {
1657         size_t size;
1658         size = sizeof(*ptr) - sizeof(ptr->param) +
1659                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1660         ptr->prev->next = ptr->next;
1661         ptr->next->prev = ptr->prev;
1662         if (ptr->use) {
1663                 internal_error(state, ptr, "ptr->use != 0");
1664         }
1665         memset(ptr, -1, size);
1666         xfree(ptr);
1667 }
1668
1669 static void release_triple(struct compile_state *state, struct triple *ptr)
1670 {
1671         struct triple_set *set, *next;
1672         struct triple **expr;
1673         /* Remove ptr from use chains where it is the user */
1674         expr = triple_rhs(state, ptr, 0);
1675         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1676                 if (*expr) {
1677                         unuse_triple(*expr, ptr);
1678                 }
1679         }
1680         expr = triple_lhs(state, ptr, 0);
1681         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1682                 if (*expr) {
1683                         unuse_triple(*expr, ptr);
1684                 }
1685         }
1686         expr = triple_misc(state, ptr, 0);
1687         for(; expr; expr = triple_misc(state, ptr, expr)) {
1688                 if (*expr) {
1689                         unuse_triple(*expr, ptr);
1690                 }
1691         }
1692         expr = triple_targ(state, ptr, 0);
1693         for(; expr; expr = triple_targ(state, ptr, expr)) {
1694                 if (*expr) {
1695                         unuse_triple(*expr, ptr);
1696                 }
1697         }
1698         /* Reomve ptr from use chains where it is used */
1699         for(set = ptr->use; set; set = next) {
1700                 next = set->next;
1701                 expr = triple_rhs(state, set->member, 0);
1702                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1703                         if (*expr == ptr) {
1704                                 *expr = &zero_triple;
1705                         }
1706                 }
1707                 expr = triple_lhs(state, set->member, 0);
1708                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1709                         if (*expr == ptr) {
1710                                 *expr = &zero_triple;
1711                         }
1712                 }
1713                 expr = triple_misc(state, set->member, 0);
1714                 for(; expr; expr = triple_misc(state, set->member, expr)) {
1715                         if (*expr == ptr) {
1716                                 *expr = &zero_triple;
1717                         }
1718                 }
1719                 expr = triple_targ(state, set->member, 0);
1720                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1721                         if (*expr == ptr) {
1722                                 *expr = &zero_triple;
1723                         }
1724                 }
1725                 unuse_triple(ptr, set->member);
1726         }
1727         free_triple(state, ptr);
1728 }
1729
1730 static void print_triple(struct compile_state *state, struct triple *ptr);
1731
1732 #define TOK_UNKNOWN     0
1733 #define TOK_SPACE       1
1734 #define TOK_SEMI        2
1735 #define TOK_LBRACE      3
1736 #define TOK_RBRACE      4
1737 #define TOK_COMMA       5
1738 #define TOK_EQ          6
1739 #define TOK_COLON       7
1740 #define TOK_LBRACKET    8
1741 #define TOK_RBRACKET    9
1742 #define TOK_LPAREN      10
1743 #define TOK_RPAREN      11
1744 #define TOK_STAR        12
1745 #define TOK_DOTS        13
1746 #define TOK_MORE        14
1747 #define TOK_LESS        15
1748 #define TOK_TIMESEQ     16
1749 #define TOK_DIVEQ       17
1750 #define TOK_MODEQ       18
1751 #define TOK_PLUSEQ      19
1752 #define TOK_MINUSEQ     20
1753 #define TOK_SLEQ        21
1754 #define TOK_SREQ        22
1755 #define TOK_ANDEQ       23
1756 #define TOK_XOREQ       24
1757 #define TOK_OREQ        25
1758 #define TOK_EQEQ        26
1759 #define TOK_NOTEQ       27
1760 #define TOK_QUEST       28
1761 #define TOK_LOGOR       29
1762 #define TOK_LOGAND      30
1763 #define TOK_OR          31
1764 #define TOK_AND         32
1765 #define TOK_XOR         33
1766 #define TOK_LESSEQ      34
1767 #define TOK_MOREEQ      35
1768 #define TOK_SL          36
1769 #define TOK_SR          37
1770 #define TOK_PLUS        38
1771 #define TOK_MINUS       39
1772 #define TOK_DIV         40
1773 #define TOK_MOD         41
1774 #define TOK_PLUSPLUS    42
1775 #define TOK_MINUSMINUS  43
1776 #define TOK_BANG        44
1777 #define TOK_ARROW       45
1778 #define TOK_DOT         46
1779 #define TOK_TILDE       47
1780 #define TOK_LIT_STRING  48
1781 #define TOK_LIT_CHAR    49
1782 #define TOK_LIT_INT     50
1783 #define TOK_LIT_FLOAT   51
1784 #define TOK_MACRO       52
1785 #define TOK_CONCATENATE 53
1786
1787 #define TOK_IDENT       54
1788 #define TOK_STRUCT_NAME 55
1789 #define TOK_ENUM_CONST  56
1790 #define TOK_TYPE_NAME   57
1791
1792 #define TOK_AUTO        58
1793 #define TOK_BREAK       59
1794 #define TOK_CASE        60
1795 #define TOK_CHAR        61
1796 #define TOK_CONST       62
1797 #define TOK_CONTINUE    63
1798 #define TOK_DEFAULT     64
1799 #define TOK_DO          65
1800 #define TOK_DOUBLE      66
1801 #define TOK_ELSE        67
1802 #define TOK_ENUM        68
1803 #define TOK_EXTERN      69
1804 #define TOK_FLOAT       70
1805 #define TOK_FOR         71
1806 #define TOK_GOTO        72
1807 #define TOK_IF          73
1808 #define TOK_INLINE      74
1809 #define TOK_INT         75
1810 #define TOK_LONG        76
1811 #define TOK_REGISTER    77
1812 #define TOK_RESTRICT    78
1813 #define TOK_RETURN      79
1814 #define TOK_SHORT       80
1815 #define TOK_SIGNED      81
1816 #define TOK_SIZEOF      82
1817 #define TOK_STATIC      83
1818 #define TOK_STRUCT      84
1819 #define TOK_SWITCH      85
1820 #define TOK_TYPEDEF     86
1821 #define TOK_UNION       87
1822 #define TOK_UNSIGNED    88
1823 #define TOK_VOID        89
1824 #define TOK_VOLATILE    90
1825 #define TOK_WHILE       91
1826 #define TOK_ASM         92
1827 #define TOK_ATTRIBUTE   93
1828 #define TOK_ALIGNOF     94
1829 #define TOK_FIRST_KEYWORD TOK_AUTO
1830 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1831
1832 #define TOK_DEFINE      100
1833 #define TOK_UNDEF       101
1834 #define TOK_INCLUDE     102
1835 #define TOK_LINE        103
1836 #define TOK_ERROR       104
1837 #define TOK_WARNING     105
1838 #define TOK_PRAGMA      106
1839 #define TOK_IFDEF       107
1840 #define TOK_IFNDEF      108
1841 #define TOK_ELIF        109
1842 #define TOK_ENDIF       110
1843
1844 #define TOK_FIRST_MACRO TOK_DEFINE
1845 #define TOK_LAST_MACRO  TOK_ENDIF
1846          
1847 #define TOK_EOF         111
1848
1849 static const char *tokens[] = {
1850 [TOK_UNKNOWN     ] = "unknown",
1851 [TOK_SPACE       ] = ":space:",
1852 [TOK_SEMI        ] = ";",
1853 [TOK_LBRACE      ] = "{",
1854 [TOK_RBRACE      ] = "}",
1855 [TOK_COMMA       ] = ",",
1856 [TOK_EQ          ] = "=",
1857 [TOK_COLON       ] = ":",
1858 [TOK_LBRACKET    ] = "[",
1859 [TOK_RBRACKET    ] = "]",
1860 [TOK_LPAREN      ] = "(",
1861 [TOK_RPAREN      ] = ")",
1862 [TOK_STAR        ] = "*",
1863 [TOK_DOTS        ] = "...",
1864 [TOK_MORE        ] = ">",
1865 [TOK_LESS        ] = "<",
1866 [TOK_TIMESEQ     ] = "*=",
1867 [TOK_DIVEQ       ] = "/=",
1868 [TOK_MODEQ       ] = "%=",
1869 [TOK_PLUSEQ      ] = "+=",
1870 [TOK_MINUSEQ     ] = "-=",
1871 [TOK_SLEQ        ] = "<<=",
1872 [TOK_SREQ        ] = ">>=",
1873 [TOK_ANDEQ       ] = "&=",
1874 [TOK_XOREQ       ] = "^=",
1875 [TOK_OREQ        ] = "|=",
1876 [TOK_EQEQ        ] = "==",
1877 [TOK_NOTEQ       ] = "!=",
1878 [TOK_QUEST       ] = "?",
1879 [TOK_LOGOR       ] = "||",
1880 [TOK_LOGAND      ] = "&&",
1881 [TOK_OR          ] = "|",
1882 [TOK_AND         ] = "&",
1883 [TOK_XOR         ] = "^",
1884 [TOK_LESSEQ      ] = "<=",
1885 [TOK_MOREEQ      ] = ">=",
1886 [TOK_SL          ] = "<<",
1887 [TOK_SR          ] = ">>",
1888 [TOK_PLUS        ] = "+",
1889 [TOK_MINUS       ] = "-",
1890 [TOK_DIV         ] = "/",
1891 [TOK_MOD         ] = "%",
1892 [TOK_PLUSPLUS    ] = "++",
1893 [TOK_MINUSMINUS  ] = "--",
1894 [TOK_BANG        ] = "!",
1895 [TOK_ARROW       ] = "->",
1896 [TOK_DOT         ] = ".",
1897 [TOK_TILDE       ] = "~",
1898 [TOK_LIT_STRING  ] = ":string:",
1899 [TOK_IDENT       ] = ":ident:",
1900 [TOK_TYPE_NAME   ] = ":typename:",
1901 [TOK_LIT_CHAR    ] = ":char:",
1902 [TOK_LIT_INT     ] = ":integer:",
1903 [TOK_LIT_FLOAT   ] = ":float:",
1904 [TOK_MACRO       ] = "#",
1905 [TOK_CONCATENATE ] = "##",
1906
1907 [TOK_AUTO        ] = "auto",
1908 [TOK_BREAK       ] = "break",
1909 [TOK_CASE        ] = "case",
1910 [TOK_CHAR        ] = "char",
1911 [TOK_CONST       ] = "const",
1912 [TOK_CONTINUE    ] = "continue",
1913 [TOK_DEFAULT     ] = "default",
1914 [TOK_DO          ] = "do",
1915 [TOK_DOUBLE      ] = "double",
1916 [TOK_ELSE        ] = "else",
1917 [TOK_ENUM        ] = "enum",
1918 [TOK_EXTERN      ] = "extern",
1919 [TOK_FLOAT       ] = "float",
1920 [TOK_FOR         ] = "for",
1921 [TOK_GOTO        ] = "goto",
1922 [TOK_IF          ] = "if",
1923 [TOK_INLINE      ] = "inline",
1924 [TOK_INT         ] = "int",
1925 [TOK_LONG        ] = "long",
1926 [TOK_REGISTER    ] = "register",
1927 [TOK_RESTRICT    ] = "restrict",
1928 [TOK_RETURN      ] = "return",
1929 [TOK_SHORT       ] = "short",
1930 [TOK_SIGNED      ] = "signed",
1931 [TOK_SIZEOF      ] = "sizeof",
1932 [TOK_STATIC      ] = "static",
1933 [TOK_STRUCT      ] = "struct",
1934 [TOK_SWITCH      ] = "switch",
1935 [TOK_TYPEDEF     ] = "typedef",
1936 [TOK_UNION       ] = "union",
1937 [TOK_UNSIGNED    ] = "unsigned",
1938 [TOK_VOID        ] = "void",
1939 [TOK_VOLATILE    ] = "volatile",
1940 [TOK_WHILE       ] = "while",
1941 [TOK_ASM         ] = "asm",
1942 [TOK_ATTRIBUTE   ] = "__attribute__",
1943 [TOK_ALIGNOF     ] = "__alignof__",
1944
1945 [TOK_DEFINE      ] = "define",
1946 [TOK_UNDEF       ] = "undef",
1947 [TOK_INCLUDE     ] = "include",
1948 [TOK_LINE        ] = "line",
1949 [TOK_ERROR       ] = "error",
1950 [TOK_WARNING     ] = "warning",
1951 [TOK_PRAGMA      ] = "pragma",
1952 [TOK_IFDEF       ] = "ifdef",
1953 [TOK_IFNDEF      ] = "ifndef",
1954 [TOK_ELIF        ] = "elif",
1955 [TOK_ENDIF       ] = "endif",
1956
1957 [TOK_EOF         ] = "EOF",
1958 };
1959
1960 static unsigned int hash(const char *str, int str_len)
1961 {
1962         unsigned int hash;
1963         const char *end;
1964         end = str + str_len;
1965         hash = 0;
1966         for(; str < end; str++) {
1967                 hash = (hash *263) + *str;
1968         }
1969         hash = hash & (HASH_TABLE_SIZE -1);
1970         return hash;
1971 }
1972
1973 static struct hash_entry *lookup(
1974         struct compile_state *state, const char *name, int name_len)
1975 {
1976         struct hash_entry *entry;
1977         unsigned int index;
1978         index = hash(name, name_len);
1979         entry = state->hash_table[index];
1980         while(entry && 
1981                 ((entry->name_len != name_len) ||
1982                         (memcmp(entry->name, name, name_len) != 0))) {
1983                 entry = entry->next;
1984         }
1985         if (!entry) {
1986                 char *new_name;
1987                 /* Get a private copy of the name */
1988                 new_name = xmalloc(name_len + 1, "hash_name");
1989                 memcpy(new_name, name, name_len);
1990                 new_name[name_len] = '\0';
1991
1992                 /* Create a new hash entry */
1993                 entry = xcmalloc(sizeof(*entry), "hash_entry");
1994                 entry->next = state->hash_table[index];
1995                 entry->name = new_name;
1996                 entry->name_len = name_len;
1997
1998                 /* Place the new entry in the hash table */
1999                 state->hash_table[index] = entry;
2000         }
2001         return entry;
2002 }
2003
2004 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2005 {
2006         struct hash_entry *entry;
2007         entry = tk->ident;
2008         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2009                 (entry->tok == TOK_ENUM_CONST) ||
2010                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
2011                         (entry->tok <= TOK_LAST_KEYWORD)))) {
2012                 tk->tok = entry->tok;
2013         }
2014 }
2015
2016 static void ident_to_macro(struct compile_state *state, struct token *tk)
2017 {
2018         struct hash_entry *entry;
2019         entry = tk->ident;
2020         if (entry && 
2021                 (entry->tok >= TOK_FIRST_MACRO) &&
2022                 (entry->tok <= TOK_LAST_MACRO)) {
2023                 tk->tok = entry->tok;
2024         }
2025 }
2026
2027 static void hash_keyword(
2028         struct compile_state *state, const char *keyword, int tok)
2029 {
2030         struct hash_entry *entry;
2031         entry = lookup(state, keyword, strlen(keyword));
2032         if (entry && entry->tok != TOK_UNKNOWN) {
2033                 die("keyword %s already hashed", keyword);
2034         }
2035         entry->tok  = tok;
2036 }
2037
2038 static void symbol(
2039         struct compile_state *state, struct hash_entry *ident,
2040         struct symbol **chain, struct triple *def, struct type *type)
2041 {
2042         struct symbol *sym;
2043         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2044                 error(state, 0, "%s already defined", ident->name);
2045         }
2046         sym = xcmalloc(sizeof(*sym), "symbol");
2047         sym->ident = ident;
2048         sym->def   = def;
2049         sym->type  = type;
2050         sym->scope_depth = state->scope_depth;
2051         sym->next = *chain;
2052         *chain    = sym;
2053 }
2054
2055 static void start_scope(struct compile_state *state)
2056 {
2057         state->scope_depth++;
2058 }
2059
2060 static void end_scope_syms(struct symbol **chain, int depth)
2061 {
2062         struct symbol *sym, *next;
2063         sym = *chain;
2064         while(sym && (sym->scope_depth == depth)) {
2065                 next = sym->next;
2066                 xfree(sym);
2067                 sym = next;
2068         }
2069         *chain = sym;
2070 }
2071
2072 static void end_scope(struct compile_state *state)
2073 {
2074         int i;
2075         int depth;
2076         /* Walk through the hash table and remove all symbols
2077          * in the current scope. 
2078          */
2079         depth = state->scope_depth;
2080         for(i = 0; i < HASH_TABLE_SIZE; i++) {
2081                 struct hash_entry *entry;
2082                 entry = state->hash_table[i];
2083                 while(entry) {
2084                         end_scope_syms(&entry->sym_label,  depth);
2085                         end_scope_syms(&entry->sym_struct, depth);
2086                         end_scope_syms(&entry->sym_ident,  depth);
2087                         entry = entry->next;
2088                 }
2089         }
2090         state->scope_depth = depth - 1;
2091 }
2092
2093 static void register_keywords(struct compile_state *state)
2094 {
2095         hash_keyword(state, "auto",          TOK_AUTO);
2096         hash_keyword(state, "break",         TOK_BREAK);
2097         hash_keyword(state, "case",          TOK_CASE);
2098         hash_keyword(state, "char",          TOK_CHAR);
2099         hash_keyword(state, "const",         TOK_CONST);
2100         hash_keyword(state, "continue",      TOK_CONTINUE);
2101         hash_keyword(state, "default",       TOK_DEFAULT);
2102         hash_keyword(state, "do",            TOK_DO);
2103         hash_keyword(state, "double",        TOK_DOUBLE);
2104         hash_keyword(state, "else",          TOK_ELSE);
2105         hash_keyword(state, "enum",          TOK_ENUM);
2106         hash_keyword(state, "extern",        TOK_EXTERN);
2107         hash_keyword(state, "float",         TOK_FLOAT);
2108         hash_keyword(state, "for",           TOK_FOR);
2109         hash_keyword(state, "goto",          TOK_GOTO);
2110         hash_keyword(state, "if",            TOK_IF);
2111         hash_keyword(state, "inline",        TOK_INLINE);
2112         hash_keyword(state, "int",           TOK_INT);
2113         hash_keyword(state, "long",          TOK_LONG);
2114         hash_keyword(state, "register",      TOK_REGISTER);
2115         hash_keyword(state, "restrict",      TOK_RESTRICT);
2116         hash_keyword(state, "return",        TOK_RETURN);
2117         hash_keyword(state, "short",         TOK_SHORT);
2118         hash_keyword(state, "signed",        TOK_SIGNED);
2119         hash_keyword(state, "sizeof",        TOK_SIZEOF);
2120         hash_keyword(state, "static",        TOK_STATIC);
2121         hash_keyword(state, "struct",        TOK_STRUCT);
2122         hash_keyword(state, "switch",        TOK_SWITCH);
2123         hash_keyword(state, "typedef",       TOK_TYPEDEF);
2124         hash_keyword(state, "union",         TOK_UNION);
2125         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
2126         hash_keyword(state, "void",          TOK_VOID);
2127         hash_keyword(state, "volatile",      TOK_VOLATILE);
2128         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
2129         hash_keyword(state, "while",         TOK_WHILE);
2130         hash_keyword(state, "asm",           TOK_ASM);
2131         hash_keyword(state, "__asm__",       TOK_ASM);
2132         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2133         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
2134 }
2135
2136 static void register_macro_keywords(struct compile_state *state)
2137 {
2138         hash_keyword(state, "define",        TOK_DEFINE);
2139         hash_keyword(state, "undef",         TOK_UNDEF);
2140         hash_keyword(state, "include",       TOK_INCLUDE);
2141         hash_keyword(state, "line",          TOK_LINE);
2142         hash_keyword(state, "error",         TOK_ERROR);
2143         hash_keyword(state, "warning",       TOK_WARNING);
2144         hash_keyword(state, "pragma",        TOK_PRAGMA);
2145         hash_keyword(state, "ifdef",         TOK_IFDEF);
2146         hash_keyword(state, "ifndef",        TOK_IFNDEF);
2147         hash_keyword(state, "elif",          TOK_ELIF);
2148         hash_keyword(state, "endif",         TOK_ENDIF);
2149 }
2150
2151 static int spacep(int c)
2152 {
2153         int ret = 0;
2154         switch(c) {
2155         case ' ':
2156         case '\t':
2157         case '\f':
2158         case '\v':
2159         case '\r':
2160         case '\n':
2161                 ret = 1;
2162                 break;
2163         }
2164         return ret;
2165 }
2166
2167 static int digitp(int c)
2168 {
2169         int ret = 0;
2170         switch(c) {
2171         case '0': case '1': case '2': case '3': case '4': 
2172         case '5': case '6': case '7': case '8': case '9':
2173                 ret = 1;
2174                 break;
2175         }
2176         return ret;
2177 }
2178 static int digval(int c)
2179 {
2180         int val = -1;
2181         if ((c >= '0') && (c <= '9')) {
2182                 val = c - '0';
2183         }
2184         return val;
2185 }
2186
2187 static int hexdigitp(int c)
2188 {
2189         int ret = 0;
2190         switch(c) {
2191         case '0': case '1': case '2': case '3': case '4': 
2192         case '5': case '6': case '7': case '8': case '9':
2193         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2194         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2195                 ret = 1;
2196                 break;
2197         }
2198         return ret;
2199 }
2200 static int hexdigval(int c) 
2201 {
2202         int val = -1;
2203         if ((c >= '0') && (c <= '9')) {
2204                 val = c - '0';
2205         }
2206         else if ((c >= 'A') && (c <= 'F')) {
2207                 val = 10 + (c - 'A');
2208         }
2209         else if ((c >= 'a') && (c <= 'f')) {
2210                 val = 10 + (c - 'a');
2211         }
2212         return val;
2213 }
2214
2215 static int octdigitp(int c)
2216 {
2217         int ret = 0;
2218         switch(c) {
2219         case '0': case '1': case '2': case '3': 
2220         case '4': case '5': case '6': case '7':
2221                 ret = 1;
2222                 break;
2223         }
2224         return ret;
2225 }
2226 static int octdigval(int c)
2227 {
2228         int val = -1;
2229         if ((c >= '0') && (c <= '7')) {
2230                 val = c - '0';
2231         }
2232         return val;
2233 }
2234
2235 static int letterp(int c)
2236 {
2237         int ret = 0;
2238         switch(c) {
2239         case 'a': case 'b': case 'c': case 'd': case 'e':
2240         case 'f': case 'g': case 'h': case 'i': case 'j':
2241         case 'k': case 'l': case 'm': case 'n': case 'o':
2242         case 'p': case 'q': case 'r': case 's': case 't':
2243         case 'u': case 'v': case 'w': case 'x': case 'y':
2244         case 'z':
2245         case 'A': case 'B': case 'C': case 'D': case 'E':
2246         case 'F': case 'G': case 'H': case 'I': case 'J':
2247         case 'K': case 'L': case 'M': case 'N': case 'O':
2248         case 'P': case 'Q': case 'R': case 'S': case 'T':
2249         case 'U': case 'V': case 'W': case 'X': case 'Y':
2250         case 'Z':
2251         case '_':
2252                 ret = 1;
2253                 break;
2254         }
2255         return ret;
2256 }
2257
2258 static int char_value(struct compile_state *state,
2259         const signed char **strp, const signed char *end)
2260 {
2261         const signed char *str;
2262         int c;
2263         str = *strp;
2264         c = *str++;
2265         if ((c == '\\') && (str < end)) {
2266                 switch(*str) {
2267                 case 'n':  c = '\n'; str++; break;
2268                 case 't':  c = '\t'; str++; break;
2269                 case 'v':  c = '\v'; str++; break;
2270                 case 'b':  c = '\b'; str++; break;
2271                 case 'r':  c = '\r'; str++; break;
2272                 case 'f':  c = '\f'; str++; break;
2273                 case 'a':  c = '\a'; str++; break;
2274                 case '\\': c = '\\'; str++; break;
2275                 case '?':  c = '?';  str++; break;
2276                 case '\'': c = '\''; str++; break;
2277                 case '"':  c = '"';  break;
2278                 case 'x': 
2279                         c = 0;
2280                         str++;
2281                         while((str < end) && hexdigitp(*str)) {
2282                                 c <<= 4;
2283                                 c += hexdigval(*str);
2284                                 str++;
2285                         }
2286                         break;
2287                 case '0': case '1': case '2': case '3': 
2288                 case '4': case '5': case '6': case '7':
2289                         c = 0;
2290                         while((str < end) && octdigitp(*str)) {
2291                                 c <<= 3;
2292                                 c += octdigval(*str);
2293                                 str++;
2294                         }
2295                         break;
2296                 default:
2297                         error(state, 0, "Invalid character constant");
2298                         break;
2299                 }
2300         }
2301         *strp = str;
2302         return c;
2303 }
2304
2305 static char *after_digits(char *ptr, char *end)
2306 {
2307         while((ptr < end) && digitp(*ptr)) {
2308                 ptr++;
2309         }
2310         return ptr;
2311 }
2312
2313 static char *after_octdigits(char *ptr, char *end)
2314 {
2315         while((ptr < end) && octdigitp(*ptr)) {
2316                 ptr++;
2317         }
2318         return ptr;
2319 }
2320
2321 static char *after_hexdigits(char *ptr, char *end)
2322 {
2323         while((ptr < end) && hexdigitp(*ptr)) {
2324                 ptr++;
2325         }
2326         return ptr;
2327 }
2328
2329 static void save_string(struct compile_state *state, 
2330         struct token *tk, char *start, char *end, const char *id)
2331 {
2332         char *str;
2333         int str_len;
2334         /* Create a private copy of the string */
2335         str_len = end - start + 1;
2336         str = xmalloc(str_len + 1, id);
2337         memcpy(str, start, str_len);
2338         str[str_len] = '\0';
2339
2340         /* Store the copy in the token */
2341         tk->val.str = str;
2342         tk->str_len = str_len;
2343 }
2344 static void next_token(struct compile_state *state, int index)
2345 {
2346         struct file_state *file;
2347         struct token *tk;
2348         char *token;
2349         int c, c1, c2, c3;
2350         char *tokp, *end;
2351         int tok;
2352 next_token:
2353         file = state->file;
2354         tk = &state->token[index];
2355         tk->str_len = 0;
2356         tk->ident = 0;
2357         token = tokp = file->pos;
2358         end = file->buf + file->size;
2359         tok = TOK_UNKNOWN;
2360         c = -1;
2361         if (tokp < end) {
2362                 c = *tokp;
2363         }
2364         c1 = -1;
2365         if ((tokp + 1) < end) {
2366                 c1 = tokp[1];
2367         }
2368         c2 = -1;
2369         if ((tokp + 2) < end) {
2370                 c2 = tokp[2];
2371         }
2372         c3 = -1;
2373         if ((tokp + 3) < end) {
2374                 c3 = tokp[3];
2375         }
2376         if (tokp >= end) {
2377                 tok = TOK_EOF;
2378                 tokp = end;
2379         }
2380         /* Whitespace */
2381         else if (spacep(c)) {
2382                 tok = TOK_SPACE;
2383                 while ((tokp < end) && spacep(c)) {
2384                         if (c == '\n') {
2385                                 file->line++;
2386                                 file->line_start = tokp + 1;
2387                         }
2388                         c = *(++tokp);
2389                 }
2390                 if (!spacep(c)) {
2391                         tokp--;
2392                 }
2393         }
2394         /* EOL Comments */
2395         else if ((c == '/') && (c1 == '/')) {
2396                 tok = TOK_SPACE;
2397                 for(tokp += 2; tokp < end; tokp++) {
2398                         c = *tokp;
2399                         if (c == '\n') {
2400                                 file->line++;
2401                                 file->line_start = tokp +1;
2402                                 break;
2403                         }
2404                 }
2405         }
2406         /* Comments */
2407         else if ((c == '/') && (c1 == '*')) {
2408                 int line;
2409                 char *line_start;
2410                 line = file->line;
2411                 line_start = file->line_start;
2412                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2413                         c = *tokp;
2414                         if (c == '\n') {
2415                                 line++;
2416                                 line_start = tokp +1;
2417                         }
2418                         else if ((c == '*') && (tokp[1] == '/')) {
2419                                 tok = TOK_SPACE;
2420                                 tokp += 1;
2421                                 break;
2422                         }
2423                 }
2424                 if (tok == TOK_UNKNOWN) {
2425                         error(state, 0, "unterminated comment");
2426                 }
2427                 file->line = line;
2428                 file->line_start = line_start;
2429         }
2430         /* string constants */
2431         else if ((c == '"') ||
2432                 ((c == 'L') && (c1 == '"'))) {
2433                 int line;
2434                 char *line_start;
2435                 int wchar;
2436                 line = file->line;
2437                 line_start = file->line_start;
2438                 wchar = 0;
2439                 if (c == 'L') {
2440                         wchar = 1;
2441                         tokp++;
2442                 }
2443                 for(tokp += 1; tokp < end; tokp++) {
2444                         c = *tokp;
2445                         if (c == '\n') {
2446                                 line++;
2447                                 line_start = tokp + 1;
2448                         }
2449                         else if ((c == '\\') && (tokp +1 < end)) {
2450                                 tokp++;
2451                         }
2452                         else if (c == '"') {
2453                                 tok = TOK_LIT_STRING;
2454                                 break;
2455                         }
2456                 }
2457                 if (tok == TOK_UNKNOWN) {
2458                         error(state, 0, "unterminated string constant");
2459                 }
2460                 if (line != file->line) {
2461                         warning(state, 0, "multiline string constant");
2462                 }
2463                 file->line = line;
2464                 file->line_start = line_start;
2465
2466                 /* Save the string value */
2467                 save_string(state, tk, token, tokp, "literal string");
2468         }
2469         /* character constants */
2470         else if ((c == '\'') ||
2471                 ((c == 'L') && (c1 == '\''))) {
2472                 int line;
2473                 char *line_start;
2474                 int wchar;
2475                 line = file->line;
2476                 line_start = file->line_start;
2477                 wchar = 0;
2478                 if (c == 'L') {
2479                         wchar = 1;
2480                         tokp++;
2481                 }
2482                 for(tokp += 1; tokp < end; tokp++) {
2483                         c = *tokp;
2484                         if (c == '\n') {
2485                                 line++;
2486                                 line_start = tokp + 1;
2487                         }
2488                         else if ((c == '\\') && (tokp +1 < end)) {
2489                                 tokp++;
2490                         }
2491                         else if (c == '\'') {
2492                                 tok = TOK_LIT_CHAR;
2493                                 break;
2494                         }
2495                 }
2496                 if (tok == TOK_UNKNOWN) {
2497                         error(state, 0, "unterminated character constant");
2498                 }
2499                 if (line != file->line) {
2500                         warning(state, 0, "multiline character constant");
2501                 }
2502                 file->line = line;
2503                 file->line_start = line_start;
2504
2505                 /* Save the character value */
2506                 save_string(state, tk, token, tokp, "literal character");
2507         }
2508         /* integer and floating constants 
2509          * Integer Constants
2510          * {digits}
2511          * 0[Xx]{hexdigits}
2512          * 0{octdigit}+
2513          * 
2514          * Floating constants
2515          * {digits}.{digits}[Ee][+-]?{digits}
2516          * {digits}.{digits}
2517          * {digits}[Ee][+-]?{digits}
2518          * .{digits}[Ee][+-]?{digits}
2519          * .{digits}
2520          */
2521         
2522         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2523                 char *next, *new;
2524                 int is_float;
2525                 is_float = 0;
2526                 if (c != '.') {
2527                         next = after_digits(tokp, end);
2528                 }
2529                 else {
2530                         next = tokp;
2531                 }
2532                 if (next[0] == '.') {
2533                         new = after_digits(next, end);
2534                         is_float = (new != next);
2535                         next = new;
2536                 }
2537                 if ((next[0] == 'e') || (next[0] == 'E')) {
2538                         if (((next + 1) < end) && 
2539                                 ((next[1] == '+') || (next[1] == '-'))) {
2540                                 next++;
2541                         }
2542                         new = after_digits(next, end);
2543                         is_float = (new != next);
2544                         next = new;
2545                 }
2546                 if (is_float) {
2547                         tok = TOK_LIT_FLOAT;
2548                         if ((next < end) && (
2549                                 (next[0] == 'f') ||
2550                                 (next[0] == 'F') ||
2551                                 (next[0] == 'l') ||
2552                                 (next[0] == 'L'))
2553                                 ) {
2554                                 next++;
2555                         }
2556                 }
2557                 if (!is_float && digitp(c)) {
2558                         tok = TOK_LIT_INT;
2559                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2560                                 next = after_hexdigits(tokp + 2, end);
2561                         }
2562                         else if (c == '0') {
2563                                 next = after_octdigits(tokp, end);
2564                         }
2565                         else {
2566                                 next = after_digits(tokp, end);
2567                         }
2568                         /* crazy integer suffixes */
2569                         if ((next < end) && 
2570                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2571                                 next++;
2572                                 if ((next < end) &&
2573                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2574                                         next++;
2575                                 }
2576                         }
2577                         else if ((next < end) &&
2578                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2579                                 next++;
2580                                 if ((next < end) && 
2581                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2582                                         next++;
2583                                 }
2584                         }
2585                 }
2586                 tokp = next - 1;
2587
2588                 /* Save the integer/floating point value */
2589                 save_string(state, tk, token, tokp, "literal number");
2590         }
2591         /* identifiers */
2592         else if (letterp(c)) {
2593                 tok = TOK_IDENT;
2594                 for(tokp += 1; tokp < end; tokp++) {
2595                         c = *tokp;
2596                         if (!letterp(c) && !digitp(c)) {
2597                                 break;
2598                         }
2599                 }
2600                 tokp -= 1;
2601                 tk->ident = lookup(state, token, tokp +1 - token);
2602         }
2603         /* C99 alternate macro characters */
2604         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2605                 tokp += 3; 
2606                 tok = TOK_CONCATENATE; 
2607         }
2608         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2609         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2610         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2611         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2612         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2613         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2614         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2615         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2616         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2617         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2618         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2619         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2620         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2621         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2622         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2623         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2624         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2625         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2626         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2627         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2628         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2629         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2630         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2631         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2632         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2633         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2634         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2635         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2636         else if (c == ';') { tok = TOK_SEMI; }
2637         else if (c == '{') { tok = TOK_LBRACE; }
2638         else if (c == '}') { tok = TOK_RBRACE; }
2639         else if (c == ',') { tok = TOK_COMMA; }
2640         else if (c == '=') { tok = TOK_EQ; }
2641         else if (c == ':') { tok = TOK_COLON; }
2642         else if (c == '[') { tok = TOK_LBRACKET; }
2643         else if (c == ']') { tok = TOK_RBRACKET; }
2644         else if (c == '(') { tok = TOK_LPAREN; }
2645         else if (c == ')') { tok = TOK_RPAREN; }
2646         else if (c == '*') { tok = TOK_STAR; }
2647         else if (c == '>') { tok = TOK_MORE; }
2648         else if (c == '<') { tok = TOK_LESS; }
2649         else if (c == '?') { tok = TOK_QUEST; }
2650         else if (c == '|') { tok = TOK_OR; }
2651         else if (c == '&') { tok = TOK_AND; }
2652         else if (c == '^') { tok = TOK_XOR; }
2653         else if (c == '+') { tok = TOK_PLUS; }
2654         else if (c == '-') { tok = TOK_MINUS; }
2655         else if (c == '/') { tok = TOK_DIV; }
2656         else if (c == '%') { tok = TOK_MOD; }
2657         else if (c == '!') { tok = TOK_BANG; }
2658         else if (c == '.') { tok = TOK_DOT; }
2659         else if (c == '~') { tok = TOK_TILDE; }
2660         else if (c == '#') { tok = TOK_MACRO; }
2661         if (tok == TOK_MACRO) {
2662                 /* Only match preprocessor directives at the start of a line */
2663                 char *ptr;
2664                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2665                         ;
2666                 if (ptr != tokp) {
2667                         tok = TOK_UNKNOWN;
2668                 }
2669         }
2670         if (tok == TOK_UNKNOWN) {
2671                 error(state, 0, "unknown token");
2672         }
2673
2674         file->pos = tokp + 1;
2675         tk->tok = tok;
2676         if (tok == TOK_IDENT) {
2677                 ident_to_keyword(state, tk);
2678         }
2679         /* Don't return space tokens. */
2680         if (tok == TOK_SPACE) {
2681                 goto next_token;
2682         }
2683 }
2684
2685 static void compile_macro(struct compile_state *state, struct token *tk)
2686 {
2687         struct file_state *file;
2688         struct hash_entry *ident;
2689         ident = tk->ident;
2690         file = xmalloc(sizeof(*file), "file_state");
2691         file->basename = xstrdup(tk->ident->name);
2692         file->dirname = xstrdup("");
2693         file->size = ident->sym_define->buf_len;
2694         file->buf = xmalloc(file->size +2,  file->basename);
2695         memcpy(file->buf, ident->sym_define->buf, file->size);
2696         file->buf[file->size] = '\n';
2697         file->buf[file->size + 1] = '\0';
2698         file->pos = file->buf;
2699         file->line_start = file->pos;
2700         file->line = 1;
2701         file->prev = state->file;
2702         state->file = file;
2703 }
2704
2705
2706 static int mpeek(struct compile_state *state, int index)
2707 {
2708         struct token *tk;
2709         int rescan;
2710         tk = &state->token[index + 1];
2711         if (tk->tok == -1) {
2712                 next_token(state, index + 1);
2713         }
2714         do {
2715                 rescan = 0;
2716                 if ((tk->tok == TOK_EOF) && 
2717                         (state->file != state->macro_file) &&
2718                         (state->file->prev)) {
2719                         struct file_state *file = state->file;
2720                         state->file = file->prev;
2721                         /* file->basename is used keep it */
2722                         xfree(file->dirname);
2723                         xfree(file->buf);
2724                         xfree(file);
2725                         next_token(state, index + 1);
2726                         rescan = 1;
2727                 }
2728                 else if (tk->ident && tk->ident->sym_define) {
2729                         compile_macro(state, tk);
2730                         next_token(state, index + 1);
2731                         rescan = 1;
2732                 }
2733         } while(rescan);
2734         /* Don't show the token on the next line */
2735         if (state->macro_line < state->macro_file->line) {
2736                 return TOK_EOF;
2737         }
2738         return state->token[index +1].tok;
2739 }
2740
2741 static void meat(struct compile_state *state, int index, int tok)
2742 {
2743         int next_tok;
2744         int i;
2745         next_tok = mpeek(state, index);
2746         if (next_tok != tok) {
2747                 const char *name1, *name2;
2748                 name1 = tokens[next_tok];
2749                 name2 = "";
2750                 if (next_tok == TOK_IDENT) {
2751                         name2 = state->token[index + 1].ident->name;
2752                 }
2753                 error(state, 0, "found %s %s expected %s", 
2754                         name1, name2, tokens[tok]);
2755         }
2756         /* Free the old token value */
2757         if (state->token[index].str_len) {
2758                 memset((void *)(state->token[index].val.str), -1, 
2759                         state->token[index].str_len);
2760                 xfree(state->token[index].val.str);
2761         }
2762         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2763                 state->token[i] = state->token[i + 1];
2764         }
2765         memset(&state->token[i], 0, sizeof(state->token[i]));
2766         state->token[i].tok = -1;
2767 }
2768
2769 static long_t mcexpr(struct compile_state *state, int index);
2770
2771 static long_t mprimary_expr(struct compile_state *state, int index)
2772 {
2773         long_t val;
2774         int tok;
2775         tok = mpeek(state, index);
2776         while(state->token[index + 1].ident && 
2777                 state->token[index + 1].ident->sym_define) {
2778                 meat(state, index, tok);
2779                 compile_macro(state, &state->token[index]);
2780                 tok = mpeek(state, index);
2781         }
2782         switch(tok) {
2783         case TOK_LPAREN:
2784                 meat(state, index, TOK_LPAREN);
2785                 val = mcexpr(state, index);
2786                 meat(state, index, TOK_RPAREN);
2787                 break;
2788         case TOK_LIT_INT:
2789         {
2790                 char *end;
2791                 meat(state, index, TOK_LIT_INT);
2792                 errno = 0;
2793                 val = strtol(state->token[index].val.str, &end, 0);
2794                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2795                         (errno == ERANGE)) {
2796                         error(state, 0, "Integer constant to large");
2797                 }
2798                 break;
2799         }
2800         default:
2801                 meat(state, index, TOK_LIT_INT);
2802                 val = 0;
2803         }
2804         return val;
2805 }
2806 static long_t munary_expr(struct compile_state *state, int index)
2807 {
2808         long_t val;
2809         switch(mpeek(state, index)) {
2810         case TOK_PLUS:
2811                 meat(state, index, TOK_PLUS);
2812                 val = munary_expr(state, index);
2813                 val = + val;
2814                 break;
2815         case TOK_MINUS:
2816                 meat(state, index, TOK_MINUS);
2817                 val = munary_expr(state, index);
2818                 val = - val;
2819                 break;
2820         case TOK_TILDE:
2821                 meat(state, index, TOK_BANG);
2822                 val = munary_expr(state, index);
2823                 val = ~ val;
2824                 break;
2825         case TOK_BANG:
2826                 meat(state, index, TOK_BANG);
2827                 val = munary_expr(state, index);
2828                 val = ! val;
2829                 break;
2830         default:
2831                 val = mprimary_expr(state, index);
2832                 break;
2833         }
2834         return val;
2835         
2836 }
2837 static long_t mmul_expr(struct compile_state *state, int index)
2838 {
2839         long_t val;
2840         int done;
2841         val = munary_expr(state, index);
2842         do {
2843                 long_t right;
2844                 done = 0;
2845                 switch(mpeek(state, index)) {
2846                 case TOK_STAR:
2847                         meat(state, index, TOK_STAR);
2848                         right = munary_expr(state, index);
2849                         val = val * right;
2850                         break;
2851                 case TOK_DIV:
2852                         meat(state, index, TOK_DIV);
2853                         right = munary_expr(state, index);
2854                         val = val / right;
2855                         break;
2856                 case TOK_MOD:
2857                         meat(state, index, TOK_MOD);
2858                         right = munary_expr(state, index);
2859                         val = val % right;
2860                         break;
2861                 default:
2862                         done = 1;
2863                         break;
2864                 }
2865         } while(!done);
2866
2867         return val;
2868 }
2869
2870 static long_t madd_expr(struct compile_state *state, int index)
2871 {
2872         long_t val;
2873         int done;
2874         val = mmul_expr(state, index);
2875         do {
2876                 long_t right;
2877                 done = 0;
2878                 switch(mpeek(state, index)) {
2879                 case TOK_PLUS:
2880                         meat(state, index, TOK_PLUS);
2881                         right = mmul_expr(state, index);
2882                         val = val + right;
2883                         break;
2884                 case TOK_MINUS:
2885                         meat(state, index, TOK_MINUS);
2886                         right = mmul_expr(state, index);
2887                         val = val - right;
2888                         break;
2889                 default:
2890                         done = 1;
2891                         break;
2892                 }
2893         } while(!done);
2894
2895         return val;
2896 }
2897
2898 static long_t mshift_expr(struct compile_state *state, int index)
2899 {
2900         long_t val;
2901         int done;
2902         val = madd_expr(state, index);
2903         do {
2904                 long_t right;
2905                 done = 0;
2906                 switch(mpeek(state, index)) {
2907                 case TOK_SL:
2908                         meat(state, index, TOK_SL);
2909                         right = madd_expr(state, index);
2910                         val = val << right;
2911                         break;
2912                 case TOK_SR:
2913                         meat(state, index, TOK_SR);
2914                         right = madd_expr(state, index);
2915                         val = val >> right;
2916                         break;
2917                 default:
2918                         done = 1;
2919                         break;
2920                 }
2921         } while(!done);
2922
2923         return val;
2924 }
2925
2926 static long_t mrel_expr(struct compile_state *state, int index)
2927 {
2928         long_t val;
2929         int done;
2930         val = mshift_expr(state, index);
2931         do {
2932                 long_t right;
2933                 done = 0;
2934                 switch(mpeek(state, index)) {
2935                 case TOK_LESS:
2936                         meat(state, index, TOK_LESS);
2937                         right = mshift_expr(state, index);
2938                         val = val < right;
2939                         break;
2940                 case TOK_MORE:
2941                         meat(state, index, TOK_MORE);
2942                         right = mshift_expr(state, index);
2943                         val = val > right;
2944                         break;
2945                 case TOK_LESSEQ:
2946                         meat(state, index, TOK_LESSEQ);
2947                         right = mshift_expr(state, index);
2948                         val = val <= right;
2949                         break;
2950                 case TOK_MOREEQ:
2951                         meat(state, index, TOK_MOREEQ);
2952                         right = mshift_expr(state, index);
2953                         val = val >= right;
2954                         break;
2955                 default:
2956                         done = 1;
2957                         break;
2958                 }
2959         } while(!done);
2960         return val;
2961 }
2962
2963 static long_t meq_expr(struct compile_state *state, int index)
2964 {
2965         long_t val;
2966         int done;
2967         val = mrel_expr(state, index);
2968         do {
2969                 long_t right;
2970                 done = 0;
2971                 switch(mpeek(state, index)) {
2972                 case TOK_EQEQ:
2973                         meat(state, index, TOK_EQEQ);
2974                         right = mrel_expr(state, index);
2975                         val = val == right;
2976                         break;
2977                 case TOK_NOTEQ:
2978                         meat(state, index, TOK_NOTEQ);
2979                         right = mrel_expr(state, index);
2980                         val = val != right;
2981                         break;
2982                 default:
2983                         done = 1;
2984                         break;
2985                 }
2986         } while(!done);
2987         return val;
2988 }
2989
2990 static long_t mand_expr(struct compile_state *state, int index)
2991 {
2992         long_t val;
2993         val = meq_expr(state, index);
2994         if (mpeek(state, index) == TOK_AND) {
2995                 long_t right;
2996                 meat(state, index, TOK_AND);
2997                 right = meq_expr(state, index);
2998                 val = val & right;
2999         }
3000         return val;
3001 }
3002
3003 static long_t mxor_expr(struct compile_state *state, int index)
3004 {
3005         long_t val;
3006         val = mand_expr(state, index);
3007         if (mpeek(state, index) == TOK_XOR) {
3008                 long_t right;
3009                 meat(state, index, TOK_XOR);
3010                 right = mand_expr(state, index);
3011                 val = val ^ right;
3012         }
3013         return val;
3014 }
3015
3016 static long_t mor_expr(struct compile_state *state, int index)
3017 {
3018         long_t val;
3019         val = mxor_expr(state, index);
3020         if (mpeek(state, index) == TOK_OR) {
3021                 long_t right;
3022                 meat(state, index, TOK_OR);
3023                 right = mxor_expr(state, index);
3024                 val = val | right;
3025         }
3026         return val;
3027 }
3028
3029 static long_t mland_expr(struct compile_state *state, int index)
3030 {
3031         long_t val;
3032         val = mor_expr(state, index);
3033         if (mpeek(state, index) == TOK_LOGAND) {
3034                 long_t right;
3035                 meat(state, index, TOK_LOGAND);
3036                 right = mor_expr(state, index);
3037                 val = val && right;
3038         }
3039         return val;
3040 }
3041 static long_t mlor_expr(struct compile_state *state, int index)
3042 {
3043         long_t val;
3044         val = mland_expr(state, index);
3045         if (mpeek(state, index) == TOK_LOGOR) {
3046                 long_t right;
3047                 meat(state, index, TOK_LOGOR);
3048                 right = mland_expr(state, index);
3049                 val = val || right;
3050         }
3051         return val;
3052 }
3053
3054 static long_t mcexpr(struct compile_state *state, int index)
3055 {
3056         return mlor_expr(state, index);
3057 }
3058 static void preprocess(struct compile_state *state, int index)
3059 {
3060         /* Doing much more with the preprocessor would require
3061          * a parser and a major restructuring.
3062          * Postpone that for later.
3063          */
3064         struct file_state *file;
3065         struct token *tk;
3066         int line;
3067         int tok;
3068         
3069         file = state->file;
3070         tk = &state->token[index];
3071         state->macro_line = line = file->line;
3072         state->macro_file = file;
3073
3074         next_token(state, index);
3075         ident_to_macro(state, tk);
3076         if (tk->tok == TOK_IDENT) {
3077                 error(state, 0, "undefined preprocessing directive `%s'",
3078                         tk->ident->name);
3079         }
3080         switch(tk->tok) {
3081         case TOK_UNDEF:
3082         case TOK_LINE:
3083         case TOK_PRAGMA:
3084                 if (state->if_value < 0) {
3085                         break;
3086                 }
3087                 warning(state, 0, "Ignoring preprocessor directive: %s", 
3088                         tk->ident->name);
3089                 break;
3090         case TOK_ELIF:
3091                 error(state, 0, "#elif not supported");
3092 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3093                 if (state->if_depth == 0) {
3094                         error(state, 0, "#elif without #if");
3095                 }
3096                 /* If the #if was taken the #elif just disables the following code */
3097                 if (state->if_value >= 0) {
3098                         state->if_value = - state->if_value;
3099                 }
3100                 /* If the previous #if was not taken see if the #elif enables the 
3101                  * trailing code.
3102                  */
3103                 else if ((state->if_value < 0) && 
3104                         (state->if_depth == - state->if_value))
3105                 {
3106                         if (mcexpr(state, index) != 0) {
3107                                 state->if_value = state->if_depth;
3108                         }
3109                         else {
3110                                 state->if_value = - state->if_depth;
3111                         }
3112                 }
3113                 break;
3114         case TOK_IF:
3115                 state->if_depth++;
3116                 if (state->if_value < 0) {
3117                         break;
3118                 }
3119                 if (mcexpr(state, index) != 0) {
3120                         state->if_value = state->if_depth;
3121                 }
3122                 else {
3123                         state->if_value = - state->if_depth;
3124                 }
3125                 break;
3126         case TOK_IFNDEF:
3127                 state->if_depth++;
3128                 if (state->if_value < 0) {
3129                         break;
3130                 }
3131                 next_token(state, index);
3132                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3133                         error(state, 0, "Invalid macro name");
3134                 }
3135                 if (tk->ident->sym_define == 0) {
3136                         state->if_value = state->if_depth;
3137                 } 
3138                 else {
3139                         state->if_value = - state->if_depth;
3140                 }
3141                 break;
3142         case TOK_IFDEF:
3143                 state->if_depth++;
3144                 if (state->if_value < 0) {
3145                         break;
3146                 }
3147                 next_token(state, index);
3148                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3149                         error(state, 0, "Invalid macro name");
3150                 }
3151                 if (tk->ident->sym_define != 0) {
3152                         state->if_value = state->if_depth;
3153                 }
3154                 else {
3155                         state->if_value = - state->if_depth;
3156                 }
3157                 break;
3158         case TOK_ELSE:
3159                 if (state->if_depth == 0) {
3160                         error(state, 0, "#else without #if");
3161                 }
3162                 if ((state->if_value >= 0) ||
3163                         ((state->if_value < 0) && 
3164                                 (state->if_depth == -state->if_value)))
3165                 {
3166                         state->if_value = - state->if_value;
3167                 }
3168                 break;
3169         case TOK_ENDIF:
3170                 if (state->if_depth == 0) {
3171                         error(state, 0, "#endif without #if");
3172                 }
3173                 if ((state->if_value >= 0) ||
3174                         ((state->if_value < 0) &&
3175                                 (state->if_depth == -state->if_value))) 
3176                 {
3177                         state->if_value = state->if_depth - 1;
3178                 }
3179                 state->if_depth--;
3180                 break;
3181         case TOK_DEFINE:
3182         {
3183                 struct hash_entry *ident;
3184                 struct macro *macro;
3185                 char *ptr;
3186                 
3187                 if (state->if_value < 0) /* quit early when #if'd out */
3188                         break;
3189
3190                 meat(state, index, TOK_IDENT);
3191                 ident = tk->ident;
3192                 
3193
3194                 if (*file->pos == '(') {
3195 #warning "FIXME macros with arguments not supported"
3196                         error(state, 0, "Macros with arguments not supported");
3197                 }
3198
3199                 /* Find the end of the line to get an estimate of
3200                  * the macro's length.
3201                  */
3202                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
3203                         ;
3204
3205                 if (ident->sym_define != 0) {
3206                         error(state, 0, "macro %s already defined\n", ident->name);
3207                 }
3208                 macro = xmalloc(sizeof(*macro), "macro");
3209                 macro->ident = ident;
3210                 macro->buf_len = ptr - file->pos +1;
3211                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3212
3213                 memcpy(macro->buf, file->pos, macro->buf_len);
3214                 macro->buf[macro->buf_len] = '\n';
3215                 macro->buf[macro->buf_len +1] = '\0';
3216
3217                 ident->sym_define = macro;
3218                 break;
3219         }
3220         case TOK_ERROR:
3221         {
3222                 char *end;
3223                 int len;
3224                 /* Find the end of the line */
3225                 for(end = file->pos; *end != '\n'; end++)
3226                         ;
3227                 len = (end - file->pos);
3228                 if (state->if_value >= 0) {
3229                         error(state, 0, "%*.*s", len, len, file->pos);
3230                 }
3231                 file->pos = end;
3232                 break;
3233         }
3234         case TOK_WARNING:
3235         {
3236                 char *end;
3237                 int len;
3238                 /* Find the end of the line */
3239                 for(end = file->pos; *end != '\n'; end++)
3240                         ;
3241                 len = (end - file->pos);
3242                 if (state->if_value >= 0) {
3243                         warning(state, 0, "%*.*s", len, len, file->pos);
3244                 }
3245                 file->pos = end;
3246                 break;
3247         }
3248         case TOK_INCLUDE:
3249         {
3250                 char *name;
3251                 char *ptr;
3252                 int local;
3253                 local = 0;
3254                 name = 0;
3255                 next_token(state, index);
3256                 if (tk->tok == TOK_LIT_STRING) {
3257                         const char *token;
3258                         int name_len;
3259                         name = xmalloc(tk->str_len, "include");
3260                         token = tk->val.str +1;
3261                         name_len = tk->str_len -2;
3262                         if (*token == '"') {
3263                                 token++;
3264                                 name_len--;
3265                         }
3266                         memcpy(name, token, name_len);
3267                         name[name_len] = '\0';
3268                         local = 1;
3269                 }
3270                 else if (tk->tok == TOK_LESS) {
3271                         char *start, *end;
3272                         start = file->pos;
3273                         for(end = start; *end != '\n'; end++) {
3274                                 if (*end == '>') {
3275                                         break;
3276                                 }
3277                         }
3278                         if (*end == '\n') {
3279                                 error(state, 0, "Unterminated included directive");
3280                         }
3281                         name = xmalloc(end - start + 1, "include");
3282                         memcpy(name, start, end - start);
3283                         name[end - start] = '\0';
3284                         file->pos = end +1;
3285                         local = 0;
3286                 }
3287                 else {
3288                         error(state, 0, "Invalid include directive");
3289                 }
3290                 /* Error if there are any characters after the include */
3291                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3292                         switch(*ptr) {
3293                         case ' ':
3294                         case '\t':
3295                         case '\v':
3296                                 break;
3297                         default:
3298                                 error(state, 0, "garbage after include directive");
3299                         }
3300                 }
3301                 if (state->if_value >= 0) {
3302                         compile_file(state, name, local);
3303                 }
3304                 xfree(name);
3305                 next_token(state, index);
3306                 return;
3307         }
3308         default:
3309                 /* Ignore # without a following ident */
3310                 if (tk->tok == TOK_IDENT) {
3311                         error(state, 0, "Invalid preprocessor directive: %s", 
3312                                 tk->ident->name);
3313                 }
3314                 break;
3315         }
3316         /* Consume the rest of the macro line */
3317         do {
3318                 tok = mpeek(state, index);
3319                 meat(state, index, tok);
3320         } while(tok != TOK_EOF);
3321         return;
3322 }
3323
3324 static void token(struct compile_state *state, int index)
3325 {
3326         struct file_state *file;
3327         struct token *tk;
3328         int rescan;
3329
3330         tk = &state->token[index];
3331         next_token(state, index);
3332         do {
3333                 rescan = 0;
3334                 file = state->file;
3335                 if (tk->tok == TOK_EOF && file->prev) {
3336                         state->file = file->prev;
3337                         /* file->basename is used keep it */
3338                         xfree(file->dirname);
3339                         xfree(file->buf);
3340                         xfree(file);
3341                         next_token(state, index);
3342                         rescan = 1;
3343                 }
3344                 else if (tk->tok == TOK_MACRO) {
3345                         preprocess(state, index);
3346                         rescan = 1;
3347                 }
3348                 else if (tk->ident && tk->ident->sym_define) {
3349                         compile_macro(state, tk);
3350                         next_token(state, index);
3351                         rescan = 1;
3352                 }
3353                 else if (state->if_value < 0) {
3354                         next_token(state, index);
3355                         rescan = 1;
3356                 }
3357         } while(rescan);
3358 }
3359
3360 static int peek(struct compile_state *state)
3361 {
3362         if (state->token[1].tok == -1) {
3363                 token(state, 1);
3364         }
3365         return state->token[1].tok;
3366 }
3367
3368 static int peek2(struct compile_state *state)
3369 {
3370         if (state->token[1].tok == -1) {
3371                 token(state, 1);
3372         }
3373         if (state->token[2].tok == -1) {
3374                 token(state, 2);
3375         }
3376         return state->token[2].tok;
3377 }
3378
3379 static void eat(struct compile_state *state, int tok)
3380 {
3381         int next_tok;
3382         int i;
3383         next_tok = peek(state);
3384         if (next_tok != tok) {
3385                 const char *name1, *name2;
3386                 name1 = tokens[next_tok];
3387                 name2 = "";
3388                 if (next_tok == TOK_IDENT) {
3389                         name2 = state->token[1].ident->name;
3390                 }
3391                 error(state, 0, "\tfound %s %s expected %s",
3392                         name1, name2 ,tokens[tok]);
3393         }
3394         /* Free the old token value */
3395         if (state->token[0].str_len) {
3396                 xfree((void *)(state->token[0].val.str));
3397         }
3398         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3399                 state->token[i] = state->token[i + 1];
3400         }
3401         memset(&state->token[i], 0, sizeof(state->token[i]));
3402         state->token[i].tok = -1;
3403 }
3404
3405 #warning "FIXME do not hardcode the include paths"
3406 static char *include_paths[] = {
3407         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3408         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3409         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3410         0
3411 };
3412
3413 static void compile_file(struct compile_state *state, const char *filename, int local)
3414 {
3415         char cwd[4096];
3416         const char *subdir, *base;
3417         int subdir_len;
3418         struct file_state *file;
3419         char *basename;
3420         file = xmalloc(sizeof(*file), "file_state");
3421
3422         base = strrchr(filename, '/');
3423         subdir = filename;
3424         if (base != 0) {
3425                 subdir_len = base - filename;
3426                 base++;
3427         }
3428         else {
3429                 base = filename;
3430                 subdir_len = 0;
3431         }
3432         basename = xmalloc(strlen(base) +1, "basename");
3433         strcpy(basename, base);
3434         file->basename = basename;
3435
3436         if (getcwd(cwd, sizeof(cwd)) == 0) {
3437                 die("cwd buffer to small");
3438         }
3439         
3440         if (subdir[0] == '/') {
3441                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3442                 memcpy(file->dirname, subdir, subdir_len);
3443                 file->dirname[subdir_len] = '\0';
3444         }
3445         else {
3446                 char *dir;
3447                 int dirlen;
3448                 char **path;
3449                 /* Find the appropriate directory... */
3450                 dir = 0;
3451                 if (!state->file && exists(cwd, filename)) {
3452                         dir = cwd;
3453                 }
3454                 if (local && state->file && exists(state->file->dirname, filename)) {
3455                         dir = state->file->dirname;
3456                 }
3457                 for(path = include_paths; !dir && *path; path++) {
3458                         if (exists(*path, filename)) {
3459                                 dir = *path;
3460                         }
3461                 }
3462                 if (!dir) {
3463                         error(state, 0, "Cannot find `%s'\n", filename);
3464                 }
3465                 dirlen = strlen(dir);
3466                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3467                 memcpy(file->dirname, dir, dirlen);
3468                 file->dirname[dirlen] = '/';
3469                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3470                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3471         }
3472         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3473         xchdir(cwd);
3474
3475         file->pos = file->buf;
3476         file->line_start = file->pos;
3477         file->line = 1;
3478
3479         file->prev = state->file;
3480         state->file = file;
3481         
3482         process_trigraphs(state);
3483         splice_lines(state);
3484 }
3485
3486 /* Type helper functions */
3487
3488 static struct type *new_type(
3489         unsigned int type, struct type *left, struct type *right)
3490 {
3491         struct type *result;
3492         result = xmalloc(sizeof(*result), "type");
3493         result->type = type;
3494         result->left = left;
3495         result->right = right;
3496         result->field_ident = 0;
3497         result->type_ident = 0;
3498         return result;
3499 }
3500
3501 static struct type *clone_type(unsigned int specifiers, struct type *old)
3502 {
3503         struct type *result;
3504         result = xmalloc(sizeof(*result), "type");
3505         memcpy(result, old, sizeof(*result));
3506         result->type &= TYPE_MASK;
3507         result->type |= specifiers;
3508         return result;
3509 }
3510
3511 #define SIZEOF_SHORT 2
3512 #define SIZEOF_INT   4
3513 #define SIZEOF_LONG  (sizeof(long_t))
3514
3515 #define ALIGNOF_SHORT 2
3516 #define ALIGNOF_INT   4
3517 #define ALIGNOF_LONG  (sizeof(long_t))
3518
3519 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3520 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3521 static inline ulong_t mask_uint(ulong_t x)
3522 {
3523         if (SIZEOF_INT < SIZEOF_LONG) {
3524                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3525                 x &= mask;
3526         }
3527         return x;
3528 }
3529 #define MASK_UINT(X)      (mask_uint(X))
3530 #define MASK_ULONG(X)    (X)
3531
3532 static struct type void_type   = { .type  = TYPE_VOID };
3533 static struct type char_type   = { .type  = TYPE_CHAR };
3534 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3535 static struct type short_type  = { .type  = TYPE_SHORT };
3536 static struct type ushort_type = { .type  = TYPE_USHORT };
3537 static struct type int_type    = { .type  = TYPE_INT };
3538 static struct type uint_type   = { .type  = TYPE_UINT };
3539 static struct type long_type   = { .type  = TYPE_LONG };
3540 static struct type ulong_type  = { .type  = TYPE_ULONG };
3541
3542 static struct triple *variable(struct compile_state *state, struct type *type)
3543 {
3544         struct triple *result;
3545         if ((type->type & STOR_MASK) != STOR_PERM) {
3546                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3547                         result = triple(state, OP_ADECL, type, 0, 0);
3548                 } else {
3549                         struct type *field;
3550                         struct triple **vector;
3551                         ulong_t index;
3552                         result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3553                         vector = &result->param[0];
3554
3555                         field = type->left;
3556                         index = 0;
3557                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3558                                 vector[index] = variable(state, field->left);
3559                                 field = field->right;
3560                                 index++;
3561                         }
3562                         vector[index] = variable(state, field);
3563                 }
3564         }
3565         else {
3566                 result = triple(state, OP_SDECL, type, 0, 0);
3567         }
3568         return result;
3569 }
3570
3571 static void stor_of(FILE *fp, struct type *type)
3572 {
3573         switch(type->type & STOR_MASK) {
3574         case STOR_AUTO:
3575                 fprintf(fp, "auto ");
3576                 break;
3577         case STOR_STATIC:
3578                 fprintf(fp, "static ");
3579                 break;
3580         case STOR_EXTERN:
3581                 fprintf(fp, "extern ");
3582                 break;
3583         case STOR_REGISTER:
3584                 fprintf(fp, "register ");
3585                 break;
3586         case STOR_TYPEDEF:
3587                 fprintf(fp, "typedef ");
3588                 break;
3589         case STOR_INLINE:
3590                 fprintf(fp, "inline ");
3591                 break;
3592         }
3593 }
3594 static void qual_of(FILE *fp, struct type *type)
3595 {
3596         if (type->type & QUAL_CONST) {
3597                 fprintf(fp, " const");
3598         }
3599         if (type->type & QUAL_VOLATILE) {
3600                 fprintf(fp, " volatile");
3601         }
3602         if (type->type & QUAL_RESTRICT) {
3603                 fprintf(fp, " restrict");
3604         }
3605 }
3606
3607 static void name_of(FILE *fp, struct type *type)
3608 {
3609         stor_of(fp, type);
3610         switch(type->type & TYPE_MASK) {
3611         case TYPE_VOID:
3612                 fprintf(fp, "void");
3613                 qual_of(fp, type);
3614                 break;
3615         case TYPE_CHAR:
3616                 fprintf(fp, "signed char");
3617                 qual_of(fp, type);
3618                 break;
3619         case TYPE_UCHAR:
3620                 fprintf(fp, "unsigned char");
3621                 qual_of(fp, type);
3622                 break;
3623         case TYPE_SHORT:
3624                 fprintf(fp, "signed short");
3625                 qual_of(fp, type);
3626                 break;
3627         case TYPE_USHORT:
3628                 fprintf(fp, "unsigned short");
3629                 qual_of(fp, type);
3630                 break;
3631         case TYPE_INT:
3632                 fprintf(fp, "signed int");
3633                 qual_of(fp, type);
3634                 break;
3635         case TYPE_UINT:
3636                 fprintf(fp, "unsigned int");
3637                 qual_of(fp, type);
3638                 break;
3639         case TYPE_LONG:
3640                 fprintf(fp, "signed long");
3641                 qual_of(fp, type);
3642                 break;
3643         case TYPE_ULONG:
3644                 fprintf(fp, "unsigned long");
3645                 qual_of(fp, type);
3646                 break;
3647         case TYPE_POINTER:
3648                 name_of(fp, type->left);
3649                 fprintf(fp, " * ");
3650                 qual_of(fp, type);
3651                 break;
3652         case TYPE_PRODUCT:
3653         case TYPE_OVERLAP:
3654                 name_of(fp, type->left);
3655                 fprintf(fp, ", ");
3656                 name_of(fp, type->right);
3657                 break;
3658         case TYPE_ENUM:
3659                 fprintf(fp, "enum %s", type->type_ident->name);
3660                 qual_of(fp, type);
3661                 break;
3662         case TYPE_STRUCT:
3663                 fprintf(fp, "struct %s", type->type_ident->name);
3664                 qual_of(fp, type);
3665                 break;
3666         case TYPE_FUNCTION:
3667         {
3668                 name_of(fp, type->left);
3669                 fprintf(fp, " (*)(");
3670                 name_of(fp, type->right);
3671                 fprintf(fp, ")");
3672                 break;
3673         }
3674         case TYPE_ARRAY:
3675                 name_of(fp, type->left);
3676                 fprintf(fp, " [%ld]", type->elements);
3677                 break;
3678         default:
3679                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3680                 break;
3681         }
3682 }
3683
3684 static size_t align_of(struct compile_state *state, struct type *type)
3685 {
3686         size_t align;
3687         align = 0;
3688         switch(type->type & TYPE_MASK) {
3689         case TYPE_VOID:
3690                 align = 1;
3691                 break;
3692         case TYPE_CHAR:
3693         case TYPE_UCHAR:
3694                 align = 1;
3695                 break;
3696         case TYPE_SHORT:
3697         case TYPE_USHORT:
3698                 align = ALIGNOF_SHORT;
3699                 break;
3700         case TYPE_INT:
3701         case TYPE_UINT:
3702         case TYPE_ENUM:
3703                 align = ALIGNOF_INT;
3704                 break;
3705         case TYPE_LONG:
3706         case TYPE_ULONG:
3707         case TYPE_POINTER:
3708                 align = ALIGNOF_LONG;
3709                 break;
3710         case TYPE_PRODUCT:
3711         case TYPE_OVERLAP:
3712         {
3713                 size_t left_align, right_align;
3714                 left_align  = align_of(state, type->left);
3715                 right_align = align_of(state, type->right);
3716                 align = (left_align >= right_align) ? left_align : right_align;
3717                 break;
3718         }
3719         case TYPE_ARRAY:
3720                 align = align_of(state, type->left);
3721                 break;
3722         case TYPE_STRUCT:
3723                 align = align_of(state, type->left);
3724                 break;
3725         default:
3726                 error(state, 0, "alignof not yet defined for type\n");
3727                 break;
3728         }
3729         return align;
3730 }
3731
3732 static size_t size_of(struct compile_state *state, struct type *type)
3733 {
3734         size_t size;
3735         size = 0;
3736         switch(type->type & TYPE_MASK) {
3737         case TYPE_VOID:
3738                 size = 0;
3739                 break;
3740         case TYPE_CHAR:
3741         case TYPE_UCHAR:
3742                 size = 1;
3743                 break;
3744         case TYPE_SHORT:
3745         case TYPE_USHORT:
3746                 size = SIZEOF_SHORT;
3747                 break;
3748         case TYPE_INT:
3749         case TYPE_UINT:
3750         case TYPE_ENUM:
3751                 size = SIZEOF_INT;
3752                 break;
3753         case TYPE_LONG:
3754         case TYPE_ULONG:
3755         case TYPE_POINTER:
3756                 size = SIZEOF_LONG;
3757                 break;
3758         case TYPE_PRODUCT:
3759         {
3760                 size_t align, pad;
3761                 size = size_of(state, type->left);
3762                 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3763                         type = type->right;
3764                         align = align_of(state, type->left);
3765                         pad = align - (size % align);
3766                         size = size + pad + size_of(state, type->left);
3767                 }
3768                 align = align_of(state, type->right);
3769                 pad = align - (size % align);
3770                 size = size + pad + sizeof(type->right);
3771                 break;
3772         }
3773         case TYPE_OVERLAP:
3774         {
3775                 size_t size_left, size_right;
3776                 size_left = size_of(state, type->left);
3777                 size_right = size_of(state, type->right);
3778                 size = (size_left >= size_right)? size_left : size_right;
3779                 break;
3780         }
3781         case TYPE_ARRAY:
3782                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3783                         internal_error(state, 0, "Invalid array type");
3784                 } else {
3785                         size = size_of(state, type->left) * type->elements;
3786                 }
3787                 break;
3788         case TYPE_STRUCT:
3789                 size = size_of(state, type->left);
3790                 break;
3791         default:
3792                 error(state, 0, "sizeof not yet defined for type\n");
3793                 break;
3794         }
3795         return size;
3796 }
3797
3798 static size_t field_offset(struct compile_state *state, 
3799         struct type *type, struct hash_entry *field)
3800 {
3801         size_t size, align, pad;
3802         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3803                 internal_error(state, 0, "field_offset only works on structures");
3804         }
3805         size = 0;
3806         type = type->left;
3807         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3808                 if (type->left->field_ident == field) {
3809                         type = type->left;
3810                 }
3811                 size += size_of(state, type->left);
3812                 type = type->right;
3813                 align = align_of(state, type->left);
3814                 pad = align - (size % align);
3815                 size += pad;
3816         }
3817         if (type->field_ident != field) {
3818                 internal_error(state, 0, "field_offset: member %s not present",
3819                         field->name);
3820         }
3821         return size;
3822 }
3823
3824 static struct type *field_type(struct compile_state *state, 
3825         struct type *type, struct hash_entry *field)
3826 {
3827         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3828                 internal_error(state, 0, "field_type only works on structures");
3829         }
3830         type = type->left;
3831         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3832                 if (type->left->field_ident == field) {
3833                         type = type->left;
3834                         break;
3835                 }
3836                 type = type->right;
3837         }
3838         if (type->field_ident != field) {
3839                 internal_error(state, 0, "field_type: member %s not present", 
3840                         field->name);
3841         }
3842         return type;
3843 }
3844
3845 static struct triple *struct_field(struct compile_state *state,
3846         struct triple *decl, struct hash_entry *field)
3847 {
3848         struct triple **vector;
3849         struct type *type;
3850         ulong_t index;
3851         type = decl->type;
3852         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3853                 return decl;
3854         }
3855         if (decl->op != OP_VAL_VEC) {
3856                 internal_error(state, 0, "Invalid struct variable");
3857         }
3858         if (!field) {
3859                 internal_error(state, 0, "Missing structure field");
3860         }
3861         type = type->left;
3862         vector = &RHS(decl, 0);
3863         index = 0;
3864         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3865                 if (type->left->field_ident == field) {
3866                         type = type->left;
3867                         break;
3868                 }
3869                 index += 1;
3870                 type = type->right;
3871         }
3872         if (type->field_ident != field) {
3873                 internal_error(state, 0, "field %s not found?", field->name);
3874         }
3875         return vector[index];
3876 }
3877
3878 static void arrays_complete(struct compile_state *state, struct type *type)
3879 {
3880         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3881                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3882                         error(state, 0, "array size not specified");
3883                 }
3884                 arrays_complete(state, type->left);
3885         }
3886 }
3887
3888 static unsigned int do_integral_promotion(unsigned int type)
3889 {
3890         type &= TYPE_MASK;
3891         if (TYPE_INTEGER(type) && 
3892                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3893                 type = TYPE_INT;
3894         }
3895         return type;
3896 }
3897
3898 static unsigned int do_arithmetic_conversion(
3899         unsigned int left, unsigned int right)
3900 {
3901         left &= TYPE_MASK;
3902         right &= TYPE_MASK;
3903         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3904                 return TYPE_LDOUBLE;
3905         }
3906         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3907                 return TYPE_DOUBLE;
3908         }
3909         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3910                 return TYPE_FLOAT;
3911         }
3912         left = do_integral_promotion(left);
3913         right = do_integral_promotion(right);
3914         /* If both operands have the same size done */
3915         if (left == right) {
3916                 return left;
3917         }
3918         /* If both operands have the same signedness pick the larger */
3919         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3920                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3921         }
3922         /* If the signed type can hold everything use it */
3923         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3924                 return left;
3925         }
3926         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3927                 return right;
3928         }
3929         /* Convert to the unsigned type with the same rank as the signed type */
3930         else if (TYPE_SIGNED(left)) {
3931                 return TYPE_MKUNSIGNED(left);
3932         }
3933         else {
3934                 return TYPE_MKUNSIGNED(right);
3935         }
3936 }
3937
3938 /* see if two types are the same except for qualifiers */
3939 static int equiv_types(struct type *left, struct type *right)
3940 {
3941         unsigned int type;
3942         /* Error if the basic types do not match */
3943         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3944                 return 0;
3945         }
3946         type = left->type & TYPE_MASK;
3947         /* if the basic types match and it is an arithmetic type we are done */
3948         if (TYPE_ARITHMETIC(type)) {
3949                 return 1;
3950         }
3951         /* If it is a pointer type recurse and keep testing */
3952         if (type == TYPE_POINTER) {
3953                 return equiv_types(left->left, right->left);
3954         }
3955         else if (type == TYPE_ARRAY) {
3956                 return (left->elements == right->elements) &&
3957                         equiv_types(left->left, right->left);
3958         }
3959         /* test for struct/union equality */
3960         else if (type == TYPE_STRUCT) {
3961                 return left->type_ident == right->type_ident;
3962         }
3963         /* Test for equivalent functions */
3964         else if (type == TYPE_FUNCTION) {
3965                 return equiv_types(left->left, right->left) &&
3966                         equiv_types(left->right, right->right);
3967         }
3968         /* We only see TYPE_PRODUCT as part of function equivalence matching */
3969         else if (type == TYPE_PRODUCT) {
3970                 return equiv_types(left->left, right->left) &&
3971                         equiv_types(left->right, right->right);
3972         }
3973         /* We should see TYPE_OVERLAP */
3974         else {
3975                 return 0;
3976         }
3977 }
3978
3979 static int equiv_ptrs(struct type *left, struct type *right)
3980 {
3981         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3982                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3983                 return 0;
3984         }
3985         return equiv_types(left->left, right->left);
3986 }
3987
3988 static struct type *compatible_types(struct type *left, struct type *right)
3989 {
3990         struct type *result;
3991         unsigned int type, qual_type;
3992         /* Error if the basic types do not match */
3993         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3994                 return 0;
3995         }
3996         type = left->type & TYPE_MASK;
3997         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3998         result = 0;
3999         /* if the basic types match and it is an arithmetic type we are done */
4000         if (TYPE_ARITHMETIC(type)) {
4001                 result = new_type(qual_type, 0, 0);
4002         }
4003         /* If it is a pointer type recurse and keep testing */
4004         else if (type == TYPE_POINTER) {
4005                 result = compatible_types(left->left, right->left);
4006                 if (result) {
4007                         result = new_type(qual_type, result, 0);
4008                 }
4009         }
4010         /* test for struct/union equality */
4011         else if (type == TYPE_STRUCT) {
4012                 if (left->type_ident == right->type_ident) {
4013                         result = left;
4014                 }
4015         }
4016         /* Test for equivalent functions */
4017         else if (type == TYPE_FUNCTION) {
4018                 struct type *lf, *rf;
4019                 lf = compatible_types(left->left, right->left);
4020                 rf = compatible_types(left->right, right->right);
4021                 if (lf && rf) {
4022                         result = new_type(qual_type, lf, rf);
4023                 }
4024         }
4025         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4026         else if (type == TYPE_PRODUCT) {
4027                 struct type *lf, *rf;
4028                 lf = compatible_types(left->left, right->left);
4029                 rf = compatible_types(left->right, right->right);
4030                 if (lf && rf) {
4031                         result = new_type(qual_type, lf, rf);
4032                 }
4033         }
4034         else {
4035                 /* Nothing else is compatible */
4036         }
4037         return result;
4038 }
4039
4040 static struct type *compatible_ptrs(struct type *left, struct type *right)
4041 {
4042         struct type *result;
4043         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4044                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4045                 return 0;
4046         }
4047         result = compatible_types(left->left, right->left);
4048         if (result) {
4049                 unsigned int qual_type;
4050                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4051                 result = new_type(qual_type, result, 0);
4052         }
4053         return result;
4054         
4055 }
4056 static struct triple *integral_promotion(
4057         struct compile_state *state, struct triple *def)
4058 {
4059         struct type *type;
4060         type = def->type;
4061         /* As all operations are carried out in registers
4062          * the values are converted on load I just convert
4063          * logical type of the operand.
4064          */
4065         if (TYPE_INTEGER(type->type)) {
4066                 unsigned int int_type;
4067                 int_type = type->type & ~TYPE_MASK;
4068                 int_type |= do_integral_promotion(type->type);
4069                 if (int_type != type->type) {
4070                         def->type = new_type(int_type, 0, 0);
4071                 }
4072         }
4073         return def;
4074 }
4075
4076
4077 static void arithmetic(struct compile_state *state, struct triple *def)
4078 {
4079         if (!TYPE_ARITHMETIC(def->type->type)) {
4080                 error(state, 0, "arithmetic type expexted");
4081         }
4082 }
4083
4084 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4085 {
4086         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4087                 error(state, def, "pointer or arithmetic type expected");
4088         }
4089 }
4090
4091 static int is_integral(struct triple *ins)
4092 {
4093         return TYPE_INTEGER(ins->type->type);
4094 }
4095
4096 static void integral(struct compile_state *state, struct triple *def)
4097 {
4098         if (!is_integral(def)) {
4099                 error(state, 0, "integral type expected");
4100         }
4101 }
4102
4103
4104 static void bool(struct compile_state *state, struct triple *def)
4105 {
4106         if (!TYPE_ARITHMETIC(def->type->type) &&
4107                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4108                 error(state, 0, "arithmetic or pointer type expected");
4109         }
4110 }
4111
4112 static int is_signed(struct type *type)
4113 {
4114         return !!TYPE_SIGNED(type->type);
4115 }
4116
4117 /* Is this value located in a register otherwise it must be in memory */
4118 static int is_in_reg(struct compile_state *state, struct triple *def)
4119 {
4120         int in_reg;
4121         if (def->op == OP_ADECL) {
4122                 in_reg = 1;
4123         }
4124         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4125                 in_reg = 0;
4126         }
4127         else if (def->op == OP_VAL_VEC) {
4128                 in_reg = is_in_reg(state, RHS(def, 0));
4129         }
4130         else if (def->op == OP_DOT) {
4131                 in_reg = is_in_reg(state, RHS(def, 0));
4132         }
4133         else {
4134                 internal_error(state, 0, "unknown expr storage location");
4135                 in_reg = -1;
4136         }
4137         return in_reg;
4138 }
4139
4140 /* Is this a stable variable location otherwise it must be a temporary */
4141 static int is_stable(struct compile_state *state, struct triple *def)
4142 {
4143         int ret;
4144         ret = 0;
4145         if (!def) {
4146                 return 0;
4147         }
4148         if ((def->op == OP_ADECL) || 
4149                 (def->op == OP_SDECL) || 
4150                 (def->op == OP_DEREF) ||
4151                 (def->op == OP_BLOBCONST)) {
4152                 ret = 1;
4153         }
4154         else if (def->op == OP_DOT) {
4155                 ret = is_stable(state, RHS(def, 0));
4156         }
4157         else if (def->op == OP_VAL_VEC) {
4158                 struct triple **vector;
4159                 ulong_t i;
4160                 ret = 1;
4161                 vector = &RHS(def, 0);
4162                 for(i = 0; i < def->type->elements; i++) {
4163                         if (!is_stable(state, vector[i])) {
4164                                 ret = 0;
4165                                 break;
4166                         }
4167                 }
4168         }
4169         return ret;
4170 }
4171
4172 static int is_lvalue(struct compile_state *state, struct triple *def)
4173 {
4174         int ret;
4175         ret = 1;
4176         if (!def) {
4177                 return 0;
4178         }
4179         if (!is_stable(state, def)) {
4180                 return 0;
4181         }
4182         if (def->type->type & QUAL_CONST) {
4183                 ret = 0;
4184         }
4185         else if (def->op == OP_DOT) {
4186                 ret = is_lvalue(state, RHS(def, 0));
4187         }
4188         return ret;
4189 }
4190
4191 static void lvalue(struct compile_state *state, struct triple *def)
4192 {
4193         if (!def) {
4194                 internal_error(state, def, "nothing where lvalue expected?");
4195         }
4196         if (!is_lvalue(state, def)) { 
4197                 error(state, def, "lvalue expected");
4198         }
4199 }
4200
4201 static int is_pointer(struct triple *def)
4202 {
4203         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4204 }
4205
4206 static void pointer(struct compile_state *state, struct triple *def)
4207 {
4208         if (!is_pointer(def)) {
4209                 error(state, def, "pointer expected");
4210         }
4211 }
4212
4213 static struct triple *int_const(
4214         struct compile_state *state, struct type *type, ulong_t value)
4215 {
4216         struct triple *result;
4217         switch(type->type & TYPE_MASK) {
4218         case TYPE_CHAR:
4219         case TYPE_INT:   case TYPE_UINT:
4220         case TYPE_LONG:  case TYPE_ULONG:
4221                 break;
4222         default:
4223                 internal_error(state, 0, "constant for unkown type");
4224         }
4225         result = triple(state, OP_INTCONST, type, 0, 0);
4226         result->u.cval = value;
4227         return result;
4228 }
4229
4230
4231 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4232         struct triple *expr, struct type *type, ulong_t offset)
4233 {
4234         struct triple *result;
4235         lvalue(state, expr);
4236
4237         result = 0;
4238         if (expr->op == OP_ADECL) {
4239                 error(state, expr, "address of auto variables not supported");
4240         }
4241         else if (expr->op == OP_SDECL) {
4242                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4243                 MISC(result, 0) = expr;
4244                 result->u.cval = offset;
4245         }
4246         else if (expr->op == OP_DEREF) {
4247                 result = triple(state, OP_ADD, type,
4248                         RHS(expr, 0),
4249                         int_const(state, &ulong_type, offset));
4250         }
4251         return result;
4252 }
4253
4254 static struct triple *mk_addr_expr(
4255         struct compile_state *state, struct triple *expr, ulong_t offset)
4256 {
4257         struct type *type;
4258         
4259         type = new_type(
4260                 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4261                 expr->type, 0);
4262
4263         return do_mk_addr_expr(state, expr, type, offset);
4264 }
4265
4266 static struct triple *mk_deref_expr(
4267         struct compile_state *state, struct triple *expr)
4268 {
4269         struct type *base_type;
4270         pointer(state, expr);
4271         base_type = expr->type->left;
4272         if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4273                 error(state, 0, 
4274                         "Only pointer and arithmetic values can be dereferenced");
4275         }
4276         return triple(state, OP_DEREF, base_type, expr, 0);
4277 }
4278
4279 static struct triple *deref_field(
4280         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4281 {
4282         struct triple *result;
4283         struct type *type, *member;
4284         if (!field) {
4285                 internal_error(state, 0, "No field passed to deref_field");
4286         }
4287         result = 0;
4288         type = expr->type;
4289         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4290                 error(state, 0, "request for member %s in something not a struct or union",
4291                         field->name);
4292         }
4293         member = type->left;
4294         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4295                 if (member->left->field_ident == field) {
4296                         member = member->left;
4297                         break;
4298                 }
4299                 member = member->right;
4300         }
4301         if (member->field_ident != field) {
4302                 error(state, 0, "%s is not a member", field->name);
4303         }
4304         if ((type->type & STOR_MASK) == STOR_PERM) {
4305                 /* Do the pointer arithmetic to get a deref the field */
4306                 ulong_t offset;
4307                 offset = field_offset(state, type, field);
4308                 result = do_mk_addr_expr(state, expr, member, offset);
4309                 result = mk_deref_expr(state, result);
4310         }
4311         else {
4312                 /* Find the variable for the field I want. */
4313                 result = triple(state, OP_DOT, 
4314                         field_type(state, type, field), expr, 0);
4315                 result->u.field = field;
4316         }
4317         return result;
4318 }
4319
4320 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4321 {
4322         int op;
4323         if  (!def) {
4324                 return 0;
4325         }
4326         if (!is_stable(state, def)) {
4327                 return def;
4328         }
4329         /* Tranform an array to a pointer to the first element */
4330 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4331         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4332                 struct type *type;
4333                 struct triple *result;
4334                 type = new_type(
4335                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4336                         def->type->left, 0);
4337                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4338                 MISC(result, 0) = def;
4339                 return result;
4340         }
4341         if (is_in_reg(state, def)) {
4342                 op = OP_READ;
4343         } else {
4344                 op = OP_LOAD;
4345         }
4346         return triple(state, op, def->type, def, 0);
4347 }
4348
4349 static void write_compatible(struct compile_state *state,
4350         struct type *dest, struct type *rval)
4351 {
4352         int compatible = 0;
4353         /* Both operands have arithmetic type */
4354         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4355                 compatible = 1;
4356         }
4357         /* One operand is a pointer and the other is a pointer to void */
4358         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4359                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4360                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4361                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4362                 compatible = 1;
4363         }
4364         /* If both types are the same without qualifiers we are good */
4365         else if (equiv_ptrs(dest, rval)) {
4366                 compatible = 1;
4367         }
4368         /* test for struct/union equality  */
4369         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4370                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4371                 (dest->type_ident == rval->type_ident)) {
4372                 compatible = 1;
4373         }
4374         if (!compatible) {
4375                 error(state, 0, "Incompatible types in assignment");
4376         }
4377 }
4378
4379 static struct triple *write_expr(
4380         struct compile_state *state, struct triple *dest, struct triple *rval)
4381 {
4382         struct triple *def;
4383         int op;
4384
4385         def = 0;
4386         if (!rval) {
4387                 internal_error(state, 0, "missing rval");
4388         }
4389
4390         if (rval->op == OP_LIST) {
4391                 internal_error(state, 0, "expression of type OP_LIST?");
4392         }
4393         if (!is_lvalue(state, dest)) {
4394                 internal_error(state, 0, "writing to a non lvalue?");
4395         }
4396
4397         write_compatible(state, dest->type, rval->type);
4398
4399         /* Now figure out which assignment operator to use */
4400         op = -1;
4401         if (is_in_reg(state, dest)) {
4402                 op = OP_WRITE;
4403         } else {
4404                 op = OP_STORE;
4405         }
4406         def = triple(state, op, dest->type, dest, rval);
4407         return def;
4408 }
4409
4410 static struct triple *init_expr(
4411         struct compile_state *state, struct triple *dest, struct triple *rval)
4412 {
4413         struct triple *def;
4414
4415         def = 0;
4416         if (!rval) {
4417                 internal_error(state, 0, "missing rval");
4418         }
4419         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4420                 rval = read_expr(state, rval);
4421                 def = write_expr(state, dest, rval);
4422         }
4423         else {
4424                 /* Fill in the array size if necessary */
4425                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4426                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4427                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4428                                 dest->type->elements = rval->type->elements;
4429                         }
4430                 }
4431                 if (!equiv_types(dest->type, rval->type)) {
4432                         error(state, 0, "Incompatible types in inializer");
4433                 }
4434                 MISC(dest, 0) = rval;
4435                 insert_triple(state, dest, rval);
4436                 rval->id |= TRIPLE_FLAG_FLATTENED;
4437                 use_triple(MISC(dest, 0), dest);
4438         }
4439         return def;
4440 }
4441
4442 struct type *arithmetic_result(
4443         struct compile_state *state, struct triple *left, struct triple *right)
4444 {
4445         struct type *type;
4446         /* Sanity checks to ensure I am working with arithmetic types */
4447         arithmetic(state, left);
4448         arithmetic(state, right);
4449         type = new_type(
4450                 do_arithmetic_conversion(
4451                         left->type->type, 
4452                         right->type->type), 0, 0);
4453         return type;
4454 }
4455
4456 struct type *ptr_arithmetic_result(
4457         struct compile_state *state, struct triple *left, struct triple *right)
4458 {
4459         struct type *type;
4460         /* Sanity checks to ensure I am working with the proper types */
4461         ptr_arithmetic(state, left);
4462         arithmetic(state, right);
4463         if (TYPE_ARITHMETIC(left->type->type) && 
4464                 TYPE_ARITHMETIC(right->type->type)) {
4465                 type = arithmetic_result(state, left, right);
4466         }
4467         else if (TYPE_PTR(left->type->type)) {
4468                 type = left->type;
4469         }
4470         else {
4471                 internal_error(state, 0, "huh?");
4472                 type = 0;
4473         }
4474         return type;
4475 }
4476
4477
4478 /* boolean helper function */
4479
4480 static struct triple *ltrue_expr(struct compile_state *state, 
4481         struct triple *expr)
4482 {
4483         switch(expr->op) {
4484         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4485         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4486         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4487                 /* If the expression is already boolean do nothing */
4488                 break;
4489         default:
4490                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4491                 break;
4492         }
4493         return expr;
4494 }
4495
4496 static struct triple *lfalse_expr(struct compile_state *state, 
4497         struct triple *expr)
4498 {
4499         return triple(state, OP_LFALSE, &int_type, expr, 0);
4500 }
4501
4502 static struct triple *cond_expr(
4503         struct compile_state *state, 
4504         struct triple *test, struct triple *left, struct triple *right)
4505 {
4506         struct triple *def;
4507         struct type *result_type;
4508         unsigned int left_type, right_type;
4509         bool(state, test);
4510         left_type = left->type->type;
4511         right_type = right->type->type;
4512         result_type = 0;
4513         /* Both operands have arithmetic type */
4514         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4515                 result_type = arithmetic_result(state, left, right);
4516         }
4517         /* Both operands have void type */
4518         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4519                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4520                 result_type = &void_type;
4521         }
4522         /* pointers to the same type... */
4523         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4524                 ;
4525         }
4526         /* Both operands are pointers and left is a pointer to void */
4527         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4528                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4529                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4530                 result_type = right->type;
4531         }
4532         /* Both operands are pointers and right is a pointer to void */
4533         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4534                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4535                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4536                 result_type = left->type;
4537         }
4538         if (!result_type) {
4539                 error(state, 0, "Incompatible types in conditional expression");
4540         }
4541         /* Cleanup and invert the test */
4542         test = lfalse_expr(state, read_expr(state, test));
4543         def = new_triple(state, OP_COND, result_type, 0, 3);
4544         def->param[0] = test;
4545         def->param[1] = left;
4546         def->param[2] = right;
4547         return def;
4548 }
4549
4550
4551 static int expr_depth(struct compile_state *state, struct triple *ins)
4552 {
4553         int count;
4554         count = 0;
4555         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4556                 count = 0;
4557         }
4558         else if (ins->op == OP_DEREF) {
4559                 count = expr_depth(state, RHS(ins, 0)) - 1;
4560         }
4561         else if (ins->op == OP_VAL) {
4562                 count = expr_depth(state, RHS(ins, 0)) - 1;
4563         }
4564         else if (ins->op == OP_COMMA) {
4565                 int ldepth, rdepth;
4566                 ldepth = expr_depth(state, RHS(ins, 0));
4567                 rdepth = expr_depth(state, RHS(ins, 1));
4568                 count = (ldepth >= rdepth)? ldepth : rdepth;
4569         }
4570         else if (ins->op == OP_CALL) {
4571                 /* Don't figure the depth of a call just guess it is huge */
4572                 count = 1000;
4573         }
4574         else {
4575                 struct triple **expr;
4576                 expr = triple_rhs(state, ins, 0);
4577                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4578                         if (*expr) {
4579                                 int depth;
4580                                 depth = expr_depth(state, *expr);
4581                                 if (depth > count) {
4582                                         count = depth;
4583                                 }
4584                         }
4585                 }
4586         }
4587         return count + 1;
4588 }
4589
4590 static struct triple *flatten(
4591         struct compile_state *state, struct triple *first, struct triple *ptr);
4592
4593 static struct triple *flatten_generic(
4594         struct compile_state *state, struct triple *first, struct triple *ptr)
4595 {
4596         struct rhs_vector {
4597                 int depth;
4598                 struct triple **ins;
4599         } vector[MAX_RHS];
4600         int i, rhs, lhs;
4601         /* Only operations with just a rhs should come here */
4602         rhs = TRIPLE_RHS(ptr->sizes);
4603         lhs = TRIPLE_LHS(ptr->sizes);
4604         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4605                 internal_error(state, ptr, "unexpected args for: %d %s",
4606                         ptr->op, tops(ptr->op));
4607         }
4608         /* Find the depth of the rhs elements */
4609         for(i = 0; i < rhs; i++) {
4610                 vector[i].ins = &RHS(ptr, i);
4611                 vector[i].depth = expr_depth(state, *vector[i].ins);
4612         }
4613         /* Selection sort the rhs */
4614         for(i = 0; i < rhs; i++) {
4615                 int j, max = i;
4616                 for(j = i + 1; j < rhs; j++ ) {
4617                         if (vector[j].depth > vector[max].depth) {
4618                                 max = j;
4619                         }
4620                 }
4621                 if (max != i) {
4622                         struct rhs_vector tmp;
4623                         tmp = vector[i];
4624                         vector[i] = vector[max];
4625                         vector[max] = tmp;
4626                 }
4627         }
4628         /* Now flatten the rhs elements */
4629         for(i = 0; i < rhs; i++) {
4630                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4631                 use_triple(*vector[i].ins, ptr);
4632         }
4633         
4634         /* Now flatten the lhs elements */
4635         for(i = 0; i < lhs; i++) {
4636                 struct triple **ins = &LHS(ptr, i);
4637                 *ins = flatten(state, first, *ins);
4638                 use_triple(*ins, ptr);
4639         }
4640         return ptr;
4641 }
4642
4643 static struct triple *flatten_land(
4644         struct compile_state *state, struct triple *first, struct triple *ptr)
4645 {
4646         struct triple *left, *right;
4647         struct triple *val, *test, *jmp, *label1, *end;
4648
4649         /* Find the triples */
4650         left = RHS(ptr, 0);
4651         right = RHS(ptr, 1);
4652
4653         /* Generate the needed triples */
4654         end = label(state);
4655
4656         /* Thread the triples together */
4657         val          = flatten(state, first, variable(state, ptr->type));
4658         left         = flatten(state, first, write_expr(state, val, left));
4659         test         = flatten(state, first, 
4660                 lfalse_expr(state, read_expr(state, val)));
4661         jmp          = flatten(state, first, branch(state, end, test));
4662         label1       = flatten(state, first, label(state));
4663         right        = flatten(state, first, write_expr(state, val, right));
4664         TARG(jmp, 0) = flatten(state, first, end); 
4665         
4666         /* Now give the caller something to chew on */
4667         return read_expr(state, val);
4668 }
4669
4670 static struct triple *flatten_lor(
4671         struct compile_state *state, struct triple *first, struct triple *ptr)
4672 {
4673         struct triple *left, *right;
4674         struct triple *val, *jmp, *label1, *end;
4675
4676         /* Find the triples */
4677         left = RHS(ptr, 0);
4678         right = RHS(ptr, 1);
4679
4680         /* Generate the needed triples */
4681         end = label(state);
4682
4683         /* Thread the triples together */
4684         val          = flatten(state, first, variable(state, ptr->type));
4685         left         = flatten(state, first, write_expr(state, val, left));
4686         jmp          = flatten(state, first, branch(state, end, left));
4687         label1       = flatten(state, first, label(state));
4688         right        = flatten(state, first, write_expr(state, val, right));
4689         TARG(jmp, 0) = flatten(state, first, end);
4690        
4691         
4692         /* Now give the caller something to chew on */
4693         return read_expr(state, val);
4694 }
4695
4696 static struct triple *flatten_cond(
4697         struct compile_state *state, struct triple *first, struct triple *ptr)
4698 {
4699         struct triple *test, *left, *right;
4700         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4701
4702         /* Find the triples */
4703         test = RHS(ptr, 0);
4704         left = RHS(ptr, 1);
4705         right = RHS(ptr, 2);
4706
4707         /* Generate the needed triples */
4708         end = label(state);
4709         middle = label(state);
4710
4711         /* Thread the triples together */
4712         val           = flatten(state, first, variable(state, ptr->type));
4713         test          = flatten(state, first, test);
4714         jmp1          = flatten(state, first, branch(state, middle, test));
4715         label1        = flatten(state, first, label(state));
4716         left          = flatten(state, first, left);
4717         mv1           = flatten(state, first, write_expr(state, val, left));
4718         jmp2          = flatten(state, first, branch(state, end, 0));
4719         TARG(jmp1, 0) = flatten(state, first, middle);
4720         right         = flatten(state, first, right);
4721         mv2           = flatten(state, first, write_expr(state, val, right));
4722         TARG(jmp2, 0) = flatten(state, first, end);
4723         
4724         /* Now give the caller something to chew on */
4725         return read_expr(state, val);
4726 }
4727
4728 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4729 {
4730         struct triple *nfunc;
4731         struct triple *nfirst, *ofirst;
4732         struct triple *new, *old;
4733
4734 #if 0
4735         fprintf(stdout, "\n");
4736         loc(stdout, state, 0);
4737         fprintf(stdout, "\n__________ copy_func _________\n");
4738         print_triple(state, ofunc);
4739         fprintf(stdout, "__________ copy_func _________ done\n\n");
4740 #endif
4741
4742         /* Make a new copy of the old function */
4743         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4744         nfirst = 0;
4745         ofirst = old = RHS(ofunc, 0);
4746         do {
4747                 struct triple *new;
4748                 int old_lhs, old_rhs;
4749                 old_lhs = TRIPLE_LHS(old->sizes);
4750                 old_rhs = TRIPLE_RHS(old->sizes);
4751                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4752                         old->filename, old->line, old->col);
4753                 if (!triple_stores_block(state, new)) {
4754                         memcpy(&new->u, &old->u, sizeof(new->u));
4755                 }
4756                 if (!nfirst) {
4757                         RHS(nfunc, 0) = nfirst = new;
4758                 }
4759                 else {
4760                         insert_triple(state, nfirst, new);
4761                 }
4762                 new->id |= TRIPLE_FLAG_FLATTENED;
4763                 
4764                 /* During the copy remember new as user of old */
4765                 use_triple(old, new);
4766
4767                 /* Populate the return type if present */
4768                 if (old == MISC(ofunc, 0)) {
4769                         MISC(nfunc, 0) = new;
4770                 }
4771                 old = old->next;
4772         } while(old != ofirst);
4773
4774         /* Make a second pass to fix up any unresolved references */
4775         old = ofirst;
4776         new = nfirst;
4777         do {
4778                 struct triple **oexpr, **nexpr;
4779                 int count, i;
4780                 /* Lookup where the copy is, to join pointers */
4781                 count = TRIPLE_SIZE(old->sizes);
4782                 for(i = 0; i < count; i++) {
4783                         oexpr = &old->param[i];
4784                         nexpr = &new->param[i];
4785                         if (!*nexpr && *oexpr && (*oexpr)->use) {
4786                                 *nexpr = (*oexpr)->use->member;
4787                                 if (*nexpr == old) {
4788                                         internal_error(state, 0, "new == old?");
4789                                 }
4790                                 use_triple(*nexpr, new);
4791                         }
4792                         if (!*nexpr && *oexpr) {
4793                                 internal_error(state, 0, "Could not copy %d\n", i);
4794                         }
4795                 }
4796                 old = old->next;
4797                 new = new->next;
4798         } while((old != ofirst) && (new != nfirst));
4799         
4800         /* Make a third pass to cleanup the extra useses */
4801         old = ofirst;
4802         new = nfirst;
4803         do {
4804                 unuse_triple(old, new);
4805                 old = old->next;
4806                 new = new->next;
4807         } while ((old != ofirst) && (new != nfirst));
4808         return nfunc;
4809 }
4810
4811 static struct triple *flatten_call(
4812         struct compile_state *state, struct triple *first, struct triple *ptr)
4813 {
4814         /* Inline the function call */
4815         struct type *ptype;
4816         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4817         struct triple *end, *nend;
4818         int pvals, i;
4819
4820         /* Find the triples */
4821         ofunc = MISC(ptr, 0);
4822         if (ofunc->op != OP_LIST) {
4823                 internal_error(state, 0, "improper function");
4824         }
4825         nfunc = copy_func(state, ofunc);
4826         nfirst = RHS(nfunc, 0)->next;
4827         /* Prepend the parameter reading into the new function list */
4828         ptype = nfunc->type->right;
4829         param = RHS(nfunc, 0)->next;
4830         pvals = TRIPLE_RHS(ptr->sizes);
4831         for(i = 0; i < pvals; i++) {
4832                 struct type *atype;
4833                 struct triple *arg;
4834                 atype = ptype;
4835                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4836                         atype = ptype->left;
4837                 }
4838                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4839                         param = param->next;
4840                 }
4841                 arg = RHS(ptr, i);
4842                 flatten(state, nfirst, write_expr(state, param, arg));
4843                 ptype = ptype->right;
4844                 param = param->next;
4845         }
4846         result = 0;
4847         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4848                 result = read_expr(state, MISC(nfunc,0));
4849         }
4850 #if 0
4851         fprintf(stdout, "\n");
4852         loc(stdout, state, 0);
4853         fprintf(stdout, "\n__________ flatten_call _________\n");
4854         print_triple(state, nfunc);
4855         fprintf(stdout, "__________ flatten_call _________ done\n\n");
4856 #endif
4857
4858         /* Get rid of the extra triples */
4859         nfirst = RHS(nfunc, 0)->next;
4860         free_triple(state, RHS(nfunc, 0));
4861         RHS(nfunc, 0) = 0;
4862         free_triple(state, nfunc);
4863
4864         /* Append the new function list onto the return list */
4865         end = first->prev;
4866         nend = nfirst->prev;
4867         end->next    = nfirst;
4868         nfirst->prev = end;
4869         nend->next   = first;
4870         first->prev  = nend;
4871
4872         return result;
4873 }
4874
4875 static struct triple *flatten(
4876         struct compile_state *state, struct triple *first, struct triple *ptr)
4877 {
4878         struct triple *orig_ptr;
4879         if (!ptr)
4880                 return 0;
4881         do {
4882                 orig_ptr = ptr;
4883                 /* Only flatten triples once */
4884                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4885                         return ptr;
4886                 }
4887                 switch(ptr->op) {
4888                 case OP_WRITE:
4889                 case OP_STORE:
4890                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4891                         LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4892                         use_triple(LHS(ptr, 0), ptr);
4893                         use_triple(RHS(ptr, 0), ptr);
4894                         break;
4895                 case OP_COMMA:
4896                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4897                         ptr = RHS(ptr, 1);
4898                         break;
4899                 case OP_VAL:
4900                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4901                         return MISC(ptr, 0);
4902                         break;
4903                 case OP_LAND:
4904                         ptr = flatten_land(state, first, ptr);
4905                         break;
4906                 case OP_LOR:
4907                         ptr = flatten_lor(state, first, ptr);
4908                         break;
4909                 case OP_COND:
4910                         ptr = flatten_cond(state, first, ptr);
4911                         break;
4912                 case OP_CALL:
4913                         ptr = flatten_call(state, first, ptr);
4914                         break;
4915                 case OP_READ:
4916                 case OP_LOAD:
4917                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4918                         use_triple(RHS(ptr, 0), ptr);
4919                         break;
4920                 case OP_BRANCH:
4921                         use_triple(TARG(ptr, 0), ptr);
4922                         if (TRIPLE_RHS(ptr->sizes)) {
4923                                 use_triple(RHS(ptr, 0), ptr);
4924                                 if (ptr->next != ptr) {
4925                                         use_triple(ptr->next, ptr);
4926                                 }
4927                         }
4928                         break;
4929                 case OP_BLOBCONST:
4930                         insert_triple(state, first, ptr);
4931                         ptr->id |= TRIPLE_FLAG_FLATTENED;
4932                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4933                         use_triple(MISC(ptr, 0), ptr);
4934                         break;
4935                 case OP_DEREF:
4936                         /* Since OP_DEREF is just a marker delete it when I flatten it */
4937                         ptr = RHS(ptr, 0);
4938                         RHS(orig_ptr, 0) = 0;
4939                         free_triple(state, orig_ptr);
4940                         break;
4941                 case OP_DOT:
4942                 {
4943                         struct triple *base;
4944                         base = RHS(ptr, 0);
4945                         base = flatten(state, first, base);
4946                         if (base->op == OP_VAL_VEC) {
4947                                 ptr = struct_field(state, base, ptr->u.field);
4948                         }
4949                         break;
4950                 }
4951                 case OP_PIECE:
4952                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4953                         use_triple(MISC(ptr, 0), ptr);
4954                         use_triple(ptr, MISC(ptr, 0));
4955                         break;
4956                 case OP_ADDRCONST:
4957                 case OP_SDECL:
4958                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4959                         use_triple(MISC(ptr, 0), ptr);
4960                         break;
4961                 case OP_ADECL:
4962                         break;
4963                 default:
4964                         /* Flatten the easy cases we don't override */
4965                         ptr = flatten_generic(state, first, ptr);
4966                         break;
4967                 }
4968         } while(ptr && (ptr != orig_ptr));
4969         if (ptr) {
4970                 insert_triple(state, first, ptr);
4971                 ptr->id |= TRIPLE_FLAG_FLATTENED;
4972         }
4973         return ptr;
4974 }
4975
4976 static void release_expr(struct compile_state *state, struct triple *expr)
4977 {
4978         struct triple *head;
4979         head = label(state);
4980         flatten(state, head, expr);
4981         while(head->next != head) {
4982                 release_triple(state, head->next);
4983         }
4984         free_triple(state, head);
4985 }
4986
4987 static int replace_rhs_use(struct compile_state *state,
4988         struct triple *orig, struct triple *new, struct triple *use)
4989 {
4990         struct triple **expr;
4991         int found;
4992         found = 0;
4993         expr = triple_rhs(state, use, 0);
4994         for(;expr; expr = triple_rhs(state, use, expr)) {
4995                 if (*expr == orig) {
4996                         *expr = new;
4997                         found = 1;
4998                 }
4999         }
5000         if (found) {
5001                 unuse_triple(orig, use);
5002                 use_triple(new, use);
5003         }
5004         return found;
5005 }
5006
5007 static int replace_lhs_use(struct compile_state *state,
5008         struct triple *orig, struct triple *new, struct triple *use)
5009 {
5010         struct triple **expr;
5011         int found;
5012         found = 0;
5013         expr = triple_lhs(state, use, 0);
5014         for(;expr; expr = triple_lhs(state, use, expr)) {
5015                 if (*expr == orig) {
5016                         *expr = new;
5017                         found = 1;
5018                 }
5019         }
5020         if (found) {
5021                 unuse_triple(orig, use);
5022                 use_triple(new, use);
5023         }
5024         return found;
5025 }
5026
5027 static void propogate_use(struct compile_state *state,
5028         struct triple *orig, struct triple *new)
5029 {
5030         struct triple_set *user, *next;
5031         for(user = orig->use; user; user = next) {
5032                 struct triple *use;
5033                 int found;
5034                 next = user->next;
5035                 use = user->member;
5036                 found = 0;
5037                 found |= replace_rhs_use(state, orig, new, use);
5038                 found |= replace_lhs_use(state, orig, new, use);
5039                 if (!found) {
5040                         internal_error(state, use, "use without use");
5041                 }
5042         }
5043         if (orig->use) {
5044                 internal_error(state, orig, "used after propogate_use");
5045         }
5046 }
5047
5048 /*
5049  * Code generators
5050  * ===========================
5051  */
5052
5053 static struct triple *mk_add_expr(
5054         struct compile_state *state, struct triple *left, struct triple *right)
5055 {
5056         struct type *result_type;
5057         /* Put pointer operands on the left */
5058         if (is_pointer(right)) {
5059                 struct triple *tmp;
5060                 tmp = left;
5061                 left = right;
5062                 right = tmp;
5063         }
5064         left  = read_expr(state, left);
5065         right = read_expr(state, right);
5066         result_type = ptr_arithmetic_result(state, left, right);
5067         if (is_pointer(left)) {
5068                 right = triple(state, 
5069                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5070                         &ulong_type, 
5071                         right, 
5072                         int_const(state, &ulong_type, 
5073                                 size_of(state, left->type->left)));
5074         }
5075         return triple(state, OP_ADD, result_type, left, right);
5076 }
5077
5078 static struct triple *mk_sub_expr(
5079         struct compile_state *state, struct triple *left, struct triple *right)
5080 {
5081         struct type *result_type;
5082         result_type = ptr_arithmetic_result(state, left, right);
5083         left  = read_expr(state, left);
5084         right = read_expr(state, right);
5085         if (is_pointer(left)) {
5086                 right = triple(state, 
5087                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5088                         &ulong_type, 
5089                         right, 
5090                         int_const(state, &ulong_type, 
5091                                 size_of(state, left->type->left)));
5092         }
5093         return triple(state, OP_SUB, result_type, left, right);
5094 }
5095
5096 static struct triple *mk_pre_inc_expr(
5097         struct compile_state *state, struct triple *def)
5098 {
5099         struct triple *val;
5100         lvalue(state, def);
5101         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5102         return triple(state, OP_VAL, def->type,
5103                 write_expr(state, def, val),
5104                 val);
5105 }
5106
5107 static struct triple *mk_pre_dec_expr(
5108         struct compile_state *state, struct triple *def)
5109 {
5110         struct triple *val;
5111         lvalue(state, def);
5112         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5113         return triple(state, OP_VAL, def->type,
5114                 write_expr(state, def, val),
5115                 val);
5116 }
5117
5118 static struct triple *mk_post_inc_expr(
5119         struct compile_state *state, struct triple *def)
5120 {
5121         struct triple *val;
5122         lvalue(state, def);
5123         val = read_expr(state, def);
5124         return triple(state, OP_VAL, def->type,
5125                 write_expr(state, def,
5126                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
5127                 , val);
5128 }
5129
5130 static struct triple *mk_post_dec_expr(
5131         struct compile_state *state, struct triple *def)
5132 {
5133         struct triple *val;
5134         lvalue(state, def);
5135         val = read_expr(state, def);
5136         return triple(state, OP_VAL, def->type, 
5137                 write_expr(state, def,
5138                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5139                 , val);
5140 }
5141
5142 static struct triple *mk_subscript_expr(
5143         struct compile_state *state, struct triple *left, struct triple *right)
5144 {
5145         left  = read_expr(state, left);
5146         right = read_expr(state, right);
5147         if (!is_pointer(left) && !is_pointer(right)) {
5148                 error(state, left, "subscripted value is not a pointer");
5149         }
5150         return mk_deref_expr(state, mk_add_expr(state, left, right));
5151 }
5152
5153 /*
5154  * Compile time evaluation
5155  * ===========================
5156  */
5157 static int is_const(struct triple *ins)
5158 {
5159         return IS_CONST_OP(ins->op);
5160 }
5161
5162 static int constants_equal(struct compile_state *state, 
5163         struct triple *left, struct triple *right)
5164 {
5165         int equal;
5166         if (!is_const(left) || !is_const(right)) {
5167                 equal = 0;
5168         }
5169         else if (left->op != right->op) {
5170                 equal = 0;
5171         }
5172         else if (!equiv_types(left->type, right->type)) {
5173                 equal = 0;
5174         }
5175         else {
5176                 equal = 0;
5177                 switch(left->op) {
5178                 case OP_INTCONST:
5179                         if (left->u.cval == right->u.cval) {
5180                                 equal = 1;
5181                         }
5182                         break;
5183                 case OP_BLOBCONST:
5184                 {
5185                         size_t lsize, rsize;
5186                         lsize = size_of(state, left->type);
5187                         rsize = size_of(state, right->type);
5188                         if (lsize != rsize) {
5189                                 break;
5190                         }
5191                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5192                                 equal = 1;
5193                         }
5194                         break;
5195                 }
5196                 case OP_ADDRCONST:
5197                         if ((MISC(left, 0) == MISC(right, 0)) &&
5198                                 (left->u.cval == right->u.cval)) {
5199                                 equal = 1;
5200                         }
5201                         break;
5202                 default:
5203                         internal_error(state, left, "uknown constant type");
5204                         break;
5205                 }
5206         }
5207         return equal;
5208 }
5209
5210 static int is_zero(struct triple *ins)
5211 {
5212         return is_const(ins) && (ins->u.cval == 0);
5213 }
5214
5215 static int is_one(struct triple *ins)
5216 {
5217         return is_const(ins) && (ins->u.cval == 1);
5218 }
5219
5220 static long_t bsr(ulong_t value)
5221 {
5222         int i;
5223         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5224                 ulong_t mask;
5225                 mask = 1;
5226                 mask <<= i;
5227                 if (value & mask) {
5228                         return i;
5229                 }
5230         }
5231         return -1;
5232 }
5233
5234 static long_t bsf(ulong_t value)
5235 {
5236         int i;
5237         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5238                 ulong_t mask;
5239                 mask = 1;
5240                 mask <<= 1;
5241                 if (value & mask) {
5242                         return i;
5243                 }
5244         }
5245         return -1;
5246 }
5247
5248 static long_t log2(ulong_t value)
5249 {
5250         return bsr(value);
5251 }
5252
5253 static long_t tlog2(struct triple *ins)
5254 {
5255         return log2(ins->u.cval);
5256 }
5257
5258 static int is_pow2(struct triple *ins)
5259 {
5260         ulong_t value, mask;
5261         long_t log;
5262         if (!is_const(ins)) {
5263                 return 0;
5264         }
5265         value = ins->u.cval;
5266         log = log2(value);
5267         if (log == -1) {
5268                 return 0;
5269         }
5270         mask = 1;
5271         mask <<= log;
5272         return  ((value & mask) == value);
5273 }
5274
5275 static ulong_t read_const(struct compile_state *state,
5276         struct triple *ins, struct triple **expr)
5277 {
5278         struct triple *rhs;
5279         rhs = *expr;
5280         switch(rhs->type->type &TYPE_MASK) {
5281         case TYPE_CHAR:   
5282         case TYPE_SHORT:
5283         case TYPE_INT:
5284         case TYPE_LONG:
5285         case TYPE_UCHAR:   
5286         case TYPE_USHORT:  
5287         case TYPE_UINT:
5288         case TYPE_ULONG:
5289         case TYPE_POINTER:
5290                 break;
5291         default:
5292                 internal_error(state, rhs, "bad type to read_const\n");
5293                 break;
5294         }
5295         return rhs->u.cval;
5296 }
5297
5298 static long_t read_sconst(struct triple *ins, struct triple **expr)
5299 {
5300         struct triple *rhs;
5301         rhs = *expr;
5302         return (long_t)(rhs->u.cval);
5303 }
5304
5305 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5306 {
5307         struct triple **expr;
5308         expr = triple_rhs(state, ins, 0);
5309         for(;expr;expr = triple_rhs(state, ins, expr)) {
5310                 if (*expr) {
5311                         unuse_triple(*expr, ins);
5312                         *expr = 0;
5313                 }
5314         }
5315 }
5316
5317 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5318 {
5319         struct triple **expr;
5320         expr = triple_lhs(state, ins, 0);
5321         for(;expr;expr = triple_lhs(state, ins, expr)) {
5322                 unuse_triple(*expr, ins);
5323                 *expr = 0;
5324         }
5325 }
5326
5327 static void check_lhs(struct compile_state *state, struct triple *ins)
5328 {
5329         struct triple **expr;
5330         expr = triple_lhs(state, ins, 0);
5331         for(;expr;expr = triple_lhs(state, ins, expr)) {
5332                 internal_error(state, ins, "unexpected lhs");
5333         }
5334         
5335 }
5336 static void check_targ(struct compile_state *state, struct triple *ins)
5337 {
5338         struct triple **expr;
5339         expr = triple_targ(state, ins, 0);
5340         for(;expr;expr = triple_targ(state, ins, expr)) {
5341                 internal_error(state, ins, "unexpected targ");
5342         }
5343 }
5344
5345 static void wipe_ins(struct compile_state *state, struct triple *ins)
5346 {
5347         /* Becareful which instructions you replace the wiped
5348          * instruction with, as there are not enough slots
5349          * in all instructions to hold all others.
5350          */
5351         check_targ(state, ins);
5352         unuse_rhs(state, ins);
5353         unuse_lhs(state, ins);
5354 }
5355
5356 static void mkcopy(struct compile_state *state, 
5357         struct triple *ins, struct triple *rhs)
5358 {
5359         wipe_ins(state, ins);
5360         ins->op = OP_COPY;
5361         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5362         RHS(ins, 0) = rhs;
5363         use_triple(RHS(ins, 0), ins);
5364 }
5365
5366 static void mkconst(struct compile_state *state, 
5367         struct triple *ins, ulong_t value)
5368 {
5369         if (!is_integral(ins) && !is_pointer(ins)) {
5370                 internal_error(state, ins, "unknown type to make constant\n");
5371         }
5372         wipe_ins(state, ins);
5373         ins->op = OP_INTCONST;
5374         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5375         ins->u.cval = value;
5376 }
5377
5378 static void mkaddr_const(struct compile_state *state,
5379         struct triple *ins, struct triple *sdecl, ulong_t value)
5380 {
5381         wipe_ins(state, ins);
5382         ins->op = OP_ADDRCONST;
5383         ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5384         MISC(ins, 0) = sdecl;
5385         ins->u.cval = value;
5386         use_triple(sdecl, ins);
5387 }
5388
5389 /* Transform multicomponent variables into simple register variables */
5390 static void flatten_structures(struct compile_state *state)
5391 {
5392         struct triple *ins, *first;
5393         first = RHS(state->main_function, 0);
5394         ins = first;
5395         /* Pass one expand structure values into valvecs.
5396          */
5397         ins = first;
5398         do {
5399                 struct triple *next;
5400                 next = ins->next;
5401                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5402                         if (ins->op == OP_VAL_VEC) {
5403                                 /* Do nothing */
5404                         }
5405                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5406                                 struct triple *def, **vector;
5407                                 struct type *tptr;
5408                                 int op;
5409                                 ulong_t i;
5410
5411                                 op = ins->op;
5412                                 def = RHS(ins, 0);
5413                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5414                                         ins->filename, ins->line, ins->col);
5415
5416                                 vector = &RHS(next, 0);
5417                                 tptr = next->type->left;
5418                                 for(i = 0; i < next->type->elements; i++) {
5419                                         struct triple *sfield;
5420                                         struct type *mtype;
5421                                         mtype = tptr;
5422                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5423                                                 mtype = mtype->left;
5424                                         }
5425                                         sfield = deref_field(state, def, mtype->field_ident);
5426                                         
5427                                         vector[i] = triple(
5428                                                 state, op, mtype, sfield, 0);
5429                                         vector[i]->filename = next->filename;
5430                                         vector[i]->line = next->line;
5431                                         vector[i]->col = next->col;
5432                                         tptr = tptr->right;
5433                                 }
5434                                 propogate_use(state, ins, next);
5435                                 flatten(state, ins, next);
5436                                 free_triple(state, ins);
5437                         }
5438                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5439                                 struct triple *src, *dst, **vector;
5440                                 struct type *tptr;
5441                                 int op;
5442                                 ulong_t i;
5443
5444                                 op = ins->op;
5445                                 src = RHS(ins, 0);
5446                                 dst = LHS(ins, 0);
5447                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5448                                         ins->filename, ins->line, ins->col);
5449                                 
5450                                 vector = &RHS(next, 0);
5451                                 tptr = next->type->left;
5452                                 for(i = 0; i < ins->type->elements; i++) {
5453                                         struct triple *dfield, *sfield;
5454                                         struct type *mtype;
5455                                         mtype = tptr;
5456                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5457                                                 mtype = mtype->left;
5458                                         }
5459                                         sfield = deref_field(state, src, mtype->field_ident);
5460                                         dfield = deref_field(state, dst, mtype->field_ident);
5461                                         vector[i] = triple(
5462                                                 state, op, mtype, dfield, sfield);
5463                                         vector[i]->filename = next->filename;
5464                                         vector[i]->line = next->line;
5465                                         vector[i]->col = next->col;
5466                                         tptr = tptr->right;
5467                                 }
5468                                 propogate_use(state, ins, next);
5469                                 flatten(state, ins, next);
5470                                 free_triple(state, ins);
5471                         }
5472                 }
5473                 ins = next;
5474         } while(ins != first);
5475         /* Pass two flatten the valvecs.
5476          */
5477         ins = first;
5478         do {
5479                 struct triple *next;
5480                 next = ins->next;
5481                 if (ins->op == OP_VAL_VEC) {
5482                         release_triple(state, ins);
5483                 } 
5484                 ins = next;
5485         } while(ins != first);
5486         /* Pass three verify the state and set ->id to 0.
5487          */
5488         ins = first;
5489         do {
5490                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5491                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5492                         internal_error(state, 0, "STRUCT_TYPE remains?");
5493                 }
5494                 if (ins->op == OP_DOT) {
5495                         internal_error(state, 0, "OP_DOT remains?");
5496                 }
5497                 if (ins->op == OP_VAL_VEC) {
5498                         internal_error(state, 0, "OP_VAL_VEC remains?");
5499                 }
5500                 ins = ins->next;
5501         } while(ins != first);
5502 }
5503
5504 /* For those operations that cannot be simplified */
5505 static void simplify_noop(struct compile_state *state, struct triple *ins)
5506 {
5507         return;
5508 }
5509
5510 static void simplify_smul(struct compile_state *state, struct triple *ins)
5511 {
5512         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5513                 struct triple *tmp;
5514                 tmp = RHS(ins, 0);
5515                 RHS(ins, 0) = RHS(ins, 1);
5516                 RHS(ins, 1) = tmp;
5517         }
5518         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5519                 long_t left, right;
5520                 left  = read_sconst(ins, &RHS(ins, 0));
5521                 right = read_sconst(ins, &RHS(ins, 1));
5522                 mkconst(state, ins, left * right);
5523         }
5524         else if (is_zero(RHS(ins, 1))) {
5525                 mkconst(state, ins, 0);
5526         }
5527         else if (is_one(RHS(ins, 1))) {
5528                 mkcopy(state, ins, RHS(ins, 0));
5529         }
5530         else if (is_pow2(RHS(ins, 1))) {
5531                 struct triple *val;
5532                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5533                 ins->op = OP_SL;
5534                 insert_triple(state, ins, val);
5535                 unuse_triple(RHS(ins, 1), ins);
5536                 use_triple(val, ins);
5537                 RHS(ins, 1) = val;
5538         }
5539 }
5540
5541 static void simplify_umul(struct compile_state *state, struct triple *ins)
5542 {
5543         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5544                 struct triple *tmp;
5545                 tmp = RHS(ins, 0);
5546                 RHS(ins, 0) = RHS(ins, 1);
5547                 RHS(ins, 1) = tmp;
5548         }
5549         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5550                 ulong_t left, right;
5551                 left  = read_const(state, ins, &RHS(ins, 0));
5552                 right = read_const(state, ins, &RHS(ins, 1));
5553                 mkconst(state, ins, left * right);
5554         }
5555         else if (is_zero(RHS(ins, 1))) {
5556                 mkconst(state, ins, 0);
5557         }
5558         else if (is_one(RHS(ins, 1))) {
5559                 mkcopy(state, ins, RHS(ins, 0));
5560         }
5561         else if (is_pow2(RHS(ins, 1))) {
5562                 struct triple *val;
5563                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5564                 ins->op = OP_SL;
5565                 insert_triple(state, ins, val);
5566                 unuse_triple(RHS(ins, 1), ins);
5567                 use_triple(val, ins);
5568                 RHS(ins, 1) = val;
5569         }
5570 }
5571
5572 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5573 {
5574         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5575                 long_t left, right;
5576                 left  = read_sconst(ins, &RHS(ins, 0));
5577                 right = read_sconst(ins, &RHS(ins, 1));
5578                 mkconst(state, ins, left / right);
5579         }
5580         else if (is_zero(RHS(ins, 0))) {
5581                 mkconst(state, ins, 0);
5582         }
5583         else if (is_zero(RHS(ins, 1))) {
5584                 error(state, ins, "division by zero");
5585         }
5586         else if (is_one(RHS(ins, 1))) {
5587                 mkcopy(state, ins, RHS(ins, 0));
5588         }
5589         else if (is_pow2(RHS(ins, 1))) {
5590                 struct triple *val;
5591                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5592                 ins->op = OP_SSR;
5593                 insert_triple(state, ins, val);
5594                 unuse_triple(RHS(ins, 1), ins);
5595                 use_triple(val, ins);
5596                 RHS(ins, 1) = val;
5597         }
5598 }
5599
5600 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5601 {
5602         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5603                 ulong_t left, right;
5604                 left  = read_const(state, ins, &RHS(ins, 0));
5605                 right = read_const(state, ins, &RHS(ins, 1));
5606                 mkconst(state, ins, left / right);
5607         }
5608         else if (is_zero(RHS(ins, 0))) {
5609                 mkconst(state, ins, 0);
5610         }
5611         else if (is_zero(RHS(ins, 1))) {
5612                 error(state, ins, "division by zero");
5613         }
5614         else if (is_one(RHS(ins, 1))) {
5615                 mkcopy(state, ins, RHS(ins, 0));
5616         }
5617         else if (is_pow2(RHS(ins, 1))) {
5618                 struct triple *val;
5619                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5620                 ins->op = OP_USR;
5621                 insert_triple(state, ins, val);
5622                 unuse_triple(RHS(ins, 1), ins);
5623                 use_triple(val, ins);
5624                 RHS(ins, 1) = val;
5625         }
5626 }
5627
5628 static void simplify_smod(struct compile_state *state, struct triple *ins)
5629 {
5630         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5631                 long_t left, right;
5632                 left  = read_const(state, ins, &RHS(ins, 0));
5633                 right = read_const(state, ins, &RHS(ins, 1));
5634                 mkconst(state, ins, left % right);
5635         }
5636         else if (is_zero(RHS(ins, 0))) {
5637                 mkconst(state, ins, 0);
5638         }
5639         else if (is_zero(RHS(ins, 1))) {
5640                 error(state, ins, "division by zero");
5641         }
5642         else if (is_one(RHS(ins, 1))) {
5643                 mkconst(state, ins, 0);
5644         }
5645         else if (is_pow2(RHS(ins, 1))) {
5646                 struct triple *val;
5647                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5648                 ins->op = OP_AND;
5649                 insert_triple(state, ins, val);
5650                 unuse_triple(RHS(ins, 1), ins);
5651                 use_triple(val, ins);
5652                 RHS(ins, 1) = val;
5653         }
5654 }
5655 static void simplify_umod(struct compile_state *state, struct triple *ins)
5656 {
5657         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5658                 ulong_t left, right;
5659                 left  = read_const(state, ins, &RHS(ins, 0));
5660                 right = read_const(state, ins, &RHS(ins, 1));
5661                 mkconst(state, ins, left % right);
5662         }
5663         else if (is_zero(RHS(ins, 0))) {
5664                 mkconst(state, ins, 0);
5665         }
5666         else if (is_zero(RHS(ins, 1))) {
5667                 error(state, ins, "division by zero");
5668         }
5669         else if (is_one(RHS(ins, 1))) {
5670                 mkconst(state, ins, 0);
5671         }
5672         else if (is_pow2(RHS(ins, 1))) {
5673                 struct triple *val;
5674                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5675                 ins->op = OP_AND;
5676                 insert_triple(state, ins, val);
5677                 unuse_triple(RHS(ins, 1), ins);
5678                 use_triple(val, ins);
5679                 RHS(ins, 1) = val;
5680         }
5681 }
5682
5683 static void simplify_add(struct compile_state *state, struct triple *ins)
5684 {
5685         /* start with the pointer on the left */
5686         if (is_pointer(RHS(ins, 1))) {
5687                 struct triple *tmp;
5688                 tmp = RHS(ins, 0);
5689                 RHS(ins, 0) = RHS(ins, 1);
5690                 RHS(ins, 1) = tmp;
5691         }
5692         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5693                 if (!is_pointer(RHS(ins, 0))) {
5694                         ulong_t left, right;
5695                         left  = read_const(state, ins, &RHS(ins, 0));
5696                         right = read_const(state, ins, &RHS(ins, 1));
5697                         mkconst(state, ins, left + right);
5698                 }
5699                 else /* op == OP_ADDRCONST */ {
5700                         struct triple *sdecl;
5701                         ulong_t left, right;
5702                         sdecl = MISC(RHS(ins, 0), 0);
5703                         left  = RHS(ins, 0)->u.cval;
5704                         right = RHS(ins, 1)->u.cval;
5705                         mkaddr_const(state, ins, sdecl, left + right);
5706                 }
5707         }
5708         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5709                 struct triple *tmp;
5710                 tmp = RHS(ins, 1);
5711                 RHS(ins, 1) = RHS(ins, 0);
5712                 RHS(ins, 0) = tmp;
5713         }
5714 }
5715
5716 static void simplify_sub(struct compile_state *state, struct triple *ins)
5717 {
5718         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5719                 if (!is_pointer(RHS(ins, 0))) {
5720                         ulong_t left, right;
5721                         left  = read_const(state, ins, &RHS(ins, 0));
5722                         right = read_const(state, ins, &RHS(ins, 1));
5723                         mkconst(state, ins, left - right);
5724                 }
5725                 else /* op == OP_ADDRCONST */ {
5726                         struct triple *sdecl;
5727                         ulong_t left, right;
5728                         sdecl = MISC(RHS(ins, 0), 0);
5729                         left  = RHS(ins, 0)->u.cval;
5730                         right = RHS(ins, 1)->u.cval;
5731                         mkaddr_const(state, ins, sdecl, left - right);
5732                 }
5733         }
5734 }
5735
5736 static void simplify_sl(struct compile_state *state, struct triple *ins)
5737 {
5738         if (is_const(RHS(ins, 1))) {
5739                 ulong_t right;
5740                 right = read_const(state, ins, &RHS(ins, 1));
5741                 if (right >= (size_of(state, ins->type)*8)) {
5742                         warning(state, ins, "left shift count >= width of type");
5743                 }
5744         }
5745         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5746                 ulong_t left, right;
5747                 left  = read_const(state, ins, &RHS(ins, 0));
5748                 right = read_const(state, ins, &RHS(ins, 1));
5749                 mkconst(state, ins,  left << right);
5750         }
5751 }
5752
5753 static void simplify_usr(struct compile_state *state, struct triple *ins)
5754 {
5755         if (is_const(RHS(ins, 1))) {
5756                 ulong_t right;
5757                 right = read_const(state, ins, &RHS(ins, 1));
5758                 if (right >= (size_of(state, ins->type)*8)) {
5759                         warning(state, ins, "right shift count >= width of type");
5760                 }
5761         }
5762         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5763                 ulong_t left, right;
5764                 left  = read_const(state, ins, &RHS(ins, 0));
5765                 right = read_const(state, ins, &RHS(ins, 1));
5766                 mkconst(state, ins, left >> right);
5767         }
5768 }
5769
5770 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5771 {
5772         if (is_const(RHS(ins, 1))) {
5773                 ulong_t right;
5774                 right = read_const(state, ins, &RHS(ins, 1));
5775                 if (right >= (size_of(state, ins->type)*8)) {
5776                         warning(state, ins, "right shift count >= width of type");
5777                 }
5778         }
5779         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5780                 long_t left, right;
5781                 left  = read_sconst(ins, &RHS(ins, 0));
5782                 right = read_sconst(ins, &RHS(ins, 1));
5783                 mkconst(state, ins, left >> right);
5784         }
5785 }
5786
5787 static void simplify_and(struct compile_state *state, struct triple *ins)
5788 {
5789         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5790                 ulong_t left, right;
5791                 left  = read_const(state, ins, &RHS(ins, 0));
5792                 right = read_const(state, ins, &RHS(ins, 1));
5793                 mkconst(state, ins, left & right);
5794         }
5795 }
5796
5797 static void simplify_or(struct compile_state *state, struct triple *ins)
5798 {
5799         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5800                 ulong_t left, right;
5801                 left  = read_const(state, ins, &RHS(ins, 0));
5802                 right = read_const(state, ins, &RHS(ins, 1));
5803                 mkconst(state, ins, left | right);
5804         }
5805 }
5806
5807 static void simplify_xor(struct compile_state *state, struct triple *ins)
5808 {
5809         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5810                 ulong_t left, right;
5811                 left  = read_const(state, ins, &RHS(ins, 0));
5812                 right = read_const(state, ins, &RHS(ins, 1));
5813                 mkconst(state, ins, left ^ right);
5814         }
5815 }
5816
5817 static void simplify_pos(struct compile_state *state, struct triple *ins)
5818 {
5819         if (is_const(RHS(ins, 0))) {
5820                 mkconst(state, ins, RHS(ins, 0)->u.cval);
5821         }
5822         else {
5823                 mkcopy(state, ins, RHS(ins, 0));
5824         }
5825 }
5826
5827 static void simplify_neg(struct compile_state *state, struct triple *ins)
5828 {
5829         if (is_const(RHS(ins, 0))) {
5830                 ulong_t left;
5831                 left = read_const(state, ins, &RHS(ins, 0));
5832                 mkconst(state, ins, -left);
5833         }
5834         else if (RHS(ins, 0)->op == OP_NEG) {
5835                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5836         }
5837 }
5838
5839 static void simplify_invert(struct compile_state *state, struct triple *ins)
5840 {
5841         if (is_const(RHS(ins, 0))) {
5842                 ulong_t left;
5843                 left = read_const(state, ins, &RHS(ins, 0));
5844                 mkconst(state, ins, ~left);
5845         }
5846 }
5847
5848 static void simplify_eq(struct compile_state *state, struct triple *ins)
5849 {
5850         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5851                 ulong_t left, right;
5852                 left  = read_const(state, ins, &RHS(ins, 0));
5853                 right = read_const(state, ins, &RHS(ins, 1));
5854                 mkconst(state, ins, left == right);
5855         }
5856         else if (RHS(ins, 0) == RHS(ins, 1)) {
5857                 mkconst(state, ins, 1);
5858         }
5859 }
5860
5861 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5862 {
5863         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5864                 ulong_t left, right;
5865                 left  = read_const(state, ins, &RHS(ins, 0));
5866                 right = read_const(state, ins, &RHS(ins, 1));
5867                 mkconst(state, ins, left != right);
5868         }
5869         else if (RHS(ins, 0) == RHS(ins, 1)) {
5870                 mkconst(state, ins, 0);
5871         }
5872 }
5873
5874 static void simplify_sless(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_sconst(ins, &RHS(ins, 0));
5879                 right = read_sconst(ins, &RHS(ins, 1));
5880                 mkconst(state, ins, left < right);
5881         }
5882         else if (RHS(ins, 0) == RHS(ins, 1)) {
5883                 mkconst(state, ins, 0);
5884         }
5885 }
5886
5887 static void simplify_uless(struct compile_state *state, struct triple *ins)
5888 {
5889         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5890                 ulong_t left, right;
5891                 left  = read_const(state, ins, &RHS(ins, 0));
5892                 right = read_const(state, ins, &RHS(ins, 1));
5893                 mkconst(state, ins, left < right);
5894         }
5895         else if (is_zero(RHS(ins, 0))) {
5896                 mkconst(state, ins, 1);
5897         }
5898         else if (RHS(ins, 0) == RHS(ins, 1)) {
5899                 mkconst(state, ins, 0);
5900         }
5901 }
5902
5903 static void simplify_smore(struct compile_state *state, struct triple *ins)
5904 {
5905         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5906                 long_t left, right;
5907                 left  = read_sconst(ins, &RHS(ins, 0));
5908                 right = read_sconst(ins, &RHS(ins, 1));
5909                 mkconst(state, ins, left > right);
5910         }
5911         else if (RHS(ins, 0) == RHS(ins, 1)) {
5912                 mkconst(state, ins, 0);
5913         }
5914 }
5915
5916 static void simplify_umore(struct compile_state *state, struct triple *ins)
5917 {
5918         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5919                 ulong_t left, right;
5920                 left  = read_const(state, ins, &RHS(ins, 0));
5921                 right = read_const(state, ins, &RHS(ins, 1));
5922                 mkconst(state, ins, left > right);
5923         }
5924         else if (is_zero(RHS(ins, 1))) {
5925                 mkconst(state, ins, 1);
5926         }
5927         else if (RHS(ins, 0) == RHS(ins, 1)) {
5928                 mkconst(state, ins, 0);
5929         }
5930 }
5931
5932
5933 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5934 {
5935         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5936                 long_t left, right;
5937                 left  = read_sconst(ins, &RHS(ins, 0));
5938                 right = read_sconst(ins, &RHS(ins, 1));
5939                 mkconst(state, ins, left <= right);
5940         }
5941         else if (RHS(ins, 0) == RHS(ins, 1)) {
5942                 mkconst(state, ins, 1);
5943         }
5944 }
5945
5946 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5947 {
5948         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5949                 ulong_t left, right;
5950                 left  = read_const(state, ins, &RHS(ins, 0));
5951                 right = read_const(state, ins, &RHS(ins, 1));
5952                 mkconst(state, ins, left <= right);
5953         }
5954         else if (is_zero(RHS(ins, 0))) {
5955                 mkconst(state, ins, 1);
5956         }
5957         else if (RHS(ins, 0) == RHS(ins, 1)) {
5958                 mkconst(state, ins, 1);
5959         }
5960 }
5961
5962 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5963 {
5964         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5965                 long_t left, right;
5966                 left  = read_sconst(ins, &RHS(ins, 0));
5967                 right = read_sconst(ins, &RHS(ins, 1));
5968                 mkconst(state, ins, left >= right);
5969         }
5970         else if (RHS(ins, 0) == RHS(ins, 1)) {
5971                 mkconst(state, ins, 1);
5972         }
5973 }
5974
5975 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5976 {
5977         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5978                 ulong_t left, right;
5979                 left  = read_const(state, ins, &RHS(ins, 0));
5980                 right = read_const(state, ins, &RHS(ins, 1));
5981                 mkconst(state, ins, left >= right);
5982         }
5983         else if (is_zero(RHS(ins, 1))) {
5984                 mkconst(state, ins, 1);
5985         }
5986         else if (RHS(ins, 0) == RHS(ins, 1)) {
5987                 mkconst(state, ins, 1);
5988         }
5989 }
5990
5991 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5992 {
5993         if (is_const(RHS(ins, 0))) {
5994                 ulong_t left;
5995                 left = read_const(state, ins, &RHS(ins, 0));
5996                 mkconst(state, ins, left == 0);
5997         }
5998         /* Otherwise if I am the only user... */
5999         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6000                 int need_copy = 1;
6001                 /* Invert a boolean operation */
6002                 switch(RHS(ins, 0)->op) {
6003                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
6004                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
6005                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
6006                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
6007                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
6008                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
6009                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
6010                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
6011                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
6012                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
6013                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
6014                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
6015                 default:
6016                         need_copy = 0;
6017                         break;
6018                 }
6019                 if (need_copy) {
6020                         mkcopy(state, ins, RHS(ins, 0));
6021                 }
6022         }
6023 }
6024
6025 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6026 {
6027         if (is_const(RHS(ins, 0))) {
6028                 ulong_t left;
6029                 left = read_const(state, ins, &RHS(ins, 0));
6030                 mkconst(state, ins, left != 0);
6031         }
6032         else switch(RHS(ins, 0)->op) {
6033         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
6034         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
6035         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6036                 mkcopy(state, ins, RHS(ins, 0));
6037         }
6038
6039 }
6040
6041 static void simplify_copy(struct compile_state *state, struct triple *ins)
6042 {
6043         if (is_const(RHS(ins, 0))) {
6044                 switch(RHS(ins, 0)->op) {
6045                 case OP_INTCONST:
6046                 {
6047                         ulong_t left;
6048                         left = read_const(state, ins, &RHS(ins, 0));
6049                         mkconst(state, ins, left);
6050                         break;
6051                 }
6052                 case OP_ADDRCONST:
6053                 {
6054                         struct triple *sdecl;
6055                         ulong_t offset;
6056                         sdecl  = MISC(RHS(ins, 0), 0);
6057                         offset = RHS(ins, 0)->u.cval;
6058                         mkaddr_const(state, ins, sdecl, offset);
6059                         break;
6060                 }
6061                 default:
6062                         internal_error(state, ins, "uknown constant");
6063                         break;
6064                 }
6065         }
6066 }
6067
6068 static void simplify_branch(struct compile_state *state, struct triple *ins)
6069 {
6070         struct block *block;
6071         if (ins->op != OP_BRANCH) {
6072                 internal_error(state, ins, "not branch");
6073         }
6074         if (ins->use != 0) {
6075                 internal_error(state, ins, "branch use");
6076         }
6077 #warning "FIXME implement simplify branch."
6078         /* The challenge here with simplify branch is that I need to 
6079          * make modifications to the control flow graph as well
6080          * as to the branch instruction itself.
6081          */
6082         block = ins->u.block;
6083         
6084         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6085                 struct triple *targ;
6086                 ulong_t value;
6087                 value = read_const(state, ins, &RHS(ins, 0));
6088                 unuse_triple(RHS(ins, 0), ins);
6089                 targ = TARG(ins, 0);
6090                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6091                 if (value) {
6092                         unuse_triple(ins->next, ins);
6093                         TARG(ins, 0) = targ;
6094                 }
6095                 else {
6096                         unuse_triple(targ, ins);
6097                         TARG(ins, 0) = ins->next;
6098                 }
6099 #warning "FIXME handle the case of making a branch unconditional"
6100         }
6101         if (TARG(ins, 0) == ins->next) {
6102                 unuse_triple(ins->next, ins);
6103                 if (TRIPLE_RHS(ins->sizes)) {
6104                         unuse_triple(RHS(ins, 0), ins);
6105                         unuse_triple(ins->next, ins);
6106                 }
6107                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6108                 ins->op = OP_NOOP;
6109                 if (ins->use) {
6110                         internal_error(state, ins, "noop use != 0");
6111                 }
6112 #warning "FIXME handle the case of killing a branch"
6113         }
6114 }
6115
6116 static void simplify_phi(struct compile_state *state, struct triple *ins)
6117 {
6118         struct triple **expr;
6119         ulong_t value;
6120         expr = triple_rhs(state, ins, 0);
6121         if (!*expr || !is_const(*expr)) {
6122                 return;
6123         }
6124         value = read_const(state, ins, expr);
6125         for(;expr;expr = triple_rhs(state, ins, expr)) {
6126                 if (!*expr || !is_const(*expr)) {
6127                         return;
6128                 }
6129                 if (value != read_const(state, ins, expr)) {
6130                         return;
6131                 }
6132         }
6133         mkconst(state, ins, value);
6134 }
6135
6136
6137 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6138 {
6139         if (is_const(RHS(ins, 0))) {
6140                 ulong_t left;
6141                 left = read_const(state, ins, &RHS(ins, 0));
6142                 mkconst(state, ins, bsf(left));
6143         }
6144 }
6145
6146 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6147 {
6148         if (is_const(RHS(ins, 0))) {
6149                 ulong_t left;
6150                 left = read_const(state, ins, &RHS(ins, 0));
6151                 mkconst(state, ins, bsr(left));
6152         }
6153 }
6154
6155
6156 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6157 static const simplify_t table_simplify[] = {
6158 #if 0
6159 #define simplify_smul     simplify_noop
6160 #define simplify_umul     simplify_noop
6161 #define simplify_sdiv     simplify_noop
6162 #define simplify_udiv     simplify_noop
6163 #define simplify_smod     simplify_noop
6164 #define simplify_umod     simplify_noop
6165 #endif
6166 #if 0
6167 #define simplify_add      simplify_noop
6168 #define simplify_sub      simplify_noop
6169 #endif
6170 #if 0
6171 #define simplify_sl       simplify_noop
6172 #define simplify_usr      simplify_noop
6173 #define simplify_ssr      simplify_noop
6174 #endif
6175 #if 0
6176 #define simplify_and      simplify_noop
6177 #define simplify_xor      simplify_noop
6178 #define simplify_or       simplify_noop
6179 #endif
6180 #if 0
6181 #define simplify_pos      simplify_noop
6182 #define simplify_neg      simplify_noop
6183 #define simplify_invert   simplify_noop
6184 #endif
6185
6186 #if 0
6187 #define simplify_eq       simplify_noop
6188 #define simplify_noteq    simplify_noop
6189 #endif
6190 #if 0
6191 #define simplify_sless    simplify_noop
6192 #define simplify_uless    simplify_noop
6193 #define simplify_smore    simplify_noop
6194 #define simplify_umore    simplify_noop
6195 #endif
6196 #if 0
6197 #define simplify_slesseq  simplify_noop
6198 #define simplify_ulesseq  simplify_noop
6199 #define simplify_smoreeq  simplify_noop
6200 #define simplify_umoreeq  simplify_noop
6201 #endif
6202 #if 0
6203 #define simplify_lfalse   simplify_noop
6204 #endif
6205 #if 0
6206 #define simplify_ltrue    simplify_noop
6207 #endif
6208
6209 #if 0
6210 #define simplify_copy     simplify_noop
6211 #endif
6212
6213 #if 0
6214 #define simplify_branch   simplify_noop
6215 #endif
6216
6217 #if 0
6218 #define simplify_phi      simplify_noop
6219 #endif
6220
6221 #if 0
6222 #define simplify_bsf      simplify_noop
6223 #define simplify_bsr      simplify_noop
6224 #endif
6225
6226 [OP_SMUL       ] = simplify_smul,
6227 [OP_UMUL       ] = simplify_umul,
6228 [OP_SDIV       ] = simplify_sdiv,
6229 [OP_UDIV       ] = simplify_udiv,
6230 [OP_SMOD       ] = simplify_smod,
6231 [OP_UMOD       ] = simplify_umod,
6232 [OP_ADD        ] = simplify_add,
6233 [OP_SUB        ] = simplify_sub,
6234 [OP_SL         ] = simplify_sl,
6235 [OP_USR        ] = simplify_usr,
6236 [OP_SSR        ] = simplify_ssr,
6237 [OP_AND        ] = simplify_and,
6238 [OP_XOR        ] = simplify_xor,
6239 [OP_OR         ] = simplify_or,
6240 [OP_POS        ] = simplify_pos,
6241 [OP_NEG        ] = simplify_neg,
6242 [OP_INVERT     ] = simplify_invert,
6243
6244 [OP_EQ         ] = simplify_eq,
6245 [OP_NOTEQ      ] = simplify_noteq,
6246 [OP_SLESS      ] = simplify_sless,
6247 [OP_ULESS      ] = simplify_uless,
6248 [OP_SMORE      ] = simplify_smore,
6249 [OP_UMORE      ] = simplify_umore,
6250 [OP_SLESSEQ    ] = simplify_slesseq,
6251 [OP_ULESSEQ    ] = simplify_ulesseq,
6252 [OP_SMOREEQ    ] = simplify_smoreeq,
6253 [OP_UMOREEQ    ] = simplify_umoreeq,
6254 [OP_LFALSE     ] = simplify_lfalse,
6255 [OP_LTRUE      ] = simplify_ltrue,
6256
6257 [OP_LOAD       ] = simplify_noop,
6258 [OP_STORE      ] = simplify_noop,
6259
6260 [OP_NOOP       ] = simplify_noop,
6261
6262 [OP_INTCONST   ] = simplify_noop,
6263 [OP_BLOBCONST  ] = simplify_noop,
6264 [OP_ADDRCONST  ] = simplify_noop,
6265
6266 [OP_WRITE      ] = simplify_noop,
6267 [OP_READ       ] = simplify_noop,
6268 [OP_COPY       ] = simplify_copy,
6269 [OP_PIECE      ] = simplify_noop,
6270 [OP_ASM        ] = simplify_noop,
6271
6272 [OP_DOT        ] = simplify_noop,
6273 [OP_VAL_VEC    ] = simplify_noop,
6274
6275 [OP_LIST       ] = simplify_noop,
6276 [OP_BRANCH     ] = simplify_branch,
6277 [OP_LABEL      ] = simplify_noop,
6278 [OP_ADECL      ] = simplify_noop,
6279 [OP_SDECL      ] = simplify_noop,
6280 [OP_PHI        ] = simplify_phi,
6281
6282 [OP_INB        ] = simplify_noop,
6283 [OP_INW        ] = simplify_noop,
6284 [OP_INL        ] = simplify_noop,
6285 [OP_OUTB       ] = simplify_noop,
6286 [OP_OUTW       ] = simplify_noop,
6287 [OP_OUTL       ] = simplify_noop,
6288 [OP_BSF        ] = simplify_bsf,
6289 [OP_BSR        ] = simplify_bsr,
6290 [OP_RDMSR      ] = simplify_noop,
6291 [OP_WRMSR      ] = simplify_noop,                    
6292 [OP_HLT        ] = simplify_noop,
6293 };
6294
6295 static void simplify(struct compile_state *state, struct triple *ins)
6296 {
6297         int op;
6298         simplify_t do_simplify;
6299         do {
6300                 op = ins->op;
6301                 do_simplify = 0;
6302                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6303                         do_simplify = 0;
6304                 }
6305                 else {
6306                         do_simplify = table_simplify[op];
6307                 }
6308                 if (!do_simplify) {
6309                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6310                                 op, tops(op));
6311                         return;
6312                 }
6313                 do_simplify(state, ins);
6314         } while(ins->op != op);
6315 }
6316
6317 static void simplify_all(struct compile_state *state)
6318 {
6319         struct triple *ins, *first;
6320         first = RHS(state->main_function, 0);
6321         ins = first;
6322         do {
6323                 simplify(state, ins);
6324                 ins = ins->next;
6325         } while(ins != first);
6326 }
6327
6328 /*
6329  * Builtins....
6330  * ============================
6331  */
6332
6333 static void register_builtin_function(struct compile_state *state,
6334         const char *name, int op, struct type *rtype, ...)
6335 {
6336         struct type *ftype, *atype, *param, **next;
6337         struct triple *def, *arg, *result, *work, *last, *first;
6338         struct hash_entry *ident;
6339         struct file_state file;
6340         int parameters;
6341         int name_len;
6342         va_list args;
6343         int i;
6344
6345         /* Dummy file state to get debug handling right */
6346         memset(&file, 0, sizeof(file));
6347         file.basename = name;
6348         file.line = 1;
6349         file.prev = state->file;
6350         state->file = &file;
6351
6352         /* Find the Parameter count */
6353         valid_op(state, op);
6354         parameters = table_ops[op].rhs;
6355         if (parameters < 0 ) {
6356                 internal_error(state, 0, "Invalid builtin parameter count");
6357         }
6358
6359         /* Find the function type */
6360         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6361         next = &ftype->right;
6362         va_start(args, rtype);
6363         for(i = 0; i < parameters; i++) {
6364                 atype = va_arg(args, struct type *);
6365                 if (!*next) {
6366                         *next = atype;
6367                 } else {
6368                         *next = new_type(TYPE_PRODUCT, *next, atype);
6369                         next = &((*next)->right);
6370                 }
6371         }
6372         if (!*next) {
6373                 *next = &void_type;
6374         }
6375         va_end(args);
6376
6377         /* Generate the needed triples */
6378         def = triple(state, OP_LIST, ftype, 0, 0);
6379         first = label(state);
6380         RHS(def, 0) = first;
6381
6382         /* Now string them together */
6383         param = ftype->right;
6384         for(i = 0; i < parameters; i++) {
6385                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6386                         atype = param->left;
6387                 } else {
6388                         atype = param;
6389                 }
6390                 arg = flatten(state, first, variable(state, atype));
6391                 param = param->right;
6392         }
6393         result = 0;
6394         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6395                 result = flatten(state, first, variable(state, rtype));
6396         }
6397         MISC(def, 0) = result;
6398         work = new_triple(state, op, rtype, -1, parameters);
6399         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6400                 RHS(work, i) = read_expr(state, arg);
6401         }
6402         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6403                 struct triple *val;
6404                 /* Populate the LHS with the target registers */
6405                 work = flatten(state, first, work);
6406                 work->type = &void_type;
6407                 param = rtype->left;
6408                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6409                         internal_error(state, 0, "Invalid result type");
6410                 }
6411                 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6412                 for(i = 0; i < rtype->elements; i++) {
6413                         struct triple *piece;
6414                         atype = param;
6415                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6416                                 atype = param->left;
6417                         }
6418                         if (!TYPE_ARITHMETIC(atype->type) &&
6419                                 !TYPE_PTR(atype->type)) {
6420                                 internal_error(state, 0, "Invalid lhs type");
6421                         }
6422                         piece = triple(state, OP_PIECE, atype, work, 0);
6423                         piece->u.cval = i;
6424                         LHS(work, i) = piece;
6425                         RHS(val, i) = piece;
6426                 }
6427                 work = val;
6428         }
6429         if (result) {
6430                 work = write_expr(state, result, work);
6431         }
6432         work = flatten(state, first, work);
6433         last = flatten(state, first, label(state));
6434         name_len = strlen(name);
6435         ident = lookup(state, name, name_len);
6436         symbol(state, ident, &ident->sym_ident, def, ftype);
6437         
6438         state->file = file.prev;
6439 #if 0
6440         fprintf(stdout, "\n");
6441         loc(stdout, state, 0);
6442         fprintf(stdout, "\n__________ builtin_function _________\n");
6443         print_triple(state, def);
6444         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6445 #endif
6446 }
6447
6448 static struct type *partial_struct(struct compile_state *state,
6449         const char *field_name, struct type *type, struct type *rest)
6450 {
6451         struct hash_entry *field_ident;
6452         struct type *result;
6453         int field_name_len;
6454
6455         field_name_len = strlen(field_name);
6456         field_ident = lookup(state, field_name, field_name_len);
6457
6458         result = clone_type(0, type);
6459         result->field_ident = field_ident;
6460
6461         if (rest) {
6462                 result = new_type(TYPE_PRODUCT, result, rest);
6463         }
6464         return result;
6465 }
6466
6467 static struct type *register_builtin_type(struct compile_state *state,
6468         const char *name, struct type *type)
6469 {
6470         struct hash_entry *ident;
6471         int name_len;
6472
6473         name_len = strlen(name);
6474         ident = lookup(state, name, name_len);
6475         
6476         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6477                 ulong_t elements = 0;
6478                 struct type *field;
6479                 type = new_type(TYPE_STRUCT, type, 0);
6480                 field = type->left;
6481                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6482                         elements++;
6483                         field = field->right;
6484                 }
6485                 elements++;
6486                 symbol(state, ident, &ident->sym_struct, 0, type);
6487                 type->type_ident = ident;
6488                 type->elements = elements;
6489         }
6490         symbol(state, ident, &ident->sym_ident, 0, type);
6491         ident->tok = TOK_TYPE_NAME;
6492         return type;
6493 }
6494
6495
6496 static void register_builtins(struct compile_state *state)
6497 {
6498         struct type *msr_type;
6499
6500         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6501                 &ushort_type);
6502         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6503                 &ushort_type);
6504         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6505                 &ushort_type);
6506
6507         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6508                 &uchar_type, &ushort_type);
6509         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6510                 &ushort_type, &ushort_type);
6511         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6512                 &uint_type, &ushort_type);
6513         
6514         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6515                 &int_type);
6516         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6517                 &int_type);
6518
6519         msr_type = register_builtin_type(state, "__builtin_msr_t",
6520                 partial_struct(state, "lo", &ulong_type,
6521                 partial_struct(state, "hi", &ulong_type, 0)));
6522
6523         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6524                 &ulong_type);
6525         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6526                 &ulong_type, &ulong_type, &ulong_type);
6527         
6528         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6529                 &void_type);
6530 }
6531
6532 static struct type *declarator(
6533         struct compile_state *state, struct type *type, 
6534         struct hash_entry **ident, int need_ident);
6535 static void decl(struct compile_state *state, struct triple *first);
6536 static struct type *specifier_qualifier_list(struct compile_state *state);
6537 static int isdecl_specifier(int tok);
6538 static struct type *decl_specifiers(struct compile_state *state);
6539 static int istype(int tok);
6540 static struct triple *expr(struct compile_state *state);
6541 static struct triple *assignment_expr(struct compile_state *state);
6542 static struct type *type_name(struct compile_state *state);
6543 static void statement(struct compile_state *state, struct triple *fist);
6544
6545 static struct triple *call_expr(
6546         struct compile_state *state, struct triple *func)
6547 {
6548         struct triple *def;
6549         struct type *param, *type;
6550         ulong_t pvals, index;
6551
6552         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6553                 error(state, 0, "Called object is not a function");
6554         }
6555         if (func->op != OP_LIST) {
6556                 internal_error(state, 0, "improper function");
6557         }
6558         eat(state, TOK_LPAREN);
6559         /* Find the return type without any specifiers */
6560         type = clone_type(0, func->type->left);
6561         def = new_triple(state, OP_CALL, func->type, -1, -1);
6562         def->type = type;
6563
6564         pvals = TRIPLE_RHS(def->sizes);
6565         MISC(def, 0) = func;
6566
6567         param = func->type->right;
6568         for(index = 0; index < pvals; index++) {
6569                 struct triple *val;
6570                 struct type *arg_type;
6571                 val = read_expr(state, assignment_expr(state));
6572                 arg_type = param;
6573                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6574                         arg_type = param->left;
6575                 }
6576                 write_compatible(state, arg_type, val->type);
6577                 RHS(def, index) = val;
6578                 if (index != (pvals - 1)) {
6579                         eat(state, TOK_COMMA);
6580                         param = param->right;
6581                 }
6582         }
6583         eat(state, TOK_RPAREN);
6584         return def;
6585 }
6586
6587
6588 static struct triple *character_constant(struct compile_state *state)
6589 {
6590         struct triple *def;
6591         struct token *tk;
6592         const signed char *str, *end;
6593         int c;
6594         int str_len;
6595         eat(state, TOK_LIT_CHAR);
6596         tk = &state->token[0];
6597         str = tk->val.str + 1;
6598         str_len = tk->str_len - 2;
6599         if (str_len <= 0) {
6600                 error(state, 0, "empty character constant");
6601         }
6602         end = str + str_len;
6603         c = char_value(state, &str, end);
6604         if (str != end) {
6605                 error(state, 0, "multibyte character constant not supported");
6606         }
6607         def = int_const(state, &char_type, (ulong_t)((long_t)c));
6608         return def;
6609 }
6610
6611 static struct triple *string_constant(struct compile_state *state)
6612 {
6613         struct triple *def;
6614         struct token *tk;
6615         struct type *type;
6616         const signed char *str, *end;
6617         signed char *buf, *ptr;
6618         int str_len;
6619
6620         buf = 0;
6621         type = new_type(TYPE_ARRAY, &char_type, 0);
6622         type->elements = 0;
6623         /* The while loop handles string concatenation */
6624         do {
6625                 eat(state, TOK_LIT_STRING);
6626                 tk = &state->token[0];
6627                 str = tk->val.str + 1;
6628                 str_len = tk->str_len - 2;
6629                 if (str_len < 0) {
6630                         error(state, 0, "negative string constant length");
6631                 }
6632                 end = str + str_len;
6633                 ptr = buf;
6634                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6635                 memcpy(buf, ptr, type->elements);
6636                 ptr = buf + type->elements;
6637                 do {
6638                         *ptr++ = char_value(state, &str, end);
6639                 } while(str < end);
6640                 type->elements = ptr - buf;
6641         } while(peek(state) == TOK_LIT_STRING);
6642         *ptr = '\0';
6643         type->elements += 1;
6644         def = triple(state, OP_BLOBCONST, type, 0, 0);
6645         def->u.blob = buf;
6646         return def;
6647 }
6648
6649
6650 static struct triple *integer_constant(struct compile_state *state)
6651 {
6652         struct triple *def;
6653         unsigned long val;
6654         struct token *tk;
6655         char *end;
6656         int u, l, decimal;
6657         struct type *type;
6658
6659         eat(state, TOK_LIT_INT);
6660         tk = &state->token[0];
6661         errno = 0;
6662         decimal = (tk->val.str[0] != '0');
6663         val = strtoul(tk->val.str, &end, 0);
6664         if ((val == ULONG_MAX) && (errno == ERANGE)) {
6665                 error(state, 0, "Integer constant to large");
6666         }
6667         u = l = 0;
6668         if ((*end == 'u') || (*end == 'U')) {
6669                 u = 1;
6670                         end++;
6671         }
6672         if ((*end == 'l') || (*end == 'L')) {
6673                 l = 1;
6674                 end++;
6675         }
6676         if ((*end == 'u') || (*end == 'U')) {
6677                 u = 1;
6678                 end++;
6679         }
6680         if (*end) {
6681                 error(state, 0, "Junk at end of integer constant");
6682         }
6683         if (u && l)  {
6684                 type = &ulong_type;
6685         }
6686         else if (l) {
6687                 type = &long_type;
6688                 if (!decimal && (val > LONG_MAX)) {
6689                         type = &ulong_type;
6690                 }
6691         }
6692         else if (u) {
6693                 type = &uint_type;
6694                 if (val > UINT_MAX) {
6695                         type = &ulong_type;
6696                 }
6697         }
6698         else {
6699                 type = &int_type;
6700                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6701                         type = &uint_type;
6702                 }
6703                 else if (!decimal && (val > LONG_MAX)) {
6704                         type = &ulong_type;
6705                 }
6706                 else if (val > INT_MAX) {
6707                         type = &long_type;
6708                 }
6709         }
6710         def = int_const(state, type, val);
6711         return def;
6712 }
6713
6714 static struct triple *primary_expr(struct compile_state *state)
6715 {
6716         struct triple *def;
6717         int tok;
6718         tok = peek(state);
6719         switch(tok) {
6720         case TOK_IDENT:
6721         {
6722                 struct hash_entry *ident;
6723                 /* Here ident is either:
6724                  * a varable name
6725                  * a function name
6726                  * an enumeration constant.
6727                  */
6728                 eat(state, TOK_IDENT);
6729                 ident = state->token[0].ident;
6730                 if (!ident->sym_ident) {
6731                         error(state, 0, "%s undeclared", ident->name);
6732                 }
6733                 def = ident->sym_ident->def;
6734                 break;
6735         }
6736         case TOK_ENUM_CONST:
6737                 /* Here ident is an enumeration constant */
6738                 eat(state, TOK_ENUM_CONST);
6739                 def = 0;
6740                 FINISHME();
6741                 break;
6742         case TOK_LPAREN:
6743                 eat(state, TOK_LPAREN);
6744                 def = expr(state);
6745                 eat(state, TOK_RPAREN);
6746                 break;
6747         case TOK_LIT_INT:
6748                 def = integer_constant(state);
6749                 break;
6750         case TOK_LIT_FLOAT:
6751                 eat(state, TOK_LIT_FLOAT);
6752                 error(state, 0, "Floating point constants not supported");
6753                 def = 0;
6754                 FINISHME();
6755                 break;
6756         case TOK_LIT_CHAR:
6757                 def = character_constant(state);
6758                 break;
6759         case TOK_LIT_STRING:
6760                 def = string_constant(state);
6761                 break;
6762         default:
6763                 def = 0;
6764                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6765         }
6766         return def;
6767 }
6768
6769 static struct triple *postfix_expr(struct compile_state *state)
6770 {
6771         struct triple *def;
6772         int postfix;
6773         def = primary_expr(state);
6774         do {
6775                 struct triple *left;
6776                 int tok;
6777                 postfix = 1;
6778                 left = def;
6779                 switch((tok = peek(state))) {
6780                 case TOK_LBRACKET:
6781                         eat(state, TOK_LBRACKET);
6782                         def = mk_subscript_expr(state, left, expr(state));
6783                         eat(state, TOK_RBRACKET);
6784                         break;
6785                 case TOK_LPAREN:
6786                         def = call_expr(state, def);
6787                         break;
6788                 case TOK_DOT:
6789                 {
6790                         struct hash_entry *field;
6791                         eat(state, TOK_DOT);
6792                         eat(state, TOK_IDENT);
6793                         field = state->token[0].ident;
6794                         def = deref_field(state, def, field);
6795                         break;
6796                 }
6797                 case TOK_ARROW:
6798                 {
6799                         struct hash_entry *field;
6800                         eat(state, TOK_ARROW);
6801                         eat(state, TOK_IDENT);
6802                         field = state->token[0].ident;
6803                         def = mk_deref_expr(state, read_expr(state, def));
6804                         def = deref_field(state, def, field);
6805                         break;
6806                 }
6807                 case TOK_PLUSPLUS:
6808                         eat(state, TOK_PLUSPLUS);
6809                         def = mk_post_inc_expr(state, left);
6810                         break;
6811                 case TOK_MINUSMINUS:
6812                         eat(state, TOK_MINUSMINUS);
6813                         def = mk_post_dec_expr(state, left);
6814                         break;
6815                 default:
6816                         postfix = 0;
6817                         break;
6818                 }
6819         } while(postfix);
6820         return def;
6821 }
6822
6823 static struct triple *cast_expr(struct compile_state *state);
6824
6825 static struct triple *unary_expr(struct compile_state *state)
6826 {
6827         struct triple *def, *right;
6828         int tok;
6829         switch((tok = peek(state))) {
6830         case TOK_PLUSPLUS:
6831                 eat(state, TOK_PLUSPLUS);
6832                 def = mk_pre_inc_expr(state, unary_expr(state));
6833                 break;
6834         case TOK_MINUSMINUS:
6835                 eat(state, TOK_MINUSMINUS);
6836                 def = mk_pre_dec_expr(state, unary_expr(state));
6837                 break;
6838         case TOK_AND:
6839                 eat(state, TOK_AND);
6840                 def = mk_addr_expr(state, cast_expr(state), 0);
6841                 break;
6842         case TOK_STAR:
6843                 eat(state, TOK_STAR);
6844                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6845                 break;
6846         case TOK_PLUS:
6847                 eat(state, TOK_PLUS);
6848                 right = read_expr(state, cast_expr(state));
6849                 arithmetic(state, right);
6850                 def = integral_promotion(state, right);
6851                 break;
6852         case TOK_MINUS:
6853                 eat(state, TOK_MINUS);
6854                 right = read_expr(state, cast_expr(state));
6855                 arithmetic(state, right);
6856                 def = integral_promotion(state, right);
6857                 def = triple(state, OP_NEG, def->type, def, 0);
6858                 break;
6859         case TOK_TILDE:
6860                 eat(state, TOK_TILDE);
6861                 right = read_expr(state, cast_expr(state));
6862                 integral(state, right);
6863                 def = integral_promotion(state, right);
6864                 def = triple(state, OP_INVERT, def->type, def, 0);
6865                 break;
6866         case TOK_BANG:
6867                 eat(state, TOK_BANG);
6868                 right = read_expr(state, cast_expr(state));
6869                 bool(state, right);
6870                 def = lfalse_expr(state, right);
6871                 break;
6872         case TOK_SIZEOF:
6873         {
6874                 struct type *type;
6875                 int tok1, tok2;
6876                 eat(state, TOK_SIZEOF);
6877                 tok1 = peek(state);
6878                 tok2 = peek2(state);
6879                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6880                         eat(state, TOK_LPAREN);
6881                         type = type_name(state);
6882                         eat(state, TOK_RPAREN);
6883                 }
6884                 else {
6885                         struct triple *expr;
6886                         expr = unary_expr(state);
6887                         type = expr->type;
6888                         release_expr(state, expr);
6889                 }
6890                 def = int_const(state, &ulong_type, size_of(state, type));
6891                 break;
6892         }
6893         case TOK_ALIGNOF:
6894         {
6895                 struct type *type;
6896                 int tok1, tok2;
6897                 eat(state, TOK_ALIGNOF);
6898                 tok1 = peek(state);
6899                 tok2 = peek2(state);
6900                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6901                         eat(state, TOK_LPAREN);
6902                         type = type_name(state);
6903                         eat(state, TOK_RPAREN);
6904                 }
6905                 else {
6906                         struct triple *expr;
6907                         expr = unary_expr(state);
6908                         type = expr->type;
6909                         release_expr(state, expr);
6910                 }
6911                 def = int_const(state, &ulong_type, align_of(state, type));
6912                 break;
6913         }
6914         default:
6915                 def = postfix_expr(state);
6916                 break;
6917         }
6918         return def;
6919 }
6920
6921 static struct triple *cast_expr(struct compile_state *state)
6922 {
6923         struct triple *def;
6924         int tok1, tok2;
6925         tok1 = peek(state);
6926         tok2 = peek2(state);
6927         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6928                 struct type *type;
6929                 eat(state, TOK_LPAREN);
6930                 type = type_name(state);
6931                 eat(state, TOK_RPAREN);
6932                 def = read_expr(state, cast_expr(state));
6933                 def = triple(state, OP_COPY, type, def, 0);
6934         }
6935         else {
6936                 def = unary_expr(state);
6937         }
6938         return def;
6939 }
6940
6941 static struct triple *mult_expr(struct compile_state *state)
6942 {
6943         struct triple *def;
6944         int done;
6945         def = cast_expr(state);
6946         do {
6947                 struct triple *left, *right;
6948                 struct type *result_type;
6949                 int tok, op, sign;
6950                 done = 0;
6951                 switch(tok = (peek(state))) {
6952                 case TOK_STAR:
6953                 case TOK_DIV:
6954                 case TOK_MOD:
6955                         left = read_expr(state, def);
6956                         arithmetic(state, left);
6957
6958                         eat(state, tok);
6959
6960                         right = read_expr(state, cast_expr(state));
6961                         arithmetic(state, right);
6962
6963                         result_type = arithmetic_result(state, left, right);
6964                         sign = is_signed(result_type);
6965                         op = -1;
6966                         switch(tok) {
6967                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6968                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
6969                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
6970                         }
6971                         def = triple(state, op, result_type, left, right);
6972                         break;
6973                 default:
6974                         done = 1;
6975                         break;
6976                 }
6977         } while(!done);
6978         return def;
6979 }
6980
6981 static struct triple *add_expr(struct compile_state *state)
6982 {
6983         struct triple *def;
6984         int done;
6985         def = mult_expr(state);
6986         do {
6987                 done = 0;
6988                 switch( peek(state)) {
6989                 case TOK_PLUS:
6990                         eat(state, TOK_PLUS);
6991                         def = mk_add_expr(state, def, mult_expr(state));
6992                         break;
6993                 case TOK_MINUS:
6994                         eat(state, TOK_MINUS);
6995                         def = mk_sub_expr(state, def, mult_expr(state));
6996                         break;
6997                 default:
6998                         done = 1;
6999                         break;
7000                 }
7001         } while(!done);
7002         return def;
7003 }
7004
7005 static struct triple *shift_expr(struct compile_state *state)
7006 {
7007         struct triple *def;
7008         int done;
7009         def = add_expr(state);
7010         do {
7011                 struct triple *left, *right;
7012                 int tok, op;
7013                 done = 0;
7014                 switch((tok = peek(state))) {
7015                 case TOK_SL:
7016                 case TOK_SR:
7017                         left = read_expr(state, def);
7018                         integral(state, left);
7019                         left = integral_promotion(state, left);
7020
7021                         eat(state, tok);
7022
7023                         right = read_expr(state, add_expr(state));
7024                         integral(state, right);
7025                         right = integral_promotion(state, right);
7026                         
7027                         op = (tok == TOK_SL)? OP_SL : 
7028                                 is_signed(left->type)? OP_SSR: OP_USR;
7029
7030                         def = triple(state, op, left->type, left, right);
7031                         break;
7032                 default:
7033                         done = 1;
7034                         break;
7035                 }
7036         } while(!done);
7037         return def;
7038 }
7039
7040 static struct triple *relational_expr(struct compile_state *state)
7041 {
7042 #warning "Extend relational exprs to work on more than arithmetic types"
7043         struct triple *def;
7044         int done;
7045         def = shift_expr(state);
7046         do {
7047                 struct triple *left, *right;
7048                 struct type *arg_type;
7049                 int tok, op, sign;
7050                 done = 0;
7051                 switch((tok = peek(state))) {
7052                 case TOK_LESS:
7053                 case TOK_MORE:
7054                 case TOK_LESSEQ:
7055                 case TOK_MOREEQ:
7056                         left = read_expr(state, def);
7057                         arithmetic(state, left);
7058
7059                         eat(state, tok);
7060
7061                         right = read_expr(state, shift_expr(state));
7062                         arithmetic(state, right);
7063
7064                         arg_type = arithmetic_result(state, left, right);
7065                         sign = is_signed(arg_type);
7066                         op = -1;
7067                         switch(tok) {
7068                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
7069                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
7070                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7071                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7072                         }
7073                         def = triple(state, op, &int_type, left, right);
7074                         break;
7075                 default:
7076                         done = 1;
7077                         break;
7078                 }
7079         } while(!done);
7080         return def;
7081 }
7082
7083 static struct triple *equality_expr(struct compile_state *state)
7084 {
7085 #warning "Extend equality exprs to work on more than arithmetic types"
7086         struct triple *def;
7087         int done;
7088         def = relational_expr(state);
7089         do {
7090                 struct triple *left, *right;
7091                 int tok, op;
7092                 done = 0;
7093                 switch((tok = peek(state))) {
7094                 case TOK_EQEQ:
7095                 case TOK_NOTEQ:
7096                         left = read_expr(state, def);
7097                         arithmetic(state, left);
7098                         eat(state, tok);
7099                         right = read_expr(state, relational_expr(state));
7100                         arithmetic(state, right);
7101                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7102                         def = triple(state, op, &int_type, left, right);
7103                         break;
7104                 default:
7105                         done = 1;
7106                         break;
7107                 }
7108         } while(!done);
7109         return def;
7110 }
7111
7112 static struct triple *and_expr(struct compile_state *state)
7113 {
7114         struct triple *def;
7115         def = equality_expr(state);
7116         while(peek(state) == TOK_AND) {
7117                 struct triple *left, *right;
7118                 struct type *result_type;
7119                 left = read_expr(state, def);
7120                 integral(state, left);
7121                 eat(state, TOK_AND);
7122                 right = read_expr(state, equality_expr(state));
7123                 integral(state, right);
7124                 result_type = arithmetic_result(state, left, right);
7125                 def = triple(state, OP_AND, result_type, left, right);
7126         }
7127         return def;
7128 }
7129
7130 static struct triple *xor_expr(struct compile_state *state)
7131 {
7132         struct triple *def;
7133         def = and_expr(state);
7134         while(peek(state) == TOK_XOR) {
7135                 struct triple *left, *right;
7136                 struct type *result_type;
7137                 left = read_expr(state, def);
7138                 integral(state, left);
7139                 eat(state, TOK_XOR);
7140                 right = read_expr(state, and_expr(state));
7141                 integral(state, right);
7142                 result_type = arithmetic_result(state, left, right);
7143                 def = triple(state, OP_XOR, result_type, left, right);
7144         }
7145         return def;
7146 }
7147
7148 static struct triple *or_expr(struct compile_state *state)
7149 {
7150         struct triple *def;
7151         def = xor_expr(state);
7152         while(peek(state) == TOK_OR) {
7153                 struct triple *left, *right;
7154                 struct type *result_type;
7155                 left = read_expr(state, def);
7156                 integral(state, left);
7157                 eat(state, TOK_OR);
7158                 right = read_expr(state, xor_expr(state));
7159                 integral(state, right);
7160                 result_type = arithmetic_result(state, left, right);
7161                 def = triple(state, OP_OR, result_type, left, right);
7162         }
7163         return def;
7164 }
7165
7166 static struct triple *land_expr(struct compile_state *state)
7167 {
7168         struct triple *def;
7169         def = or_expr(state);
7170         while(peek(state) == TOK_LOGAND) {
7171                 struct triple *left, *right;
7172                 left = read_expr(state, def);
7173                 bool(state, left);
7174                 eat(state, TOK_LOGAND);
7175                 right = read_expr(state, or_expr(state));
7176                 bool(state, right);
7177
7178                 def = triple(state, OP_LAND, &int_type,
7179                         ltrue_expr(state, left),
7180                         ltrue_expr(state, right));
7181         }
7182         return def;
7183 }
7184
7185 static struct triple *lor_expr(struct compile_state *state)
7186 {
7187         struct triple *def;
7188         def = land_expr(state);
7189         while(peek(state) == TOK_LOGOR) {
7190                 struct triple *left, *right;
7191                 left = read_expr(state, def);
7192                 bool(state, left);
7193                 eat(state, TOK_LOGOR);
7194                 right = read_expr(state, land_expr(state));
7195                 bool(state, right);
7196                 
7197                 def = triple(state, OP_LOR, &int_type,
7198                         ltrue_expr(state, left),
7199                         ltrue_expr(state, right));
7200         }
7201         return def;
7202 }
7203
7204 static struct triple *conditional_expr(struct compile_state *state)
7205 {
7206         struct triple *def;
7207         def = lor_expr(state);
7208         if (peek(state) == TOK_QUEST) {
7209                 struct triple *test, *left, *right;
7210                 bool(state, def);
7211                 test = ltrue_expr(state, read_expr(state, def));
7212                 eat(state, TOK_QUEST);
7213                 left = read_expr(state, expr(state));
7214                 eat(state, TOK_COLON);
7215                 right = read_expr(state, conditional_expr(state));
7216
7217                 def = cond_expr(state, test, left, right);
7218         }
7219         return def;
7220 }
7221
7222 static struct triple *eval_const_expr(
7223         struct compile_state *state, struct triple *expr)
7224 {
7225         struct triple *def;
7226         struct triple *head, *ptr;
7227         head = label(state); /* dummy initial triple */
7228         flatten(state, head, expr);
7229         for(ptr = head->next; ptr != head; ptr = ptr->next) {
7230                 simplify(state, ptr);
7231         }
7232         /* Remove the constant value the tail of the list */
7233         def = head->prev;
7234         def->prev->next = def->next;
7235         def->next->prev = def->prev;
7236         def->next = def->prev = def;
7237         if (!is_const(def)) {
7238                 internal_error(state, 0, "Not a constant expression");
7239         }
7240         /* Free the intermediate expressions */
7241         while(head->next != head) {
7242                 release_triple(state, head->next);
7243         }
7244         free_triple(state, head);
7245         return def;
7246 }
7247
7248 static struct triple *constant_expr(struct compile_state *state)
7249 {
7250         return eval_const_expr(state, conditional_expr(state));
7251 }
7252
7253 static struct triple *assignment_expr(struct compile_state *state)
7254 {
7255         struct triple *def, *left, *right;
7256         int tok, op, sign;
7257         /* The C grammer in K&R shows assignment expressions
7258          * only taking unary expressions as input on their
7259          * left hand side.  But specifies the precedence of
7260          * assignemnt as the lowest operator except for comma.
7261          *
7262          * Allowing conditional expressions on the left hand side
7263          * of an assignement results in a grammar that accepts
7264          * a larger set of statements than standard C.   As long
7265          * as the subset of the grammar that is standard C behaves
7266          * correctly this should cause no problems.
7267          * 
7268          * For the extra token strings accepted by the grammar
7269          * none of them should produce a valid lvalue, so they
7270          * should not produce functioning programs.
7271          *
7272          * GCC has this bug as well, so surprises should be minimal.
7273          */
7274         def = conditional_expr(state);
7275         left = def;
7276         switch((tok = peek(state))) {
7277         case TOK_EQ:
7278                 lvalue(state, left);
7279                 eat(state, TOK_EQ);
7280                 def = write_expr(state, left, 
7281                         read_expr(state, assignment_expr(state)));
7282                 break;
7283         case TOK_TIMESEQ:
7284         case TOK_DIVEQ:
7285         case TOK_MODEQ:
7286                 lvalue(state, left);
7287                 arithmetic(state, left);
7288                 eat(state, tok);
7289                 right = read_expr(state, assignment_expr(state));
7290                 arithmetic(state, right);
7291
7292                 sign = is_signed(left->type);
7293                 op = -1;
7294                 switch(tok) {
7295                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7296                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7297                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7298                 }
7299                 def = write_expr(state, left,
7300                         triple(state, op, left->type, 
7301                                 read_expr(state, left), right));
7302                 break;
7303         case TOK_PLUSEQ:
7304                 lvalue(state, left);
7305                 eat(state, TOK_PLUSEQ);
7306                 def = write_expr(state, left,
7307                         mk_add_expr(state, left, assignment_expr(state)));
7308                 break;
7309         case TOK_MINUSEQ:
7310                 lvalue(state, left);
7311                 eat(state, TOK_MINUSEQ);
7312                 def = write_expr(state, left,
7313                         mk_sub_expr(state, left, assignment_expr(state)));
7314                 break;
7315         case TOK_SLEQ:
7316         case TOK_SREQ:
7317         case TOK_ANDEQ:
7318         case TOK_XOREQ:
7319         case TOK_OREQ:
7320                 lvalue(state, left);
7321                 integral(state, left);
7322                 eat(state, tok);
7323                 right = read_expr(state, assignment_expr(state));
7324                 integral(state, right);
7325                 right = integral_promotion(state, right);
7326                 sign = is_signed(left->type);
7327                 op = -1;
7328                 switch(tok) {
7329                 case TOK_SLEQ:  op = OP_SL; break;
7330                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7331                 case TOK_ANDEQ: op = OP_AND; break;
7332                 case TOK_XOREQ: op = OP_XOR; break;
7333                 case TOK_OREQ:  op = OP_OR; break;
7334                 }
7335                 def = write_expr(state, left,
7336                         triple(state, op, left->type, 
7337                                 read_expr(state, left), right));
7338                 break;
7339         }
7340         return def;
7341 }
7342
7343 static struct triple *expr(struct compile_state *state)
7344 {
7345         struct triple *def;
7346         def = assignment_expr(state);
7347         while(peek(state) == TOK_COMMA) {
7348                 struct triple *left, *right;
7349                 left = def;
7350                 eat(state, TOK_COMMA);
7351                 right = assignment_expr(state);
7352                 def = triple(state, OP_COMMA, right->type, left, right);
7353         }
7354         return def;
7355 }
7356
7357 static void expr_statement(struct compile_state *state, struct triple *first)
7358 {
7359         if (peek(state) != TOK_SEMI) {
7360                 flatten(state, first, expr(state));
7361         }
7362         eat(state, TOK_SEMI);
7363 }
7364
7365 static void if_statement(struct compile_state *state, struct triple *first)
7366 {
7367         struct triple *test, *jmp1, *jmp2, *middle, *end;
7368
7369         jmp1 = jmp2 = middle = 0;
7370         eat(state, TOK_IF);
7371         eat(state, TOK_LPAREN);
7372         test = expr(state);
7373         bool(state, test);
7374         /* Cleanup and invert the test */
7375         test = lfalse_expr(state, read_expr(state, test));
7376         eat(state, TOK_RPAREN);
7377         /* Generate the needed pieces */
7378         middle = label(state);
7379         jmp1 = branch(state, middle, test);
7380         /* Thread the pieces together */
7381         flatten(state, first, test);
7382         flatten(state, first, jmp1);
7383         flatten(state, first, label(state));
7384         statement(state, first);
7385         if (peek(state) == TOK_ELSE) {
7386                 eat(state, TOK_ELSE);
7387                 /* Generate the rest of the pieces */
7388                 end = label(state);
7389                 jmp2 = branch(state, end, 0);
7390                 /* Thread them together */
7391                 flatten(state, first, jmp2);
7392                 flatten(state, first, middle);
7393                 statement(state, first);
7394                 flatten(state, first, end);
7395         }
7396         else {
7397                 flatten(state, first, middle);
7398         }
7399 }
7400
7401 static void for_statement(struct compile_state *state, struct triple *first)
7402 {
7403         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7404         struct triple *label1, *label2, *label3;
7405         struct hash_entry *ident;
7406
7407         eat(state, TOK_FOR);
7408         eat(state, TOK_LPAREN);
7409         head = test = tail = jmp1 = jmp2 = 0;
7410         if (peek(state) != TOK_SEMI) {
7411                 head = expr(state);
7412         } 
7413         eat(state, TOK_SEMI);
7414         if (peek(state) != TOK_SEMI) {
7415                 test = expr(state);
7416                 bool(state, test);
7417                 test = ltrue_expr(state, read_expr(state, test));
7418         }
7419         eat(state, TOK_SEMI);
7420         if (peek(state) != TOK_RPAREN) {
7421                 tail = expr(state);
7422         }
7423         eat(state, TOK_RPAREN);
7424         /* Generate the needed pieces */
7425         label1 = label(state);
7426         label2 = label(state);
7427         label3 = label(state);
7428         if (test) {
7429                 jmp1 = branch(state, label3, 0);
7430                 jmp2 = branch(state, label1, test);
7431         }
7432         else {
7433                 jmp2 = branch(state, label1, 0);
7434         }
7435         end = label(state);
7436         /* Remember where break and continue go */
7437         start_scope(state);
7438         ident = state->i_break;
7439         symbol(state, ident, &ident->sym_ident, end, end->type);
7440         ident = state->i_continue;
7441         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7442         /* Now include the body */
7443         flatten(state, first, head);
7444         flatten(state, first, jmp1);
7445         flatten(state, first, label1);
7446         statement(state, first);
7447         flatten(state, first, label2);
7448         flatten(state, first, tail);
7449         flatten(state, first, label3);
7450         flatten(state, first, test);
7451         flatten(state, first, jmp2);
7452         flatten(state, first, end);
7453         /* Cleanup the break/continue scope */
7454         end_scope(state);
7455 }
7456
7457 static void while_statement(struct compile_state *state, struct triple *first)
7458 {
7459         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7460         struct hash_entry *ident;
7461         eat(state, TOK_WHILE);
7462         eat(state, TOK_LPAREN);
7463         test = expr(state);
7464         bool(state, test);
7465         test = ltrue_expr(state, read_expr(state, test));
7466         eat(state, TOK_RPAREN);
7467         /* Generate the needed pieces */
7468         label1 = label(state);
7469         label2 = label(state);
7470         jmp1 = branch(state, label2, 0);
7471         jmp2 = branch(state, label1, test);
7472         end = label(state);
7473         /* Remember where break and continue go */
7474         start_scope(state);
7475         ident = state->i_break;
7476         symbol(state, ident, &ident->sym_ident, end, end->type);
7477         ident = state->i_continue;
7478         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7479         /* Thread them together */
7480         flatten(state, first, jmp1);
7481         flatten(state, first, label1);
7482         statement(state, first);
7483         flatten(state, first, label2);
7484         flatten(state, first, test);
7485         flatten(state, first, jmp2);
7486         flatten(state, first, end);
7487         /* Cleanup the break/continue scope */
7488         end_scope(state);
7489 }
7490
7491 static void do_statement(struct compile_state *state, struct triple *first)
7492 {
7493         struct triple *label1, *label2, *test, *end;
7494         struct hash_entry *ident;
7495         eat(state, TOK_DO);
7496         /* Generate the needed pieces */
7497         label1 = label(state);
7498         label2 = label(state);
7499         end = label(state);
7500         /* Remember where break and continue go */
7501         start_scope(state);
7502         ident = state->i_break;
7503         symbol(state, ident, &ident->sym_ident, end, end->type);
7504         ident = state->i_continue;
7505         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7506         /* Now include the body */
7507         flatten(state, first, label1);
7508         statement(state, first);
7509         /* Cleanup the break/continue scope */
7510         end_scope(state);
7511         /* Eat the rest of the loop */
7512         eat(state, TOK_WHILE);
7513         eat(state, TOK_LPAREN);
7514         test = read_expr(state, expr(state));
7515         bool(state, test);
7516         eat(state, TOK_RPAREN);
7517         eat(state, TOK_SEMI);
7518         /* Thread the pieces together */
7519         test = ltrue_expr(state, test);
7520         flatten(state, first, label2);
7521         flatten(state, first, test);
7522         flatten(state, first, branch(state, label1, test));
7523         flatten(state, first, end);
7524 }
7525
7526
7527 static void return_statement(struct compile_state *state, struct triple *first)
7528 {
7529         struct triple *jmp, *mv, *dest, *var, *val;
7530         int last;
7531         eat(state, TOK_RETURN);
7532
7533 #warning "FIXME implement a more general excess branch elimination"
7534         val = 0;
7535         /* If we have a return value do some more work */
7536         if (peek(state) != TOK_SEMI) {
7537                 val = read_expr(state, expr(state));
7538         }
7539         eat(state, TOK_SEMI);
7540
7541         /* See if this last statement in a function */
7542         last = ((peek(state) == TOK_RBRACE) && 
7543                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7544
7545         /* Find the return variable */
7546         var = MISC(state->main_function, 0);
7547         /* Find the return destination */
7548         dest = RHS(state->main_function, 0)->prev;
7549         mv = jmp = 0;
7550         /* If needed generate a jump instruction */
7551         if (!last) {
7552                 jmp = branch(state, dest, 0);
7553         }
7554         /* If needed generate an assignment instruction */
7555         if (val) {
7556                 mv = write_expr(state, var, val);
7557         }
7558         /* Now put the code together */
7559         if (mv) {
7560                 flatten(state, first, mv);
7561                 flatten(state, first, jmp);
7562         }
7563         else if (jmp) {
7564                 flatten(state, first, jmp);
7565         }
7566 }
7567
7568 static void break_statement(struct compile_state *state, struct triple *first)
7569 {
7570         struct triple *dest;
7571         eat(state, TOK_BREAK);
7572         eat(state, TOK_SEMI);
7573         if (!state->i_break->sym_ident) {
7574                 error(state, 0, "break statement not within loop or switch");
7575         }
7576         dest = state->i_break->sym_ident->def;
7577         flatten(state, first, branch(state, dest, 0));
7578 }
7579
7580 static void continue_statement(struct compile_state *state, struct triple *first)
7581 {
7582         struct triple *dest;
7583         eat(state, TOK_CONTINUE);
7584         eat(state, TOK_SEMI);
7585         if (!state->i_continue->sym_ident) {
7586                 error(state, 0, "continue statement outside of a loop");
7587         }
7588         dest = state->i_continue->sym_ident->def;
7589         flatten(state, first, branch(state, dest, 0));
7590 }
7591
7592 static void goto_statement(struct compile_state *state, struct triple *first)
7593 {
7594         FINISHME();
7595         eat(state, TOK_GOTO);
7596         eat(state, TOK_IDENT);
7597         eat(state, TOK_SEMI);
7598         error(state, 0, "goto is not implemeted");
7599         FINISHME();
7600 }
7601
7602 static void labeled_statement(struct compile_state *state, struct triple *first)
7603 {
7604         FINISHME();
7605         eat(state, TOK_IDENT);
7606         eat(state, TOK_COLON);
7607         statement(state, first);
7608         error(state, 0, "labeled statements are not implemented");
7609         FINISHME();
7610 }
7611
7612 static void switch_statement(struct compile_state *state, struct triple *first)
7613 {
7614         FINISHME();
7615         eat(state, TOK_SWITCH);
7616         eat(state, TOK_LPAREN);
7617         expr(state);
7618         eat(state, TOK_RPAREN);
7619         statement(state, first);
7620         error(state, 0, "switch statements are not implemented");
7621         FINISHME();
7622 }
7623
7624 static void case_statement(struct compile_state *state, struct triple *first)
7625 {
7626         FINISHME();
7627         eat(state, TOK_CASE);
7628         constant_expr(state);
7629         eat(state, TOK_COLON);
7630         statement(state, first);
7631         error(state, 0, "case statements are not implemented");
7632         FINISHME();
7633 }
7634
7635 static void default_statement(struct compile_state *state, struct triple *first)
7636 {
7637         FINISHME();
7638         eat(state, TOK_DEFAULT);
7639         eat(state, TOK_COLON);
7640         statement(state, first);
7641         error(state, 0, "default statements are not implemented");
7642         FINISHME();
7643 }
7644
7645 static void asm_statement(struct compile_state *state, struct triple *first)
7646 {
7647         struct asm_info *info;
7648         struct {
7649                 struct triple *constraint;
7650                 struct triple *expr;
7651         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7652         struct triple *def, *asm_str;
7653         int out, in, clobbers, more, colons, i;
7654
7655         eat(state, TOK_ASM);
7656         /* For now ignore the qualifiers */
7657         switch(peek(state)) {
7658         case TOK_CONST:
7659                 eat(state, TOK_CONST);
7660                 break;
7661         case TOK_VOLATILE:
7662                 eat(state, TOK_VOLATILE);
7663                 break;
7664         }
7665         eat(state, TOK_LPAREN);
7666         asm_str = string_constant(state);
7667
7668         colons = 0;
7669         out = in = clobbers = 0;
7670         /* Outputs */
7671         if ((colons == 0) && (peek(state) == TOK_COLON)) {
7672                 eat(state, TOK_COLON);
7673                 colons++;
7674                 more = (peek(state) == TOK_LIT_STRING);
7675                 while(more) {
7676                         struct triple *var;
7677                         struct triple *constraint;
7678                         char *str;
7679                         more = 0;
7680                         if (out > MAX_LHS) {
7681                                 error(state, 0, "Maximum output count exceeded.");
7682                         }
7683                         constraint = string_constant(state);
7684                         str = constraint->u.blob;
7685                         if (str[0] != '=') {
7686                                 error(state, 0, "Output constraint does not start with =");
7687                         }
7688                         constraint->u.blob = str + 1;
7689                         eat(state, TOK_LPAREN);
7690                         var = conditional_expr(state);
7691                         eat(state, TOK_RPAREN);
7692
7693                         lvalue(state, var);
7694                         out_param[out].constraint = constraint;
7695                         out_param[out].expr       = var;
7696                         if (peek(state) == TOK_COMMA) {
7697                                 eat(state, TOK_COMMA);
7698                                 more = 1;
7699                         }
7700                         out++;
7701                 }
7702         }
7703         /* Inputs */
7704         if ((colons == 1) && (peek(state) == TOK_COLON)) {
7705                 eat(state, TOK_COLON);
7706                 colons++;
7707                 more = (peek(state) == TOK_LIT_STRING);
7708                 while(more) {
7709                         struct triple *val;
7710                         struct triple *constraint;
7711                         char *str;
7712                         more = 0;
7713                         if (in > MAX_RHS) {
7714                                 error(state, 0, "Maximum input count exceeded.");
7715                         }
7716                         constraint = string_constant(state);
7717                         str = constraint->u.blob;
7718                         if (digitp(str[0] && str[1] == '\0')) {
7719                                 int val;
7720                                 val = digval(str[0]);
7721                                 if ((val < 0) || (val >= out)) {
7722                                         error(state, 0, "Invalid input constraint %d", val);
7723                                 }
7724                         }
7725                         eat(state, TOK_LPAREN);
7726                         val = conditional_expr(state);
7727                         eat(state, TOK_RPAREN);
7728
7729                         in_param[in].constraint = constraint;
7730                         in_param[in].expr       = val;
7731                         if (peek(state) == TOK_COMMA) {
7732                                 eat(state, TOK_COMMA);
7733                                 more = 1;
7734                         }
7735                         in++;
7736                 }
7737         }
7738
7739         /* Clobber */
7740         if ((colons == 2) && (peek(state) == TOK_COLON)) {
7741                 eat(state, TOK_COLON);
7742                 colons++;
7743                 more = (peek(state) == TOK_LIT_STRING);
7744                 while(more) {
7745                         struct triple *clobber;
7746                         more = 0;
7747                         if ((clobbers + out) > MAX_LHS) {
7748                                 error(state, 0, "Maximum clobber limit exceeded.");
7749                         }
7750                         clobber = string_constant(state);
7751                         eat(state, TOK_RPAREN);
7752
7753                         clob_param[clobbers].constraint = clobber;
7754                         if (peek(state) == TOK_COMMA) {
7755                                 eat(state, TOK_COMMA);
7756                                 more = 1;
7757                         }
7758                         clobbers++;
7759                 }
7760         }
7761         eat(state, TOK_RPAREN);
7762         eat(state, TOK_SEMI);
7763
7764
7765         info = xcmalloc(sizeof(*info), "asm_info");
7766         info->str = asm_str->u.blob;
7767         free_triple(state, asm_str);
7768
7769         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
7770         def->u.ainfo = info;
7771
7772         /* Find the register constraints */
7773         for(i = 0; i < out; i++) {
7774                 struct triple *constraint;
7775                 constraint = out_param[i].constraint;
7776                 info->tmpl.lhs[i] = arch_reg_constraint(state, 
7777                         out_param[i].expr->type, constraint->u.blob);
7778                 free_triple(state, constraint);
7779         }
7780         for(; i - out < clobbers; i++) {
7781                 struct triple *constraint;
7782                 constraint = clob_param[i - out].constraint;
7783                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
7784                 free_triple(state, constraint);
7785         }
7786         for(i = 0; i < in; i++) {
7787                 struct triple *constraint;
7788                 const char *str;
7789                 constraint = in_param[i].constraint;
7790                 str = constraint->u.blob;
7791                 if (digitp(str[0]) && str[1] == '\0') {
7792                         struct reg_info cinfo;
7793                         int val;
7794                         val = digval(str[0]);
7795                         cinfo.reg = info->tmpl.lhs[val].reg;
7796                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
7797                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
7798                         if (cinfo.reg == REG_UNSET) {
7799                                 cinfo.reg = REG_VIRT0 + val;
7800                         }
7801                         if (cinfo.regcm == 0) {
7802                                 error(state, 0, "No registers for %d", val);
7803                         }
7804                         info->tmpl.lhs[val] = cinfo;
7805                         info->tmpl.rhs[i]   = cinfo;
7806                                 
7807                 } else {
7808                         info->tmpl.rhs[i] = arch_reg_constraint(state, 
7809                                 in_param[i].expr->type, str);
7810                 }
7811                 free_triple(state, constraint);
7812         }
7813
7814         /* Now build the helper expressions */
7815         for(i = 0; i < in; i++) {
7816                 RHS(def, i) = read_expr(state,in_param[i].expr);
7817         }
7818         flatten(state, first, def);
7819         for(i = 0; i < out; i++) {
7820                 struct triple *piece;
7821                 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
7822                 piece->u.cval = i;
7823                 LHS(def, i) = piece;
7824                 flatten(state, first,
7825                         write_expr(state, out_param[i].expr, piece));
7826         }
7827         for(; i - out < clobbers; i++) {
7828                 struct triple *piece;
7829                 piece = triple(state, OP_PIECE, &void_type, def, 0);
7830                 piece->u.cval = i;
7831                 LHS(def, i) = piece;
7832                 flatten(state, first, piece);
7833         }
7834 }
7835
7836
7837 static int isdecl(int tok)
7838 {
7839         switch(tok) {
7840         case TOK_AUTO:
7841         case TOK_REGISTER:
7842         case TOK_STATIC:
7843         case TOK_EXTERN:
7844         case TOK_TYPEDEF:
7845         case TOK_CONST:
7846         case TOK_RESTRICT:
7847         case TOK_VOLATILE:
7848         case TOK_VOID:
7849         case TOK_CHAR:
7850         case TOK_SHORT:
7851         case TOK_INT:
7852         case TOK_LONG:
7853         case TOK_FLOAT:
7854         case TOK_DOUBLE:
7855         case TOK_SIGNED:
7856         case TOK_UNSIGNED:
7857         case TOK_STRUCT:
7858         case TOK_UNION:
7859         case TOK_ENUM:
7860         case TOK_TYPE_NAME: /* typedef name */
7861                 return 1;
7862         default:
7863                 return 0;
7864         }
7865 }
7866
7867 static void compound_statement(struct compile_state *state, struct triple *first)
7868 {
7869         eat(state, TOK_LBRACE);
7870         start_scope(state);
7871
7872         /* statement-list opt */
7873         while (peek(state) != TOK_RBRACE) {
7874                 statement(state, first);
7875         }
7876         end_scope(state);
7877         eat(state, TOK_RBRACE);
7878 }
7879
7880 static void statement(struct compile_state *state, struct triple *first)
7881 {
7882         int tok;
7883         tok = peek(state);
7884         if (tok == TOK_LBRACE) {
7885                 compound_statement(state, first);
7886         }
7887         else if (tok == TOK_IF) {
7888                 if_statement(state, first); 
7889         }
7890         else if (tok == TOK_FOR) {
7891                 for_statement(state, first);
7892         }
7893         else if (tok == TOK_WHILE) {
7894                 while_statement(state, first);
7895         }
7896         else if (tok == TOK_DO) {
7897                 do_statement(state, first);
7898         }
7899         else if (tok == TOK_RETURN) {
7900                 return_statement(state, first);
7901         }
7902         else if (tok == TOK_BREAK) {
7903                 break_statement(state, first);
7904         }
7905         else if (tok == TOK_CONTINUE) {
7906                 continue_statement(state, first);
7907         }
7908         else if (tok == TOK_GOTO) {
7909                 goto_statement(state, first);
7910         }
7911         else if (tok == TOK_SWITCH) {
7912                 switch_statement(state, first);
7913         }
7914         else if (tok == TOK_ASM) {
7915                 asm_statement(state, first);
7916         }
7917         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7918                 labeled_statement(state, first); 
7919         }
7920         else if (tok == TOK_CASE) {
7921                 case_statement(state, first);
7922         }
7923         else if (tok == TOK_DEFAULT) {
7924                 default_statement(state, first);
7925         }
7926         else if (isdecl(tok)) {
7927                 /* This handles C99 intermixing of statements and decls */
7928                 decl(state, first);
7929         }
7930         else {
7931                 expr_statement(state, first);
7932         }
7933 }
7934
7935 static struct type *param_decl(struct compile_state *state)
7936 {
7937         struct type *type;
7938         struct hash_entry *ident;
7939         /* Cheat so the declarator will know we are not global */
7940         start_scope(state); 
7941         ident = 0;
7942         type = decl_specifiers(state);
7943         type = declarator(state, type, &ident, 0);
7944         type->field_ident = ident;
7945         end_scope(state);
7946         return type;
7947 }
7948
7949 static struct type *param_type_list(struct compile_state *state, struct type *type)
7950 {
7951         struct type *ftype, **next;
7952         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7953         next = &ftype->right;
7954         while(peek(state) == TOK_COMMA) {
7955                 eat(state, TOK_COMMA);
7956                 if (peek(state) == TOK_DOTS) {
7957                         eat(state, TOK_DOTS);
7958                         error(state, 0, "variadic functions not supported");
7959                 }
7960                 else {
7961                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7962                         next = &((*next)->right);
7963                 }
7964         }
7965         return ftype;
7966 }
7967
7968
7969 static struct type *type_name(struct compile_state *state)
7970 {
7971         struct type *type;
7972         type = specifier_qualifier_list(state);
7973         /* abstract-declarator (may consume no tokens) */
7974         type = declarator(state, type, 0, 0);
7975         return type;
7976 }
7977
7978 static struct type *direct_declarator(
7979         struct compile_state *state, struct type *type, 
7980         struct hash_entry **ident, int need_ident)
7981 {
7982         struct type *outer;
7983         int op;
7984         outer = 0;
7985         arrays_complete(state, type);
7986         switch(peek(state)) {
7987         case TOK_IDENT:
7988                 eat(state, TOK_IDENT);
7989                 if (!ident) {
7990                         error(state, 0, "Unexpected identifier found");
7991                 }
7992                 /* The name of what we are declaring */
7993                 *ident = state->token[0].ident;
7994                 break;
7995         case TOK_LPAREN:
7996                 eat(state, TOK_LPAREN);
7997                 outer = declarator(state, type, ident, need_ident);
7998                 eat(state, TOK_RPAREN);
7999                 break;
8000         default:
8001                 if (need_ident) {
8002                         error(state, 0, "Identifier expected");
8003                 }
8004                 break;
8005         }
8006         do {
8007                 op = 1;
8008                 arrays_complete(state, type);
8009                 switch(peek(state)) {
8010                 case TOK_LPAREN:
8011                         eat(state, TOK_LPAREN);
8012                         type = param_type_list(state, type);
8013                         eat(state, TOK_RPAREN);
8014                         break;
8015                 case TOK_LBRACKET:
8016                 {
8017                         unsigned int qualifiers;
8018                         struct triple *value;
8019                         value = 0;
8020                         eat(state, TOK_LBRACKET);
8021                         if (peek(state) != TOK_RBRACKET) {
8022                                 value = constant_expr(state);
8023                                 integral(state, value);
8024                         }
8025                         eat(state, TOK_RBRACKET);
8026
8027                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8028                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8029                         if (value) {
8030                                 type->elements = value->u.cval;
8031                                 free_triple(state, value);
8032                         } else {
8033                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8034                                 op = 0;
8035                         }
8036                 }
8037                         break;
8038                 default:
8039                         op = 0;
8040                         break;
8041                 }
8042         } while(op);
8043         if (outer) {
8044                 struct type *inner;
8045                 arrays_complete(state, type);
8046                 FINISHME();
8047                 for(inner = outer; inner->left; inner = inner->left)
8048                         ;
8049                 inner->left = type;
8050                 type = outer;
8051         }
8052         return type;
8053 }
8054
8055 static struct type *declarator(
8056         struct compile_state *state, struct type *type, 
8057         struct hash_entry **ident, int need_ident)
8058 {
8059         while(peek(state) == TOK_STAR) {
8060                 eat(state, TOK_STAR);
8061                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8062         }
8063         type = direct_declarator(state, type, ident, need_ident);
8064         return type;
8065 }
8066
8067
8068 static struct type *typedef_name(
8069         struct compile_state *state, unsigned int specifiers)
8070 {
8071         struct hash_entry *ident;
8072         struct type *type;
8073         eat(state, TOK_TYPE_NAME);
8074         ident = state->token[0].ident;
8075         type = ident->sym_ident->type;
8076         specifiers |= type->type & QUAL_MASK;
8077         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
8078                 (type->type & (STOR_MASK | QUAL_MASK))) {
8079                 type = clone_type(specifiers, type);
8080         }
8081         return type;
8082 }
8083
8084 static struct type *enum_specifier(
8085         struct compile_state *state, unsigned int specifiers)
8086 {
8087         int tok;
8088         struct type *type;
8089         type = 0;
8090         FINISHME();
8091         eat(state, TOK_ENUM);
8092         tok = peek(state);
8093         if (tok == TOK_IDENT) {
8094                 eat(state, TOK_IDENT);
8095         }
8096         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8097                 eat(state, TOK_LBRACE);
8098                 do {
8099                         eat(state, TOK_IDENT);
8100                         if (peek(state) == TOK_EQ) {
8101                                 eat(state, TOK_EQ);
8102                                 constant_expr(state);
8103                         }
8104                         if (peek(state) == TOK_COMMA) {
8105                                 eat(state, TOK_COMMA);
8106                         }
8107                 } while(peek(state) != TOK_RBRACE);
8108                 eat(state, TOK_RBRACE);
8109         }
8110         FINISHME();
8111         return type;
8112 }
8113
8114 #if 0
8115 static struct type *struct_declarator(
8116         struct compile_state *state, struct type *type, struct hash_entry **ident)
8117 {
8118         int tok;
8119 #warning "struct_declarator is complicated because of bitfields, kill them?"
8120         tok = peek(state);
8121         if (tok != TOK_COLON) {
8122                 type = declarator(state, type, ident, 1);
8123         }
8124         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8125                 eat(state, TOK_COLON);
8126                 constant_expr(state);
8127         }
8128         FINISHME();
8129         return type;
8130 }
8131 #endif
8132
8133 static struct type *struct_or_union_specifier(
8134         struct compile_state *state, unsigned int specifiers)
8135 {
8136         struct type *struct_type;
8137         struct hash_entry *ident;
8138         unsigned int type_join;
8139         int tok;
8140         struct_type = 0;
8141         ident = 0;
8142         switch(peek(state)) {
8143         case TOK_STRUCT:
8144                 eat(state, TOK_STRUCT);
8145                 type_join = TYPE_PRODUCT;
8146                 break;
8147         case TOK_UNION:
8148                 eat(state, TOK_UNION);
8149                 type_join = TYPE_OVERLAP;
8150                 error(state, 0, "unions not yet supported\n");
8151                 break;
8152         default:
8153                 eat(state, TOK_STRUCT);
8154                 type_join = TYPE_PRODUCT;
8155                 break;
8156         }
8157         tok = peek(state);
8158         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8159                 eat(state, tok);
8160                 ident = state->token[0].ident;
8161         }
8162         if (!ident || (peek(state) == TOK_LBRACE)) {
8163                 ulong_t elements;
8164                 elements = 0;
8165                 eat(state, TOK_LBRACE);
8166                 do {
8167                         struct type *base_type;
8168                         struct type **next;
8169                         int done;
8170                         base_type = specifier_qualifier_list(state);
8171                         next = &struct_type;
8172                         do {
8173                                 struct type *type;
8174                                 struct hash_entry *fident;
8175                                 done = 1;
8176                                 type = declarator(state, base_type, &fident, 1);
8177                                 elements++;
8178                                 if (peek(state) == TOK_COMMA) {
8179                                         done = 0;
8180                                         eat(state, TOK_COMMA);
8181                                 }
8182                                 type = clone_type(0, type);
8183                                 type->field_ident = fident;
8184                                 if (*next) {
8185                                         *next = new_type(type_join, *next, type);
8186                                         next = &((*next)->right);
8187                                 } else {
8188                                         *next = type;
8189                                 }
8190                         } while(!done);
8191                         eat(state, TOK_SEMI);
8192                 } while(peek(state) != TOK_RBRACE);
8193                 eat(state, TOK_RBRACE);
8194                 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
8195                 struct_type->type_ident = ident;
8196                 struct_type->elements = elements;
8197                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8198         }
8199         if (ident && ident->sym_struct) {
8200                 struct_type = ident->sym_struct->type;
8201         }
8202         else if (ident && !ident->sym_struct) {
8203                 error(state, 0, "struct %s undeclared", ident->name);
8204         }
8205         return struct_type;
8206 }
8207
8208 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8209 {
8210         unsigned int specifiers;
8211         switch(peek(state)) {
8212         case TOK_AUTO:
8213                 eat(state, TOK_AUTO);
8214                 specifiers = STOR_AUTO;
8215                 break;
8216         case TOK_REGISTER:
8217                 eat(state, TOK_REGISTER);
8218                 specifiers = STOR_REGISTER;
8219                 break;
8220         case TOK_STATIC:
8221                 eat(state, TOK_STATIC);
8222                 specifiers = STOR_STATIC;
8223                 break;
8224         case TOK_EXTERN:
8225                 eat(state, TOK_EXTERN);
8226                 specifiers = STOR_EXTERN;
8227                 break;
8228         case TOK_TYPEDEF:
8229                 eat(state, TOK_TYPEDEF);
8230                 specifiers = STOR_TYPEDEF;
8231                 break;
8232         default:
8233                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8234                         specifiers = STOR_STATIC;
8235                 }
8236                 else {
8237                         specifiers = STOR_AUTO;
8238                 }
8239         }
8240         return specifiers;
8241 }
8242
8243 static unsigned int function_specifier_opt(struct compile_state *state)
8244 {
8245         /* Ignore the inline keyword */
8246         unsigned int specifiers;
8247         specifiers = 0;
8248         switch(peek(state)) {
8249         case TOK_INLINE:
8250                 eat(state, TOK_INLINE);
8251                 specifiers = STOR_INLINE;
8252         }
8253         return specifiers;
8254 }
8255
8256 static unsigned int type_qualifiers(struct compile_state *state)
8257 {
8258         unsigned int specifiers;
8259         int done;
8260         done = 0;
8261         specifiers = QUAL_NONE;
8262         do {
8263                 switch(peek(state)) {
8264                 case TOK_CONST:
8265                         eat(state, TOK_CONST);
8266                         specifiers = QUAL_CONST;
8267                         break;
8268                 case TOK_VOLATILE:
8269                         eat(state, TOK_VOLATILE);
8270                         specifiers = QUAL_VOLATILE;
8271                         break;
8272                 case TOK_RESTRICT:
8273                         eat(state, TOK_RESTRICT);
8274                         specifiers = QUAL_RESTRICT;
8275                         break;
8276                 default:
8277                         done = 1;
8278                         break;
8279                 }
8280         } while(!done);
8281         return specifiers;
8282 }
8283
8284 static struct type *type_specifier(
8285         struct compile_state *state, unsigned int spec)
8286 {
8287         struct type *type;
8288         type = 0;
8289         switch(peek(state)) {
8290         case TOK_VOID:
8291                 eat(state, TOK_VOID);
8292                 type = new_type(TYPE_VOID | spec, 0, 0);
8293                 break;
8294         case TOK_CHAR:
8295                 eat(state, TOK_CHAR);
8296                 type = new_type(TYPE_CHAR | spec, 0, 0);
8297                 break;
8298         case TOK_SHORT:
8299                 eat(state, TOK_SHORT);
8300                 if (peek(state) == TOK_INT) {
8301                         eat(state, TOK_INT);
8302                 }
8303                 type = new_type(TYPE_SHORT | spec, 0, 0);
8304                 break;
8305         case TOK_INT:
8306                 eat(state, TOK_INT);
8307                 type = new_type(TYPE_INT | spec, 0, 0);
8308                 break;
8309         case TOK_LONG:
8310                 eat(state, TOK_LONG);
8311                 switch(peek(state)) {
8312                 case TOK_LONG:
8313                         eat(state, TOK_LONG);
8314                         error(state, 0, "long long not supported");
8315                         break;
8316                 case TOK_DOUBLE:
8317                         eat(state, TOK_DOUBLE);
8318                         error(state, 0, "long double not supported");
8319                         break;
8320                 case TOK_INT:
8321                         eat(state, TOK_INT);
8322                         type = new_type(TYPE_LONG | spec, 0, 0);
8323                         break;
8324                 default:
8325                         type = new_type(TYPE_LONG | spec, 0, 0);
8326                         break;
8327                 }
8328                 break;
8329         case TOK_FLOAT:
8330                 eat(state, TOK_FLOAT);
8331                 error(state, 0, "type float not supported");
8332                 break;
8333         case TOK_DOUBLE:
8334                 eat(state, TOK_DOUBLE);
8335                 error(state, 0, "type double not supported");
8336                 break;
8337         case TOK_SIGNED:
8338                 eat(state, TOK_SIGNED);
8339                 switch(peek(state)) {
8340                 case TOK_LONG:
8341                         eat(state, TOK_LONG);
8342                         switch(peek(state)) {
8343                         case TOK_LONG:
8344                                 eat(state, TOK_LONG);
8345                                 error(state, 0, "type long long not supported");
8346                                 break;
8347                         case TOK_INT:
8348                                 eat(state, TOK_INT);
8349                                 type = new_type(TYPE_LONG | spec, 0, 0);
8350                                 break;
8351                         default:
8352                                 type = new_type(TYPE_LONG | spec, 0, 0);
8353                                 break;
8354                         }
8355                         break;
8356                 case TOK_INT:
8357                         eat(state, TOK_INT);
8358                         type = new_type(TYPE_INT | spec, 0, 0);
8359                         break;
8360                 case TOK_SHORT:
8361                         eat(state, TOK_SHORT);
8362                         type = new_type(TYPE_SHORT | spec, 0, 0);
8363                         break;
8364                 case TOK_CHAR:
8365                         eat(state, TOK_CHAR);
8366                         type = new_type(TYPE_CHAR | spec, 0, 0);
8367                         break;
8368                 default:
8369                         type = new_type(TYPE_INT | spec, 0, 0);
8370                         break;
8371                 }
8372                 break;
8373         case TOK_UNSIGNED:
8374                 eat(state, TOK_UNSIGNED);
8375                 switch(peek(state)) {
8376                 case TOK_LONG:
8377                         eat(state, TOK_LONG);
8378                         switch(peek(state)) {
8379                         case TOK_LONG:
8380                                 eat(state, TOK_LONG);
8381                                 error(state, 0, "unsigned long long not supported");
8382                                 break;
8383                         case TOK_INT:
8384                                 eat(state, TOK_INT);
8385                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8386                                 break;
8387                         default:
8388                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8389                                 break;
8390                         }
8391                         break;
8392                 case TOK_INT:
8393                         eat(state, TOK_INT);
8394                         type = new_type(TYPE_UINT | spec, 0, 0);
8395                         break;
8396                 case TOK_SHORT:
8397                         eat(state, TOK_SHORT);
8398                         type = new_type(TYPE_USHORT | spec, 0, 0);
8399                         break;
8400                 case TOK_CHAR:
8401                         eat(state, TOK_CHAR);
8402                         type = new_type(TYPE_UCHAR | spec, 0, 0);
8403                         break;
8404                 default:
8405                         type = new_type(TYPE_UINT | spec, 0, 0);
8406                         break;
8407                 }
8408                 break;
8409                 /* struct or union specifier */
8410         case TOK_STRUCT:
8411         case TOK_UNION:
8412                 type = struct_or_union_specifier(state, spec);
8413                 break;
8414                 /* enum-spefifier */
8415         case TOK_ENUM:
8416                 type = enum_specifier(state, spec);
8417                 break;
8418                 /* typedef name */
8419         case TOK_TYPE_NAME:
8420                 type = typedef_name(state, spec);
8421                 break;
8422         default:
8423                 error(state, 0, "bad type specifier %s", 
8424                         tokens[peek(state)]);
8425                 break;
8426         }
8427         return type;
8428 }
8429
8430 static int istype(int tok)
8431 {
8432         switch(tok) {
8433         case TOK_CONST:
8434         case TOK_RESTRICT:
8435         case TOK_VOLATILE:
8436         case TOK_VOID:
8437         case TOK_CHAR:
8438         case TOK_SHORT:
8439         case TOK_INT:
8440         case TOK_LONG:
8441         case TOK_FLOAT:
8442         case TOK_DOUBLE:
8443         case TOK_SIGNED:
8444         case TOK_UNSIGNED:
8445         case TOK_STRUCT:
8446         case TOK_UNION:
8447         case TOK_ENUM:
8448         case TOK_TYPE_NAME:
8449                 return 1;
8450         default:
8451                 return 0;
8452         }
8453 }
8454
8455
8456 static struct type *specifier_qualifier_list(struct compile_state *state)
8457 {
8458         struct type *type;
8459         unsigned int specifiers = 0;
8460
8461         /* type qualifiers */
8462         specifiers |= type_qualifiers(state);
8463
8464         /* type specifier */
8465         type = type_specifier(state, specifiers);
8466
8467         return type;
8468 }
8469
8470 static int isdecl_specifier(int tok)
8471 {
8472         switch(tok) {
8473                 /* storage class specifier */
8474         case TOK_AUTO:
8475         case TOK_REGISTER:
8476         case TOK_STATIC:
8477         case TOK_EXTERN:
8478         case TOK_TYPEDEF:
8479                 /* type qualifier */
8480         case TOK_CONST:
8481         case TOK_RESTRICT:
8482         case TOK_VOLATILE:
8483                 /* type specifiers */
8484         case TOK_VOID:
8485         case TOK_CHAR:
8486         case TOK_SHORT:
8487         case TOK_INT:
8488         case TOK_LONG:
8489         case TOK_FLOAT:
8490         case TOK_DOUBLE:
8491         case TOK_SIGNED:
8492         case TOK_UNSIGNED:
8493                 /* struct or union specifier */
8494         case TOK_STRUCT:
8495         case TOK_UNION:
8496                 /* enum-spefifier */
8497         case TOK_ENUM:
8498                 /* typedef name */
8499         case TOK_TYPE_NAME:
8500                 /* function specifiers */
8501         case TOK_INLINE:
8502                 return 1;
8503         default:
8504                 return 0;
8505         }
8506 }
8507
8508 static struct type *decl_specifiers(struct compile_state *state)
8509 {
8510         struct type *type;
8511         unsigned int specifiers;
8512         /* I am overly restrictive in the arragement of specifiers supported.
8513          * C is overly flexible in this department it makes interpreting
8514          * the parse tree difficult.
8515          */
8516         specifiers = 0;
8517
8518         /* storage class specifier */
8519         specifiers |= storage_class_specifier_opt(state);
8520
8521         /* function-specifier */
8522         specifiers |= function_specifier_opt(state);
8523
8524         /* type qualifier */
8525         specifiers |= type_qualifiers(state);
8526
8527         /* type specifier */
8528         type = type_specifier(state, specifiers);
8529         return type;
8530 }
8531
8532 static unsigned designator(struct compile_state *state)
8533 {
8534         int tok;
8535         unsigned index;
8536         index = -1U;
8537         do {
8538                 switch(peek(state)) {
8539                 case TOK_LBRACKET:
8540                 {
8541                         struct triple *value;
8542                         eat(state, TOK_LBRACKET);
8543                         value = constant_expr(state);
8544                         eat(state, TOK_RBRACKET);
8545                         index = value->u.cval;
8546                         break;
8547                 }
8548                 case TOK_DOT:
8549                         eat(state, TOK_DOT);
8550                         eat(state, TOK_IDENT);
8551                         error(state, 0, "Struct Designators not currently supported");
8552                         break;
8553                 default:
8554                         error(state, 0, "Invalid designator");
8555                 }
8556                 tok = peek(state);
8557         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8558         eat(state, TOK_EQ);
8559         return index;
8560 }
8561
8562 static struct triple *initializer(
8563         struct compile_state *state, struct type *type)
8564 {
8565         struct triple *result;
8566         if (peek(state) != TOK_LBRACE) {
8567                 result = assignment_expr(state);
8568         }
8569         else {
8570                 int comma;
8571                 unsigned index, max_index;
8572                 void *buf;
8573                 max_index = index = 0;
8574                 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8575                         max_index = type->elements;
8576                         if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8577                                 type->elements = 0;
8578                         }
8579                 } else {
8580                         error(state, 0, "Struct initializers not currently supported");
8581                 }
8582                 buf = xcmalloc(size_of(state, type), "initializer");
8583                 eat(state, TOK_LBRACE);
8584                 do {
8585                         struct triple *value;
8586                         struct type *value_type;
8587                         size_t value_size;
8588                         int tok;
8589                         comma = 0;
8590                         tok = peek(state);
8591                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8592                                 index = designator(state);
8593                         }
8594                         if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8595                                 (index > max_index)) {
8596                                 error(state, 0, "element beyond bounds");
8597                         }
8598                         value_type = 0;
8599                         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8600                                 value_type = type->left;
8601                         }
8602                         value = eval_const_expr(state, initializer(state, value_type));
8603                         value_size = size_of(state, value_type);
8604                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8605                                 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8606                                 (type->elements <= index)) {
8607                                 void *old_buf;
8608                                 size_t old_size;
8609                                 old_buf = buf;
8610                                 old_size = size_of(state, type);
8611                                 type->elements = index + 1;
8612                                 buf = xmalloc(size_of(state, type), "initializer");
8613                                 memcpy(buf, old_buf, old_size);
8614                                 xfree(old_buf);
8615                         }
8616                         if (value->op == OP_BLOBCONST) {
8617                                 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8618                         }
8619                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8620                                 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8621                         }
8622                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8623                                 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8624                         }
8625                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8626                                 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8627                         }
8628                         else {
8629                                 fprintf(stderr, "%d %d\n",
8630                                         value->op, value_size);
8631                                 internal_error(state, 0, "unhandled constant initializer");
8632                         }
8633                         if (peek(state) == TOK_COMMA) {
8634                                 eat(state, TOK_COMMA);
8635                                 comma = 1;
8636                         }
8637                         index += 1;
8638                 } while(comma && (peek(state) != TOK_RBRACE));
8639                 eat(state, TOK_RBRACE);
8640                 result = triple(state, OP_BLOBCONST, type, 0, 0);
8641                 result->u.blob = buf;
8642         }
8643         return result;
8644 }
8645
8646 static struct triple *function_definition(
8647         struct compile_state *state, struct type *type)
8648 {
8649         struct triple *def, *tmp, *first, *end;
8650         struct hash_entry *ident;
8651         struct type *param;
8652         int i;
8653         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8654                 error(state, 0, "Invalid function header");
8655         }
8656
8657         /* Verify the function type */
8658         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
8659                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8660                 (type->right->field_ident == 0)) {
8661                 error(state, 0, "Invalid function parameters");
8662         }
8663         param = type->right;
8664         i = 0;
8665         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8666                 i++;
8667                 if (!param->left->field_ident) {
8668                         error(state, 0, "No identifier for parameter %d\n", i);
8669                 }
8670                 param = param->right;
8671         }
8672         i++;
8673         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8674                 error(state, 0, "No identifier for paramter %d\n", i);
8675         }
8676         
8677         /* Get a list of statements for this function. */
8678         def = triple(state, OP_LIST, type, 0, 0);
8679
8680         /* Start a new scope for the passed parameters */
8681         start_scope(state);
8682
8683         /* Put a label at the very start of a function */
8684         first = label(state);
8685         RHS(def, 0) = first;
8686
8687         /* Put a label at the very end of a function */
8688         end = label(state);
8689         flatten(state, first, end);
8690
8691         /* Walk through the parameters and create symbol table entries
8692          * for them.
8693          */
8694         param = type->right;
8695         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8696                 ident = param->left->field_ident;
8697                 tmp = variable(state, param->left);
8698                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8699                 flatten(state, end, tmp);
8700                 param = param->right;
8701         }
8702         if ((param->type & TYPE_MASK) != TYPE_VOID) {
8703                 /* And don't forget the last parameter */
8704                 ident = param->field_ident;
8705                 tmp = variable(state, param);
8706                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8707                 flatten(state, end, tmp);
8708         }
8709         /* Add a variable for the return value */
8710         MISC(def, 0) = 0;
8711         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8712                 /* Remove all type qualifiers from the return type */
8713                 tmp = variable(state, clone_type(0, type->left));
8714                 flatten(state, end, tmp);
8715                 /* Remember where the return value is */
8716                 MISC(def, 0) = tmp;
8717         }
8718
8719         /* Remember which function I am compiling.
8720          * Also assume the last defined function is the main function.
8721          */
8722         state->main_function = def;
8723
8724         /* Now get the actual function definition */
8725         compound_statement(state, end);
8726
8727         /* Remove the parameter scope */
8728         end_scope(state);
8729 #if 0
8730         fprintf(stdout, "\n");
8731         loc(stdout, state, 0);
8732         fprintf(stdout, "\n__________ function_definition _________\n");
8733         print_triple(state, def);
8734         fprintf(stdout, "__________ function_definition _________ done\n\n");
8735 #endif
8736
8737         return def;
8738 }
8739
8740 static struct triple *do_decl(struct compile_state *state, 
8741         struct type *type, struct hash_entry *ident)
8742 {
8743         struct triple *def;
8744         def = 0;
8745         /* Clean up the storage types used */
8746         switch (type->type & STOR_MASK) {
8747         case STOR_AUTO:
8748         case STOR_STATIC:
8749                 /* These are the good types I am aiming for */
8750                 break;
8751         case STOR_REGISTER:
8752                 type->type &= ~STOR_MASK;
8753                 type->type |= STOR_AUTO;
8754                 break;
8755         case STOR_EXTERN:
8756                 type->type &= ~STOR_MASK;
8757                 type->type |= STOR_STATIC;
8758                 break;
8759         case STOR_TYPEDEF:
8760                 if (!ident) {
8761                         error(state, 0, "typedef without name");
8762                 }
8763                 symbol(state, ident, &ident->sym_ident, 0, type);
8764                 ident->tok = TOK_TYPE_NAME;
8765                 return 0;
8766                 break;
8767         default:
8768                 internal_error(state, 0, "Undefined storage class");
8769         }
8770         if (((type->type & STOR_MASK) == STOR_STATIC) &&
8771                 ((type->type & QUAL_CONST) == 0)) {
8772                 error(state, 0, "non const static variables not supported");
8773         }
8774         if (ident) {
8775                 def = variable(state, type);
8776                 symbol(state, ident, &ident->sym_ident, def, type);
8777         }
8778         return def;
8779 }
8780
8781 static void decl(struct compile_state *state, struct triple *first)
8782 {
8783         struct type *base_type, *type;
8784         struct hash_entry *ident;
8785         struct triple *def;
8786         int global;
8787         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8788         base_type = decl_specifiers(state);
8789         ident = 0;
8790         type = declarator(state, base_type, &ident, 0);
8791         if (global && ident && (peek(state) == TOK_LBRACE)) {
8792                 /* function */
8793                 def = function_definition(state, type);
8794                 symbol(state, ident, &ident->sym_ident, def, type);
8795         }
8796         else {
8797                 int done;
8798                 flatten(state, first, do_decl(state, type, ident));
8799                 /* type or variable definition */
8800                 do {
8801                         done = 1;
8802                         if (peek(state) == TOK_EQ) {
8803                                 if (!ident) {
8804                                         error(state, 0, "cannot assign to a type");
8805                                 }
8806                                 eat(state, TOK_EQ);
8807                                 flatten(state, first,
8808                                         init_expr(state, 
8809                                                 ident->sym_ident->def, 
8810                                                 initializer(state, type)));
8811                         }
8812                         arrays_complete(state, type);
8813                         if (peek(state) == TOK_COMMA) {
8814                                 eat(state, TOK_COMMA);
8815                                 ident = 0;
8816                                 type = declarator(state, base_type, &ident, 0);
8817                                 flatten(state, first, do_decl(state, type, ident));
8818                                 done = 0;
8819                         }
8820                 } while(!done);
8821                 eat(state, TOK_SEMI);
8822         }
8823 }
8824
8825 static void decls(struct compile_state *state)
8826 {
8827         struct triple *list;
8828         int tok;
8829         list = label(state);
8830         while(1) {
8831                 tok = peek(state);
8832                 if (tok == TOK_EOF) {
8833                         return;
8834                 }
8835                 if (tok == TOK_SPACE) {
8836                         eat(state, TOK_SPACE);
8837                 }
8838                 decl(state, list);
8839                 if (list->next != list) {
8840                         error(state, 0, "global variables not supported");
8841                 }
8842         }
8843 }
8844
8845 /*
8846  * Data structurs for optimation.
8847  */
8848
8849 static void do_use_block(
8850         struct block *used, struct block_set **head, struct block *user, 
8851         int front)
8852 {
8853         struct block_set **ptr, *new;
8854         if (!used)
8855                 return;
8856         if (!user)
8857                 return;
8858         ptr = head;
8859         while(*ptr) {
8860                 if ((*ptr)->member == user) {
8861                         return;
8862                 }
8863                 ptr = &(*ptr)->next;
8864         }
8865         new = xcmalloc(sizeof(*new), "block_set");
8866         new->member = user;
8867         if (front) {
8868                 new->next = *head;
8869                 *head = new;
8870         }
8871         else {
8872                 new->next = 0;
8873                 *ptr = new;
8874         }
8875 }
8876 static void do_unuse_block(
8877         struct block *used, struct block_set **head, struct block *unuser)
8878 {
8879         struct block_set *use, **ptr;
8880         ptr = head;
8881         while(*ptr) {
8882                 use = *ptr;
8883                 if (use->member == unuser) {
8884                         *ptr = use->next;
8885                         memset(use, -1, sizeof(*use));
8886                         xfree(use);
8887                 }
8888                 else {
8889                         ptr = &use->next;
8890                 }
8891         }
8892 }
8893
8894 static void use_block(struct block *used, struct block *user)
8895 {
8896         /* Append new to the head of the list, print_block
8897          * depends on this.
8898          */
8899         do_use_block(used, &used->use, user, 1); 
8900         used->users++;
8901 }
8902 static void unuse_block(struct block *used, struct block *unuser)
8903 {
8904         do_unuse_block(used, &used->use, unuser); 
8905         used->users--;
8906 }
8907
8908 static void idom_block(struct block *idom, struct block *user)
8909 {
8910         do_use_block(idom, &idom->idominates, user, 0);
8911 }
8912
8913 static void unidom_block(struct block *idom, struct block *unuser)
8914 {
8915         do_unuse_block(idom, &idom->idominates, unuser);
8916 }
8917
8918 static void domf_block(struct block *block, struct block *domf)
8919 {
8920         do_use_block(block, &block->domfrontier, domf, 0);
8921 }
8922
8923 static void undomf_block(struct block *block, struct block *undomf)
8924 {
8925         do_unuse_block(block, &block->domfrontier, undomf);
8926 }
8927
8928 static void ipdom_block(struct block *ipdom, struct block *user)
8929 {
8930         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8931 }
8932
8933 static void unipdom_block(struct block *ipdom, struct block *unuser)
8934 {
8935         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8936 }
8937
8938 static void ipdomf_block(struct block *block, struct block *ipdomf)
8939 {
8940         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8941 }
8942
8943 static void unipdomf_block(struct block *block, struct block *unipdomf)
8944 {
8945         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8946 }
8947
8948
8949
8950 static int do_walk_triple(struct compile_state *state,
8951         struct triple *ptr, int depth,
8952         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
8953 {
8954         int result;
8955         result = cb(state, ptr, depth);
8956         if ((result == 0) && (ptr->op == OP_LIST)) {
8957                 struct triple *list;
8958                 list = ptr;
8959                 ptr = RHS(list, 0);
8960                 do {
8961                         result = do_walk_triple(state, ptr, depth + 1, cb);
8962                         if (ptr->next->prev != ptr) {
8963                                 internal_error(state, ptr->next, "bad prev");
8964                         }
8965                         ptr = ptr->next;
8966                         
8967                 } while((result == 0) && (ptr != RHS(list, 0)));
8968         }
8969         return result;
8970 }
8971
8972 static int walk_triple(
8973         struct compile_state *state, 
8974         struct triple *ptr, 
8975         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8976 {
8977         return do_walk_triple(state, ptr, 0, cb);
8978 }
8979
8980 static void do_print_prefix(int depth)
8981 {
8982         int i;
8983         for(i = 0; i < depth; i++) {
8984                 printf("  ");
8985         }
8986 }
8987
8988 #define PRINT_LIST 1
8989 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8990 {
8991         int op;
8992         op = ins->op;
8993         if (op == OP_LIST) {
8994 #if !PRINT_LIST
8995                 return 0;
8996 #endif
8997         }
8998         if ((op == OP_LABEL) && (ins->use)) {
8999                 printf("\n%p:\n", ins);
9000         }
9001         do_print_prefix(depth);
9002         display_triple(stdout, ins);
9003
9004         if ((ins->op == OP_BRANCH) && ins->use) {
9005                 internal_error(state, ins, "branch used?");
9006         }
9007 #if 0
9008         {
9009                 struct triple_set *user;
9010                 for(user = ins->use; user; user = user->next) {
9011                         printf("use: %p\n", user->member);
9012                 }
9013         }
9014 #endif
9015         if (triple_is_branch(state, ins)) {
9016                 printf("\n");
9017         }
9018         return 0;
9019 }
9020
9021 static void print_triple(struct compile_state *state, struct triple *ins)
9022 {
9023         walk_triple(state, ins, do_print_triple);
9024 }
9025
9026 static void print_triples(struct compile_state *state)
9027 {
9028         print_triple(state, state->main_function);
9029 }
9030
9031 struct cf_block {
9032         struct block *block;
9033 };
9034 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9035 {
9036         if (!block || (cf[block->vertex].block == block)) {
9037                 return;
9038         }
9039         cf[block->vertex].block = block;
9040         find_cf_blocks(cf, block->left);
9041         find_cf_blocks(cf, block->right);
9042 }
9043
9044 static void print_control_flow(struct compile_state *state)
9045 {
9046         struct cf_block *cf;
9047         int i;
9048         printf("\ncontrol flow\n");
9049         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9050         find_cf_blocks(cf, state->first_block);
9051
9052         for(i = 1; i <= state->last_vertex; i++) {
9053                 struct block *block;
9054                 block = cf[i].block;
9055                 if (!block)
9056                         continue;
9057                 printf("(%p) %d:", block, block->vertex);
9058                 if (block->left) {
9059                         printf(" %d", block->left->vertex);
9060                 }
9061                 if (block->right && (block->right != block->left)) {
9062                         printf(" %d", block->right->vertex);
9063                 }
9064                 printf("\n");
9065         }
9066
9067         xfree(cf);
9068 }
9069
9070
9071 static struct block *basic_block(struct compile_state *state,
9072         struct triple *first)
9073 {
9074         struct block *block;
9075         struct triple *ptr;
9076         int op;
9077         if (first->op != OP_LABEL) {
9078                 internal_error(state, 0, "block does not start with a label");
9079         }
9080         /* See if this basic block has already been setup */
9081         if (first->u.block != 0) {
9082                 return first->u.block;
9083         }
9084         /* Allocate another basic block structure */
9085         state->last_vertex += 1;
9086         block = xcmalloc(sizeof(*block), "block");
9087         block->first = block->last = first;
9088         block->vertex = state->last_vertex;
9089         ptr = first;
9090         do {
9091                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9092                         break;
9093                 }
9094                 block->last = ptr;
9095                 /* If ptr->u is not used remember where the baic block is */
9096                 if (triple_stores_block(state, ptr)) {
9097                         ptr->u.block = block;
9098                 }
9099                 if (ptr->op == OP_BRANCH) {
9100                         break;
9101                 }
9102                 ptr = ptr->next;
9103         } while (ptr != RHS(state->main_function, 0));
9104         if (ptr == RHS(state->main_function, 0))
9105                 return block;
9106         op = ptr->op;
9107         if (op == OP_LABEL) {
9108                 block->left = basic_block(state, ptr);
9109                 block->right = 0;
9110                 use_block(block->left, block);
9111         }
9112         else if (op == OP_BRANCH) {
9113                 block->left = 0;
9114                 /* Trace the branch target */
9115                 block->right = basic_block(state, TARG(ptr, 0));
9116                 use_block(block->right, block);
9117                 /* If there is a test trace the branch as well */
9118                 if (TRIPLE_RHS(ptr->sizes)) {
9119                         block->left = basic_block(state, ptr->next);
9120                         use_block(block->left, block);
9121                 }
9122         }
9123         else {
9124                 internal_error(state, 0, "Bad basic block split");
9125         }
9126         return block;
9127 }
9128
9129
9130 static void walk_blocks(struct compile_state *state,
9131         void (*cb)(struct compile_state *state, struct block *block, void *arg),
9132         void *arg)
9133 {
9134         struct triple *ptr, *first;
9135         struct block *last_block;
9136         last_block = 0;
9137         first = RHS(state->main_function, 0);
9138         ptr = first;
9139         do {
9140                 struct block *block;
9141                 if (ptr->op == OP_LABEL) {
9142                         block = ptr->u.block;
9143                         if (block && (block != last_block)) {
9144                                 cb(state, block, arg);
9145                         }
9146                         last_block = block;
9147                 }
9148                 ptr = ptr->next;
9149         } while(ptr != first);
9150 }
9151
9152 static void print_block(
9153         struct compile_state *state, struct block *block, void *arg)
9154 {
9155         struct triple *ptr;
9156         FILE *fp = arg;
9157
9158         fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n", 
9159                 block, 
9160                 block->vertex,
9161                 block->left, 
9162                 block->left && block->left->use?block->left->use->member : 0,
9163                 block->right, 
9164                 block->right && block->right->use?block->right->use->member : 0);
9165         if (block->first->op == OP_LABEL) {
9166                 fprintf(fp, "%p:\n", block->first);
9167         }
9168         for(ptr = block->first; ; ptr = ptr->next) {
9169                 struct triple_set *user;
9170                 int op = ptr->op;
9171                 
9172                 if (triple_stores_block(state, ptr)) {
9173                         if (ptr->u.block != block) {
9174                                 internal_error(state, ptr, 
9175                                         "Wrong block pointer: %p\n",
9176                                         ptr->u.block);
9177                         }
9178                 }
9179                 if (op == OP_ADECL) {
9180                         for(user = ptr->use; user; user = user->next) {
9181                                 if (!user->member->u.block) {
9182                                         internal_error(state, user->member, 
9183                                                 "Use %p not in a block?\n",
9184                                                 user->member);
9185                                 }
9186                         }
9187                 }
9188                 display_triple(fp, ptr);
9189
9190 #if 0
9191                 for(user = ptr->use; user; user = user->next) {
9192                         fprintf(fp, "use: %p\n", user->member);
9193                 }
9194 #endif
9195
9196                 /* Sanity checks... */
9197                 valid_ins(state, ptr);
9198                 for(user = ptr->use; user; user = user->next) {
9199                         struct triple *use;
9200                         use = user->member;
9201                         valid_ins(state, use);
9202                         if (triple_stores_block(state, user->member) &&
9203                                 !user->member->u.block) {
9204                                 internal_error(state, user->member,
9205                                         "Use %p not in a block?",
9206                                         user->member);
9207                         }
9208                 }
9209
9210                 if (ptr == block->last)
9211                         break;
9212         }
9213         fprintf(fp,"\n");
9214 }
9215
9216
9217 static void print_blocks(struct compile_state *state, FILE *fp)
9218 {
9219         fprintf(fp, "--------------- blocks ---------------\n");
9220         walk_blocks(state, print_block, fp);
9221 }
9222
9223 static void prune_nonblock_triples(struct compile_state *state)
9224 {
9225         struct block *block;
9226         struct triple *first, *ins, *next;
9227         /* Delete the triples not in a basic block */
9228         first = RHS(state->main_function, 0);
9229         block = 0;
9230         ins = first;
9231         do {
9232                 next = ins->next;
9233                 if (ins->op == OP_LABEL) {
9234                         block = ins->u.block;
9235                 }
9236                 if (!block) {
9237                         release_triple(state, ins);
9238                 }
9239                 ins = next;
9240         } while(ins != first);
9241 }
9242
9243 static void setup_basic_blocks(struct compile_state *state)
9244 {
9245         if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9246                 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9247                 internal_error(state, 0, "ins will not store block?");
9248         }
9249         /* Find the basic blocks */
9250         state->last_vertex = 0;
9251         state->first_block = basic_block(state, RHS(state->main_function,0));
9252         /* Delete the triples not in a basic block */
9253         prune_nonblock_triples(state);
9254         /* Find the last basic block */
9255         state->last_block = RHS(state->main_function, 0)->prev->u.block;
9256         if (!state->last_block) {
9257                 internal_error(state, 0, "end not used?");
9258         }
9259         /* Insert an extra unused edge from start to the end 
9260          * This helps with reverse control flow calculations.
9261          */
9262         use_block(state->first_block, state->last_block);
9263         /* If we are debugging print what I have just done */
9264         if (state->debug & DEBUG_BASIC_BLOCKS) {
9265                 print_blocks(state, stdout);
9266                 print_control_flow(state);
9267         }
9268 }
9269
9270 static void free_basic_block(struct compile_state *state, struct block *block)
9271 {
9272         struct block_set *entry, *next;
9273         struct block *child;
9274         if (!block) {
9275                 return;
9276         }
9277         if (block->vertex == -1) {
9278                 return;
9279         }
9280         block->vertex = -1;
9281         if (block->left) {
9282                 unuse_block(block->left, block);
9283         }
9284         if (block->right) {
9285                 unuse_block(block->right, block);
9286         }
9287         if (block->idom) {
9288                 unidom_block(block->idom, block);
9289         }
9290         block->idom = 0;
9291         if (block->ipdom) {
9292                 unipdom_block(block->ipdom, block);
9293         }
9294         block->ipdom = 0;
9295         for(entry = block->use; entry; entry = next) {
9296                 next = entry->next;
9297                 child = entry->member;
9298                 unuse_block(block, child);
9299                 if (child->left == block) {
9300                         child->left = 0;
9301                 }
9302                 if (child->right == block) {
9303                         child->right = 0;
9304                 }
9305         }
9306         for(entry = block->idominates; entry; entry = next) {
9307                 next = entry->next;
9308                 child = entry->member;
9309                 unidom_block(block, child);
9310                 child->idom = 0;
9311         }
9312         for(entry = block->domfrontier; entry; entry = next) {
9313                 next = entry->next;
9314                 child = entry->member;
9315                 undomf_block(block, child);
9316         }
9317         for(entry = block->ipdominates; entry; entry = next) {
9318                 next = entry->next;
9319                 child = entry->member;
9320                 unipdom_block(block, child);
9321                 child->ipdom = 0;
9322         }
9323         for(entry = block->ipdomfrontier; entry; entry = next) {
9324                 next = entry->next;
9325                 child = entry->member;
9326                 unipdomf_block(block, child);
9327         }
9328         if (block->users != 0) {
9329                 internal_error(state, 0, "block still has users");
9330         }
9331         free_basic_block(state, block->left);
9332         block->left = 0;
9333         free_basic_block(state, block->right);
9334         block->right = 0;
9335         memset(block, -1, sizeof(*block));
9336         xfree(block);
9337 }
9338
9339 static void free_basic_blocks(struct compile_state *state)
9340 {
9341         struct triple *first, *ins;
9342         free_basic_block(state, state->first_block);
9343         state->last_vertex = 0;
9344         state->first_block = state->last_block = 0;
9345         first = RHS(state->main_function, 0);
9346         ins = first;
9347         do {
9348                 if (triple_stores_block(state, ins)) {
9349                         ins->u.block = 0;
9350                 }
9351                 ins = ins->next;
9352         } while(ins != first);
9353         
9354 }
9355
9356 struct sdom_block {
9357         struct block *block;
9358         struct sdom_block *sdominates;
9359         struct sdom_block *sdom_next;
9360         struct sdom_block *sdom;
9361         struct sdom_block *label;
9362         struct sdom_block *parent;
9363         struct sdom_block *ancestor;
9364         int vertex;
9365 };
9366
9367
9368 static void unsdom_block(struct sdom_block *block)
9369 {
9370         struct sdom_block **ptr;
9371         if (!block->sdom_next) {
9372                 return;
9373         }
9374         ptr = &block->sdom->sdominates;
9375         while(*ptr) {
9376                 if ((*ptr) == block) {
9377                         *ptr = block->sdom_next;
9378                         return;
9379                 }
9380                 ptr = &(*ptr)->sdom_next;
9381         }
9382 }
9383
9384 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9385 {
9386         unsdom_block(block);
9387         block->sdom = sdom;
9388         block->sdom_next = sdom->sdominates;
9389         sdom->sdominates = block;
9390 }
9391
9392
9393
9394 static int initialize_sdblock(struct sdom_block *sd,
9395         struct block *parent, struct block *block, int vertex)
9396 {
9397         if (!block || (sd[block->vertex].block == block)) {
9398                 return vertex;
9399         }
9400         vertex += 1;
9401         /* Renumber the blocks in a convinient fashion */
9402         block->vertex = vertex;
9403         sd[vertex].block    = block;
9404         sd[vertex].sdom     = &sd[vertex];
9405         sd[vertex].label    = &sd[vertex];
9406         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9407         sd[vertex].ancestor = 0;
9408         sd[vertex].vertex   = vertex;
9409         vertex = initialize_sdblock(sd, block, block->left, vertex);
9410         vertex = initialize_sdblock(sd, block, block->right, vertex);
9411         return vertex;
9412 }
9413
9414 static int initialize_sdpblock(struct sdom_block *sd,
9415         struct block *parent, struct block *block, int vertex)
9416 {
9417         struct block_set *user;
9418         if (!block || (sd[block->vertex].block == block)) {
9419                 return vertex;
9420         }
9421         vertex += 1;
9422         /* Renumber the blocks in a convinient fashion */
9423         block->vertex = vertex;
9424         sd[vertex].block    = block;
9425         sd[vertex].sdom     = &sd[vertex];
9426         sd[vertex].label    = &sd[vertex];
9427         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9428         sd[vertex].ancestor = 0;
9429         sd[vertex].vertex   = vertex;
9430         for(user = block->use; user; user = user->next) {
9431                 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9432         }
9433         return vertex;
9434 }
9435
9436 static void compress_ancestors(struct sdom_block *v)
9437 {
9438         /* This procedure assumes ancestor(v) != 0 */
9439         /* if (ancestor(ancestor(v)) != 0) {
9440          *      compress(ancestor(ancestor(v)));
9441          *      if (semi(label(ancestor(v))) < semi(label(v))) {
9442          *              label(v) = label(ancestor(v));
9443          *      }
9444          *      ancestor(v) = ancestor(ancestor(v));
9445          * }
9446          */
9447         if (!v->ancestor) {
9448                 return;
9449         }
9450         if (v->ancestor->ancestor) {
9451                 compress_ancestors(v->ancestor->ancestor);
9452                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9453                         v->label = v->ancestor->label;
9454                 }
9455                 v->ancestor = v->ancestor->ancestor;
9456         }
9457 }
9458
9459 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9460 {
9461         int i;
9462         /* // step 2 
9463          *  for each v <= pred(w) {
9464          *      u = EVAL(v);
9465          *      if (semi[u] < semi[w] { 
9466          *              semi[w] = semi[u]; 
9467          *      } 
9468          * }
9469          * add w to bucket(vertex(semi[w]));
9470          * LINK(parent(w), w);
9471          *
9472          * // step 3
9473          * for each v <= bucket(parent(w)) {
9474          *      delete v from bucket(parent(w));
9475          *      u = EVAL(v);
9476          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9477          * }
9478          */
9479         for(i = state->last_vertex; i >= 2; i--) {
9480                 struct sdom_block *v, *parent, *next;
9481                 struct block_set *user;
9482                 struct block *block;
9483                 block = sd[i].block;
9484                 parent = sd[i].parent;
9485                 /* Step 2 */
9486                 for(user = block->use; user; user = user->next) {
9487                         struct sdom_block *v, *u;
9488                         v = &sd[user->member->vertex];
9489                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9490                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9491                                 sd[i].sdom = u->sdom;
9492                         }
9493                 }
9494                 sdom_block(sd[i].sdom, &sd[i]);
9495                 sd[i].ancestor = parent;
9496                 /* Step 3 */
9497                 for(v = parent->sdominates; v; v = next) {
9498                         struct sdom_block *u;
9499                         next = v->sdom_next;
9500                         unsdom_block(v);
9501                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9502                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
9503                                 u->block : parent->block;
9504                 }
9505         }
9506 }
9507
9508 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9509 {
9510         int i;
9511         /* // step 2 
9512          *  for each v <= pred(w) {
9513          *      u = EVAL(v);
9514          *      if (semi[u] < semi[w] { 
9515          *              semi[w] = semi[u]; 
9516          *      } 
9517          * }
9518          * add w to bucket(vertex(semi[w]));
9519          * LINK(parent(w), w);
9520          *
9521          * // step 3
9522          * for each v <= bucket(parent(w)) {
9523          *      delete v from bucket(parent(w));
9524          *      u = EVAL(v);
9525          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9526          * }
9527          */
9528         for(i = state->last_vertex; i >= 2; i--) {
9529                 struct sdom_block *u, *v, *parent, *next;
9530                 struct block *block;
9531                 block = sd[i].block;
9532                 parent = sd[i].parent;
9533                 /* Step 2 */
9534                 if (block->left) {
9535                         v = &sd[block->left->vertex];
9536                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9537                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9538                                 sd[i].sdom = u->sdom;
9539                         }
9540                 }
9541                 if (block->right && (block->right != block->left)) {
9542                         v = &sd[block->right->vertex];
9543                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9544                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9545                                 sd[i].sdom = u->sdom;
9546                         }
9547                 }
9548                 sdom_block(sd[i].sdom, &sd[i]);
9549                 sd[i].ancestor = parent;
9550                 /* Step 3 */
9551                 for(v = parent->sdominates; v; v = next) {
9552                         struct sdom_block *u;
9553                         next = v->sdom_next;
9554                         unsdom_block(v);
9555                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9556                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
9557                                 u->block : parent->block;
9558                 }
9559         }
9560 }
9561
9562 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9563 {
9564         int i;
9565         for(i = 2; i <= state->last_vertex; i++) {
9566                 struct block *block;
9567                 block = sd[i].block;
9568                 if (block->idom->vertex != sd[i].sdom->vertex) {
9569                         block->idom = block->idom->idom;
9570                 }
9571                 idom_block(block->idom, block);
9572         }
9573         sd[1].block->idom = 0;
9574 }
9575
9576 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9577 {
9578         int i;
9579         for(i = 2; i <= state->last_vertex; i++) {
9580                 struct block *block;
9581                 block = sd[i].block;
9582                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9583                         block->ipdom = block->ipdom->ipdom;
9584                 }
9585                 ipdom_block(block->ipdom, block);
9586         }
9587         sd[1].block->ipdom = 0;
9588 }
9589
9590         /* Theorem 1:
9591          *   Every vertex of a flowgraph G = (V, E, r) except r has
9592          *   a unique immediate dominator.  
9593          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9594          *   rooted at r, called the dominator tree of G, such that 
9595          *   v dominates w if and only if v is a proper ancestor of w in
9596          *   the dominator tree.
9597          */
9598         /* Lemma 1:  
9599          *   If v and w are vertices of G such that v <= w,
9600          *   than any path from v to w must contain a common ancestor
9601          *   of v and w in T.
9602          */
9603         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
9604         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
9605         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
9606         /* Theorem 2:
9607          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
9608          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
9609          */
9610         /* Theorem 3:
9611          *   Let w != r and let u be a vertex for which sdom(u) is 
9612          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9613          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9614          */
9615         /* Lemma 5:  Let vertices v,w satisfy v -> w.
9616          *           Then v -> idom(w) or idom(w) -> idom(v)
9617          */
9618
9619 static void find_immediate_dominators(struct compile_state *state)
9620 {
9621         struct sdom_block *sd;
9622         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9623          *           vi > w for (1 <= i <= k - 1}
9624          */
9625         /* Theorem 4:
9626          *   For any vertex w != r.
9627          *   sdom(w) = min(
9628          *                 {v|(v,w) <= E  and v < w } U 
9629          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9630          */
9631         /* Corollary 1:
9632          *   Let w != r and let u be a vertex for which sdom(u) is 
9633          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9634          *   Then:
9635          *                   { sdom(w) if sdom(w) = sdom(u),
9636          *        idom(w) = {
9637          *                   { idom(u) otherwise
9638          */
9639         /* The algorithm consists of the following 4 steps.
9640          * Step 1.  Carry out a depth-first search of the problem graph.  
9641          *    Number the vertices from 1 to N as they are reached during
9642          *    the search.  Initialize the variables used in succeeding steps.
9643          * Step 2.  Compute the semidominators of all vertices by applying
9644          *    theorem 4.   Carry out the computation vertex by vertex in
9645          *    decreasing order by number.
9646          * Step 3.  Implicitly define the immediate dominator of each vertex
9647          *    by applying Corollary 1.
9648          * Step 4.  Explicitly define the immediate dominator of each vertex,
9649          *    carrying out the computation vertex by vertex in increasing order
9650          *    by number.
9651          */
9652         /* Step 1 initialize the basic block information */
9653         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9654         initialize_sdblock(sd, 0, state->first_block, 0);
9655 #if 0
9656         sd[1].size  = 0;
9657         sd[1].label = 0;
9658         sd[1].sdom  = 0;
9659 #endif
9660         /* Step 2 compute the semidominators */
9661         /* Step 3 implicitly define the immediate dominator of each vertex */
9662         compute_sdom(state, sd);
9663         /* Step 4 explicitly define the immediate dominator of each vertex */
9664         compute_idom(state, sd);
9665         xfree(sd);
9666 }
9667
9668 static void find_post_dominators(struct compile_state *state)
9669 {
9670         struct sdom_block *sd;
9671         /* Step 1 initialize the basic block information */
9672         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9673
9674         initialize_sdpblock(sd, 0, state->last_block, 0);
9675
9676         /* Step 2 compute the semidominators */
9677         /* Step 3 implicitly define the immediate dominator of each vertex */
9678         compute_spdom(state, sd);
9679         /* Step 4 explicitly define the immediate dominator of each vertex */
9680         compute_ipdom(state, sd);
9681         xfree(sd);
9682 }
9683
9684
9685
9686 static void find_block_domf(struct compile_state *state, struct block *block)
9687 {
9688         struct block *child;
9689         struct block_set *user;
9690         if (block->domfrontier != 0) {
9691                 internal_error(state, block->first, "domfrontier present?");
9692         }
9693         for(user = block->idominates; user; user = user->next) {
9694                 child = user->member;
9695                 if (child->idom != block) {
9696                         internal_error(state, block->first, "bad idom");
9697                 }
9698                 find_block_domf(state, child);
9699         }
9700         if (block->left && block->left->idom != block) {
9701                 domf_block(block, block->left);
9702         }
9703         if (block->right && block->right->idom != block) {
9704                 domf_block(block, block->right);
9705         }
9706         for(user = block->idominates; user; user = user->next) {
9707                 struct block_set *frontier;
9708                 child = user->member;
9709                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9710                         if (frontier->member->idom != block) {
9711                                 domf_block(block, frontier->member);
9712                         }
9713                 }
9714         }
9715 }
9716
9717 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9718 {
9719         struct block *child;
9720         struct block_set *user;
9721         if (block->ipdomfrontier != 0) {
9722                 internal_error(state, block->first, "ipdomfrontier present?");
9723         }
9724         for(user = block->ipdominates; user; user = user->next) {
9725                 child = user->member;
9726                 if (child->ipdom != block) {
9727                         internal_error(state, block->first, "bad ipdom");
9728                 }
9729                 find_block_ipdomf(state, child);
9730         }
9731         if (block->left && block->left->ipdom != block) {
9732                 ipdomf_block(block, block->left);
9733         }
9734         if (block->right && block->right->ipdom != block) {
9735                 ipdomf_block(block, block->right);
9736         }
9737         for(user = block->idominates; user; user = user->next) {
9738                 struct block_set *frontier;
9739                 child = user->member;
9740                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9741                         if (frontier->member->ipdom != block) {
9742                                 ipdomf_block(block, frontier->member);
9743                         }
9744                 }
9745         }
9746 }
9747
9748 static void print_dominated(
9749         struct compile_state *state, struct block *block, void *arg)
9750 {
9751         struct block_set *user;
9752         FILE *fp = arg;
9753
9754         fprintf(fp, "%d:", block->vertex);
9755         for(user = block->idominates; user; user = user->next) {
9756                 fprintf(fp, " %d", user->member->vertex);
9757                 if (user->member->idom != block) {
9758                         internal_error(state, user->member->first, "bad idom");
9759                 }
9760         }
9761         fprintf(fp,"\n");
9762 }
9763
9764 static void print_dominators(struct compile_state *state, FILE *fp)
9765 {
9766         fprintf(fp, "\ndominates\n");
9767         walk_blocks(state, print_dominated, fp);
9768 }
9769
9770
9771 static int print_frontiers(
9772         struct compile_state *state, struct block *block, int vertex)
9773 {
9774         struct block_set *user;
9775
9776         if (!block || (block->vertex != vertex + 1)) {
9777                 return vertex;
9778         }
9779         vertex += 1;
9780
9781         printf("%d:", block->vertex);
9782         for(user = block->domfrontier; user; user = user->next) {
9783                 printf(" %d", user->member->vertex);
9784         }
9785         printf("\n");
9786
9787         vertex = print_frontiers(state, block->left, vertex);
9788         vertex = print_frontiers(state, block->right, vertex);
9789         return vertex;
9790 }
9791 static void print_dominance_frontiers(struct compile_state *state)
9792 {
9793         printf("\ndominance frontiers\n");
9794         print_frontiers(state, state->first_block, 0);
9795         
9796 }
9797
9798 static void analyze_idominators(struct compile_state *state)
9799 {
9800         /* Find the immediate dominators */
9801         find_immediate_dominators(state);
9802         /* Find the dominance frontiers */
9803         find_block_domf(state, state->first_block);
9804         /* If debuging print the print what I have just found */
9805         if (state->debug & DEBUG_FDOMINATORS) {
9806                 print_dominators(state, stdout);
9807                 print_dominance_frontiers(state);
9808                 print_control_flow(state);
9809         }
9810 }
9811
9812
9813
9814 static void print_ipdominated(
9815         struct compile_state *state, struct block *block, void *arg)
9816 {
9817         struct block_set *user;
9818         FILE *fp = arg;
9819
9820         fprintf(fp, "%d:", block->vertex);
9821         for(user = block->ipdominates; user; user = user->next) {
9822                 fprintf(fp, " %d", user->member->vertex);
9823                 if (user->member->ipdom != block) {
9824                         internal_error(state, user->member->first, "bad ipdom");
9825                 }
9826         }
9827         fprintf(fp, "\n");
9828 }
9829
9830 static void print_ipdominators(struct compile_state *state, FILE *fp)
9831 {
9832         fprintf(fp, "\nipdominates\n");
9833         walk_blocks(state, print_ipdominated, fp);
9834 }
9835
9836 static int print_pfrontiers(
9837         struct compile_state *state, struct block *block, int vertex)
9838 {
9839         struct block_set *user;
9840
9841         if (!block || (block->vertex != vertex + 1)) {
9842                 return vertex;
9843         }
9844         vertex += 1;
9845
9846         printf("%d:", block->vertex);
9847         for(user = block->ipdomfrontier; user; user = user->next) {
9848                 printf(" %d", user->member->vertex);
9849         }
9850         printf("\n");
9851         for(user = block->use; user; user = user->next) {
9852                 vertex = print_pfrontiers(state, user->member, vertex);
9853         }
9854         return vertex;
9855 }
9856 static void print_ipdominance_frontiers(struct compile_state *state)
9857 {
9858         printf("\nipdominance frontiers\n");
9859         print_pfrontiers(state, state->last_block, 0);
9860         
9861 }
9862
9863 static void analyze_ipdominators(struct compile_state *state)
9864 {
9865         /* Find the post dominators */
9866         find_post_dominators(state);
9867         /* Find the control dependencies (post dominance frontiers) */
9868         find_block_ipdomf(state, state->last_block);
9869         /* If debuging print the print what I have just found */
9870         if (state->debug & DEBUG_RDOMINATORS) {
9871                 print_ipdominators(state, stdout);
9872                 print_ipdominance_frontiers(state);
9873                 print_control_flow(state);
9874         }
9875 }
9876
9877 static int bdominates(struct compile_state *state,
9878         struct block *dom, struct block *sub)
9879 {
9880         while(sub && (sub != dom)) {
9881                 sub = sub->idom;
9882         }
9883         return sub == dom;
9884 }
9885
9886 static int tdominates(struct compile_state *state,
9887         struct triple *dom, struct triple *sub)
9888 {
9889         struct block *bdom, *bsub;
9890         int result;
9891         bdom = block_of_triple(state, dom);
9892         bsub = block_of_triple(state, sub);
9893         if (bdom != bsub) {
9894                 result = bdominates(state, bdom, bsub);
9895         } 
9896         else {
9897                 struct triple *ins;
9898                 ins = sub;
9899                 while((ins != bsub->first) && (ins != dom)) {
9900                         ins = ins->prev;
9901                 }
9902                 result = (ins == dom);
9903         }
9904         return result;
9905 }
9906
9907 static void insert_phi_operations(struct compile_state *state)
9908 {
9909         size_t size;
9910         struct triple *first;
9911         int *has_already, *work;
9912         struct block *work_list, **work_list_tail;
9913         int iter;
9914         struct triple *var;
9915
9916         size = sizeof(int) * (state->last_vertex + 1);
9917         has_already = xcmalloc(size, "has_already");
9918         work =        xcmalloc(size, "work");
9919         iter = 0;
9920
9921         first = RHS(state->main_function, 0);
9922         for(var = first->next; var != first ; var = var->next) {
9923                 struct block *block;
9924                 struct triple_set *user;
9925                 if ((var->op != OP_ADECL) || !var->use) {
9926                         continue;
9927                 }
9928                 iter += 1;
9929                 work_list = 0;
9930                 work_list_tail = &work_list;
9931                 for(user = var->use; user; user = user->next) {
9932                         if (user->member->op == OP_READ) {
9933                                 continue;
9934                         }
9935                         if (user->member->op != OP_WRITE) {
9936                                 internal_error(state, user->member, 
9937                                         "bad variable access");
9938                         }
9939                         block = user->member->u.block;
9940                         if (!block) {
9941                                 warning(state, user->member, "dead code");
9942                         }
9943                         if (work[block->vertex] >= iter) {
9944                                 continue;
9945                         }
9946                         work[block->vertex] = iter;
9947                         *work_list_tail = block;
9948                         block->work_next = 0;
9949                         work_list_tail = &block->work_next;
9950                 }
9951                 for(block = work_list; block; block = block->work_next) {
9952                         struct block_set *df;
9953                         for(df = block->domfrontier; df; df = df->next) {
9954                                 struct triple *phi;
9955                                 struct block *front;
9956                                 int in_edges;
9957                                 front = df->member;
9958
9959                                 if (has_already[front->vertex] >= iter) {
9960                                         continue;
9961                                 }
9962                                 /* Count how many edges flow into this block */
9963                                 in_edges = front->users;
9964                                 /* Insert a phi function for this variable */
9965                                 phi = alloc_triple(
9966                                         state, OP_PHI, var->type, -1, in_edges, 
9967                                         front->first->filename, 
9968                                         front->first->line,
9969                                         front->first->col);
9970                                 phi->u.block = front;
9971                                 MISC(phi, 0) = var;
9972                                 use_triple(var, phi);
9973                                 /* Insert the phi functions immediately after the label */
9974                                 insert_triple(state, front->first->next, phi);
9975                                 if (front->first == front->last) {
9976                                         front->last = front->first->next;
9977                                 }
9978                                 has_already[front->vertex] = iter;
9979
9980                                 /* If necessary plan to visit the basic block */
9981                                 if (work[front->vertex] >= iter) {
9982                                         continue;
9983                                 }
9984                                 work[front->vertex] = iter;
9985                                 *work_list_tail = front;
9986                                 front->work_next = 0;
9987                                 work_list_tail = &front->work_next;
9988                         }
9989                 }
9990         }
9991         xfree(has_already);
9992         xfree(work);
9993 }
9994
9995 /*
9996  * C(V)
9997  * S(V)
9998  */
9999 static void fixup_block_phi_variables(
10000         struct compile_state *state, struct block *parent, struct block *block)
10001 {
10002         struct block_set *set;
10003         struct triple *ptr;
10004         int edge;
10005         if (!parent || !block)
10006                 return;
10007         /* Find the edge I am coming in on */
10008         edge = 0;
10009         for(set = block->use; set; set = set->next, edge++) {
10010                 if (set->member == parent) {
10011                         break;
10012                 }
10013         }
10014         if (!set) {
10015                 internal_error(state, 0, "phi input is not on a control predecessor");
10016         }
10017         for(ptr = block->first; ; ptr = ptr->next) {
10018                 if (ptr->op == OP_PHI) {
10019                         struct triple *var, *val, **slot;
10020                         var = MISC(ptr, 0);
10021                         if (!var) {
10022                                 internal_error(state, ptr, "no var???");
10023                         }
10024                         /* Find the current value of the variable */
10025                         val = var->use->member;
10026                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10027                                 internal_error(state, val, "bad value in phi");
10028                         }
10029                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
10030                                 internal_error(state, ptr, "edges > phi rhs");
10031                         }
10032                         slot = &RHS(ptr, edge);
10033                         if ((*slot != 0) && (*slot != val)) {
10034                                 internal_error(state, ptr, "phi already bound on this edge");
10035                         }
10036                         *slot = val;
10037                         use_triple(val, ptr);
10038                 }
10039                 if (ptr == block->last) {
10040                         break;
10041                 }
10042         }
10043 }
10044
10045
10046 static void rename_block_variables(
10047         struct compile_state *state, struct block *block)
10048 {
10049         struct block_set *user;
10050         struct triple *ptr, *next, *last;
10051         int done;
10052         if (!block)
10053                 return;
10054         last = block->first;
10055         done = 0;
10056         for(ptr = block->first; !done; ptr = next) {
10057                 next = ptr->next;
10058                 if (ptr == block->last) {
10059                         done = 1;
10060                 }
10061                 /* RHS(A) */
10062                 if (ptr->op == OP_READ) {
10063                         struct triple *var, *val;
10064                         var = RHS(ptr, 0);
10065                         unuse_triple(var, ptr);
10066                         if (!var->use) {
10067                                 error(state, ptr, "variable used without being set");
10068                         }
10069                         /* Find the current value of the variable */
10070                         val = var->use->member;
10071                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10072                                 internal_error(state, val, "bad value in read");
10073                         }
10074                         propogate_use(state, ptr, val);
10075                         release_triple(state, ptr);
10076                         continue;
10077                 }
10078                 /* LHS(A) */
10079                 if (ptr->op == OP_WRITE) {
10080                         struct triple *var, *val;
10081                         var = LHS(ptr, 0);
10082                         val = RHS(ptr, 0);
10083                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10084                                 internal_error(state, val, "bad value in write");
10085                         }
10086                         propogate_use(state, ptr, val);
10087                         unuse_triple(var, ptr);
10088                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
10089                         push_triple(var, val);
10090                 }
10091                 if (ptr->op == OP_PHI) {
10092                         struct triple *var;
10093                         var = MISC(ptr, 0);
10094                         /* Push OP_PHI onto a stack of variable uses */
10095                         push_triple(var, ptr);
10096                 }
10097                 last = ptr;
10098         }
10099         block->last = last;
10100
10101         /* Fixup PHI functions in the cf successors */
10102         fixup_block_phi_variables(state, block, block->left);
10103         fixup_block_phi_variables(state, block, block->right);
10104         /* rename variables in the dominated nodes */
10105         for(user = block->idominates; user; user = user->next) {
10106                 rename_block_variables(state, user->member);
10107         }
10108         /* pop the renamed variable stack */
10109         last = block->first;
10110         done = 0;
10111         for(ptr = block->first; !done ; ptr = next) {
10112                 next = ptr->next;
10113                 if (ptr == block->last) {
10114                         done = 1;
10115                 }
10116                 if (ptr->op == OP_WRITE) {
10117                         struct triple *var;
10118                         var = LHS(ptr, 0);
10119                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10120                         pop_triple(var, RHS(ptr, 0));
10121                         release_triple(state, ptr);
10122                         continue;
10123                 }
10124                 if (ptr->op == OP_PHI) {
10125                         struct triple *var;
10126                         var = MISC(ptr, 0);
10127                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10128                         pop_triple(var, ptr);
10129                 }
10130                 last = ptr;
10131         }
10132         block->last = last;
10133 }
10134
10135 static void prune_block_variables(struct compile_state *state,
10136         struct block *block)
10137 {
10138         struct block_set *user;
10139         struct triple *next, *last, *ptr;
10140         int done;
10141         last = block->first;
10142         done = 0;
10143         for(ptr = block->first; !done; ptr = next) {
10144                 next = ptr->next;
10145                 if (ptr == block->last) {
10146                         done = 1;
10147                 }
10148                 if (ptr->op == OP_ADECL) {
10149                         struct triple_set *user, *next;
10150                         for(user = ptr->use; user; user = next) {
10151                                 struct triple *use;
10152                                 next = user->next;
10153                                 use = user->member;
10154                                 if (use->op != OP_PHI) {
10155                                         internal_error(state, use, "decl still used");
10156                                 }
10157                                 if (MISC(use, 0) != ptr) {
10158                                         internal_error(state, use, "bad phi use of decl");
10159                                 }
10160                                 unuse_triple(ptr, use);
10161                                 MISC(use, 0) = 0;
10162                         }
10163                         release_triple(state, ptr);
10164                         continue;
10165                 }
10166                 last = ptr;
10167         }
10168         block->last = last;
10169         for(user = block->idominates; user; user = user->next) {
10170                 prune_block_variables(state, user->member);
10171         }
10172 }
10173
10174 static void transform_to_ssa_form(struct compile_state *state)
10175 {
10176         insert_phi_operations(state);
10177 #if 0
10178         printf("@%s:%d\n", __FILE__, __LINE__);
10179         print_blocks(state, stdout);
10180 #endif
10181         rename_block_variables(state, state->first_block);
10182         prune_block_variables(state, state->first_block);
10183 }
10184
10185
10186 static void clear_vertex(
10187         struct compile_state *state, struct block *block, void *arg)
10188 {
10189         block->vertex = 0;
10190 }
10191
10192 static void mark_live_block(
10193         struct compile_state *state, struct block *block, int *next_vertex)
10194 {
10195         /* See if this is a block that has not been marked */
10196         if (block->vertex != 0) {
10197                 return;
10198         }
10199         block->vertex = *next_vertex;
10200         *next_vertex += 1;
10201         if (triple_is_branch(state, block->last)) {
10202                 struct triple **targ;
10203                 targ = triple_targ(state, block->last, 0);
10204                 for(; targ; targ = triple_targ(state, block->last, targ)) {
10205                         if (!*targ) {
10206                                 continue;
10207                         }
10208                         if (!triple_stores_block(state, *targ)) {
10209                                 internal_error(state, 0, "bad targ");
10210                         }
10211                         mark_live_block(state, (*targ)->u.block, next_vertex);
10212                 }
10213         }
10214         else if (block->last->next != RHS(state->main_function, 0)) {
10215                 struct triple *ins;
10216                 ins = block->last->next;
10217                 if (!triple_stores_block(state, ins)) {
10218                         internal_error(state, 0, "bad block start");
10219                 }
10220                 mark_live_block(state, ins->u.block, next_vertex);
10221         }
10222 }
10223
10224 static void transform_from_ssa_form(struct compile_state *state)
10225 {
10226         /* To get out of ssa form we insert moves on the incoming
10227          * edges to blocks containting phi functions.
10228          */
10229         struct triple *first;
10230         struct triple *phi, *next;
10231         int next_vertex;
10232
10233         /* Walk the control flow to see which blocks remain alive */
10234         walk_blocks(state, clear_vertex, 0);
10235         next_vertex = 1;
10236         mark_live_block(state, state->first_block, &next_vertex);
10237
10238         /* Walk all of the operations to find the phi functions */
10239         first = RHS(state->main_function, 0);
10240         for(phi = first->next; phi != first ; phi = next) {
10241                 struct block_set *set;
10242                 struct block *block;
10243                 struct triple **slot;
10244                 struct triple *var, *read;
10245                 struct triple_set *use, *use_next;
10246                 int edge, used;
10247                 next = phi->next;
10248                 if (phi->op != OP_PHI) {
10249                         continue;
10250                 }
10251                 block = phi->u.block;
10252                 slot  = &RHS(phi, 0);
10253
10254                 /* Forget uses from code in dead blocks */
10255                 for(use = phi->use; use; use = use_next) {
10256                         struct block *ublock;
10257                         struct triple **expr;
10258                         use_next = use->next;
10259                         ublock = block_of_triple(state, use->member);
10260                         if ((use->member == phi) || (ublock->vertex != 0)) {
10261                                 continue;
10262                         }
10263                         expr = triple_rhs(state, use->member, 0);
10264                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
10265                                 if (*expr == phi) {
10266                                         *expr = 0;
10267                                 }
10268                         }
10269                         unuse_triple(phi, use->member);
10270                 }
10271
10272                 /* A variable to replace the phi function */
10273                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10274                 /* A read of the single value that is set into the variable */
10275                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10276                 use_triple(var, read);
10277
10278                 /* Replaces uses of the phi with variable reads */
10279                 propogate_use(state, phi, read);
10280
10281                 /* Walk all of the incoming edges/blocks and insert moves.
10282                  */
10283                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10284                         struct block *eblock;
10285                         struct triple *move;
10286                         struct triple *val;
10287                         eblock = set->member;
10288                         val = slot[edge];
10289                         slot[edge] = 0;
10290                         unuse_triple(val, phi);
10291
10292                         if (!val || (val == &zero_triple) ||
10293                                 (block->vertex == 0) || (eblock->vertex == 0) ||
10294                                 (val == phi) || (val == read)) {
10295                                 continue;
10296                         }
10297                         
10298                         move = post_triple(state, 
10299                                 val, OP_WRITE, phi->type, var, val);
10300                         use_triple(val, move);
10301                         use_triple(var, move);
10302                 }               
10303                 /* See if there are any writers of var */
10304                 used = 0;
10305                 for(use = var->use; use; use = use->next) {
10306                         struct triple **expr;
10307                         expr = triple_lhs(state, use->member, 0);
10308                         for(; expr; expr = triple_lhs(state, use->member, expr)) {
10309                                 if (*expr == var) {
10310                                         used = 1;
10311                                 }
10312                         }
10313                 }
10314                 /* If var is not used free it */
10315                 if (!used) {
10316                         unuse_triple(var, read);
10317                         free_triple(state, read);
10318                         free_triple(state, var);
10319                 }
10320
10321                 /* Release the phi function */
10322                 release_triple(state, phi);
10323         }
10324         
10325 }
10326
10327
10328 /* 
10329  * Register conflict resolution
10330  * =========================================================
10331  */
10332
10333 static struct reg_info find_def_color(
10334         struct compile_state *state, struct triple *def)
10335 {
10336         struct triple_set *set;
10337         struct reg_info info;
10338         info.reg = REG_UNSET;
10339         info.regcm = 0;
10340         if (!triple_is_def(state, def)) {
10341                 return info;
10342         }
10343         info = arch_reg_lhs(state, def, 0);
10344         if (info.reg >= MAX_REGISTERS) {
10345                 info.reg = REG_UNSET;
10346         }
10347         for(set = def->use; set; set = set->next) {
10348                 struct reg_info tinfo;
10349                 int i;
10350                 i = find_rhs_use(state, set->member, def);
10351                 if (i < 0) {
10352                         continue;
10353                 }
10354                 tinfo = arch_reg_rhs(state, set->member, i);
10355                 if (tinfo.reg >= MAX_REGISTERS) {
10356                         tinfo.reg = REG_UNSET;
10357                 }
10358                 if ((tinfo.reg != REG_UNSET) && 
10359                         (info.reg != REG_UNSET) &&
10360                         (tinfo.reg != info.reg)) {
10361                         internal_error(state, def, "register conflict");
10362                 }
10363                 if ((info.regcm & tinfo.regcm) == 0) {
10364                         internal_error(state, def, "regcm conflict %x & %x == 0",
10365                                 info.regcm, tinfo.regcm);
10366                 }
10367                 if (info.reg == REG_UNSET) {
10368                         info.reg = tinfo.reg;
10369                 }
10370                 info.regcm &= tinfo.regcm;
10371         }
10372         if (info.reg >= MAX_REGISTERS) {
10373                 internal_error(state, def, "register out of range");
10374         }
10375         return info;
10376 }
10377
10378 static struct reg_info find_lhs_pre_color(
10379         struct compile_state *state, struct triple *ins, int index)
10380 {
10381         struct reg_info info;
10382         int zlhs, zrhs, i;
10383         zrhs = TRIPLE_RHS(ins->sizes);
10384         zlhs = TRIPLE_LHS(ins->sizes);
10385         if (!zlhs && triple_is_def(state, ins)) {
10386                 zlhs = 1;
10387         }
10388         if (index >= zlhs) {
10389                 internal_error(state, ins, "Bad lhs %d", index);
10390         }
10391         info = arch_reg_lhs(state, ins, index);
10392         for(i = 0; i < zrhs; i++) {
10393                 struct reg_info rinfo;
10394                 rinfo = arch_reg_rhs(state, ins, i);
10395                 if ((info.reg == rinfo.reg) &&
10396                         (rinfo.reg >= MAX_REGISTERS)) {
10397                         struct reg_info tinfo;
10398                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10399                         info.reg = tinfo.reg;
10400                         info.regcm &= tinfo.regcm;
10401                         break;
10402                 }
10403         }
10404         if (info.reg >= MAX_REGISTERS) {
10405                 info.reg = REG_UNSET;
10406         }
10407         return info;
10408 }
10409
10410 static struct reg_info find_rhs_post_color(
10411         struct compile_state *state, struct triple *ins, int index);
10412
10413 static struct reg_info find_lhs_post_color(
10414         struct compile_state *state, struct triple *ins, int index)
10415 {
10416         struct triple_set *set;
10417         struct reg_info info;
10418         struct triple *lhs;
10419 #if 0
10420         fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10421                 ins, index);
10422 #endif
10423         if ((index == 0) && triple_is_def(state, ins)) {
10424                 lhs = ins;
10425         }
10426         else if (index < TRIPLE_LHS(ins->sizes)) {
10427                 lhs = LHS(ins, index);
10428         }
10429         else {
10430                 internal_error(state, ins, "Bad lhs %d", index);
10431                 lhs = 0;
10432         }
10433         info = arch_reg_lhs(state, ins, index);
10434         if (info.reg >= MAX_REGISTERS) {
10435                 info.reg = REG_UNSET;
10436         }
10437         for(set = lhs->use; set; set = set->next) {
10438                 struct reg_info rinfo;
10439                 struct triple *user;
10440                 int zrhs, i;
10441                 user = set->member;
10442                 zrhs = TRIPLE_RHS(user->sizes);
10443                 for(i = 0; i < zrhs; i++) {
10444                         if (RHS(user, i) != lhs) {
10445                                 continue;
10446                         }
10447                         rinfo = find_rhs_post_color(state, user, i);
10448                         if ((info.reg != REG_UNSET) &&
10449                                 (rinfo.reg != REG_UNSET) &&
10450                                 (info.reg != rinfo.reg)) {
10451                                 internal_error(state, ins, "register conflict");
10452                         }
10453                         if ((info.regcm & rinfo.regcm) == 0) {
10454                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
10455                                         info.regcm, rinfo.regcm);
10456                         }
10457                         if (info.reg == REG_UNSET) {
10458                                 info.reg = rinfo.reg;
10459                         }
10460                         info.regcm &= rinfo.regcm;
10461                 }
10462         }
10463 #if 0
10464         fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10465                 ins, index, info.reg, info.regcm);
10466 #endif
10467         return info;
10468 }
10469
10470 static struct reg_info find_rhs_post_color(
10471         struct compile_state *state, struct triple *ins, int index)
10472 {
10473         struct reg_info info, rinfo;
10474         int zlhs, i;
10475 #if 0
10476         fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10477                 ins, index);
10478 #endif
10479         rinfo = arch_reg_rhs(state, ins, index);
10480         zlhs = TRIPLE_LHS(ins->sizes);
10481         if (!zlhs && triple_is_def(state, ins)) {
10482                 zlhs = 1;
10483         }
10484         info = rinfo;
10485         if (info.reg >= MAX_REGISTERS) {
10486                 info.reg = REG_UNSET;
10487         }
10488         for(i = 0; i < zlhs; i++) {
10489                 struct reg_info linfo;
10490                 linfo = arch_reg_lhs(state, ins, i);
10491                 if ((linfo.reg == rinfo.reg) &&
10492                         (linfo.reg >= MAX_REGISTERS)) {
10493                         struct reg_info tinfo;
10494                         tinfo = find_lhs_post_color(state, ins, i);
10495                         if (tinfo.reg >= MAX_REGISTERS) {
10496                                 tinfo.reg = REG_UNSET;
10497                         }
10498                         info.regcm &= linfo.reg;
10499                         info.regcm &= tinfo.regcm;
10500                         if (info.reg != REG_UNSET) {
10501                                 internal_error(state, ins, "register conflict");
10502                         }
10503                         if (info.regcm == 0) {
10504                                 internal_error(state, ins, "regcm conflict");
10505                         }
10506                         info.reg = tinfo.reg;
10507                 }
10508         }
10509 #if 0
10510         fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10511                 ins, index, info.reg, info.regcm);
10512 #endif
10513         return info;
10514 }
10515
10516 static struct reg_info find_lhs_color(
10517         struct compile_state *state, struct triple *ins, int index)
10518 {
10519         struct reg_info pre, post, info;
10520 #if 0
10521         fprintf(stderr, "find_lhs_color(%p, %d)\n",
10522                 ins, index);
10523 #endif
10524         pre = find_lhs_pre_color(state, ins, index);
10525         post = find_lhs_post_color(state, ins, index);
10526         if ((pre.reg != post.reg) &&
10527                 (pre.reg != REG_UNSET) &&
10528                 (post.reg != REG_UNSET)) {
10529                 internal_error(state, ins, "register conflict");
10530         }
10531         info.regcm = pre.regcm & post.regcm;
10532         info.reg = pre.reg;
10533         if (info.reg == REG_UNSET) {
10534                 info.reg = post.reg;
10535         }
10536 #if 0
10537         fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10538                 ins, index, info.reg, info.regcm);
10539 #endif
10540         return info;
10541 }
10542
10543 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10544 {
10545         struct triple_set *entry, *next;
10546         struct triple *out;
10547         struct reg_info info, rinfo;
10548
10549         info = arch_reg_lhs(state, ins, 0);
10550         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10551         use_triple(RHS(out, 0), out);
10552         /* Get the users of ins to use out instead */
10553         for(entry = ins->use; entry; entry = next) {
10554                 int i;
10555                 next = entry->next;
10556                 if (entry->member == out) {
10557                         continue;
10558                 }
10559                 i = find_rhs_use(state, entry->member, ins);
10560                 if (i < 0) {
10561                         continue;
10562                 }
10563                 rinfo = arch_reg_rhs(state, entry->member, i);
10564                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10565                         continue;
10566                 }
10567                 replace_rhs_use(state, ins, out, entry->member);
10568         }
10569         transform_to_arch_instruction(state, out);
10570         return out;
10571 }
10572
10573 static struct triple *pre_copy(
10574         struct compile_state *state, struct triple *ins, int index)
10575 {
10576         /* Carefully insert enough operations so that I can
10577          * enter any operation with a GPR32.
10578          */
10579         struct triple *in;
10580         struct triple **expr;
10581         expr = &RHS(ins, index);
10582         in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10583         unuse_triple(*expr, ins);
10584         *expr = in;
10585         use_triple(RHS(in, 0), in);
10586         use_triple(in, ins);
10587         transform_to_arch_instruction(state, in);
10588         return in;
10589 }
10590
10591
10592 static void insert_copies_to_phi(struct compile_state *state)
10593 {
10594         /* To get out of ssa form we insert moves on the incoming
10595          * edges to blocks containting phi functions.
10596          */
10597         struct triple *first;
10598         struct triple *phi;
10599
10600         /* Walk all of the operations to find the phi functions */
10601         first = RHS(state->main_function, 0);
10602         for(phi = first->next; phi != first ; phi = phi->next) {
10603                 struct block_set *set;
10604                 struct block *block;
10605                 struct triple **slot;
10606                 int edge;
10607                 if (phi->op != OP_PHI) {
10608                         continue;
10609                 }
10610                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10611                 block = phi->u.block;
10612                 slot  = &RHS(phi, 0);
10613                 /* Walk all of the incoming edges/blocks and insert moves.
10614                  */
10615                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10616                         struct block *eblock;
10617                         struct triple *move;
10618                         struct triple *val;
10619                         struct triple *ptr;
10620                         eblock = set->member;
10621                         val = slot[edge];
10622
10623                         if (val == phi) {
10624                                 continue;
10625                         }
10626
10627                         move = build_triple(state, OP_COPY, phi->type, val, 0,
10628                                 val->filename, val->line, val->col);
10629                         move->u.block = eblock;
10630                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
10631                         use_triple(val, move);
10632                         
10633                         slot[edge] = move;
10634                         unuse_triple(val, phi);
10635                         use_triple(move, phi);
10636
10637                         /* Walk through the block backwards to find
10638                          * an appropriate location for the OP_COPY.
10639                          */
10640                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10641                                 struct triple **expr;
10642                                 if ((ptr == phi) || (ptr == val)) {
10643                                         goto out;
10644                                 }
10645                                 expr = triple_rhs(state, ptr, 0);
10646                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10647                                         if ((*expr) == phi) {
10648                                                 goto out;
10649                                         }
10650                                 }
10651                         }
10652                 out:
10653                         if (triple_is_branch(state, ptr)) {
10654                                 internal_error(state, ptr,
10655                                         "Could not insert write to phi");
10656                         }
10657                         insert_triple(state, ptr->next, move);
10658                         if (eblock->last == ptr) {
10659                                 eblock->last = move;
10660                         }
10661                         transform_to_arch_instruction(state, move);
10662                 }
10663         }
10664 }
10665
10666 struct triple_reg_set {
10667         struct triple_reg_set *next;
10668         struct triple *member;
10669         struct triple *new;
10670 };
10671
10672 struct reg_block {
10673         struct block *block;
10674         struct triple_reg_set *in;
10675         struct triple_reg_set *out;
10676         int vertex;
10677 };
10678
10679 static int do_triple_set(struct triple_reg_set **head, 
10680         struct triple *member, struct triple *new_member)
10681 {
10682         struct triple_reg_set **ptr, *new;
10683         if (!member)
10684                 return 0;
10685         ptr = head;
10686         while(*ptr) {
10687                 if ((*ptr)->member == member) {
10688                         return 0;
10689                 }
10690                 ptr = &(*ptr)->next;
10691         }
10692         new = xcmalloc(sizeof(*new), "triple_set");
10693         new->member = member;
10694         new->new    = new_member;
10695         new->next   = *head;
10696         *head       = new;
10697         return 1;
10698 }
10699
10700 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
10701 {
10702         struct triple_reg_set *entry, **ptr;
10703         ptr = head;
10704         while(*ptr) {
10705                 entry = *ptr;
10706                 if (entry->member == member) {
10707                         *ptr = entry->next;
10708                         xfree(entry);
10709                         return;
10710                 }
10711                 else {
10712                         ptr = &entry->next;
10713                 }
10714         }
10715 }
10716
10717 static int in_triple(struct reg_block *rb, struct triple *in)
10718 {
10719         return do_triple_set(&rb->in, in, 0);
10720 }
10721 static void unin_triple(struct reg_block *rb, struct triple *unin)
10722 {
10723         do_triple_unset(&rb->in, unin);
10724 }
10725
10726 static int out_triple(struct reg_block *rb, struct triple *out)
10727 {
10728         return do_triple_set(&rb->out, out, 0);
10729 }
10730 static void unout_triple(struct reg_block *rb, struct triple *unout)
10731 {
10732         do_triple_unset(&rb->out, unout);
10733 }
10734
10735 static int initialize_regblock(struct reg_block *blocks,
10736         struct block *block, int vertex)
10737 {
10738         struct block_set *user;
10739         if (!block || (blocks[block->vertex].block == block)) {
10740                 return vertex;
10741         }
10742         vertex += 1;
10743         /* Renumber the blocks in a convinient fashion */
10744         block->vertex = vertex;
10745         blocks[vertex].block    = block;
10746         blocks[vertex].vertex   = vertex;
10747         for(user = block->use; user; user = user->next) {
10748                 vertex = initialize_regblock(blocks, user->member, vertex);
10749         }
10750         return vertex;
10751 }
10752
10753 static int phi_in(struct compile_state *state, struct reg_block *blocks,
10754         struct reg_block *rb, struct block *suc)
10755 {
10756         /* Read the conditional input set of a successor block
10757          * (i.e. the input to the phi nodes) and place it in the
10758          * current blocks output set.
10759          */
10760         struct block_set *set;
10761         struct triple *ptr;
10762         int edge;
10763         int done, change;
10764         change = 0;
10765         /* Find the edge I am coming in on */
10766         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
10767                 if (set->member == rb->block) {
10768                         break;
10769                 }
10770         }
10771         if (!set) {
10772                 internal_error(state, 0, "Not coming on a control edge?");
10773         }
10774         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
10775                 struct triple **slot, *expr, *ptr2;
10776                 int out_change, done2;
10777                 done = (ptr == suc->last);
10778                 if (ptr->op != OP_PHI) {
10779                         continue;
10780                 }
10781                 slot = &RHS(ptr, 0);
10782                 expr = slot[edge];
10783                 out_change = out_triple(rb, expr);
10784                 if (!out_change) {
10785                         continue;
10786                 }
10787                 /* If we don't define the variable also plast it
10788                  * in the current blocks input set.
10789                  */
10790                 ptr2 = rb->block->first;
10791                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
10792                         if (ptr2 == expr) {
10793                                 break;
10794                         }
10795                         done2 = (ptr2 == rb->block->last);
10796                 }
10797                 if (!done2) {
10798                         continue;
10799                 }
10800                 change |= in_triple(rb, expr);
10801         }
10802         return change;
10803 }
10804
10805 static int reg_in(struct compile_state *state, struct reg_block *blocks,
10806         struct reg_block *rb, struct block *suc)
10807 {
10808         struct triple_reg_set *in_set;
10809         int change;
10810         change = 0;
10811         /* Read the input set of a successor block
10812          * and place it in the current blocks output set.
10813          */
10814         in_set = blocks[suc->vertex].in;
10815         for(; in_set; in_set = in_set->next) {
10816                 int out_change, done;
10817                 struct triple *first, *last, *ptr;
10818                 out_change = out_triple(rb, in_set->member);
10819                 if (!out_change) {
10820                         continue;
10821                 }
10822                 /* If we don't define the variable also place it
10823                  * in the current blocks input set.
10824                  */
10825                 first = rb->block->first;
10826                 last = rb->block->last;
10827                 done = 0;
10828                 for(ptr = first; !done; ptr = ptr->next) {
10829                         if (ptr == in_set->member) {
10830                                 break;
10831                         }
10832                         done = (ptr == last);
10833                 }
10834                 if (!done) {
10835                         continue;
10836                 }
10837                 change |= in_triple(rb, in_set->member);
10838         }
10839         change |= phi_in(state, blocks, rb, suc);
10840         return change;
10841 }
10842
10843
10844 static int use_in(struct compile_state *state, struct reg_block *rb)
10845 {
10846         /* Find the variables we use but don't define and add
10847          * it to the current blocks input set.
10848          */
10849 #warning "FIXME is this O(N^2) algorithm bad?"
10850         struct block *block;
10851         struct triple *ptr;
10852         int done;
10853         int change;
10854         block = rb->block;
10855         change = 0;
10856         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10857                 struct triple **expr;
10858                 done = (ptr == block->first);
10859                 /* The variable a phi function uses depends on the
10860                  * control flow, and is handled in phi_in, not
10861                  * here.
10862                  */
10863                 if (ptr->op == OP_PHI) {
10864                         continue;
10865                 }
10866                 expr = triple_rhs(state, ptr, 0);
10867                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10868                         struct triple *rhs, *test;
10869                         int tdone;
10870                         rhs = *expr;
10871                         if (!rhs) {
10872                                 continue;
10873                         }
10874                         /* See if rhs is defined in this block */
10875                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10876                                 tdone = (test == block->first);
10877                                 if (test == rhs) {
10878                                         rhs = 0;
10879                                         break;
10880                                 }
10881                         }
10882                         /* If I still have a valid rhs add it to in */
10883                         change |= in_triple(rb, rhs);
10884                 }
10885         }
10886         return change;
10887 }
10888
10889 static struct reg_block *compute_variable_lifetimes(
10890         struct compile_state *state)
10891 {
10892         struct reg_block *blocks;
10893         int change;
10894         blocks = xcmalloc(
10895                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10896         initialize_regblock(blocks, state->last_block, 0);
10897         do {
10898                 int i;
10899                 change = 0;
10900                 for(i = 1; i <= state->last_vertex; i++) {
10901                         struct reg_block *rb;
10902                         rb = &blocks[i];
10903                         /* Add the left successor's input set to in */
10904                         if (rb->block->left) {
10905                                 change |= reg_in(state, blocks, rb, rb->block->left);
10906                         }
10907                         /* Add the right successor's input set to in */
10908                         if ((rb->block->right) && 
10909                                 (rb->block->right != rb->block->left)) {
10910                                 change |= reg_in(state, blocks, rb, rb->block->right);
10911                         }
10912                         /* Add use to in... */
10913                         change |= use_in(state, rb);
10914                 }
10915         } while(change);
10916         return blocks;
10917 }
10918
10919 static void free_variable_lifetimes(
10920         struct compile_state *state, struct reg_block *blocks)
10921 {
10922         int i;
10923         /* free in_set && out_set on each block */
10924         for(i = 1; i <= state->last_vertex; i++) {
10925                 struct triple_reg_set *entry, *next;
10926                 struct reg_block *rb;
10927                 rb = &blocks[i];
10928                 for(entry = rb->in; entry ; entry = next) {
10929                         next = entry->next;
10930                         do_triple_unset(&rb->in, entry->member);
10931                 }
10932                 for(entry = rb->out; entry; entry = next) {
10933                         next = entry->next;
10934                         do_triple_unset(&rb->out, entry->member);
10935                 }
10936         }
10937         xfree(blocks);
10938
10939 }
10940
10941 typedef void (*wvl_cb_t)(
10942         struct compile_state *state, 
10943         struct reg_block *blocks, struct triple_reg_set *live, 
10944         struct reg_block *rb, struct triple *ins, void *arg);
10945
10946 static void walk_variable_lifetimes(struct compile_state *state,
10947         struct reg_block *blocks, wvl_cb_t cb, void *arg)
10948 {
10949         int i;
10950         
10951         for(i = 1; i <= state->last_vertex; i++) {
10952                 struct triple_reg_set *live;
10953                 struct triple_reg_set *entry, *next;
10954                 struct triple *ptr, *prev;
10955                 struct reg_block *rb;
10956                 struct block *block;
10957                 int done;
10958
10959                 /* Get the blocks */
10960                 rb = &blocks[i];
10961                 block = rb->block;
10962
10963                 /* Copy out into live */
10964                 live = 0;
10965                 for(entry = rb->out; entry; entry = next) {
10966                         next = entry->next;
10967                         do_triple_set(&live, entry->member, entry->new);
10968                 }
10969                 /* Walk through the basic block calculating live */
10970                 for(done = 0, ptr = block->last; !done; ptr = prev) {
10971                         struct triple **expr;
10972
10973                         prev = ptr->prev;
10974                         done = (ptr == block->first);
10975
10976                         /* Ensure the current definition is in live */
10977                         if (triple_is_def(state, ptr)) {
10978                                 do_triple_set(&live, ptr, 0);
10979                         }
10980
10981                         /* Inform the callback function of what is
10982                          * going on.
10983                          */
10984                          cb(state, blocks, live, rb, ptr, arg);
10985                         
10986                         /* Remove the current definition from live */
10987                         do_triple_unset(&live, ptr);
10988
10989                         /* Add the current uses to live.
10990                          *
10991                          * It is safe to skip phi functions because they do
10992                          * not have any block local uses, and the block
10993                          * output sets already properly account for what
10994                          * control flow depedent uses phi functions do have.
10995                          */
10996                         if (ptr->op == OP_PHI) {
10997                                 continue;
10998                         }
10999                         expr = triple_rhs(state, ptr, 0);
11000                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
11001                                 /* If the triple is not a definition skip it. */
11002                                 if (!*expr || !triple_is_def(state, *expr)) {
11003                                         continue;
11004                                 }
11005                                 do_triple_set(&live, *expr, 0);
11006                         }
11007                 }
11008                 /* Free live */
11009                 for(entry = live; entry; entry = next) {
11010                         next = entry->next;
11011                         do_triple_unset(&live, entry->member);
11012                 }
11013         }
11014 }
11015
11016 static int count_triples(struct compile_state *state)
11017 {
11018         struct triple *first, *ins;
11019         int triples = 0;
11020         first = RHS(state->main_function, 0);
11021         ins = first;
11022         do {
11023                 triples++;
11024                 ins = ins->next;
11025         } while (ins != first);
11026         return triples;
11027 }
11028 struct dead_triple {
11029         struct triple *triple;
11030         struct dead_triple *work_next;
11031         struct block *block;
11032         int color;
11033         int flags;
11034 #define TRIPLE_FLAG_ALIVE 1
11035 };
11036
11037
11038 static void awaken(
11039         struct compile_state *state,
11040         struct dead_triple *dtriple, struct triple **expr,
11041         struct dead_triple ***work_list_tail)
11042 {
11043         struct triple *triple;
11044         struct dead_triple *dt;
11045         if (!expr) {
11046                 return;
11047         }
11048         triple = *expr;
11049         if (!triple) {
11050                 return;
11051         }
11052         if (triple->id <= 0)  {
11053                 internal_error(state, triple, "bad triple id: %d",
11054                         triple->id);
11055         }
11056         if (triple->op == OP_NOOP) {
11057                 internal_warning(state, triple, "awakening noop?");
11058                 return;
11059         }
11060         dt = &dtriple[triple->id];
11061         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11062                 dt->flags |= TRIPLE_FLAG_ALIVE;
11063                 if (!dt->work_next) {
11064                         **work_list_tail = dt;
11065                         *work_list_tail = &dt->work_next;
11066                 }
11067         }
11068 }
11069
11070 static void eliminate_inefectual_code(struct compile_state *state)
11071 {
11072         struct block *block;
11073         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11074         int triples, i;
11075         struct triple *first, *ins;
11076
11077         /* Setup the work list */
11078         work_list = 0;
11079         work_list_tail = &work_list;
11080
11081         first = RHS(state->main_function, 0);
11082
11083         /* Count how many triples I have */
11084         triples = count_triples(state);
11085
11086         /* Now put then in an array and mark all of the triples dead */
11087         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11088         
11089         ins = first;
11090         i = 1;
11091         block = 0;
11092         do {
11093                 if (ins->op == OP_LABEL) {
11094                         block = ins->u.block;
11095                 }
11096                 dtriple[i].triple = ins;
11097                 dtriple[i].block  = block;
11098                 dtriple[i].flags  = 0;
11099                 dtriple[i].color  = ins->id;
11100                 ins->id = i;
11101                 /* See if it is an operation we always keep */
11102 #warning "FIXME handle the case of killing a branch instruction"
11103                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11104                         awaken(state, dtriple, &ins, &work_list_tail);
11105                 }
11106                 i++;
11107                 ins = ins->next;
11108         } while(ins != first);
11109         while(work_list) {
11110                 struct dead_triple *dt;
11111                 struct block_set *user;
11112                 struct triple **expr;
11113                 dt = work_list;
11114                 work_list = dt->work_next;
11115                 if (!work_list) {
11116                         work_list_tail = &work_list;
11117                 }
11118                 /* Wake up the data depencencies of this triple */
11119                 expr = 0;
11120                 do {
11121                         expr = triple_rhs(state, dt->triple, expr);
11122                         awaken(state, dtriple, expr, &work_list_tail);
11123                 } while(expr);
11124                 do {
11125                         expr = triple_lhs(state, dt->triple, expr);
11126                         awaken(state, dtriple, expr, &work_list_tail);
11127                 } while(expr);
11128                 do {
11129                         expr = triple_misc(state, dt->triple, expr);
11130                         awaken(state, dtriple, expr, &work_list_tail);
11131                 } while(expr);
11132                 /* Wake up the forward control dependencies */
11133                 do {
11134                         expr = triple_targ(state, dt->triple, expr);
11135                         awaken(state, dtriple, expr, &work_list_tail);
11136                 } while(expr);
11137                 /* Wake up the reverse control dependencies of this triple */
11138                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11139                         awaken(state, dtriple, &user->member->last, &work_list_tail);
11140                 }
11141         }
11142         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11143                 if ((dt->triple->op == OP_NOOP) && 
11144                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
11145                         internal_error(state, dt->triple, "noop effective?");
11146                 }
11147                 dt->triple->id = dt->color;     /* Restore the color */
11148                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11149 #warning "FIXME handle the case of killing a basic block"
11150                         if (dt->block->first == dt->triple) {
11151                                 continue;
11152                         }
11153                         if (dt->block->last == dt->triple) {
11154                                 dt->block->last = dt->triple->prev;
11155                         }
11156                         release_triple(state, dt->triple);
11157                 }
11158         }
11159         xfree(dtriple);
11160 }
11161
11162
11163 static void insert_mandatory_copies(struct compile_state *state)
11164 {
11165         struct triple *ins, *first;
11166
11167         /* The object is with a minimum of inserted copies,
11168          * to resolve in fundamental register conflicts between
11169          * register value producers and consumers.
11170          * Theoretically we may be greater than minimal when we
11171          * are inserting copies before instructions but that
11172          * case should be rare.
11173          */
11174         first = RHS(state->main_function, 0);
11175         ins = first;
11176         do {
11177                 struct triple_set *entry, *next;
11178                 struct triple *tmp;
11179                 struct reg_info info;
11180                 unsigned reg, regcm;
11181                 int do_post_copy, do_pre_copy;
11182                 tmp = 0;
11183                 if (!triple_is_def(state, ins)) {
11184                         goto next;
11185                 }
11186                 /* Find the architecture specific color information */
11187                 info = arch_reg_lhs(state, ins, 0);
11188                 if (info.reg >= MAX_REGISTERS) {
11189                         info.reg = REG_UNSET;
11190                 }
11191                 
11192                 reg = REG_UNSET;
11193                 regcm = arch_type_to_regcm(state, ins->type);
11194                 do_post_copy = do_pre_copy = 0;
11195
11196                 /* Walk through the uses of ins and check for conflicts */
11197                 for(entry = ins->use; entry; entry = next) {
11198                         struct reg_info rinfo;
11199                         int i;
11200                         next = entry->next;
11201                         i = find_rhs_use(state, entry->member, ins);
11202                         if (i < 0) {
11203                                 continue;
11204                         }
11205                         
11206                         /* Find the users color requirements */
11207                         rinfo = arch_reg_rhs(state, entry->member, i);
11208                         if (rinfo.reg >= MAX_REGISTERS) {
11209                                 rinfo.reg = REG_UNSET;
11210                         }
11211                         
11212                         /* See if I need a pre_copy */
11213                         if (rinfo.reg != REG_UNSET) {
11214                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11215                                         do_pre_copy = 1;
11216                                 }
11217                                 reg = rinfo.reg;
11218                         }
11219                         regcm &= rinfo.regcm;
11220                         regcm = arch_regcm_normalize(state, regcm);
11221                         if (regcm == 0) {
11222                                 do_pre_copy = 1;
11223                         }
11224                 }
11225                 do_post_copy =
11226                         !do_pre_copy &&
11227                         (((info.reg != REG_UNSET) && 
11228                                 (reg != REG_UNSET) &&
11229                                 (info.reg != reg)) ||
11230                         ((info.regcm & regcm) == 0));
11231
11232                 reg = info.reg;
11233                 regcm = info.regcm;
11234                 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11235                 for(entry = ins->use; entry; entry = next) {
11236                         struct reg_info rinfo;
11237                         int i;
11238                         next = entry->next;
11239                         i = find_rhs_use(state, entry->member, ins);
11240                         if (i < 0) {
11241                                 continue;
11242                         }
11243                         
11244                         /* Find the users color requirements */
11245                         rinfo = arch_reg_rhs(state, entry->member, i);
11246                         if (rinfo.reg >= MAX_REGISTERS) {
11247                                 rinfo.reg = REG_UNSET;
11248                         }
11249
11250                         /* Now see if it is time to do the pre_copy */
11251                         if (rinfo.reg != REG_UNSET) {
11252                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11253                                         ((regcm & rinfo.regcm) == 0) ||
11254                                         /* Don't let a mandatory coalesce sneak
11255                                          * into a operation that is marked to prevent
11256                                          * coalescing.
11257                                          */
11258                                         ((reg != REG_UNNEEDED) &&
11259                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11260                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11261                                         ) {
11262                                         if (do_pre_copy) {
11263                                                 struct triple *user;
11264                                                 user = entry->member;
11265                                                 if (RHS(user, i) != ins) {
11266                                                         internal_error(state, user, "bad rhs");
11267                                                 }
11268                                                 tmp = pre_copy(state, user, i);
11269                                                 continue;
11270                                         } else {
11271                                                 do_post_copy = 1;
11272                                         }
11273                                 }
11274                                 reg = rinfo.reg;
11275                         }
11276                         if ((regcm & rinfo.regcm) == 0) {
11277                                 if (do_pre_copy) {
11278                                         struct triple *user;
11279                                         user = entry->member;
11280                                         if (RHS(user, i) != ins) {
11281                                                 internal_error(state, user, "bad rhs");
11282                                         }
11283                                         tmp = pre_copy(state, user, i);
11284                                         continue;
11285                                 } else {
11286                                         do_post_copy = 1;
11287                                 }
11288                         }
11289                         regcm &= rinfo.regcm;
11290                         
11291                 }
11292                 if (do_post_copy) {
11293                         struct reg_info pre, post;
11294                         tmp = post_copy(state, ins);
11295                         pre = arch_reg_lhs(state, ins, 0);
11296                         post = arch_reg_lhs(state, tmp, 0);
11297                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11298                                 internal_error(state, tmp, "useless copy");
11299                         }
11300                 }
11301         next:
11302                 ins = ins->next;
11303         } while(ins != first);
11304 }
11305
11306
11307 struct live_range_edge;
11308 struct live_range_def;
11309 struct live_range {
11310         struct live_range_edge *edges;
11311         struct live_range_def *defs;
11312 /* Note. The list pointed to by defs is kept in order.
11313  * That is baring splits in the flow control
11314  * defs dominates defs->next wich dominates defs->next->next
11315  * etc.
11316  */
11317         unsigned color;
11318         unsigned classes;
11319         unsigned degree;
11320         unsigned length;
11321         struct live_range *group_next, **group_prev;
11322 };
11323
11324 struct live_range_edge {
11325         struct live_range_edge *next;
11326         struct live_range *node;
11327 };
11328
11329 struct live_range_def {
11330         struct live_range_def *next;
11331         struct live_range_def *prev;
11332         struct live_range *lr;
11333         struct triple *def;
11334         unsigned orig_id;
11335 };
11336
11337 #define LRE_HASH_SIZE 2048
11338 struct lre_hash {
11339         struct lre_hash *next;
11340         struct live_range *left;
11341         struct live_range *right;
11342 };
11343
11344
11345 struct reg_state {
11346         struct lre_hash *hash[LRE_HASH_SIZE];
11347         struct reg_block *blocks;
11348         struct live_range_def *lrd;
11349         struct live_range *lr;
11350         struct live_range *low, **low_tail;
11351         struct live_range *high, **high_tail;
11352         unsigned defs;
11353         unsigned ranges;
11354         int passes, max_passes;
11355 #define MAX_ALLOCATION_PASSES 100
11356 };
11357
11358
11359 static unsigned regc_max_size(struct compile_state *state, int classes)
11360 {
11361         unsigned max_size;
11362         int i;
11363         max_size = 0;
11364         for(i = 0; i < MAX_REGC; i++) {
11365                 if (classes & (1 << i)) {
11366                         unsigned size;
11367                         size = arch_regc_size(state, i);
11368                         if (size > max_size) {
11369                                 max_size = size;
11370                         }
11371                 }
11372         }
11373         return max_size;
11374 }
11375
11376 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11377 {
11378         unsigned equivs[MAX_REG_EQUIVS];
11379         int i;
11380         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11381                 internal_error(state, 0, "invalid register");
11382         }
11383         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11384                 internal_error(state, 0, "invalid register");
11385         }
11386         arch_reg_equivs(state, equivs, reg1);
11387         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11388                 if (equivs[i] == reg2) {
11389                         return 1;
11390                 }
11391         }
11392         return 0;
11393 }
11394
11395 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11396 {
11397         unsigned equivs[MAX_REG_EQUIVS];
11398         int i;
11399         if (reg == REG_UNNEEDED) {
11400                 return;
11401         }
11402         arch_reg_equivs(state, equivs, reg);
11403         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11404                 used[equivs[i]] = 1;
11405         }
11406         return;
11407 }
11408
11409 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11410 {
11411         unsigned equivs[MAX_REG_EQUIVS];
11412         int i;
11413         if (reg == REG_UNNEEDED) {
11414                 return;
11415         }
11416         arch_reg_equivs(state, equivs, reg);
11417         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11418                 used[equivs[i]] += 1;
11419         }
11420         return;
11421 }
11422
11423 static unsigned int hash_live_edge(
11424         struct live_range *left, struct live_range *right)
11425 {
11426         unsigned int hash, val;
11427         unsigned long lval, rval;
11428         lval = ((unsigned long)left)/sizeof(struct live_range);
11429         rval = ((unsigned long)right)/sizeof(struct live_range);
11430         hash = 0;
11431         while(lval) {
11432                 val = lval & 0xff;
11433                 lval >>= 8;
11434                 hash = (hash *263) + val;
11435         }
11436         while(rval) {
11437                 val = rval & 0xff;
11438                 rval >>= 8;
11439                 hash = (hash *263) + val;
11440         }
11441         hash = hash & (LRE_HASH_SIZE - 1);
11442         return hash;
11443 }
11444
11445 static struct lre_hash **lre_probe(struct reg_state *rstate,
11446         struct live_range *left, struct live_range *right)
11447 {
11448         struct lre_hash **ptr;
11449         unsigned int index;
11450         /* Ensure left <= right */
11451         if (left > right) {
11452                 struct live_range *tmp;
11453                 tmp = left;
11454                 left = right;
11455                 right = tmp;
11456         }
11457         index = hash_live_edge(left, right);
11458         
11459         ptr = &rstate->hash[index];
11460         while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
11461                 ptr = &(*ptr)->next;
11462         }
11463         return ptr;
11464 }
11465
11466 static int interfere(struct reg_state *rstate,
11467         struct live_range *left, struct live_range *right)
11468 {
11469         struct lre_hash **ptr;
11470         ptr = lre_probe(rstate, left, right);
11471         return ptr && *ptr;
11472 }
11473
11474 static void add_live_edge(struct reg_state *rstate, 
11475         struct live_range *left, struct live_range *right)
11476 {
11477         /* FIXME the memory allocation overhead is noticeable here... */
11478         struct lre_hash **ptr, *new_hash;
11479         struct live_range_edge *edge;
11480
11481         if (left == right) {
11482                 return;
11483         }
11484         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11485                 return;
11486         }
11487         /* Ensure left <= right */
11488         if (left > right) {
11489                 struct live_range *tmp;
11490                 tmp = left;
11491                 left = right;
11492                 right = tmp;
11493         }
11494         ptr = lre_probe(rstate, left, right);
11495         if (*ptr) {
11496                 return;
11497         }
11498         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11499         new_hash->next  = *ptr;
11500         new_hash->left  = left;
11501         new_hash->right = right;
11502         *ptr = new_hash;
11503
11504         edge = xmalloc(sizeof(*edge), "live_range_edge");
11505         edge->next   = left->edges;
11506         edge->node   = right;
11507         left->edges  = edge;
11508         left->degree += 1;
11509         
11510         edge = xmalloc(sizeof(*edge), "live_range_edge");
11511         edge->next    = right->edges;
11512         edge->node    = left;
11513         right->edges  = edge;
11514         right->degree += 1;
11515 }
11516
11517 static void remove_live_edge(struct reg_state *rstate,
11518         struct live_range *left, struct live_range *right)
11519 {
11520         struct live_range_edge *edge, **ptr;
11521         struct lre_hash **hptr, *entry;
11522         hptr = lre_probe(rstate, left, right);
11523         if (!hptr || !*hptr) {
11524                 return;
11525         }
11526         entry = *hptr;
11527         *hptr = entry->next;
11528         xfree(entry);
11529
11530         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11531                 edge = *ptr;
11532                 if (edge->node == right) {
11533                         *ptr = edge->next;
11534                         memset(edge, 0, sizeof(*edge));
11535                         xfree(edge);
11536                         break;
11537                 }
11538         }
11539         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11540                 edge = *ptr;
11541                 if (edge->node == left) {
11542                         *ptr = edge->next;
11543                         memset(edge, 0, sizeof(*edge));
11544                         xfree(edge);
11545                         break;
11546                 }
11547         }
11548 }
11549
11550 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11551 {
11552         struct live_range_edge *edge, *next;
11553         for(edge = range->edges; edge; edge = next) {
11554                 next = edge->next;
11555                 remove_live_edge(rstate, range, edge->node);
11556         }
11557 }
11558
11559
11560 /* Interference graph...
11561  * 
11562  * new(n) --- Return a graph with n nodes but no edges.
11563  * add(g,x,y) --- Return a graph including g with an between x and y
11564  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11565  *                x and y in the graph g
11566  * degree(g, x) --- Return the degree of the node x in the graph g
11567  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11568  *
11569  * Implement with a hash table && a set of adjcency vectors.
11570  * The hash table supports constant time implementations of add and interfere.
11571  * The adjacency vectors support an efficient implementation of neighbors.
11572  */
11573
11574 /* 
11575  *     +---------------------------------------------------+
11576  *     |         +--------------+                          |
11577  *     v         v              |                          |
11578  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
11579  *
11580  * -- In simplify implment optimistic coloring... (No backtracking)
11581  * -- Implement Rematerialization it is the only form of spilling we can perform
11582  *    Essentially this means dropping a constant from a register because
11583  *    we can regenerate it later.
11584  *
11585  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11586  *     coalesce at phi points...
11587  * --- Bias coloring if at all possible do the coalesing a compile time.
11588  *
11589  *
11590  */
11591
11592 static void different_colored(
11593         struct compile_state *state, struct reg_state *rstate, 
11594         struct triple *parent, struct triple *ins)
11595 {
11596         struct live_range *lr;
11597         struct triple **expr;
11598         lr = rstate->lrd[ins->id].lr;
11599         expr = triple_rhs(state, ins, 0);
11600         for(;expr; expr = triple_rhs(state, ins, expr)) {
11601                 struct live_range *lr2;
11602                 if (!*expr || (*expr == parent) || (*expr == ins)) {
11603                         continue;
11604                 }
11605                 lr2 = rstate->lrd[(*expr)->id].lr;
11606                 if (lr->color == lr2->color) {
11607                         internal_error(state, ins, "live range too big");
11608                 }
11609         }
11610 }
11611
11612
11613 static struct live_range *coalesce_ranges(
11614         struct compile_state *state, struct reg_state *rstate,
11615         struct live_range *lr1, struct live_range *lr2)
11616 {
11617         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11618         unsigned color;
11619         unsigned classes;
11620         if (lr1 == lr2) {
11621                 return lr1;
11622         }
11623         if (!lr1->defs || !lr2->defs) {
11624                 internal_error(state, 0,
11625                         "cannot coalese dead live ranges");
11626         }
11627         if ((lr1->color == REG_UNNEEDED) ||
11628                 (lr2->color == REG_UNNEEDED)) {
11629                 internal_error(state, 0, 
11630                         "cannot coalesce live ranges without a possible color");
11631         }
11632         if ((lr1->color != lr2->color) &&
11633                 (lr1->color != REG_UNSET) &&
11634                 (lr2->color != REG_UNSET)) {
11635                 internal_error(state, lr1->defs->def, 
11636                         "cannot coalesce live ranges of different colors");
11637         }
11638         color = lr1->color;
11639         if (color == REG_UNSET) {
11640                 color = lr2->color;
11641         }
11642         classes = lr1->classes & lr2->classes;
11643         if (!classes) {
11644                 internal_error(state, lr1->defs->def,
11645                         "cannot coalesce live ranges with dissimilar register classes");
11646         }
11647         /* If there is a clear dominate live range put it in lr1,
11648          * For purposes of this test phi functions are
11649          * considered dominated by the definitions that feed into
11650          * them. 
11651          */
11652         if ((lr1->defs->prev->def->op == OP_PHI) ||
11653                 ((lr2->defs->prev->def->op != OP_PHI) &&
11654                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
11655                 struct live_range *tmp;
11656                 tmp = lr1;
11657                 lr1 = lr2;
11658                 lr2 = tmp;
11659         }
11660 #if 0
11661         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
11662                 fprintf(stderr, "lr1 post\n");
11663         }
11664         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11665                 fprintf(stderr, "lr1 pre\n");
11666         }
11667         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
11668                 fprintf(stderr, "lr2 post\n");
11669         }
11670         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11671                 fprintf(stderr, "lr2 pre\n");
11672         }
11673 #endif
11674 #if 0
11675         fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
11676                 lr1->defs->def,
11677                 lr1->color,
11678                 lr2->defs->def,
11679                 lr2->color);
11680 #endif
11681         
11682         lr1->classes = classes;
11683         /* Append lr2 onto lr1 */
11684 #warning "FIXME should this be a merge instead of a splice?"
11685         head = lr1->defs;
11686         mid1 = lr1->defs->prev;
11687         mid2 = lr2->defs;
11688         end  = lr2->defs->prev;
11689         
11690         head->prev = end;
11691         end->next  = head;
11692
11693         mid1->next = mid2;
11694         mid2->prev = mid1;
11695
11696         /* Fixup the live range in the added live range defs */
11697         lrd = head;
11698         do {
11699                 lrd->lr = lr1;
11700                 lrd = lrd->next;
11701         } while(lrd != head);
11702
11703         /* Mark lr2 as free. */
11704         lr2->defs = 0;
11705         lr2->color = REG_UNNEEDED;
11706         lr2->classes = 0;
11707
11708         if (!lr1->defs) {
11709                 internal_error(state, 0, "lr1->defs == 0 ?");
11710         }
11711
11712         lr1->color   = color;
11713         lr1->classes = classes;
11714
11715         return lr1;
11716 }
11717
11718 static struct live_range_def *live_range_head(
11719         struct compile_state *state, struct live_range *lr,
11720         struct live_range_def *last)
11721 {
11722         struct live_range_def *result;
11723         result = 0;
11724         if (last == 0) {
11725                 result = lr->defs;
11726         }
11727         else if (!tdominates(state, lr->defs->def, last->next->def)) {
11728                 result = last->next;
11729         }
11730         return result;
11731 }
11732
11733 static struct live_range_def *live_range_end(
11734         struct compile_state *state, struct live_range *lr,
11735         struct live_range_def *last)
11736 {
11737         struct live_range_def *result;
11738         result = 0;
11739         if (last == 0) {
11740                 result = lr->defs->prev;
11741         }
11742         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
11743                 result = last->prev;
11744         }
11745         return result;
11746 }
11747
11748
11749 static void initialize_live_ranges(
11750         struct compile_state *state, struct reg_state *rstate)
11751 {
11752         struct triple *ins, *first;
11753         size_t count, size;
11754         int i, j;
11755
11756         first = RHS(state->main_function, 0);
11757         /* First count how many instructions I have.
11758          */
11759         count = count_triples(state);
11760         /* Potentially I need one live range definitions for each
11761          * instruction, plus an extra for the split routines.
11762          */
11763         rstate->defs = count + 1;
11764         /* Potentially I need one live range for each instruction
11765          * plus an extra for the dummy live range.
11766          */
11767         rstate->ranges = count + 1;
11768         size = sizeof(rstate->lrd[0]) * rstate->defs;
11769         rstate->lrd = xcmalloc(size, "live_range_def");
11770         size = sizeof(rstate->lr[0]) * rstate->ranges;
11771         rstate->lr  = xcmalloc(size, "live_range");
11772
11773         /* Setup the dummy live range */
11774         rstate->lr[0].classes = 0;
11775         rstate->lr[0].color = REG_UNSET;
11776         rstate->lr[0].defs = 0;
11777         i = j = 0;
11778         ins = first;
11779         do {
11780                 /* If the triple is a variable give it a live range */
11781                 if (triple_is_def(state, ins)) {
11782                         struct reg_info info;
11783                         /* Find the architecture specific color information */
11784                         info = find_def_color(state, ins);
11785
11786                         i++;
11787                         rstate->lr[i].defs    = &rstate->lrd[j];
11788                         rstate->lr[i].color   = info.reg;
11789                         rstate->lr[i].classes = info.regcm;
11790                         rstate->lr[i].degree  = 0;
11791                         rstate->lrd[j].lr = &rstate->lr[i];
11792                 } 
11793                 /* Otherwise give the triple the dummy live range. */
11794                 else {
11795                         rstate->lrd[j].lr = &rstate->lr[0];
11796                 }
11797
11798                 /* Initalize the live_range_def */
11799                 rstate->lrd[j].next    = &rstate->lrd[j];
11800                 rstate->lrd[j].prev    = &rstate->lrd[j];
11801                 rstate->lrd[j].def     = ins;
11802                 rstate->lrd[j].orig_id = ins->id;
11803                 ins->id = j;
11804
11805                 j++;
11806                 ins = ins->next;
11807         } while(ins != first);
11808         rstate->ranges = i;
11809         rstate->defs -= 1;
11810
11811         /* Make a second pass to handle achitecture specific register
11812          * constraints.
11813          */
11814         ins = first;
11815         do {
11816                 int zlhs, zrhs, i, j;
11817                 if (ins->id > rstate->defs) {
11818                         internal_error(state, ins, "bad id");
11819                 }
11820                 
11821                 /* Walk through the template of ins and coalesce live ranges */
11822                 zlhs = TRIPLE_LHS(ins->sizes);
11823                 if ((zlhs == 0) && triple_is_def(state, ins)) {
11824                         zlhs = 1;
11825                 }
11826                 zrhs = TRIPLE_RHS(ins->sizes);
11827                 
11828                 for(i = 0; i < zlhs; i++) {
11829                         struct reg_info linfo;
11830                         struct live_range_def *lhs;
11831                         linfo = arch_reg_lhs(state, ins, i);
11832                         if (linfo.reg < MAX_REGISTERS) {
11833                                 continue;
11834                         }
11835                         if (triple_is_def(state, ins)) {
11836                                 lhs = &rstate->lrd[ins->id];
11837                         } else {
11838                                 lhs = &rstate->lrd[LHS(ins, i)->id];
11839                         }
11840                         for(j = 0; j < zrhs; j++) {
11841                                 struct reg_info rinfo;
11842                                 struct live_range_def *rhs;
11843                                 rinfo = arch_reg_rhs(state, ins, j);
11844                                 if (rinfo.reg < MAX_REGISTERS) {
11845                                         continue;
11846                                 }
11847                                 rhs = &rstate->lrd[RHS(ins, i)->id];
11848                                 if (rinfo.reg == linfo.reg) {
11849                                         coalesce_ranges(state, rstate, 
11850                                                 lhs->lr, rhs->lr);
11851                                 }
11852                         }
11853                 }
11854                 ins = ins->next;
11855         } while(ins != first);
11856 }
11857
11858 static void graph_ins(
11859         struct compile_state *state, 
11860         struct reg_block *blocks, struct triple_reg_set *live, 
11861         struct reg_block *rb, struct triple *ins, void *arg)
11862 {
11863         struct reg_state *rstate = arg;
11864         struct live_range *def;
11865         struct triple_reg_set *entry;
11866
11867         /* If the triple is not a definition
11868          * we do not have a definition to add to
11869          * the interference graph.
11870          */
11871         if (!triple_is_def(state, ins)) {
11872                 return;
11873         }
11874         def = rstate->lrd[ins->id].lr;
11875         
11876         /* Create an edge between ins and everything that is
11877          * alive, unless the live_range cannot share
11878          * a physical register with ins.
11879          */
11880         for(entry = live; entry; entry = entry->next) {
11881                 struct live_range *lr;
11882                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
11883                         internal_error(state, 0, "bad entry?");
11884                 }
11885                 lr = rstate->lrd[entry->member->id].lr;
11886                 if (def == lr) {
11887                         continue;
11888                 }
11889                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
11890                         continue;
11891                 }
11892                 add_live_edge(rstate, def, lr);
11893         }
11894         return;
11895 }
11896
11897
11898 static void print_interference_ins(
11899         struct compile_state *state, 
11900         struct reg_block *blocks, struct triple_reg_set *live, 
11901         struct reg_block *rb, struct triple *ins, void *arg)
11902 {
11903         struct reg_state *rstate = arg;
11904         struct live_range *lr;
11905
11906         lr = rstate->lrd[ins->id].lr;
11907         display_triple(stdout, ins);
11908
11909         if (lr->defs) {
11910                 struct live_range_def *lrd;
11911                 printf("       range:");
11912                 lrd = lr->defs;
11913                 do {
11914                         printf(" %-10p", lrd->def);
11915                         lrd = lrd->next;
11916                 } while(lrd != lr->defs);
11917                 printf("\n");
11918         }
11919         if (live) {
11920                 struct triple_reg_set *entry;
11921                 printf("        live:");
11922                 for(entry = live; entry; entry = entry->next) {
11923                         printf(" %-10p", entry->member);
11924                 }
11925                 printf("\n");
11926         }
11927         if (lr->edges) {
11928                 struct live_range_edge *entry;
11929                 printf("       edges:");
11930                 for(entry = lr->edges; entry; entry = entry->next) {
11931                         struct live_range_def *lrd;
11932                         lrd = entry->node->defs;
11933                         do {
11934                                 printf(" %-10p", lrd->def);
11935                                 lrd = lrd->next;
11936                         } while(lrd != entry->node->defs);
11937                         printf("|");
11938                 }
11939                 printf("\n");
11940         }
11941         if (triple_is_branch(state, ins)) {
11942                 printf("\n");
11943         }
11944         return;
11945 }
11946
11947 static int coalesce_live_ranges(
11948         struct compile_state *state, struct reg_state *rstate)
11949 {
11950         /* At the point where a value is moved from one
11951          * register to another that value requires two
11952          * registers, thus increasing register pressure.
11953          * Live range coaleescing reduces the register
11954          * pressure by keeping a value in one register
11955          * longer.
11956          *
11957          * In the case of a phi function all paths leading
11958          * into it must be allocated to the same register
11959          * otherwise the phi function may not be removed.
11960          *
11961          * Forcing a value to stay in a single register
11962          * for an extended period of time does have
11963          * limitations when applied to non homogenous
11964          * register pool.  
11965          *
11966          * The two cases I have identified are:
11967          * 1) Two forced register assignments may
11968          *    collide.
11969          * 2) Registers may go unused because they
11970          *    are only good for storing the value
11971          *    and not manipulating it.
11972          *
11973          * Because of this I need to split live ranges,
11974          * even outside of the context of coalesced live
11975          * ranges.  The need to split live ranges does
11976          * impose some constraints on live range coalescing.
11977          *
11978          * - Live ranges may not be coalesced across phi
11979          *   functions.  This creates a 2 headed live
11980          *   range that cannot be sanely split.
11981          *
11982          * - phi functions (coalesced in initialize_live_ranges) 
11983          *   are handled as pre split live ranges so we will
11984          *   never attempt to split them.
11985          */
11986         int coalesced;
11987         int i;
11988
11989         coalesced = 0;
11990         for(i = 0; i <= rstate->ranges; i++) {
11991                 struct live_range *lr1;
11992                 struct live_range_def *lrd1;
11993                 lr1 = &rstate->lr[i];
11994                 if (!lr1->defs) {
11995                         continue;
11996                 }
11997                 lrd1 = live_range_end(state, lr1, 0);
11998                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
11999                         struct triple_set *set;
12000                         if (lrd1->def->op != OP_COPY) {
12001                                 continue;
12002                         }
12003                         /* Skip copies that are the result of a live range split. */
12004                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12005                                 continue;
12006                         }
12007                         for(set = lrd1->def->use; set; set = set->next) {
12008                                 struct live_range_def *lrd2;
12009                                 struct live_range *lr2, *res;
12010
12011                                 lrd2 = &rstate->lrd[set->member->id];
12012
12013                                 /* Don't coalesce with instructions
12014                                  * that are the result of a live range
12015                                  * split.
12016                                  */
12017                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12018                                         continue;
12019                                 }
12020                                 lr2 = rstate->lrd[set->member->id].lr;
12021                                 if (lr1 == lr2) {
12022                                         continue;
12023                                 }
12024                                 if ((lr1->color != lr2->color) &&
12025                                         (lr1->color != REG_UNSET) &&
12026                                         (lr2->color != REG_UNSET)) {
12027                                         continue;
12028                                 }
12029                                 if ((lr1->classes & lr2->classes) == 0) {
12030                                         continue;
12031                                 }
12032                                 
12033                                 if (interfere(rstate, lr1, lr2)) {
12034                                         continue;
12035                                 }
12036                                 
12037                                 res = coalesce_ranges(state, rstate, lr1, lr2);
12038                                 coalesced += 1;
12039                                 if (res != lr1) {
12040                                         goto next;
12041                                 }
12042                         }
12043                 }
12044         next:
12045                 ;
12046         }
12047         return coalesced;
12048 }
12049
12050
12051 static void fix_coalesce_conflicts(struct compile_state *state,
12052         struct reg_block *blocks, struct triple_reg_set *live,
12053         struct reg_block *rb, struct triple *ins, void *arg)
12054 {
12055         int zlhs, zrhs, i, j;
12056
12057         /* See if we have a mandatory coalesce operation between
12058          * a lhs and a rhs value.  If so and the rhs value is also
12059          * alive then this triple needs to be pre copied.  Otherwise
12060          * we would have two definitions in the same live range simultaneously
12061          * alive.
12062          */
12063         zlhs = TRIPLE_LHS(ins->sizes);
12064         if ((zlhs == 0) && triple_is_def(state, ins)) {
12065                 zlhs = 1;
12066         }
12067         zrhs = TRIPLE_RHS(ins->sizes);
12068         for(i = 0; i < zlhs; i++) {
12069                 struct reg_info linfo;
12070                 linfo = arch_reg_lhs(state, ins, i);
12071                 if (linfo.reg < MAX_REGISTERS) {
12072                         continue;
12073                 }
12074                 for(j = 0; j < zrhs; j++) {
12075                         struct reg_info rinfo;
12076                         struct triple *rhs;
12077                         struct triple_reg_set *set;
12078                         int found;
12079                         found = 0;
12080                         rinfo = arch_reg_rhs(state, ins, j);
12081                         if (rinfo.reg != linfo.reg) {
12082                                 continue;
12083                         }
12084                         rhs = RHS(ins, j);
12085                         for(set = live; set && !found; set = set->next) {
12086                                 if (set->member == rhs) {
12087                                         found = 1;
12088                                 }
12089                         }
12090                         if (found) {
12091                                 struct triple *copy;
12092                                 copy = pre_copy(state, ins, j);
12093                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12094                         }
12095                 }
12096         }
12097         return;
12098 }
12099
12100 static void replace_set_use(struct compile_state *state,
12101         struct triple_reg_set *head, struct triple *orig, struct triple *new)
12102 {
12103         struct triple_reg_set *set;
12104         for(set = head; set; set = set->next) {
12105                 if (set->member == orig) {
12106                         set->member = new;
12107                 }
12108         }
12109 }
12110
12111 static void replace_block_use(struct compile_state *state, 
12112         struct reg_block *blocks, struct triple *orig, struct triple *new)
12113 {
12114         int i;
12115 #warning "WISHLIST visit just those blocks that need it *"
12116         for(i = 1; i <= state->last_vertex; i++) {
12117                 struct reg_block *rb;
12118                 rb = &blocks[i];
12119                 replace_set_use(state, rb->in, orig, new);
12120                 replace_set_use(state, rb->out, orig, new);
12121         }
12122 }
12123
12124 static void color_instructions(struct compile_state *state)
12125 {
12126         struct triple *ins, *first;
12127         first = RHS(state->main_function, 0);
12128         ins = first;
12129         do {
12130                 if (triple_is_def(state, ins)) {
12131                         struct reg_info info;
12132                         info = find_lhs_color(state, ins, 0);
12133                         if (info.reg >= MAX_REGISTERS) {
12134                                 info.reg = REG_UNSET;
12135                         }
12136                         SET_INFO(ins->id, info);
12137                 }
12138                 ins = ins->next;
12139         } while(ins != first);
12140 }
12141
12142 static struct reg_info read_lhs_color(
12143         struct compile_state *state, struct triple *ins, int index)
12144 {
12145         struct reg_info info;
12146         if ((index == 0) && triple_is_def(state, ins)) {
12147                 info.reg   = ID_REG(ins->id);
12148                 info.regcm = ID_REGCM(ins->id);
12149         }
12150         else if (index < TRIPLE_LHS(ins->sizes)) {
12151                 info = read_lhs_color(state, LHS(ins, index), 0);
12152         }
12153         else {
12154                 internal_error(state, ins, "Bad lhs %d", index);
12155                 info.reg = REG_UNSET;
12156                 info.regcm = 0;
12157         }
12158         return info;
12159 }
12160
12161 static struct triple *resolve_tangle(
12162         struct compile_state *state, struct triple *tangle)
12163 {
12164         struct reg_info info, uinfo;
12165         struct triple_set *set, *next;
12166         struct triple *copy;
12167
12168 #warning "WISHLIST recalculate all affected instructions colors"
12169         info = find_lhs_color(state, tangle, 0);
12170         for(set = tangle->use; set; set = next) {
12171                 struct triple *user;
12172                 int i, zrhs;
12173                 next = set->next;
12174                 user = set->member;
12175                 zrhs = TRIPLE_RHS(user->sizes);
12176                 for(i = 0; i < zrhs; i++) {
12177                         if (RHS(user, i) != tangle) {
12178                                 continue;
12179                         }
12180                         uinfo = find_rhs_post_color(state, user, i);
12181                         if (uinfo.reg == info.reg) {
12182                                 copy = pre_copy(state, user, i);
12183                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12184                                 SET_INFO(copy->id, uinfo);
12185                         }
12186                 }
12187         }
12188         copy = 0;
12189         uinfo = find_lhs_pre_color(state, tangle, 0);
12190         if (uinfo.reg == info.reg) {
12191                 struct reg_info linfo;
12192                 copy = post_copy(state, tangle);
12193                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12194                 linfo = find_lhs_color(state, copy, 0);
12195                 SET_INFO(copy->id, linfo);
12196         }
12197         info = find_lhs_color(state, tangle, 0);
12198         SET_INFO(tangle->id, info);
12199         
12200         return copy;
12201 }
12202
12203
12204 static void fix_tangles(struct compile_state *state,
12205         struct reg_block *blocks, struct triple_reg_set *live,
12206         struct reg_block *rb, struct triple *ins, void *arg)
12207 {
12208         struct triple *tangle;
12209         do {
12210                 char used[MAX_REGISTERS];
12211                 struct triple_reg_set *set;
12212                 tangle = 0;
12213
12214                 /* Find out which registers have multiple uses at this point */
12215                 memset(used, 0, sizeof(used));
12216                 for(set = live; set; set = set->next) {
12217                         struct reg_info info;
12218                         info = read_lhs_color(state, set->member, 0);
12219                         if (info.reg == REG_UNSET) {
12220                                 continue;
12221                         }
12222                         reg_inc_used(state, used, info.reg);
12223                 }
12224                 
12225                 /* Now find the least dominated definition of a register in
12226                  * conflict I have seen so far.
12227                  */
12228                 for(set = live; set; set = set->next) {
12229                         struct reg_info info;
12230                         info = read_lhs_color(state, set->member, 0);
12231                         if (used[info.reg] < 2) {
12232                                 continue;
12233                         }
12234                         if (!tangle || tdominates(state, set->member, tangle)) {
12235                                 tangle = set->member;
12236                         }
12237                 }
12238                 /* If I have found a tangle resolve it */
12239                 if (tangle) {
12240                         struct triple *post_copy;
12241                         post_copy = resolve_tangle(state, tangle);
12242                         if (post_copy) {
12243                                 replace_block_use(state, blocks, tangle, post_copy);
12244                         }
12245                         if (post_copy && (tangle != ins)) {
12246                                 replace_set_use(state, live, tangle, post_copy);
12247                         }
12248                 }
12249         } while(tangle);
12250         return;
12251 }
12252
12253 static void correct_tangles(
12254         struct compile_state *state, struct reg_block *blocks)
12255 {
12256         color_instructions(state);
12257         walk_variable_lifetimes(state, blocks, fix_tangles, 0);
12258 }
12259
12260 struct least_conflict {
12261         struct reg_state *rstate;
12262         struct live_range *ref_range;
12263         struct triple *ins;
12264         struct triple_reg_set *live;
12265         size_t count;
12266         int constraints;
12267 };
12268 static void least_conflict(struct compile_state *state,
12269         struct reg_block *blocks, struct triple_reg_set *live,
12270         struct reg_block *rb, struct triple *ins, void *arg)
12271 {
12272         struct least_conflict *conflict = arg;
12273         struct live_range_edge *edge;
12274         struct triple_reg_set *set;
12275         size_t count;
12276         int constraints;
12277
12278 #warning "FIXME handle instructions with left hand sides..."
12279         /* Only instructions that introduce a new definition
12280          * can be the conflict instruction.
12281          */
12282         if (!triple_is_def(state, ins)) {
12283                 return;
12284         }
12285
12286         /* See if live ranges at this instruction are a
12287          * strict subset of the live ranges that are in conflict.
12288          */
12289         count = 0;
12290         for(set = live; set; set = set->next) {
12291                 struct live_range *lr;
12292                 lr = conflict->rstate->lrd[set->member->id].lr;
12293                 /* Ignore it if there cannot be an edge between these two nodes */
12294                 if (!arch_regcm_intersect(conflict->ref_range->classes, lr->classes)) {
12295                         continue;
12296                 }
12297                 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12298                         if (edge->node == lr) {
12299                                 break;
12300                         }
12301                 }
12302                 if (!edge && (lr != conflict->ref_range)) {
12303                         return;
12304                 }
12305                 count++;
12306         }
12307         if (count <= 1) {
12308                 return;
12309         }
12310
12311 #if 0
12312         /* See if there is an uncolored member in this subset. 
12313          */
12314          for(set = live; set; set = set->next) {
12315                 struct live_range *lr;
12316                 lr = conflict->rstate->lrd[set->member->id].lr;
12317                 if (lr->color == REG_UNSET) {
12318                         break;
12319                 }
12320         }
12321         if (!set && (conflict->ref_range != REG_UNSET)) {
12322                 return;
12323         }
12324 #endif
12325
12326         /* See if any of the live registers are constrained,
12327          * if not it won't be productive to pick this as
12328          * a conflict instruction.
12329          */
12330         constraints = 0;
12331         for(set = live; set; set = set->next) {
12332                 struct triple_set *uset;
12333                 struct reg_info info;
12334                 unsigned classes;
12335                 unsigned cur_size, size;
12336                 /* Skip this instruction */
12337                 if (set->member == ins) {
12338                         continue;
12339                 }
12340                 /* Find how many registers this value can potentially 
12341                  * be assigned to.
12342                  */
12343                 classes = arch_type_to_regcm(state, set->member->type);
12344                 size = regc_max_size(state, classes);
12345                 
12346                 /* Find how many registers we allow this value to
12347                  * be assigned to.
12348                  */
12349                 info = arch_reg_lhs(state, set->member, 0);
12350                 
12351                 /* If the value does not live in a register it
12352                  * isn't constrained.
12353                  */
12354                 if (info.reg == REG_UNNEEDED) {
12355                         continue;
12356                 }
12357                 
12358                 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12359                         cur_size = regc_max_size(state, info.regcm);
12360                 } else {
12361                         cur_size = 1;
12362                 }
12363
12364                 /* If there is no difference between potential and
12365                  * actual register count there is not a constraint
12366                  */
12367                 if (cur_size >= size) {
12368                         continue;
12369                 }
12370                 
12371                 /* If this live_range feeds into conflict->inds
12372                  * it isn't a constraint we can relieve.
12373                  */
12374                 for(uset = set->member->use; uset; uset = uset->next) {
12375                         if (uset->member == ins) {
12376                                 break;
12377                         }
12378                 }
12379                 if (uset) {
12380                         continue;
12381                 }
12382                 constraints = 1;
12383                 break;
12384         }
12385         /* Don't drop canidates with constraints */
12386         if (conflict->constraints && !constraints) {
12387                 return;
12388         }
12389
12390
12391 #if 0
12392         fprintf(stderr, "conflict ins? %p %s count: %d constraints: %d\n",
12393                 ins, tops(ins->op), count, constraints);
12394 #endif
12395         /* Find the instruction with the largest possible subset of
12396          * conflict ranges and that dominates any other instruction
12397          * with an equal sized set of conflicting ranges.
12398          */
12399         if ((count > conflict->count) ||
12400                 ((count == conflict->count) &&
12401                         tdominates(state, ins, conflict->ins))) {
12402                 struct triple_reg_set *next;
12403                 /* Remember the canidate instruction */
12404                 conflict->ins = ins;
12405                 conflict->count = count;
12406                 conflict->constraints = constraints;
12407                 /* Free the old collection of live registers */
12408                 for(set = conflict->live; set; set = next) {
12409                         next = set->next;
12410                         do_triple_unset(&conflict->live, set->member);
12411                 }
12412                 conflict->live = 0;
12413                 /* Rember the registers that are alive but do not feed
12414                  * into or out of conflict->ins.
12415                  */
12416                 for(set = live; set; set = set->next) {
12417                         struct triple **expr;
12418                         if (set->member == ins) {
12419                                 goto next;
12420                         }
12421                         expr = triple_rhs(state, ins, 0);
12422                         for(;expr; expr = triple_rhs(state, ins, expr)) {
12423                                 if (*expr == set->member) {
12424                                         goto next;
12425                                 }
12426                         }
12427                         expr = triple_lhs(state, ins, 0);
12428                         for(; expr; expr = triple_lhs(state, ins, expr)) {
12429                                 if (*expr == set->member) {
12430                                         goto next;
12431                                 }
12432                         }
12433                         do_triple_set(&conflict->live, set->member, set->new);
12434                 next:
12435                         ;
12436                 }
12437         }
12438         return;
12439 }
12440
12441 static void find_range_conflict(struct compile_state *state,
12442         struct reg_state *rstate, char *used, struct live_range *ref_range,
12443         struct least_conflict *conflict)
12444 {
12445
12446         /* there are 3 kinds ways conflicts can occure.
12447          * 1) the life time of 2 values simply overlap.
12448          * 2) the 2 values feed into the same instruction.
12449          * 3) the 2 values feed into a phi function.
12450          */
12451
12452         /* find the instruction where the problematic conflict comes
12453          * into existance.  that the instruction where all of
12454          * the values are alive, and among such instructions it is
12455          * the least dominated one.
12456          *
12457          * a value is alive an an instruction if either;
12458          * 1) the value defintion dominates the instruction and there
12459          *    is a use at or after that instrction
12460          * 2) the value definition feeds into a phi function in the
12461          *    same block as the instruction.  and the phi function
12462          *    is at or after the instruction.
12463          */
12464         memset(conflict, 0, sizeof(*conflict));
12465         conflict->rstate      = rstate;
12466         conflict->ref_range   = ref_range;
12467         conflict->ins         = 0;
12468         conflict->live        = 0;
12469         conflict->count       = 0;
12470         conflict->constraints = 0;
12471         walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12472
12473         if (!conflict->ins) {
12474                 internal_error(state, ref_range->defs->def, "No conflict ins?");
12475         }
12476         if (!conflict->live) {
12477                 internal_error(state, ref_range->defs->def, "No conflict live?");
12478         }
12479 #if 0
12480         fprintf(stderr, "conflict ins: %p %s count: %d constraints: %d\n", 
12481                 conflict->ins, tops(conflict->ins->op),
12482                 conflict->count, conflict->constraints);
12483 #endif
12484         return;
12485 }
12486
12487 static struct triple *split_constrained_range(struct compile_state *state, 
12488         struct reg_state *rstate, char *used, struct least_conflict *conflict)
12489 {
12490         unsigned constrained_size;
12491         struct triple *new, *constrained;
12492         struct triple_reg_set *cset;
12493         /* Find a range that is having problems because it is
12494          * artificially constrained.
12495          */
12496         constrained_size = ~0;
12497         constrained = 0;
12498         new = 0;
12499         for(cset = conflict->live; cset; cset = cset->next) {
12500                 struct triple_set *set;
12501                 struct reg_info info;
12502                 unsigned classes;
12503                 unsigned cur_size, size;
12504                 /* Skip the live range that starts with conflict->ins */
12505                 if (cset->member == conflict->ins) {
12506                         continue;
12507                 }
12508                 /* Find how many registers this value can potentially
12509                  * be assigned to.
12510                  */
12511                 classes = arch_type_to_regcm(state, cset->member->type);
12512                 size = regc_max_size(state, classes);
12513
12514                 /* Find how many registers we allow this value to
12515                  * be assigned to.
12516                  */
12517                 info = arch_reg_lhs(state, cset->member, 0);
12518
12519                 /* If the register doesn't need a register 
12520                  * splitting it can't help.
12521                  */
12522                 if (info.reg == REG_UNNEEDED) {
12523                         continue;
12524                 }
12525 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
12526                 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12527                         cur_size = regc_max_size(state, info.regcm);
12528                 } else {
12529                         cur_size = 1;
12530                 }
12531                 /* If this live_range feeds into conflict->ins
12532                  * splitting it is unlikely to help.
12533                  */
12534                 for(set = cset->member->use; set; set = set->next) {
12535                         if (set->member == conflict->ins) {
12536                                 goto next;
12537                         }
12538                 }
12539
12540                 /* If there is no difference between potential and
12541                  * actual register count there is nothing to do.
12542                  */
12543                 if (cur_size >= size) {
12544                         continue;
12545                 }
12546                 /* Of the constrained registers deal with the
12547                  * most constrained one first.
12548                  */
12549                 if (!constrained ||
12550                         (size < constrained_size)) {
12551                         constrained = cset->member;
12552                         constrained_size = size;
12553                 }
12554         next:
12555                 ;
12556         }
12557         if (constrained) {
12558                 new = post_copy(state, constrained);
12559                 new->id |= TRIPLE_FLAG_POST_SPLIT;
12560         }
12561         return new;
12562 }
12563
12564 static int split_ranges(
12565         struct compile_state *state, struct reg_state *rstate, 
12566         char *used, struct live_range *range)
12567 {
12568         struct triple *new;
12569
12570 #if 0
12571         fprintf(stderr, "split_ranges %d %s %p\n", 
12572                 rstate->passes, tops(range->defs->def->op), range->defs->def);
12573 #endif
12574         if ((range->color == REG_UNNEEDED) ||
12575                 (rstate->passes >= rstate->max_passes)) {
12576                 return 0;
12577         }
12578         new = 0;
12579         /* If I can't allocate a register something needs to be split */
12580         if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
12581                 struct least_conflict conflict;
12582
12583 #if 0
12584         fprintf(stderr, "find_range_conflict\n");
12585 #endif
12586                 /* Find where in the set of registers the conflict
12587                  * actually occurs.
12588                  */
12589                 find_range_conflict(state, rstate, used, range, &conflict);
12590
12591                 /* If a range has been artifically constrained split it */
12592                 new = split_constrained_range(state, rstate, used, &conflict);
12593                 
12594                 if (!new) {
12595                 /* Ideally I would split the live range that will not be used
12596                  * for the longest period of time in hopes that this will 
12597                  * (a) allow me to spill a register or
12598                  * (b) allow me to place a value in another register.
12599                  *
12600                  * So far I don't have a test case for this, the resolving
12601                  * of mandatory constraints has solved all of my
12602                  * know issues.  So I have choosen not to write any
12603                  * code until I cat get a better feel for cases where
12604                  * it would be useful to have.
12605                  *
12606                  */
12607 #warning "WISHLIST implement live range splitting..."
12608 #if 0
12609                         print_blocks(state, stderr);
12610                         print_dominators(state, stderr);
12611
12612 #endif
12613                         return 0;
12614                 }
12615         }
12616         if (new) {
12617                 rstate->lrd[rstate->defs].orig_id = new->id;
12618                 new->id = rstate->defs;
12619                 rstate->defs++;
12620 #if 0
12621                 fprintf(stderr, "new: %p old: %s %p\n", 
12622                         new, tops(RHS(new, 0)->op), RHS(new, 0));
12623 #endif
12624 #if 0
12625                 print_blocks(state, stderr);
12626                 print_dominators(state, stderr);
12627
12628 #endif
12629                 return 1;
12630         }
12631         return 0;
12632 }
12633
12634 #if DEBUG_COLOR_GRAPH > 1
12635 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
12636 #define cgdebug_flush() fflush(stdout)
12637 #elif DEBUG_COLOR_GRAPH == 1
12638 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
12639 #define cgdebug_flush() fflush(stderr)
12640 #else
12641 #define cgdebug_printf(...)
12642 #define cgdebug_flush()
12643 #endif
12644
12645         
12646 static int select_free_color(struct compile_state *state, 
12647         struct reg_state *rstate, struct live_range *range)
12648 {
12649         struct triple_set *entry;
12650         struct live_range_def *lrd;
12651         struct live_range_def *phi;
12652         struct live_range_edge *edge;
12653         char used[MAX_REGISTERS];
12654         struct triple **expr;
12655
12656         /* Instead of doing just the trivial color select here I try
12657          * a few extra things because a good color selection will help reduce
12658          * copies.
12659          */
12660
12661         /* Find the registers currently in use */
12662         memset(used, 0, sizeof(used));
12663         for(edge = range->edges; edge; edge = edge->next) {
12664                 if (edge->node->color == REG_UNSET) {
12665                         continue;
12666                 }
12667                 reg_fill_used(state, used, edge->node->color);
12668         }
12669 #if DEBUG_COLOR_GRAPH > 1
12670         {
12671                 int i;
12672                 i = 0;
12673                 for(edge = range->edges; edge; edge = edge->next) {
12674                         i++;
12675                 }
12676                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
12677                         tops(range->def->op), i, 
12678                         range->def->filename, range->def->line, range->def->col);
12679                 for(i = 0; i < MAX_REGISTERS; i++) {
12680                         if (used[i]) {
12681                                 cgdebug_printf("used: %s\n",
12682                                         arch_reg_str(i));
12683                         }
12684                 }
12685         }       
12686 #endif
12687
12688 #warning "FIXME detect conflicts caused by the source and destination being the same register"
12689
12690         /* If a color is already assigned see if it will work */
12691         if (range->color != REG_UNSET) {
12692                 struct live_range_def *lrd;
12693                 if (!used[range->color]) {
12694                         return 1;
12695                 }
12696                 for(edge = range->edges; edge; edge = edge->next) {
12697                         if (edge->node->color != range->color) {
12698                                 continue;
12699                         }
12700                         warning(state, edge->node->defs->def, "edge: ");
12701                         lrd = edge->node->defs;
12702                         do {
12703                                 warning(state, lrd->def, " %p %s",
12704                                         lrd->def, tops(lrd->def->op));
12705                                 lrd = lrd->next;
12706                         } while(lrd != edge->node->defs);
12707                 }
12708                 lrd = range->defs;
12709                 warning(state, range->defs->def, "def: ");
12710                 do {
12711                         warning(state, lrd->def, " %p %s",
12712                                 lrd->def, tops(lrd->def->op));
12713                         lrd = lrd->next;
12714                 } while(lrd != range->defs);
12715                 internal_error(state, range->defs->def,
12716                         "live range with already used color %s",
12717                         arch_reg_str(range->color));
12718         }
12719
12720         /* If I feed into an expression reuse it's color.
12721          * This should help remove copies in the case of 2 register instructions
12722          * and phi functions.
12723          */
12724         phi = 0;
12725         lrd = live_range_end(state, range, 0);
12726         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
12727                 entry = lrd->def->use;
12728                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
12729                         struct live_range_def *insd;
12730                         insd = &rstate->lrd[entry->member->id];
12731                         if (insd->lr->defs == 0) {
12732                                 continue;
12733                         }
12734                         if (!phi && (insd->def->op == OP_PHI) &&
12735                                 !interfere(rstate, range, insd->lr)) {
12736                                 phi = insd;
12737                         }
12738                         if ((insd->lr->color == REG_UNSET) ||
12739                                 ((insd->lr->classes & range->classes) == 0) ||
12740                                 (used[insd->lr->color])) {
12741                                 continue;
12742                         }
12743                         if (interfere(rstate, range, insd->lr)) {
12744                                 continue;
12745                         }
12746                         range->color = insd->lr->color;
12747                 }
12748         }
12749         /* If I feed into a phi function reuse it's color or the color
12750          * of something else that feeds into the phi function.
12751          */
12752         if (phi) {
12753                 if (phi->lr->color != REG_UNSET) {
12754                         if (used[phi->lr->color]) {
12755                                 range->color = phi->lr->color;
12756                         }
12757                 }
12758                 else {
12759                         expr = triple_rhs(state, phi->def, 0);
12760                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
12761                                 struct live_range *lr;
12762                                 if (!*expr) {
12763                                         continue;
12764                                 }
12765                                 lr = rstate->lrd[(*expr)->id].lr;
12766                                 if ((lr->color == REG_UNSET) || 
12767                                         ((lr->classes & range->classes) == 0) ||
12768                                         (used[lr->color])) {
12769                                         continue;
12770                                 }
12771                                 if (interfere(rstate, range, lr)) {
12772                                         continue;
12773                                 }
12774                                 range->color = lr->color;
12775                         }
12776                 }
12777         }
12778         /* If I don't interfere with a rhs node reuse it's color */
12779         lrd = live_range_head(state, range, 0);
12780         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
12781                 expr = triple_rhs(state, lrd->def, 0);
12782                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
12783                         struct live_range *lr;
12784                         if (!*expr) {
12785                                 continue;
12786                         }
12787                         lr = rstate->lrd[(*expr)->id].lr;
12788                         if ((lr->color == -1) || 
12789                                 ((lr->classes & range->classes) == 0) ||
12790                                 (used[lr->color])) {
12791                                 continue;
12792                         }
12793                         if (interfere(rstate, range, lr)) {
12794                                 continue;
12795                         }
12796                         range->color = lr->color;
12797                         break;
12798                 }
12799         }
12800         /* If I have not opportunitically picked a useful color
12801          * pick the first color that is free.
12802          */
12803         if (range->color == REG_UNSET) {
12804                 range->color = 
12805                         arch_select_free_register(state, used, range->classes);
12806         }
12807         if (range->color == REG_UNSET) {
12808                 struct live_range_def *lrd;
12809                 int i;
12810                 if (split_ranges(state, rstate, used, range)) {
12811                         return 0;
12812                 }
12813                 for(edge = range->edges; edge; edge = edge->next) {
12814                         warning(state, edge->node->defs->def, "edge reg %s",
12815                                 arch_reg_str(edge->node->color));
12816                         lrd = edge->node->defs;
12817                         do {
12818                                 warning(state, lrd->def, " %s",
12819                                         tops(lrd->def->op));
12820                                 lrd = lrd->next;
12821                         } while(lrd != edge->node->defs);
12822                 }
12823                 warning(state, range->defs->def, "range: ");
12824                 lrd = range->defs;
12825                 do {
12826                         warning(state, lrd->def, " %s",
12827                                 tops(lrd->def->op));
12828                         lrd = lrd->next;
12829                 } while(lrd != range->defs);
12830                         
12831                 warning(state, range->defs->def, "classes: %x",
12832                         range->classes);
12833                 for(i = 0; i < MAX_REGISTERS; i++) {
12834                         if (used[i]) {
12835                                 warning(state, range->defs->def, "used: %s",
12836                                         arch_reg_str(i));
12837                         }
12838                 }
12839 #if DEBUG_COLOR_GRAPH < 2
12840                 error(state, range->defs->def, "too few registers");
12841 #else
12842                 internal_error(state, range->defs->def, "too few registers");
12843 #endif
12844         }
12845         range->classes = arch_reg_regcm(state, range->color);
12846         if (range->color == -1) {
12847                 internal_error(state, range->defs->def, "select_free_color did not?");
12848         }
12849         return 1;
12850 }
12851
12852 static int color_graph(struct compile_state *state, struct reg_state *rstate)
12853 {
12854         int colored;
12855         struct live_range_edge *edge;
12856         struct live_range *range;
12857         if (rstate->low) {
12858                 cgdebug_printf("Lo: ");
12859                 range = rstate->low;
12860                 if (*range->group_prev != range) {
12861                         internal_error(state, 0, "lo: *prev != range?");
12862                 }
12863                 *range->group_prev = range->group_next;
12864                 if (range->group_next) {
12865                         range->group_next->group_prev = range->group_prev;
12866                 }
12867                 if (&range->group_next == rstate->low_tail) {
12868                         rstate->low_tail = range->group_prev;
12869                 }
12870                 if (rstate->low == range) {
12871                         internal_error(state, 0, "low: next != prev?");
12872                 }
12873         }
12874         else if (rstate->high) {
12875                 cgdebug_printf("Hi: ");
12876                 range = rstate->high;
12877                 if (*range->group_prev != range) {
12878                         internal_error(state, 0, "hi: *prev != range?");
12879                 }
12880                 *range->group_prev = range->group_next;
12881                 if (range->group_next) {
12882                         range->group_next->group_prev = range->group_prev;
12883                 }
12884                 if (&range->group_next == rstate->high_tail) {
12885                         rstate->high_tail = range->group_prev;
12886                 }
12887                 if (rstate->high == range) {
12888                         internal_error(state, 0, "high: next != prev?");
12889                 }
12890         }
12891         else {
12892                 return 1;
12893         }
12894         cgdebug_printf(" %d\n", range - rstate->lr);
12895         range->group_prev = 0;
12896         for(edge = range->edges; edge; edge = edge->next) {
12897                 struct live_range *node;
12898                 node = edge->node;
12899                 /* Move nodes from the high to the low list */
12900                 if (node->group_prev && (node->color == REG_UNSET) &&
12901                         (node->degree == regc_max_size(state, node->classes))) {
12902                         if (*node->group_prev != node) {
12903                                 internal_error(state, 0, "move: *prev != node?");
12904                         }
12905                         *node->group_prev = node->group_next;
12906                         if (node->group_next) {
12907                                 node->group_next->group_prev = node->group_prev;
12908                         }
12909                         if (&node->group_next == rstate->high_tail) {
12910                                 rstate->high_tail = node->group_prev;
12911                         }
12912                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
12913                         node->group_prev  = rstate->low_tail;
12914                         node->group_next  = 0;
12915                         *rstate->low_tail = node;
12916                         rstate->low_tail  = &node->group_next;
12917                         if (*node->group_prev != node) {
12918                                 internal_error(state, 0, "move2: *prev != node?");
12919                         }
12920                 }
12921                 node->degree -= 1;
12922         }
12923         colored = color_graph(state, rstate);
12924         if (colored) {
12925                 cgdebug_printf("Coloring %d @%s:%d.%d:", 
12926                         range - rstate->lr,
12927                         range->def->filename, range->def->line, range->def->col);
12928                 cgdebug_flush();
12929                 colored = select_free_color(state, rstate, range);
12930                 cgdebug_printf(" %s\n", arch_reg_str(range->color));
12931         }
12932         return colored;
12933 }
12934
12935 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
12936 {
12937         struct live_range *lr;
12938         struct live_range_edge *edge;
12939         struct triple *ins, *first;
12940         char used[MAX_REGISTERS];
12941         first = RHS(state->main_function, 0);
12942         ins = first;
12943         do {
12944                 if (triple_is_def(state, ins)) {
12945                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
12946                                 internal_error(state, ins, 
12947                                         "triple without a live range def");
12948                         }
12949                         lr = rstate->lrd[ins->id].lr;
12950                         if (lr->color == REG_UNSET) {
12951                                 internal_error(state, ins,
12952                                         "triple without a color");
12953                         }
12954                         /* Find the registers used by the edges */
12955                         memset(used, 0, sizeof(used));
12956                         for(edge = lr->edges; edge; edge = edge->next) {
12957                                 if (edge->node->color == REG_UNSET) {
12958                                         internal_error(state, 0,
12959                                                 "live range without a color");
12960                         }
12961                                 reg_fill_used(state, used, edge->node->color);
12962                         }
12963                         if (used[lr->color]) {
12964                                 internal_error(state, ins,
12965                                         "triple with already used color");
12966                         }
12967                 }
12968                 ins = ins->next;
12969         } while(ins != first);
12970 }
12971
12972 static void color_triples(struct compile_state *state, struct reg_state *rstate)
12973 {
12974         struct live_range *lr;
12975         struct triple *first, *ins;
12976         first = RHS(state->main_function, 0);
12977         ins = first;
12978         do {
12979                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12980                         internal_error(state, ins, 
12981                                 "triple without a live range");
12982                 }
12983                 lr = rstate->lrd[ins->id].lr;
12984                 SET_REG(ins->id, lr->color);
12985                 ins = ins->next;
12986         } while (ins != first);
12987 }
12988
12989 static void print_interference_block(
12990         struct compile_state *state, struct block *block, void *arg)
12991
12992 {
12993         struct reg_state *rstate = arg;
12994         struct reg_block *rb;
12995         struct triple *ptr;
12996         int phi_present;
12997         int done;
12998         rb = &rstate->blocks[block->vertex];
12999
13000         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
13001                 block, 
13002                 block->vertex,
13003                 block->left, 
13004                 block->left && block->left->use?block->left->use->member : 0,
13005                 block->right, 
13006                 block->right && block->right->use?block->right->use->member : 0);
13007         if (rb->in) {
13008                 struct triple_reg_set *in_set;
13009                 printf("        in:");
13010                 for(in_set = rb->in; in_set; in_set = in_set->next) {
13011                         printf(" %-10p", in_set->member);
13012                 }
13013                 printf("\n");
13014         }
13015         phi_present = 0;
13016         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13017                 done = (ptr == block->last);
13018                 if (ptr->op == OP_PHI) {
13019                         phi_present = 1;
13020                         break;
13021                 }
13022         }
13023         if (phi_present) {
13024                 int edge;
13025                 for(edge = 0; edge < block->users; edge++) {
13026                         printf("     in(%d):", edge);
13027                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13028                                 struct triple **slot;
13029                                 done = (ptr == block->last);
13030                                 if (ptr->op != OP_PHI) {
13031                                         continue;
13032                                 }
13033                                 slot = &RHS(ptr, 0);
13034                                 printf(" %-10p", slot[edge]);
13035                         }
13036                         printf("\n");
13037                 }
13038         }
13039         if (block->first->op == OP_LABEL) {
13040                 printf("%p:\n", block->first);
13041         }
13042         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13043                 struct triple_set *user;
13044                 struct live_range *lr;
13045                 unsigned id;
13046                 int op;
13047                 op = ptr->op;
13048                 done = (ptr == block->last);
13049                 lr = rstate->lrd[ptr->id].lr;
13050                 
13051                 if (triple_stores_block(state, ptr)) {
13052                         if (ptr->u.block != block) {
13053                                 internal_error(state, ptr, 
13054                                         "Wrong block pointer: %p",
13055                                         ptr->u.block);
13056                         }
13057                 }
13058                 if (op == OP_ADECL) {
13059                         for(user = ptr->use; user; user = user->next) {
13060                                 if (!user->member->u.block) {
13061                                         internal_error(state, user->member, 
13062                                                 "Use %p not in a block?",
13063                                                 user->member);
13064                                 }
13065                                 
13066                         }
13067                 }
13068                 id = ptr->id;
13069                 SET_REG(ptr->id, lr->color);
13070                 display_triple(stdout, ptr);
13071                 ptr->id = id;
13072
13073                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
13074                         internal_error(state, ptr, "lr has no defs!");
13075                 }
13076
13077                 if (lr->defs) {
13078                         struct live_range_def *lrd;
13079                         printf("       range:");
13080                         lrd = lr->defs;
13081                         do {
13082                                 printf(" %-10p", lrd->def);
13083                                 lrd = lrd->next;
13084                         } while(lrd != lr->defs);
13085                         printf("\n");
13086                 }
13087                 if (lr->edges > 0) {
13088                         struct live_range_edge *edge;
13089                         printf("       edges:");
13090                         for(edge = lr->edges; edge; edge = edge->next) {
13091                                 struct live_range_def *lrd;
13092                                 lrd = edge->node->defs;
13093                                 do {
13094                                         printf(" %-10p", lrd->def);
13095                                         lrd = lrd->next;
13096                                 } while(lrd != edge->node->defs);
13097                                 printf("|");
13098                         }
13099                         printf("\n");
13100                 }
13101                 /* Do a bunch of sanity checks */
13102                 valid_ins(state, ptr);
13103                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
13104                         internal_error(state, ptr, "Invalid triple id: %d",
13105                                 ptr->id);
13106                 }
13107                 for(user = ptr->use; user; user = user->next) {
13108                         struct triple *use;
13109                         struct live_range *ulr;
13110                         use = user->member;
13111                         valid_ins(state, use);
13112                         if ((use->id < 0) || (use->id > rstate->defs)) {
13113                                 internal_error(state, use, "Invalid triple id: %d",
13114                                         use->id);
13115                         }
13116                         ulr = rstate->lrd[user->member->id].lr;
13117                         if (triple_stores_block(state, user->member) &&
13118                                 !user->member->u.block) {
13119                                 internal_error(state, user->member,
13120                                         "Use %p not in a block?",
13121                                         user->member);
13122                         }
13123                 }
13124         }
13125         if (rb->out) {
13126                 struct triple_reg_set *out_set;
13127                 printf("       out:");
13128                 for(out_set = rb->out; out_set; out_set = out_set->next) {
13129                         printf(" %-10p", out_set->member);
13130                 }
13131                 printf("\n");
13132         }
13133         printf("\n");
13134 }
13135
13136 static struct live_range *merge_sort_lr(
13137         struct live_range *first, struct live_range *last)
13138 {
13139         struct live_range *mid, *join, **join_tail, *pick;
13140         size_t size;
13141         size = (last - first) + 1;
13142         if (size >= 2) {
13143                 mid = first + size/2;
13144                 first = merge_sort_lr(first, mid -1);
13145                 mid   = merge_sort_lr(mid, last);
13146                 
13147                 join = 0;
13148                 join_tail = &join;
13149                 /* merge the two lists */
13150                 while(first && mid) {
13151                         if ((first->degree < mid->degree) ||
13152                                 ((first->degree == mid->degree) &&
13153                                         (first->length < mid->length))) {
13154                                 pick = first;
13155                                 first = first->group_next;
13156                                 if (first) {
13157                                         first->group_prev = 0;
13158                                 }
13159                         }
13160                         else {
13161                                 pick = mid;
13162                                 mid = mid->group_next;
13163                                 if (mid) {
13164                                         mid->group_prev = 0;
13165                                 }
13166                         }
13167                         pick->group_next = 0;
13168                         pick->group_prev = join_tail;
13169                         *join_tail = pick;
13170                         join_tail = &pick->group_next;
13171                 }
13172                 /* Splice the remaining list */
13173                 pick = (first)? first : mid;
13174                 *join_tail = pick;
13175                 if (pick) { 
13176                         pick->group_prev = join_tail;
13177                 }
13178         }
13179         else {
13180                 if (!first->defs) {
13181                         first = 0;
13182                 }
13183                 join = first;
13184         }
13185         return join;
13186 }
13187
13188 static void ids_from_rstate(struct compile_state *state, 
13189         struct reg_state *rstate)
13190 {
13191         struct triple *ins, *first;
13192         if (!rstate->defs) {
13193                 return;
13194         }
13195         /* Display the graph if desired */
13196         if (state->debug & DEBUG_INTERFERENCE) {
13197                 print_blocks(state, stdout);
13198                 print_control_flow(state);
13199         }
13200         first = RHS(state->main_function, 0);
13201         ins = first;
13202         do {
13203                 if (ins->id) {
13204                         struct live_range_def *lrd;
13205                         lrd = &rstate->lrd[ins->id];
13206                         ins->id = lrd->orig_id;
13207                 }
13208                 ins = ins->next;
13209         } while(ins != first);
13210 }
13211
13212 static void cleanup_live_edges(struct reg_state *rstate)
13213 {
13214         int i;
13215         /* Free the edges on each node */
13216         for(i = 1; i <= rstate->ranges; i++) {
13217                 remove_live_edges(rstate, &rstate->lr[i]);
13218         }
13219 }
13220
13221 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13222 {
13223         cleanup_live_edges(rstate);
13224         xfree(rstate->lrd);
13225         xfree(rstate->lr);
13226
13227         /* Free the variable lifetime information */
13228         if (rstate->blocks) {
13229                 free_variable_lifetimes(state, rstate->blocks);
13230         }
13231         rstate->defs = 0;
13232         rstate->ranges = 0;
13233         rstate->lrd = 0;
13234         rstate->lr = 0;
13235         rstate->blocks = 0;
13236 }
13237
13238 static void allocate_registers(struct compile_state *state)
13239 {
13240         struct reg_state rstate;
13241         int colored;
13242
13243         /* Clear out the reg_state */
13244         memset(&rstate, 0, sizeof(rstate));
13245         rstate.max_passes = MAX_ALLOCATION_PASSES;
13246
13247         do {
13248                 struct live_range **point, **next;
13249                 int coalesced;
13250
13251                 /* Restore ids */
13252                 ids_from_rstate(state, &rstate);
13253
13254                 /* Cleanup the temporary data structures */
13255                 cleanup_rstate(state, &rstate);
13256
13257                 /* Compute the variable lifetimes */
13258                 rstate.blocks = compute_variable_lifetimes(state);
13259
13260                 /* Fix invalid mandatory live range coalesce conflicts */
13261                 walk_variable_lifetimes(
13262                         state, rstate.blocks, fix_coalesce_conflicts, 0);
13263
13264                 /* Fix two simultaneous uses of the same register */
13265                 correct_tangles(state, rstate.blocks);
13266
13267                 if (state->debug & DEBUG_INSERTED_COPIES) {
13268                         printf("After resolve_tangles\n");
13269                         print_blocks(state, stdout);
13270                         print_control_flow(state);
13271                 }
13272
13273                 
13274                 /* Allocate and initialize the live ranges */
13275                 initialize_live_ranges(state, &rstate);
13276                 
13277                 do {
13278                         /* Forget previous live range edge calculations */
13279                         cleanup_live_edges(&rstate);
13280
13281                         /* Compute the interference graph */
13282                         walk_variable_lifetimes(
13283                                 state, rstate.blocks, graph_ins, &rstate);
13284                 
13285                         /* Display the interference graph if desired */
13286                         if (state->debug & DEBUG_INTERFERENCE) {
13287                                 printf("\nlive variables by block\n");
13288                                 walk_blocks(state, print_interference_block, &rstate);
13289                                 printf("\nlive variables by instruction\n");
13290                                 walk_variable_lifetimes(
13291                                         state, rstate.blocks, 
13292                                         print_interference_ins, &rstate);
13293                         }
13294                         
13295                         coalesced = coalesce_live_ranges(state, &rstate);
13296                 } while(coalesced);
13297                         
13298                 /* Build the groups low and high.  But with the nodes
13299                  * first sorted by degree order.
13300                  */
13301                 rstate.low_tail  = &rstate.low;
13302                 rstate.high_tail = &rstate.high;
13303                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13304                 if (rstate.high) {
13305                         rstate.high->group_prev = &rstate.high;
13306                 }
13307                 for(point = &rstate.high; *point; point = &(*point)->group_next)
13308                         ;
13309                 rstate.high_tail = point;
13310                 /* Walk through the high list and move everything that needs
13311                  * to be onto low.
13312                  */
13313                 for(point = &rstate.high; *point; point = next) {
13314                         struct live_range *range;
13315                         next = &(*point)->group_next;
13316                         range = *point;
13317                         
13318                         /* If it has a low degree or it already has a color
13319                          * place the node in low.
13320                          */
13321                         if ((range->degree < regc_max_size(state, range->classes)) ||
13322                                 (range->color != REG_UNSET)) {
13323                                 cgdebug_printf("Lo: %5d degree %5d%s\n", 
13324                                         range - rstate.lr, range->degree,
13325                                         (range->color != REG_UNSET) ? " (colored)": "");
13326                                 *range->group_prev = range->group_next;
13327                                 if (range->group_next) {
13328                                         range->group_next->group_prev = range->group_prev;
13329                                 }
13330                                 if (&range->group_next == rstate.high_tail) {
13331                                         rstate.high_tail = range->group_prev;
13332                                 }
13333                                 range->group_prev  = rstate.low_tail;
13334                                 range->group_next  = 0;
13335                                 *rstate.low_tail   = range;
13336                                 rstate.low_tail    = &range->group_next;
13337                                 next = point;
13338                         }
13339                         else {
13340                                 cgdebug_printf("hi: %5d degree %5d%s\n", 
13341                                         range - rstate.lr, range->degree,
13342                                         (range->color != REG_UNSET) ? " (colored)": "");
13343                         }
13344                 }
13345                 /* Color the live_ranges */
13346                 colored = color_graph(state, &rstate);
13347                 rstate.passes++;
13348         } while (!colored);
13349
13350         /* Verify the graph was properly colored */
13351         verify_colors(state, &rstate);
13352
13353         /* Move the colors from the graph to the triples */
13354         color_triples(state, &rstate);
13355
13356         /* Cleanup the temporary data structures */
13357         cleanup_rstate(state, &rstate);
13358 }
13359
13360 /* Sparce Conditional Constant Propogation
13361  * =========================================
13362  */
13363 struct ssa_edge;
13364 struct flow_block;
13365 struct lattice_node {
13366         unsigned old_id;
13367         struct triple *def;
13368         struct ssa_edge *out;
13369         struct flow_block *fblock;
13370         struct triple *val;
13371         /* lattice high   val && !is_const(val) 
13372          * lattice const  is_const(val)
13373          * lattice low    val == 0
13374          */
13375 };
13376 struct ssa_edge {
13377         struct lattice_node *src;
13378         struct lattice_node *dst;
13379         struct ssa_edge *work_next;
13380         struct ssa_edge *work_prev;
13381         struct ssa_edge *out_next;
13382 };
13383 struct flow_edge {
13384         struct flow_block *src;
13385         struct flow_block *dst;
13386         struct flow_edge *work_next;
13387         struct flow_edge *work_prev;
13388         struct flow_edge *in_next;
13389         struct flow_edge *out_next;
13390         int executable;
13391 };
13392 struct flow_block {
13393         struct block *block;
13394         struct flow_edge *in;
13395         struct flow_edge *out;
13396         struct flow_edge left, right;
13397 };
13398
13399 struct scc_state {
13400         int ins_count;
13401         struct lattice_node *lattice;
13402         struct ssa_edge     *ssa_edges;
13403         struct flow_block   *flow_blocks;
13404         struct flow_edge    *flow_work_list;
13405         struct ssa_edge     *ssa_work_list;
13406 };
13407
13408
13409 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
13410         struct flow_edge *fedge)
13411 {
13412         if (!scc->flow_work_list) {
13413                 scc->flow_work_list = fedge;
13414                 fedge->work_next = fedge->work_prev = fedge;
13415         }
13416         else {
13417                 struct flow_edge *ftail;
13418                 ftail = scc->flow_work_list->work_prev;
13419                 fedge->work_next = ftail->work_next;
13420                 fedge->work_prev = ftail;
13421                 fedge->work_next->work_prev = fedge;
13422                 fedge->work_prev->work_next = fedge;
13423         }
13424 }
13425
13426 static struct flow_edge *scc_next_fedge(
13427         struct compile_state *state, struct scc_state *scc)
13428 {
13429         struct flow_edge *fedge;
13430         fedge = scc->flow_work_list;
13431         if (fedge) {
13432                 fedge->work_next->work_prev = fedge->work_prev;
13433                 fedge->work_prev->work_next = fedge->work_next;
13434                 if (fedge->work_next != fedge) {
13435                         scc->flow_work_list = fedge->work_next;
13436                 } else {
13437                         scc->flow_work_list = 0;
13438                 }
13439         }
13440         return fedge;
13441 }
13442
13443 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13444         struct ssa_edge *sedge)
13445 {
13446         if (!scc->ssa_work_list) {
13447                 scc->ssa_work_list = sedge;
13448                 sedge->work_next = sedge->work_prev = sedge;
13449         }
13450         else {
13451                 struct ssa_edge *stail;
13452                 stail = scc->ssa_work_list->work_prev;
13453                 sedge->work_next = stail->work_next;
13454                 sedge->work_prev = stail;
13455                 sedge->work_next->work_prev = sedge;
13456                 sedge->work_prev->work_next = sedge;
13457         }
13458 }
13459
13460 static struct ssa_edge *scc_next_sedge(
13461         struct compile_state *state, struct scc_state *scc)
13462 {
13463         struct ssa_edge *sedge;
13464         sedge = scc->ssa_work_list;
13465         if (sedge) {
13466                 sedge->work_next->work_prev = sedge->work_prev;
13467                 sedge->work_prev->work_next = sedge->work_next;
13468                 if (sedge->work_next != sedge) {
13469                         scc->ssa_work_list = sedge->work_next;
13470                 } else {
13471                         scc->ssa_work_list = 0;
13472                 }
13473         }
13474         return sedge;
13475 }
13476
13477 static void initialize_scc_state(
13478         struct compile_state *state, struct scc_state *scc)
13479 {
13480         int ins_count, ssa_edge_count;
13481         int ins_index, ssa_edge_index, fblock_index;
13482         struct triple *first, *ins;
13483         struct block *block;
13484         struct flow_block *fblock;
13485
13486         memset(scc, 0, sizeof(*scc));
13487
13488         /* Inialize pass zero find out how much memory we need */
13489         first = RHS(state->main_function, 0);
13490         ins = first;
13491         ins_count = ssa_edge_count = 0;
13492         do {
13493                 struct triple_set *edge;
13494                 ins_count += 1;
13495                 for(edge = ins->use; edge; edge = edge->next) {
13496                         ssa_edge_count++;
13497                 }
13498                 ins = ins->next;
13499         } while(ins != first);
13500 #if DEBUG_SCC
13501         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13502                 ins_count, ssa_edge_count, state->last_vertex);
13503 #endif
13504         scc->ins_count   = ins_count;
13505         scc->lattice     = 
13506                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13507         scc->ssa_edges   = 
13508                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13509         scc->flow_blocks = 
13510                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
13511                         "flow_blocks");
13512
13513         /* Initialize pass one collect up the nodes */
13514         fblock = 0;
13515         block = 0;
13516         ins_index = ssa_edge_index = fblock_index = 0;
13517         ins = first;
13518         do {
13519                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13520                         block = ins->u.block;
13521                         if (!block) {
13522                                 internal_error(state, ins, "label without block");
13523                         }
13524                         fblock_index += 1;
13525                         block->vertex = fblock_index;
13526                         fblock = &scc->flow_blocks[fblock_index];
13527                         fblock->block = block;
13528                 }
13529                 {
13530                         struct lattice_node *lnode;
13531                         ins_index += 1;
13532                         lnode = &scc->lattice[ins_index];
13533                         lnode->def = ins;
13534                         lnode->out = 0;
13535                         lnode->fblock = fblock;
13536                         lnode->val = ins; /* LATTICE HIGH */
13537                         lnode->old_id = ins->id;
13538                         ins->id = ins_index;
13539                 }
13540                 ins = ins->next;
13541         } while(ins != first);
13542         /* Initialize pass two collect up the edges */
13543         block = 0;
13544         fblock = 0;
13545         ins = first;
13546         do {
13547                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13548                         struct flow_edge *fedge, **ftail;
13549                         struct block_set *bedge;
13550                         block = ins->u.block;
13551                         fblock = &scc->flow_blocks[block->vertex];
13552                         fblock->in = 0;
13553                         fblock->out = 0;
13554                         ftail = &fblock->out;
13555                         if (block->left) {
13556                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13557                                 if (fblock->left.dst->block != block->left) {
13558                                         internal_error(state, 0, "block mismatch");
13559                                 }
13560                                 fblock->left.out_next = 0;
13561                                 *ftail = &fblock->left;
13562                                 ftail = &fblock->left.out_next;
13563                         }
13564                         if (block->right) {
13565                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13566                                 if (fblock->right.dst->block != block->right) {
13567                                         internal_error(state, 0, "block mismatch");
13568                                 }
13569                                 fblock->right.out_next = 0;
13570                                 *ftail = &fblock->right;
13571                                 ftail = &fblock->right.out_next;
13572                         }
13573                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13574                                 fedge->src = fblock;
13575                                 fedge->work_next = fedge->work_prev = fedge;
13576                                 fedge->executable = 0;
13577                         }
13578                         ftail = &fblock->in;
13579                         for(bedge = block->use; bedge; bedge = bedge->next) {
13580                                 struct block *src_block;
13581                                 struct flow_block *sfblock;
13582                                 struct flow_edge *sfedge;
13583                                 src_block = bedge->member;
13584                                 sfblock = &scc->flow_blocks[src_block->vertex];
13585                                 sfedge = 0;
13586                                 if (src_block->left == block) {
13587                                         sfedge = &sfblock->left;
13588                                 } else {
13589                                         sfedge = &sfblock->right;
13590                                 }
13591                                 *ftail = sfedge;
13592                                 ftail = &sfedge->in_next;
13593                                 sfedge->in_next = 0;
13594                         }
13595                 }
13596                 {
13597                         struct triple_set *edge;
13598                         struct ssa_edge **stail;
13599                         struct lattice_node *lnode;
13600                         lnode = &scc->lattice[ins->id];
13601                         lnode->out = 0;
13602                         stail = &lnode->out;
13603                         for(edge = ins->use; edge; edge = edge->next) {
13604                                 struct ssa_edge *sedge;
13605                                 ssa_edge_index += 1;
13606                                 sedge = &scc->ssa_edges[ssa_edge_index];
13607                                 *stail = sedge;
13608                                 stail = &sedge->out_next;
13609                                 sedge->src = lnode;
13610                                 sedge->dst = &scc->lattice[edge->member->id];
13611                                 sedge->work_next = sedge->work_prev = sedge;
13612                                 sedge->out_next = 0;
13613                         }
13614                 }
13615                 ins = ins->next;
13616         } while(ins != first);
13617         /* Setup a dummy block 0 as a node above the start node */
13618         {
13619                 struct flow_block *fblock, *dst;
13620                 struct flow_edge *fedge;
13621                 fblock = &scc->flow_blocks[0];
13622                 fblock->block = 0;
13623                 fblock->in = 0;
13624                 fblock->out = &fblock->left;
13625                 dst = &scc->flow_blocks[state->first_block->vertex];
13626                 fedge = &fblock->left;
13627                 fedge->src        = fblock;
13628                 fedge->dst        = dst;
13629                 fedge->work_next  = fedge;
13630                 fedge->work_prev  = fedge;
13631                 fedge->in_next    = fedge->dst->in;
13632                 fedge->out_next   = 0;
13633                 fedge->executable = 0;
13634                 fedge->dst->in = fedge;
13635                 
13636                 /* Initialize the work lists */
13637                 scc->flow_work_list = 0;
13638                 scc->ssa_work_list  = 0;
13639                 scc_add_fedge(state, scc, fedge);
13640         }
13641 #if DEBUG_SCC
13642         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
13643                 ins_index, ssa_edge_index, fblock_index);
13644 #endif
13645 }
13646
13647         
13648 static void free_scc_state(
13649         struct compile_state *state, struct scc_state *scc)
13650 {
13651         xfree(scc->flow_blocks);
13652         xfree(scc->ssa_edges);
13653         xfree(scc->lattice);
13654         
13655 }
13656
13657 static struct lattice_node *triple_to_lattice(
13658         struct compile_state *state, struct scc_state *scc, struct triple *ins)
13659 {
13660         if (ins->id <= 0) {
13661                 internal_error(state, ins, "bad id");
13662         }
13663         return &scc->lattice[ins->id];
13664 }
13665
13666 static struct triple *preserve_lval(
13667         struct compile_state *state, struct lattice_node *lnode)
13668 {
13669         struct triple *old;
13670         /* Preserve the original value */
13671         if (lnode->val) {
13672                 old = dup_triple(state, lnode->val);
13673                 if (lnode->val != lnode->def) {
13674                         xfree(lnode->val);
13675                 }
13676                 lnode->val = 0;
13677         } else {
13678                 old = 0;
13679         }
13680         return old;
13681 }
13682
13683 static int lval_changed(struct compile_state *state, 
13684         struct triple *old, struct lattice_node *lnode)
13685 {
13686         int changed;
13687         /* See if the lattice value has changed */
13688         changed = 1;
13689         if (!old && !lnode->val) {
13690                 changed = 0;
13691         }
13692         if (changed && lnode->val && !is_const(lnode->val)) {
13693                 changed = 0;
13694         }
13695         if (changed &&
13696                 lnode->val && old &&
13697                 (memcmp(lnode->val->param, old->param,
13698                         TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
13699                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
13700                 changed = 0;
13701         }
13702         if (old) {
13703                 xfree(old);
13704         }
13705         return changed;
13706
13707 }
13708
13709 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
13710         struct lattice_node *lnode)
13711 {
13712         struct lattice_node *tmp;
13713         struct triple **slot, *old;
13714         struct flow_edge *fedge;
13715         int index;
13716         if (lnode->def->op != OP_PHI) {
13717                 internal_error(state, lnode->def, "not phi");
13718         }
13719         /* Store the original value */
13720         old = preserve_lval(state, lnode);
13721
13722         /* default to lattice high */
13723         lnode->val = lnode->def;
13724         slot = &RHS(lnode->def, 0);
13725         index = 0;
13726         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
13727                 if (!fedge->executable) {
13728                         continue;
13729                 }
13730                 if (!slot[index]) {
13731                         internal_error(state, lnode->def, "no phi value");
13732                 }
13733                 tmp = triple_to_lattice(state, scc, slot[index]);
13734                 /* meet(X, lattice low) = lattice low */
13735                 if (!tmp->val) {
13736                         lnode->val = 0;
13737                 }
13738                 /* meet(X, lattice high) = X */
13739                 else if (!tmp->val) {
13740                         lnode->val = lnode->val;
13741                 }
13742                 /* meet(lattice high, X) = X */
13743                 else if (!is_const(lnode->val)) {
13744                         lnode->val = dup_triple(state, tmp->val);
13745                         lnode->val->type = lnode->def->type;
13746                 }
13747                 /* meet(const, const) = const or lattice low */
13748                 else if (!constants_equal(state, lnode->val, tmp->val)) {
13749                         lnode->val = 0;
13750                 }
13751                 if (!lnode->val) {
13752                         break;
13753                 }
13754         }
13755 #if DEBUG_SCC
13756         fprintf(stderr, "phi: %d -> %s\n",
13757                 lnode->def->id,
13758                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13759 #endif
13760         /* If the lattice value has changed update the work lists. */
13761         if (lval_changed(state, old, lnode)) {
13762                 struct ssa_edge *sedge;
13763                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13764                         scc_add_sedge(state, scc, sedge);
13765                 }
13766         }
13767 }
13768
13769 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
13770         struct lattice_node *lnode)
13771 {
13772         int changed;
13773         struct triple *old, *scratch;
13774         struct triple **dexpr, **vexpr;
13775         int count, i;
13776         
13777         /* Store the original value */
13778         old = preserve_lval(state, lnode);
13779
13780         /* Reinitialize the value */
13781         lnode->val = scratch = dup_triple(state, lnode->def);
13782         scratch->id = lnode->old_id;
13783         scratch->next     = scratch;
13784         scratch->prev     = scratch;
13785         scratch->use      = 0;
13786
13787         count = TRIPLE_SIZE(scratch->sizes);
13788         for(i = 0; i < count; i++) {
13789                 dexpr = &lnode->def->param[i];
13790                 vexpr = &scratch->param[i];
13791                 *vexpr = *dexpr;
13792                 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13793                         (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13794                         *dexpr) {
13795                         struct lattice_node *tmp;
13796                         tmp = triple_to_lattice(state, scc, *dexpr);
13797                         *vexpr = (tmp->val)? tmp->val : tmp->def;
13798                 }
13799         }
13800         if (scratch->op == OP_BRANCH) {
13801                 scratch->next = lnode->def->next;
13802         }
13803         /* Recompute the value */
13804 #warning "FIXME see if simplify does anything bad"
13805         /* So far it looks like only the strength reduction
13806          * optimization are things I need to worry about.
13807          */
13808         simplify(state, scratch);
13809         /* Cleanup my value */
13810         if (scratch->use) {
13811                 internal_error(state, lnode->def, "scratch used?");
13812         }
13813         if ((scratch->prev != scratch) ||
13814                 ((scratch->next != scratch) &&
13815                         ((lnode->def->op != OP_BRANCH) ||
13816                                 (scratch->next != lnode->def->next)))) {
13817                 internal_error(state, lnode->def, "scratch in list?");
13818         }
13819         /* undo any uses... */
13820         count = TRIPLE_SIZE(scratch->sizes);
13821         for(i = 0; i < count; i++) {
13822                 vexpr = &scratch->param[i];
13823                 if (*vexpr) {
13824                         unuse_triple(*vexpr, scratch);
13825                 }
13826         }
13827         if (!is_const(scratch)) {
13828                 for(i = 0; i < count; i++) {
13829                         dexpr = &lnode->def->param[i];
13830                         if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13831                                 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13832                                 *dexpr) {
13833                                 struct lattice_node *tmp;
13834                                 tmp = triple_to_lattice(state, scc, *dexpr);
13835                                 if (!tmp->val) {
13836                                         lnode->val = 0;
13837                                 }
13838                         }
13839                 }
13840         }
13841         if (lnode->val && 
13842                 (lnode->val->op == lnode->def->op) &&
13843                 (memcmp(lnode->val->param, lnode->def->param, 
13844                         count * sizeof(lnode->val->param[0])) == 0) &&
13845                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
13846                 lnode->val = lnode->def;
13847         }
13848         /* Find the cases that are always lattice lo */
13849         if (lnode->val && 
13850                 triple_is_def(state, lnode->val) &&
13851                 !triple_is_pure(state, lnode->val)) {
13852                 lnode->val = 0;
13853         }
13854         if (lnode->val && 
13855                 (lnode->val->op == OP_SDECL) && 
13856                 (lnode->val != lnode->def)) {
13857                 internal_error(state, lnode->def, "bad sdecl");
13858         }
13859         /* See if the lattice value has changed */
13860         changed = lval_changed(state, old, lnode);
13861         if (lnode->val != scratch) {
13862                 xfree(scratch);
13863         }
13864         return changed;
13865 }
13866
13867 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
13868         struct lattice_node *lnode)
13869 {
13870         struct lattice_node *cond;
13871 #if DEBUG_SCC
13872         {
13873                 struct flow_edge *fedge;
13874                 fprintf(stderr, "branch: %d (",
13875                         lnode->def->id);
13876                 
13877                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
13878                         fprintf(stderr, " %d", fedge->dst->block->vertex);
13879                 }
13880                 fprintf(stderr, " )");
13881                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
13882                         fprintf(stderr, " <- %d",
13883                                 RHS(lnode->def, 0)->id);
13884                 }
13885                 fprintf(stderr, "\n");
13886         }
13887 #endif
13888         if (lnode->def->op != OP_BRANCH) {
13889                 internal_error(state, lnode->def, "not branch");
13890         }
13891         /* This only applies to conditional branches */
13892         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
13893                 return;
13894         }
13895         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
13896         if (cond->val && !is_const(cond->val)) {
13897 #warning "FIXME do I need to do something here?"
13898                 warning(state, cond->def, "condition not constant?");
13899                 return;
13900         }
13901         if (cond->val == 0) {
13902                 scc_add_fedge(state, scc, cond->fblock->out);
13903                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13904         }
13905         else if (cond->val->u.cval) {
13906                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13907                 
13908         } else {
13909                 scc_add_fedge(state, scc, cond->fblock->out);
13910         }
13911
13912 }
13913
13914 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
13915         struct lattice_node *lnode)
13916 {
13917         int changed;
13918
13919         changed = compute_lnode_val(state, scc, lnode);
13920 #if DEBUG_SCC
13921         {
13922                 struct triple **expr;
13923                 fprintf(stderr, "expr: %3d %10s (",
13924                         lnode->def->id, tops(lnode->def->op));
13925                 expr = triple_rhs(state, lnode->def, 0);
13926                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
13927                         if (*expr) {
13928                                 fprintf(stderr, " %d", (*expr)->id);
13929                         }
13930                 }
13931                 fprintf(stderr, " ) -> %s\n",
13932                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13933         }
13934 #endif
13935         if (lnode->def->op == OP_BRANCH) {
13936                 scc_visit_branch(state, scc, lnode);
13937
13938         }
13939         else if (changed) {
13940                 struct ssa_edge *sedge;
13941                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13942                         scc_add_sedge(state, scc, sedge);
13943                 }
13944         }
13945 }
13946
13947 static void scc_writeback_values(
13948         struct compile_state *state, struct scc_state *scc)
13949 {
13950         struct triple *first, *ins;
13951         first = RHS(state->main_function, 0);
13952         ins = first;
13953         do {
13954                 struct lattice_node *lnode;
13955                 lnode = triple_to_lattice(state, scc, ins);
13956                 /* Restore id */
13957                 ins->id = lnode->old_id;
13958 #if DEBUG_SCC
13959                 if (lnode->val && !is_const(lnode->val)) {
13960                         warning(state, lnode->def, 
13961                                 "lattice node still high?");
13962                 }
13963 #endif
13964                 if (lnode->val && (lnode->val != ins)) {
13965                         /* See if it something I know how to write back */
13966                         switch(lnode->val->op) {
13967                         case OP_INTCONST:
13968                                 mkconst(state, ins, lnode->val->u.cval);
13969                                 break;
13970                         case OP_ADDRCONST:
13971                                 mkaddr_const(state, ins, 
13972                                         MISC(lnode->val, 0), lnode->val->u.cval);
13973                                 break;
13974                         default:
13975                                 /* By default don't copy the changes,
13976                                  * recompute them in place instead.
13977                                  */
13978                                 simplify(state, ins);
13979                                 break;
13980                         }
13981                         if (is_const(lnode->val) &&
13982                                 !constants_equal(state, lnode->val, ins)) {
13983                                 internal_error(state, 0, "constants not equal");
13984                         }
13985                         /* Free the lattice nodes */
13986                         xfree(lnode->val);
13987                         lnode->val = 0;
13988                 }
13989                 ins = ins->next;
13990         } while(ins != first);
13991 }
13992
13993 static void scc_transform(struct compile_state *state)
13994 {
13995         struct scc_state scc;
13996
13997         initialize_scc_state(state, &scc);
13998
13999         while(scc.flow_work_list || scc.ssa_work_list) {
14000                 struct flow_edge *fedge;
14001                 struct ssa_edge *sedge;
14002                 struct flow_edge *fptr;
14003                 while((fedge = scc_next_fedge(state, &scc))) {
14004                         struct block *block;
14005                         struct triple *ptr;
14006                         struct flow_block *fblock;
14007                         int time;
14008                         int done;
14009                         if (fedge->executable) {
14010                                 continue;
14011                         }
14012                         if (!fedge->dst) {
14013                                 internal_error(state, 0, "fedge without dst");
14014                         }
14015                         if (!fedge->src) {
14016                                 internal_error(state, 0, "fedge without src");
14017                         }
14018                         fedge->executable = 1;
14019                         fblock = fedge->dst;
14020                         block = fblock->block;
14021                         time = 0;
14022                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14023                                 if (fptr->executable) {
14024                                         time++;
14025                                 }
14026                         }
14027 #if DEBUG_SCC
14028                         fprintf(stderr, "vertex: %d time: %d\n", 
14029                                 block->vertex, time);
14030                         
14031 #endif
14032                         done = 0;
14033                         for(ptr = block->first; !done; ptr = ptr->next) {
14034                                 struct lattice_node *lnode;
14035                                 done = (ptr == block->last);
14036                                 lnode = &scc.lattice[ptr->id];
14037                                 if (ptr->op == OP_PHI) {
14038                                         scc_visit_phi(state, &scc, lnode);
14039                                 }
14040                                 else if (time == 1) {
14041                                         scc_visit_expr(state, &scc, lnode);
14042                                 }
14043                         }
14044                         if (fblock->out && !fblock->out->out_next) {
14045                                 scc_add_fedge(state, &scc, fblock->out);
14046                         }
14047                 }
14048                 while((sedge = scc_next_sedge(state, &scc))) {
14049                         struct lattice_node *lnode;
14050                         struct flow_block *fblock;
14051                         lnode = sedge->dst;
14052                         fblock = lnode->fblock;
14053 #if DEBUG_SCC
14054                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14055                                 sedge - scc.ssa_edges,
14056                                 sedge->src->def->id,
14057                                 sedge->dst->def->id);
14058 #endif
14059                         if (lnode->def->op == OP_PHI) {
14060                                 scc_visit_phi(state, &scc, lnode);
14061                         }
14062                         else {
14063                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14064                                         if (fptr->executable) {
14065                                                 break;
14066                                         }
14067                                 }
14068                                 if (fptr) {
14069                                         scc_visit_expr(state, &scc, lnode);
14070                                 }
14071                         }
14072                 }
14073         }
14074         
14075         scc_writeback_values(state, &scc);
14076         free_scc_state(state, &scc);
14077 }
14078
14079
14080 static void transform_to_arch_instructions(struct compile_state *state)
14081 {
14082         struct triple *ins, *first;
14083         first = RHS(state->main_function, 0);
14084         ins = first;
14085         do {
14086                 ins = transform_to_arch_instruction(state, ins);
14087         } while(ins != first);
14088 }
14089
14090 #if DEBUG_CONSISTENCY
14091 static void verify_uses(struct compile_state *state)
14092 {
14093         struct triple *first, *ins;
14094         struct triple_set *set;
14095         first = RHS(state->main_function, 0);
14096         ins = first;
14097         do {
14098                 struct triple **expr;
14099                 expr = triple_rhs(state, ins, 0);
14100                 for(; expr; expr = triple_rhs(state, ins, expr)) {
14101                         struct triple *rhs;
14102                         rhs = *expr;
14103                         for(set = rhs?rhs->use:0; set; set = set->next) {
14104                                 if (set->member == ins) {
14105                                         break;
14106                                 }
14107                         }
14108                         if (!set) {
14109                                 internal_error(state, ins, "rhs not used");
14110                         }
14111                 }
14112                 expr = triple_lhs(state, ins, 0);
14113                 for(; expr; expr = triple_lhs(state, ins, expr)) {
14114                         struct triple *lhs;
14115                         lhs = *expr;
14116                         for(set =  lhs?lhs->use:0; set; set = set->next) {
14117                                 if (set->member == ins) {
14118                                         break;
14119                                 }
14120                         }
14121                         if (!set) {
14122                                 internal_error(state, ins, "lhs not used");
14123                         }
14124                 }
14125                 ins = ins->next;
14126         } while(ins != first);
14127         
14128 }
14129 static void verify_blocks(struct compile_state *state)
14130 {
14131         struct triple *ins;
14132         struct block *block;
14133         block = state->first_block;
14134         if (!block) {
14135                 return;
14136         }
14137         do {
14138                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14139                         if (!triple_stores_block(state, ins)) {
14140                                 continue;
14141                         }
14142                         if (ins->u.block != block) {
14143                                 internal_error(state, ins, "inconsitent block specified");
14144                         }
14145                 }
14146                 if (!triple_stores_block(state, block->last->next)) {
14147                         internal_error(state, block->last->next, 
14148                                 "cannot find next block");
14149                 }
14150                 block = block->last->next->u.block;
14151                 if (!block) {
14152                         internal_error(state, block->last->next,
14153                                 "bad next block");
14154                 }
14155         } while(block != state->first_block);
14156 }
14157
14158 static void verify_domination(struct compile_state *state)
14159 {
14160         struct triple *first, *ins;
14161         struct triple_set *set;
14162         if (!state->first_block) {
14163                 return;
14164         }
14165         
14166         first = RHS(state->main_function, 0);
14167         ins = first;
14168         do {
14169                 for(set = ins->use; set; set = set->next) {
14170                         struct triple **expr;
14171                         if (set->member->op == OP_PHI) {
14172                                 continue;
14173                         }
14174                         /* See if the use is on the righ hand side */
14175                         expr = triple_rhs(state, set->member, 0);
14176                         for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14177                                 if (*expr == ins) {
14178                                         break;
14179                                 }
14180                         }
14181                         if (expr &&
14182                                 !tdominates(state, ins, set->member)) {
14183                                 internal_error(state, set->member, 
14184                                         "non dominated rhs use?");
14185                         }
14186                 }
14187                 ins = ins->next;
14188         } while(ins != first);
14189 }
14190
14191 static void verify_piece(struct compile_state *state)
14192 {
14193         struct triple *first, *ins;
14194         first = RHS(state->main_function, 0);
14195         ins = first;
14196         do {
14197                 struct triple *ptr;
14198                 int lhs, i;
14199                 lhs = TRIPLE_LHS(ins->sizes);
14200                 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14201                         lhs = 0;
14202                 }
14203                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14204                         if (ptr != LHS(ins, i)) {
14205                                 internal_error(state, ins, "malformed lhs on %s",
14206                                         tops(ins->op));
14207                         }
14208                         if (ptr->op != OP_PIECE) {
14209                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
14210                                         tops(ptr->op), i, tops(ins->op));
14211                         }
14212                         if (ptr->u.cval != i) {
14213                                 internal_error(state, ins, "bad u.cval of %d %d expected",
14214                                         ptr->u.cval, i);
14215                         }
14216                 }
14217                 ins = ins->next;
14218         } while(ins != first);
14219 }
14220 static void verify_ins_colors(struct compile_state *state)
14221 {
14222         struct triple *first, *ins;
14223         
14224         first = RHS(state->main_function, 0);
14225         ins = first;
14226         do {
14227                 ins = ins->next;
14228         } while(ins != first);
14229 }
14230 static void verify_consistency(struct compile_state *state)
14231 {
14232         verify_uses(state);
14233         verify_blocks(state);
14234         verify_domination(state);
14235         verify_piece(state);
14236         verify_ins_colors(state);
14237 }
14238 #else 
14239 #define verify_consistency(state) do {} while(0)
14240 #endif /* DEBUG_USES */
14241
14242 static void optimize(struct compile_state *state)
14243 {
14244         if (state->debug & DEBUG_TRIPLES) {
14245                 print_triples(state);
14246         }
14247         /* Replace structures with simpler data types */
14248         flatten_structures(state);
14249         if (state->debug & DEBUG_TRIPLES) {
14250                 print_triples(state);
14251         }
14252         verify_consistency(state);
14253         /* Analize the intermediate code */
14254         setup_basic_blocks(state);
14255         analyze_idominators(state);
14256         analyze_ipdominators(state);
14257         /* Transform the code to ssa form */
14258         transform_to_ssa_form(state);
14259         verify_consistency(state);
14260         if (state->debug & DEBUG_CODE_ELIMINATION) {
14261                 fprintf(stdout, "After transform_to_ssa_form\n");
14262                 print_blocks(state, stdout);
14263         }
14264         /* Do strength reduction and simple constant optimizations */
14265         if (state->optimize >= 1) {
14266                 simplify_all(state);
14267         }
14268         verify_consistency(state);
14269         /* Propogate constants throughout the code */
14270         if (state->optimize >= 2) {
14271 #warning "FIXME fix scc_transform"
14272                 scc_transform(state);
14273                 transform_from_ssa_form(state);
14274                 free_basic_blocks(state);
14275                 setup_basic_blocks(state);
14276                 analyze_idominators(state);
14277                 analyze_ipdominators(state);
14278                 transform_to_ssa_form(state);
14279         }
14280         verify_consistency(state);
14281 #warning "WISHLIST implement single use constants (least possible register pressure)"
14282 #warning "WISHLIST implement induction variable elimination"
14283         /* Select architecture instructions and an initial partial
14284          * coloring based on architecture constraints.
14285          */
14286         transform_to_arch_instructions(state);
14287         verify_consistency(state);
14288         if (state->debug & DEBUG_ARCH_CODE) {
14289                 printf("After transform_to_arch_instructions\n");
14290                 print_blocks(state, stdout);
14291                 print_control_flow(state);
14292         }
14293         eliminate_inefectual_code(state);
14294         verify_consistency(state);
14295         if (state->debug & DEBUG_CODE_ELIMINATION) {
14296                 printf("After eliminate_inefectual_code\n");
14297                 print_blocks(state, stdout);
14298                 print_control_flow(state);
14299         }
14300         verify_consistency(state);
14301         /* Color all of the variables to see if they will fit in registers */
14302         insert_copies_to_phi(state);
14303         if (state->debug & DEBUG_INSERTED_COPIES) {
14304                 printf("After insert_copies_to_phi\n");
14305                 print_blocks(state, stdout);
14306                 print_control_flow(state);
14307         }
14308         verify_consistency(state);
14309         insert_mandatory_copies(state);
14310         if (state->debug & DEBUG_INSERTED_COPIES) {
14311                 printf("After insert_mandatory_copies\n");
14312                 print_blocks(state, stdout);
14313                 print_control_flow(state);
14314         }
14315         verify_consistency(state);
14316         allocate_registers(state);
14317         verify_consistency(state);
14318         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14319                 print_blocks(state, stdout);
14320         }
14321         if (state->debug & DEBUG_CONTROL_FLOW) {
14322                 print_control_flow(state);
14323         }
14324         /* Remove the optimization information.
14325          * This is more to check for memory consistency than to free memory.
14326          */
14327         free_basic_blocks(state);
14328 }
14329
14330 static void print_op_asm(struct compile_state *state,
14331         struct triple *ins, FILE *fp)
14332 {
14333         struct asm_info *info;
14334         const char *ptr;
14335         unsigned lhs, rhs, i;
14336         info = ins->u.ainfo;
14337         lhs = TRIPLE_LHS(ins->sizes);
14338         rhs = TRIPLE_RHS(ins->sizes);
14339         /* Don't count the clobbers in lhs */
14340         for(i = 0; i < lhs; i++) {
14341                 if (LHS(ins, i)->type == &void_type) {
14342                         break;
14343                 }
14344         }
14345         lhs = i;
14346         fprintf(fp, "#ASM\n");
14347         fputc('\t', fp);
14348         for(ptr = info->str; *ptr; ptr++) {
14349                 char *next;
14350                 unsigned long param;
14351                 struct triple *piece;
14352                 if (*ptr != '%') {
14353                         fputc(*ptr, fp);
14354                         continue;
14355                 }
14356                 ptr++;
14357                 if (*ptr == '%') {
14358                         fputc('%', fp);
14359                         continue;
14360                 }
14361                 param = strtoul(ptr, &next, 10);
14362                 if (ptr == next) {
14363                         error(state, ins, "Invalid asm template");
14364                 }
14365                 if (param >= (lhs + rhs)) {
14366                         error(state, ins, "Invalid param %%%u in asm template",
14367                                 param);
14368                 }
14369                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14370                 fprintf(fp, "%s", 
14371                         arch_reg_str(ID_REG(piece->id)));
14372                 ptr = next -1;
14373         }
14374         fprintf(fp, "\n#NOT ASM\n");
14375 }
14376
14377
14378 /* Only use the low x86 byte registers.  This allows me
14379  * allocate the entire register when a byte register is used.
14380  */
14381 #define X86_4_8BIT_GPRS 1
14382
14383 /* Recognized x86 cpu variants */
14384 #define BAD_CPU      0
14385 #define CPU_I386     1
14386 #define CPU_P3       2
14387 #define CPU_P4       3
14388 #define CPU_K7       4
14389 #define CPU_K8       5
14390
14391 #define CPU_DEFAULT  CPU_I386
14392
14393 /* The x86 register classes */
14394 #define REGC_FLAGS    0
14395 #define REGC_GPR8     1
14396 #define REGC_GPR16    2
14397 #define REGC_GPR32    3
14398 #define REGC_GPR64    4
14399 #define REGC_MMX      5
14400 #define REGC_XMM      6
14401 #define REGC_GPR32_8  7
14402 #define REGC_GPR16_8  8
14403 #define REGC_IMM32    9
14404 #define REGC_IMM16   10
14405 #define REGC_IMM8    11
14406 #define LAST_REGC  REGC_IMM8
14407 #if LAST_REGC >= MAX_REGC
14408 #error "MAX_REGC is to low"
14409 #endif
14410
14411 /* Register class masks */
14412 #define REGCM_FLAGS   (1 << REGC_FLAGS)
14413 #define REGCM_GPR8    (1 << REGC_GPR8)
14414 #define REGCM_GPR16   (1 << REGC_GPR16)
14415 #define REGCM_GPR32   (1 << REGC_GPR32)
14416 #define REGCM_GPR64   (1 << REGC_GPR64)
14417 #define REGCM_MMX     (1 << REGC_MMX)
14418 #define REGCM_XMM     (1 << REGC_XMM)
14419 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14420 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14421 #define REGCM_IMM32   (1 << REGC_IMM32)
14422 #define REGCM_IMM16   (1 << REGC_IMM16)
14423 #define REGCM_IMM8    (1 << REGC_IMM8)
14424 #define REGCM_ALL     ((1 << (LAST_REGC + 1)) - 1)
14425
14426 /* The x86 registers */
14427 #define REG_EFLAGS  2
14428 #define REGC_FLAGS_FIRST REG_EFLAGS
14429 #define REGC_FLAGS_LAST  REG_EFLAGS
14430 #define REG_AL      3
14431 #define REG_BL      4
14432 #define REG_CL      5
14433 #define REG_DL      6
14434 #define REG_AH      7
14435 #define REG_BH      8
14436 #define REG_CH      9
14437 #define REG_DH      10
14438 #define REGC_GPR8_FIRST  REG_AL
14439 #if X86_4_8BIT_GPRS
14440 #define REGC_GPR8_LAST   REG_DL
14441 #else 
14442 #define REGC_GPR8_LAST   REG_DH
14443 #endif
14444 #define REG_AX     11
14445 #define REG_BX     12
14446 #define REG_CX     13
14447 #define REG_DX     14
14448 #define REG_SI     15
14449 #define REG_DI     16
14450 #define REG_BP     17
14451 #define REG_SP     18
14452 #define REGC_GPR16_FIRST REG_AX
14453 #define REGC_GPR16_LAST  REG_SP
14454 #define REG_EAX    19
14455 #define REG_EBX    20
14456 #define REG_ECX    21
14457 #define REG_EDX    22
14458 #define REG_ESI    23
14459 #define REG_EDI    24
14460 #define REG_EBP    25
14461 #define REG_ESP    26
14462 #define REGC_GPR32_FIRST REG_EAX
14463 #define REGC_GPR32_LAST  REG_ESP
14464 #define REG_EDXEAX 27
14465 #define REGC_GPR64_FIRST REG_EDXEAX
14466 #define REGC_GPR64_LAST  REG_EDXEAX
14467 #define REG_MMX0   28
14468 #define REG_MMX1   29
14469 #define REG_MMX2   30
14470 #define REG_MMX3   31
14471 #define REG_MMX4   32
14472 #define REG_MMX5   33
14473 #define REG_MMX6   34
14474 #define REG_MMX7   35
14475 #define REGC_MMX_FIRST REG_MMX0
14476 #define REGC_MMX_LAST  REG_MMX7
14477 #define REG_XMM0   36
14478 #define REG_XMM1   37
14479 #define REG_XMM2   38
14480 #define REG_XMM3   39
14481 #define REG_XMM4   40
14482 #define REG_XMM5   41
14483 #define REG_XMM6   42
14484 #define REG_XMM7   43
14485 #define REGC_XMM_FIRST REG_XMM0
14486 #define REGC_XMM_LAST  REG_XMM7
14487 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14488 #define LAST_REG   REG_XMM7
14489
14490 #define REGC_GPR32_8_FIRST REG_EAX
14491 #define REGC_GPR32_8_LAST  REG_EDX
14492 #define REGC_GPR16_8_FIRST REG_AX
14493 #define REGC_GPR16_8_LAST  REG_DX
14494
14495 #define REGC_IMM8_FIRST    -1
14496 #define REGC_IMM8_LAST     -1
14497 #define REGC_IMM16_FIRST   -2
14498 #define REGC_IMM16_LAST    -1
14499 #define REGC_IMM32_FIRST   -4
14500 #define REGC_IMM32_LAST    -1
14501
14502 #if LAST_REG >= MAX_REGISTERS
14503 #error "MAX_REGISTERS to low"
14504 #endif
14505
14506
14507 static unsigned regc_size[LAST_REGC +1] = {
14508         [REGC_FLAGS]   = REGC_FLAGS_LAST   - REGC_FLAGS_FIRST + 1,
14509         [REGC_GPR8]    = REGC_GPR8_LAST    - REGC_GPR8_FIRST + 1,
14510         [REGC_GPR16]   = REGC_GPR16_LAST   - REGC_GPR16_FIRST + 1,
14511         [REGC_GPR32]   = REGC_GPR32_LAST   - REGC_GPR32_FIRST + 1,
14512         [REGC_GPR64]   = REGC_GPR64_LAST   - REGC_GPR64_FIRST + 1,
14513         [REGC_MMX]     = REGC_MMX_LAST     - REGC_MMX_FIRST + 1,
14514         [REGC_XMM]     = REGC_XMM_LAST     - REGC_XMM_FIRST + 1,
14515         [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14516         [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14517         [REGC_IMM32]   = 0,
14518         [REGC_IMM16]   = 0,
14519         [REGC_IMM8]    = 0,
14520 };
14521
14522 static const struct {
14523         int first, last;
14524 } regcm_bound[LAST_REGC + 1] = {
14525         [REGC_FLAGS]   = { REGC_FLAGS_FIRST,   REGC_FLAGS_LAST },
14526         [REGC_GPR8]    = { REGC_GPR8_FIRST,    REGC_GPR8_LAST },
14527         [REGC_GPR16]   = { REGC_GPR16_FIRST,   REGC_GPR16_LAST },
14528         [REGC_GPR32]   = { REGC_GPR32_FIRST,   REGC_GPR32_LAST },
14529         [REGC_GPR64]   = { REGC_GPR64_FIRST,   REGC_GPR64_LAST },
14530         [REGC_MMX]     = { REGC_MMX_FIRST,     REGC_MMX_LAST },
14531         [REGC_XMM]     = { REGC_XMM_FIRST,     REGC_XMM_LAST },
14532         [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14533         [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14534         [REGC_IMM32]   = { REGC_IMM32_FIRST,   REGC_IMM32_LAST },
14535         [REGC_IMM16]   = { REGC_IMM16_FIRST,   REGC_IMM16_LAST },
14536         [REGC_IMM8]    = { REGC_IMM8_FIRST,    REGC_IMM8_LAST },
14537 };
14538
14539 static int arch_encode_cpu(const char *cpu)
14540 {
14541         struct cpu {
14542                 const char *name;
14543                 int cpu;
14544         } cpus[] = {
14545                 { "i386", CPU_I386 },
14546                 { "p3",   CPU_P3 },
14547                 { "p4",   CPU_P4 },
14548                 { "k7",   CPU_K7 },
14549                 { "k8",   CPU_K8 },
14550                 {  0,     BAD_CPU }
14551         };
14552         struct cpu *ptr;
14553         for(ptr = cpus; ptr->name; ptr++) {
14554                 if (strcmp(ptr->name, cpu) == 0) {
14555                         break;
14556                 }
14557         }
14558         return ptr->cpu;
14559 }
14560
14561 static unsigned arch_regc_size(struct compile_state *state, int class)
14562 {
14563         if ((class < 0) || (class > LAST_REGC)) {
14564                 return 0;
14565         }
14566         return regc_size[class];
14567 }
14568 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14569 {
14570         /* See if two register classes may have overlapping registers */
14571         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14572                 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14573
14574         /* Special case for the immediates */
14575         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14576                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14577                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14578                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
14579                 return 0;
14580         }
14581         return (regcm1 & regcm2) ||
14582                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14583 }
14584
14585 static void arch_reg_equivs(
14586         struct compile_state *state, unsigned *equiv, int reg)
14587 {
14588         if ((reg < 0) || (reg > LAST_REG)) {
14589                 internal_error(state, 0, "invalid register");
14590         }
14591         *equiv++ = reg;
14592         switch(reg) {
14593         case REG_AL:
14594 #if X86_4_8BIT_GPRS
14595                 *equiv++ = REG_AH;
14596 #endif
14597                 *equiv++ = REG_AX;
14598                 *equiv++ = REG_EAX;
14599                 *equiv++ = REG_EDXEAX;
14600                 break;
14601         case REG_AH:
14602 #if X86_4_8BIT_GPRS
14603                 *equiv++ = REG_AL;
14604 #endif
14605                 *equiv++ = REG_AX;
14606                 *equiv++ = REG_EAX;
14607                 *equiv++ = REG_EDXEAX;
14608                 break;
14609         case REG_BL:  
14610 #if X86_4_8BIT_GPRS
14611                 *equiv++ = REG_BH;
14612 #endif
14613                 *equiv++ = REG_BX;
14614                 *equiv++ = REG_EBX;
14615                 break;
14616
14617         case REG_BH:
14618 #if X86_4_8BIT_GPRS
14619                 *equiv++ = REG_BL;
14620 #endif
14621                 *equiv++ = REG_BX;
14622                 *equiv++ = REG_EBX;
14623                 break;
14624         case REG_CL:
14625 #if X86_4_8BIT_GPRS
14626                 *equiv++ = REG_CH;
14627 #endif
14628                 *equiv++ = REG_CX;
14629                 *equiv++ = REG_ECX;
14630                 break;
14631
14632         case REG_CH:
14633 #if X86_4_8BIT_GPRS
14634                 *equiv++ = REG_CL;
14635 #endif
14636                 *equiv++ = REG_CX;
14637                 *equiv++ = REG_ECX;
14638                 break;
14639         case REG_DL:
14640 #if X86_4_8BIT_GPRS
14641                 *equiv++ = REG_DH;
14642 #endif
14643                 *equiv++ = REG_DX;
14644                 *equiv++ = REG_EDX;
14645                 *equiv++ = REG_EDXEAX;
14646                 break;
14647         case REG_DH:
14648 #if X86_4_8BIT_GPRS
14649                 *equiv++ = REG_DL;
14650 #endif
14651                 *equiv++ = REG_DX;
14652                 *equiv++ = REG_EDX;
14653                 *equiv++ = REG_EDXEAX;
14654                 break;
14655         case REG_AX:
14656                 *equiv++ = REG_AL;
14657                 *equiv++ = REG_AH;
14658                 *equiv++ = REG_EAX;
14659                 *equiv++ = REG_EDXEAX;
14660                 break;
14661         case REG_BX:
14662                 *equiv++ = REG_BL;
14663                 *equiv++ = REG_BH;
14664                 *equiv++ = REG_EBX;
14665                 break;
14666         case REG_CX:  
14667                 *equiv++ = REG_CL;
14668                 *equiv++ = REG_CH;
14669                 *equiv++ = REG_ECX;
14670                 break;
14671         case REG_DX:  
14672                 *equiv++ = REG_DL;
14673                 *equiv++ = REG_DH;
14674                 *equiv++ = REG_EDX;
14675                 *equiv++ = REG_EDXEAX;
14676                 break;
14677         case REG_SI:  
14678                 *equiv++ = REG_ESI;
14679                 break;
14680         case REG_DI:
14681                 *equiv++ = REG_EDI;
14682                 break;
14683         case REG_BP:
14684                 *equiv++ = REG_EBP;
14685                 break;
14686         case REG_SP:
14687                 *equiv++ = REG_ESP;
14688                 break;
14689         case REG_EAX:
14690                 *equiv++ = REG_AL;
14691                 *equiv++ = REG_AH;
14692                 *equiv++ = REG_AX;
14693                 *equiv++ = REG_EDXEAX;
14694                 break;
14695         case REG_EBX:
14696                 *equiv++ = REG_BL;
14697                 *equiv++ = REG_BH;
14698                 *equiv++ = REG_BX;
14699                 break;
14700         case REG_ECX:
14701                 *equiv++ = REG_CL;
14702                 *equiv++ = REG_CH;
14703                 *equiv++ = REG_CX;
14704                 break;
14705         case REG_EDX:
14706                 *equiv++ = REG_DL;
14707                 *equiv++ = REG_DH;
14708                 *equiv++ = REG_DX;
14709                 *equiv++ = REG_EDXEAX;
14710                 break;
14711         case REG_ESI: 
14712                 *equiv++ = REG_SI;
14713                 break;
14714         case REG_EDI: 
14715                 *equiv++ = REG_DI;
14716                 break;
14717         case REG_EBP: 
14718                 *equiv++ = REG_BP;
14719                 break;
14720         case REG_ESP: 
14721                 *equiv++ = REG_SP;
14722                 break;
14723         case REG_EDXEAX: 
14724                 *equiv++ = REG_AL;
14725                 *equiv++ = REG_AH;
14726                 *equiv++ = REG_DL;
14727                 *equiv++ = REG_DH;
14728                 *equiv++ = REG_AX;
14729                 *equiv++ = REG_DX;
14730                 *equiv++ = REG_EAX;
14731                 *equiv++ = REG_EDX;
14732                 break;
14733         }
14734         *equiv++ = REG_UNSET; 
14735 }
14736
14737 static unsigned arch_avail_mask(struct compile_state *state)
14738 {
14739         unsigned avail_mask;
14740         avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 | 
14741                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
14742                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
14743         switch(state->cpu) {
14744         case CPU_P3:
14745         case CPU_K7:
14746                 avail_mask |= REGCM_MMX;
14747                 break;
14748         case CPU_P4:
14749         case CPU_K8:
14750                 avail_mask |= REGCM_MMX | REGCM_XMM;
14751                 break;
14752         }
14753 #if 0
14754         /* Don't enable 8 bit values until I can force both operands
14755          * to be 8bits simultaneously.
14756          */
14757         avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
14758 #endif
14759         return avail_mask;
14760 }
14761
14762 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
14763 {
14764         unsigned mask, result;
14765         int class, class2;
14766         result = regcm;
14767         result &= arch_avail_mask(state);
14768
14769         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
14770                 if ((result & mask) == 0) {
14771                         continue;
14772                 }
14773                 if (class > LAST_REGC) {
14774                         result &= ~mask;
14775                 }
14776                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
14777                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
14778                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
14779                                 result |= (1 << class2);
14780                         }
14781                 }
14782         }
14783         return result;
14784 }
14785
14786 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
14787 {
14788         unsigned mask;
14789         int class;
14790         mask = 0;
14791         for(class = 0; class <= LAST_REGC; class++) {
14792                 if ((reg >= regcm_bound[class].first) &&
14793                         (reg <= regcm_bound[class].last)) {
14794                         mask |= (1 << class);
14795                 }
14796         }
14797         if (!mask) {
14798                 internal_error(state, 0, "reg %d not in any class", reg);
14799         }
14800         return mask;
14801 }
14802
14803 static struct reg_info arch_reg_constraint(
14804         struct compile_state *state, struct type *type, const char *constraint)
14805 {
14806         static const struct {
14807                 char class;
14808                 unsigned int mask;
14809                 unsigned int reg;
14810         } constraints[] = {
14811                 { 'r', REGCM_GPR32, REG_UNSET },
14812                 { 'g', REGCM_GPR32, REG_UNSET },
14813                 { 'p', REGCM_GPR32, REG_UNSET },
14814                 { 'q', REGCM_GPR8,  REG_UNSET },
14815                 { 'Q', REGCM_GPR32_8, REG_UNSET },
14816                 { 'x', REGCM_XMM,   REG_UNSET },
14817                 { 'y', REGCM_MMX,   REG_UNSET },
14818                 { 'a', REGCM_GPR32, REG_EAX },
14819                 { 'b', REGCM_GPR32, REG_EBX },
14820                 { 'c', REGCM_GPR32, REG_ECX },
14821                 { 'd', REGCM_GPR32, REG_EDX },
14822                 { 'D', REGCM_GPR32, REG_EDI },
14823                 { 'S', REGCM_GPR32, REG_ESI },
14824                 { '\0', 0, REG_UNSET },
14825         };
14826         unsigned int regcm;
14827         unsigned int mask, reg;
14828         struct reg_info result;
14829         const char *ptr;
14830         regcm = arch_type_to_regcm(state, type);
14831         reg = REG_UNSET;
14832         mask = 0;
14833         for(ptr = constraint; *ptr; ptr++) {
14834                 int i;
14835                 if (*ptr ==  ' ') {
14836                         continue;
14837                 }
14838                 for(i = 0; constraints[i].class != '\0'; i++) {
14839                         if (constraints[i].class == *ptr) {
14840                                 break;
14841                         }
14842                 }
14843                 if (constraints[i].class == '\0') {
14844                         error(state, 0, "invalid register constraint ``%c''", *ptr);
14845                         break;
14846                 }
14847                 if ((constraints[i].mask & regcm) == 0) {
14848                         error(state, 0, "invalid register class %c specified",
14849                                 *ptr);
14850                 }
14851                 mask |= constraints[i].mask;
14852                 if (constraints[i].reg != REG_UNSET) {
14853                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
14854                                 error(state, 0, "Only one register may be specified");
14855                         }
14856                         reg = constraints[i].reg;
14857                 }
14858         }
14859         result.reg = reg;
14860         result.regcm = mask;
14861         return result;
14862 }
14863
14864 static struct reg_info arch_reg_clobber(
14865         struct compile_state *state, const char *clobber)
14866 {
14867         struct reg_info result;
14868         if (strcmp(clobber, "memory") == 0) {
14869                 result.reg = REG_UNSET;
14870                 result.regcm = 0;
14871         }
14872         else if (strcmp(clobber, "%eax") == 0) {
14873                 result.reg = REG_EAX;
14874                 result.regcm = REGCM_GPR32;
14875         }
14876         else if (strcmp(clobber, "%ebx") == 0) {
14877                 result.reg = REG_EBX;
14878                 result.regcm = REGCM_GPR32;
14879         }
14880         else if (strcmp(clobber, "%ecx") == 0) {
14881                 result.reg = REG_ECX;
14882                 result.regcm = REGCM_GPR32;
14883         }
14884         else if (strcmp(clobber, "%edx") == 0) {
14885                 result.reg = REG_EDX;
14886                 result.regcm = REGCM_GPR32;
14887         }
14888         else if (strcmp(clobber, "%esi") == 0) {
14889                 result.reg = REG_ESI;
14890                 result.regcm = REGCM_GPR32;
14891         }
14892         else if (strcmp(clobber, "%edi") == 0) {
14893                 result.reg = REG_EDI;
14894                 result.regcm = REGCM_GPR32;
14895         }
14896         else if (strcmp(clobber, "%ebp") == 0) {
14897                 result.reg = REG_EBP;
14898                 result.regcm = REGCM_GPR32;
14899         }
14900         else if (strcmp(clobber, "%esp") == 0) {
14901                 result.reg = REG_ESP;
14902                 result.regcm = REGCM_GPR32;
14903         }
14904         else if (strcmp(clobber, "cc") == 0) {
14905                 result.reg = REG_EFLAGS;
14906                 result.regcm = REGCM_FLAGS;
14907         }
14908         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
14909                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14910                 result.reg = REG_XMM0 + octdigval(clobber[3]);
14911                 result.regcm = REGCM_XMM;
14912         }
14913         else if ((strncmp(clobber, "mmx", 3) == 0) &&
14914                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14915                 result.reg = REG_MMX0 + octdigval(clobber[3]);
14916                 result.regcm = REGCM_MMX;
14917         }
14918         else {
14919                 error(state, 0, "Invalid register clobber");
14920                 result.reg = REG_UNSET;
14921                 result.regcm = 0;
14922         }
14923         return result;
14924 }
14925
14926 static int do_select_reg(struct compile_state *state, 
14927         char *used, int reg, unsigned classes)
14928 {
14929         unsigned mask;
14930         if (used[reg]) {
14931                 return REG_UNSET;
14932         }
14933         mask = arch_reg_regcm(state, reg);
14934         return (classes & mask) ? reg : REG_UNSET;
14935 }
14936
14937 static int arch_select_free_register(
14938         struct compile_state *state, char *used, int classes)
14939 {
14940         /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
14941          * other types of registers.
14942          */
14943         int i, reg;
14944         reg = REG_UNSET;
14945         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
14946                 reg = do_select_reg(state, used, i, classes);
14947         }
14948         for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
14949                 reg = do_select_reg(state, used, i, classes);
14950         }
14951         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
14952                 reg = do_select_reg(state, used, i, classes);
14953         }
14954         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
14955                 reg = do_select_reg(state, used, i, classes);
14956         }
14957         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
14958                 reg = do_select_reg(state, used, i, classes);
14959         }
14960         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
14961                 reg = do_select_reg(state, used, i, classes);
14962         }
14963         for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
14964                 reg = do_select_reg(state, used, i, classes);
14965         }
14966         return reg;
14967 }
14968
14969
14970 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
14971 {
14972 #warning "FIXME force types smaller (if legal) before I get here"
14973         unsigned avail_mask;
14974         unsigned mask;
14975         mask = 0;
14976         avail_mask = arch_avail_mask(state);
14977         switch(type->type & TYPE_MASK) {
14978         case TYPE_ARRAY:
14979         case TYPE_VOID: 
14980                 mask = 0; 
14981                 break;
14982         case TYPE_CHAR:
14983         case TYPE_UCHAR:
14984                 mask = REGCM_GPR8 | 
14985                         REGCM_GPR16 | REGCM_GPR16_8 | 
14986                         REGCM_GPR32 | REGCM_GPR32_8 |
14987                         REGCM_GPR64 |
14988                         REGCM_MMX | REGCM_XMM |
14989                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
14990                 break;
14991         case TYPE_SHORT:
14992         case TYPE_USHORT:
14993                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
14994                         REGCM_GPR32 | REGCM_GPR32_8 |
14995                         REGCM_GPR64 |
14996                         REGCM_MMX | REGCM_XMM |
14997                         REGCM_IMM32 | REGCM_IMM16;
14998                 break;
14999         case TYPE_INT:
15000         case TYPE_UINT:
15001         case TYPE_LONG:
15002         case TYPE_ULONG:
15003         case TYPE_POINTER:
15004                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
15005                         REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15006                         REGCM_IMM32;
15007                 break;
15008         default:
15009                 internal_error(state, 0, "no register class for type");
15010                 break;
15011         }
15012         mask &= avail_mask;
15013         return mask;
15014 }
15015
15016 static int is_imm32(struct triple *imm)
15017 {
15018         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15019                 (imm->op == OP_ADDRCONST);
15020         
15021 }
15022 static int is_imm16(struct triple *imm)
15023 {
15024         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15025 }
15026 static int is_imm8(struct triple *imm)
15027 {
15028         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15029 }
15030
15031 static int get_imm32(struct triple *ins, struct triple **expr)
15032 {
15033         struct triple *imm;
15034         imm = *expr;
15035         while(imm->op == OP_COPY) {
15036                 imm = RHS(imm, 0);
15037         }
15038         if (!is_imm32(imm)) {
15039                 return 0;
15040         }
15041         unuse_triple(*expr, ins);
15042         use_triple(imm, ins);
15043         *expr = imm;
15044         return 1;
15045 }
15046
15047 static int get_imm8(struct triple *ins, struct triple **expr)
15048 {
15049         struct triple *imm;
15050         imm = *expr;
15051         while(imm->op == OP_COPY) {
15052                 imm = RHS(imm, 0);
15053         }
15054         if (!is_imm8(imm)) {
15055                 return 0;
15056         }
15057         unuse_triple(*expr, ins);
15058         use_triple(imm, ins);
15059         *expr = imm;
15060         return 1;
15061 }
15062
15063 #define TEMPLATE_NOP         0
15064 #define TEMPLATE_INTCONST8   1
15065 #define TEMPLATE_INTCONST32  2
15066 #define TEMPLATE_COPY_REG    3
15067 #define TEMPLATE_COPY_IMM32  4
15068 #define TEMPLATE_COPY_IMM16  5
15069 #define TEMPLATE_COPY_IMM8   6
15070 #define TEMPLATE_PHI         7
15071 #define TEMPLATE_STORE8      8
15072 #define TEMPLATE_STORE16     9
15073 #define TEMPLATE_STORE32    10
15074 #define TEMPLATE_LOAD8      11
15075 #define TEMPLATE_LOAD16     12
15076 #define TEMPLATE_LOAD32     13
15077 #define TEMPLATE_BINARY_REG 14
15078 #define TEMPLATE_BINARY_IMM 15
15079 #define TEMPLATE_SL_CL      16
15080 #define TEMPLATE_SL_IMM     17
15081 #define TEMPLATE_UNARY      18
15082 #define TEMPLATE_CMP_REG    19
15083 #define TEMPLATE_CMP_IMM    20
15084 #define TEMPLATE_TEST       21
15085 #define TEMPLATE_SET        22
15086 #define TEMPLATE_JMP        23
15087 #define TEMPLATE_INB_DX     24
15088 #define TEMPLATE_INB_IMM    25
15089 #define TEMPLATE_INW_DX     26
15090 #define TEMPLATE_INW_IMM    27
15091 #define TEMPLATE_INL_DX     28
15092 #define TEMPLATE_INL_IMM    29
15093 #define TEMPLATE_OUTB_DX    30
15094 #define TEMPLATE_OUTB_IMM   31
15095 #define TEMPLATE_OUTW_DX    32
15096 #define TEMPLATE_OUTW_IMM   33
15097 #define TEMPLATE_OUTL_DX    34
15098 #define TEMPLATE_OUTL_IMM   35
15099 #define TEMPLATE_BSF        36
15100 #define TEMPLATE_RDMSR      37
15101 #define TEMPLATE_WRMSR      38
15102 #define LAST_TEMPLATE       TEMPLATE_WRMSR
15103 #if LAST_TEMPLATE >= MAX_TEMPLATES
15104 #error "MAX_TEMPLATES to low"
15105 #endif
15106
15107 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15108 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15109
15110 static struct ins_template templates[] = {
15111         [TEMPLATE_NOP]      = {},
15112         [TEMPLATE_INTCONST8] = { 
15113                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15114         },
15115         [TEMPLATE_INTCONST32] = { 
15116                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15117         },
15118         [TEMPLATE_COPY_REG] = {
15119                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15120                 .rhs = { [0] = { REG_UNSET, COPY_REGCM }  },
15121         },
15122         [TEMPLATE_COPY_IMM32] = {
15123                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15124                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15125         },
15126         [TEMPLATE_COPY_IMM16] = {
15127                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
15128                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
15129         },
15130         [TEMPLATE_COPY_IMM8] = {
15131                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15132                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15133         },
15134         [TEMPLATE_PHI] = { 
15135                 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
15136                 .rhs = { 
15137                         [ 0] = { REG_VIRT0, COPY_REGCM },
15138                         [ 1] = { REG_VIRT0, COPY_REGCM },
15139                         [ 2] = { REG_VIRT0, COPY_REGCM },
15140                         [ 3] = { REG_VIRT0, COPY_REGCM },
15141                         [ 4] = { REG_VIRT0, COPY_REGCM },
15142                         [ 5] = { REG_VIRT0, COPY_REGCM },
15143                         [ 6] = { REG_VIRT0, COPY_REGCM },
15144                         [ 7] = { REG_VIRT0, COPY_REGCM },
15145                         [ 8] = { REG_VIRT0, COPY_REGCM },
15146                         [ 9] = { REG_VIRT0, COPY_REGCM },
15147                         [10] = { REG_VIRT0, COPY_REGCM },
15148                         [11] = { REG_VIRT0, COPY_REGCM },
15149                         [12] = { REG_VIRT0, COPY_REGCM },
15150                         [13] = { REG_VIRT0, COPY_REGCM },
15151                         [14] = { REG_VIRT0, COPY_REGCM },
15152                         [15] = { REG_VIRT0, COPY_REGCM },
15153                 }, },
15154         [TEMPLATE_STORE8] = {
15155                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15156                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15157         },
15158         [TEMPLATE_STORE16] = {
15159                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15160                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15161         },
15162         [TEMPLATE_STORE32] = {
15163                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15164                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15165         },
15166         [TEMPLATE_LOAD8] = {
15167                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15168                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15169         },
15170         [TEMPLATE_LOAD16] = {
15171                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15172                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15173         },
15174         [TEMPLATE_LOAD32] = {
15175                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15176                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15177         },
15178         [TEMPLATE_BINARY_REG] = {
15179                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15180                 .rhs = { 
15181                         [0] = { REG_VIRT0, REGCM_GPR32 },
15182                         [1] = { REG_UNSET, REGCM_GPR32 },
15183                 },
15184         },
15185         [TEMPLATE_BINARY_IMM] = {
15186                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15187                 .rhs = { 
15188                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15189                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15190                 },
15191         },
15192         [TEMPLATE_SL_CL] = {
15193                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15194                 .rhs = { 
15195                         [0] = { REG_VIRT0, REGCM_GPR32 },
15196                         [1] = { REG_CL, REGCM_GPR8 },
15197                 },
15198         },
15199         [TEMPLATE_SL_IMM] = {
15200                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15201                 .rhs = { 
15202                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15203                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15204                 },
15205         },
15206         [TEMPLATE_UNARY] = {
15207                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15208                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15209         },
15210         [TEMPLATE_CMP_REG] = {
15211                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15212                 .rhs = {
15213                         [0] = { REG_UNSET, REGCM_GPR32 },
15214                         [1] = { REG_UNSET, REGCM_GPR32 },
15215                 },
15216         },
15217         [TEMPLATE_CMP_IMM] = {
15218                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15219                 .rhs = {
15220                         [0] = { REG_UNSET, REGCM_GPR32 },
15221                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15222                 },
15223         },
15224         [TEMPLATE_TEST] = {
15225                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15226                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15227         },
15228         [TEMPLATE_SET] = {
15229                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15230                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15231         },
15232         [TEMPLATE_JMP] = {
15233                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15234         },
15235         [TEMPLATE_INB_DX] = {
15236                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15237                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15238         },
15239         [TEMPLATE_INB_IMM] = {
15240                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15241                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15242         },
15243         [TEMPLATE_INW_DX]  = { 
15244                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15245                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15246         },
15247         [TEMPLATE_INW_IMM] = { 
15248                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15249                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15250         },
15251         [TEMPLATE_INL_DX]  = {
15252                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15253                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15254         },
15255         [TEMPLATE_INL_IMM] = {
15256                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15257                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15258         },
15259         [TEMPLATE_OUTB_DX] = { 
15260                 .rhs = {
15261                         [0] = { REG_AL,  REGCM_GPR8 },
15262                         [1] = { REG_DX, REGCM_GPR16 },
15263                 },
15264         },
15265         [TEMPLATE_OUTB_IMM] = { 
15266                 .rhs = {
15267                         [0] = { REG_AL,  REGCM_GPR8 },  
15268                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15269                 },
15270         },
15271         [TEMPLATE_OUTW_DX] = { 
15272                 .rhs = {
15273                         [0] = { REG_AX,  REGCM_GPR16 },
15274                         [1] = { REG_DX, REGCM_GPR16 },
15275                 },
15276         },
15277         [TEMPLATE_OUTW_IMM] = {
15278                 .rhs = {
15279                         [0] = { REG_AX,  REGCM_GPR16 }, 
15280                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15281                 },
15282         },
15283         [TEMPLATE_OUTL_DX] = { 
15284                 .rhs = {
15285                         [0] = { REG_EAX, REGCM_GPR32 },
15286                         [1] = { REG_DX, REGCM_GPR16 },
15287                 },
15288         },
15289         [TEMPLATE_OUTL_IMM] = { 
15290                 .rhs = {
15291                         [0] = { REG_EAX, REGCM_GPR32 }, 
15292                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15293                 },
15294         },
15295         [TEMPLATE_BSF] = {
15296                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15297                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15298         },
15299         [TEMPLATE_RDMSR] = {
15300                 .lhs = { 
15301                         [0] = { REG_EAX, REGCM_GPR32 },
15302                         [1] = { REG_EDX, REGCM_GPR32 },
15303                 },
15304                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15305         },
15306         [TEMPLATE_WRMSR] = {
15307                 .rhs = {
15308                         [0] = { REG_ECX, REGCM_GPR32 },
15309                         [1] = { REG_EAX, REGCM_GPR32 },
15310                         [2] = { REG_EDX, REGCM_GPR32 },
15311                 },
15312         },
15313 };
15314
15315 static void fixup_branches(struct compile_state *state,
15316         struct triple *cmp, struct triple *use, int jmp_op)
15317 {
15318         struct triple_set *entry, *next;
15319         for(entry = use->use; entry; entry = next) {
15320                 next = entry->next;
15321                 if (entry->member->op == OP_COPY) {
15322                         fixup_branches(state, cmp, entry->member, jmp_op);
15323                 }
15324                 else if (entry->member->op == OP_BRANCH) {
15325                         struct triple *branch, *test;
15326                         struct triple *left, *right;
15327                         left = right = 0;
15328                         left = RHS(cmp, 0);
15329                         if (TRIPLE_RHS(cmp->sizes) > 1) {
15330                                 right = RHS(cmp, 1);
15331                         }
15332                         branch = entry->member;
15333                         test = pre_triple(state, branch,
15334                                 cmp->op, cmp->type, left, right);
15335                         test->template_id = TEMPLATE_TEST; 
15336                         if (cmp->op == OP_CMP) {
15337                                 test->template_id = TEMPLATE_CMP_REG;
15338                                 if (get_imm32(test, &RHS(test, 1))) {
15339                                         test->template_id = TEMPLATE_CMP_IMM;
15340                                 }
15341                         }
15342                         use_triple(RHS(test, 0), test);
15343                         use_triple(RHS(test, 1), test);
15344                         unuse_triple(RHS(branch, 0), branch);
15345                         RHS(branch, 0) = test;
15346                         branch->op = jmp_op;
15347                         branch->template_id = TEMPLATE_JMP;
15348                         use_triple(RHS(branch, 0), branch);
15349                 }
15350         }
15351 }
15352
15353 static void bool_cmp(struct compile_state *state, 
15354         struct triple *ins, int cmp_op, int jmp_op, int set_op)
15355 {
15356         struct triple_set *entry, *next;
15357         struct triple *set;
15358
15359         /* Put a barrier up before the cmp which preceeds the
15360          * copy instruction.  If a set actually occurs this gives
15361          * us a chance to move variables in registers out of the way.
15362          */
15363
15364         /* Modify the comparison operator */
15365         ins->op = cmp_op;
15366         ins->template_id = TEMPLATE_TEST;
15367         if (cmp_op == OP_CMP) {
15368                 ins->template_id = TEMPLATE_CMP_REG;
15369                 if (get_imm32(ins, &RHS(ins, 1))) {
15370                         ins->template_id =  TEMPLATE_CMP_IMM;
15371                 }
15372         }
15373         /* Generate the instruction sequence that will transform the
15374          * result of the comparison into a logical value.
15375          */
15376         set = post_triple(state, ins, set_op, ins->type, ins, 0);
15377         use_triple(ins, set);
15378         set->template_id = TEMPLATE_SET;
15379
15380         for(entry = ins->use; entry; entry = next) {
15381                 next = entry->next;
15382                 if (entry->member == set) {
15383                         continue;
15384                 }
15385                 replace_rhs_use(state, ins, set, entry->member);
15386         }
15387         fixup_branches(state, ins, set, jmp_op);
15388 }
15389
15390 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15391 {
15392         struct triple *next;
15393         int lhs, i;
15394         lhs = TRIPLE_LHS(ins->sizes);
15395         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15396                 if (next != LHS(ins, i)) {
15397                         internal_error(state, ins, "malformed lhs on %s",
15398                                 tops(ins->op));
15399                 }
15400                 if (next->op != OP_PIECE) {
15401                         internal_error(state, ins, "bad lhs op %s at %d on %s",
15402                                 tops(next->op), i, tops(ins->op));
15403                 }
15404                 if (next->u.cval != i) {
15405                         internal_error(state, ins, "bad u.cval of %d %d expected",
15406                                 next->u.cval, i);
15407                 }
15408         }
15409         return next;
15410 }
15411
15412 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15413 {
15414         struct ins_template *template;
15415         struct reg_info result;
15416         int zlhs;
15417         if (ins->op == OP_PIECE) {
15418                 index = ins->u.cval;
15419                 ins = MISC(ins, 0);
15420         }
15421         zlhs = TRIPLE_LHS(ins->sizes);
15422         if (triple_is_def(state, ins)) {
15423                 zlhs = 1;
15424         }
15425         if (index >= zlhs) {
15426                 internal_error(state, ins, "index %d out of range for %s\n",
15427                         index, tops(ins->op));
15428         }
15429         switch(ins->op) {
15430         case OP_ASM:
15431                 template = &ins->u.ainfo->tmpl;
15432                 break;
15433         default:
15434                 if (ins->template_id > LAST_TEMPLATE) {
15435                         internal_error(state, ins, "bad template number %d", 
15436                                 ins->template_id);
15437                 }
15438                 template = &templates[ins->template_id];
15439                 break;
15440         }
15441         result = template->lhs[index];
15442         result.regcm = arch_regcm_normalize(state, result.regcm);
15443         if (result.reg != REG_UNNEEDED) {
15444                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15445         }
15446         if (result.regcm == 0) {
15447                 internal_error(state, ins, "lhs %d regcm == 0", index);
15448         }
15449         return result;
15450 }
15451
15452 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15453 {
15454         struct reg_info result;
15455         struct ins_template *template;
15456         if ((index > TRIPLE_RHS(ins->sizes)) ||
15457                 (ins->op == OP_PIECE)) {
15458                 internal_error(state, ins, "index %d out of range for %s\n",
15459                         index, tops(ins->op));
15460         }
15461         switch(ins->op) {
15462         case OP_ASM:
15463                 template = &ins->u.ainfo->tmpl;
15464                 break;
15465         default:
15466                 if (ins->template_id > LAST_TEMPLATE) {
15467                         internal_error(state, ins, "bad template number %d", 
15468                                 ins->template_id);
15469                 }
15470                 template = &templates[ins->template_id];
15471                 break;
15472         }
15473         result = template->rhs[index];
15474         result.regcm = arch_regcm_normalize(state, result.regcm);
15475         if (result.regcm == 0) {
15476                 internal_error(state, ins, "rhs %d regcm == 0", index);
15477         }
15478         return result;
15479 }
15480
15481 static struct triple *transform_to_arch_instruction(
15482         struct compile_state *state, struct triple *ins)
15483 {
15484         /* Transform from generic 3 address instructions
15485          * to archtecture specific instructions.
15486          * And apply architecture specific constrains to instructions.
15487          * Copies are inserted to preserve the register flexibility
15488          * of 3 address instructions.
15489          */
15490         struct triple *next;
15491         next = ins->next;
15492         switch(ins->op) {
15493         case OP_INTCONST:
15494                 ins->template_id = TEMPLATE_INTCONST32;
15495                 if (ins->u.cval < 256) {
15496                         ins->template_id = TEMPLATE_INTCONST8;
15497                 }
15498                 break;
15499         case OP_ADDRCONST:
15500                 ins->template_id = TEMPLATE_INTCONST32;
15501                 break;
15502         case OP_NOOP:
15503         case OP_SDECL:
15504         case OP_BLOBCONST:
15505         case OP_LABEL:
15506                 ins->template_id = TEMPLATE_NOP;
15507                 break;
15508         case OP_COPY:
15509                 ins->template_id = TEMPLATE_COPY_REG;
15510                 if (is_imm8(RHS(ins, 0))) {
15511                         ins->template_id = TEMPLATE_COPY_IMM8;
15512                 }
15513                 else if (is_imm16(RHS(ins, 0))) {
15514                         ins->template_id = TEMPLATE_COPY_IMM16;
15515                 }
15516                 else if (is_imm32(RHS(ins, 0))) {
15517                         ins->template_id = TEMPLATE_COPY_IMM32;
15518                 }
15519                 else if (is_const(RHS(ins, 0))) {
15520                         internal_error(state, ins, "bad constant passed to copy");
15521                 }
15522                 break;
15523         case OP_PHI:
15524                 ins->template_id = TEMPLATE_PHI;
15525                 break;
15526         case OP_STORE:
15527                 switch(ins->type->type & TYPE_MASK) {
15528                 case TYPE_CHAR:    case TYPE_UCHAR:
15529                         ins->template_id = TEMPLATE_STORE8;
15530                         break;
15531                 case TYPE_SHORT:   case TYPE_USHORT:
15532                         ins->template_id = TEMPLATE_STORE16;
15533                         break;
15534                 case TYPE_INT:     case TYPE_UINT:
15535                 case TYPE_LONG:    case TYPE_ULONG:
15536                 case TYPE_POINTER:
15537                         ins->template_id = TEMPLATE_STORE32;
15538                         break;
15539                 default:
15540                         internal_error(state, ins, "unknown type in store");
15541                         break;
15542                 }
15543                 break;
15544         case OP_LOAD:
15545                 switch(ins->type->type & TYPE_MASK) {
15546                 case TYPE_CHAR:   case TYPE_UCHAR:
15547                         ins->template_id = TEMPLATE_LOAD8;
15548                         break;
15549                 case TYPE_SHORT:
15550                 case TYPE_USHORT:
15551                         ins->template_id = TEMPLATE_LOAD16;
15552                         break;
15553                 case TYPE_INT:
15554                 case TYPE_UINT:
15555                 case TYPE_LONG:
15556                 case TYPE_ULONG:
15557                 case TYPE_POINTER:
15558                         ins->template_id = TEMPLATE_LOAD32;
15559                         break;
15560                 default:
15561                         internal_error(state, ins, "unknown type in load");
15562                         break;
15563                 }
15564                 break;
15565         case OP_ADD:
15566         case OP_SUB:
15567         case OP_AND:
15568         case OP_XOR:
15569         case OP_OR:
15570         case OP_SMUL:
15571                 ins->template_id = TEMPLATE_BINARY_REG;
15572                 if (get_imm32(ins, &RHS(ins, 1))) {
15573                         ins->template_id = TEMPLATE_BINARY_IMM;
15574                 }
15575                 break;
15576         case OP_SL:
15577         case OP_SSR:
15578         case OP_USR:
15579                 ins->template_id = TEMPLATE_SL_CL;
15580                 if (get_imm8(ins, &RHS(ins, 1))) {
15581                         ins->template_id = TEMPLATE_SL_IMM;
15582                 }
15583                 break;
15584         case OP_INVERT:
15585         case OP_NEG:
15586                 ins->template_id = TEMPLATE_UNARY;
15587                 break;
15588         case OP_EQ: 
15589                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
15590                 break;
15591         case OP_NOTEQ:
15592                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15593                 break;
15594         case OP_SLESS:
15595                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
15596                 break;
15597         case OP_ULESS:
15598                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
15599                 break;
15600         case OP_SMORE:
15601                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
15602                 break;
15603         case OP_UMORE:
15604                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
15605                 break;
15606         case OP_SLESSEQ:
15607                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
15608                 break;
15609         case OP_ULESSEQ:
15610                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
15611                 break;
15612         case OP_SMOREEQ:
15613                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
15614                 break;
15615         case OP_UMOREEQ:
15616                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
15617                 break;
15618         case OP_LTRUE:
15619                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15620                 break;
15621         case OP_LFALSE:
15622                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
15623                 break;
15624         case OP_BRANCH:
15625                 if (TRIPLE_RHS(ins->sizes) > 0) {
15626                         internal_error(state, ins, "bad branch test");
15627                 }
15628                 ins->op = OP_JMP;
15629                 ins->template_id = TEMPLATE_NOP;
15630                 break;
15631         case OP_INB:
15632         case OP_INW:
15633         case OP_INL:
15634                 switch(ins->op) {
15635                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
15636                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
15637                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
15638                 }
15639                 if (get_imm8(ins, &RHS(ins, 0))) {
15640                         ins->template_id += 1;
15641                 }
15642                 break;
15643         case OP_OUTB:
15644         case OP_OUTW:
15645         case OP_OUTL:
15646                 switch(ins->op) {
15647                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
15648                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
15649                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
15650                 }
15651                 if (get_imm8(ins, &RHS(ins, 1))) {
15652                         ins->template_id += 1;
15653                 }
15654                 break;
15655         case OP_BSF:
15656         case OP_BSR:
15657                 ins->template_id = TEMPLATE_BSF;
15658                 break;
15659         case OP_RDMSR:
15660                 ins->template_id = TEMPLATE_RDMSR;
15661                 next = after_lhs(state, ins);
15662                 break;
15663         case OP_WRMSR:
15664                 ins->template_id = TEMPLATE_WRMSR;
15665                 break;
15666         case OP_HLT:
15667                 ins->template_id = TEMPLATE_NOP;
15668                 break;
15669         case OP_ASM:
15670                 ins->template_id = TEMPLATE_NOP;
15671                 next = after_lhs(state, ins);
15672                 break;
15673                 /* Already transformed instructions */
15674         case OP_TEST:
15675                 ins->template_id = TEMPLATE_TEST;
15676                 break;
15677         case OP_CMP:
15678                 ins->template_id = TEMPLATE_CMP_REG;
15679                 if (get_imm32(ins, &RHS(ins, 1))) {
15680                         ins->template_id = TEMPLATE_CMP_IMM;
15681                 }
15682                 break;
15683         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
15684         case OP_JMP_SLESS:   case OP_JMP_ULESS:
15685         case OP_JMP_SMORE:   case OP_JMP_UMORE:
15686         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
15687         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
15688                 ins->template_id = TEMPLATE_JMP;
15689                 break;
15690         case OP_SET_EQ:      case OP_SET_NOTEQ:
15691         case OP_SET_SLESS:   case OP_SET_ULESS:
15692         case OP_SET_SMORE:   case OP_SET_UMORE:
15693         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
15694         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
15695                 ins->template_id = TEMPLATE_SET;
15696                 break;
15697                 /* Unhandled instructions */
15698         case OP_PIECE:
15699         default:
15700                 internal_error(state, ins, "unhandled ins: %d %s\n",
15701                         ins->op, tops(ins->op));
15702                 break;
15703         }
15704         return next;
15705 }
15706
15707 static void generate_local_labels(struct compile_state *state)
15708 {
15709         struct triple *first, *label;
15710         int label_counter;
15711         label_counter = 0;
15712         first = RHS(state->main_function, 0);
15713         label = first;
15714         do {
15715                 if ((label->op == OP_LABEL) || 
15716                         (label->op == OP_SDECL)) {
15717                         if (label->use) {
15718                                 label->u.cval = ++label_counter;
15719                         } else {
15720                                 label->u.cval = 0;
15721                         }
15722                         
15723                 }
15724                 label = label->next;
15725         } while(label != first);
15726 }
15727
15728 static int check_reg(struct compile_state *state, 
15729         struct triple *triple, int classes)
15730 {
15731         unsigned mask;
15732         int reg;
15733         reg = ID_REG(triple->id);
15734         if (reg == REG_UNSET) {
15735                 internal_error(state, triple, "register not set");
15736         }
15737         mask = arch_reg_regcm(state, reg);
15738         if (!(classes & mask)) {
15739                 internal_error(state, triple, "reg %d in wrong class",
15740                         reg);
15741         }
15742         return reg;
15743 }
15744
15745 static const char *arch_reg_str(int reg)
15746 {
15747         static const char *regs[] = {
15748                 "%bad_register",
15749                 "%bad_register2",
15750                 "%eflags",
15751                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
15752                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
15753                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
15754                 "%edx:%eax",
15755                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
15756                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
15757                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
15758         };
15759         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
15760                 reg = 0;
15761         }
15762         return regs[reg];
15763 }
15764
15765
15766 static const char *reg(struct compile_state *state, struct triple *triple,
15767         int classes)
15768 {
15769         int reg;
15770         reg = check_reg(state, triple, classes);
15771         return arch_reg_str(reg);
15772 }
15773
15774 const char *type_suffix(struct compile_state *state, struct type *type)
15775 {
15776         const char *suffix;
15777         switch(size_of(state, type)) {
15778         case 1: suffix = "b"; break;
15779         case 2: suffix = "w"; break;
15780         case 4: suffix = "l"; break;
15781         default:
15782                 internal_error(state, 0, "unknown suffix");
15783                 suffix = 0;
15784                 break;
15785         }
15786         return suffix;
15787 }
15788
15789 static void print_const_val(
15790         struct compile_state *state, struct triple *ins, FILE *fp)
15791 {
15792         switch(ins->op) {
15793         case OP_INTCONST:
15794                 fprintf(fp, " $%ld ", 
15795                         (long_t)(ins->u.cval));
15796                 break;
15797         case OP_ADDRCONST:
15798                 fprintf(fp, " $L%s%lu+%lu ",
15799                         state->label_prefix, 
15800                         MISC(ins, 0)->u.cval,
15801                         ins->u.cval);
15802                 break;
15803         default:
15804                 internal_error(state, ins, "unknown constant type");
15805                 break;
15806         }
15807 }
15808
15809 static void print_binary_op(struct compile_state *state,
15810         const char *op, struct triple *ins, FILE *fp) 
15811 {
15812         unsigned mask;
15813         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15814         if (RHS(ins, 0)->id != ins->id) {
15815                 internal_error(state, ins, "invalid register assignment");
15816         }
15817         if (is_const(RHS(ins, 1))) {
15818                 fprintf(fp, "\t%s ", op);
15819                 print_const_val(state, RHS(ins, 1), fp);
15820                 fprintf(fp, ", %s\n",
15821                         reg(state, RHS(ins, 0), mask));
15822         }
15823         else {
15824                 unsigned lmask, rmask;
15825                 int lreg, rreg;
15826                 lreg = check_reg(state, RHS(ins, 0), mask);
15827                 rreg = check_reg(state, RHS(ins, 1), mask);
15828                 lmask = arch_reg_regcm(state, lreg);
15829                 rmask = arch_reg_regcm(state, rreg);
15830                 mask = lmask & rmask;
15831                 fprintf(fp, "\t%s %s, %s\n",
15832                         op,
15833                         reg(state, RHS(ins, 1), mask),
15834                         reg(state, RHS(ins, 0), mask));
15835         }
15836 }
15837 static void print_unary_op(struct compile_state *state, 
15838         const char *op, struct triple *ins, FILE *fp)
15839 {
15840         unsigned mask;
15841         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15842         fprintf(fp, "\t%s %s\n",
15843                 op,
15844                 reg(state, RHS(ins, 0), mask));
15845 }
15846
15847 static void print_op_shift(struct compile_state *state,
15848         const char *op, struct triple *ins, FILE *fp)
15849 {
15850         unsigned mask;
15851         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15852         if (RHS(ins, 0)->id != ins->id) {
15853                 internal_error(state, ins, "invalid register assignment");
15854         }
15855         if (is_const(RHS(ins, 1))) {
15856                 fprintf(fp, "\t%s ", op);
15857                 print_const_val(state, RHS(ins, 1), fp);
15858                 fprintf(fp, ", %s\n",
15859                         reg(state, RHS(ins, 0), mask));
15860         }
15861         else {
15862                 fprintf(fp, "\t%s %s, %s\n",
15863                         op,
15864                         reg(state, RHS(ins, 1), REGCM_GPR8),
15865                         reg(state, RHS(ins, 0), mask));
15866         }
15867 }
15868
15869 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
15870 {
15871         const char *op;
15872         int mask;
15873         int dreg;
15874         mask = 0;
15875         switch(ins->op) {
15876         case OP_INB: op = "inb", mask = REGCM_GPR8; break;
15877         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
15878         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
15879         default:
15880                 internal_error(state, ins, "not an in operation");
15881                 op = 0;
15882                 break;
15883         }
15884         dreg = check_reg(state, ins, mask);
15885         if (!reg_is_reg(state, dreg, REG_EAX)) {
15886                 internal_error(state, ins, "dst != %%eax");
15887         }
15888         if (is_const(RHS(ins, 0))) {
15889                 fprintf(fp, "\t%s ", op);
15890                 print_const_val(state, RHS(ins, 0), fp);
15891                 fprintf(fp, ", %s\n",
15892                         reg(state, ins, mask));
15893         }
15894         else {
15895                 int addr_reg;
15896                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
15897                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15898                         internal_error(state, ins, "src != %%dx");
15899                 }
15900                 fprintf(fp, "\t%s %s, %s\n",
15901                         op, 
15902                         reg(state, RHS(ins, 0), REGCM_GPR16),
15903                         reg(state, ins, mask));
15904         }
15905 }
15906
15907 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
15908 {
15909         const char *op;
15910         int mask;
15911         int lreg;
15912         mask = 0;
15913         switch(ins->op) {
15914         case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
15915         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
15916         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
15917         default:
15918                 internal_error(state, ins, "not an out operation");
15919                 op = 0;
15920                 break;
15921         }
15922         lreg = check_reg(state, RHS(ins, 0), mask);
15923         if (!reg_is_reg(state, lreg, REG_EAX)) {
15924                 internal_error(state, ins, "src != %%eax");
15925         }
15926         if (is_const(RHS(ins, 1))) {
15927                 fprintf(fp, "\t%s %s,", 
15928                         op, reg(state, RHS(ins, 0), mask));
15929                 print_const_val(state, RHS(ins, 1), fp);
15930                 fprintf(fp, "\n");
15931         }
15932         else {
15933                 int addr_reg;
15934                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
15935                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15936                         internal_error(state, ins, "dst != %%dx");
15937                 }
15938                 fprintf(fp, "\t%s %s, %s\n",
15939                         op, 
15940                         reg(state, RHS(ins, 0), mask),
15941                         reg(state, RHS(ins, 1), REGCM_GPR16));
15942         }
15943 }
15944
15945 static void print_op_move(struct compile_state *state,
15946         struct triple *ins, FILE *fp)
15947 {
15948         /* op_move is complex because there are many types
15949          * of registers we can move between.
15950          * Because OP_COPY will be introduced in arbitrary locations
15951          * OP_COPY must not affect flags.
15952          */
15953         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
15954         struct triple *dst, *src;
15955         if (ins->op == OP_COPY) {
15956                 src = RHS(ins, 0);
15957                 dst = ins;
15958         }
15959         else if (ins->op == OP_WRITE) {
15960                 dst = LHS(ins, 0);
15961                 src = RHS(ins, 0);
15962         }
15963         else {
15964                 internal_error(state, ins, "unknown move operation");
15965                 src = dst = 0;
15966         }
15967         if (!is_const(src)) {
15968                 int src_reg, dst_reg;
15969                 int src_regcm, dst_regcm;
15970                 src_reg = ID_REG(src->id);
15971                 dst_reg   = ID_REG(dst->id);
15972                 src_regcm = arch_reg_regcm(state, src_reg);
15973                 dst_regcm   = arch_reg_regcm(state, dst_reg);
15974                 /* If the class is the same just move the register */
15975                 if (src_regcm & dst_regcm & 
15976                         (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
15977                         if ((src_reg != dst_reg) || !omit_copy) {
15978                                 fprintf(fp, "\tmov %s, %s\n",
15979                                         reg(state, src, src_regcm),
15980                                         reg(state, dst, dst_regcm));
15981                         }
15982                 }
15983                 /* Move 32bit to 16bit */
15984                 else if ((src_regcm & REGCM_GPR32) &&
15985                         (dst_regcm & REGCM_GPR16)) {
15986                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
15987                         if ((src_reg != dst_reg) || !omit_copy) {
15988                                 fprintf(fp, "\tmovw %s, %s\n",
15989                                         arch_reg_str(src_reg), 
15990                                         arch_reg_str(dst_reg));
15991                         }
15992                 }
15993                 /* Move 32bit to 8bit */
15994                 else if ((src_regcm & REGCM_GPR32_8) &&
15995                         (dst_regcm & REGCM_GPR8))
15996                 {
15997                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
15998                         if ((src_reg != dst_reg) || !omit_copy) {
15999                                 fprintf(fp, "\tmovb %s, %s\n",
16000                                         arch_reg_str(src_reg),
16001                                         arch_reg_str(dst_reg));
16002                         }
16003                 }
16004                 /* Move 16bit to 8bit */
16005                 else if ((src_regcm & REGCM_GPR16_8) &&
16006                         (dst_regcm & REGCM_GPR8))
16007                 {
16008                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16009                         if ((src_reg != dst_reg) || !omit_copy) {
16010                                 fprintf(fp, "\tmovb %s, %s\n",
16011                                         arch_reg_str(src_reg),
16012                                         arch_reg_str(dst_reg));
16013                         }
16014                 }
16015                 /* Move 8/16bit to 16/32bit */
16016                 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) && 
16017                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16018                         const char *op;
16019                         op = is_signed(src->type)? "movsx": "movzx";
16020                         fprintf(fp, "\t%s %s, %s\n",
16021                                 op,
16022                                 reg(state, src, src_regcm),
16023                                 reg(state, dst, dst_regcm));
16024                 }
16025                 /* Move between sse registers */
16026                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16027                         if ((src_reg != dst_reg) || !omit_copy) {
16028                                 fprintf(fp, "\tmovdqa %s, %s\n",
16029                                         reg(state, src, src_regcm),
16030                                         reg(state, dst, dst_regcm));
16031                         }
16032                 }
16033                 /* Move between mmx registers or mmx & sse  registers */
16034                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16035                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16036                         if ((src_reg != dst_reg) || !omit_copy) {
16037                                 fprintf(fp, "\tmovq %s, %s\n",
16038                                         reg(state, src, src_regcm),
16039                                         reg(state, dst, dst_regcm));
16040                         }
16041                 }
16042                 /* Move between 32bit gprs & mmx/sse registers */
16043                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16044                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16045                         fprintf(fp, "\tmovd %s, %s\n",
16046                                 reg(state, src, src_regcm),
16047                                 reg(state, dst, dst_regcm));
16048                 }
16049 #if X86_4_8BIT_GPRS
16050                 /* Move from 8bit gprs to  mmx/sse registers */
16051                 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16052                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16053                         const char *op;
16054                         int mid_reg;
16055                         op = is_signed(src->type)? "movsx":"movzx";
16056                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16057                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16058                                 op,
16059                                 reg(state, src, src_regcm),
16060                                 arch_reg_str(mid_reg),
16061                                 arch_reg_str(mid_reg),
16062                                 reg(state, dst, dst_regcm));
16063                 }
16064                 /* Move from mmx/sse registers and 8bit gprs */
16065                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16066                         (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16067                         int mid_reg;
16068                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16069                         fprintf(fp, "\tmovd %s, %s\n",
16070                                 reg(state, src, src_regcm),
16071                                 arch_reg_str(mid_reg));
16072                 }
16073                 /* Move from 32bit gprs to 16bit gprs */
16074                 else if ((src_regcm & REGCM_GPR32) &&
16075                         (dst_regcm & REGCM_GPR16)) {
16076                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16077                         if ((src_reg != dst_reg) || !omit_copy) {
16078                                 fprintf(fp, "\tmov %s, %s\n",
16079                                         arch_reg_str(src_reg),
16080                                         arch_reg_str(dst_reg));
16081                         }
16082                 }
16083                 /* Move from 32bit gprs to 8bit gprs */
16084                 else if ((src_regcm & REGCM_GPR32) &&
16085                         (dst_regcm & REGCM_GPR8)) {
16086                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16087                         if ((src_reg != dst_reg) || !omit_copy) {
16088                                 fprintf(fp, "\tmov %s, %s\n",
16089                                         arch_reg_str(src_reg),
16090                                         arch_reg_str(dst_reg));
16091                         }
16092                 }
16093                 /* Move from 16bit gprs to 8bit gprs */
16094                 else if ((src_regcm & REGCM_GPR16) &&
16095                         (dst_regcm & REGCM_GPR8)) {
16096                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16097                         if ((src_reg != dst_reg) || !omit_copy) {
16098                                 fprintf(fp, "\tmov %s, %s\n",
16099                                         arch_reg_str(src_reg),
16100                                         arch_reg_str(dst_reg));
16101                         }
16102                 }
16103 #endif /* X86_4_8BIT_GPRS */
16104                 else {
16105                         internal_error(state, ins, "unknown copy type");
16106                 }
16107         }
16108         else {
16109                 fprintf(fp, "\tmov ");
16110                 print_const_val(state, src, fp);
16111                 fprintf(fp, ", %s\n",
16112                         reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16113         }
16114 }
16115
16116 static void print_op_load(struct compile_state *state,
16117         struct triple *ins, FILE *fp)
16118 {
16119         struct triple *dst, *src;
16120         dst = ins;
16121         src = RHS(ins, 0);
16122         if (is_const(src) || is_const(dst)) {
16123                 internal_error(state, ins, "unknown load operation");
16124         }
16125         fprintf(fp, "\tmov (%s), %s\n",
16126                 reg(state, src, REGCM_GPR32),
16127                 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16128 }
16129
16130
16131 static void print_op_store(struct compile_state *state,
16132         struct triple *ins, FILE *fp)
16133 {
16134         struct triple *dst, *src;
16135         dst = LHS(ins, 0);
16136         src = RHS(ins, 0);
16137         if (is_const(src) && (src->op == OP_INTCONST)) {
16138                 long_t value;
16139                 value = (long_t)(src->u.cval);
16140                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16141                         type_suffix(state, src->type),
16142                         value,
16143                         reg(state, dst, REGCM_GPR32));
16144         }
16145         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16146                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16147                         type_suffix(state, src->type),
16148                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16149                         dst->u.cval);
16150         }
16151         else {
16152                 if (is_const(src) || is_const(dst)) {
16153                         internal_error(state, ins, "unknown store operation");
16154                 }
16155                 fprintf(fp, "\tmov%s %s, (%s)\n",
16156                         type_suffix(state, src->type),
16157                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16158                         reg(state, dst, REGCM_GPR32));
16159         }
16160         
16161         
16162 }
16163
16164 static void print_op_smul(struct compile_state *state,
16165         struct triple *ins, FILE *fp)
16166 {
16167         if (!is_const(RHS(ins, 1))) {
16168                 fprintf(fp, "\timul %s, %s\n",
16169                         reg(state, RHS(ins, 1), REGCM_GPR32),
16170                         reg(state, RHS(ins, 0), REGCM_GPR32));
16171         }
16172         else {
16173                 fprintf(fp, "\timul ");
16174                 print_const_val(state, RHS(ins, 1), fp);
16175                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16176         }
16177 }
16178
16179 static void print_op_cmp(struct compile_state *state,
16180         struct triple *ins, FILE *fp)
16181 {
16182         unsigned mask;
16183         int dreg;
16184         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16185         dreg = check_reg(state, ins, REGCM_FLAGS);
16186         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16187                 internal_error(state, ins, "bad dest register for cmp");
16188         }
16189         if (is_const(RHS(ins, 1))) {
16190                 fprintf(fp, "\tcmp ");
16191                 print_const_val(state, RHS(ins, 1), fp);
16192                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16193         }
16194         else {
16195                 unsigned lmask, rmask;
16196                 int lreg, rreg;
16197                 lreg = check_reg(state, RHS(ins, 0), mask);
16198                 rreg = check_reg(state, RHS(ins, 1), mask);
16199                 lmask = arch_reg_regcm(state, lreg);
16200                 rmask = arch_reg_regcm(state, rreg);
16201                 mask = lmask & rmask;
16202                 fprintf(fp, "\tcmp %s, %s\n",
16203                         reg(state, RHS(ins, 1), mask),
16204                         reg(state, RHS(ins, 0), mask));
16205         }
16206 }
16207
16208 static void print_op_test(struct compile_state *state,
16209         struct triple *ins, FILE *fp)
16210 {
16211         unsigned mask;
16212         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16213         fprintf(fp, "\ttest %s, %s\n",
16214                 reg(state, RHS(ins, 0), mask),
16215                 reg(state, RHS(ins, 0), mask));
16216 }
16217
16218 static void print_op_branch(struct compile_state *state,
16219         struct triple *branch, FILE *fp)
16220 {
16221         const char *bop = "j";
16222         if (branch->op == OP_JMP) {
16223                 if (TRIPLE_RHS(branch->sizes) != 0) {
16224                         internal_error(state, branch, "jmp with condition?");
16225                 }
16226                 bop = "jmp";
16227         }
16228         else {
16229                 struct triple *ptr;
16230                 if (TRIPLE_RHS(branch->sizes) != 1) {
16231                         internal_error(state, branch, "jmpcc without condition?");
16232                 }
16233                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16234                 if ((RHS(branch, 0)->op != OP_CMP) &&
16235                         (RHS(branch, 0)->op != OP_TEST)) {
16236                         internal_error(state, branch, "bad branch test");
16237                 }
16238 #warning "FIXME I have observed instructions between the test and branch instructions"
16239                 ptr = RHS(branch, 0);
16240                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16241                         if (ptr->op != OP_COPY) {
16242                                 internal_error(state, branch, "branch does not follow test");
16243                         }
16244                 }
16245                 switch(branch->op) {
16246                 case OP_JMP_EQ:       bop = "jz";  break;
16247                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
16248                 case OP_JMP_SLESS:    bop = "jl";  break;
16249                 case OP_JMP_ULESS:    bop = "jb";  break;
16250                 case OP_JMP_SMORE:    bop = "jg";  break;
16251                 case OP_JMP_UMORE:    bop = "ja";  break;
16252                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
16253                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
16254                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
16255                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
16256                 default:
16257                         internal_error(state, branch, "Invalid branch op");
16258                         break;
16259                 }
16260                 
16261         }
16262         fprintf(fp, "\t%s L%s%lu\n",
16263                 bop, 
16264                 state->label_prefix,
16265                 TARG(branch, 0)->u.cval);
16266 }
16267
16268 static void print_op_set(struct compile_state *state,
16269         struct triple *set, FILE *fp)
16270 {
16271         const char *sop = "set";
16272         if (TRIPLE_RHS(set->sizes) != 1) {
16273                 internal_error(state, set, "setcc without condition?");
16274         }
16275         check_reg(state, RHS(set, 0), REGCM_FLAGS);
16276         if ((RHS(set, 0)->op != OP_CMP) &&
16277                 (RHS(set, 0)->op != OP_TEST)) {
16278                 internal_error(state, set, "bad set test");
16279         }
16280         if (RHS(set, 0)->next != set) {
16281                 internal_error(state, set, "set does not follow test");
16282         }
16283         switch(set->op) {
16284         case OP_SET_EQ:       sop = "setz";  break;
16285         case OP_SET_NOTEQ:    sop = "setnz"; break;
16286         case OP_SET_SLESS:    sop = "setl";  break;
16287         case OP_SET_ULESS:    sop = "setb";  break;
16288         case OP_SET_SMORE:    sop = "setg";  break;
16289         case OP_SET_UMORE:    sop = "seta";  break;
16290         case OP_SET_SLESSEQ:  sop = "setle"; break;
16291         case OP_SET_ULESSEQ:  sop = "setbe"; break;
16292         case OP_SET_SMOREEQ:  sop = "setge"; break;
16293         case OP_SET_UMOREEQ:  sop = "setae"; break;
16294         default:
16295                 internal_error(state, set, "Invalid set op");
16296                 break;
16297         }
16298         fprintf(fp, "\t%s %s\n",
16299                 sop, reg(state, set, REGCM_GPR8));
16300 }
16301
16302 static void print_op_bit_scan(struct compile_state *state, 
16303         struct triple *ins, FILE *fp) 
16304 {
16305         const char *op;
16306         switch(ins->op) {
16307         case OP_BSF: op = "bsf"; break;
16308         case OP_BSR: op = "bsr"; break;
16309         default: 
16310                 internal_error(state, ins, "unknown bit scan");
16311                 op = 0;
16312                 break;
16313         }
16314         fprintf(fp, 
16315                 "\t%s %s, %s\n"
16316                 "\tjnz 1f\n"
16317                 "\tmovl $-1, %s\n"
16318                 "1:\n",
16319                 op,
16320                 reg(state, RHS(ins, 0), REGCM_GPR32),
16321                 reg(state, ins, REGCM_GPR32),
16322                 reg(state, ins, REGCM_GPR32));
16323 }
16324
16325 static void print_const(struct compile_state *state,
16326         struct triple *ins, FILE *fp)
16327 {
16328         switch(ins->op) {
16329         case OP_INTCONST:
16330                 switch(ins->type->type & TYPE_MASK) {
16331                 case TYPE_CHAR:
16332                 case TYPE_UCHAR:
16333                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16334                         break;
16335                 case TYPE_SHORT:
16336                 case TYPE_USHORT:
16337                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16338                         break;
16339                 case TYPE_INT:
16340                 case TYPE_UINT:
16341                 case TYPE_LONG:
16342                 case TYPE_ULONG:
16343                         fprintf(fp, ".int %lu\n", ins->u.cval);
16344                         break;
16345                 default:
16346                         internal_error(state, ins, "Unknown constant type");
16347                 }
16348                 break;
16349         case OP_BLOBCONST:
16350         {
16351                 unsigned char *blob;
16352                 size_t size, i;
16353                 size = size_of(state, ins->type);
16354                 blob = ins->u.blob;
16355                 for(i = 0; i < size; i++) {
16356                         fprintf(fp, ".byte 0x%02x\n",
16357                                 blob[i]);
16358                 }
16359                 break;
16360         }
16361         default:
16362                 internal_error(state, ins, "Unknown constant type");
16363                 break;
16364         }
16365 }
16366
16367 #define TEXT_SECTION ".rom.text"
16368 #define DATA_SECTION ".rom.data"
16369
16370 static void print_sdecl(struct compile_state *state,
16371         struct triple *ins, FILE *fp)
16372 {
16373         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16374         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16375         fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16376         print_const(state, MISC(ins, 0), fp);
16377         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16378                 
16379 }
16380
16381 static void print_instruction(struct compile_state *state,
16382         struct triple *ins, FILE *fp)
16383 {
16384         /* Assumption: after I have exted the register allocator
16385          * everything is in a valid register. 
16386          */
16387         switch(ins->op) {
16388         case OP_ASM:
16389                 print_op_asm(state, ins, fp);
16390                 break;
16391         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
16392         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
16393         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
16394         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
16395         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
16396         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
16397         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
16398         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
16399         case OP_POS:    break;
16400         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
16401         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16402         case OP_INTCONST:
16403         case OP_ADDRCONST:
16404         case OP_BLOBCONST:
16405                 /* Don't generate anything here for constants */
16406         case OP_PHI:
16407                 /* Don't generate anything for variable declarations. */
16408                 break;
16409         case OP_SDECL:
16410                 print_sdecl(state, ins, fp);
16411                 break;
16412         case OP_WRITE: 
16413         case OP_COPY:   
16414                 print_op_move(state, ins, fp);
16415                 break;
16416         case OP_LOAD:
16417                 print_op_load(state, ins, fp);
16418                 break;
16419         case OP_STORE:
16420                 print_op_store(state, ins, fp);
16421                 break;
16422         case OP_SMUL:
16423                 print_op_smul(state, ins, fp);
16424                 break;
16425         case OP_CMP:    print_op_cmp(state, ins, fp); break;
16426         case OP_TEST:   print_op_test(state, ins, fp); break;
16427         case OP_JMP:
16428         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16429         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16430         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16431         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16432         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16433                 print_op_branch(state, ins, fp);
16434                 break;
16435         case OP_SET_EQ:      case OP_SET_NOTEQ:
16436         case OP_SET_SLESS:   case OP_SET_ULESS:
16437         case OP_SET_SMORE:   case OP_SET_UMORE:
16438         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16439         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16440                 print_op_set(state, ins, fp);
16441                 break;
16442         case OP_INB:  case OP_INW:  case OP_INL:
16443                 print_op_in(state, ins, fp); 
16444                 break;
16445         case OP_OUTB: case OP_OUTW: case OP_OUTL:
16446                 print_op_out(state, ins, fp); 
16447                 break;
16448         case OP_BSF:
16449         case OP_BSR:
16450                 print_op_bit_scan(state, ins, fp);
16451                 break;
16452         case OP_RDMSR:
16453                 after_lhs(state, ins);
16454                 fprintf(fp, "\trdmsr\n");
16455                 break;
16456         case OP_WRMSR:
16457                 fprintf(fp, "\twrmsr\n");
16458                 break;
16459         case OP_HLT:
16460                 fprintf(fp, "\thlt\n");
16461                 break;
16462         case OP_LABEL:
16463                 if (!ins->use) {
16464                         return;
16465                 }
16466                 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16467                 break;
16468                 /* Ignore OP_PIECE */
16469         case OP_PIECE:
16470                 break;
16471                 /* Operations I am not yet certain how to handle */
16472         case OP_UMUL:
16473         case OP_SDIV: case OP_UDIV:
16474         case OP_SMOD: case OP_UMOD:
16475                 /* Operations that should never get here */
16476         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
16477         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
16478         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16479         default:
16480                 internal_error(state, ins, "unknown op: %d %s",
16481                         ins->op, tops(ins->op));
16482                 break;
16483         }
16484 }
16485
16486 static void print_instructions(struct compile_state *state)
16487 {
16488         struct triple *first, *ins;
16489         int print_location;
16490         int last_line;
16491         int last_col;
16492         const char *last_filename;
16493         FILE *fp;
16494         print_location = 1;
16495         last_line = -1;
16496         last_col  = -1;
16497         last_filename = 0;
16498         fp = state->output;
16499         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16500         first = RHS(state->main_function, 0);
16501         ins = first;
16502         do {
16503                 if (print_location &&
16504                         ((last_filename != ins->filename) ||
16505                                 (last_line != ins->line) ||
16506                                 (last_col  != ins->col))) {
16507                         fprintf(fp, "\t/* %s:%d */\n",
16508                                 ins->filename, ins->line);
16509                         last_filename = ins->filename;
16510                         last_line = ins->line;
16511                         last_col  = ins->col;
16512                 }
16513
16514                 print_instruction(state, ins, fp);
16515                 ins = ins->next;
16516         } while(ins != first);
16517         
16518 }
16519 static void generate_code(struct compile_state *state)
16520 {
16521         generate_local_labels(state);
16522         print_instructions(state);
16523         
16524 }
16525
16526 static void print_tokens(struct compile_state *state)
16527 {
16528         struct token *tk;
16529         tk = &state->token[0];
16530         do {
16531 #if 1
16532                 token(state, 0);
16533 #else
16534                 next_token(state, 0);
16535 #endif
16536                 loc(stdout, state, 0);
16537                 printf("%s <- `%s'\n",
16538                         tokens[tk->tok],
16539                         tk->ident ? tk->ident->name :
16540                         tk->str_len ? tk->val.str : "");
16541                 
16542         } while(tk->tok != TOK_EOF);
16543 }
16544
16545 static void compile(const char *filename, const char *ofilename, 
16546         int cpu, int debug, int opt, const char *label_prefix)
16547 {
16548         int i;
16549         struct compile_state state;
16550         memset(&state, 0, sizeof(state));
16551         state.file = 0;
16552         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
16553                 memset(&state.token[i], 0, sizeof(state.token[i]));
16554                 state.token[i].tok = -1;
16555         }
16556         /* Remember the debug settings */
16557         state.cpu      = cpu;
16558         state.debug    = debug;
16559         state.optimize = opt;
16560         /* Remember the output filename */
16561         state.ofilename = ofilename;
16562         state.output    = fopen(state.ofilename, "w");
16563         if (!state.output) {
16564                 error(&state, 0, "Cannot open output file %s\n",
16565                         ofilename);
16566         }
16567         /* Remember the label prefix */
16568         state.label_prefix = label_prefix;
16569         /* Prep the preprocessor */
16570         state.if_depth = 0;
16571         state.if_value = 0;
16572         /* register the C keywords */
16573         register_keywords(&state);
16574         /* register the keywords the macro preprocessor knows */
16575         register_macro_keywords(&state);
16576         /* Memorize where some special keywords are. */
16577         state.i_continue = lookup(&state, "continue", 8);
16578         state.i_break    = lookup(&state, "break", 5);
16579         /* Enter the globl definition scope */
16580         start_scope(&state);
16581         register_builtins(&state);
16582         compile_file(&state, filename, 1);
16583 #if 0
16584         print_tokens(&state);
16585 #endif  
16586         decls(&state);
16587         /* Exit the global definition scope */
16588         end_scope(&state);
16589
16590         /* Now that basic compilation has happened 
16591          * optimize the intermediate code 
16592          */
16593         optimize(&state);
16594
16595         generate_code(&state);
16596         if (state.debug) {
16597                 fprintf(stderr, "done\n");
16598         }
16599 }
16600
16601 static void version(void)
16602 {
16603         printf("romcc " VERSION " released " RELEASE_DATE "\n");
16604 }
16605
16606 static void usage(void)
16607 {
16608         version();
16609         printf(
16610                 "Usage: romcc <source>.c\n"
16611                 "Compile a C source file without using ram\n"
16612         );
16613 }
16614
16615 static void arg_error(char *fmt, ...)
16616 {
16617         va_list args;
16618         va_start(args, fmt);
16619         vfprintf(stderr, fmt, args);
16620         va_end(args);
16621         usage();
16622         exit(1);
16623 }
16624
16625 int main(int argc, char **argv)
16626 {
16627         const char *filename;
16628         const char *ofilename;
16629         const char *label_prefix;
16630         int cpu;
16631         int last_argc;
16632         int debug;
16633         int optimize;
16634         cpu = CPU_DEFAULT;
16635         label_prefix = "";
16636         ofilename = "auto.inc";
16637         optimize = 0;
16638         debug = 0;
16639         last_argc = -1;
16640         while((argc > 1) && (argc != last_argc)) {
16641                 last_argc = argc;
16642                 if (strncmp(argv[1], "--debug=", 8) == 0) {
16643                         debug = atoi(argv[1] + 8);
16644                         argv++;
16645                         argc--;
16646                 }
16647                 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
16648                         label_prefix= argv[1] + 15;
16649                         argv++;
16650                         argc--;
16651                 }
16652                 else if ((strcmp(argv[1],"-O") == 0) ||
16653                         (strcmp(argv[1], "-O1") == 0)) {
16654                         optimize = 1;
16655                         argv++;
16656                         argc--;
16657                 }
16658                 else if (strcmp(argv[1],"-O2") == 0) {
16659                         optimize = 2;
16660                         argv++;
16661                         argc--;
16662                 }
16663                 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
16664                         ofilename = argv[2];
16665                         argv += 2;
16666                         argc -= 2;
16667                 }
16668                 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
16669                         cpu = arch_encode_cpu(argv[1] + 6);
16670                         if (cpu == BAD_CPU) {
16671                                 arg_error("Invalid cpu specified: %s\n",
16672                                         argv[1] + 6);
16673                         }
16674                         argv++;
16675                         argc--;
16676                 }
16677         }
16678         if (argc != 2) {
16679                 arg_error("Wrong argument count %d\n", argc);
16680         }
16681         filename = argv[1];
16682         compile(filename, ofilename, cpu, debug, optimize, label_prefix);
16683
16684         return 0;
16685 }