- Add a test to make certain romcc is properly allocating registers.
[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 <ctype.h>
13 #include <limits.h>
14
15 #define DEBUG_ERROR_MESSAGES 0
16 #define DEBUG_COLOR_GRAPH 0
17 #define DEBUG_SCC 0
18 #define X86_4_8BIT_GPRS 1
19
20 #warning "FIXME static constant variables"
21 #warning "FIXME enable pointers"
22 #warning "FIXME enable string constants"
23
24 /*  Control flow graph of a loop without goto.
25  * 
26  *        AAA
27  *   +---/
28  *  /
29  * / +--->CCC
30  * | |    / \
31  * | |  DDD EEE    break;
32  * | |    \    \
33  * | |    FFF   \
34  *  \|    / \    \
35  *   |\ GGG HHH   |   continue;
36  *   | \  \   |   |
37  *   |  \ III |  /
38  *   |   \ | /  / 
39  *   |    vvv  /  
40  *   +----BBB /   
41  *         | /
42  *         vv
43  *        JJJ
44  *
45  * 
46  *             AAA
47  *     +-----+  |  +----+
48  *     |      \ | /     |
49  *     |       BBB  +-+ |
50  *     |       / \ /  | |
51  *     |     CCC JJJ / /
52  *     |     / \    / / 
53  *     |   DDD EEE / /  
54  *     |    |   +-/ /
55  *     |   FFF     /    
56  *     |   / \    /     
57  *     | GGG HHH /      
58  *     |  |   +-/
59  *     | III
60  *     +--+ 
61  *
62  * 
63  * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
64  * DFup(Z)    = { Y <- DF(Z) | idom(Y) != X }
65  *
66  *
67  * [] == DFlocal(X) U DF(X)
68  * () == DFup(X)
69  *
70  * Dominator graph of the same nodes.
71  *
72  *           AAA     AAA: [ ] ()
73  *          /   \
74  *        BBB    JJJ BBB: [ JJJ ] ( JJJ )  JJJ: [ ] ()
75  *         |
76  *        CCC        CCC: [ ] ( BBB, JJJ )
77  *        / \
78  *     DDD   EEE     DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
79  *      |
80  *     FFF           FFF: [ ] ( BBB )
81  *     / \         
82  *  GGG   HHH        GGG: [ ] ( BBB ) HHH: [ BBB ] ()
83  *   |
84  *  III              III: [ BBB ] ()
85  *
86  *
87  * BBB and JJJ are definitely the dominance frontier.
88  * Where do I place phi functions and how do I make that decision.
89  *   
90  */
91 static void die(char *fmt, ...)
92 {
93         va_list args;
94
95         va_start(args, fmt);
96         vfprintf(stderr, fmt, args);
97         va_end(args);
98         fflush(stdout);
99         fflush(stderr);
100         exit(1);
101 }
102
103 #define MALLOC_STRONG_DEBUG
104 static void *xmalloc(size_t size, const char *name)
105 {
106         void *buf;
107         buf = malloc(size);
108         if (!buf) {
109                 die("Cannot malloc %ld bytes to hold %s: %s\n",
110                         size + 0UL, name, strerror(errno));
111         }
112         return buf;
113 }
114
115 static void *xcmalloc(size_t size, const char *name)
116 {
117         void *buf;
118         buf = xmalloc(size, name);
119         memset(buf, 0, size);
120         return buf;
121 }
122
123 static void xfree(const void *ptr)
124 {
125         free((void *)ptr);
126 }
127
128 static char *xstrdup(const char *str)
129 {
130         char *new;
131         int len;
132         len = strlen(str);
133         new = xmalloc(len + 1, "xstrdup string");
134         memcpy(new, str, len);
135         new[len] = '\0';
136         return new;
137 }
138
139 static void xchdir(const char *path)
140 {
141         if (chdir(path) != 0) {
142                 die("chdir to %s failed: %s\n",
143                         path, strerror(errno));
144         }
145 }
146
147 static int exists(const char *dirname, const char *filename)
148 {
149         int does_exist = 1;
150         xchdir(dirname);
151         if (access(filename, O_RDONLY) < 0) {
152                 if ((errno != EACCES) && (errno != EROFS)) {
153                         does_exist = 0;
154                 }
155         }
156         return does_exist;
157 }
158
159
160 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
161 {
162         int fd;
163         char *buf;
164         off_t size, progress;
165         ssize_t result;
166         struct stat stats;
167         
168         if (!filename) {
169                 *r_size = 0;
170                 return 0;
171         }
172         xchdir(dirname);
173         fd = open(filename, O_RDONLY);
174         if (fd < 0) {
175                 die("Cannot open '%s' : %s\n",
176                         filename, strerror(errno));
177         }
178         result = fstat(fd, &stats);
179         if (result < 0) {
180                 die("Cannot stat: %s: %s\n",
181                         filename, strerror(errno));
182         }
183         size = stats.st_size;
184         *r_size = size +1;
185         buf = xmalloc(size +2, filename);
186         buf[size] = '\n'; /* Make certain the file is newline terminated */
187         buf[size+1] = '\0'; /* Null terminate the file for good measure */
188         progress = 0;
189         while(progress < size) {
190                 result = read(fd, buf + progress, size - progress);
191                 if (result < 0) {
192                         if ((errno == EINTR) || (errno == EAGAIN))
193                                 continue;
194                         die("read on %s of %ld bytes failed: %s\n",
195                                 filename, (size - progress)+ 0UL, strerror(errno));
196                 }
197                 progress += result;
198         }
199         result = close(fd);
200         if (result < 0) {
201                 die("Close of %s failed: %s\n",
202                         filename, strerror(errno));
203         }
204         return buf;
205 }
206
207 /* Long on the destination platform */
208 typedef unsigned long ulong_t;
209 typedef long long_t;
210
211 struct file_state {
212         struct file_state *prev;
213         const char *basename;
214         char *dirname;
215         char *buf;
216         off_t size;
217         char *pos;
218         int line;
219         char *line_start;
220 };
221 struct hash_entry;
222 struct token {
223         int tok;
224         struct hash_entry *ident;
225         int str_len;
226         union {
227                 ulong_t integer;
228                 const char *str;
229         } val;
230 };
231
232 /* I have two classes of types:
233  * Operational types.
234  * Logical types.  (The type the C standard says the operation is of)
235  *
236  * The operational types are:
237  * chars
238  * shorts
239  * ints
240  * longs
241  *
242  * floats
243  * doubles
244  * long doubles
245  *
246  * pointer
247  */
248
249
250 /* Machine model.
251  * No memory is useable by the compiler.
252  * There is no floating point support.
253  * All operations take place in general purpose registers.
254  * There is one type of general purpose register.
255  * Unsigned longs are stored in that general purpose register.
256  */
257
258 /* Operations on general purpose registers.
259  */
260
261 #define OP_SMUL       0
262 #define OP_UMUL       1
263 #define OP_SDIV       2
264 #define OP_UDIV       3
265 #define OP_SMOD       4
266 #define OP_UMOD       5
267 #define OP_ADD        6
268 #define OP_SUB        7
269 #define OP_SL         8
270 #define OP_USR        9
271 #define OP_SSR       10 
272 #define OP_AND       11 
273 #define OP_XOR       12
274 #define OP_OR        13
275 #define OP_POS       14 /* Dummy positive operator don't use it */
276 #define OP_NEG       15
277 #define OP_INVERT    16
278                      
279 #define OP_EQ        20
280 #define OP_NOTEQ     21
281 #define OP_SLESS     22
282 #define OP_ULESS     23
283 #define OP_SMORE     24
284 #define OP_UMORE     25
285 #define OP_SLESSEQ   26
286 #define OP_ULESSEQ   27
287 #define OP_SMOREEQ   28
288 #define OP_UMOREEQ   29
289                      
290 #define OP_LFALSE    30  /* Test if the expression is logically false */
291 #define OP_LTRUE     31  /* Test if the expression is logcially true */
292
293 #define OP_LOAD      32
294 #define OP_STORE     33
295
296 #define OP_NOOP      34
297
298 #define OP_MIN_CONST 50
299 #define OP_MAX_CONST 59
300 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
301 #define OP_INTCONST  50
302 #define OP_BLOBCONST 51
303 /* For OP_BLOBCONST ->type holds the layout and size
304  * information.  u.blob holds a pointer to the raw binary
305  * data for the constant initializer.
306  */
307 #define OP_ADDRCONST 52
308 /* For OP_ADDRCONST ->type holds the type.
309  * RHS(0) holds the reference to the static variable.
310  * ->u.cval holds an offset from that value.
311  */
312
313 #define OP_WRITE     60 
314 /* OP_WRITE moves one pseudo register to another.
315  * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
316  * RHS(0) holds the psuedo to move.
317  */
318
319 #define OP_READ      61
320 /* OP_READ reads the value of a variable and makes
321  * it available for the pseudo operation.
322  * Useful for things like def-use chains.
323  * RHS(0) holds points to the triple to read from.
324  */
325 #define OP_COPY      62
326 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
327  */
328 #define OP_PIECE     63
329 /* OP_PIECE returns one piece of a instruction that returns a structure.
330  * RHS(0) is the instruction
331  * u.cval is the LHS piece of the instruction to return.
332  */
333
334 #define OP_DEREF     65
335 /* OP_DEREF generates an lvalue from a pointer.
336  * RHS(0) holds the pointer value.
337  * OP_DEREF serves as a place holder to indicate all necessary
338  * checks have been done to indicate a value is an lvalue.
339  */
340 #define OP_DOT       66
341 /* OP_DOT references a submember of a structure lvalue.
342  * RHS(0) holds the lvalue.
343  * ->u.field holds the name of the field we want.
344  *
345  * Not seen outside of expressions.
346  */
347 #define OP_VAL       67
348 /* OP_VAL returns the value of a subexpression of the current expression.
349  * Useful for operators that have side effects.
350  * RHS(0) holds the expression.
351  * MISC(0) holds the subexpression of RHS(0) that is the
352  * value of the expression.
353  *
354  * Not seen outside of expressions.
355  */
356 #define OP_LAND      68
357 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
358  * Not seen outside of expressions.
359  */
360 #define OP_LOR       69
361 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
362  * Not seen outside of expressions.
363  */
364 #define OP_COND      70
365 /* OP_CODE performas a C ? : operation. 
366  * RHS(0) holds the test.
367  * RHS(1) holds the expression to evaluate if the test returns true.
368  * RHS(2) holds the expression to evaluate if the test returns false.
369  * Not seen outside of expressions.
370  */
371 #define OP_COMMA     71
372 /* OP_COMMA performacs a C comma operation.
373  * That is RHS(0) is evaluated, then RHS(1)
374  * and the value of RHS(1) is returned.
375  * Not seen outside of expressions.
376  */
377
378 #define OP_CALL      72
379 /* OP_CALL performs a procedure call. 
380  * MISC(0) holds a pointer to the OP_LIST of a function
381  * RHS(x) holds argument x of a function
382  * 
383  * Currently not seen outside of expressions.
384  */
385 #define OP_VAL_VEC   74
386 /* OP_VAL_VEC is an array of triples that are either variable
387  * or values for a structure or an array.
388  * RHS(x) holds element x of the vector.
389  * triple->type->elements holds the size of the vector.
390  */
391
392 /* statements */
393 #define OP_LIST      80
394 /* OP_LIST Holds a list of statements, and a result value.
395  * RHS(0) holds the list of statements.
396  * MISC(0) holds the value of the statements.
397  */
398
399 #define OP_BRANCH    81 /* branch */
400 /* For branch instructions
401  * TARG(0) holds the branch target.
402  * RHS(0) if present holds the branch condition.
403  * ->next holds where to branch to if the branch is not taken.
404  * The branch target can only be a decl...
405  */
406
407 #define OP_LABEL     83
408 /* OP_LABEL is a triple that establishes an target for branches.
409  * ->use is the list of all branches that use this label.
410  */
411
412 #define OP_ADECL     84 
413 /* OP_DECL is a triple that establishes an lvalue for assignments.
414  * ->use is a list of statements that use the variable.
415  */
416
417 #define OP_SDECL     85
418 /* OP_VAR is a triple that establishes a variable of static
419  * storage duration.
420  * ->use is a list of statements that use the variable.
421  * MISC(0) holds the initializer expression.
422  */
423
424
425 #define OP_PHI       86
426 /* OP_PHI is a triple used in SSA form code.  
427  * It is used when multiple code paths merge and a variable needs
428  * a single assignment from any of those code paths.
429  * The operation is a cross between OP_DECL and OP_WRITE, which
430  * is what OP_PHI is geneared from.
431  * 
432  * RHS(x) points to the value from code path x
433  * The number of RHS entries is the number of control paths into the block
434  * in which OP_PHI resides.  The elements of the array point to point
435  * to the variables OP_PHI is derived from.
436  *
437  * MISC(0) holds a pointer to the orginal OP_DECL node.
438  */
439
440 /* Architecture specific instructions */
441 #define OP_CMP         100
442 #define OP_TEST        101
443 #define OP_SET_EQ      102
444 #define OP_SET_NOTEQ   103
445 #define OP_SET_SLESS   104
446 #define OP_SET_ULESS   105
447 #define OP_SET_SMORE   106
448 #define OP_SET_UMORE   107
449 #define OP_SET_SLESSEQ 108
450 #define OP_SET_ULESSEQ 109
451 #define OP_SET_SMOREEQ 110
452 #define OP_SET_UMOREEQ 111
453
454 #define OP_JMP         112
455 #define OP_JMP_EQ      113
456 #define OP_JMP_NOTEQ   114
457 #define OP_JMP_SLESS   115
458 #define OP_JMP_ULESS   116
459 #define OP_JMP_SMORE   117
460 #define OP_JMP_UMORE   118
461 #define OP_JMP_SLESSEQ 119
462 #define OP_JMP_ULESSEQ 120
463 #define OP_JMP_SMOREEQ 121
464 #define OP_JMP_UMOREEQ 122
465
466 /* Builtin operators that it is just simpler to use the compiler for */
467 #define OP_INB         130
468 #define OP_INW         131
469 #define OP_INL         132
470 #define OP_OUTB        133
471 #define OP_OUTW        134
472 #define OP_OUTL        135
473 #define OP_BSF         136
474 #define OP_BSR         137
475 #define OP_RDMSR       138
476 #define OP_WRMSR       139
477 #define OP_HLT         140
478
479 struct op_info {
480         const char *name;
481         unsigned flags;
482 #define PURE   1
483 #define IMPURE 2
484 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
485 #define DEF    4
486         unsigned char lhs, rhs, misc, targ;
487 };
488
489 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
490         .name = (NAME), \
491         .flags = (FLAGS), \
492         .lhs = (LHS), \
493         .rhs = (RHS), \
494         .misc = (MISC), \
495         .targ = (TARG), \
496          }
497 static const struct op_info table_ops[] = {
498 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF, "smul"),
499 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF, "umul"),
500 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF, "sdiv"),
501 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF, "udiv"),
502 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF, "smod"),
503 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF, "umod"),
504 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF, "add"),
505 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF, "sub"),
506 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF, "sl"),
507 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF, "usr"),
508 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF, "ssr"),
509 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF, "and"),
510 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF, "xor"),
511 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF, "or"),
512 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF, "pos"),
513 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF, "neg"),
514 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF, "invert"),
515
516 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF, "eq"),
517 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF, "noteq"),
518 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF, "sless"),
519 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF, "uless"),
520 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF, "smore"),
521 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF, "umore"),
522 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF, "slesseq"),
523 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF, "ulesseq"),
524 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF, "smoreeq"),
525 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF, "umoreeq"),
526 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF, "lfalse"),
527 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF, "ltrue"),
528
529 [OP_LOAD       ] = OP( 0,  1, 0, 0, IMPURE | DEF, "load"),
530 [OP_STORE      ] = OP( 1,  1, 0, 0, IMPURE, "store"),
531
532 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE, "noop"),
533
534 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE, "intconst"),
535 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE, "blobconst"),
536 [OP_ADDRCONST  ] = OP( 0,  1, 0, 0, PURE, "addrconst"),
537
538 [OP_WRITE      ] = OP( 1,  1, 0, 0, PURE, "write"),
539 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF, "read"),
540 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF, "copy"),
541 [OP_PIECE      ] = OP( 0,  1, 0, 0, PURE | DEF, "piece"),
542 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF, "deref"), 
543 [OP_DOT        ] = OP( 0,  1, 0, 0, 0 | DEF, "dot"),
544
545 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF, "val"),
546 [OP_LAND       ] = OP( 0,  2, 0, 0, 0 | DEF, "land"),
547 [OP_LOR        ] = OP( 0,  2, 0, 0, 0 | DEF, "lor"),
548 [OP_COND       ] = OP( 0,  3, 0, 0, 0 | DEF, "cond"),
549 [OP_COMMA      ] = OP( 0,  2, 0, 0, 0 | DEF, "comma"),
550 /* Call is special most it can stand in for anything so it depends on context */
551 [OP_CALL       ] = OP(-1, -1, 1, 0, 0, "call"),
552 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
553 [OP_VAL_VEC    ] = OP( 0, -1, 0, 0, 0, "valvec"),
554
555 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF, "list"),
556 /* The number of targets for OP_BRANCH depends on context */
557 [OP_BRANCH     ] = OP( 0, -1, 0, 1, PURE, "branch"),
558 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE, "label"),
559 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE, "adecl"),
560 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE, "sdecl"),
561 /* The number of RHS elements of OP_PHI depend upon context */
562 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF, "phi"),
563
564 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF, "cmp"),
565 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF, "test"),
566 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF, "set_eq"),
567 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_noteq"),
568 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_sless"),
569 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_uless"),
570 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_smore"),
571 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF, "set_umore"),
572 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF, "set_slesseq"),
573 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF, "set_ulesseq"),
574 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF, "set_smoreq"),
575 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF, "set_umoreq"),
576 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE, "jmp"),
577 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE, "jmp_eq"),
578 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE, "jmp_noteq"),
579 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE, "jmp_sless"),
580 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE, "jmp_uless"),
581 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE, "jmp_smore"),
582 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE, "jmp_umore"),
583 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE, "jmp_slesseq"),
584 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE, "jmp_ulesseq"),
585 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE, "jmp_smoreq"),
586 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE, "jmp_umoreq"),
587
588 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF, "__inb"),
589 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF, "__inw"),
590 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF, "__inl"),
591 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE, "__outb"),
592 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE, "__outw"),
593 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE, "__outl"),
594 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF, "__bsf"),
595 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF, "__bsr"),
596 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE, "__rdmsr"),
597 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE, "__wrmsr"),
598 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE, "__hlt"),
599 };
600 #undef OP
601 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
602
603 static const char *tops(int index) 
604 {
605         static const char unknown[] = "unknown op";
606         if (index < 0) {
607                 return unknown;
608         }
609         if (index > OP_MAX) {
610                 return unknown;
611         }
612         return table_ops[index].name;
613 }
614
615 struct triple;
616 struct block;
617 struct triple_set {
618         struct triple_set *next;
619         struct triple *member;
620 };
621
622 #define MAX_LHS  15
623 #define MAX_RHS  15
624 #define MAX_MISC 15
625 #define MAX_TARG 15
626
627 struct triple {
628         struct triple *next, *prev;
629         struct triple_set *use;
630         struct type *type;
631         short op;
632         unsigned short sizes;
633 #define TRIPLE_LHS(SIZES)  (((SIZES) >>  0) & 0x0f)
634 #define TRIPLE_RHS(SIZES)  (((SIZES) >>  4) & 0x0f)
635 #define TRIPLE_MISC(SIZES) (((SIZES) >>  8) & 0x0f)
636 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
637 #define TRIPLE_SIZE(SIZES) \
638         ((((SIZES) >> 0) & 0x0f) + \
639         (((SIZES) >>  4) & 0x0f) + \
640         (((SIZES) >>  8) & 0x0f) + \
641         (((SIZES) >> 12) & 0x0f))
642 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
643         ((((LHS) & 0x0f) <<  0) | \
644         (((RHS) & 0x0f)  <<  4) | \
645         (((MISC) & 0x0f) <<  8) | \
646         (((TARG) & 0x0f) << 12))
647 #define TRIPLE_LHS_OFF(SIZES)  (0)
648 #define TRIPLE_RHS_OFF(SIZES)  (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
649 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
650 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
651 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
652 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
653 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
654 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
655         unsigned id; /* A scratch value and finally the register */
656 #define TRIPLE_FLAG_FLATTENED 1
657         const char *filename;
658         int line;
659         int col;
660         union {
661                 ulong_t cval;
662                 struct block  *block;
663                 void *blob;
664                 struct hash_entry *field;
665         } u;
666         struct triple *param[2];
667 };
668
669 struct block_set {
670         struct block_set *next;
671         struct block *member;
672 };
673 struct block {
674         struct block *work_next;
675         struct block *left, *right;
676         struct triple *first, *last;
677         int users;
678         struct block_set *use;
679         struct block_set *idominates;
680         struct block_set *domfrontier;
681         struct block *idom;
682         struct block_set *ipdominates;
683         struct block_set *ipdomfrontier;
684         struct block *ipdom;
685         int vertex;
686         
687 };
688
689 struct symbol {
690         struct symbol *next;
691         struct hash_entry *ident;
692         struct triple *def;
693         struct type *type;
694         int scope_depth;
695 };
696
697 struct macro {
698         struct hash_entry *ident;
699         char *buf;
700         int buf_len;
701 };
702
703 struct hash_entry {
704         struct hash_entry *next;
705         const char *name;
706         int name_len;
707         int tok;
708         struct macro *sym_define;
709         struct symbol *sym_label;
710         struct symbol *sym_struct;
711         struct symbol *sym_ident;
712 };
713
714 #define HASH_TABLE_SIZE 2048
715
716 struct compile_state {
717         struct triple *vars;
718         struct file_state *file;
719         struct token token[4];
720         struct hash_entry *hash_table[HASH_TABLE_SIZE];
721         struct hash_entry *i_continue;
722         struct hash_entry *i_break;
723         int scope_depth;
724         int if_depth, if_value;
725         int macro_line;
726         struct file_state *macro_file;
727         struct triple *main_function;
728         struct block *first_block, *last_block;
729         int last_vertex;
730         int debug;
731         int optimize;
732 };
733
734 /* visibility global/local */
735 /* static/auto duration */
736 /* typedef, register, inline */
737 #define STOR_SHIFT         0
738 #define STOR_MASK     0x000f
739 /* Visibility */
740 #define STOR_GLOBAL   0x0001
741 /* Duration */
742 #define STOR_PERM     0x0002
743 /* Storage specifiers */
744 #define STOR_AUTO     0x0000
745 #define STOR_STATIC   0x0002
746 #define STOR_EXTERN   0x0003
747 #define STOR_REGISTER 0x0004
748 #define STOR_TYPEDEF  0x0008
749 #define STOR_INLINE   0x000c
750
751 #define QUAL_SHIFT         4
752 #define QUAL_MASK     0x0070
753 #define QUAL_NONE     0x0000
754 #define QUAL_CONST    0x0010
755 #define QUAL_VOLATILE 0x0020
756 #define QUAL_RESTRICT 0x0040
757
758 #define TYPE_SHIFT         8
759 #define TYPE_MASK     0x1f00
760 #define TYPE_INTEGER(TYPE)    (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
761 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
762 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
763 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
764 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
765 #define TYPE_RANK(TYPE)       ((TYPE) & ~0x0100)
766 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
767 #define TYPE_DEFAULT  0x0000
768 #define TYPE_VOID     0x0100
769 #define TYPE_CHAR     0x0200
770 #define TYPE_UCHAR    0x0300
771 #define TYPE_SHORT    0x0400
772 #define TYPE_USHORT   0x0500
773 #define TYPE_INT      0x0600
774 #define TYPE_UINT     0x0700
775 #define TYPE_LONG     0x0800
776 #define TYPE_ULONG    0x0900
777 #define TYPE_LLONG    0x0a00 /* long long */
778 #define TYPE_ULLONG   0x0b00
779 #define TYPE_FLOAT    0x0c00
780 #define TYPE_DOUBLE   0x0d00
781 #define TYPE_LDOUBLE  0x0e00 /* long double */
782 #define TYPE_STRUCT   0x1000
783 #define TYPE_ENUM     0x1100
784 #define TYPE_POINTER  0x1200 
785 /* For TYPE_POINTER:
786  * type->left holds the type pointed to.
787  */
788 #define TYPE_FUNCTION 0x1300 
789 /* For TYPE_FUNCTION:
790  * type->left holds the return type.
791  * type->right holds the...
792  */
793 #define TYPE_PRODUCT  0x1400
794 /* TYPE_PRODUCT is a basic building block when defining structures
795  * type->left holds the type that appears first in memory.
796  * type->right holds the type that appears next in memory.
797  */
798 #define TYPE_OVERLAP  0x1500
799 /* TYPE_OVERLAP is a basic building block when defining unions
800  * type->left and type->right holds to types that overlap
801  * each other in memory.
802  */
803 #define TYPE_ARRAY    0x1600
804 /* TYPE_ARRAY is a basic building block when definitng arrays.
805  * type->left holds the type we are an array of.
806  * type-> holds the number of elements.
807  */
808
809 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
810
811 struct type {
812         unsigned int type;
813         struct type *left, *right;
814         ulong_t elements;
815         struct hash_entry *field_ident;
816         struct hash_entry *type_ident;
817 };
818
819 #define MAX_REGISTERS      75
820 #define MAX_REG_EQUIVS     16
821 #define MAX_REGC           12
822 #define REG_UNSET          0
823
824 /* Provision for 8 register classes */
825 #define REGC_MASK ((1 << MAX_REGC) - 1)
826 #define ID_REG_CLASSES(ID)      ((ID) & REGC_MASK)
827 #define ID_REG(ID)              ((ID) >> MAX_REGC)
828 #define MK_REG_ID(REG, CLASSES) (((REG) << MAX_REGC) | ((CLASSES) & REGC_MASK))
829
830 static unsigned alloc_virtual_reg(void)
831 {
832         static unsigned virtual_reg = MAX_REGISTERS;
833         virtual_reg += 1;
834         return virtual_reg;
835 }
836
837 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
838 static void arch_reg_equivs(
839         struct compile_state *state, unsigned *equiv, int reg);
840 static int arch_select_free_register(
841         struct compile_state *state, char *used, int classes);
842 static unsigned arch_regc_size(struct compile_state *state, int class);
843 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
844 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
845 static const char *arch_reg_str(int reg);
846
847 #define DEBUG_ABORT_ON_ERROR    0x0001
848 #define DEBUG_INTERMEDIATE_CODE 0x0002
849 #define DEBUG_CONTROL_FLOW      0x0004
850 #define DEBUG_BASIC_BLOCKS      0x0008
851 #define DEBUG_FDOMINATORS       0x0010
852 #define DEBUG_RDOMINATORS       0x0020
853 #define DEBUG_TRIPLES           0x0040
854 #define DEBUG_INTERFERENCE      0x0080
855 #define DEBUG_ARCH_CODE         0x0100
856 #define DEBUG_CODE_ELIMINATION  0x0200
857
858 #define GLOBAL_SCOPE_DEPTH 1
859
860 static void compile_file(struct compile_state *old_state, char *filename, int local);
861
862 static int get_col(struct file_state *file)
863 {
864         int col;
865         char *ptr, *end;
866         ptr = file->line_start;
867         end = file->pos;
868         for(col = 0; ptr < end; ptr++) {
869                 if (*ptr != '\t') {
870                         col++;
871                 } 
872                 else {
873                         col = (col & ~7) + 8;
874                 }
875         }
876         return col;
877 }
878
879 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
880 {
881         int col;
882         if (triple) {
883                 fprintf(fp, "%s:%d.%d: ", 
884                         triple->filename, triple->line, triple->col);
885                 return;
886         }
887         if (!state->file) {
888                 return;
889         }
890         col = get_col(state->file);
891         fprintf(fp, "%s:%d.%d: ", 
892                 state->file->basename, state->file->line, col);
893 }
894
895 static void __internal_error(struct compile_state *state, struct triple *ptr, 
896         char *fmt, ...)
897 {
898         va_list args;
899         va_start(args, fmt);
900         loc(stderr, state, ptr);
901         fprintf(stderr, "Internal compiler error: ");
902         vfprintf(stderr, fmt, args);
903         fprintf(stderr, "\n");
904         va_end(args);
905         abort();
906 }
907
908
909 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
910         char *fmt, ...)
911 {
912         va_list args;
913         va_start(args, fmt);
914         loc(stderr, state, ptr);
915         fprintf(stderr, "Internal compiler warning: ");
916         vfprintf(stderr, fmt, args);
917         fprintf(stderr, "\n");
918         va_end(args);
919 }
920
921
922
923 static void __error(struct compile_state *state, struct triple *ptr, 
924         char *fmt, ...)
925 {
926         va_list args;
927         va_start(args, fmt);
928         loc(stderr, state, ptr);
929         vfprintf(stderr, fmt, args);
930         va_end(args);
931         fprintf(stderr, "\n");
932         if (state->debug & DEBUG_ABORT_ON_ERROR) {
933                 abort();
934         }
935         exit(1);
936 }
937
938 static void __warning(struct compile_state *state, struct triple *ptr, 
939         char *fmt, ...)
940 {
941         va_list args;
942         va_start(args, fmt);
943         loc(stderr, state, ptr);
944         fprintf(stderr, "warning: "); 
945         vfprintf(stderr, fmt, args);
946         fprintf(stderr, "\n");
947         va_end(args);
948 }
949
950 #if DEBUG_ERROR_MESSAGES 
951 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
952 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
953 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
954 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
955 #else
956 #  define internal_error __internal_error
957 #  define internal_warning __internal_warning
958 #  define error __error
959 #  define warning __warning
960 #endif
961 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
962
963
964 static void valid_op(struct compile_state *state, int op)
965 {
966         char *fmt = "invalid op: %d";
967         if (op >= OP_MAX) {
968                 internal_error(state, 0, fmt, op);
969         }
970         if (op < 0) {
971                 internal_error(state, 0, fmt, op);
972         }
973 }
974
975 static void valid_ins(struct compile_state *state, struct triple *ptr)
976 {
977         valid_op(state, ptr->op);
978 }
979
980 static void process_trigraphs(struct compile_state *state)
981 {
982         char *src, *dest, *end;
983         struct file_state *file;
984         file = state->file;
985         src = dest = file->buf;
986         end = file->buf + file->size;
987         while((end - src) >= 3) {
988                 if ((src[0] == '?') && (src[1] == '?')) {
989                         int c = -1;
990                         switch(src[2]) {
991                         case '=': c = '#'; break;
992                         case '/': c = '\\'; break;
993                         case '\'': c = '^'; break;
994                         case '(': c = '['; break;
995                         case ')': c = ']'; break;
996                         case '!': c = '!'; break;
997                         case '<': c = '{'; break;
998                         case '>': c = '}'; break;
999                         case '-': c = '~'; break;
1000                         }
1001                         if (c != -1) {
1002                                 *dest++ = c;
1003                                 src += 3;
1004                         }
1005                         else {
1006                                 *dest++ = *src++;
1007                         }
1008                 }
1009                 else {
1010                         *dest++ = *src++;
1011                 }
1012         }
1013         while(src != end) {
1014                 *dest++ = *src++;
1015         }
1016         file->size = dest - file->buf;
1017 }
1018
1019 static void splice_lines(struct compile_state *state)
1020 {
1021         char *src, *dest, *end;
1022         struct file_state *file;
1023         file = state->file;
1024         src = dest = file->buf;
1025         end = file->buf + file->size;
1026         while((end - src) >= 2) {
1027                 if ((src[0] == '\\') && (src[1] == '\n')) {
1028                         src += 2;
1029                 }
1030                 else {
1031                         *dest++ = *src++;
1032                 }
1033         }
1034         while(src != end) {
1035                 *dest++ = *src++;
1036         }
1037         file->size = dest - file->buf;
1038 }
1039
1040 static struct type void_type;
1041 static void use_triple(struct triple *used, struct triple *user)
1042 {
1043         struct triple_set **ptr, *new;
1044         if (!used)
1045                 return;
1046         if (!user)
1047                 return;
1048         ptr = &used->use;
1049         while(*ptr) {
1050                 if ((*ptr)->member == user) {
1051                         return;
1052                 }
1053                 ptr = &(*ptr)->next;
1054         }
1055         /* Append new to the head of the list, 
1056          * copy_func and rename_block_variables
1057          * depends on this.
1058          */
1059         new = xcmalloc(sizeof(*new), "triple_set");
1060         new->member = user;
1061         new->next   = used->use;
1062         used->use   = new;
1063 }
1064
1065 static void unuse_triple(struct triple *used, struct triple *unuser)
1066 {
1067         struct triple_set *use, **ptr;
1068         ptr = &used->use;
1069         while(*ptr) {
1070                 use = *ptr;
1071                 if (use->member == unuser) {
1072                         *ptr = use->next;
1073                         xfree(use);
1074                 }
1075                 else {
1076                         ptr = &use->next;
1077                 }
1078         }
1079 }
1080
1081 static void push_triple(struct triple *used, struct triple *user)
1082 {
1083         struct triple_set *new;
1084         if (!used)
1085                 return;
1086         if (!user)
1087                 return;
1088         /* Append new to the head of the list,
1089          * it's the only sensible behavoir for a stack.
1090          */
1091         new = xcmalloc(sizeof(*new), "triple_set");
1092         new->member = user;
1093         new->next   = used->use;
1094         used->use   = new;
1095 }
1096
1097 static void pop_triple(struct triple *used, struct triple *unuser)
1098 {
1099         struct triple_set *use, **ptr;
1100         ptr = &used->use;
1101         while(*ptr) {
1102                 use = *ptr;
1103                 if (use->member == unuser) {
1104                         *ptr = use->next;
1105                         xfree(use);
1106                         /* Only free one occurance from the stack */
1107                         return;
1108                 }
1109                 else {
1110                         ptr = &use->next;
1111                 }
1112         }
1113 }
1114
1115
1116 /* The zero triple is used as a place holder when we are removing pointers
1117  * from a triple.  Having allows certain sanity checks to pass even
1118  * when the original triple that was pointed to is gone.
1119  */
1120 static struct triple zero_triple = {
1121         .next     = &zero_triple,
1122         .prev     = &zero_triple,
1123         .use      = 0,
1124         .op       = OP_INTCONST,
1125         .sizes    = TRIPLE_SIZES(0, 0, 0, 0),
1126         .id       = -1, /* An invalid id */
1127         .u = { .cval   = 0, },
1128         .filename = __FILE__,
1129         .line     = __LINE__,
1130         .col      = 0,
1131         .param { [0] = 0, [1] = 0, },
1132 };
1133
1134
1135 static unsigned short triple_sizes(struct compile_state *state,
1136         int op, struct type *type, int rhs_wanted)
1137 {
1138         int lhs, rhs, misc, targ;
1139         valid_op(state, op);
1140         lhs = table_ops[op].lhs;
1141         rhs = table_ops[op].rhs;
1142         misc = table_ops[op].misc;
1143         targ = table_ops[op].targ;
1144         
1145         
1146         if (op == OP_CALL) {
1147                 struct type *param;
1148                 rhs = 0;
1149                 param = type->right;
1150                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1151                         rhs++;
1152                         param = param->right;
1153                 }
1154                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1155                         rhs++;
1156                 }
1157                 lhs = 0;
1158                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1159                         lhs = type->left->elements;
1160                 }
1161         }
1162         else if (op == OP_VAL_VEC) {
1163                 rhs = type->elements;
1164         }
1165         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1166                 rhs = rhs_wanted;
1167         }
1168         if ((rhs < 0) || (rhs > MAX_RHS)) {
1169                 internal_error(state, 0, "bad rhs");
1170         }
1171         if ((lhs < 0) || (lhs > MAX_LHS)) {
1172                 internal_error(state, 0, "bad lhs");
1173         }
1174         if ((misc < 0) || (misc > MAX_MISC)) {
1175                 internal_error(state, 0, "bad misc");
1176         }
1177         if ((targ < 0) || (targ > MAX_TARG)) {
1178                 internal_error(state, 0, "bad targs");
1179         }
1180         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1181 }
1182
1183 static struct triple *alloc_triple(struct compile_state *state, 
1184         int op, struct type *type, int rhs,
1185         const char *filename, int line, int col)
1186 {
1187         size_t size, sizes, extra_count, min_count;
1188         struct triple *ret;
1189         sizes = triple_sizes(state, op, type, rhs);
1190
1191         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1192         extra_count = TRIPLE_SIZE(sizes);
1193         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1194
1195         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1196         ret = xcmalloc(size, "tripple");
1197         ret->op       = op;
1198         ret->sizes    = sizes;
1199         ret->type     = type;
1200         ret->next     = ret;
1201         ret->prev     = ret;
1202         ret->filename = filename;
1203         ret->line     = line;
1204         ret->col      = col;
1205         return ret;
1206 }
1207
1208 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1209 {
1210         struct triple *dup;
1211         int src_rhs;
1212         src_rhs = TRIPLE_RHS(src->sizes);
1213         dup = alloc_triple(state, src->op, src->type, src_rhs,
1214                 src->filename, src->line, src->col);
1215         memcpy(dup, src, sizeof(*src));
1216         memcpy(dup->param, src->param, src_rhs * sizeof(src->param[0]));
1217         return dup;
1218 }
1219
1220 static struct triple *new_triple(struct compile_state *state, 
1221         int op, struct type *type, int rhs)
1222 {
1223         struct triple *ret;
1224         const char *filename;
1225         int line, col;
1226         filename = 0;
1227         line = 0;
1228         col  = 0;
1229         if (state->file) {
1230                 filename = state->file->basename;
1231                 line     = state->file->line;
1232                 col      = get_col(state->file);
1233         }
1234         ret = alloc_triple(state, op, type, rhs,
1235                 filename, line, col);
1236         return ret;
1237 }
1238
1239 static struct triple *build_triple(struct compile_state *state, 
1240         int op, struct type *type, struct triple *left, struct triple *right,
1241         const char *filename, int line, int col)
1242 {
1243         struct triple *ret;
1244         size_t count;
1245         ret = alloc_triple(state, op, type, -1, filename, line, col);
1246         count = TRIPLE_SIZE(ret->sizes);
1247         if (count > 0) {
1248                 ret->param[0] = left;
1249         }
1250         if (count > 1) {
1251                 ret->param[1] = right;
1252         }
1253         return ret;
1254 }
1255
1256 static struct triple *triple(struct compile_state *state, 
1257         int op, struct type *type, struct triple *left, struct triple *right)
1258 {
1259         struct triple *ret;
1260         size_t count;
1261         ret = new_triple(state, op, type, -1);
1262         count = TRIPLE_SIZE(ret->sizes);
1263         if (count >= 1) {
1264                 ret->param[0] = left;
1265         }
1266         if (count >= 2) {
1267                 ret->param[1] = right;
1268         }
1269         return ret;
1270 }
1271
1272 static struct triple *branch(struct compile_state *state, 
1273         struct triple *targ, struct triple *test)
1274 {
1275         struct triple *ret;
1276         ret = new_triple(state, OP_BRANCH, &void_type, test?1:0);
1277         if (test) {
1278                 RHS(ret, 0) = test;
1279         }
1280         TARG(ret, 0) = targ;
1281         /* record the branch target was used */
1282         if (!targ || (targ->op != OP_LABEL)) {
1283                 internal_error(state, 0, "branch not to label");
1284                 use_triple(targ, ret);
1285         }
1286         return ret;
1287 }
1288
1289
1290 static void insert_triple(struct compile_state *state,
1291         struct triple *first, struct triple *ptr)
1292 {
1293         if (ptr) {
1294                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1295                         internal_error(state, ptr, "expression already used");
1296                 }
1297                 ptr->next       = first;
1298                 ptr->prev       = first->prev;
1299                 ptr->prev->next = ptr;
1300                 ptr->next->prev = ptr;
1301                 if ((ptr->prev->op == OP_BRANCH) && 
1302                         TRIPLE_RHS(ptr->prev->sizes)) {
1303                         unuse_triple(first, ptr->prev);
1304                         use_triple(ptr, ptr->prev);
1305                 }
1306         }
1307 }
1308
1309 static struct triple *pre_triple(struct compile_state *state,
1310         struct triple *base,
1311         int op, struct type *type, struct triple *left, struct triple *right)
1312 {
1313         /* Careful this assumes it can do the easy thing to get the block */
1314         struct triple *ret;
1315         ret = build_triple(state, op, type, left, right, 
1316                 base->filename, base->line, base->col);
1317         ret->u.block = base->u.block;
1318         insert_triple(state, base, ret);
1319         return ret;
1320 }
1321
1322 static struct triple *post_triple(struct compile_state *state,
1323         struct triple *base,
1324         int op, struct type *type, struct triple *left, struct triple *right)
1325 {
1326         /* Careful this assumes it can do the easy thing to get the block */
1327         struct triple *ret;
1328         ret = build_triple(state, op, type, left, right, 
1329                 base->filename, base->line, base->col);
1330         ret->u.block = base->u.block;
1331         insert_triple(state, base->next, ret);
1332         return ret;
1333 }
1334
1335 static struct triple *label(struct compile_state *state)
1336 {
1337         /* Labels don't get a type */
1338         struct triple *result;
1339         result = triple(state, OP_LABEL, &void_type, 0, 0);
1340         return result;
1341 }
1342
1343 static void display_triple(FILE *fp, struct triple *ins)
1344 {
1345         if (ins->op == OP_INTCONST) {
1346                 fprintf(fp, "(%p) %3d %-10s 0x%08lx            @ %s:%d.%d\n",
1347                         ins, ID_REG(ins->id), tops(ins->op), ins->u.cval,
1348                         ins->filename, ins->line, ins->col);
1349         }
1350         else if (ins->op == OP_SDECL) {
1351                 fprintf(fp, "(%p) %3d %-10s %-10p            @ %s:%d.%d\n",
1352                         ins, ID_REG(ins->id), tops(ins->op), MISC(ins, 0),
1353                         ins->filename, ins->line, ins->col);
1354 #if 0
1355                 print_ins(state, MISC(ins, 0));
1356 #endif
1357         }
1358         else {
1359                 int i, count;
1360                 fprintf(fp, "(%p) %3d %-10s", 
1361                         ins, ID_REG(ins->id), tops(ins->op));
1362                 count = TRIPLE_SIZE(ins->sizes);
1363                 for(i = 0; i < count; i++) {
1364                         fprintf(fp, " %-10p", ins->param[i]);
1365                 }
1366                 for(; i < 2; i++) {
1367                         printf("           ");
1368                 }
1369                 fprintf(fp, " @ %s:%d.%d\n", 
1370                         ins->filename, ins->line, ins->col);
1371         }
1372         fflush(fp);
1373 }
1374
1375 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1376 {
1377         /* Does the triple have no side effects.
1378          * I.e. Rexecuting the triple with the same arguments 
1379          * gives the same value.
1380          */
1381         unsigned pure;
1382         valid_ins(state, ins);
1383         pure = PURE_BITS(table_ops[ins->op].flags);
1384         if ((pure != PURE) && (pure != IMPURE)) {
1385                 internal_error(state, 0, "Purity of %s not known\n",
1386                         tops(ins->op));
1387         }
1388         return pure == PURE;
1389 }
1390
1391 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1392 {
1393         /* This function is used to determine which triples need
1394          * a register.
1395          */
1396         int is_branch;
1397         valid_ins(state, ins);
1398         is_branch = (table_ops[ins->op].targ != 0);
1399         return is_branch;
1400 }
1401
1402 static int triple_is_def(struct compile_state *state, struct triple *ins)
1403 {
1404         /* This function is used to determine which triples need
1405          * a register.
1406          */
1407         int is_def;
1408         valid_ins(state, ins);
1409         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1410         return is_def;
1411 }
1412
1413 static struct triple **triple_iter(struct compile_state *state,
1414         size_t count, struct triple **vector,
1415         struct triple *ins, struct triple **last)
1416 {
1417         struct triple **ret;
1418         ret = 0;
1419         if (count) {
1420                 if (!last) {
1421                         ret = vector;
1422                 }
1423                 else if ((last >= vector) && (last < (vector + count - 1))) {
1424                         ret = last + 1;
1425                 }
1426         }
1427         return ret;
1428         
1429 }
1430
1431 static struct triple **triple_lhs(struct compile_state *state,
1432         struct triple *ins, struct triple **last)
1433 {
1434         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1435                 ins, last);
1436 }
1437
1438 static struct triple **triple_rhs(struct compile_state *state,
1439         struct triple *ins, struct triple **last)
1440 {
1441         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1442                 ins, last);
1443 }
1444
1445 static struct triple **triple_misc(struct compile_state *state,
1446         struct triple *ins, struct triple **last)
1447 {
1448         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1449                 ins, last);
1450 }
1451 static struct triple **triple_targ(struct compile_state *state,
1452         struct triple *ins, struct triple **last)
1453 {
1454         return triple_iter(state, TRIPLE_TARG(ins->sizes), &TARG(ins,0), 
1455                 ins, last);
1456 }
1457
1458 static void free_triple(struct compile_state *state, struct triple *ptr)
1459 {
1460         size_t size;
1461         size = sizeof(*ptr) - sizeof(ptr->param) +
1462                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1463         ptr->prev->next = ptr->next;
1464         ptr->next->prev = ptr->prev;
1465         if (ptr->use) {
1466                 internal_error(state, ptr, "ptr->use != 0");
1467         }
1468         memset(ptr, -1, size);
1469         xfree(ptr);
1470 }
1471
1472 static void release_triple(struct compile_state *state, struct triple *ptr)
1473 {
1474         struct triple_set *set, *next;
1475         struct triple **expr;
1476         /* Remove ptr from use chains where it is the user */
1477         expr = triple_rhs(state, ptr, 0);
1478         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1479                 if (*expr) {
1480                         unuse_triple(*expr, ptr);
1481                 }
1482         }
1483         expr = triple_lhs(state, ptr, 0);
1484         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1485                 if (*expr) {
1486                         unuse_triple(*expr, ptr);
1487                 }
1488         }
1489         expr = triple_targ(state, ptr, 0);
1490         for(; expr; expr = triple_targ(state, ptr, expr)) {
1491                 if (*expr) {
1492                         unuse_triple(*expr, ptr);
1493                 }
1494         }
1495         /* Reomve ptr from use chains where it is used */
1496         for(set = ptr->use; set; set = next) {
1497                 next = set->next;
1498                 expr = triple_rhs(state, set->member, 0);
1499                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1500                         if (*expr == ptr) {
1501                                 *expr = &zero_triple;
1502                         }
1503                 }
1504                 expr = triple_lhs(state, set->member, 0);
1505                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1506                         if (*expr == ptr) {
1507                                 *expr = &zero_triple;
1508                         }
1509                 }
1510                 expr = triple_targ(state, set->member, 0);
1511                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1512                         if (*expr == ptr) {
1513                                 *expr = &zero_triple;
1514                         }
1515                 }
1516                 unuse_triple(ptr, set->member);
1517         }
1518         free_triple(state, ptr);
1519 }
1520
1521 static void print_triple(struct compile_state *state, struct triple *ptr);
1522
1523 #define TOK_UNKNOWN     0
1524 #define TOK_SPACE       1
1525 #define TOK_SEMI        2
1526 #define TOK_LBRACE      3
1527 #define TOK_RBRACE      4
1528 #define TOK_COMMA       5
1529 #define TOK_EQ          6
1530 #define TOK_COLON       7
1531 #define TOK_LBRACKET    8
1532 #define TOK_RBRACKET    9
1533 #define TOK_LPAREN      10
1534 #define TOK_RPAREN      11
1535 #define TOK_STAR        12
1536 #define TOK_DOTS        13
1537 #define TOK_MORE        14
1538 #define TOK_LESS        15
1539 #define TOK_TIMESEQ     16
1540 #define TOK_DIVEQ       17
1541 #define TOK_MODEQ       18
1542 #define TOK_PLUSEQ      19
1543 #define TOK_MINUSEQ     20
1544 #define TOK_SLEQ        21
1545 #define TOK_SREQ        22
1546 #define TOK_ANDEQ       23
1547 #define TOK_XOREQ       24
1548 #define TOK_OREQ        25
1549 #define TOK_EQEQ        26
1550 #define TOK_NOTEQ       27
1551 #define TOK_QUEST       28
1552 #define TOK_LOGOR       29
1553 #define TOK_LOGAND      30
1554 #define TOK_OR          31
1555 #define TOK_AND         32
1556 #define TOK_XOR         33
1557 #define TOK_LESSEQ      34
1558 #define TOK_MOREEQ      35
1559 #define TOK_SL          36
1560 #define TOK_SR          37
1561 #define TOK_PLUS        38
1562 #define TOK_MINUS       39
1563 #define TOK_DIV         40
1564 #define TOK_MOD         41
1565 #define TOK_PLUSPLUS    42
1566 #define TOK_MINUSMINUS  43
1567 #define TOK_BANG        44
1568 #define TOK_ARROW       45
1569 #define TOK_DOT         46
1570 #define TOK_TILDE       47
1571 #define TOK_LIT_STRING  48
1572 #define TOK_LIT_CHAR    49
1573 #define TOK_LIT_INT     50
1574 #define TOK_LIT_FLOAT   51
1575 #define TOK_MACRO       52
1576 #define TOK_CONCATENATE 53
1577
1578 #define TOK_IDENT       54
1579 #define TOK_STRUCT_NAME 55
1580 #define TOK_ENUM_CONST  56
1581 #define TOK_TYPE_NAME   57
1582
1583 #define TOK_AUTO        58
1584 #define TOK_BREAK       59
1585 #define TOK_CASE        60
1586 #define TOK_CHAR        61
1587 #define TOK_CONST       62
1588 #define TOK_CONTINUE    63
1589 #define TOK_DEFAULT     64
1590 #define TOK_DO          65
1591 #define TOK_DOUBLE      66
1592 #define TOK_ELSE        67
1593 #define TOK_ENUM        68
1594 #define TOK_EXTERN      69
1595 #define TOK_FLOAT       70
1596 #define TOK_FOR         71
1597 #define TOK_GOTO        72
1598 #define TOK_IF          73
1599 #define TOK_INLINE      74
1600 #define TOK_INT         75
1601 #define TOK_LONG        76
1602 #define TOK_REGISTER    77
1603 #define TOK_RESTRICT    78
1604 #define TOK_RETURN      79
1605 #define TOK_SHORT       80
1606 #define TOK_SIGNED      81
1607 #define TOK_SIZEOF      82
1608 #define TOK_STATIC      83
1609 #define TOK_STRUCT      84
1610 #define TOK_SWITCH      85
1611 #define TOK_TYPEDEF     86
1612 #define TOK_UNION       87
1613 #define TOK_UNSIGNED    88
1614 #define TOK_VOID        89
1615 #define TOK_VOLATILE    90
1616 #define TOK_WHILE       91
1617 #define TOK_ASM         92
1618 #define TOK_ATTRIBUTE   93
1619 #define TOK_ALIGNOF     94
1620 #define TOK_FIRST_KEYWORD TOK_AUTO
1621 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1622
1623 #define TOK_DEFINE      100
1624 #define TOK_UNDEF       101
1625 #define TOK_INCLUDE     102
1626 #define TOK_LINE        103
1627 #define TOK_ERROR       104
1628 #define TOK_WARNING     105
1629 #define TOK_PRAGMA      106
1630 #define TOK_IFDEF       107
1631 #define TOK_IFNDEF      108
1632 #define TOK_ELIF        109
1633 #define TOK_ENDIF       110
1634
1635 #define TOK_FIRST_MACRO TOK_DEFINE
1636 #define TOK_LAST_MACRO  TOK_ENDIF
1637          
1638 #define TOK_EOF         111
1639
1640 static const char *tokens[] = {
1641 [TOK_UNKNOWN     ] = "unknown",
1642 [TOK_SPACE       ] = ":space:",
1643 [TOK_SEMI        ] = ";",
1644 [TOK_LBRACE      ] = "{",
1645 [TOK_RBRACE      ] = "}",
1646 [TOK_COMMA       ] = ",",
1647 [TOK_EQ          ] = "=",
1648 [TOK_COLON       ] = ":",
1649 [TOK_LBRACKET    ] = "[",
1650 [TOK_RBRACKET    ] = "]",
1651 [TOK_LPAREN      ] = "(",
1652 [TOK_RPAREN      ] = ")",
1653 [TOK_STAR        ] = "*",
1654 [TOK_DOTS        ] = "...",
1655 [TOK_MORE        ] = ">",
1656 [TOK_LESS        ] = "<",
1657 [TOK_TIMESEQ     ] = "*=",
1658 [TOK_DIVEQ       ] = "/=",
1659 [TOK_MODEQ       ] = "%=",
1660 [TOK_PLUSEQ      ] = "+=",
1661 [TOK_MINUSEQ     ] = "-=",
1662 [TOK_SLEQ        ] = "<<=",
1663 [TOK_SREQ        ] = ">>=",
1664 [TOK_ANDEQ       ] = "&=",
1665 [TOK_XOREQ       ] = "^=",
1666 [TOK_OREQ        ] = "|=",
1667 [TOK_EQEQ        ] = "==",
1668 [TOK_NOTEQ       ] = "!=",
1669 [TOK_QUEST       ] = "?",
1670 [TOK_LOGOR       ] = "||",
1671 [TOK_LOGAND      ] = "&&",
1672 [TOK_OR          ] = "|",
1673 [TOK_AND         ] = "&",
1674 [TOK_XOR         ] = "^",
1675 [TOK_LESSEQ      ] = "<=",
1676 [TOK_MOREEQ      ] = ">=",
1677 [TOK_SL          ] = "<<",
1678 [TOK_SR          ] = ">>",
1679 [TOK_PLUS        ] = "+",
1680 [TOK_MINUS       ] = "-",
1681 [TOK_DIV         ] = "/",
1682 [TOK_MOD         ] = "%",
1683 [TOK_PLUSPLUS    ] = "++",
1684 [TOK_MINUSMINUS  ] = "--",
1685 [TOK_BANG        ] = "!",
1686 [TOK_ARROW       ] = "->",
1687 [TOK_DOT         ] = ".",
1688 [TOK_TILDE       ] = "~",
1689 [TOK_LIT_STRING  ] = ":string:",
1690 [TOK_IDENT       ] = ":ident:",
1691 [TOK_TYPE_NAME   ] = ":typename:",
1692 [TOK_LIT_CHAR    ] = ":char:",
1693 [TOK_LIT_INT     ] = ":integer:",
1694 [TOK_LIT_FLOAT   ] = ":float:",
1695 [TOK_MACRO       ] = "#",
1696 [TOK_CONCATENATE ] = "##",
1697
1698 [TOK_AUTO        ] = "auto",
1699 [TOK_BREAK       ] = "break",
1700 [TOK_CASE        ] = "case",
1701 [TOK_CHAR        ] = "char",
1702 [TOK_CONST       ] = "const",
1703 [TOK_CONTINUE    ] = "continue",
1704 [TOK_DEFAULT     ] = "default",
1705 [TOK_DO          ] = "do",
1706 [TOK_DOUBLE      ] = "double",
1707 [TOK_ELSE        ] = "else",
1708 [TOK_ENUM        ] = "enum",
1709 [TOK_EXTERN      ] = "extern",
1710 [TOK_FLOAT       ] = "float",
1711 [TOK_FOR         ] = "for",
1712 [TOK_GOTO        ] = "goto",
1713 [TOK_IF          ] = "if",
1714 [TOK_INLINE      ] = "inline",
1715 [TOK_INT         ] = "int",
1716 [TOK_LONG        ] = "long",
1717 [TOK_REGISTER    ] = "register",
1718 [TOK_RESTRICT    ] = "restrict",
1719 [TOK_RETURN      ] = "return",
1720 [TOK_SHORT       ] = "short",
1721 [TOK_SIGNED      ] = "signed",
1722 [TOK_SIZEOF      ] = "sizeof",
1723 [TOK_STATIC      ] = "static",
1724 [TOK_STRUCT      ] = "struct",
1725 [TOK_SWITCH      ] = "switch",
1726 [TOK_TYPEDEF     ] = "typedef",
1727 [TOK_UNION       ] = "union",
1728 [TOK_UNSIGNED    ] = "unsigned",
1729 [TOK_VOID        ] = "void",
1730 [TOK_VOLATILE    ] = "volatile",
1731 [TOK_WHILE       ] = "while",
1732 [TOK_ASM         ] = "asm",
1733 [TOK_ATTRIBUTE   ] = "__attribute__",
1734 [TOK_ALIGNOF     ] = "__alignof__",
1735
1736 [TOK_DEFINE      ] = "define",
1737 [TOK_UNDEF       ] = "undef",
1738 [TOK_INCLUDE     ] = "include",
1739 [TOK_LINE        ] = "line",
1740 [TOK_ERROR       ] = "error",
1741 [TOK_WARNING     ] = "warning",
1742 [TOK_PRAGMA      ] = "pragma",
1743 [TOK_IFDEF       ] = "ifdef",
1744 [TOK_IFNDEF      ] = "ifndef",
1745 [TOK_ELIF        ] = "elif",
1746 [TOK_ENDIF       ] = "endif",
1747
1748 [TOK_EOF         ] = "EOF",
1749 };
1750
1751 static unsigned int hash(const char *str, int str_len)
1752 {
1753         unsigned int hash;
1754         const char *end;
1755         end = str + str_len;
1756         hash = 0;
1757         for(; str < end; str++) {
1758                 hash = (hash *263) + *str;
1759         }
1760         hash = hash & (HASH_TABLE_SIZE -1);
1761         return hash;
1762 }
1763
1764 static struct hash_entry *lookup(
1765         struct compile_state *state, const char *name, int name_len)
1766 {
1767         struct hash_entry *entry;
1768         unsigned int index;
1769         index = hash(name, name_len);
1770         entry = state->hash_table[index];
1771         while(entry && 
1772                 ((entry->name_len != name_len) ||
1773                         (memcmp(entry->name, name, name_len) != 0))) {
1774                 entry = entry->next;
1775         }
1776         if (!entry) {
1777                 char *new_name;
1778                 /* Get a private copy of the name */
1779                 new_name = xmalloc(name_len + 1, "hash_name");
1780                 memcpy(new_name, name, name_len);
1781                 new_name[name_len] = '\0';
1782
1783                 /* Create a new hash entry */
1784                 entry = xcmalloc(sizeof(*entry), "hash_entry");
1785                 entry->next = state->hash_table[index];
1786                 entry->name = new_name;
1787                 entry->name_len = name_len;
1788
1789                 /* Place the new entry in the hash table */
1790                 state->hash_table[index] = entry;
1791         }
1792         return entry;
1793 }
1794
1795 static void ident_to_keyword(struct compile_state *state, struct token *tk)
1796 {
1797         struct hash_entry *entry;
1798         entry = tk->ident;
1799         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
1800                 (entry->tok == TOK_ENUM_CONST) ||
1801                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
1802                         (entry->tok <= TOK_LAST_KEYWORD)))) {
1803                 tk->tok = entry->tok;
1804         }
1805 }
1806
1807 static void ident_to_macro(struct compile_state *state, struct token *tk)
1808 {
1809         struct hash_entry *entry;
1810         entry = tk->ident;
1811         if (entry && 
1812                 (entry->tok >= TOK_FIRST_MACRO) &&
1813                 (entry->tok <= TOK_LAST_MACRO)) {
1814                 tk->tok = entry->tok;
1815         }
1816 }
1817
1818 static void hash_keyword(
1819         struct compile_state *state, const char *keyword, int tok)
1820 {
1821         struct hash_entry *entry;
1822         entry = lookup(state, keyword, strlen(keyword));
1823         if (entry && entry->tok != TOK_UNKNOWN) {
1824                 die("keyword %s already hashed", keyword);
1825         }
1826         entry->tok  = tok;
1827 }
1828
1829 static void symbol(
1830         struct compile_state *state, struct hash_entry *ident,
1831         struct symbol **chain, struct triple *def, struct type *type)
1832 {
1833         struct symbol *sym;
1834         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
1835                 error(state, 0, "%s already defined", ident->name);
1836         }
1837         sym = xcmalloc(sizeof(*sym), "symbol");
1838         sym->ident = ident;
1839         sym->def   = def;
1840         sym->type  = type;
1841         sym->scope_depth = state->scope_depth;
1842         sym->next = *chain;
1843         *chain    = sym;
1844 }
1845
1846 static void start_scope(struct compile_state *state)
1847 {
1848         state->scope_depth++;
1849 }
1850
1851 static void end_scope_syms(struct symbol **chain, int depth)
1852 {
1853         struct symbol *sym, *next;
1854         sym = *chain;
1855         while(sym && (sym->scope_depth == depth)) {
1856                 next = sym->next;
1857                 xfree(sym);
1858                 sym = next;
1859         }
1860         *chain = sym;
1861 }
1862
1863 static void end_scope(struct compile_state *state)
1864 {
1865         int i;
1866         int depth;
1867         /* Walk through the hash table and remove all symbols
1868          * in the current scope. 
1869          */
1870         depth = state->scope_depth;
1871         for(i = 0; i < HASH_TABLE_SIZE; i++) {
1872                 struct hash_entry *entry;
1873                 entry = state->hash_table[i];
1874                 while(entry) {
1875                         end_scope_syms(&entry->sym_label,  depth);
1876                         end_scope_syms(&entry->sym_struct, depth);
1877                         end_scope_syms(&entry->sym_ident,  depth);
1878                         entry = entry->next;
1879                 }
1880         }
1881         state->scope_depth = depth - 1;
1882 }
1883
1884 static void register_keywords(struct compile_state *state)
1885 {
1886         hash_keyword(state, "auto",          TOK_AUTO);
1887         hash_keyword(state, "break",         TOK_BREAK);
1888         hash_keyword(state, "case",          TOK_CASE);
1889         hash_keyword(state, "char",          TOK_CHAR);
1890         hash_keyword(state, "const",         TOK_CONST);
1891         hash_keyword(state, "continue",      TOK_CONTINUE);
1892         hash_keyword(state, "default",       TOK_DEFAULT);
1893         hash_keyword(state, "do",            TOK_DO);
1894         hash_keyword(state, "double",        TOK_DOUBLE);
1895         hash_keyword(state, "else",          TOK_ELSE);
1896         hash_keyword(state, "enum",          TOK_ENUM);
1897         hash_keyword(state, "extern",        TOK_EXTERN);
1898         hash_keyword(state, "float",         TOK_FLOAT);
1899         hash_keyword(state, "for",           TOK_FOR);
1900         hash_keyword(state, "goto",          TOK_GOTO);
1901         hash_keyword(state, "if",            TOK_IF);
1902         hash_keyword(state, "inline",        TOK_INLINE);
1903         hash_keyword(state, "int",           TOK_INT);
1904         hash_keyword(state, "long",          TOK_LONG);
1905         hash_keyword(state, "register",      TOK_REGISTER);
1906         hash_keyword(state, "restrict",      TOK_RESTRICT);
1907         hash_keyword(state, "return",        TOK_RETURN);
1908         hash_keyword(state, "short",         TOK_SHORT);
1909         hash_keyword(state, "signed",        TOK_SIGNED);
1910         hash_keyword(state, "sizeof",        TOK_SIZEOF);
1911         hash_keyword(state, "static",        TOK_STATIC);
1912         hash_keyword(state, "struct",        TOK_STRUCT);
1913         hash_keyword(state, "switch",        TOK_SWITCH);
1914         hash_keyword(state, "typedef",       TOK_TYPEDEF);
1915         hash_keyword(state, "union",         TOK_UNION);
1916         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
1917         hash_keyword(state, "void",          TOK_VOID);
1918         hash_keyword(state, "volatile",      TOK_VOLATILE);
1919         hash_keyword(state, "while",         TOK_WHILE);
1920         hash_keyword(state, "asm",           TOK_ASM);
1921         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
1922         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
1923 }
1924
1925 static void register_macro_keywords(struct compile_state *state)
1926 {
1927         hash_keyword(state, "define",        TOK_DEFINE);
1928         hash_keyword(state, "undef",         TOK_UNDEF);
1929         hash_keyword(state, "include",       TOK_INCLUDE);
1930         hash_keyword(state, "line",          TOK_LINE);
1931         hash_keyword(state, "error",         TOK_ERROR);
1932         hash_keyword(state, "warning",       TOK_WARNING);
1933         hash_keyword(state, "pragma",        TOK_PRAGMA);
1934         hash_keyword(state, "ifdef",         TOK_IFDEF);
1935         hash_keyword(state, "ifndef",        TOK_IFNDEF);
1936         hash_keyword(state, "elif",          TOK_ELIF);
1937         hash_keyword(state, "endif",         TOK_ENDIF);
1938 }
1939
1940 static int spacep(int c)
1941 {
1942         int ret = 0;
1943         switch(c) {
1944         case ' ':
1945         case '\t':
1946         case '\f':
1947         case '\v':
1948         case '\r':
1949         case '\n':
1950                 ret = 1;
1951                 break;
1952         }
1953         return ret;
1954 }
1955
1956 static int digitp(int c)
1957 {
1958         int ret = 0;
1959         switch(c) {
1960         case '0': case '1': case '2': case '3': case '4': 
1961         case '5': case '6': case '7': case '8': case '9':
1962                 ret = 1;
1963                 break;
1964         }
1965         return ret;
1966 }
1967
1968 static int hexdigitp(int c)
1969 {
1970         int ret = 0;
1971         switch(c) {
1972         case '0': case '1': case '2': case '3': case '4': 
1973         case '5': case '6': case '7': case '8': case '9':
1974         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1975         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1976                 ret = 1;
1977                 break;
1978         }
1979         return ret;
1980 }
1981 static int hexdigval(int c) 
1982 {
1983         int val = -1;
1984         if ((c >= '0') && (c <= '9')) {
1985                 val = c - '0';
1986         }
1987         else if ((c >= 'A') && (c <= 'F')) {
1988                 val = 10 + (c - 'A');
1989         }
1990         else if ((c >= 'a') && (c <= 'f')) {
1991                 val = 10 + (c - 'a');
1992         }
1993         return val;
1994 }
1995
1996 static int octdigitp(int c)
1997 {
1998         int ret = 0;
1999         switch(c) {
2000         case '0': case '1': case '2': case '3': 
2001         case '4': case '5': case '6': case '7':
2002                 ret = 1;
2003                 break;
2004         }
2005         return ret;
2006 }
2007 static int octdigval(int c)
2008 {
2009         int val = -1;
2010         if ((c >= '0') && (c <= '7')) {
2011                 val = c - '0';
2012         }
2013         return val;
2014 }
2015
2016 static int letterp(int c)
2017 {
2018         int ret = 0;
2019         switch(c) {
2020         case 'a': case 'b': case 'c': case 'd': case 'e':
2021         case 'f': case 'g': case 'h': case 'i': case 'j':
2022         case 'k': case 'l': case 'm': case 'n': case 'o':
2023         case 'p': case 'q': case 'r': case 's': case 't':
2024         case 'u': case 'v': case 'w': case 'x': case 'y':
2025         case 'z':
2026         case 'A': case 'B': case 'C': case 'D': case 'E':
2027         case 'F': case 'G': case 'H': case 'I': case 'J':
2028         case 'K': case 'L': case 'M': case 'N': case 'O':
2029         case 'P': case 'Q': case 'R': case 'S': case 'T':
2030         case 'U': case 'V': case 'W': case 'X': case 'Y':
2031         case 'Z':
2032         case '_':
2033                 ret = 1;
2034                 break;
2035         }
2036         return ret;
2037 }
2038
2039 static int char_value(struct compile_state *state,
2040         const signed char **strp, const signed char *end)
2041 {
2042         const signed char *str;
2043         int c;
2044         str = *strp;
2045         c = *str++;
2046         if ((c == '\\') && (str < end)) {
2047                 switch(*str) {
2048                 case 'n':  c = '\n'; str++; break;
2049                 case 't':  c = '\t'; str++; break;
2050                 case 'v':  c = '\v'; str++; break;
2051                 case 'b':  c = '\b'; str++; break;
2052                 case 'r':  c = '\r'; str++; break;
2053                 case 'f':  c = '\f'; str++; break;
2054                 case 'a':  c = '\a'; str++; break;
2055                 case '\\': c = '\\'; str++; break;
2056                 case '?':  c = '?';  str++; break;
2057                 case '\'': c = '\''; str++; break;
2058                 case '"':  c = '"';  break;
2059                 case 'x': 
2060                         c = 0;
2061                         str++;
2062                         while((str < end) && hexdigitp(*str)) {
2063                                 c <<= 4;
2064                                 c += hexdigval(*str);
2065                                 str++;
2066                         }
2067                         break;
2068                 case '0': case '1': case '2': case '3': 
2069                 case '4': case '5': case '6': case '7':
2070                         c = 0;
2071                         while((str < end) && octdigitp(*str)) {
2072                                 c <<= 3;
2073                                 c += octdigval(*str);
2074                                 str++;
2075                         }
2076                         break;
2077                 default:
2078                         error(state, 0, "Invalid character constant");
2079                         break;
2080                 }
2081         }
2082         *strp = str;
2083         return c;
2084 }
2085
2086 static char *after_digits(char *ptr, char *end)
2087 {
2088         while((ptr < end) && digitp(*ptr)) {
2089                 ptr++;
2090         }
2091         return ptr;
2092 }
2093
2094 static char *after_octdigits(char *ptr, char *end)
2095 {
2096         while((ptr < end) && octdigitp(*ptr)) {
2097                 ptr++;
2098         }
2099         return ptr;
2100 }
2101
2102 static char *after_hexdigits(char *ptr, char *end)
2103 {
2104         while((ptr < end) && hexdigitp(*ptr)) {
2105                 ptr++;
2106         }
2107         return ptr;
2108 }
2109
2110 static void save_string(struct compile_state *state, 
2111         struct token *tk, char *start, char *end, const char *id)
2112 {
2113         char *str;
2114         int str_len;
2115         /* Create a private copy of the string */
2116         str_len = end - start + 1;
2117         str = xmalloc(str_len + 1, id);
2118         memcpy(str, start, str_len);
2119         str[str_len] = '\0';
2120
2121         /* Store the copy in the token */
2122         tk->val.str = str;
2123         tk->str_len = str_len;
2124 }
2125 static void next_token(struct compile_state *state, int index)
2126 {
2127         struct file_state *file;
2128         struct token *tk;
2129         char *token;
2130         int c, c1, c2, c3;
2131         char *tokp, *end;
2132         int tok;
2133 next_token:
2134         file = state->file;
2135         tk = &state->token[index];
2136         tk->str_len = 0;
2137         tk->ident = 0;
2138         token = tokp = file->pos;
2139         end = file->buf + file->size;
2140         tok = TOK_UNKNOWN;
2141         c = -1;
2142         if (tokp < end) {
2143                 c = *tokp;
2144         }
2145         c1 = -1;
2146         if ((tokp + 1) < end) {
2147                 c1 = tokp[1];
2148         }
2149         c2 = -1;
2150         if ((tokp + 2) < end) {
2151                 c2 = tokp[2];
2152         }
2153         c3 = -1;
2154         if ((tokp + 3) < end) {
2155                 c3 = tokp[3];
2156         }
2157         if (tokp >= end) {
2158                 tok = TOK_EOF;
2159                 tokp = end;
2160         }
2161         /* Whitespace */
2162         else if (spacep(c)) {
2163                 tok = TOK_SPACE;
2164                 while ((tokp < end) && spacep(c)) {
2165                         if (c == '\n') {
2166                                 file->line++;
2167                                 file->line_start = tokp + 1;
2168                         }
2169                         c = *(++tokp);
2170                 }
2171                 if (!spacep(c)) {
2172                         tokp--;
2173                 }
2174         }
2175         /* EOL Comments */
2176         else if ((c == '/') && (c1 == '/')) {
2177                 tok = TOK_SPACE;
2178                 for(tokp += 2; tokp < end; tokp++) {
2179                         c = *tokp;
2180                         if (c == '\n') {
2181                                 file->line++;
2182                                 file->line_start = tokp +1;
2183                                 break;
2184                         }
2185                 }
2186         }
2187         /* Comments */
2188         else if ((c == '/') && (c1 == '*')) {
2189                 int line;
2190                 char *line_start;
2191                 line = file->line;
2192                 line_start = file->line_start;
2193                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2194                         c = *tokp;
2195                         if (c == '\n') {
2196                                 line++;
2197                                 line_start = tokp +1;
2198                         }
2199                         else if ((c == '*') && (tokp[1] == '/')) {
2200                                 tok = TOK_SPACE;
2201                                 tokp += 1;
2202                                 break;
2203                         }
2204                 }
2205                 if (tok == TOK_UNKNOWN) {
2206                         error(state, 0, "unterminated comment");
2207                 }
2208                 file->line = line;
2209                 file->line_start = line_start;
2210         }
2211         /* string constants */
2212         else if ((c == '"') ||
2213                 ((c == 'L') && (c1 == '"'))) {
2214                 int line;
2215                 char *line_start;
2216                 int wchar;
2217                 line = file->line;
2218                 line_start = file->line_start;
2219                 wchar = 0;
2220                 if (c == 'L') {
2221                         wchar = 1;
2222                         tokp++;
2223                 }
2224                 for(tokp += 1; tokp < end; tokp++) {
2225                         c = *tokp;
2226                         if (c == '\n') {
2227                                 line++;
2228                                 line_start = tokp + 1;
2229                         }
2230                         else if ((c == '\\') && (tokp +1 < end)) {
2231                                 tokp++;
2232                         }
2233                         else if (c == '"') {
2234                                 tok = TOK_LIT_STRING;
2235                                 break;
2236                         }
2237                 }
2238                 if (tok == TOK_UNKNOWN) {
2239                         error(state, 0, "unterminated string constant");
2240                 }
2241                 if (line != file->line) {
2242                         warning(state, 0, "multiline string constant");
2243                 }
2244                 file->line = line;
2245                 file->line_start = line_start;
2246
2247                 /* Save the string value */
2248                 save_string(state, tk, token, tokp, "literal string");
2249         }
2250         /* character constants */
2251         else if ((c == '\'') ||
2252                 ((c == 'L') && (c1 == '\''))) {
2253                 int line;
2254                 char *line_start;
2255                 int wchar;
2256                 line = file->line;
2257                 line_start = file->line_start;
2258                 wchar = 0;
2259                 if (c == 'L') {
2260                         wchar = 1;
2261                         tokp++;
2262                 }
2263                 for(tokp += 1; tokp < end; tokp++) {
2264                         c = *tokp;
2265                         if (c == '\n') {
2266                                 line++;
2267                                 line_start = tokp + 1;
2268                         }
2269                         else if ((c == '\\') && (tokp +1 < end)) {
2270                                 tokp++;
2271                         }
2272                         else if (c == '\'') {
2273                                 tok = TOK_LIT_CHAR;
2274                                 break;
2275                         }
2276                 }
2277                 if (tok == TOK_UNKNOWN) {
2278                         error(state, 0, "unterminated character constant");
2279                 }
2280                 if (line != file->line) {
2281                         warning(state, 0, "multiline character constant");
2282                 }
2283                 file->line = line;
2284                 file->line_start = line_start;
2285
2286                 /* Save the character value */
2287                 save_string(state, tk, token, tokp, "literal character");
2288         }
2289         /* integer and floating constants 
2290          * Integer Constants
2291          * {digits}
2292          * 0[Xx]{hexdigits}
2293          * 0{octdigit}+
2294          * 
2295          * Floating constants
2296          * {digits}.{digits}[Ee][+-]?{digits}
2297          * {digits}.{digits}
2298          * {digits}[Ee][+-]?{digits}
2299          * .{digits}[Ee][+-]?{digits}
2300          * .{digits}
2301          */
2302         
2303         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2304                 char *next, *new;
2305                 int is_float;
2306                 is_float = 0;
2307                 if (c != '.') {
2308                         next = after_digits(tokp, end);
2309                 }
2310                 else {
2311                         next = tokp;
2312                 }
2313                 if (next[0] == '.') {
2314                         new = after_digits(next, end);
2315                         is_float = (new != next);
2316                         next = new;
2317                 }
2318                 if ((next[0] == 'e') || (next[0] == 'E')) {
2319                         if (((next + 1) < end) && 
2320                                 ((next[1] == '+') || (next[1] == '-'))) {
2321                                 next++;
2322                         }
2323                         new = after_digits(next, end);
2324                         is_float = (new != next);
2325                         next = new;
2326                 }
2327                 if (is_float) {
2328                         tok = TOK_LIT_FLOAT;
2329                         if ((next < end) && (
2330                                 (next[0] == 'f') ||
2331                                 (next[0] == 'F') ||
2332                                 (next[0] == 'l') ||
2333                                 (next[0] == 'L'))
2334                                 ) {
2335                                 next++;
2336                         }
2337                 }
2338                 if (!is_float && digitp(c)) {
2339                         tok = TOK_LIT_INT;
2340                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2341                                 next = after_hexdigits(tokp + 2, end);
2342                         }
2343                         else if (c == '0') {
2344                                 next = after_octdigits(tokp, end);
2345                         }
2346                         else {
2347                                 next = after_digits(tokp, end);
2348                         }
2349                         /* crazy integer suffixes */
2350                         if ((next < end) && 
2351                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2352                                 next++;
2353                                 if ((next < end) &&
2354                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2355                                         next++;
2356                                 }
2357                         }
2358                         else if ((next < end) &&
2359                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2360                                 next++;
2361                                 if ((next < end) && 
2362                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2363                                         next++;
2364                                 }
2365                         }
2366                 }
2367                 tokp = next - 1;
2368
2369                 /* Save the integer/floating point value */
2370                 save_string(state, tk, token, tokp, "literal number");
2371         }
2372         /* identifiers */
2373         else if (letterp(c)) {
2374                 tok = TOK_IDENT;
2375                 for(tokp += 1; tokp < end; tokp++) {
2376                         c = *tokp;
2377                         if (!letterp(c) && !digitp(c)) {
2378                                 break;
2379                         }
2380                 }
2381                 tokp -= 1;
2382                 tk->ident = lookup(state, token, tokp +1 - token);
2383         }
2384         /* C99 alternate macro characters */
2385         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2386                 tokp += 3; 
2387                 tok = TOK_CONCATENATE; 
2388         }
2389         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2390         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2391         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2392         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2393         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2394         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2395         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2396         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2397         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2398         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2399         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2400         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2401         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2402         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2403         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2404         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2405         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2406         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2407         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2408         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2409         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2410         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2411         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2412         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2413         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2414         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2415         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2416         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2417         else if (c == ';') { tok = TOK_SEMI; }
2418         else if (c == '{') { tok = TOK_LBRACE; }
2419         else if (c == '}') { tok = TOK_RBRACE; }
2420         else if (c == ',') { tok = TOK_COMMA; }
2421         else if (c == '=') { tok = TOK_EQ; }
2422         else if (c == ':') { tok = TOK_COLON; }
2423         else if (c == '[') { tok = TOK_LBRACKET; }
2424         else if (c == ']') { tok = TOK_RBRACKET; }
2425         else if (c == '(') { tok = TOK_LPAREN; }
2426         else if (c == ')') { tok = TOK_RPAREN; }
2427         else if (c == '*') { tok = TOK_STAR; }
2428         else if (c == '>') { tok = TOK_MORE; }
2429         else if (c == '<') { tok = TOK_LESS; }
2430         else if (c == '?') { tok = TOK_QUEST; }
2431         else if (c == '|') { tok = TOK_OR; }
2432         else if (c == '&') { tok = TOK_AND; }
2433         else if (c == '^') { tok = TOK_XOR; }
2434         else if (c == '+') { tok = TOK_PLUS; }
2435         else if (c == '-') { tok = TOK_MINUS; }
2436         else if (c == '/') { tok = TOK_DIV; }
2437         else if (c == '%') { tok = TOK_MOD; }
2438         else if (c == '!') { tok = TOK_BANG; }
2439         else if (c == '.') { tok = TOK_DOT; }
2440         else if (c == '~') { tok = TOK_TILDE; }
2441         else if (c == '#') { tok = TOK_MACRO; }
2442         if (tok == TOK_MACRO) {
2443                 /* Only match preprocessor directives at the start of a line */
2444                 char *ptr;
2445                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2446                         ;
2447                 if (ptr != tokp) {
2448                         tok = TOK_UNKNOWN;
2449                 }
2450         }
2451         if (tok == TOK_UNKNOWN) {
2452                 error(state, 0, "unknown token");
2453         }
2454
2455         file->pos = tokp + 1;
2456         tk->tok = tok;
2457         if (tok == TOK_IDENT) {
2458                 ident_to_keyword(state, tk);
2459         }
2460         /* Don't return space tokens. */
2461         if (tok == TOK_SPACE) {
2462                 goto next_token;
2463         }
2464 }
2465
2466 static void compile_macro(struct compile_state *state, struct token *tk)
2467 {
2468         struct file_state *file;
2469         struct hash_entry *ident;
2470         ident = tk->ident;
2471         file = xmalloc(sizeof(*file), "file_state");
2472         file->basename = xstrdup(tk->ident->name);
2473         file->dirname = xstrdup("");
2474         file->size = ident->sym_define->buf_len;
2475         file->buf = xmalloc(file->size +2,  file->basename);
2476         memcpy(file->buf, ident->sym_define->buf, file->size);
2477         file->buf[file->size] = '\n';
2478         file->buf[file->size + 1] = '\0';
2479         file->pos = file->buf;
2480         file->line_start = file->pos;
2481         file->line = 1;
2482         file->prev = state->file;
2483         state->file = file;
2484 }
2485
2486
2487 static int mpeek(struct compile_state *state, int index)
2488 {
2489         struct token *tk;
2490         int rescan;
2491         tk = &state->token[index + 1];
2492         if (tk->tok == -1) {
2493                 next_token(state, index + 1);
2494         }
2495         do {
2496                 rescan = 0;
2497                 if ((tk->tok == TOK_EOF) && 
2498                         (state->file != state->macro_file) &&
2499                         (state->file->prev)) {
2500                         struct file_state *file = state->file;
2501                         state->file = file->prev;
2502                         /* file->basename is used keep it */
2503                         xfree(file->dirname);
2504                         xfree(file->buf);
2505                         xfree(file);
2506                         next_token(state, index + 1);
2507                         rescan = 1;
2508                 }
2509                 else if (tk->ident && tk->ident->sym_define) {
2510                         compile_macro(state, tk);
2511                         next_token(state, index + 1);
2512                         rescan = 1;
2513                 }
2514         } while(rescan);
2515         /* Don't show the token on the next line */
2516         if (state->macro_line < state->macro_file->line) {
2517                 return TOK_EOF;
2518         }
2519         return state->token[index +1].tok;
2520 }
2521
2522 static void meat(struct compile_state *state, int index, int tok)
2523 {
2524         int next_tok;
2525         int i;
2526         next_tok = mpeek(state, index);
2527         if (next_tok != tok) {
2528                 const char *name1, *name2;
2529                 name1 = tokens[next_tok];
2530                 name2 = "";
2531                 if (next_tok == TOK_IDENT) {
2532                         name2 = state->token[index + 1].ident->name;
2533                 }
2534                 error(state, 0, "found %s %s expected %s", 
2535                         name1, name2, tokens[tok]);
2536         }
2537         /* Free the old token value */
2538         if (state->token[index].str_len) {
2539                 memset((void *)(state->token[index].val.str), -1, 
2540                         state->token[index].str_len);
2541                 xfree(state->token[index].val.str);
2542         }
2543         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2544                 state->token[i] = state->token[i + 1];
2545         }
2546         memset(&state->token[i], 0, sizeof(state->token[i]));
2547         state->token[i].tok = -1;
2548 }
2549
2550 static long_t mcexpr(struct compile_state *state, int index);
2551
2552 static long_t mprimary_expr(struct compile_state *state, int index)
2553 {
2554         long_t val;
2555         int tok;
2556         tok = mpeek(state, index);
2557         while(state->token[index + 1].ident && 
2558                 state->token[index + 1].ident->sym_define) {
2559                 meat(state, index, tok);
2560                 compile_macro(state, &state->token[index]);
2561                 tok = mpeek(state, index);
2562         }
2563         switch(tok) {
2564         case TOK_LPAREN:
2565                 meat(state, index, TOK_LPAREN);
2566                 val = mcexpr(state, index);
2567                 meat(state, index, TOK_RPAREN);
2568                 break;
2569         case TOK_LIT_INT:
2570         {
2571                 char *end;
2572                 meat(state, index, TOK_LIT_INT);
2573                 errno = 0;
2574                 val = strtol(state->token[index].val.str, &end, 0);
2575                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2576                         (errno == ERANGE)) {
2577                         error(state, 0, "Integer constant to large");
2578                 }
2579                 break;
2580         }
2581         default:
2582                 meat(state, index, TOK_LIT_INT);
2583                 val = 0;
2584         }
2585         return val;
2586 }
2587 static long_t munary_expr(struct compile_state *state, int index)
2588 {
2589         long_t val;
2590         switch(mpeek(state, index)) {
2591         case TOK_PLUS:
2592                 meat(state, index, TOK_PLUS);
2593                 val = munary_expr(state, index);
2594                 val = + val;
2595                 break;
2596         case TOK_MINUS:
2597                 meat(state, index, TOK_MINUS);
2598                 val = munary_expr(state, index);
2599                 val = - val;
2600                 break;
2601         case TOK_TILDE:
2602                 meat(state, index, TOK_BANG);
2603                 val = munary_expr(state, index);
2604                 val = ~ val;
2605                 break;
2606         case TOK_BANG:
2607                 meat(state, index, TOK_BANG);
2608                 val = munary_expr(state, index);
2609                 val = ! val;
2610                 break;
2611         default:
2612                 val = mprimary_expr(state, index);
2613                 break;
2614         }
2615         return val;
2616         
2617 }
2618 static long_t mmul_expr(struct compile_state *state, int index)
2619 {
2620         long_t val;
2621         int done;
2622         val = munary_expr(state, index);
2623         do {
2624                 long_t right;
2625                 done = 0;
2626                 switch(mpeek(state, index)) {
2627                 case TOK_STAR:
2628                         meat(state, index, TOK_STAR);
2629                         right = munary_expr(state, index);
2630                         val = val * right;
2631                         break;
2632                 case TOK_DIV:
2633                         meat(state, index, TOK_DIV);
2634                         right = munary_expr(state, index);
2635                         val = val / right;
2636                         break;
2637                 case TOK_MOD:
2638                         meat(state, index, TOK_MOD);
2639                         right = munary_expr(state, index);
2640                         val = val % right;
2641                         break;
2642                 default:
2643                         done = 1;
2644                         break;
2645                 }
2646         } while(!done);
2647
2648         return val;
2649 }
2650
2651 static long_t madd_expr(struct compile_state *state, int index)
2652 {
2653         long_t val;
2654         int done;
2655         val = mmul_expr(state, index);
2656         do {
2657                 long_t right;
2658                 done = 0;
2659                 switch(mpeek(state, index)) {
2660                 case TOK_PLUS:
2661                         meat(state, index, TOK_PLUS);
2662                         right = mmul_expr(state, index);
2663                         val = val + right;
2664                         break;
2665                 case TOK_MINUS:
2666                         meat(state, index, TOK_MINUS);
2667                         right = mmul_expr(state, index);
2668                         val = val - right;
2669                         break;
2670                 default:
2671                         done = 1;
2672                         break;
2673                 }
2674         } while(!done);
2675
2676         return val;
2677 }
2678
2679 static long_t mshift_expr(struct compile_state *state, int index)
2680 {
2681         long_t val;
2682         int done;
2683         val = madd_expr(state, index);
2684         do {
2685                 long_t right;
2686                 done = 0;
2687                 switch(mpeek(state, index)) {
2688                 case TOK_SL:
2689                         meat(state, index, TOK_SL);
2690                         right = madd_expr(state, index);
2691                         val = val << right;
2692                         break;
2693                 case TOK_SR:
2694                         meat(state, index, TOK_SR);
2695                         right = madd_expr(state, index);
2696                         val = val >> right;
2697                         break;
2698                 default:
2699                         done = 1;
2700                         break;
2701                 }
2702         } while(!done);
2703
2704         return val;
2705 }
2706
2707 static long_t mrel_expr(struct compile_state *state, int index)
2708 {
2709         long_t val;
2710         int done;
2711         val = mshift_expr(state, index);
2712         do {
2713                 long_t right;
2714                 done = 0;
2715                 switch(mpeek(state, index)) {
2716                 case TOK_LESS:
2717                         meat(state, index, TOK_LESS);
2718                         right = mshift_expr(state, index);
2719                         val = val < right;
2720                         break;
2721                 case TOK_MORE:
2722                         meat(state, index, TOK_MORE);
2723                         right = mshift_expr(state, index);
2724                         val = val > right;
2725                         break;
2726                 case TOK_LESSEQ:
2727                         meat(state, index, TOK_LESSEQ);
2728                         right = mshift_expr(state, index);
2729                         val = val <= right;
2730                         break;
2731                 case TOK_MOREEQ:
2732                         meat(state, index, TOK_MOREEQ);
2733                         right = mshift_expr(state, index);
2734                         val = val >= right;
2735                         break;
2736                 default:
2737                         done = 1;
2738                         break;
2739                 }
2740         } while(!done);
2741         return val;
2742 }
2743
2744 static long_t meq_expr(struct compile_state *state, int index)
2745 {
2746         long_t val;
2747         int done;
2748         val = mrel_expr(state, index);
2749         do {
2750                 long_t right;
2751                 done = 0;
2752                 switch(mpeek(state, index)) {
2753                 case TOK_EQEQ:
2754                         meat(state, index, TOK_EQEQ);
2755                         right = mrel_expr(state, index);
2756                         val = val == right;
2757                         break;
2758                 case TOK_NOTEQ:
2759                         meat(state, index, TOK_NOTEQ);
2760                         right = mrel_expr(state, index);
2761                         val = val != right;
2762                         break;
2763                 default:
2764                         done = 1;
2765                         break;
2766                 }
2767         } while(!done);
2768         return val;
2769 }
2770
2771 static long_t mand_expr(struct compile_state *state, int index)
2772 {
2773         long_t val;
2774         val = meq_expr(state, index);
2775         if (mpeek(state, index) == TOK_AND) {
2776                 long_t right;
2777                 meat(state, index, TOK_AND);
2778                 right = meq_expr(state, index);
2779                 val = val & right;
2780         }
2781         return val;
2782 }
2783
2784 static long_t mxor_expr(struct compile_state *state, int index)
2785 {
2786         long_t val;
2787         val = mand_expr(state, index);
2788         if (mpeek(state, index) == TOK_XOR) {
2789                 long_t right;
2790                 meat(state, index, TOK_XOR);
2791                 right = mand_expr(state, index);
2792                 val = val ^ right;
2793         }
2794         return val;
2795 }
2796
2797 static long_t mor_expr(struct compile_state *state, int index)
2798 {
2799         long_t val;
2800         val = mxor_expr(state, index);
2801         if (mpeek(state, index) == TOK_OR) {
2802                 long_t right;
2803                 meat(state, index, TOK_OR);
2804                 right = mxor_expr(state, index);
2805                 val = val | right;
2806         }
2807         return val;
2808 }
2809
2810 static long_t mland_expr(struct compile_state *state, int index)
2811 {
2812         long_t val;
2813         val = mor_expr(state, index);
2814         if (mpeek(state, index) == TOK_LOGAND) {
2815                 long_t right;
2816                 meat(state, index, TOK_LOGAND);
2817                 right = mor_expr(state, index);
2818                 val = val && right;
2819         }
2820         return val;
2821 }
2822 static long_t mlor_expr(struct compile_state *state, int index)
2823 {
2824         long_t val;
2825         val = mland_expr(state, index);
2826         if (mpeek(state, index) == TOK_LOGOR) {
2827                 long_t right;
2828                 meat(state, index, TOK_LOGOR);
2829                 right = mland_expr(state, index);
2830                 val = val || right;
2831         }
2832         return val;
2833 }
2834
2835 static long_t mcexpr(struct compile_state *state, int index)
2836 {
2837         return mlor_expr(state, index);
2838 }
2839 static void preprocess(struct compile_state *state, int index)
2840 {
2841         /* Doing much more with the preprocessor would require
2842          * a parser and a major restructuring.
2843          * Postpone that for later.
2844          */
2845         struct file_state *file;
2846         struct token *tk;
2847         int line;
2848         int tok;
2849         
2850         file = state->file;
2851         tk = &state->token[index];
2852         state->macro_line = line = file->line;
2853         state->macro_file = file;
2854
2855         next_token(state, index);
2856         ident_to_macro(state, tk);
2857         if (tk->tok == TOK_IDENT) {
2858                 error(state, 0, "undefined preprocessing directive `%s'",
2859                         tk->ident->name);
2860         }
2861         switch(tk->tok) {
2862         case TOK_UNDEF:
2863         case TOK_LINE:
2864         case TOK_PRAGMA:
2865                 if (state->if_value < 0) {
2866                         break;
2867                 }
2868                 warning(state, 0, "Ignoring preprocessor directive: %s", 
2869                         tk->ident->name);
2870                 break;
2871         case TOK_ELIF:
2872                 error(state, 0, "#elif not supported");
2873 #warning "FIXME multiple #elif and #else in an #if do not work properly"
2874                 if (state->if_depth == 0) {
2875                         error(state, 0, "#elif without #if");
2876                 }
2877                 /* If the #if was taken the #elif just disables the following code */
2878                 if (state->if_value >= 0) {
2879                         state->if_value = - state->if_value;
2880                 }
2881                 /* If the previous #if was not taken see if the #elif enables the 
2882                  * trailing code.
2883                  */
2884                 else if ((state->if_value < 0) && 
2885                         (state->if_depth == - state->if_value))
2886                 {
2887                         if (mcexpr(state, index) != 0) {
2888                                 state->if_value = state->if_depth;
2889                         }
2890                         else {
2891                                 state->if_value = - state->if_depth;
2892                         }
2893                 }
2894                 break;
2895         case TOK_IF:
2896                 state->if_depth++;
2897                 if (state->if_value < 0) {
2898                         break;
2899                 }
2900                 if (mcexpr(state, index) != 0) {
2901                         state->if_value = state->if_depth;
2902                 }
2903                 else {
2904                         state->if_value = - state->if_depth;
2905                 }
2906                 break;
2907         case TOK_IFNDEF:
2908                 state->if_depth++;
2909                 if (state->if_value < 0) {
2910                         break;
2911                 }
2912                 next_token(state, index);
2913                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2914                         error(state, 0, "Invalid macro name");
2915                 }
2916                 if (tk->ident->sym_define == 0) {
2917                         state->if_value = state->if_depth;
2918                 } 
2919                 else {
2920                         state->if_value = - state->if_depth;
2921                 }
2922                 break;
2923         case TOK_IFDEF:
2924                 state->if_depth++;
2925                 if (state->if_value < 0) {
2926                         break;
2927                 }
2928                 next_token(state, index);
2929                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
2930                         error(state, 0, "Invalid macro name");
2931                 }
2932                 if (tk->ident->sym_define != 0) {
2933                         state->if_value = state->if_depth;
2934                 }
2935                 else {
2936                         state->if_value = - state->if_depth;
2937                 }
2938                 break;
2939         case TOK_ELSE:
2940                 if (state->if_depth == 0) {
2941                         error(state, 0, "#else without #if");
2942                 }
2943                 if ((state->if_value >= 0) ||
2944                         ((state->if_value < 0) && 
2945                                 (state->if_depth == -state->if_value)))
2946                 {
2947                         state->if_value = - state->if_value;
2948                 }
2949                 break;
2950         case TOK_ENDIF:
2951                 if (state->if_depth == 0) {
2952                         error(state, 0, "#endif without #if");
2953                 }
2954                 if ((state->if_value >= 0) ||
2955                         ((state->if_value < 0) &&
2956                                 (state->if_depth == -state->if_value))) 
2957                 {
2958                         state->if_value = state->if_depth - 1;
2959                 }
2960                 state->if_depth--;
2961                 break;
2962         case TOK_DEFINE:
2963         {
2964                 struct hash_entry *ident;
2965                 struct macro *macro;
2966                 char *ptr;
2967                 
2968                 if (state->if_value < 0) /* quit early when #if'd out */
2969                         break;
2970
2971                 meat(state, index, TOK_IDENT);
2972                 ident = tk->ident;
2973                 
2974
2975                 if (*file->pos == '(') {
2976 #warning "FIXME macros with arguments not supported"
2977                         error(state, 0, "Macros with arguments not supported");
2978                 }
2979
2980                 /* Find the end of the line to get an estimate of
2981                  * the macro's length.
2982                  */
2983                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
2984                         ;
2985
2986                 if (ident->sym_define != 0) {
2987                         error(state, 0, "macro %s already defined\n", ident->name);
2988                 }
2989                 macro = xmalloc(sizeof(*macro), "macro");
2990                 macro->ident = ident;
2991                 macro->buf_len = ptr - file->pos +1;
2992                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
2993
2994                 memcpy(macro->buf, file->pos, macro->buf_len);
2995                 macro->buf[macro->buf_len] = '\n';
2996                 macro->buf[macro->buf_len +1] = '\0';
2997
2998                 ident->sym_define = macro;
2999                 break;
3000         }
3001         case TOK_ERROR:
3002         {
3003                 char *end;
3004                 int len;
3005                 /* Find the end of the line */
3006                 for(end = file->pos; *end != '\n'; end++)
3007                         ;
3008                 len = (end - file->pos);
3009                 if (state->if_value >= 0) {
3010                         error(state, 0, "%*.*s", len, len, file->pos);
3011                 }
3012                 file->pos = end;
3013                 break;
3014         }
3015         case TOK_WARNING:
3016         {
3017                 char *end;
3018                 int len;
3019                 /* Find the end of the line */
3020                 for(end = file->pos; *end != '\n'; end++)
3021                         ;
3022                 len = (end - file->pos);
3023                 if (state->if_value >= 0) {
3024                         warning(state, 0, "%*.*s", len, len, file->pos);
3025                 }
3026                 file->pos = end;
3027                 break;
3028         }
3029         case TOK_INCLUDE:
3030         {
3031                 char *name;
3032                 char *ptr;
3033                 int local;
3034                 local = 0;
3035                 name = 0;
3036                 next_token(state, index);
3037                 if (tk->tok == TOK_LIT_STRING) {
3038                         const char *token;
3039                         int name_len;
3040                         name = xmalloc(tk->str_len, "include");
3041                         token = tk->val.str +1;
3042                         name_len = tk->str_len -2;
3043                         if (*token == '"') {
3044                                 token++;
3045                                 name_len--;
3046                         }
3047                         memcpy(name, token, name_len);
3048                         name[name_len] = '\0';
3049                         local = 1;
3050                 }
3051                 else if (tk->tok == TOK_LESS) {
3052                         char *start, *end;
3053                         start = file->pos;
3054                         for(end = start; *end != '\n'; end++) {
3055                                 if (*end == '>') {
3056                                         break;
3057                                 }
3058                         }
3059                         if (*end == '\n') {
3060                                 error(state, 0, "Unterminated included directive");
3061                         }
3062                         name = xmalloc(end - start + 1, "include");
3063                         memcpy(name, start, end - start);
3064                         name[end - start] = '\0';
3065                         file->pos = end +1;
3066                         local = 0;
3067                 }
3068                 else {
3069                         error(state, 0, "Invalid include directive");
3070                 }
3071                 /* Error if there are any characters after the include */
3072                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3073                         if (!isspace(*ptr)) {
3074                                 error(state, 0, "garbage after include directive");
3075                         }
3076                 }
3077                 if (state->if_value >= 0) {
3078                         compile_file(state, name, local);
3079                 }
3080                 xfree(name);
3081                 next_token(state, index);
3082                 return;
3083         }
3084         default:
3085                 /* Ignore # without a following ident */
3086                 if (tk->tok == TOK_IDENT) {
3087                         error(state, 0, "Invalid preprocessor directive: %s", 
3088                                 tk->ident->name);
3089                 }
3090                 break;
3091         }
3092         /* Consume the rest of the macro line */
3093         do {
3094                 tok = mpeek(state, index);
3095                 meat(state, index, tok);
3096         } while(tok != TOK_EOF);
3097         return;
3098 }
3099
3100 static void token(struct compile_state *state, int index)
3101 {
3102         struct file_state *file;
3103         struct token *tk;
3104         int rescan;
3105
3106         tk = &state->token[index];
3107         next_token(state, index);
3108         do {
3109                 rescan = 0;
3110                 file = state->file;
3111                 if (tk->tok == TOK_EOF && file->prev) {
3112                         state->file = file->prev;
3113                         /* file->basename is used keep it */
3114                         xfree(file->dirname);
3115                         xfree(file->buf);
3116                         xfree(file);
3117                         next_token(state, index);
3118                         rescan = 1;
3119                 }
3120                 else if (tk->tok == TOK_MACRO) {
3121                         preprocess(state, index);
3122                         rescan = 1;
3123                 }
3124                 else if (tk->ident && tk->ident->sym_define) {
3125                         compile_macro(state, tk);
3126                         next_token(state, index);
3127                         rescan = 1;
3128                 }
3129                 else if (state->if_value < 0) {
3130                         next_token(state, index);
3131                         rescan = 1;
3132                 }
3133         } while(rescan);
3134 }
3135
3136 static int peek(struct compile_state *state)
3137 {
3138         if (state->token[1].tok == -1) {
3139                 token(state, 1);
3140         }
3141         return state->token[1].tok;
3142 }
3143
3144 static int peek2(struct compile_state *state)
3145 {
3146         if (state->token[1].tok == -1) {
3147                 token(state, 1);
3148         }
3149         if (state->token[2].tok == -1) {
3150                 token(state, 2);
3151         }
3152         return state->token[2].tok;
3153 }
3154
3155 static void eat(struct compile_state *state, int tok)
3156 {
3157         int next_tok;
3158         int i;
3159         next_tok = peek(state);
3160         if (next_tok != tok) {
3161                 const char *name1, *name2;
3162                 name1 = tokens[next_tok];
3163                 name2 = "";
3164                 if (next_tok == TOK_IDENT) {
3165                         name2 = state->token[1].ident->name;
3166                 }
3167                 error(state, 0, "\tfound %s %s expected %s",
3168                         name1, name2 ,tokens[tok]);
3169         }
3170         /* Free the old token value */
3171         if (state->token[0].str_len) {
3172                 xfree((void *)(state->token[0].val.str));
3173         }
3174         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3175                 state->token[i] = state->token[i + 1];
3176         }
3177         memset(&state->token[i], 0, sizeof(state->token[i]));
3178         state->token[i].tok = -1;
3179 }
3180
3181 #warning "FIXME do not hardcode the include paths"
3182 static char *include_paths[] = {
3183         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3184         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3185         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3186         0
3187 };
3188
3189 static void compile_file(struct compile_state *state, char *filename, int local)
3190 {
3191         char cwd[4096];
3192         char *subdir, *base;
3193         int subdir_len;
3194         struct file_state *file;
3195         char *basename;
3196         file = xmalloc(sizeof(*file), "file_state");
3197
3198         base = strrchr(filename, '/');
3199         subdir = filename;
3200         if (base != 0) {
3201                 subdir_len = base - filename;
3202                 base++;
3203         }
3204         else {
3205                 base = filename;
3206                 subdir_len = 0;
3207         }
3208         basename = xmalloc(strlen(base) +1, "basename");
3209         strcpy(basename, base);
3210         file->basename = basename;
3211
3212         if (getcwd(cwd, sizeof(cwd)) == 0) {
3213                 die("cwd buffer to small");
3214         }
3215         
3216         if (subdir[0] == '/') {
3217                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3218                 memcpy(file->dirname, subdir, subdir_len);
3219                 file->dirname[subdir_len] = '\0';
3220         }
3221         else {
3222                 char *dir;
3223                 int dirlen;
3224                 char **path;
3225                 /* Find the appropriate directory... */
3226                 dir = 0;
3227                 if (!state->file && exists(cwd, filename)) {
3228                         dir = cwd;
3229                 }
3230                 if (local && state->file && exists(state->file->dirname, filename)) {
3231                         dir = state->file->dirname;
3232                 }
3233                 for(path = include_paths; !dir && *path; path++) {
3234                         if (exists(*path, filename)) {
3235                                 dir = *path;
3236                         }
3237                 }
3238                 if (!dir) {
3239                         error(state, 0, "Cannot find `%s'\n", filename);
3240                 }
3241                 dirlen = strlen(dir);
3242                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3243                 memcpy(file->dirname, dir, dirlen);
3244                 file->dirname[dirlen] = '/';
3245                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3246                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3247         }
3248         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3249         xchdir(cwd);
3250
3251         file->pos = file->buf;
3252         file->line_start = file->pos;
3253         file->line = 1;
3254
3255         file->prev = state->file;
3256         state->file = file;
3257         
3258         process_trigraphs(state);
3259         splice_lines(state);
3260 }
3261
3262 /* Type helper functions */
3263
3264 static struct type *new_type(
3265         unsigned int type, struct type *left, struct type *right)
3266 {
3267         struct type *result;
3268         result = xmalloc(sizeof(*result), "type");
3269         result->type = type;
3270         result->left = left;
3271         result->right = right;
3272         result->field_ident = 0;
3273         result->type_ident = 0;
3274         return result;
3275 }
3276
3277 static struct type *clone_type(unsigned int specifiers, struct type *old)
3278 {
3279         struct type *result;
3280         result = xmalloc(sizeof(*result), "type");
3281         memcpy(result, old, sizeof(*result));
3282         result->type &= TYPE_MASK;
3283         result->type |= specifiers;
3284         return result;
3285 }
3286
3287 #define SIZEOF_SHORT 2
3288 #define SIZEOF_INT   4
3289 #define SIZEOF_LONG  (sizeof(long_t))
3290
3291 #define ALIGNOF_SHORT 2
3292 #define ALIGNOF_INT   4
3293 #define ALIGNOF_LONG  (sizeof(long_t))
3294
3295 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3296 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3297 static inline ulong_t mask_uint(ulong_t x)
3298 {
3299         if (SIZEOF_INT < SIZEOF_LONG) {
3300                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3301                 x &= mask;
3302         }
3303         return x;
3304 }
3305 #define MASK_UINT(X)      (mask_uint(X))
3306 #define MASK_ULONG(X)    (X)
3307
3308 static struct type void_type   = { .type  = TYPE_VOID };
3309 static struct type char_type   = { .type  = TYPE_CHAR };
3310 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3311 static struct type short_type  = { .type  = TYPE_SHORT };
3312 static struct type ushort_type = { .type  = TYPE_USHORT };
3313 static struct type int_type    = { .type  = TYPE_INT };
3314 static struct type uint_type   = { .type  = TYPE_UINT };
3315 static struct type long_type   = { .type  = TYPE_LONG };
3316 static struct type ulong_type  = { .type  = TYPE_ULONG };
3317
3318 static struct triple *variable(struct compile_state *state, struct type *type)
3319 {
3320         struct triple *result;
3321         if ((type->type & STOR_MASK) != STOR_PERM) {
3322                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3323                         result = triple(state, OP_ADECL, type, 0, 0);
3324                 } else {
3325                         struct type *field;
3326                         struct triple **vector;
3327                         ulong_t index;
3328                         result = new_triple(state, OP_VAL_VEC, type, -1);
3329                         vector = &result->param[0];
3330
3331                         field = type->left;
3332                         index = 0;
3333                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3334                                 vector[index] = variable(state, field->left);
3335                                 field = field->right;
3336                                 index++;
3337                         }
3338                         vector[index] = variable(state, field);
3339                 }
3340         }
3341         else {
3342                 result = triple(state, OP_SDECL, type, 0, 0);
3343         }
3344         return result;
3345 }
3346
3347 static void stor_of(FILE *fp, struct type *type)
3348 {
3349         switch(type->type & STOR_MASK) {
3350         case STOR_AUTO:
3351                 fprintf(fp, "auto ");
3352                 break;
3353         case STOR_STATIC:
3354                 fprintf(fp, "static ");
3355                 break;
3356         case STOR_EXTERN:
3357                 fprintf(fp, "extern ");
3358                 break;
3359         case STOR_REGISTER:
3360                 fprintf(fp, "register ");
3361                 break;
3362         case STOR_TYPEDEF:
3363                 fprintf(fp, "typedef ");
3364                 break;
3365         case STOR_INLINE:
3366                 fprintf(fp, "inline ");
3367                 break;
3368         }
3369 }
3370 static void qual_of(FILE *fp, struct type *type)
3371 {
3372         if (type->type & QUAL_CONST) {
3373                 fprintf(fp, " const");
3374         }
3375         if (type->type & QUAL_VOLATILE) {
3376                 fprintf(fp, " volatile");
3377         }
3378         if (type->type & QUAL_RESTRICT) {
3379                 fprintf(fp, " restrict");
3380         }
3381 }
3382
3383 static void name_of(FILE *fp, struct type *type)
3384 {
3385         stor_of(fp, type);
3386         switch(type->type & TYPE_MASK) {
3387         case TYPE_VOID:
3388                 fprintf(fp, "void");
3389                 qual_of(fp, type);
3390                 break;
3391         case TYPE_CHAR:
3392                 fprintf(fp, "signed char");
3393                 qual_of(fp, type);
3394                 break;
3395         case TYPE_UCHAR:
3396                 fprintf(fp, "unsigned char");
3397                 qual_of(fp, type);
3398                 break;
3399         case TYPE_SHORT:
3400                 fprintf(fp, "signed short");
3401                 qual_of(fp, type);
3402                 break;
3403         case TYPE_USHORT:
3404                 fprintf(fp, "unsigned short");
3405                 qual_of(fp, type);
3406                 break;
3407         case TYPE_INT:
3408                 fprintf(fp, "signed int");
3409                 qual_of(fp, type);
3410                 break;
3411         case TYPE_UINT:
3412                 fprintf(fp, "unsigned int");
3413                 qual_of(fp, type);
3414                 break;
3415         case TYPE_LONG:
3416                 fprintf(fp, "signed long");
3417                 qual_of(fp, type);
3418                 break;
3419         case TYPE_ULONG:
3420                 fprintf(fp, "unsigned long");
3421                 qual_of(fp, type);
3422                 break;
3423         case TYPE_POINTER:
3424                 name_of(fp, type->left);
3425                 fprintf(fp, " * ");
3426                 qual_of(fp, type);
3427                 break;
3428         case TYPE_PRODUCT:
3429         case TYPE_OVERLAP:
3430                 name_of(fp, type->left);
3431                 fprintf(fp, ", ");
3432                 name_of(fp, type->right);
3433                 break;
3434         case TYPE_ENUM:
3435                 fprintf(fp, "enum %s", type->type_ident->name);
3436                 qual_of(fp, type);
3437                 break;
3438         case TYPE_STRUCT:
3439                 fprintf(fp, "struct %s", type->type_ident->name);
3440                 qual_of(fp, type);
3441                 break;
3442         case TYPE_FUNCTION:
3443         {
3444                 name_of(fp, type->left);
3445                 fprintf(fp, " (*)(");
3446                 name_of(fp, type->right);
3447                 fprintf(fp, ")");
3448                 break;
3449         }
3450         case TYPE_ARRAY:
3451                 name_of(fp, type->left);
3452                 fprintf(fp, " [%ld]", type->elements);
3453                 break;
3454         default:
3455                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3456                 break;
3457         }
3458 }
3459
3460 static size_t align_of(struct compile_state *state, struct type *type)
3461 {
3462         size_t align;
3463         align = 0;
3464         switch(type->type & TYPE_MASK) {
3465         case TYPE_VOID:
3466                 align = 1;
3467                 break;
3468         case TYPE_CHAR:
3469         case TYPE_UCHAR:
3470                 align = 1;
3471                 break;
3472         case TYPE_SHORT:
3473         case TYPE_USHORT:
3474                 align = ALIGNOF_SHORT;
3475                 break;
3476         case TYPE_INT:
3477         case TYPE_UINT:
3478         case TYPE_ENUM:
3479                 align = ALIGNOF_INT;
3480                 break;
3481         case TYPE_LONG:
3482         case TYPE_ULONG:
3483         case TYPE_POINTER:
3484                 align = ALIGNOF_LONG;
3485                 break;
3486         case TYPE_PRODUCT:
3487         case TYPE_OVERLAP:
3488         {
3489                 size_t left_align, right_align;
3490                 left_align  = align_of(state, type->left);
3491                 right_align = align_of(state, type->right);
3492                 align = (left_align >= right_align) ? left_align : right_align;
3493                 break;
3494         }
3495         case TYPE_ARRAY:
3496                 align = align_of(state, type->left);
3497                 break;
3498         case TYPE_STRUCT:
3499                 align = align_of(state, type->left);
3500                 break;
3501         default:
3502                 error(state, 0, "alignof not yet defined for type\n");
3503                 break;
3504         }
3505         return align;
3506 }
3507
3508 static size_t size_of(struct compile_state *state, struct type *type)
3509 {
3510         size_t size;
3511         size = 0;
3512         switch(type->type & TYPE_MASK) {
3513         case TYPE_VOID:
3514                 size = 0;
3515                 break;
3516         case TYPE_CHAR:
3517         case TYPE_UCHAR:
3518                 size = 1;
3519                 break;
3520         case TYPE_SHORT:
3521         case TYPE_USHORT:
3522                 size = SIZEOF_SHORT;
3523                 break;
3524         case TYPE_INT:
3525         case TYPE_UINT:
3526         case TYPE_ENUM:
3527                 size = SIZEOF_INT;
3528                 break;
3529         case TYPE_LONG:
3530         case TYPE_ULONG:
3531         case TYPE_POINTER:
3532                 size = SIZEOF_LONG;
3533                 break;
3534         case TYPE_PRODUCT:
3535         {
3536                 size_t align, pad;
3537                 size = size_of(state, type->left);
3538                 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3539                         type = type->right;
3540                         align = align_of(state, type->left);
3541                         pad = align - (size % align);
3542                         size = size + pad + size_of(state, type->left);
3543                 }
3544                 align = align_of(state, type->right);
3545                 pad = align - (size % align);
3546                 size = size + pad + sizeof(type->right);
3547                 break;
3548         }
3549         case TYPE_OVERLAP:
3550         {
3551                 size_t size_left, size_right;
3552                 size_left = size_of(state, type->left);
3553                 size_right = size_of(state, type->right);
3554                 size = (size_left >= size_right)? size_left : size_right;
3555                 break;
3556         }
3557         case TYPE_ARRAY:
3558                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3559                         internal_error(state, 0, "Invalid array type");
3560                 } else {
3561                         size = size_of(state, type->left) * type->elements;
3562                 }
3563                 break;
3564         case TYPE_STRUCT:
3565                 size = size_of(state, type->left);
3566                 break;
3567         default:
3568                 error(state, 0, "sizeof not yet defined for type\n");
3569                 break;
3570         }
3571         return size;
3572 }
3573
3574 static size_t field_offset(struct compile_state *state, 
3575         struct type *type, struct hash_entry *field)
3576 {
3577         size_t size, align, pad;
3578         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3579                 internal_error(state, 0, "field_offset only works on structures");
3580         }
3581         size = 0;
3582         type = type->left;
3583         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3584                 if (type->left->field_ident == field) {
3585                         type = type->left;
3586                 }
3587                 size += size_of(state, type->left);
3588                 type = type->right;
3589                 align = align_of(state, type->left);
3590                 pad = align - (size % align);
3591                 size += pad;
3592         }
3593         if (type->field_ident != field) {
3594                 internal_error(state, 0, "field_offset: member %s not present",
3595                         field->name);
3596         }
3597         return size;
3598 }
3599
3600 static struct type *field_type(struct compile_state *state, 
3601         struct type *type, struct hash_entry *field)
3602 {
3603         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3604                 internal_error(state, 0, "field_type only works on structures");
3605         }
3606         type = type->left;
3607         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3608                 if (type->left->field_ident == field) {
3609                         type = type->left;
3610                         break;
3611                 }
3612                 type = type->right;
3613         }
3614         if (type->field_ident != field) {
3615                 internal_error(state, 0, "field_type: member %s not present", 
3616                         field->name);
3617         }
3618         return type;
3619 }
3620
3621 static struct triple *struct_field(struct compile_state *state,
3622         struct triple *decl, struct hash_entry *field)
3623 {
3624         struct triple **vector;
3625         struct type *type;
3626         ulong_t index;
3627         type = decl->type;
3628         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3629                 return decl;
3630         }
3631         if (decl->op != OP_VAL_VEC) {
3632                 internal_error(state, 0, "Invalid struct variable");
3633         }
3634         if (!field) {
3635                 internal_error(state, 0, "Missing structure field");
3636         }
3637         type = type->left;
3638         vector = &RHS(decl, 0);
3639         index = 0;
3640         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3641                 if (type->left->field_ident == field) {
3642                         type = type->left;
3643                         break;
3644                 }
3645                 index += 1;
3646                 type = type->right;
3647         }
3648         if (type->field_ident != field) {
3649                 internal_error(state, 0, "field %s not found?", field->name);
3650         }
3651         return vector[index];
3652 }
3653
3654 static void arrays_complete(struct compile_state *state, struct type *type)
3655 {
3656         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3657                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3658                         error(state, 0, "array size not specified");
3659                 }
3660                 arrays_complete(state, type->left);
3661         }
3662 }
3663
3664 static unsigned int do_integral_promotion(unsigned int type)
3665 {
3666         type &= TYPE_MASK;
3667         if (TYPE_INTEGER(type) && 
3668                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3669                 type = TYPE_INT;
3670         }
3671         return type;
3672 }
3673
3674 static unsigned int do_arithmetic_conversion(
3675         unsigned int left, unsigned int right)
3676 {
3677         left &= TYPE_MASK;
3678         right &= TYPE_MASK;
3679         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3680                 return TYPE_LDOUBLE;
3681         }
3682         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3683                 return TYPE_DOUBLE;
3684         }
3685         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3686                 return TYPE_FLOAT;
3687         }
3688         left = do_integral_promotion(left);
3689         right = do_integral_promotion(right);
3690         /* If both operands have the same size done */
3691         if (left == right) {
3692                 return left;
3693         }
3694         /* If both operands have the same signedness pick the larger */
3695         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3696                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3697         }
3698         /* If the signed type can hold everything use it */
3699         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3700                 return left;
3701         }
3702         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3703                 return right;
3704         }
3705         /* Convert to the unsigned type with the same rank as the signed type */
3706         else if (TYPE_SIGNED(left)) {
3707                 return TYPE_MKUNSIGNED(left);
3708         }
3709         else {
3710                 return TYPE_MKUNSIGNED(right);
3711         }
3712 }
3713
3714 /* see if two types are the same except for qualifiers */
3715 static int equiv_types(struct type *left, struct type *right)
3716 {
3717         unsigned int type;
3718         /* Error if the basic types do not match */
3719         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3720                 return 0;
3721         }
3722         type = left->type & TYPE_MASK;
3723         /* if the basic types match and it is an arithmetic type we are done */
3724         if (TYPE_ARITHMETIC(type)) {
3725                 return 1;
3726         }
3727         /* If it is a pointer type recurse and keep testing */
3728         if (type == TYPE_POINTER) {
3729                 return equiv_types(left->left, right->left);
3730         }
3731         else if (type == TYPE_ARRAY) {
3732                 return (left->elements == right->elements) &&
3733                         equiv_types(left->left, right->left);
3734         }
3735         /* test for struct/union equality */
3736         else if (type == TYPE_STRUCT) {
3737                 return left->type_ident == right->type_ident;
3738         }
3739         /* Test for equivalent functions */
3740         else if (type == TYPE_FUNCTION) {
3741                 return equiv_types(left->left, right->left) &&
3742                         equiv_types(left->right, right->right);
3743         }
3744         /* We only see TYPE_PRODUCT as part of function equivalence matching */
3745         else if (type == TYPE_PRODUCT) {
3746                 return equiv_types(left->left, right->left) &&
3747                         equiv_types(left->right, right->right);
3748         }
3749         /* We should see TYPE_OVERLAP */
3750         else {
3751                 return 0;
3752         }
3753 }
3754
3755 static int equiv_ptrs(struct type *left, struct type *right)
3756 {
3757         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3758                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3759                 return 0;
3760         }
3761         return equiv_types(left->left, right->left);
3762 }
3763
3764 static struct type *compatible_types(struct type *left, struct type *right)
3765 {
3766         struct type *result;
3767         unsigned int type, qual_type;
3768         /* Error if the basic types do not match */
3769         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3770                 return 0;
3771         }
3772         type = left->type & TYPE_MASK;
3773         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3774         result = 0;
3775         /* if the basic types match and it is an arithmetic type we are done */
3776         if (TYPE_ARITHMETIC(type)) {
3777                 result = new_type(qual_type, 0, 0);
3778         }
3779         /* If it is a pointer type recurse and keep testing */
3780         else if (type == TYPE_POINTER) {
3781                 result = compatible_types(left->left, right->left);
3782                 if (result) {
3783                         result = new_type(qual_type, result, 0);
3784                 }
3785         }
3786         /* test for struct/union equality */
3787         else if (type == TYPE_STRUCT) {
3788                 if (left->type_ident == right->type_ident) {
3789                         result = left;
3790                 }
3791         }
3792         /* Test for equivalent functions */
3793         else if (type == TYPE_FUNCTION) {
3794                 struct type *lf, *rf;
3795                 lf = compatible_types(left->left, right->left);
3796                 rf = compatible_types(left->right, right->right);
3797                 if (lf && rf) {
3798                         result = new_type(qual_type, lf, rf);
3799                 }
3800         }
3801         /* We only see TYPE_PRODUCT as part of function equivalence matching */
3802         else if (type == TYPE_PRODUCT) {
3803                 struct type *lf, *rf;
3804                 lf = compatible_types(left->left, right->left);
3805                 rf = compatible_types(left->right, right->right);
3806                 if (lf && rf) {
3807                         result = new_type(qual_type, lf, rf);
3808                 }
3809         }
3810         else {
3811                 /* Nothing else is compatible */
3812         }
3813         return result;
3814 }
3815
3816 static struct type *compatible_ptrs(struct type *left, struct type *right)
3817 {
3818         struct type *result;
3819         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3820                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3821                 return 0;
3822         }
3823         result = compatible_types(left->left, right->left);
3824         if (result) {
3825                 unsigned int qual_type;
3826                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3827                 result = new_type(qual_type, result, 0);
3828         }
3829         return result;
3830         
3831 }
3832 static struct triple *integral_promotion(
3833         struct compile_state *state, struct triple *def)
3834 {
3835         struct type *type;
3836         type = def->type;
3837         /* As all operations are carried out in registers
3838          * the values are converted on load I just convert
3839          * logical type of the operand.
3840          */
3841         if (TYPE_INTEGER(type->type)) {
3842                 unsigned int int_type;
3843                 int_type = type->type & ~TYPE_MASK;
3844                 int_type |= do_integral_promotion(type->type);
3845                 if (int_type != type->type) {
3846                         def->type = new_type(int_type, 0, 0);
3847                 }
3848         }
3849         return def;
3850 }
3851
3852
3853 static void arithmetic(struct compile_state *state, struct triple *def)
3854 {
3855         if (!TYPE_ARITHMETIC(def->type->type)) {
3856                 error(state, def, "arithmetic type expexted");
3857         }
3858 }
3859
3860 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
3861 {
3862         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
3863                 error(state, def, "pointer or arithmetic type expected");
3864         }
3865 }
3866
3867 static int is_integral(struct triple *ins)
3868 {
3869         return TYPE_INTEGER(ins->type->type);
3870 }
3871
3872 static void integral(struct compile_state *state, struct triple *def)
3873 {
3874         if (!is_integral(def)) {
3875                 error(state, 0, "integral type expected");
3876         }
3877 }
3878
3879
3880 static void bool(struct compile_state *state, struct triple *def)
3881 {
3882         if (!TYPE_ARITHMETIC(def->type->type) &&
3883                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
3884                 error(state, 0, "arithmetic or pointer type expected");
3885         }
3886 }
3887
3888 static int is_signed(struct type *type)
3889 {
3890         return !!TYPE_SIGNED(type->type);
3891 }
3892
3893 /* Is this value located in a register otherwise it must be in memory */
3894 static int is_in_reg(struct compile_state *state, struct triple *def)
3895 {
3896         int in_reg;
3897         if (def->op == OP_ADECL) {
3898                 in_reg = 1;
3899         }
3900         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
3901                 in_reg = 0;
3902         }
3903         else if (def->op == OP_VAL_VEC) {
3904                 in_reg = is_in_reg(state, RHS(def, 0));
3905         }
3906         else if (def->op == OP_DOT) {
3907                 in_reg = is_in_reg(state, RHS(def, 0));
3908         }
3909         else {
3910                 internal_error(state, 0, "unknown expr storage location");
3911                 in_reg = -1;
3912         }
3913         return in_reg;
3914 }
3915
3916 /* Is this a stable variable location otherwise it must be a temporary */
3917 static int is_stable(struct compile_state *state, struct triple *def)
3918 {
3919         int ret;
3920         ret = 0;
3921         if (!def) {
3922                 return 0;
3923         }
3924         if ((def->op == OP_ADECL) || 
3925                 (def->op == OP_SDECL) || 
3926                 (def->op == OP_DEREF) ||
3927                 (def->op == OP_BLOBCONST)) {
3928                 ret = 1;
3929         }
3930         else if (def->op == OP_DOT) {
3931                 ret = is_stable(state, RHS(def, 0));
3932         }
3933         else if (def->op == OP_VAL_VEC) {
3934                 struct triple **vector;
3935                 ulong_t i;
3936                 ret = 1;
3937                 vector = &RHS(def, 0);
3938                 for(i = 0; i < def->type->elements; i++) {
3939                         if (!is_stable(state, vector[i])) {
3940                                 ret = 0;
3941                                 break;
3942                         }
3943                 }
3944         }
3945         return ret;
3946 }
3947
3948 static int is_lvalue(struct compile_state *state, struct triple *def)
3949 {
3950         int ret;
3951         ret = 1;
3952         if (!def) {
3953                 return 0;
3954         }
3955         if (!is_stable(state, def)) {
3956                 return 0;
3957         }
3958         if (def->type->type & QUAL_CONST) {
3959                 ret = 0;
3960         }
3961         else if (def->op == OP_DOT) {
3962                 ret = is_lvalue(state, RHS(def, 0));
3963         }
3964         return ret;
3965 }
3966
3967 static void lvalue(struct compile_state *state, struct triple *def)
3968 {
3969         if (!def) {
3970                 internal_error(state, def, "nothing where lvalue expected?");
3971         }
3972         if (!is_lvalue(state, def)) { 
3973                 error(state, def, "lvalue expected");
3974         }
3975 }
3976
3977 static int is_pointer(struct triple *def)
3978 {
3979         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
3980 }
3981
3982 static void pointer(struct compile_state *state, struct triple *def)
3983 {
3984         if (!is_pointer(def)) {
3985                 error(state, def, "pointer expected");
3986         }
3987 }
3988
3989 static struct triple *int_const(
3990         struct compile_state *state, struct type *type, ulong_t value)
3991 {
3992         struct triple *result;
3993         switch(type->type & TYPE_MASK) {
3994         case TYPE_CHAR:
3995         case TYPE_INT:   case TYPE_UINT:
3996         case TYPE_LONG:  case TYPE_ULONG:
3997                 break;
3998         default:
3999                 internal_error(state, 0, "constant for unkown type");
4000         }
4001         result = triple(state, OP_INTCONST, type, 0, 0);
4002         result->u.cval = value;
4003         return result;
4004 }
4005
4006
4007 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4008         struct triple *expr, struct type *type, ulong_t offset)
4009 {
4010         struct triple *result;
4011         lvalue(state, expr);
4012
4013         result = 0;
4014         if (expr->op == OP_ADECL) {
4015                 error(state, expr, "address of auto variables not supported");
4016         }
4017         else if (expr->op == OP_SDECL) {
4018                 result = triple(state, OP_ADDRCONST, type, expr, 0);
4019                 result->u.cval = offset;
4020         }
4021         else if (expr->op == OP_DEREF) {
4022                 result = triple(state, OP_ADD, type,
4023                         RHS(expr, 0),
4024                         int_const(state, &ulong_type, offset));
4025         }
4026         return result;
4027 }
4028
4029 static struct triple *mk_addr_expr(
4030         struct compile_state *state, struct triple *expr, ulong_t offset)
4031 {
4032         struct type *type;
4033         
4034         type = new_type(
4035                 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4036                 expr->type, 0);
4037
4038         return do_mk_addr_expr(state, expr, type, offset);
4039 }
4040
4041 static struct triple *mk_deref_expr(
4042         struct compile_state *state, struct triple *expr)
4043 {
4044         struct type *base_type;
4045         pointer(state, expr);
4046         base_type = expr->type->left;
4047         if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4048                 error(state, 0, 
4049                         "Only pointer and arithmetic values can be dereferenced");
4050         }
4051         return triple(state, OP_DEREF, base_type, expr, 0);
4052 }
4053
4054 static struct triple *deref_field(
4055         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4056 {
4057         struct triple *result;
4058         struct type *type, *member;
4059         if (!field) {
4060                 internal_error(state, 0, "No field passed to deref_field");
4061         }
4062         result = 0;
4063         type = expr->type;
4064         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4065                 error(state, 0, "request for member %s in something not a struct or union",
4066                         field->name);
4067         }
4068         member = type->left;
4069         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4070                 if (member->left->field_ident == field) {
4071                         member = member->left;
4072                         break;
4073                 }
4074                 member = member->right;
4075         }
4076         if (member->field_ident != field) {
4077                 error(state, 0, "%s is not a member", field->name);
4078         }
4079         if ((type->type & STOR_MASK) == STOR_PERM) {
4080                 /* Do the pointer arithmetic to get a deref the field */
4081                 ulong_t offset;
4082                 offset = field_offset(state, type, field);
4083                 result = do_mk_addr_expr(state, expr, member, offset);
4084                 result = mk_deref_expr(state, result);
4085         }
4086         else {
4087                 /* Find the variable for the field I want. */
4088                 result = triple(state, OP_DOT, 
4089                         field_type(state, type, field), expr, 0);
4090                 result->u.field = field;
4091         }
4092         return result;
4093 }
4094
4095 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4096 {
4097         int op;
4098         if  (!def) {
4099                 return 0;
4100         }
4101         if (!is_stable(state, def)) {
4102                 return def;
4103         }
4104         /* Tranform an array to a pointer to the first element */
4105 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4106         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4107                 struct type *type;
4108                 type = new_type(
4109                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4110                         def->type->left, 0);
4111                 return triple(state, OP_ADDRCONST, type, def, 0);
4112         }
4113         if (is_in_reg(state, def)) {
4114                 op = OP_READ;
4115         } else {
4116                 op = OP_LOAD;
4117         }
4118         return triple(state, op, def->type, def, 0);
4119 }
4120
4121 static void write_compatible(struct compile_state *state,
4122         struct type *dest, struct type *rval)
4123 {
4124         int compatible = 0;
4125         /* Both operands have arithmetic type */
4126         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4127                 compatible = 1;
4128         }
4129         /* One operand is a pointer and the other is a pointer to void */
4130         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4131                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4132                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4133                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4134                 compatible = 1;
4135         }
4136         /* If both types are the same without qualifiers we are good */
4137         else if (equiv_ptrs(dest, rval)) {
4138                 compatible = 1;
4139         }
4140         /* test for struct/union equality  */
4141         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4142                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4143                 (dest->type_ident == rval->type_ident)) {
4144                 compatible = 1;
4145         }
4146         if (!compatible) {
4147                 error(state, 0, "Incompatible types in assignment");
4148         }
4149 }
4150
4151 static struct triple *write_expr(
4152         struct compile_state *state, struct triple *dest, struct triple *rval)
4153 {
4154         struct triple *def;
4155         int op;
4156
4157         def = 0;
4158         if (!rval) {
4159                 internal_error(state, 0, "missing rval");
4160         }
4161
4162         if (rval->op == OP_LIST) {
4163                 internal_error(state, 0, "expression of type OP_LIST?");
4164         }
4165         if (!is_lvalue(state, dest)) {
4166                 internal_error(state, 0, "writing to a non lvalue?");
4167         }
4168
4169         write_compatible(state, dest->type, rval->type);
4170
4171         /* Now figure out which assignment operator to use */
4172         op = -1;
4173         if (is_in_reg(state, dest)) {
4174                 op = OP_WRITE;
4175         } else {
4176                 op = OP_STORE;
4177         }
4178         def = triple(state, op, dest->type, dest, rval);
4179         return def;
4180 }
4181
4182 static struct triple *init_expr(
4183         struct compile_state *state, struct triple *dest, struct triple *rval)
4184 {
4185         struct triple *def;
4186
4187         def = 0;
4188         if (!rval) {
4189                 internal_error(state, 0, "missing rval");
4190         }
4191         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4192                 rval = read_expr(state, rval);
4193                 def = write_expr(state, dest, rval);
4194         }
4195         else {
4196                 /* Fill in the array size if necessary */
4197                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4198                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4199                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4200                                 dest->type->elements = rval->type->elements;
4201                         }
4202                 }
4203                 if (!equiv_types(dest->type, rval->type)) {
4204                         error(state, 0, "Incompatible types in inializer");
4205                 }
4206                 MISC(dest, 0) = rval;
4207         }
4208         return def;
4209 }
4210
4211 struct type *arithmetic_result(
4212         struct compile_state *state, struct triple *left, struct triple *right)
4213 {
4214         struct type *type;
4215         /* Sanity checks to ensure I am working with arithmetic types */
4216         arithmetic(state, left);
4217         arithmetic(state, right);
4218         type = new_type(
4219                 do_arithmetic_conversion(
4220                         left->type->type, 
4221                         right->type->type), 0, 0);
4222         return type;
4223 }
4224
4225 struct type *ptr_arithmetic_result(
4226         struct compile_state *state, struct triple *left, struct triple *right)
4227 {
4228         struct type *type;
4229         /* Sanity checks to ensure I am working with the proper types */
4230         ptr_arithmetic(state, left);
4231         arithmetic(state, right);
4232         if (TYPE_ARITHMETIC(left->type->type) && 
4233                 TYPE_ARITHMETIC(right->type->type)) {
4234                 type = arithmetic_result(state, left, right);
4235         }
4236         else if (TYPE_PTR(left->type->type)) {
4237                 type = left->type;
4238         }
4239         else {
4240                 internal_error(state, 0, "huh?");
4241                 type = 0;
4242         }
4243         return type;
4244 }
4245
4246
4247 /* boolean helper function */
4248
4249 static struct triple *ltrue_expr(struct compile_state *state, 
4250         struct triple *expr)
4251 {
4252         switch(expr->op) {
4253         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4254         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4255         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4256                 /* If the expression is already boolean do nothing */
4257                 break;
4258         default:
4259                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4260                 break;
4261         }
4262         return expr;
4263 }
4264
4265 static struct triple *lfalse_expr(struct compile_state *state, 
4266         struct triple *expr)
4267 {
4268         return triple(state, OP_LFALSE, &int_type, expr, 0);
4269 }
4270
4271 static struct triple *cond_expr(
4272         struct compile_state *state, 
4273         struct triple *test, struct triple *left, struct triple *right)
4274 {
4275         struct triple *def;
4276         struct type *result_type;
4277         unsigned int left_type, right_type;
4278         bool(state, test);
4279         left_type = left->type->type;
4280         right_type = right->type->type;
4281         result_type = 0;
4282         /* Both operands have arithmetic type */
4283         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4284                 result_type = arithmetic_result(state, left, right);
4285         }
4286         /* Both operands have void type */
4287         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4288                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4289                 result_type = &void_type;
4290         }
4291         /* pointers to the same type... */
4292         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4293                 ;
4294         }
4295         /* Both operands are pointers and left is a pointer to void */
4296         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4297                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4298                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4299                 result_type = right->type;
4300         }
4301         /* Both operands are pointers and right is a pointer to void */
4302         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4303                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4304                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4305                 result_type = left->type;
4306         }
4307         if (!result_type) {
4308                 error(state, 0, "Incompatible types in conditional expression");
4309         }
4310         def = new_triple(state, OP_COND, result_type, 3);
4311         def->param[0] = test;
4312         def->param[1] = left;
4313         def->param[2] = right;
4314         return def;
4315 }
4316
4317
4318 static int expr_depth(struct compile_state *state, struct triple *ins)
4319 {
4320         int count;
4321         count = 0;
4322         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4323                 count = 0;
4324         }
4325         else if (ins->op == OP_DEREF) {
4326                 count = expr_depth(state, RHS(ins, 0)) - 1;
4327         }
4328         else if (ins->op == OP_VAL) {
4329                 count = expr_depth(state, RHS(ins, 0)) - 1;
4330         }
4331         else if (ins->op == OP_COMMA) {
4332                 int ldepth, rdepth;
4333                 ldepth = expr_depth(state, RHS(ins, 0));
4334                 rdepth = expr_depth(state, RHS(ins, 1));
4335                 count = (ldepth >= rdepth)? ldepth : rdepth;
4336         }
4337         else if (ins->op == OP_CALL) {
4338                 /* Don't figure the depth of a call just guess it is huge */
4339                 count = 1000;
4340         }
4341         else {
4342                 struct triple **expr;
4343                 expr = triple_rhs(state, ins, 0);
4344                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4345                         if (*expr) {
4346                                 int depth;
4347                                 depth = expr_depth(state, *expr);
4348                                 if (depth > count) {
4349                                         count = depth;
4350                                 }
4351                         }
4352                 }
4353         }
4354         return count + 1;
4355 }
4356
4357 static struct triple *flatten(
4358         struct compile_state *state, struct triple *first, struct triple *ptr);
4359
4360 static struct triple *flatten_generic(
4361         struct compile_state *state, struct triple *first, struct triple *ptr)
4362 {
4363         struct rhs_vector {
4364                 int depth;
4365                 struct triple **ins;
4366         } vector[MAX_RHS];
4367         int i, rhs, lhs;
4368         /* Only operations with just a rhs should come here */
4369         rhs = TRIPLE_RHS(ptr->sizes);
4370         lhs = TRIPLE_LHS(ptr->sizes);
4371         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4372                 internal_error(state, ptr, "unexpected args for: %d %s",
4373                         ptr->op, tops(ptr->op));
4374         }
4375         /* Find the depth of the rhs elements */
4376         for(i = 0; i < rhs; i++) {
4377                 vector[i].ins = &RHS(ptr, i);
4378                 vector[i].depth = expr_depth(state, *vector[i].ins);
4379         }
4380         /* Selection sort the rhs */
4381         for(i = 0; i < rhs; i++) {
4382                 int j, max = i;
4383                 for(j = i + 1; j < rhs; j++ ) {
4384                         if (vector[j].depth > vector[max].depth) {
4385                                 max = j;
4386                         }
4387                 }
4388                 if (max != i) {
4389                         struct rhs_vector tmp;
4390                         tmp = vector[i];
4391                         vector[i] = vector[max];
4392                         vector[max] = tmp;
4393                 }
4394         }
4395         /* Now flatten the rhs elements */
4396         for(i = 0; i < rhs; i++) {
4397                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4398                 use_triple(*vector[i].ins, ptr);
4399         }
4400         
4401         /* Now flatten the lhs elements */
4402         for(i = 0; i < lhs; i++) {
4403                 struct triple **ins = &LHS(ptr, i);
4404                 *ins = flatten(state, first, *ins);
4405                 use_triple(*ins, ptr);
4406         }
4407         return ptr;
4408 }
4409
4410 static struct triple *flatten_land(
4411         struct compile_state *state, struct triple *first, struct triple *ptr)
4412 {
4413         struct triple *left, *right;
4414         struct triple *val, *test, *jmp, *label1, *end;
4415
4416         /* Find the triples */
4417         left = RHS(ptr, 0);
4418         right = RHS(ptr, 1);
4419
4420         /* Generate the needed triples */
4421         end = label(state);
4422
4423         /* Thread the triples together */
4424         val          = flatten(state, first, variable(state, ptr->type));
4425         left         = flatten(state, first, write_expr(state, val, left));
4426         test         = flatten(state, first, 
4427                 lfalse_expr(state, read_expr(state, val)));
4428         jmp          = flatten(state, first, branch(state, end, test));
4429         label1       = flatten(state, first, label(state));
4430         right        = flatten(state, first, write_expr(state, val, right));
4431         TARG(jmp, 0) = flatten(state, first, end); 
4432         
4433         /* Now give the caller something to chew on */
4434         return read_expr(state, val);
4435 }
4436
4437 static struct triple *flatten_lor(
4438         struct compile_state *state, struct triple *first, struct triple *ptr)
4439 {
4440         struct triple *left, *right;
4441         struct triple *val, *jmp, *label1, *end;
4442
4443         /* Find the triples */
4444         left = RHS(ptr, 0);
4445         right = RHS(ptr, 1);
4446
4447         /* Generate the needed triples */
4448         end = label(state);
4449
4450         /* Thread the triples together */
4451         val          = flatten(state, first, variable(state, ptr->type));
4452         left         = flatten(state, first, write_expr(state, val, left));
4453         jmp          = flatten(state, first, branch(state, end, left));
4454         label1       = flatten(state, first, label(state));
4455         right        = flatten(state, first, write_expr(state, val, right));
4456         TARG(jmp, 0) = flatten(state, first, end);
4457        
4458         
4459         /* Now give the caller something to chew on */
4460         return read_expr(state, val);
4461 }
4462
4463 static struct triple *flatten_cond(
4464         struct compile_state *state, struct triple *first, struct triple *ptr)
4465 {
4466         struct triple *test, *left, *right;
4467         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4468
4469         /* Find the triples */
4470         test = RHS(ptr, 0);
4471         left = RHS(ptr, 1);
4472         right = RHS(ptr, 2);
4473
4474         /* Generate the needed triples */
4475         end = label(state);
4476         middle = label(state);
4477
4478         /* Thread the triples together */
4479         val           = flatten(state, first, variable(state, ptr->type));
4480         test          = flatten(state, first, test);
4481         jmp1          = flatten(state, first, branch(state, middle, test));
4482         label1        = flatten(state, first, label(state));
4483         left          = flatten(state, first, left);
4484         mv1           = flatten(state, first, write_expr(state, val, left));
4485         jmp2          = flatten(state, first, branch(state, end, 0));
4486         TARG(jmp1, 0) = flatten(state, first, middle);
4487         right         = flatten(state, first, right);
4488         mv2           = flatten(state, first, write_expr(state, val, right));
4489         TARG(jmp2, 0) = flatten(state, first, end);
4490         
4491         /* Now give the caller something to chew on */
4492         return read_expr(state, val);
4493 }
4494
4495 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4496 {
4497         struct triple *nfunc;
4498         struct triple *nfirst, *ofirst;
4499         struct triple *new, *old;
4500
4501 #if 0
4502         fprintf(stdout, "\n");
4503         loc(stdout, state, 0);
4504         fprintf(stdout, "\n__________ copy_func _________\n");
4505         print_triple(state, ofunc);
4506         fprintf(stdout, "__________ copy_func _________ done\n\n");
4507 #endif
4508
4509         /* Make a new copy of the old function */
4510         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4511         nfirst = 0;
4512         ofirst = old = RHS(ofunc, 0);
4513         do {
4514                 struct triple *new;
4515                 int old_rhs;
4516                 old_rhs = TRIPLE_RHS(old->sizes);
4517                 new = alloc_triple(state, old->op, old->type, old_rhs,
4518                         old->filename, old->line, old->col);
4519                 if (IS_CONST_OP(new->op)) {
4520                         memcpy(&new->u, &old->u, sizeof(new->u));
4521                 }
4522 #warning "WISHLIST find a way to handle SDECL without a special case..."
4523                 /* The problem is that I don't flatten the misc field,
4524                  * so I cannot look the value the misc field should have.
4525                  */
4526                 else if (new->op == OP_SDECL) {
4527                         MISC(new, 0) = MISC(old, 0);
4528                 }
4529                 if (!nfirst) {
4530                         RHS(nfunc, 0) = nfirst = new;
4531                 }
4532                 else {
4533                         insert_triple(state, nfirst, new);
4534                 }
4535                 new->id |= TRIPLE_FLAG_FLATTENED;
4536                 
4537                 /* During the copy remember new as user of old */
4538                 use_triple(old, new);
4539
4540                 /* Populate the return type if present */
4541                 if (old == MISC(ofunc, 0)) {
4542                         MISC(nfunc, 0) = new;
4543                 }
4544                 old = old->next;
4545         } while(old != ofirst);
4546
4547         /* Make a second pass to fix up any unresolved references */
4548         old = ofirst;
4549         new = nfirst;
4550         do {
4551                 struct triple **oexpr, **nexpr;
4552                 int count, i;
4553                 /* Lookup where the copy is, to join pointers */
4554                 count = TRIPLE_SIZE(old->sizes);
4555                 for(i = 0; i < count; i++) {
4556                         oexpr = &old->param[i];
4557                         nexpr = &new->param[i];
4558                         if (!*nexpr && *oexpr && (*oexpr)->use) {
4559                                 *nexpr = (*oexpr)->use->member;
4560                                 if (*nexpr == old) {
4561                                         internal_error(state, 0, "new == old?");
4562                                 }
4563                                 use_triple(*nexpr, new);
4564                         }
4565                         if (!*nexpr && *oexpr) {
4566                                 internal_error(state, 0, "Could not copy %d\n", i);
4567                         }
4568                 }
4569                 old = old->next;
4570                 new = new->next;
4571         } while((old != ofirst) && (new != nfirst));
4572         
4573         /* Make a third pass to cleanup the extra useses */
4574         old = ofirst;
4575         new = nfirst;
4576         do {
4577                 unuse_triple(old, new);
4578                 old = old->next;
4579                 new = new->next;
4580         } while ((old != ofirst) && (new != nfirst));
4581         return nfunc;
4582 }
4583
4584 static struct triple *flatten_call(
4585         struct compile_state *state, struct triple *first, struct triple *ptr)
4586 {
4587         /* Inline the function call */
4588         struct type *ptype;
4589         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4590         struct triple *end, *nend;
4591         int pvals, i;
4592
4593         /* Find the triples */
4594         ofunc = MISC(ptr, 0);
4595         if (ofunc->op != OP_LIST) {
4596                 internal_error(state, 0, "improper function");
4597         }
4598         nfunc = copy_func(state, ofunc);
4599         nfirst = RHS(nfunc, 0)->next;
4600         /* Prepend the parameter reading into the new function list */
4601         ptype = nfunc->type->right;
4602         param = RHS(nfunc, 0)->next;
4603         pvals = TRIPLE_RHS(ptr->sizes);
4604         for(i = 0; i < pvals; i++) {
4605                 struct type *atype;
4606                 struct triple *arg;
4607                 atype = ptype;
4608                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4609                         atype = ptype->left;
4610                 }
4611                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4612                         param = param->next;
4613                 }
4614                 arg = RHS(ptr, i);
4615                 flatten(state, nfirst, write_expr(state, param, arg));
4616                 ptype = ptype->right;
4617                 param = param->next;
4618         }
4619         result = 0;
4620         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4621                 result = read_expr(state, MISC(nfunc,0));
4622         }
4623 #if 0
4624         fprintf(stdout, "\n");
4625         loc(stdout, state, 0);
4626         fprintf(stdout, "\n__________ flatten_call _________\n");
4627         print_triple(state, nfunc);
4628         fprintf(stdout, "__________ flatten_call _________ done\n\n");
4629 #endif
4630
4631         /* Get rid of the extra triples */
4632         nfirst = RHS(nfunc, 0)->next;
4633         free_triple(state, RHS(nfunc, 0));
4634         RHS(nfunc, 0) = 0;
4635         free_triple(state, nfunc);
4636
4637         /* Append the new function list onto the return list */
4638         end = first->prev;
4639         nend = nfirst->prev;
4640         end->next    = nfirst;
4641         nfirst->prev = end;
4642         nend->next   = first;
4643         first->prev  = nend;
4644
4645         return result;
4646 }
4647
4648 static struct triple *flatten(
4649         struct compile_state *state, struct triple *first, struct triple *ptr)
4650 {
4651         struct triple *orig_ptr;
4652         if (!ptr)
4653                 return 0;
4654         do {
4655                 orig_ptr = ptr;
4656                 /* Only flatten triples once */
4657                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4658                         return ptr;
4659                 }
4660                 switch(ptr->op) {
4661                 case OP_WRITE:
4662                 case OP_STORE:
4663                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4664                         LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4665                         use_triple(LHS(ptr, 0), ptr);
4666                         use_triple(RHS(ptr, 0), ptr);
4667                         break;
4668                 case OP_COMMA:
4669                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4670                         ptr = RHS(ptr, 1);
4671                         break;
4672                 case OP_VAL:
4673                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4674                         return MISC(ptr, 0);
4675                         break;
4676                 case OP_LAND:
4677                         ptr = flatten_land(state, first, ptr);
4678                         break;
4679                 case OP_LOR:
4680                         ptr = flatten_lor(state, first, ptr);
4681                         break;
4682                 case OP_COND:
4683                         ptr = flatten_cond(state, first, ptr);
4684                         break;
4685                 case OP_CALL:
4686                         ptr = flatten_call(state, first, ptr);
4687                         break;
4688                 case OP_READ:
4689                 case OP_LOAD:
4690                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4691                         use_triple(RHS(ptr, 0), ptr);
4692                         break;
4693                 case OP_BRANCH:
4694                         use_triple(TARG(ptr, 0), ptr);
4695                         if (TRIPLE_RHS(ptr->sizes)) {
4696                                 use_triple(RHS(ptr, 0), ptr);
4697                                 if (ptr->next != ptr) {
4698                                         use_triple(ptr->next, ptr);
4699                                 }
4700                         }
4701                         break;
4702                 case OP_BLOBCONST:
4703                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4704                         use_triple(MISC(ptr, 0), ptr);
4705                         break;
4706                 case OP_DEREF:
4707                         /* Since OP_DEREF is just a marker delete it when I flatten it */
4708                         ptr = RHS(ptr, 0);
4709                         RHS(orig_ptr, 0) = 0;
4710                         free_triple(state, orig_ptr);
4711                         break;
4712                 case OP_DOT:
4713                 {
4714                         struct triple *base;
4715                         base = RHS(ptr, 0);
4716                         base = flatten(state, first, base);
4717                         if (base->op == OP_VAL_VEC) {
4718                                 ptr = struct_field(state, base, ptr->u.field);
4719                         }
4720                         break;
4721                 }
4722                 case OP_SDECL:
4723                 case OP_ADECL:
4724                         break;
4725                 default:
4726                         /* Flatten the easy cases we don't override */
4727                         ptr = flatten_generic(state, first, ptr);
4728                         break;
4729                 }
4730         } while(ptr && (ptr != orig_ptr));
4731         if (ptr) {
4732                 insert_triple(state, first, ptr);
4733                 ptr->id |= TRIPLE_FLAG_FLATTENED;
4734         }
4735         return ptr;
4736 }
4737
4738 static void release_expr(struct compile_state *state, struct triple *expr)
4739 {
4740         struct triple *head;
4741         head = label(state);
4742         flatten(state, head, expr);
4743         while(head->next != head) {
4744                 release_triple(state, head->next);
4745         }
4746         free_triple(state, head);
4747 }
4748
4749 static int replace_rhs_use(struct compile_state *state,
4750         struct triple *orig, struct triple *new, struct triple *use)
4751 {
4752         struct triple **expr;
4753         int found;
4754         found = 0;
4755         expr = triple_rhs(state, use, 0);
4756         for(;expr; expr = triple_rhs(state, use, expr)) {
4757                 if (*expr == orig) {
4758                         *expr = new;
4759                         found = 1;
4760                 }
4761         }
4762         if (found) {
4763                 unuse_triple(orig, use);
4764                 use_triple(new, use);
4765         }
4766         return found;
4767 }
4768
4769 static int replace_lhs_use(struct compile_state *state,
4770         struct triple *orig, struct triple *new, struct triple *use)
4771 {
4772         struct triple **expr;
4773         int found;
4774         found = 0;
4775         expr = triple_lhs(state, use, 0);
4776         for(;expr; expr = triple_lhs(state, use, expr)) {
4777                 if (*expr == orig) {
4778                         *expr = new;
4779                         found = 1;
4780                 }
4781         }
4782         if (found) {
4783                 unuse_triple(orig, use);
4784                 use_triple(new, use);
4785         }
4786         return found;
4787 }
4788
4789 static void propogate_use(struct compile_state *state,
4790         struct triple *orig, struct triple *new)
4791 {
4792         struct triple_set *user, *next;
4793         for(user = orig->use; user; user = next) {
4794                 struct triple *use;
4795                 int found;
4796                 next = user->next;
4797                 use = user->member;
4798                 found = 0;
4799                 found |= replace_rhs_use(state, orig, new, use);
4800                 found |= replace_lhs_use(state, orig, new, use);
4801                 if (!found) {
4802                         internal_error(state, use, "use without use");
4803                 }
4804         }
4805         if (orig->use) {
4806                 internal_error(state, orig, "used after propogate_use");
4807         }
4808 }
4809
4810 /*
4811  * Code generators
4812  * ===========================
4813  */
4814
4815 static struct triple *mk_add_expr(
4816         struct compile_state *state, struct triple *left, struct triple *right)
4817 {
4818         struct type *result_type;
4819         /* Put pointer operands on the left */
4820         if (is_pointer(right)) {
4821                 struct triple *tmp;
4822                 tmp = left;
4823                 left = right;
4824                 right = tmp;
4825         }
4826         result_type = ptr_arithmetic_result(state, left, right);
4827         left  = read_expr(state, left);
4828         right = read_expr(state, right);
4829         if (is_pointer(left)) {
4830                 right = triple(state, 
4831                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
4832                         &ulong_type, 
4833                         right, 
4834                         int_const(state, &ulong_type, 
4835                                 size_of(state, left->type->left)));
4836         }
4837         return triple(state, OP_ADD, result_type, left, right);
4838 }
4839
4840 static struct triple *mk_sub_expr(
4841         struct compile_state *state, struct triple *left, struct triple *right)
4842 {
4843         struct type *result_type;
4844         result_type = ptr_arithmetic_result(state, left, right);
4845         left  = read_expr(state, left);
4846         right = read_expr(state, right);
4847         if (is_pointer(left)) {
4848                 right = triple(state, 
4849                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
4850                         &ulong_type, 
4851                         right, 
4852                         int_const(state, &ulong_type, 
4853                                 size_of(state, left->type->left)));
4854         }
4855         return triple(state, OP_SUB, result_type, left, right);
4856 }
4857
4858 static struct triple *mk_pre_inc_expr(
4859         struct compile_state *state, struct triple *def)
4860 {
4861         struct triple *val;
4862         lvalue(state, def);
4863         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
4864         return triple(state, OP_VAL, def->type,
4865                 write_expr(state, def, val),
4866                 val);
4867 }
4868
4869 static struct triple *mk_pre_dec_expr(
4870         struct compile_state *state, struct triple *def)
4871 {
4872         struct triple *val;
4873         lvalue(state, def);
4874         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
4875         return triple(state, OP_VAL, def->type,
4876                 write_expr(state, def, val),
4877                 val);
4878 }
4879
4880 static struct triple *mk_post_inc_expr(
4881         struct compile_state *state, struct triple *def)
4882 {
4883         struct triple *val;
4884         lvalue(state, def);
4885         val = read_expr(state, def);
4886         return triple(state, OP_VAL, def->type,
4887                 write_expr(state, def,
4888                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
4889                 , val);
4890 }
4891
4892 static struct triple *mk_post_dec_expr(
4893         struct compile_state *state, struct triple *def)
4894 {
4895         struct triple *val;
4896         lvalue(state, def);
4897         val = read_expr(state, def);
4898         return triple(state, OP_VAL, def->type, 
4899                 write_expr(state, def,
4900                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
4901                 , val);
4902 }
4903
4904 static struct triple *mk_subscript_expr(
4905         struct compile_state *state, struct triple *left, struct triple *right)
4906 {
4907         left  = read_expr(state, left);
4908         right = read_expr(state, right);
4909         if (!is_pointer(left) && !is_pointer(right)) {
4910                 error(state, left, "subscripted value is not a pointer");
4911         }
4912         return mk_deref_expr(state, mk_add_expr(state, left, right));
4913 }
4914
4915 /*
4916  * Compile time evaluation
4917  * ===========================
4918  */
4919 static int is_const(struct triple *ins)
4920 {
4921         return IS_CONST_OP(ins->op);
4922 }
4923
4924 static int constants_equal(struct compile_state *state, 
4925         struct triple *left, struct triple *right)
4926 {
4927         int equal;
4928         if (!is_const(left) || !is_const(right)) {
4929                 equal = 0;
4930         }
4931         else if (left->op != right->op) {
4932                 equal = 0;
4933         }
4934         else if (!equiv_types(left->type, right->type)) {
4935                 equal = 0;
4936         }
4937         else {
4938                 equal = 0;
4939                 switch(left->op) {
4940                 case OP_INTCONST:
4941                         if (left->u.cval == right->u.cval) {
4942                                 equal = 1;
4943                         }
4944                         break;
4945                 case OP_BLOBCONST:
4946                 {
4947                         size_t lsize, rsize;
4948                         lsize = size_of(state, left->type);
4949                         rsize = size_of(state, right->type);
4950                         if (lsize != rsize) {
4951                                 break;
4952                         }
4953                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
4954                                 equal = 1;
4955                         }
4956                         break;
4957                 }
4958                 case OP_ADDRCONST:
4959                         if ((RHS(left, 0) == RHS(right, 0)) &&
4960                                 (left->u.cval == right->u.cval)) {
4961                                 equal = 1;
4962                         }
4963                         break;
4964                 default:
4965                         internal_error(state, left, "uknown constant type");
4966                         break;
4967                 }
4968         }
4969         return equal;
4970 }
4971
4972 static int is_zero(struct triple *ins)
4973 {
4974         return is_const(ins) && (ins->u.cval == 0);
4975 }
4976
4977 static int is_one(struct triple *ins)
4978 {
4979         return is_const(ins) && (ins->u.cval == 1);
4980 }
4981
4982 static long_t bsr(ulong_t value)
4983 {
4984         int i;
4985         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
4986                 ulong_t mask;
4987                 mask = 1;
4988                 mask <<= i;
4989                 if (value & mask) {
4990                         return i;
4991                 }
4992         }
4993         return -1;
4994 }
4995
4996 static long_t bsf(ulong_t value)
4997 {
4998         int i;
4999         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5000                 ulong_t mask;
5001                 mask = 1;
5002                 mask <<= 1;
5003                 if (value & mask) {
5004                         return i;
5005                 }
5006         }
5007         return -1;
5008 }
5009
5010 static long_t log2(ulong_t value)
5011 {
5012         return bsr(value);
5013 }
5014
5015 static long_t tlog2(struct triple *ins)
5016 {
5017         return log2(ins->u.cval);
5018 }
5019
5020 static int is_pow2(struct triple *ins)
5021 {
5022         ulong_t value, mask;
5023         long_t log;
5024         if (!is_const(ins)) {
5025                 return 0;
5026         }
5027         value = ins->u.cval;
5028         log = log2(value);
5029         if (log == -1) {
5030                 return 0;
5031         }
5032         mask = 1;
5033         mask <<= log;
5034         return  ((value & mask) == value);
5035 }
5036
5037 static ulong_t read_const(struct compile_state *state,
5038         struct triple *ins, struct triple **expr)
5039 {
5040         struct triple *rhs;
5041         rhs = *expr;
5042         switch(rhs->type->type &TYPE_MASK) {
5043         case TYPE_CHAR:   
5044         case TYPE_SHORT:
5045         case TYPE_INT:
5046         case TYPE_LONG:
5047         case TYPE_UCHAR:   
5048         case TYPE_USHORT:  
5049         case TYPE_UINT:
5050         case TYPE_ULONG:
5051         case TYPE_POINTER:
5052                 break;
5053         default:
5054                 internal_error(state, rhs, "bad type to read_const\n");
5055                 break;
5056         }
5057         return rhs->u.cval;
5058 }
5059
5060 static long_t read_sconst(struct triple *ins, struct triple **expr)
5061 {
5062         struct triple *rhs;
5063         rhs = *expr;
5064         return (long_t)(rhs->u.cval);
5065 }
5066
5067 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5068 {
5069         struct triple **expr;
5070         expr = triple_rhs(state, ins, 0);
5071         for(;expr;expr = triple_rhs(state, ins, expr)) {
5072                 if (*expr) {
5073                         unuse_triple(*expr, ins);
5074                         *expr = 0;
5075                 }
5076         }
5077 }
5078
5079 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5080 {
5081         struct triple **expr;
5082         expr = triple_lhs(state, ins, 0);
5083         for(;expr;expr = triple_lhs(state, ins, expr)) {
5084                 unuse_triple(*expr, ins);
5085                 *expr = 0;
5086         }
5087 }
5088
5089 static void check_lhs(struct compile_state *state, struct triple *ins)
5090 {
5091         struct triple **expr;
5092         expr = triple_lhs(state, ins, 0);
5093         for(;expr;expr = triple_lhs(state, ins, expr)) {
5094                 internal_error(state, ins, "unexpected lhs");
5095         }
5096         
5097 }
5098 static void check_targ(struct compile_state *state, struct triple *ins)
5099 {
5100         struct triple **expr;
5101         expr = triple_targ(state, ins, 0);
5102         for(;expr;expr = triple_targ(state, ins, expr)) {
5103                 internal_error(state, ins, "unexpected targ");
5104         }
5105 }
5106
5107 static void wipe_ins(struct compile_state *state, struct triple *ins)
5108 {
5109         /* Becareful which instructions you replace the wiped
5110          * instruction with, as there are not enough slots
5111          * in all instructions to hold all others.
5112          */
5113         check_targ(state, ins);
5114         unuse_rhs(state, ins);
5115         unuse_lhs(state, ins);
5116 }
5117
5118 static void mkcopy(struct compile_state *state, 
5119         struct triple *ins, struct triple *rhs)
5120 {
5121         wipe_ins(state, ins);
5122         ins->op = OP_COPY;
5123         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5124         RHS(ins, 0) = rhs;
5125         use_triple(RHS(ins, 0), ins);
5126 }
5127
5128 static void mkconst(struct compile_state *state, 
5129         struct triple *ins, ulong_t value)
5130 {
5131         if (!is_integral(ins) && !is_pointer(ins)) {
5132                 internal_error(state, ins, "unknown type to make constant\n");
5133         }
5134         wipe_ins(state, ins);
5135         ins->op = OP_INTCONST;
5136         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5137         ins->u.cval = value;
5138 }
5139
5140 static void mkaddr_const(struct compile_state *state,
5141         struct triple *ins, struct triple *sdecl, ulong_t value)
5142 {
5143         wipe_ins(state, ins);
5144         ins->op = OP_ADDRCONST;
5145         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5146         RHS(ins, 0) = sdecl;
5147         ins->u.cval = value;
5148         use_triple(sdecl, ins);
5149 }
5150
5151 /* Transform multicomponent variables into simple register variables */
5152 static void flatten_structures(struct compile_state *state)
5153 {
5154         struct triple *ins, *first;
5155         first = RHS(state->main_function, 0);
5156         ins = first;
5157         /* Pass one expand structure values into valvecs.
5158          */
5159         ins = first;
5160         do {
5161                 struct triple *next;
5162                 next = ins->next;
5163                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5164                         if (ins->op == OP_VAL_VEC) {
5165                                 /* Do nothing */
5166                         }
5167                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5168                                 struct triple *def, **vector;
5169                                 struct type *tptr;
5170                                 int op;
5171                                 ulong_t i;
5172
5173                                 op = ins->op;
5174                                 def = RHS(ins, 0);
5175                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5176                                         ins->filename, ins->line, ins->col);
5177
5178                                 vector = &RHS(next, 0);
5179                                 tptr = next->type->left;
5180                                 for(i = 0; i < next->type->elements; i++) {
5181                                         struct triple *sfield;
5182                                         struct type *mtype;
5183                                         mtype = tptr;
5184                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5185                                                 mtype = mtype->left;
5186                                         }
5187                                         sfield = deref_field(state, def, mtype->field_ident);
5188                                         
5189                                         vector[i] = triple(
5190                                                 state, op, mtype, sfield, 0);
5191                                         vector[i]->filename = next->filename;
5192                                         vector[i]->line = next->line;
5193                                         vector[i]->col = next->col;
5194                                         tptr = tptr->right;
5195                                 }
5196                                 propogate_use(state, ins, next);
5197                                 flatten(state, ins, next);
5198                                 free_triple(state, ins);
5199                         }
5200                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5201                                 struct triple *src, *dst, **vector;
5202                                 struct type *tptr;
5203                                 int op;
5204                                 ulong_t i;
5205
5206                                 op = ins->op;
5207                                 src = RHS(ins, 0);
5208                                 dst = LHS(ins, 0);
5209                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1,
5210                                         ins->filename, ins->line, ins->col);
5211                                 
5212                                 vector = &RHS(next, 0);
5213                                 tptr = next->type->left;
5214                                 for(i = 0; i < ins->type->elements; i++) {
5215                                         struct triple *dfield, *sfield;
5216                                         struct type *mtype;
5217                                         mtype = tptr;
5218                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5219                                                 mtype = mtype->left;
5220                                         }
5221                                         sfield = deref_field(state, src, mtype->field_ident);
5222                                         dfield = deref_field(state, dst, mtype->field_ident);
5223                                         vector[i] = triple(
5224                                                 state, op, mtype, dfield, sfield);
5225                                         vector[i]->filename = next->filename;
5226                                         vector[i]->line = next->line;
5227                                         vector[i]->col = next->col;
5228                                         tptr = tptr->right;
5229                                 }
5230                                 propogate_use(state, ins, next);
5231                                 flatten(state, ins, next);
5232                                 free_triple(state, ins);
5233                         }
5234                 }
5235                 ins = next;
5236         } while(ins != first);
5237         /* Pass two flatten the valvecs.
5238          */
5239         ins = first;
5240         do {
5241                 struct triple *next;
5242                 next = ins->next;
5243                 if (ins->op == OP_VAL_VEC) {
5244                         release_triple(state, ins);
5245                 } 
5246                 ins = next;
5247         } while(ins != first);
5248         /* Pass three verify the state and set ->id to 0.
5249          */
5250         ins = first;
5251         do {
5252                 ins->id = 0;
5253                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5254                         internal_error(state, 0, "STRUCT_TYPE remains?");
5255                 }
5256                 if (ins->op == OP_DOT) {
5257                         internal_error(state, 0, "OP_DOT remains?");
5258                 }
5259                 if (ins->op == OP_VAL_VEC) {
5260                         internal_error(state, 0, "OP_VAL_VEC remains?");
5261                 }
5262                 ins = ins->next;
5263         } while(ins != first);
5264 }
5265
5266 /* For those operations that cannot be simplified */
5267 static void simplify_noop(struct compile_state *state, struct triple *ins)
5268 {
5269         return;
5270 }
5271
5272 static void simplify_smul(struct compile_state *state, struct triple *ins)
5273 {
5274         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5275                 struct triple *tmp;
5276                 tmp = RHS(ins, 0);
5277                 RHS(ins, 0) = RHS(ins, 1);
5278                 RHS(ins, 1) = tmp;
5279         }
5280         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5281                 long_t left, right;
5282                 left  = read_sconst(ins, &RHS(ins, 0));
5283                 right = read_sconst(ins, &RHS(ins, 1));
5284                 mkconst(state, ins, left * right);
5285         }
5286         else if (is_zero(RHS(ins, 1))) {
5287                 mkconst(state, ins, 0);
5288         }
5289         else if (is_one(RHS(ins, 1))) {
5290                 mkcopy(state, ins, RHS(ins, 0));
5291         }
5292         else if (is_pow2(RHS(ins, 1))) {
5293                 struct triple *val;
5294                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5295                 ins->op = OP_SL;
5296                 insert_triple(state, ins, val);
5297                 unuse_triple(RHS(ins, 1), ins);
5298                 use_triple(val, ins);
5299                 RHS(ins, 1) = val;
5300         }
5301 }
5302
5303 static void simplify_umul(struct compile_state *state, struct triple *ins)
5304 {
5305         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5306                 struct triple *tmp;
5307                 tmp = RHS(ins, 0);
5308                 RHS(ins, 0) = RHS(ins, 1);
5309                 RHS(ins, 1) = tmp;
5310         }
5311         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5312                 ulong_t left, right;
5313                 left  = read_const(state, ins, &RHS(ins, 0));
5314                 right = read_const(state, ins, &RHS(ins, 1));
5315                 mkconst(state, ins, left * right);
5316         }
5317         else if (is_zero(RHS(ins, 1))) {
5318                 mkconst(state, ins, 0);
5319         }
5320         else if (is_one(RHS(ins, 1))) {
5321                 mkcopy(state, ins, RHS(ins, 0));
5322         }
5323         else if (is_pow2(RHS(ins, 1))) {
5324                 struct triple *val;
5325                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5326                 ins->op = OP_SL;
5327                 insert_triple(state, ins, val);
5328                 unuse_triple(RHS(ins, 1), ins);
5329                 use_triple(val, ins);
5330                 RHS(ins, 1) = val;
5331         }
5332 }
5333
5334 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5335 {
5336         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5337                 long_t left, right;
5338                 left  = read_sconst(ins, &RHS(ins, 0));
5339                 right = read_sconst(ins, &RHS(ins, 1));
5340                 mkconst(state, ins, left / right);
5341         }
5342         else if (is_zero(RHS(ins, 0))) {
5343                 mkconst(state, ins, 0);
5344         }
5345         else if (is_zero(RHS(ins, 1))) {
5346                 error(state, ins, "division by zero");
5347         }
5348         else if (is_one(RHS(ins, 1))) {
5349                 mkcopy(state, ins, RHS(ins, 0));
5350         }
5351         else if (is_pow2(RHS(ins, 1))) {
5352                 struct triple *val;
5353                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5354                 ins->op = OP_SSR;
5355                 insert_triple(state, ins, val);
5356                 unuse_triple(RHS(ins, 1), ins);
5357                 use_triple(val, ins);
5358                 RHS(ins, 1) = val;
5359         }
5360 }
5361
5362 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5363 {
5364         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5365                 ulong_t left, right;
5366                 left  = read_const(state, ins, &RHS(ins, 0));
5367                 right = read_const(state, ins, &RHS(ins, 1));
5368                 mkconst(state, ins, left / right);
5369         }
5370         else if (is_zero(RHS(ins, 0))) {
5371                 mkconst(state, ins, 0);
5372         }
5373         else if (is_zero(RHS(ins, 1))) {
5374                 error(state, ins, "division by zero");
5375         }
5376         else if (is_one(RHS(ins, 1))) {
5377                 mkcopy(state, ins, RHS(ins, 0));
5378         }
5379         else if (is_pow2(RHS(ins, 1))) {
5380                 struct triple *val;
5381                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5382                 ins->op = OP_USR;
5383                 insert_triple(state, ins, val);
5384                 unuse_triple(RHS(ins, 1), ins);
5385                 use_triple(val, ins);
5386                 RHS(ins, 1) = val;
5387         }
5388 }
5389
5390 static void simplify_smod(struct compile_state *state, struct triple *ins)
5391 {
5392         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5393                 long_t left, right;
5394                 left  = read_const(state, ins, &RHS(ins, 0));
5395                 right = read_const(state, ins, &RHS(ins, 1));
5396                 mkconst(state, ins, left % right);
5397         }
5398         else if (is_zero(RHS(ins, 0))) {
5399                 mkconst(state, ins, 0);
5400         }
5401         else if (is_zero(RHS(ins, 1))) {
5402                 error(state, ins, "division by zero");
5403         }
5404         else if (is_one(RHS(ins, 1))) {
5405                 mkconst(state, ins, 0);
5406         }
5407         else if (is_pow2(RHS(ins, 1))) {
5408                 struct triple *val;
5409                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5410                 ins->op = OP_AND;
5411                 insert_triple(state, ins, val);
5412                 unuse_triple(RHS(ins, 1), ins);
5413                 use_triple(val, ins);
5414                 RHS(ins, 1) = val;
5415         }
5416 }
5417 static void simplify_umod(struct compile_state *state, struct triple *ins)
5418 {
5419         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5420                 ulong_t left, right;
5421                 left  = read_const(state, ins, &RHS(ins, 0));
5422                 right = read_const(state, ins, &RHS(ins, 1));
5423                 mkconst(state, ins, left % right);
5424         }
5425         else if (is_zero(RHS(ins, 0))) {
5426                 mkconst(state, ins, 0);
5427         }
5428         else if (is_zero(RHS(ins, 1))) {
5429                 error(state, ins, "division by zero");
5430         }
5431         else if (is_one(RHS(ins, 1))) {
5432                 mkconst(state, ins, 0);
5433         }
5434         else if (is_pow2(RHS(ins, 1))) {
5435                 struct triple *val;
5436                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5437                 ins->op = OP_AND;
5438                 insert_triple(state, ins, val);
5439                 unuse_triple(RHS(ins, 1), ins);
5440                 use_triple(val, ins);
5441                 RHS(ins, 1) = val;
5442         }
5443 }
5444
5445 static void simplify_add(struct compile_state *state, struct triple *ins)
5446 {
5447         /* start with the pointer on the left */
5448         if (is_pointer(RHS(ins, 1))) {
5449                 struct triple *tmp;
5450                 tmp = RHS(ins, 0);
5451                 RHS(ins, 0) = RHS(ins, 1);
5452                 RHS(ins, 1) = tmp;
5453         }
5454         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5455                 if (!is_pointer(RHS(ins, 0))) {
5456                         ulong_t left, right;
5457                         left  = read_const(state, ins, &RHS(ins, 0));
5458                         right = read_const(state, ins, &RHS(ins, 1));
5459                         mkconst(state, ins, left + right);
5460                 }
5461                 else /* op == OP_ADDRCONST */ {
5462                         struct triple *sdecl;
5463                         ulong_t left, right;
5464                         sdecl = RHS(RHS(ins, 0), 0);
5465                         left  = RHS(ins, 0)->u.cval;
5466                         right = RHS(ins, 1)->u.cval;
5467                         mkaddr_const(state, ins, sdecl, left + right);
5468                 }
5469         }
5470         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5471                 struct triple *tmp;
5472                 tmp = RHS(ins, 1);
5473                 RHS(ins, 1) = RHS(ins, 0);
5474                 RHS(ins, 0) = tmp;
5475         }
5476 }
5477
5478 static void simplify_sub(struct compile_state *state, struct triple *ins)
5479 {
5480         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5481                 if (!is_pointer(RHS(ins, 0))) {
5482                         ulong_t left, right;
5483                         left  = read_const(state, ins, &RHS(ins, 0));
5484                         right = read_const(state, ins, &RHS(ins, 1));
5485                         mkconst(state, ins, left - right);
5486                 }
5487                 else /* op == OP_ADDRCONST */ {
5488                         struct triple *sdecl;
5489                         ulong_t left, right;
5490                         sdecl = RHS(RHS(ins, 0), 0);
5491                         left  = RHS(ins, 0)->u.cval;
5492                         right = RHS(ins, 1)->u.cval;
5493                         mkaddr_const(state, ins, sdecl, left - right);
5494                 }
5495         }
5496 }
5497
5498 static void simplify_sl(struct compile_state *state, struct triple *ins)
5499 {
5500         if (is_const(RHS(ins, 1))) {
5501                 ulong_t right;
5502                 right = read_const(state, ins, &RHS(ins, 1));
5503                 if (right >= (size_of(state, ins->type)*8)) {
5504                         warning(state, ins, "left shift count >= width of type");
5505                 }
5506         }
5507         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5508                 ulong_t left, right;
5509                 left  = read_const(state, ins, &RHS(ins, 0));
5510                 right = read_const(state, ins, &RHS(ins, 1));
5511                 mkconst(state, ins,  left << right);
5512         }
5513 }
5514
5515 static void simplify_usr(struct compile_state *state, struct triple *ins)
5516 {
5517         if (is_const(RHS(ins, 1))) {
5518                 ulong_t right;
5519                 right = read_const(state, ins, &RHS(ins, 1));
5520                 if (right >= (size_of(state, ins->type)*8)) {
5521                         warning(state, ins, "right shift count >= width of type");
5522                 }
5523         }
5524         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5525                 ulong_t left, right;
5526                 left  = read_const(state, ins, &RHS(ins, 0));
5527                 right = read_const(state, ins, &RHS(ins, 1));
5528                 mkconst(state, ins, left >> right);
5529         }
5530 }
5531
5532 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5533 {
5534         if (is_const(RHS(ins, 1))) {
5535                 ulong_t right;
5536                 right = read_const(state, ins, &RHS(ins, 1));
5537                 if (right >= (size_of(state, ins->type)*8)) {
5538                         warning(state, ins, "right shift count >= width of type");
5539                 }
5540         }
5541         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5542                 long_t left, right;
5543                 left  = read_sconst(ins, &RHS(ins, 0));
5544                 right = read_sconst(ins, &RHS(ins, 1));
5545                 mkconst(state, ins, left >> right);
5546         }
5547 }
5548
5549 static void simplify_and(struct compile_state *state, struct triple *ins)
5550 {
5551         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5552                 ulong_t left, right;
5553                 left  = read_const(state, ins, &RHS(ins, 0));
5554                 right = read_const(state, ins, &RHS(ins, 1));
5555                 mkconst(state, ins, left & right);
5556         }
5557 }
5558
5559 static void simplify_or(struct compile_state *state, struct triple *ins)
5560 {
5561         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5562                 ulong_t left, right;
5563                 left  = read_const(state, ins, &RHS(ins, 0));
5564                 right = read_const(state, ins, &RHS(ins, 1));
5565                 mkconst(state, ins, left | right);
5566         }
5567 }
5568
5569 static void simplify_xor(struct compile_state *state, struct triple *ins)
5570 {
5571         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5572                 ulong_t left, right;
5573                 left  = read_const(state, ins, &RHS(ins, 0));
5574                 right = read_const(state, ins, &RHS(ins, 1));
5575                 mkconst(state, ins, left ^ right);
5576         }
5577 }
5578
5579 static void simplify_pos(struct compile_state *state, struct triple *ins)
5580 {
5581         if (is_const(RHS(ins, 0))) {
5582                 mkconst(state, ins, RHS(ins, 0)->u.cval);
5583         }
5584         else {
5585                 mkcopy(state, ins, RHS(ins, 0));
5586         }
5587 }
5588
5589 static void simplify_neg(struct compile_state *state, struct triple *ins)
5590 {
5591         if (is_const(RHS(ins, 0))) {
5592                 ulong_t left;
5593                 left = read_const(state, ins, &RHS(ins, 0));
5594                 mkconst(state, ins, -left);
5595         }
5596         else if (RHS(ins, 0)->op == OP_NEG) {
5597                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5598         }
5599 }
5600
5601 static void simplify_invert(struct compile_state *state, struct triple *ins)
5602 {
5603         if (is_const(RHS(ins, 0))) {
5604                 ulong_t left;
5605                 left = read_const(state, ins, &RHS(ins, 0));
5606                 mkconst(state, ins, ~left);
5607         }
5608 }
5609
5610 static void simplify_eq(struct compile_state *state, struct triple *ins)
5611 {
5612         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5613                 ulong_t left, right;
5614                 left  = read_const(state, ins, &RHS(ins, 0));
5615                 right = read_const(state, ins, &RHS(ins, 1));
5616                 mkconst(state, ins, left == right);
5617         }
5618         else if (RHS(ins, 0) == RHS(ins, 1)) {
5619                 mkconst(state, ins, 1);
5620         }
5621 }
5622
5623 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5624 {
5625         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5626                 ulong_t left, right;
5627                 left  = read_const(state, ins, &RHS(ins, 0));
5628                 right = read_const(state, ins, &RHS(ins, 1));
5629                 mkconst(state, ins, left != right);
5630         }
5631         else if (RHS(ins, 0) == RHS(ins, 1)) {
5632                 mkconst(state, ins, 0);
5633         }
5634 }
5635
5636 static void simplify_sless(struct compile_state *state, struct triple *ins)
5637 {
5638         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5639                 long_t left, right;
5640                 left  = read_sconst(ins, &RHS(ins, 0));
5641                 right = read_sconst(ins, &RHS(ins, 1));
5642                 mkconst(state, ins, left < right);
5643         }
5644         else if (RHS(ins, 0) == RHS(ins, 1)) {
5645                 mkconst(state, ins, 0);
5646         }
5647 }
5648
5649 static void simplify_uless(struct compile_state *state, struct triple *ins)
5650 {
5651         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5652                 ulong_t left, right;
5653                 left  = read_const(state, ins, &RHS(ins, 0));
5654                 right = read_const(state, ins, &RHS(ins, 1));
5655                 mkconst(state, ins, left < right);
5656         }
5657         else if (is_zero(RHS(ins, 0))) {
5658                 mkconst(state, ins, 1);
5659         }
5660         else if (RHS(ins, 0) == RHS(ins, 1)) {
5661                 mkconst(state, ins, 0);
5662         }
5663 }
5664
5665 static void simplify_smore(struct compile_state *state, struct triple *ins)
5666 {
5667         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5668                 long_t left, right;
5669                 left  = read_sconst(ins, &RHS(ins, 0));
5670                 right = read_sconst(ins, &RHS(ins, 1));
5671                 mkconst(state, ins, left > right);
5672         }
5673         else if (RHS(ins, 0) == RHS(ins, 1)) {
5674                 mkconst(state, ins, 0);
5675         }
5676 }
5677
5678 static void simplify_umore(struct compile_state *state, struct triple *ins)
5679 {
5680         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5681                 ulong_t left, right;
5682                 left  = read_const(state, ins, &RHS(ins, 0));
5683                 right = read_const(state, ins, &RHS(ins, 1));
5684                 mkconst(state, ins, left > right);
5685         }
5686         else if (is_zero(RHS(ins, 1))) {
5687                 mkconst(state, ins, 1);
5688         }
5689         else if (RHS(ins, 0) == RHS(ins, 1)) {
5690                 mkconst(state, ins, 0);
5691         }
5692 }
5693
5694
5695 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5696 {
5697         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5698                 long_t left, right;
5699                 left  = read_sconst(ins, &RHS(ins, 0));
5700                 right = read_sconst(ins, &RHS(ins, 1));
5701                 mkconst(state, ins, left <= right);
5702         }
5703         else if (RHS(ins, 0) == RHS(ins, 1)) {
5704                 mkconst(state, ins, 1);
5705         }
5706 }
5707
5708 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5709 {
5710         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5711                 ulong_t left, right;
5712                 left  = read_const(state, ins, &RHS(ins, 0));
5713                 right = read_const(state, ins, &RHS(ins, 1));
5714                 mkconst(state, ins, left <= right);
5715         }
5716         else if (is_zero(RHS(ins, 0))) {
5717                 mkconst(state, ins, 1);
5718         }
5719         else if (RHS(ins, 0) == RHS(ins, 1)) {
5720                 mkconst(state, ins, 1);
5721         }
5722 }
5723
5724 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5725 {
5726         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5727                 long_t left, right;
5728                 left  = read_sconst(ins, &RHS(ins, 0));
5729                 right = read_sconst(ins, &RHS(ins, 1));
5730                 mkconst(state, ins, left >= right);
5731         }
5732         else if (RHS(ins, 0) == RHS(ins, 1)) {
5733                 mkconst(state, ins, 1);
5734         }
5735 }
5736
5737 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5738 {
5739         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5740                 ulong_t left, right;
5741                 left  = read_const(state, ins, &RHS(ins, 0));
5742                 right = read_const(state, ins, &RHS(ins, 1));
5743                 mkconst(state, ins, left >= right);
5744         }
5745         else if (is_zero(RHS(ins, 1))) {
5746                 mkconst(state, ins, 1);
5747         }
5748         else if (RHS(ins, 0) == RHS(ins, 1)) {
5749                 mkconst(state, ins, 1);
5750         }
5751 }
5752
5753 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5754 {
5755         if (is_const(RHS(ins, 0))) {
5756                 ulong_t left;
5757                 left = read_const(state, ins, &RHS(ins, 0));
5758                 mkconst(state, ins, left == 0);
5759         }
5760         /* Otherwise if I am the only user... */
5761         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
5762                 int need_copy = 1;
5763                 /* Invert a boolean operation */
5764                 switch(RHS(ins, 0)->op) {
5765                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
5766                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
5767                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
5768                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
5769                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
5770                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
5771                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
5772                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
5773                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
5774                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
5775                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
5776                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
5777                 default:
5778                         need_copy = 0;
5779                         break;
5780                 }
5781                 if (need_copy) {
5782                         mkcopy(state, ins, RHS(ins, 0));
5783                 }
5784         }
5785 }
5786
5787 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
5788 {
5789         if (is_const(RHS(ins, 0))) {
5790                 ulong_t left;
5791                 left = read_const(state, ins, &RHS(ins, 0));
5792                 mkconst(state, ins, left != 0);
5793         }
5794         else switch(RHS(ins, 0)->op) {
5795         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
5796         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
5797         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
5798                 mkcopy(state, ins, RHS(ins, 0));
5799         }
5800
5801 }
5802
5803 static void simplify_copy(struct compile_state *state, struct triple *ins)
5804 {
5805         if (is_const(RHS(ins, 0))) {
5806                 switch(RHS(ins, 0)->op) {
5807                 case OP_INTCONST:
5808                 {
5809                         ulong_t left;
5810                         left = read_const(state, ins, &RHS(ins, 0));
5811                         mkconst(state, ins, left);
5812                         break;
5813                 }
5814                 case OP_ADDRCONST:
5815                 {
5816                         struct triple *sdecl;
5817                         ulong_t offset;
5818                         sdecl  = RHS(ins, 0);
5819                         offset = ins->u.cval;
5820                         mkaddr_const(state, ins, sdecl, offset);
5821                         break;
5822                 }
5823                 default:
5824                         internal_error(state, ins, "uknown constant");
5825                         break;
5826                 }
5827         }
5828 }
5829
5830 static void simplify_branch(struct compile_state *state, struct triple *ins)
5831 {
5832         struct block *block;
5833         if (ins->op != OP_BRANCH) {
5834                 internal_error(state, ins, "not branch");
5835         }
5836         if (ins->use != 0) {
5837                 internal_error(state, ins, "branch use");
5838         }
5839 #warning "FIXME implement simplify branch."
5840         /* The challenge here with simplify branch is that I need to 
5841          * make modifications to the control flow graph as well
5842          * as to the branch instruction itself.
5843          */
5844         block = ins->u.block;
5845         
5846         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
5847                 struct triple *targ;
5848                 ulong_t value;
5849                 value = read_const(state, ins, &RHS(ins, 0));
5850                 unuse_triple(RHS(ins, 0), ins);
5851                 targ = TARG(ins, 0);
5852                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
5853                 if (value) {
5854                         unuse_triple(ins->next, ins);
5855                         TARG(ins, 0) = targ;
5856                 }
5857                 else {
5858                         unuse_triple(targ, ins);
5859                         TARG(ins, 0) = ins->next;
5860                 }
5861 #warning "FIXME handle the case of making a branch unconditional"
5862         }
5863         if (TARG(ins, 0) == ins->next) {
5864                 unuse_triple(ins->next, ins);
5865                 if (TRIPLE_RHS(ins->sizes)) {
5866                         unuse_triple(RHS(ins, 0), ins);
5867                         unuse_triple(ins->next, ins);
5868                 }
5869                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5870                 ins->op = OP_NOOP;
5871                 if (ins->use) {
5872                         internal_error(state, ins, "noop use != 0");
5873                 }
5874 #warning "FIXME handle the case of killing a branch"
5875         }
5876 }
5877
5878 static void simplify_phi(struct compile_state *state, struct triple *ins)
5879 {
5880         struct triple **expr;
5881         ulong_t value;
5882         expr = triple_rhs(state, ins, 0);
5883         if (!*expr || !is_const(*expr)) {
5884                 return;
5885         }
5886         value = read_const(state, ins, expr);
5887         for(;expr;expr = triple_rhs(state, ins, expr)) {
5888                 if (!*expr || !is_const(*expr)) {
5889                         return;
5890                 }
5891                 if (value != read_const(state, ins, expr)) {
5892                         return;
5893                 }
5894         }
5895         mkconst(state, ins, value);
5896 }
5897
5898
5899 static void simplify_bsf(struct compile_state *state, struct triple *ins)
5900 {
5901         if (is_const(RHS(ins, 0))) {
5902                 ulong_t left;
5903                 left = read_const(state, ins, &RHS(ins, 0));
5904                 mkconst(state, ins, bsf(left));
5905         }
5906 }
5907
5908 static void simplify_bsr(struct compile_state *state, struct triple *ins)
5909 {
5910         if (is_const(RHS(ins, 0))) {
5911                 ulong_t left;
5912                 left = read_const(state, ins, &RHS(ins, 0));
5913                 mkconst(state, ins, bsr(left));
5914         }
5915 }
5916
5917
5918 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
5919 static const simplify_t table_simplify[] = {
5920 #if 0
5921 #define simplify_smul     simplify_noop
5922 #define simplify_umul     simplify_noop
5923 #define simplify_sdiv     simplify_noop
5924 #define simplify_udiv     simplify_noop
5925 #define simplify_smod     simplify_noop
5926 #define simplify_umod     simplify_noop
5927 #endif
5928 #if 0
5929 #define simplify_add      simplify_noop
5930 #define simplify_sub      simplify_noop
5931 #endif
5932 #if 0
5933 #define simplify_sl       simplify_noop
5934 #define simplify_usr      simplify_noop
5935 #define simplify_ssr      simplify_noop
5936 #endif
5937 #if 0
5938 #define simplify_and      simplify_noop
5939 #define simplify_xor      simplify_noop
5940 #define simplify_or       simplify_noop
5941 #endif
5942 #if 0
5943 #define simplify_pos      simplify_noop
5944 #define simplify_neg      simplify_noop
5945 #define simplify_invert   simplify_noop
5946 #endif
5947
5948 #if 0
5949 #define simplify_eq       simplify_noop
5950 #define simplify_noteq    simplify_noop
5951 #endif
5952 #if 0
5953 #define simplify_sless    simplify_noop
5954 #define simplify_uless    simplify_noop
5955 #define simplify_smore    simplify_noop
5956 #define simplify_umore    simplify_noop
5957 #endif
5958 #if 0
5959 #define simplify_slesseq  simplify_noop
5960 #define simplify_ulesseq  simplify_noop
5961 #define simplify_smoreeq  simplify_noop
5962 #define simplify_umoreeq  simplify_noop
5963 #endif
5964 #if 0
5965 #define simplify_lfalse   simplify_noop
5966 #endif
5967 #if 0
5968 #define simplify_ltrue    simplify_noop
5969 #endif
5970
5971 #if 0
5972 #define simplify_copy     simplify_noop
5973 #endif
5974
5975 #if 0
5976 #define simplify_branch   simplify_noop
5977 #endif
5978
5979 #if 0
5980 #define simplify_phi      simplify_noop
5981 #endif
5982
5983 #if 0
5984 #define simplify_bsf      simplify_noop
5985 #define simplify_bsr      simplify_noop
5986 #endif
5987
5988 [OP_SMUL       ] = simplify_smul,
5989 [OP_UMUL       ] = simplify_umul,
5990 [OP_SDIV       ] = simplify_sdiv,
5991 [OP_UDIV       ] = simplify_udiv,
5992 [OP_SMOD       ] = simplify_smod,
5993 [OP_UMOD       ] = simplify_umod,
5994 [OP_ADD        ] = simplify_add,
5995 [OP_SUB        ] = simplify_sub,
5996 [OP_SL         ] = simplify_sl,
5997 [OP_USR        ] = simplify_usr,
5998 [OP_SSR        ] = simplify_ssr,
5999 [OP_AND        ] = simplify_and,
6000 [OP_XOR        ] = simplify_xor,
6001 [OP_OR         ] = simplify_or,
6002 [OP_POS        ] = simplify_pos,
6003 [OP_NEG        ] = simplify_neg,
6004 [OP_INVERT     ] = simplify_invert,
6005
6006 [OP_EQ         ] = simplify_eq,
6007 [OP_NOTEQ      ] = simplify_noteq,
6008 [OP_SLESS      ] = simplify_sless,
6009 [OP_ULESS      ] = simplify_uless,
6010 [OP_SMORE      ] = simplify_smore,
6011 [OP_UMORE      ] = simplify_umore,
6012 [OP_SLESSEQ    ] = simplify_slesseq,
6013 [OP_ULESSEQ    ] = simplify_ulesseq,
6014 [OP_SMOREEQ    ] = simplify_smoreeq,
6015 [OP_UMOREEQ    ] = simplify_umoreeq,
6016 [OP_LFALSE     ] = simplify_lfalse,
6017 [OP_LTRUE      ] = simplify_ltrue,
6018
6019 [OP_LOAD       ] = simplify_noop,
6020 [OP_STORE      ] = simplify_noop,
6021
6022 [OP_NOOP       ] = simplify_noop,
6023
6024 [OP_INTCONST   ] = simplify_noop,
6025 [OP_BLOBCONST  ] = simplify_noop,
6026 [OP_ADDRCONST  ] = simplify_noop,
6027
6028 [OP_WRITE      ] = simplify_noop,
6029 [OP_READ       ] = simplify_noop,
6030 [OP_COPY       ] = simplify_copy,
6031 [OP_PIECE      ] = simplify_noop,
6032
6033 [OP_DOT        ] = simplify_noop,
6034 [OP_VAL_VEC    ] = simplify_noop,
6035
6036 [OP_LIST       ] = simplify_noop,
6037 [OP_BRANCH     ] = simplify_branch,
6038 [OP_LABEL      ] = simplify_noop,
6039 [OP_ADECL      ] = simplify_noop,
6040 [OP_SDECL      ] = simplify_noop,
6041 [OP_PHI        ] = simplify_phi,
6042
6043 [OP_INB        ] = simplify_noop,
6044 [OP_INW        ] = simplify_noop,
6045 [OP_INL        ] = simplify_noop,
6046 [OP_OUTB       ] = simplify_noop,
6047 [OP_OUTW       ] = simplify_noop,
6048 [OP_OUTL       ] = simplify_noop,
6049 [OP_BSF        ] = simplify_bsf,
6050 [OP_BSR        ] = simplify_bsr,
6051 [OP_RDMSR      ] = simplify_noop,
6052 [OP_WRMSR      ] = simplify_noop,                    
6053 [OP_HLT        ] = simplify_noop,
6054 };
6055
6056 static void simplify(struct compile_state *state, struct triple *ins)
6057 {
6058         int op;
6059         simplify_t do_simplify;
6060         do {
6061                 op = ins->op;
6062                 do_simplify = 0;
6063                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6064                         do_simplify = 0;
6065                 }
6066                 else {
6067                         do_simplify = table_simplify[op];
6068                 }
6069                 if (!do_simplify) {
6070                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6071                                 op, tops(op));
6072                         return;
6073                 }
6074                 do_simplify(state, ins);
6075         } while(ins->op != op);
6076 }
6077
6078 static void simplify_all(struct compile_state *state)
6079 {
6080         struct triple *ins, *first;
6081         first = RHS(state->main_function, 0);
6082         ins = first;
6083         do {
6084                 simplify(state, ins);
6085                 ins = ins->next;
6086         } while(ins != first);
6087 }
6088
6089 /*
6090  * Builtins....
6091  * ============================
6092  */
6093
6094 static void register_builtin_function(struct compile_state *state,
6095         const char *name, int op, struct type *rtype, ...)
6096 {
6097         struct type *ftype, *atype, *param, **next;
6098         struct triple *def, *arg, *result, *work, *last, *first;
6099         struct hash_entry *ident;
6100         struct file_state file;
6101         int parameters;
6102         int name_len;
6103         va_list args;
6104         int i;
6105
6106         /* Dummy file state to get debug handling right */
6107         memset(&file, 0, sizeof(file));
6108         file.basename = name;
6109         file.line = 1;
6110         file.prev = state->file;
6111         state->file = &file;
6112
6113         /* Find the Parameter count */
6114         valid_op(state, op);
6115         parameters = table_ops[op].rhs;
6116         if (parameters < 0 ) {
6117                 internal_error(state, 0, "Invalid builtin parameter count");
6118         }
6119
6120         /* Find the function type */
6121         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6122         next = &ftype->right;
6123         va_start(args, rtype);
6124         for(i = 0; i < parameters; i++) {
6125                 atype = va_arg(args, struct type *);
6126                 if (!*next) {
6127                         *next = atype;
6128                 } else {
6129                         *next = new_type(TYPE_PRODUCT, *next, atype);
6130                         next = &((*next)->right);
6131                 }
6132         }
6133         if (!*next) {
6134                 *next = &void_type;
6135         }
6136         va_end(args);
6137
6138         /* Generate the needed triples */
6139         def = triple(state, OP_LIST, ftype, 0, 0);
6140         first = label(state);
6141         RHS(def, 0) = first;
6142
6143         /* Now string them together */
6144         param = ftype->right;
6145         for(i = 0; i < parameters; i++) {
6146                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6147                         atype = param->left;
6148                 } else {
6149                         atype = param;
6150                 }
6151                 arg = flatten(state, first, variable(state, atype));
6152                 param = param->right;
6153         }
6154         result = 0;
6155         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6156                 result = flatten(state, first, variable(state, rtype));
6157         }
6158         MISC(def, 0) = result;
6159         work = new_triple(state, op, rtype, parameters);
6160         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6161                 RHS(work, i) = read_expr(state, arg);
6162         }
6163         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6164                 struct triple *val;
6165                 /* Populate the LHS with the target registers */
6166                 work = flatten(state, first, work);
6167                 work->type = &void_type;
6168                 param = rtype->left;
6169                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6170                         internal_error(state, 0, "Invalid result type");
6171                 }
6172                 val = new_triple(state, OP_VAL_VEC, rtype, -1);
6173                 for(i = 0; i < rtype->elements; i++) {
6174                         struct triple *piece;
6175                         atype = param;
6176                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6177                                 atype = param->left;
6178                         }
6179                         if (!TYPE_ARITHMETIC(atype->type) &&
6180                                 !TYPE_PTR(atype->type)) {
6181                                 internal_error(state, 0, "Invalid lhs type");
6182                         }
6183                         piece = triple(state, OP_PIECE, atype, work, 0);
6184                         piece->u.cval = i;
6185                         LHS(work, i) = piece;
6186                         RHS(val, i) = piece;
6187                 }
6188                 work = val;
6189         }
6190         if (result) {
6191                 work = write_expr(state, result, work);
6192         }
6193         work = flatten(state, first, work);
6194         last = flatten(state, first, label(state));
6195         name_len = strlen(name);
6196         ident = lookup(state, name, name_len);
6197         symbol(state, ident, &ident->sym_ident, def, ftype);
6198         
6199         state->file = file.prev;
6200 #if 0
6201         fprintf(stdout, "\n");
6202         loc(stdout, state, 0);
6203         fprintf(stdout, "\n__________ builtin_function _________\n");
6204         print_triple(state, def);
6205         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6206 #endif
6207 }
6208
6209 static struct type *partial_struct(struct compile_state *state,
6210         const char *field_name, struct type *type, struct type *rest)
6211 {
6212         struct hash_entry *field_ident;
6213         struct type *result;
6214         int field_name_len;
6215
6216         field_name_len = strlen(field_name);
6217         field_ident = lookup(state, field_name, field_name_len);
6218
6219         result = clone_type(0, type);
6220         result->field_ident = field_ident;
6221
6222         if (rest) {
6223                 result = new_type(TYPE_PRODUCT, result, rest);
6224         }
6225         return result;
6226 }
6227
6228 static struct type *register_builtin_type(struct compile_state *state,
6229         const char *name, struct type *type)
6230 {
6231         struct hash_entry *ident;
6232         int name_len;
6233
6234         name_len = strlen(name);
6235         ident = lookup(state, name, name_len);
6236         
6237         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6238                 ulong_t elements = 0;
6239                 struct type *field;
6240                 type = new_type(TYPE_STRUCT, type, 0);
6241                 field = type->left;
6242                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6243                         elements++;
6244                         field = field->right;
6245                 }
6246                 elements++;
6247                 symbol(state, ident, &ident->sym_struct, 0, type);
6248                 type->type_ident = ident;
6249                 type->elements = elements;
6250         }
6251         symbol(state, ident, &ident->sym_ident, 0, type);
6252         ident->tok = TOK_TYPE_NAME;
6253         return type;
6254 }
6255
6256
6257 static void register_builtins(struct compile_state *state)
6258 {
6259         struct type *msr_type;
6260
6261         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6262                 &ushort_type);
6263         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6264                 &ushort_type);
6265         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6266                 &ushort_type);
6267
6268         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6269                 &uchar_type, &ushort_type);
6270         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6271                 &ushort_type, &ushort_type);
6272         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6273                 &uint_type, &ushort_type);
6274         
6275         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6276                 &int_type);
6277         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6278                 &int_type);
6279
6280         msr_type = register_builtin_type(state, "__builtin_msr_t",
6281                 partial_struct(state, "lo", &ulong_type,
6282                 partial_struct(state, "hi", &ulong_type, 0)));
6283
6284         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6285                 &ulong_type);
6286         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6287                 &ulong_type, &ulong_type, &ulong_type);
6288         
6289         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6290                 &void_type);
6291 }
6292
6293 static struct type *declarator(
6294         struct compile_state *state, struct type *type, 
6295         struct hash_entry **ident, int need_ident);
6296 static void decl(struct compile_state *state, struct triple *first);
6297 static struct type *specifier_qualifier_list(struct compile_state *state);
6298 static int isdecl_specifier(int tok);
6299 static struct type *decl_specifiers(struct compile_state *state);
6300 static int istype(int tok);
6301 static struct triple *expr(struct compile_state *state);
6302 static struct triple *assignment_expr(struct compile_state *state);
6303 static struct type *type_name(struct compile_state *state);
6304 static void statement(struct compile_state *state, struct triple *fist);
6305
6306 static struct triple *call_expr(
6307         struct compile_state *state, struct triple *func)
6308 {
6309         struct triple *def;
6310         struct type *param, *type;
6311         ulong_t pvals, index;
6312
6313         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6314                 error(state, 0, "Called object is not a function");
6315         }
6316         if (func->op != OP_LIST) {
6317                 internal_error(state, 0, "improper function");
6318         }
6319         eat(state, TOK_LPAREN);
6320         /* Find the return type without any specifiers */
6321         type = clone_type(0, func->type->left);
6322         def = new_triple(state, OP_CALL, func->type, -1);
6323         def->type = type;
6324
6325         pvals = TRIPLE_RHS(def->sizes);
6326         MISC(def, 0) = func;
6327
6328         param = func->type->right;
6329         for(index = 0; index < pvals; index++) {
6330                 struct triple *val;
6331                 struct type *arg_type;
6332                 val = read_expr(state, assignment_expr(state));
6333                 arg_type = param;
6334                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6335                         arg_type = param->left;
6336                 }
6337                 write_compatible(state, arg_type, val->type);
6338                 RHS(def, index) = val;
6339                 if (index != (pvals - 1)) {
6340                         eat(state, TOK_COMMA);
6341                         param = param->right;
6342                 }
6343         }
6344         eat(state, TOK_RPAREN);
6345         return def;
6346 }
6347
6348
6349 static struct triple *character_constant(struct compile_state *state)
6350 {
6351         struct triple *def;
6352         struct token *tk;
6353         const signed char *str, *end;
6354         int c;
6355         int str_len;
6356         eat(state, TOK_LIT_CHAR);
6357         tk = &state->token[0];
6358         str = tk->val.str + 1;
6359         str_len = tk->str_len - 2;
6360         if (str_len <= 0) {
6361                 error(state, 0, "empty character constant");
6362         }
6363         end = str + str_len;
6364         c = char_value(state, &str, end);
6365         if (str != end) {
6366                 error(state, 0, "multibyte character constant not supported");
6367         }
6368         def = int_const(state, &char_type, (ulong_t)((long_t)c));
6369         return def;
6370 }
6371
6372 static struct triple *string_constant(struct compile_state *state)
6373 {
6374         struct triple *def;
6375         struct token *tk;
6376         struct type *type;
6377         const signed char *str, *end;
6378         signed char *buf, *ptr;
6379         int str_len;
6380
6381         buf = 0;
6382         type = new_type(TYPE_ARRAY, &char_type, 0);
6383         type->elements = 0;
6384         /* The while loop handles string concatenation */
6385         do {
6386                 eat(state, TOK_LIT_STRING);
6387                 tk = &state->token[0];
6388                 str = tk->val.str + 1;
6389                 str_len = tk->str_len - 2;
6390                 if (str_len < 0) {
6391                         error(state, 0, "negative string constant length");
6392                 }
6393                 end = str + str_len;
6394                 ptr = buf;
6395                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6396                 memcpy(buf, ptr, type->elements);
6397                 ptr = buf + type->elements;
6398                 do {
6399                         *ptr++ = char_value(state, &str, end);
6400                 } while(str < end);
6401                 type->elements = ptr - buf;
6402         } while(peek(state) == TOK_LIT_STRING);
6403         *ptr = '\0';
6404         type->elements += 1;
6405         def = triple(state, OP_BLOBCONST, type, 0, 0);
6406         def->u.blob = buf;
6407         return def;
6408 }
6409
6410
6411 static struct triple *integer_constant(struct compile_state *state)
6412 {
6413         struct triple *def;
6414         unsigned long val;
6415         struct token *tk;
6416         char *end;
6417         int u, l, decimal;
6418         struct type *type;
6419
6420         eat(state, TOK_LIT_INT);
6421         tk = &state->token[0];
6422         errno = 0;
6423         decimal = (tk->val.str[0] != '0');
6424         val = strtoul(tk->val.str, &end, 0);
6425         if ((val == ULONG_MAX) && (errno == ERANGE)) {
6426                 error(state, 0, "Integer constant to large");
6427         }
6428         u = l = 0;
6429         if ((*end == 'u') || (*end == 'U')) {
6430                 u = 1;
6431                         end++;
6432         }
6433         if ((*end == 'l') || (*end == 'L')) {
6434                 l = 1;
6435                 end++;
6436         }
6437         if ((*end == 'u') || (*end == 'U')) {
6438                 u = 1;
6439                 end++;
6440         }
6441         if (*end) {
6442                 error(state, 0, "Junk at end of integer constant");
6443         }
6444         if (u && l)  {
6445                 type = &ulong_type;
6446         }
6447         else if (l) {
6448                 type = &long_type;
6449                 if (!decimal && (val > LONG_MAX)) {
6450                         type = &ulong_type;
6451                 }
6452         }
6453         else if (u) {
6454                 type = &uint_type;
6455                 if (val > UINT_MAX) {
6456                         type = &ulong_type;
6457                 }
6458         }
6459         else {
6460                 type = &int_type;
6461                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6462                         type = &uint_type;
6463                 }
6464                 else if (!decimal && (val > LONG_MAX)) {
6465                         type = &ulong_type;
6466                 }
6467                 else if (val > INT_MAX) {
6468                         type = &long_type;
6469                 }
6470         }
6471         def = int_const(state, type, val);
6472         return def;
6473 }
6474
6475 static struct triple *primary_expr(struct compile_state *state)
6476 {
6477         struct triple *def;
6478         int tok;
6479         tok = peek(state);
6480         switch(tok) {
6481         case TOK_IDENT:
6482         {
6483                 struct hash_entry *ident;
6484                 /* Here ident is either:
6485                  * a varable name
6486                  * a function name
6487                  * an enumeration constant.
6488                  */
6489                 eat(state, TOK_IDENT);
6490                 ident = state->token[0].ident;
6491                 if (!ident->sym_ident) {
6492                         error(state, 0, "%s undeclared", ident->name);
6493                 }
6494                 def = ident->sym_ident->def;
6495                 break;
6496         }
6497         case TOK_ENUM_CONST:
6498                 /* Here ident is an enumeration constant */
6499                 eat(state, TOK_ENUM_CONST);
6500                 def = 0;
6501                 FINISHME();
6502                 break;
6503         case TOK_LPAREN:
6504                 eat(state, TOK_LPAREN);
6505                 def = expr(state);
6506                 eat(state, TOK_RPAREN);
6507                 break;
6508         case TOK_LIT_INT:
6509                 def = integer_constant(state);
6510                 break;
6511         case TOK_LIT_FLOAT:
6512                 eat(state, TOK_LIT_FLOAT);
6513                 error(state, 0, "Floating point constants not supported");
6514                 def = 0;
6515                 FINISHME();
6516                 break;
6517         case TOK_LIT_CHAR:
6518                 def = character_constant(state);
6519                 break;
6520         case TOK_LIT_STRING:
6521                 def = string_constant(state);
6522                 break;
6523         default:
6524                 def = 0;
6525                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6526         }
6527         return def;
6528 }
6529
6530 static struct triple *postfix_expr(struct compile_state *state)
6531 {
6532         struct triple *def;
6533         int postfix;
6534         def = primary_expr(state);
6535         do {
6536                 struct triple *left;
6537                 int tok;
6538                 postfix = 1;
6539                 left = def;
6540                 switch((tok = peek(state))) {
6541                 case TOK_LBRACKET:
6542                         eat(state, TOK_LBRACKET);
6543                         def = mk_subscript_expr(state, left, expr(state));
6544                         eat(state, TOK_RBRACKET);
6545                         break;
6546                 case TOK_LPAREN:
6547                         def = call_expr(state, def);
6548                         break;
6549                 case TOK_DOT:
6550                 {
6551                         struct hash_entry *field;
6552                         eat(state, TOK_DOT);
6553                         eat(state, TOK_IDENT);
6554                         field = state->token[0].ident;
6555                         def = deref_field(state, def, field);
6556                         break;
6557                 }
6558                 case TOK_ARROW:
6559                 {
6560                         struct hash_entry *field;
6561                         eat(state, TOK_ARROW);
6562                         eat(state, TOK_IDENT);
6563                         field = state->token[0].ident;
6564                         def = mk_deref_expr(state, read_expr(state, def));
6565                         def = deref_field(state, def, field);
6566                         break;
6567                 }
6568                 case TOK_PLUSPLUS:
6569                         eat(state, TOK_PLUSPLUS);
6570                         def = mk_post_inc_expr(state, left);
6571                         break;
6572                 case TOK_MINUSMINUS:
6573                         eat(state, TOK_MINUSMINUS);
6574                         def = mk_post_dec_expr(state, left);
6575                         break;
6576                 default:
6577                         postfix = 0;
6578                         break;
6579                 }
6580         } while(postfix);
6581         return def;
6582 }
6583
6584 static struct triple *cast_expr(struct compile_state *state);
6585
6586 static struct triple *unary_expr(struct compile_state *state)
6587 {
6588         struct triple *def, *right;
6589         int tok;
6590         switch((tok = peek(state))) {
6591         case TOK_PLUSPLUS:
6592                 eat(state, TOK_PLUSPLUS);
6593                 def = mk_pre_inc_expr(state, unary_expr(state));
6594                 break;
6595         case TOK_MINUSMINUS:
6596                 eat(state, TOK_MINUSMINUS);
6597                 def = mk_pre_dec_expr(state, unary_expr(state));
6598                 break;
6599         case TOK_AND:
6600                 eat(state, TOK_AND);
6601                 def = mk_addr_expr(state, cast_expr(state), 0);
6602                 break;
6603         case TOK_STAR:
6604                 eat(state, TOK_STAR);
6605                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6606                 break;
6607         case TOK_PLUS:
6608                 eat(state, TOK_PLUS);
6609                 right = read_expr(state, cast_expr(state));
6610                 arithmetic(state, right);
6611                 def = integral_promotion(state, right);
6612                 break;
6613         case TOK_MINUS:
6614                 eat(state, TOK_MINUS);
6615                 right = read_expr(state, cast_expr(state));
6616                 arithmetic(state, right);
6617                 def = integral_promotion(state, right);
6618                 def = triple(state, OP_NEG, def->type, def, 0);
6619                 break;
6620         case TOK_TILDE:
6621                 eat(state, TOK_TILDE);
6622                 right = read_expr(state, cast_expr(state));
6623                 integral(state, right);
6624                 def = integral_promotion(state, right);
6625                 def = triple(state, OP_INVERT, def->type, def, 0);
6626                 break;
6627         case TOK_BANG:
6628                 eat(state, TOK_BANG);
6629                 right = read_expr(state, cast_expr(state));
6630                 bool(state, right);
6631                 def = lfalse_expr(state, right);
6632                 break;
6633         case TOK_SIZEOF:
6634         {
6635                 struct type *type;
6636                 int tok1, tok2;
6637                 eat(state, TOK_SIZEOF);
6638                 tok1 = peek(state);
6639                 tok2 = peek2(state);
6640                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6641                         eat(state, TOK_LPAREN);
6642                         type = type_name(state);
6643                         eat(state, TOK_RPAREN);
6644                 }
6645                 else {
6646                         struct triple *expr;
6647                         expr = unary_expr(state);
6648                         type = expr->type;
6649                         release_expr(state, expr);
6650                 }
6651                 def = int_const(state, &ulong_type, size_of(state, type));
6652                 break;
6653         }
6654         case TOK_ALIGNOF:
6655         {
6656                 struct type *type;
6657                 int tok1, tok2;
6658                 eat(state, TOK_ALIGNOF);
6659                 tok1 = peek(state);
6660                 tok2 = peek2(state);
6661                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6662                         eat(state, TOK_LPAREN);
6663                         type = type_name(state);
6664                         eat(state, TOK_RPAREN);
6665                 }
6666                 else {
6667                         struct triple *expr;
6668                         expr = unary_expr(state);
6669                         type = expr->type;
6670                         release_expr(state, expr);
6671                 }
6672                 def = int_const(state, &ulong_type, align_of(state, type));
6673                 break;
6674         }
6675         default:
6676                 def = postfix_expr(state);
6677                 break;
6678         }
6679         return def;
6680 }
6681
6682 static struct triple *cast_expr(struct compile_state *state)
6683 {
6684         struct triple *def;
6685         int tok1, tok2;
6686         tok1 = peek(state);
6687         tok2 = peek2(state);
6688         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6689                 struct type *type;
6690                 eat(state, TOK_LPAREN);
6691                 type = type_name(state);
6692                 eat(state, TOK_RPAREN);
6693                 def = read_expr(state, cast_expr(state));
6694                 def = triple(state, OP_COPY, type, def, 0);
6695 #warning "FIXME do I need an OP_CAST expr to be semantically correct here?"
6696         }
6697         else {
6698                 def = unary_expr(state);
6699         }
6700         return def;
6701 }
6702
6703 static struct triple *mult_expr(struct compile_state *state)
6704 {
6705         struct triple *def;
6706         int done;
6707         def = cast_expr(state);
6708         do {
6709                 struct triple *left, *right;
6710                 struct type *result_type;
6711                 int tok, op, sign;
6712                 done = 0;
6713                 switch(tok = (peek(state))) {
6714                 case TOK_STAR:
6715                 case TOK_DIV:
6716                 case TOK_MOD:
6717                         left = read_expr(state, def);
6718                         arithmetic(state, left);
6719
6720                         eat(state, tok);
6721
6722                         right = read_expr(state, cast_expr(state));
6723                         arithmetic(state, right);
6724
6725                         result_type = arithmetic_result(state, left, right);
6726                         sign = is_signed(result_type);
6727                         op = -1;
6728                         switch(tok) {
6729                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6730                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
6731                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
6732                         }
6733                         def = triple(state, op, result_type, left, right);
6734                         break;
6735                 default:
6736                         done = 1;
6737                         break;
6738                 }
6739         } while(!done);
6740         return def;
6741 }
6742
6743 static struct triple *add_expr(struct compile_state *state)
6744 {
6745         struct triple *def;
6746         int done;
6747         def = mult_expr(state);
6748         do {
6749                 done = 0;
6750                 switch( peek(state)) {
6751                 case TOK_PLUS:
6752                         eat(state, TOK_PLUS);
6753                         def = mk_add_expr(state, def, mult_expr(state));
6754                         break;
6755                 case TOK_MINUS:
6756                         eat(state, TOK_MINUS);
6757                         def = mk_sub_expr(state, def, mult_expr(state));
6758                         break;
6759                 default:
6760                         done = 1;
6761                         break;
6762                 }
6763         } while(!done);
6764         return def;
6765 }
6766
6767 static struct triple *shift_expr(struct compile_state *state)
6768 {
6769         struct triple *def;
6770         int done;
6771         def = add_expr(state);
6772         do {
6773                 struct triple *left, *right;
6774                 int tok, op;
6775                 done = 0;
6776                 switch((tok = peek(state))) {
6777                 case TOK_SL:
6778                 case TOK_SR:
6779                         left = read_expr(state, def);
6780                         integral(state, left);
6781                         left = integral_promotion(state, left);
6782
6783                         eat(state, tok);
6784
6785                         right = read_expr(state, add_expr(state));
6786                         integral(state, right);
6787                         right = integral_promotion(state, right);
6788                         
6789                         op = (tok == TOK_SL)? OP_SL : 
6790                                 is_signed(left->type)? OP_SSR: OP_USR;
6791
6792                         def = triple(state, op, left->type, left, right);
6793                         break;
6794                 default:
6795                         done = 1;
6796                         break;
6797                 }
6798         } while(!done);
6799         return def;
6800 }
6801
6802 static struct triple *relational_expr(struct compile_state *state)
6803 {
6804 #warning "Extend relational exprs to work on more than arithmetic types"
6805         struct triple *def;
6806         int done;
6807         def = shift_expr(state);
6808         do {
6809                 struct triple *left, *right;
6810                 struct type *arg_type;
6811                 int tok, op, sign;
6812                 done = 0;
6813                 switch((tok = peek(state))) {
6814                 case TOK_LESS:
6815                 case TOK_MORE:
6816                 case TOK_LESSEQ:
6817                 case TOK_MOREEQ:
6818                         left = read_expr(state, def);
6819                         arithmetic(state, left);
6820
6821                         eat(state, tok);
6822
6823                         right = read_expr(state, shift_expr(state));
6824                         arithmetic(state, right);
6825
6826                         arg_type = arithmetic_result(state, left, right);
6827                         sign = is_signed(arg_type);
6828                         op = -1;
6829                         switch(tok) {
6830                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
6831                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
6832                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
6833                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
6834                         }
6835                         def = triple(state, op, &int_type, left, right);
6836                         break;
6837                 default:
6838                         done = 1;
6839                         break;
6840                 }
6841         } while(!done);
6842         return def;
6843 }
6844
6845 static struct triple *equality_expr(struct compile_state *state)
6846 {
6847 #warning "Extend equality exprs to work on more than arithmetic types"
6848         struct triple *def;
6849         int done;
6850         def = relational_expr(state);
6851         do {
6852                 struct triple *left, *right;
6853                 int tok, op;
6854                 done = 0;
6855                 switch((tok = peek(state))) {
6856                 case TOK_EQEQ:
6857                 case TOK_NOTEQ:
6858                         left = read_expr(state, def);
6859                         arithmetic(state, left);
6860                         eat(state, tok);
6861                         right = read_expr(state, relational_expr(state));
6862                         arithmetic(state, right);
6863                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
6864                         def = triple(state, op, &int_type, left, right);
6865                         break;
6866                 default:
6867                         done = 1;
6868                         break;
6869                 }
6870         } while(!done);
6871         return def;
6872 }
6873
6874 static struct triple *and_expr(struct compile_state *state)
6875 {
6876         struct triple *def;
6877         def = equality_expr(state);
6878         while(peek(state) == TOK_AND) {
6879                 struct triple *left, *right;
6880                 struct type *result_type;
6881                 left = read_expr(state, def);
6882                 integral(state, left);
6883                 eat(state, TOK_AND);
6884                 right = read_expr(state, equality_expr(state));
6885                 integral(state, right);
6886                 result_type = arithmetic_result(state, left, right);
6887                 def = triple(state, OP_AND, result_type, left, right);
6888         }
6889         return def;
6890 }
6891
6892 static struct triple *xor_expr(struct compile_state *state)
6893 {
6894         struct triple *def;
6895         def = and_expr(state);
6896         while(peek(state) == TOK_XOR) {
6897                 struct triple *left, *right;
6898                 struct type *result_type;
6899                 left = read_expr(state, def);
6900                 integral(state, left);
6901                 eat(state, TOK_XOR);
6902                 right = read_expr(state, and_expr(state));
6903                 integral(state, right);
6904                 result_type = arithmetic_result(state, left, right);
6905                 def = triple(state, OP_XOR, result_type, left, right);
6906         }
6907         return def;
6908 }
6909
6910 static struct triple *or_expr(struct compile_state *state)
6911 {
6912         struct triple *def;
6913         def = xor_expr(state);
6914         while(peek(state) == TOK_OR) {
6915                 struct triple *left, *right;
6916                 struct type *result_type;
6917                 left = read_expr(state, def);
6918                 integral(state, left);
6919                 eat(state, TOK_OR);
6920                 right = read_expr(state, xor_expr(state));
6921                 integral(state, right);
6922                 result_type = arithmetic_result(state, left, right);
6923                 def = triple(state, OP_OR, result_type, left, right);
6924         }
6925         return def;
6926 }
6927
6928 static struct triple *land_expr(struct compile_state *state)
6929 {
6930         struct triple *def;
6931         def = or_expr(state);
6932         while(peek(state) == TOK_LOGAND) {
6933                 struct triple *left, *right;
6934                 left = read_expr(state, def);
6935                 bool(state, left);
6936                 eat(state, TOK_LOGAND);
6937                 right = read_expr(state, or_expr(state));
6938                 bool(state, right);
6939
6940                 def = triple(state, OP_LAND, &int_type,
6941                         ltrue_expr(state, left),
6942                         ltrue_expr(state, right));
6943         }
6944         return def;
6945 }
6946
6947 static struct triple *lor_expr(struct compile_state *state)
6948 {
6949         struct triple *def;
6950         def = land_expr(state);
6951         while(peek(state) == TOK_LOGOR) {
6952                 struct triple *left, *right;
6953                 left = read_expr(state, def);
6954                 bool(state, left);
6955                 eat(state, TOK_LOGOR);
6956                 right = read_expr(state, land_expr(state));
6957                 bool(state, right);
6958                 
6959                 def = triple(state, OP_LOR, &int_type,
6960                         ltrue_expr(state, left),
6961                         ltrue_expr(state, right));
6962         }
6963         return def;
6964 }
6965
6966 static struct triple *conditional_expr(struct compile_state *state)
6967 {
6968         struct triple *def;
6969         def = lor_expr(state);
6970         if (peek(state) == TOK_QUEST) {
6971                 struct triple *test, *left, *right;
6972                 bool(state, def);
6973                 test = ltrue_expr(state, read_expr(state, def));
6974                 eat(state, TOK_QUEST);
6975                 left = read_expr(state, expr(state));
6976                 eat(state, TOK_COLON);
6977                 right = read_expr(state, conditional_expr(state));
6978
6979                 def = cond_expr(state, test, left, right);
6980         }
6981         return def;
6982 }
6983
6984 static struct triple *eval_const_expr(
6985         struct compile_state *state, struct triple *expr)
6986 {
6987         struct triple *def;
6988         struct triple *head, *ptr;
6989         head = label(state); /* dummy initial triple */
6990         flatten(state, head, expr);
6991         for(ptr = head->next; ptr != head; ptr = ptr->next) {
6992                 simplify(state, ptr);
6993         }
6994         /* Remove the constant value the tail of the list */
6995         def = head->prev;
6996         def->prev->next = def->next;
6997         def->next->prev = def->prev;
6998         def->next = def->prev = def;
6999         if (!is_const(def)) {
7000                 internal_error(state, 0, "Not a constant expression");
7001         }
7002         /* Free the intermediate expressions */
7003         while(head->next != head) {
7004                 release_triple(state, head->next);
7005         }
7006         free_triple(state, head);
7007         return def;
7008 }
7009
7010 static struct triple *constant_expr(struct compile_state *state)
7011 {
7012         return eval_const_expr(state, conditional_expr(state));
7013 }
7014
7015 static struct triple *assignment_expr(struct compile_state *state)
7016 {
7017         struct triple *def, *left, *right;
7018         int tok, op, sign;
7019         /* The C grammer in K&R shows assignment expressions
7020          * only taking unary expressions as input on their
7021          * left hand side.  But specifies the precedence of
7022          * assignemnt as the lowest operator except for comma.
7023          *
7024          * Allowing conditional expressions on the left hand side
7025          * of an assignement results in a grammar that accepts
7026          * a larger set of statements than standard C.   As long
7027          * as the subset of the grammar that is standard C behaves
7028          * correctly this should cause no problems.
7029          * 
7030          * For the extra token strings accepted by the grammar
7031          * none of them should produce a valid lvalue, so they
7032          * should not produce functioning programs.
7033          *
7034          * GCC has this bug as well, so surprises should be minimal.
7035          */
7036         def = conditional_expr(state);
7037         left = def;
7038         switch((tok = peek(state))) {
7039         case TOK_EQ:
7040                 lvalue(state, left);
7041                 eat(state, TOK_EQ);
7042                 def = write_expr(state, left, 
7043                         read_expr(state, assignment_expr(state)));
7044                 break;
7045         case TOK_TIMESEQ:
7046         case TOK_DIVEQ:
7047         case TOK_MODEQ:
7048         case TOK_PLUSEQ:
7049         case TOK_MINUSEQ:
7050                 lvalue(state, left);
7051                 arithmetic(state, left);
7052                 eat(state, tok);
7053                 right = read_expr(state, assignment_expr(state));
7054                 arithmetic(state, right);
7055
7056                 sign = is_signed(left->type);
7057                 op = -1;
7058                 switch(tok) {
7059                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7060                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7061                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7062                 case TOK_PLUSEQ:  op = OP_ADD; break;
7063                 case TOK_MINUSEQ: op = OP_SUB; break;
7064                 }
7065                 def = write_expr(state, left,
7066                         triple(state, op, left->type, 
7067                                 read_expr(state, left), right));
7068                 break;
7069         case TOK_SLEQ:
7070         case TOK_SREQ:
7071         case TOK_ANDEQ:
7072         case TOK_XOREQ:
7073         case TOK_OREQ:
7074                 lvalue(state, left);
7075                 integral(state, left);
7076                 eat(state, tok);
7077                 right = read_expr(state, assignment_expr(state));
7078                 integral(state, right);
7079                 right = integral_promotion(state, right);
7080                 sign = is_signed(left->type);
7081                 op = -1;
7082                 switch(tok) {
7083                 case TOK_SLEQ:  op = OP_SL; break;
7084                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7085                 case TOK_ANDEQ: op = OP_AND; break;
7086                 case TOK_XOREQ: op = OP_XOR; break;
7087                 case TOK_OREQ:  op = OP_OR; break;
7088                 }
7089                 def = write_expr(state, left,
7090                         triple(state, op, left->type, 
7091                                 read_expr(state, left), right));
7092                 break;
7093         }
7094         return def;
7095 }
7096
7097 static struct triple *expr(struct compile_state *state)
7098 {
7099         struct triple *def;
7100         def = assignment_expr(state);
7101         while(peek(state) == TOK_COMMA) {
7102                 struct triple *left, *right;
7103                 left = def;
7104                 eat(state, TOK_COMMA);
7105                 right = assignment_expr(state);
7106                 def = triple(state, OP_COMMA, right->type, left, right);
7107         }
7108         return def;
7109 }
7110
7111 static void expr_statement(struct compile_state *state, struct triple *first)
7112 {
7113         if (peek(state) != TOK_SEMI) {
7114                 flatten(state, first, expr(state));
7115         }
7116         eat(state, TOK_SEMI);
7117 }
7118
7119 static void if_statement(struct compile_state *state, struct triple *first)
7120 {
7121         struct triple *test, *jmp1, *jmp2, *middle, *end;
7122
7123         jmp1 = jmp2 = middle = 0;
7124         eat(state, TOK_IF);
7125         eat(state, TOK_LPAREN);
7126         test = expr(state);
7127         bool(state, test);
7128         /* Cleanup and invert the test */
7129         test = lfalse_expr(state, read_expr(state, test));
7130         eat(state, TOK_RPAREN);
7131         /* Generate the needed pieces */
7132         middle = label(state);
7133         jmp1 = branch(state, middle, test);
7134         /* Thread the pieces together */
7135         flatten(state, first, test);
7136         flatten(state, first, jmp1);
7137         flatten(state, first, label(state));
7138         statement(state, first);
7139         if (peek(state) == TOK_ELSE) {
7140                 eat(state, TOK_ELSE);
7141                 /* Generate the rest of the pieces */
7142                 end = label(state);
7143                 jmp2 = branch(state, end, 0);
7144                 /* Thread them together */
7145                 flatten(state, first, jmp2);
7146                 flatten(state, first, middle);
7147                 statement(state, first);
7148                 flatten(state, first, end);
7149         }
7150         else {
7151                 flatten(state, first, middle);
7152         }
7153 }
7154
7155 static void for_statement(struct compile_state *state, struct triple *first)
7156 {
7157         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7158         struct triple *label1, *label2, *label3;
7159         struct hash_entry *ident;
7160
7161         eat(state, TOK_FOR);
7162         eat(state, TOK_LPAREN);
7163         head = test = tail = jmp1 = jmp2 = 0;
7164         if (peek(state) != TOK_SEMI) {
7165                 head = expr(state);
7166         } 
7167         eat(state, TOK_SEMI);
7168         if (peek(state) != TOK_SEMI) {
7169                 test = expr(state);
7170                 bool(state, test);
7171                 test = ltrue_expr(state, read_expr(state, test));
7172         }
7173         eat(state, TOK_SEMI);
7174         if (peek(state) != TOK_RPAREN) {
7175                 tail = expr(state);
7176         }
7177         eat(state, TOK_RPAREN);
7178         /* Generate the needed pieces */
7179         label1 = label(state);
7180         label2 = label(state);
7181         label3 = label(state);
7182         if (test) {
7183                 jmp1 = branch(state, label3, 0);
7184                 jmp2 = branch(state, label1, test);
7185         }
7186         else {
7187                 jmp2 = branch(state, label1, 0);
7188         }
7189         end = label(state);
7190         /* Remember where break and continue go */
7191         start_scope(state);
7192         ident = state->i_break;
7193         symbol(state, ident, &ident->sym_ident, end, end->type);
7194         ident = state->i_continue;
7195         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7196         /* Now include the body */
7197         flatten(state, first, head);
7198         flatten(state, first, jmp1);
7199         flatten(state, first, label1);
7200         statement(state, first);
7201         flatten(state, first, label2);
7202         flatten(state, first, tail);
7203         flatten(state, first, label3);
7204         flatten(state, first, test);
7205         flatten(state, first, jmp2);
7206         flatten(state, first, end);
7207         /* Cleanup the break/continue scope */
7208         end_scope(state);
7209 }
7210
7211 static void while_statement(struct compile_state *state, struct triple *first)
7212 {
7213         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7214         struct hash_entry *ident;
7215         eat(state, TOK_WHILE);
7216         eat(state, TOK_LPAREN);
7217         test = expr(state);
7218         bool(state, test);
7219         test = ltrue_expr(state, read_expr(state, test));
7220         eat(state, TOK_RPAREN);
7221         /* Generate the needed pieces */
7222         label1 = label(state);
7223         label2 = label(state);
7224         jmp1 = branch(state, label2, 0);
7225         jmp2 = branch(state, label1, test);
7226         end = label(state);
7227         /* Remember where break and continue go */
7228         start_scope(state);
7229         ident = state->i_break;
7230         symbol(state, ident, &ident->sym_ident, end, end->type);
7231         ident = state->i_continue;
7232         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7233         /* Thread them together */
7234         flatten(state, first, jmp1);
7235         flatten(state, first, label1);
7236         statement(state, first);
7237         flatten(state, first, label2);
7238         flatten(state, first, test);
7239         flatten(state, first, jmp2);
7240         flatten(state, first, end);
7241         /* Cleanup the break/continue scope */
7242         end_scope(state);
7243 }
7244
7245 static void do_statement(struct compile_state *state, struct triple *first)
7246 {
7247         struct triple *label1, *label2, *test, *end;
7248         struct hash_entry *ident;
7249         eat(state, TOK_DO);
7250         /* Generate the needed pieces */
7251         label1 = label(state);
7252         label2 = label(state);
7253         end = label(state);
7254         /* Remember where break and continue go */
7255         start_scope(state);
7256         ident = state->i_break;
7257         symbol(state, ident, &ident->sym_ident, end, end->type);
7258         ident = state->i_continue;
7259         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7260         /* Now include the body */
7261         flatten(state, first, label1);
7262         statement(state, first);
7263         /* Cleanup the break/continue scope */
7264         end_scope(state);
7265         /* Eat the rest of the loop */
7266         eat(state, TOK_WHILE);
7267         eat(state, TOK_LPAREN);
7268         test = read_expr(state, expr(state));
7269         bool(state, test);
7270         eat(state, TOK_RPAREN);
7271         eat(state, TOK_SEMI);
7272         /* Thread the pieces together */
7273         test = ltrue_expr(state, test);
7274         flatten(state, first, label2);
7275         flatten(state, first, test);
7276         flatten(state, first, branch(state, label1, test));
7277         flatten(state, first, end);
7278 }
7279
7280
7281 static void return_statement(struct compile_state *state, struct triple *first)
7282 {
7283         struct triple *jmp, *mv, *dest, *var, *val;
7284         int last;
7285         eat(state, TOK_RETURN);
7286
7287 #warning "FIXME implement a more general excess branch elimination"
7288         val = 0;
7289         /* If we have a return value do some more work */
7290         if (peek(state) != TOK_SEMI) {
7291                 val = read_expr(state, expr(state));
7292         }
7293         eat(state, TOK_SEMI);
7294
7295         /* See if this last statement in a function */
7296         last = ((peek(state) == TOK_RBRACE) && 
7297                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7298
7299         /* Find the return variable */
7300         var = MISC(state->main_function, 0);
7301         /* Find the return destination */
7302         dest = RHS(state->main_function, 0)->prev;
7303         mv = jmp = 0;
7304         /* If needed generate a jump instruction */
7305         if (!last) {
7306                 jmp = branch(state, dest, 0);
7307         }
7308         /* If needed generate an assignment instruction */
7309         if (val) {
7310                 mv = write_expr(state, var, val);
7311         }
7312         /* Now put the code together */
7313         if (mv) {
7314                 flatten(state, first, mv);
7315                 flatten(state, first, jmp);
7316         }
7317         else if (jmp) {
7318                 flatten(state, first, jmp);
7319         }
7320 }
7321
7322 static void break_statement(struct compile_state *state, struct triple *first)
7323 {
7324         struct triple *dest;
7325         eat(state, TOK_BREAK);
7326         eat(state, TOK_SEMI);
7327         if (!state->i_break->sym_ident) {
7328                 error(state, 0, "break statement not within loop or switch");
7329         }
7330         dest = state->i_break->sym_ident->def;
7331         flatten(state, first, branch(state, dest, 0));
7332 }
7333
7334 static void continue_statement(struct compile_state *state, struct triple *first)
7335 {
7336         struct triple *dest;
7337         eat(state, TOK_CONTINUE);
7338         eat(state, TOK_SEMI);
7339         if (!state->i_continue->sym_ident) {
7340                 error(state, 0, "continue statement outside of a loop");
7341         }
7342         dest = state->i_continue->sym_ident->def;
7343         flatten(state, first, branch(state, dest, 0));
7344 }
7345
7346 static void goto_statement(struct compile_state *state, struct triple *first)
7347 {
7348         FINISHME();
7349         eat(state, TOK_GOTO);
7350         eat(state, TOK_IDENT);
7351         eat(state, TOK_SEMI);
7352         error(state, 0, "goto is not implemeted");
7353         FINISHME();
7354 }
7355
7356 static void labeled_statement(struct compile_state *state, struct triple *first)
7357 {
7358         FINISHME();
7359         eat(state, TOK_IDENT);
7360         eat(state, TOK_COLON);
7361         statement(state, first);
7362         error(state, 0, "labeled statements are not implemented");
7363         FINISHME();
7364 }
7365
7366 static void switch_statement(struct compile_state *state, struct triple *first)
7367 {
7368         FINISHME();
7369         eat(state, TOK_SWITCH);
7370         eat(state, TOK_LPAREN);
7371         expr(state);
7372         eat(state, TOK_RPAREN);
7373         statement(state, first);
7374         error(state, 0, "switch statements are not implemented");
7375         FINISHME();
7376 }
7377
7378 static void case_statement(struct compile_state *state, struct triple *first)
7379 {
7380         FINISHME();
7381         eat(state, TOK_CASE);
7382         constant_expr(state);
7383         eat(state, TOK_COLON);
7384         statement(state, first);
7385         error(state, 0, "case statements are not implemented");
7386         FINISHME();
7387 }
7388
7389 static void default_statement(struct compile_state *state, struct triple *first)
7390 {
7391         FINISHME();
7392         eat(state, TOK_DEFAULT);
7393         eat(state, TOK_COLON);
7394         statement(state, first);
7395         error(state, 0, "default statements are not implemented");
7396         FINISHME();
7397 }
7398
7399 static void asm_statement(struct compile_state *state, struct triple *first)
7400 {
7401         FINISHME();
7402         error(state, 0, "FIXME finish asm_statement");
7403 }
7404
7405
7406 static int isdecl(int tok)
7407 {
7408         switch(tok) {
7409         case TOK_AUTO:
7410         case TOK_REGISTER:
7411         case TOK_STATIC:
7412         case TOK_EXTERN:
7413         case TOK_TYPEDEF:
7414         case TOK_CONST:
7415         case TOK_RESTRICT:
7416         case TOK_VOLATILE:
7417         case TOK_VOID:
7418         case TOK_CHAR:
7419         case TOK_SHORT:
7420         case TOK_INT:
7421         case TOK_LONG:
7422         case TOK_FLOAT:
7423         case TOK_DOUBLE:
7424         case TOK_SIGNED:
7425         case TOK_UNSIGNED:
7426         case TOK_STRUCT:
7427         case TOK_UNION:
7428         case TOK_ENUM:
7429         case TOK_TYPE_NAME: /* typedef name */
7430                 return 1;
7431         default:
7432                 return 0;
7433         }
7434 }
7435
7436 static void compound_statement(struct compile_state *state, struct triple *first)
7437 {
7438         eat(state, TOK_LBRACE);
7439         start_scope(state);
7440
7441         /* statement-list opt */
7442         while (peek(state) != TOK_RBRACE) {
7443                 statement(state, first);
7444         }
7445         end_scope(state);
7446         eat(state, TOK_RBRACE);
7447 }
7448
7449 static void statement(struct compile_state *state, struct triple *first)
7450 {
7451         int tok;
7452         tok = peek(state);
7453         if (tok == TOK_LBRACE) {
7454                 compound_statement(state, first);
7455         }
7456         else if (tok == TOK_IF) {
7457                 if_statement(state, first); 
7458         }
7459         else if (tok == TOK_FOR) {
7460                 for_statement(state, first);
7461         }
7462         else if (tok == TOK_WHILE) {
7463                 while_statement(state, first);
7464         }
7465         else if (tok == TOK_DO) {
7466                 do_statement(state, first);
7467         }
7468         else if (tok == TOK_RETURN) {
7469                 return_statement(state, first);
7470         }
7471         else if (tok == TOK_BREAK) {
7472                 break_statement(state, first);
7473         }
7474         else if (tok == TOK_CONTINUE) {
7475                 continue_statement(state, first);
7476         }
7477         else if (tok == TOK_GOTO) {
7478                 goto_statement(state, first);
7479         }
7480         else if (tok == TOK_SWITCH) {
7481                 switch_statement(state, first);
7482         }
7483         else if (tok == TOK_ASM) {
7484                 asm_statement(state, first);
7485         }
7486         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7487                 labeled_statement(state, first); 
7488         }
7489         else if (tok == TOK_CASE) {
7490                 case_statement(state, first);
7491         }
7492         else if (tok == TOK_DEFAULT) {
7493                 default_statement(state, first);
7494         }
7495         else if (isdecl(tok)) {
7496                 /* This handles C99 intermixing of statements and decls */
7497                 decl(state, first);
7498         }
7499         else {
7500                 expr_statement(state, first);
7501         }
7502 }
7503
7504 static struct type *param_decl(struct compile_state *state)
7505 {
7506         struct type *type;
7507         struct hash_entry *ident;
7508         /* Cheat so the declarator will know we are not global */
7509         start_scope(state); 
7510         ident = 0;
7511         type = decl_specifiers(state);
7512         type = declarator(state, type, &ident, 0);
7513         type->field_ident = ident;
7514         end_scope(state);
7515         return type;
7516 }
7517
7518 static struct type *param_type_list(struct compile_state *state, struct type *type)
7519 {
7520         struct type *ftype, **next;
7521         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7522         next = &ftype->right;
7523         while(peek(state) == TOK_COMMA) {
7524                 eat(state, TOK_COMMA);
7525                 if (peek(state) == TOK_DOTS) {
7526                         eat(state, TOK_DOTS);
7527                         error(state, 0, "variadic functions not supported");
7528                 }
7529                 else {
7530                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7531                         next = &((*next)->right);
7532                 }
7533         }
7534         return ftype;
7535 }
7536
7537
7538 static struct type *type_name(struct compile_state *state)
7539 {
7540         struct type *type;
7541         type = specifier_qualifier_list(state);
7542         /* abstract-declarator (may consume no tokens) */
7543         type = declarator(state, type, 0, 0);
7544         return type;
7545 }
7546
7547 static struct type *direct_declarator(
7548         struct compile_state *state, struct type *type, 
7549         struct hash_entry **ident, int need_ident)
7550 {
7551         struct type *outer;
7552         int op;
7553         outer = 0;
7554         arrays_complete(state, type);
7555         switch(peek(state)) {
7556         case TOK_IDENT:
7557                 eat(state, TOK_IDENT);
7558                 if (!ident) {
7559                         error(state, 0, "Unexpected identifier found");
7560                 }
7561                 /* The name of what we are declaring */
7562                 *ident = state->token[0].ident;
7563                 break;
7564         case TOK_LPAREN:
7565                 eat(state, TOK_LPAREN);
7566                 outer = declarator(state, type, ident, need_ident);
7567                 eat(state, TOK_RPAREN);
7568                 break;
7569         default:
7570                 if (need_ident) {
7571                         error(state, 0, "Identifier expected");
7572                 }
7573                 break;
7574         }
7575         do {
7576                 op = 1;
7577                 arrays_complete(state, type);
7578                 switch(peek(state)) {
7579                 case TOK_LPAREN:
7580                         eat(state, TOK_LPAREN);
7581                         type = param_type_list(state, type);
7582                         eat(state, TOK_RPAREN);
7583                         break;
7584                 case TOK_LBRACKET:
7585                 {
7586                         unsigned int qualifiers;
7587                         struct triple *value;
7588                         value = 0;
7589                         eat(state, TOK_LBRACKET);
7590                         if (peek(state) != TOK_RBRACKET) {
7591                                 value = constant_expr(state);
7592                                 integral(state, value);
7593                         }
7594                         eat(state, TOK_RBRACKET);
7595
7596                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
7597                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
7598                         if (value) {
7599                                 type->elements = value->u.cval;
7600                                 free_triple(state, value);
7601                         } else {
7602                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
7603                                 op = 0;
7604                         }
7605                 }
7606                         break;
7607                 default:
7608                         op = 0;
7609                         break;
7610                 }
7611         } while(op);
7612         if (outer) {
7613                 struct type *inner;
7614                 arrays_complete(state, type);
7615                 FINISHME();
7616                 for(inner = outer; inner->left; inner = inner->left)
7617                         ;
7618                 inner->left = type;
7619                 type = outer;
7620         }
7621         return type;
7622 }
7623
7624 static struct type *declarator(
7625         struct compile_state *state, struct type *type, 
7626         struct hash_entry **ident, int need_ident)
7627 {
7628         while(peek(state) == TOK_STAR) {
7629                 eat(state, TOK_STAR);
7630                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
7631         }
7632         type = direct_declarator(state, type, ident, need_ident);
7633         return type;
7634 }
7635
7636
7637 static struct type *typedef_name(
7638         struct compile_state *state, unsigned int specifiers)
7639 {
7640         struct hash_entry *ident;
7641         struct type *type;
7642         eat(state, TOK_TYPE_NAME);
7643         ident = state->token[0].ident;
7644         type = ident->sym_ident->type;
7645         specifiers |= type->type & QUAL_MASK;
7646         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
7647                 (type->type & (STOR_MASK | QUAL_MASK))) {
7648                 type = clone_type(specifiers, type);
7649         }
7650         return type;
7651 }
7652
7653 static struct type *enum_specifier(
7654         struct compile_state *state, unsigned int specifiers)
7655 {
7656         int tok;
7657         struct type *type;
7658         type = 0;
7659         FINISHME();
7660         eat(state, TOK_ENUM);
7661         tok = peek(state);
7662         if (tok == TOK_IDENT) {
7663                 eat(state, TOK_IDENT);
7664         }
7665         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
7666                 eat(state, TOK_LBRACE);
7667                 do {
7668                         eat(state, TOK_IDENT);
7669                         if (peek(state) == TOK_EQ) {
7670                                 eat(state, TOK_EQ);
7671                                 constant_expr(state);
7672                         }
7673                         if (peek(state) == TOK_COMMA) {
7674                                 eat(state, TOK_COMMA);
7675                         }
7676                 } while(peek(state) != TOK_RBRACE);
7677                 eat(state, TOK_RBRACE);
7678         }
7679         FINISHME();
7680         return type;
7681 }
7682
7683 #if 0
7684 static struct type *struct_declarator(
7685         struct compile_state *state, struct type *type, struct hash_entry **ident)
7686 {
7687         int tok;
7688 #warning "struct_declarator is complicated because of bitfields, kill them?"
7689         tok = peek(state);
7690         if (tok != TOK_COLON) {
7691                 type = declarator(state, type, ident, 1);
7692         }
7693         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
7694                 eat(state, TOK_COLON);
7695                 constant_expr(state);
7696         }
7697         FINISHME();
7698         return type;
7699 }
7700 #endif
7701
7702 static struct type *struct_or_union_specifier(
7703         struct compile_state *state, unsigned int specifiers)
7704 {
7705         struct type *struct_type;
7706         struct hash_entry *ident;
7707         unsigned int type_join;
7708         int tok;
7709         struct_type = 0;
7710         ident = 0;
7711         switch(peek(state)) {
7712         case TOK_STRUCT:
7713                 eat(state, TOK_STRUCT);
7714                 type_join = TYPE_PRODUCT;
7715                 break;
7716         case TOK_UNION:
7717                 eat(state, TOK_UNION);
7718                 type_join = TYPE_OVERLAP;
7719                 error(state, 0, "unions not yet supported\n");
7720                 break;
7721         default:
7722                 eat(state, TOK_STRUCT);
7723                 type_join = TYPE_PRODUCT;
7724                 break;
7725         }
7726         tok = peek(state);
7727         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
7728                 eat(state, tok);
7729                 ident = state->token[0].ident;
7730         }
7731         if (!ident || (peek(state) == TOK_LBRACE)) {
7732                 ulong_t elements;
7733                 elements = 0;
7734                 eat(state, TOK_LBRACE);
7735                 do {
7736                         struct type *base_type;
7737                         struct type **next;
7738                         int done;
7739                         base_type = specifier_qualifier_list(state);
7740                         next = &struct_type;
7741                         do {
7742                                 struct type *type;
7743                                 struct hash_entry *fident;
7744                                 done = 1;
7745                                 type = declarator(state, base_type, &fident, 1);
7746                                 elements++;
7747                                 if (peek(state) == TOK_COMMA) {
7748                                         done = 0;
7749                                         eat(state, TOK_COMMA);
7750                                 }
7751                                 type = clone_type(0, type);
7752                                 type->field_ident = fident;
7753                                 if (*next) {
7754                                         *next = new_type(type_join, *next, type);
7755                                         next = &((*next)->right);
7756                                 } else {
7757                                         *next = type;
7758                                 }
7759                         } while(!done);
7760                         eat(state, TOK_SEMI);
7761                 } while(peek(state) != TOK_RBRACE);
7762                 eat(state, TOK_RBRACE);
7763                 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
7764                 struct_type->type_ident = ident;
7765                 struct_type->elements = elements;
7766                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
7767         }
7768         if (ident && ident->sym_struct) {
7769                 struct_type = ident->sym_struct->type;
7770         }
7771         else if (ident && !ident->sym_struct) {
7772                 error(state, 0, "struct %s undeclared", ident->name);
7773         }
7774         return struct_type;
7775 }
7776
7777 static unsigned int storage_class_specifier_opt(struct compile_state *state)
7778 {
7779         unsigned int specifiers;
7780         switch(peek(state)) {
7781         case TOK_AUTO:
7782                 eat(state, TOK_AUTO);
7783                 specifiers = STOR_AUTO;
7784                 break;
7785         case TOK_REGISTER:
7786                 eat(state, TOK_REGISTER);
7787                 specifiers = STOR_REGISTER;
7788                 break;
7789         case TOK_STATIC:
7790                 eat(state, TOK_STATIC);
7791                 specifiers = STOR_STATIC;
7792                 break;
7793         case TOK_EXTERN:
7794                 eat(state, TOK_EXTERN);
7795                 specifiers = STOR_EXTERN;
7796                 break;
7797         case TOK_TYPEDEF:
7798                 eat(state, TOK_TYPEDEF);
7799                 specifiers = STOR_TYPEDEF;
7800                 break;
7801         default:
7802                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
7803                         specifiers = STOR_STATIC;
7804                 }
7805                 else {
7806                         specifiers = STOR_AUTO;
7807                 }
7808         }
7809         return specifiers;
7810 }
7811
7812 static unsigned int function_specifier_opt(struct compile_state *state)
7813 {
7814         /* Ignore the inline keyword */
7815         unsigned int specifiers;
7816         specifiers = 0;
7817         switch(peek(state)) {
7818         case TOK_INLINE:
7819                 eat(state, TOK_INLINE);
7820                 specifiers = STOR_INLINE;
7821         }
7822         return specifiers;
7823 }
7824
7825 static unsigned int type_qualifiers(struct compile_state *state)
7826 {
7827         unsigned int specifiers;
7828         int done;
7829         done = 0;
7830         specifiers = QUAL_NONE;
7831         do {
7832                 switch(peek(state)) {
7833                 case TOK_CONST:
7834                         eat(state, TOK_CONST);
7835                         specifiers = QUAL_CONST;
7836                         break;
7837                 case TOK_VOLATILE:
7838                         eat(state, TOK_VOLATILE);
7839                         specifiers = QUAL_VOLATILE;
7840                         break;
7841                 case TOK_RESTRICT:
7842                         eat(state, TOK_RESTRICT);
7843                         specifiers = QUAL_RESTRICT;
7844                         break;
7845                 default:
7846                         done = 1;
7847                         break;
7848                 }
7849         } while(!done);
7850         return specifiers;
7851 }
7852
7853 static struct type *type_specifier(
7854         struct compile_state *state, unsigned int spec)
7855 {
7856         struct type *type;
7857         type = 0;
7858         switch(peek(state)) {
7859         case TOK_VOID:
7860                 eat(state, TOK_VOID);
7861                 type = new_type(TYPE_VOID | spec, 0, 0);
7862                 break;
7863         case TOK_CHAR:
7864                 eat(state, TOK_CHAR);
7865                 type = new_type(TYPE_CHAR | spec, 0, 0);
7866                 break;
7867         case TOK_SHORT:
7868                 eat(state, TOK_SHORT);
7869                 if (peek(state) == TOK_INT) {
7870                         eat(state, TOK_INT);
7871                 }
7872                 type = new_type(TYPE_SHORT | spec, 0, 0);
7873                 break;
7874         case TOK_INT:
7875                 eat(state, TOK_INT);
7876                 type = new_type(TYPE_INT | spec, 0, 0);
7877                 break;
7878         case TOK_LONG:
7879                 eat(state, TOK_LONG);
7880                 switch(peek(state)) {
7881                 case TOK_LONG:
7882                         eat(state, TOK_LONG);
7883                         error(state, 0, "long long not supported");
7884                         break;
7885                 case TOK_DOUBLE:
7886                         eat(state, TOK_DOUBLE);
7887                         error(state, 0, "long double not supported");
7888                         break;
7889                 case TOK_INT:
7890                         eat(state, TOK_INT);
7891                         type = new_type(TYPE_LONG | spec, 0, 0);
7892                         break;
7893                 default:
7894                         type = new_type(TYPE_LONG | spec, 0, 0);
7895                         break;
7896                 }
7897                 break;
7898         case TOK_FLOAT:
7899                 eat(state, TOK_FLOAT);
7900                 error(state, 0, "type float not supported");
7901                 break;
7902         case TOK_DOUBLE:
7903                 eat(state, TOK_DOUBLE);
7904                 error(state, 0, "type double not supported");
7905                 break;
7906         case TOK_SIGNED:
7907                 eat(state, TOK_SIGNED);
7908                 switch(peek(state)) {
7909                 case TOK_LONG:
7910                         eat(state, TOK_LONG);
7911                         switch(peek(state)) {
7912                         case TOK_LONG:
7913                                 eat(state, TOK_LONG);
7914                                 error(state, 0, "type long long not supported");
7915                                 break;
7916                         case TOK_INT:
7917                                 eat(state, TOK_INT);
7918                                 type = new_type(TYPE_LONG | spec, 0, 0);
7919                                 break;
7920                         default:
7921                                 type = new_type(TYPE_LONG | spec, 0, 0);
7922                                 break;
7923                         }
7924                         break;
7925                 case TOK_INT:
7926                         eat(state, TOK_INT);
7927                         type = new_type(TYPE_INT | spec, 0, 0);
7928                         break;
7929                 case TOK_SHORT:
7930                         eat(state, TOK_SHORT);
7931                         type = new_type(TYPE_SHORT | spec, 0, 0);
7932                         break;
7933                 case TOK_CHAR:
7934                         eat(state, TOK_CHAR);
7935                         type = new_type(TYPE_CHAR | spec, 0, 0);
7936                         break;
7937                 default:
7938                         type = new_type(TYPE_INT | spec, 0, 0);
7939                         break;
7940                 }
7941                 break;
7942         case TOK_UNSIGNED:
7943                 eat(state, TOK_UNSIGNED);
7944                 switch(peek(state)) {
7945                 case TOK_LONG:
7946                         eat(state, TOK_LONG);
7947                         switch(peek(state)) {
7948                         case TOK_LONG:
7949                                 eat(state, TOK_LONG);
7950                                 error(state, 0, "unsigned long long not supported");
7951                                 break;
7952                         case TOK_INT:
7953                                 eat(state, TOK_INT);
7954                                 type = new_type(TYPE_ULONG | spec, 0, 0);
7955                                 break;
7956                         default:
7957                                 type = new_type(TYPE_ULONG | spec, 0, 0);
7958                                 break;
7959                         }
7960                         break;
7961                 case TOK_INT:
7962                         eat(state, TOK_INT);
7963                         type = new_type(TYPE_UINT | spec, 0, 0);
7964                         break;
7965                 case TOK_SHORT:
7966                         eat(state, TOK_SHORT);
7967                         type = new_type(TYPE_USHORT | spec, 0, 0);
7968                         break;
7969                 case TOK_CHAR:
7970                         eat(state, TOK_CHAR);
7971                         type = new_type(TYPE_UCHAR | spec, 0, 0);
7972                         break;
7973                 default:
7974                         type = new_type(TYPE_UINT | spec, 0, 0);
7975                         break;
7976                 }
7977                 break;
7978                 /* struct or union specifier */
7979         case TOK_STRUCT:
7980         case TOK_UNION:
7981                 type = struct_or_union_specifier(state, spec);
7982                 break;
7983                 /* enum-spefifier */
7984         case TOK_ENUM:
7985                 type = enum_specifier(state, spec);
7986                 break;
7987                 /* typedef name */
7988         case TOK_TYPE_NAME:
7989                 type = typedef_name(state, spec);
7990                 break;
7991         default:
7992                 error(state, 0, "bad type specifier %s", 
7993                         tokens[peek(state)]);
7994                 break;
7995         }
7996         return type;
7997 }
7998
7999 static int istype(int tok)
8000 {
8001         switch(tok) {
8002         case TOK_CONST:
8003         case TOK_RESTRICT:
8004         case TOK_VOLATILE:
8005         case TOK_VOID:
8006         case TOK_CHAR:
8007         case TOK_SHORT:
8008         case TOK_INT:
8009         case TOK_LONG:
8010         case TOK_FLOAT:
8011         case TOK_DOUBLE:
8012         case TOK_SIGNED:
8013         case TOK_UNSIGNED:
8014         case TOK_STRUCT:
8015         case TOK_UNION:
8016         case TOK_ENUM:
8017         case TOK_TYPE_NAME:
8018                 return 1;
8019         default:
8020                 return 0;
8021         }
8022 }
8023
8024
8025 static struct type *specifier_qualifier_list(struct compile_state *state)
8026 {
8027         struct type *type;
8028         unsigned int specifiers = 0;
8029
8030         /* type qualifiers */
8031         specifiers |= type_qualifiers(state);
8032
8033         /* type specifier */
8034         type = type_specifier(state, specifiers);
8035
8036         return type;
8037 }
8038
8039 static int isdecl_specifier(int tok)
8040 {
8041         switch(tok) {
8042                 /* storage class specifier */
8043         case TOK_AUTO:
8044         case TOK_REGISTER:
8045         case TOK_STATIC:
8046         case TOK_EXTERN:
8047         case TOK_TYPEDEF:
8048                 /* type qualifier */
8049         case TOK_CONST:
8050         case TOK_RESTRICT:
8051         case TOK_VOLATILE:
8052                 /* type specifiers */
8053         case TOK_VOID:
8054         case TOK_CHAR:
8055         case TOK_SHORT:
8056         case TOK_INT:
8057         case TOK_LONG:
8058         case TOK_FLOAT:
8059         case TOK_DOUBLE:
8060         case TOK_SIGNED:
8061         case TOK_UNSIGNED:
8062                 /* struct or union specifier */
8063         case TOK_STRUCT:
8064         case TOK_UNION:
8065                 /* enum-spefifier */
8066         case TOK_ENUM:
8067                 /* typedef name */
8068         case TOK_TYPE_NAME:
8069                 /* function specifiers */
8070         case TOK_INLINE:
8071                 return 1;
8072         default:
8073                 return 0;
8074         }
8075 }
8076
8077 static struct type *decl_specifiers(struct compile_state *state)
8078 {
8079         struct type *type;
8080         unsigned int specifiers;
8081         /* I am overly restrictive in the arragement of specifiers supported.
8082          * C is overly flexible in this department it makes interpreting
8083          * the parse tree difficult.
8084          */
8085         specifiers = 0;
8086
8087         /* storage class specifier */
8088         specifiers |= storage_class_specifier_opt(state);
8089
8090         /* function-specifier */
8091         specifiers |= function_specifier_opt(state);
8092
8093         /* type qualifier */
8094         specifiers |= type_qualifiers(state);
8095
8096         /* type specifier */
8097         type = type_specifier(state, specifiers);
8098         return type;
8099 }
8100
8101 static unsigned designator(struct compile_state *state)
8102 {
8103         int tok;
8104         unsigned index;
8105         index = -1U;
8106         do {
8107                 switch(peek(state)) {
8108                 case TOK_LBRACKET:
8109                 {
8110                         struct triple *value;
8111                         eat(state, TOK_LBRACKET);
8112                         value = constant_expr(state);
8113                         eat(state, TOK_RBRACKET);
8114                         index = value->u.cval;
8115                         break;
8116                 }
8117                 case TOK_DOT:
8118                         eat(state, TOK_DOT);
8119                         eat(state, TOK_IDENT);
8120                         error(state, 0, "Struct Designators not currently supported");
8121                         break;
8122                 default:
8123                         error(state, 0, "Invalid designator");
8124                 }
8125                 tok = peek(state);
8126         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8127         eat(state, TOK_EQ);
8128         return index;
8129 }
8130
8131 static struct triple *initializer(
8132         struct compile_state *state, struct type *type)
8133 {
8134         struct triple *result;
8135         if (peek(state) != TOK_LBRACE) {
8136                 result = assignment_expr(state);
8137         }
8138         else {
8139                 int comma;
8140                 unsigned index, max_index;
8141                 void *buf;
8142                 max_index = index = 0;
8143                 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8144                         max_index = type->elements;
8145                         if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8146                                 type->elements = 0;
8147                         }
8148                 } else {
8149                         error(state, 0, "Struct initializers not currently supported");
8150                 }
8151                 buf = xcmalloc(size_of(state, type), "initializer");
8152                 eat(state, TOK_LBRACE);
8153                 do {
8154                         struct triple *value;
8155                         struct type *value_type;
8156                         size_t value_size;
8157                         int tok;
8158                         comma = 0;
8159                         tok = peek(state);
8160                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8161                                 index = designator(state);
8162                         }
8163                         if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8164                                 (index > max_index)) {
8165                                 error(state, 0, "element beyond bounds");
8166                         }
8167                         value_type = 0;
8168                         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8169                                 value_type = type->left;
8170                         }
8171                         value = eval_const_expr(state, initializer(state, value_type));
8172                         value_size = size_of(state, value_type);
8173                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8174                                 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8175                                 (type->elements <= index)) {
8176                                 void *old_buf;
8177                                 size_t old_size;
8178                                 old_buf = buf;
8179                                 old_size = size_of(state, type);
8180                                 type->elements = index + 1;
8181                                 buf = xmalloc(size_of(state, type), "initializer");
8182                                 memcpy(buf, old_buf, old_size);
8183                                 xfree(old_buf);
8184                         }
8185                         if (value->op == OP_BLOBCONST) {
8186                                 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8187                         }
8188                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8189                                 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8190                         }
8191                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8192                                 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8193                         }
8194                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8195                                 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8196                         }
8197                         else {
8198                                 fprintf(stderr, "%d %d\n",
8199                                         value->op, value_size);
8200                                 internal_error(state, 0, "unhandled constant initializer");
8201                         }
8202                         if (peek(state) == TOK_COMMA) {
8203                                 eat(state, TOK_COMMA);
8204                                 comma = 1;
8205                         }
8206                         index += 1;
8207                 } while(comma && (peek(state) != TOK_RBRACE));
8208                 eat(state, TOK_RBRACE);
8209                 result = triple(state, OP_BLOBCONST, type, 0, 0);
8210                 result->u.blob = buf;
8211         }
8212         return result;
8213 }
8214
8215 static struct triple *function_definition(
8216         struct compile_state *state, struct type *type)
8217 {
8218         struct triple *def, *tmp, *first, *end;
8219         struct hash_entry *ident;
8220         struct type *param;
8221         int i;
8222         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8223                 error(state, 0, "Invalid function header");
8224         }
8225
8226         /* Verify the function type */
8227         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
8228                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8229                 (type->right->field_ident == 0)) {
8230                 error(state, 0, "Invalid function parameters");
8231         }
8232         param = type->right;
8233         i = 0;
8234         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8235                 i++;
8236                 if (!param->left->field_ident) {
8237                         error(state, 0, "No identifier for parameter %d\n", i);
8238                 }
8239                 param = param->right;
8240         }
8241         i++;
8242         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8243                 error(state, 0, "No identifier for paramter %d\n", i);
8244         }
8245         
8246         /* Get a list of statements for this function. */
8247         def = triple(state, OP_LIST, type, 0, 0);
8248
8249         /* Start a new scope for the passed parameters */
8250         start_scope(state);
8251
8252         /* Put a label at the very start of a function */
8253         first = label(state);
8254         RHS(def, 0) = first;
8255
8256         /* Put a label at the very end of a function */
8257         end = label(state);
8258         flatten(state, first, end);
8259
8260         /* Walk through the parameters and create symbol table entries
8261          * for them.
8262          */
8263         param = type->right;
8264         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8265                 ident = param->left->field_ident;
8266                 tmp = variable(state, param->left);
8267                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8268                 flatten(state, end, tmp);
8269                 param = param->right;
8270         }
8271         if ((param->type & TYPE_MASK) != TYPE_VOID) {
8272                 /* And don't forget the last parameter */
8273                 ident = param->field_ident;
8274                 tmp = variable(state, param);
8275                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8276                 flatten(state, end, tmp);
8277         }
8278         /* Add a variable for the return value */
8279         MISC(def, 0) = 0;
8280         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8281                 /* Remove all type qualifiers from the return type */
8282                 tmp = variable(state, clone_type(0, type->left));
8283                 flatten(state, end, tmp);
8284                 /* Remember where the return value is */
8285                 MISC(def, 0) = tmp;
8286         }
8287
8288         /* Remember which function I am compiling.
8289          * Also assume the last defined function is the main function.
8290          */
8291         state->main_function = def;
8292
8293         /* Now get the actual function definition */
8294         compound_statement(state, end);
8295
8296         /* Remove the parameter scope */
8297         end_scope(state);
8298 #if 0
8299         fprintf(stdout, "\n");
8300         loc(stdout, state, 0);
8301         fprintf(stdout, "\n__________ function_definition _________\n");
8302         print_triple(state, def);
8303         fprintf(stdout, "__________ function_definition _________ done\n\n");
8304 #endif
8305
8306         return def;
8307 }
8308
8309 static struct triple *do_decl(struct compile_state *state, 
8310         struct type *type, struct hash_entry *ident)
8311 {
8312         struct triple *def;
8313         def = 0;
8314         /* Clean up the storage types used */
8315         switch (type->type & STOR_MASK) {
8316         case STOR_AUTO:
8317         case STOR_STATIC:
8318                 /* These are the good types I am aiming for */
8319                 break;
8320         case STOR_REGISTER:
8321                 type->type &= ~STOR_MASK;
8322                 type->type |= STOR_AUTO;
8323                 break;
8324         case STOR_EXTERN:
8325                 type->type &= ~STOR_MASK;
8326                 type->type |= STOR_STATIC;
8327                 break;
8328         case STOR_TYPEDEF:
8329                 if (!ident) {
8330                         error(state, 0, "typedef without name");
8331                 }
8332                 symbol(state, ident, &ident->sym_ident, 0, type);
8333                 ident->tok = TOK_TYPE_NAME;
8334                 return 0;
8335                 break;
8336         default:
8337                 internal_error(state, 0, "Undefined storage class");
8338         }
8339         if (((type->type & STOR_MASK) == STOR_STATIC) &&
8340                 ((type->type & QUAL_CONST) == 0)) {
8341                 error(state, 0, "non const static variables not supported");
8342         }
8343         if (ident) {
8344                 def = variable(state, type);
8345                 symbol(state, ident, &ident->sym_ident, def, type);
8346         }
8347         return def;
8348 }
8349
8350 static void decl(struct compile_state *state, struct triple *first)
8351 {
8352         struct type *base_type, *type;
8353         struct hash_entry *ident;
8354         struct triple *def;
8355         int global;
8356         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8357         base_type = decl_specifiers(state);
8358         ident = 0;
8359         type = declarator(state, base_type, &ident, 0);
8360         if (global && ident && (peek(state) == TOK_LBRACE)) {
8361                 /* function */
8362                 def = function_definition(state, type);
8363                 symbol(state, ident, &ident->sym_ident, def, type);
8364         }
8365         else {
8366                 int done;
8367                 flatten(state, first, do_decl(state, type, ident));
8368                 /* type or variable definition */
8369                 do {
8370                         done = 1;
8371                         if (peek(state) == TOK_EQ) {
8372                                 if (!ident) {
8373                                         error(state, 0, "cannot assign to a type");
8374                                 }
8375                                 eat(state, TOK_EQ);
8376                                 flatten(state, first,
8377                                         init_expr(state, 
8378                                                 ident->sym_ident->def, 
8379                                                 initializer(state, type)));
8380                         }
8381                         arrays_complete(state, type);
8382                         if (peek(state) == TOK_COMMA) {
8383                                 eat(state, TOK_COMMA);
8384                                 ident = 0;
8385                                 type = declarator(state, base_type, &ident, 0);
8386                                 flatten(state, first, do_decl(state, type, ident));
8387                                 done = 0;
8388                         }
8389                 } while(!done);
8390                 eat(state, TOK_SEMI);
8391         }
8392 }
8393
8394 static void decls(struct compile_state *state)
8395 {
8396         struct triple *list;
8397         int tok;
8398         list = label(state);
8399         while(1) {
8400                 tok = peek(state);
8401                 if (tok == TOK_EOF) {
8402                         return;
8403                 }
8404                 if (tok == TOK_SPACE) {
8405                         eat(state, TOK_SPACE);
8406                 }
8407                 decl(state, list);
8408                 if (list->next != list) {
8409                         error(state, 0, "global variables not supported");
8410                 }
8411         }
8412 }
8413
8414 /*
8415  * Data structurs for optimation.
8416  */
8417
8418 static void do_use_block(
8419         struct block *used, struct block_set **head, struct block *user, 
8420         int front)
8421 {
8422         struct block_set **ptr, *new;
8423         if (!used)
8424                 return;
8425         if (!user)
8426                 return;
8427         ptr = head;
8428         while(*ptr) {
8429                 if ((*ptr)->member == user) {
8430                         return;
8431                 }
8432                 ptr = &(*ptr)->next;
8433         }
8434         new = xcmalloc(sizeof(*new), "block_set");
8435         new->member = user;
8436         if (front) {
8437                 new->next = *head;
8438                 *head = new;
8439         }
8440         else {
8441                 new->next = 0;
8442                 *ptr = new;
8443         }
8444 }
8445 static void do_unuse_block(
8446         struct block *used, struct block_set **head, struct block *unuser)
8447 {
8448         struct block_set *use, **ptr;
8449         ptr = head;
8450         while(*ptr) {
8451                 use = *ptr;
8452                 if (use->member == unuser) {
8453                         *ptr = use->next;
8454                         memset(use, -1, sizeof(*use));
8455                         xfree(use);
8456                 }
8457                 else {
8458                         ptr = &use->next;
8459                 }
8460         }
8461 }
8462
8463 static void use_block(struct block *used, struct block *user)
8464 {
8465         /* Append new to the head of the list, print_block
8466          * depends on this.
8467          */
8468         do_use_block(used, &used->use, user, 1); 
8469         used->users++;
8470 }
8471 static void unuse_block(struct block *used, struct block *unuser)
8472 {
8473         do_unuse_block(used, &used->use, unuser); 
8474         used->users--;
8475 }
8476
8477 static void idom_block(struct block *idom, struct block *user)
8478 {
8479         do_use_block(idom, &idom->idominates, user, 0);
8480 }
8481
8482 static void unidom_block(struct block *idom, struct block *unuser)
8483 {
8484         do_unuse_block(idom, &idom->idominates, unuser);
8485 }
8486
8487 static void domf_block(struct block *block, struct block *domf)
8488 {
8489         do_use_block(block, &block->domfrontier, domf, 0);
8490 }
8491
8492 static void undomf_block(struct block *block, struct block *undomf)
8493 {
8494         do_unuse_block(block, &block->domfrontier, undomf);
8495 }
8496
8497 static void ipdom_block(struct block *ipdom, struct block *user)
8498 {
8499         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8500 }
8501
8502 static void unipdom_block(struct block *ipdom, struct block *unuser)
8503 {
8504         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8505 }
8506
8507 static void ipdomf_block(struct block *block, struct block *ipdomf)
8508 {
8509         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8510 }
8511
8512 static void unipdomf_block(struct block *block, struct block *unipdomf)
8513 {
8514         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8515 }
8516
8517
8518
8519 static int do_walk_triple(struct compile_state *state,
8520         struct triple *ptr, int depth,
8521         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
8522 {
8523         int result;
8524         result = cb(state, ptr, depth);
8525         if ((result == 0) && (ptr->op == OP_LIST)) {
8526                 struct triple *list;
8527                 list = ptr;
8528                 ptr = RHS(list, 0);
8529                 do {
8530                         result = do_walk_triple(state, ptr, depth + 1, cb);
8531                         if (ptr->next->prev != ptr) {
8532                                 internal_error(state, ptr->next, "bad prev");
8533                         }
8534                         ptr = ptr->next;
8535                         
8536                 } while((result == 0) && (ptr != RHS(list, 0)));
8537         }
8538         return result;
8539 }
8540
8541 static int walk_triple(
8542         struct compile_state *state, 
8543         struct triple *ptr, 
8544         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8545 {
8546         return do_walk_triple(state, ptr, 0, cb);
8547 }
8548
8549 static void do_print_prefix(int depth)
8550 {
8551         int i;
8552         for(i = 0; i < depth; i++) {
8553                 printf("  ");
8554         }
8555 }
8556
8557 #define PRINT_LIST 1
8558 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8559 {
8560         int op;
8561         op = ins->op;
8562         if (op == OP_LIST) {
8563 #if !PRINT_LIST
8564                 return 0;
8565 #endif
8566         }
8567         if ((op == OP_LABEL) && (ins->use)) {
8568                 printf("\n%p:\n", ins);
8569         }
8570         do_print_prefix(depth);
8571         display_triple(stdout, ins);
8572
8573         if ((ins->op == OP_BRANCH) && ins->use) {
8574                 internal_error(state, ins, "branch used?");
8575         }
8576 #if 0
8577         {
8578                 struct triple_set *user;
8579                 for(user = ins->use; user; user = user->next) {
8580                         printf("use: %p\n", user->member);
8581                 }
8582         }
8583 #endif
8584         if (triple_is_branch(state, ins)) {
8585                 printf("\n");
8586         }
8587         return 0;
8588 }
8589
8590 static void print_triple(struct compile_state *state, struct triple *ins)
8591 {
8592         walk_triple(state, ins, do_print_triple);
8593 }
8594
8595 static void print_triples(struct compile_state *state)
8596 {
8597         print_triple(state, state->main_function);
8598 }
8599
8600 struct cf_block {
8601         struct block *block;
8602 };
8603 static void find_cf_blocks(struct cf_block *cf, struct block *block)
8604 {
8605         if (!block || (cf[block->vertex].block == block)) {
8606                 return;
8607         }
8608         cf[block->vertex].block = block;
8609         find_cf_blocks(cf, block->left);
8610         find_cf_blocks(cf, block->right);
8611 }
8612
8613 static void print_control_flow(struct compile_state *state)
8614 {
8615         struct cf_block *cf;
8616         int i;
8617         printf("\ncontrol flow\n");
8618         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
8619         find_cf_blocks(cf, state->first_block);
8620
8621         for(i = 1; i <= state->last_vertex; i++) {
8622                 struct block *block;
8623                 block = cf[i].block;
8624                 if (!block)
8625                         continue;
8626                 printf("(%p) %d:", block, block->vertex);
8627                 if (block->left) {
8628                         printf(" %d", block->left->vertex);
8629                 }
8630                 if (block->right && (block->right != block->left)) {
8631                         printf(" %d", block->right->vertex);
8632                 }
8633                 printf("\n");
8634         }
8635
8636         xfree(cf);
8637 }
8638
8639
8640 static struct block *basic_block(struct compile_state *state,
8641         struct triple *first)
8642 {
8643         struct block *block;
8644         struct triple *ptr;
8645         int op;
8646         if (first->op != OP_LABEL) {
8647                 internal_error(state, 0, "block does not start with a label");
8648         }
8649         /* See if this basic block has already been setup */
8650         if (first->u.block != 0) {
8651                 return first->u.block;
8652         }
8653         /* Allocate another basic block structure */
8654         state->last_vertex += 1;
8655         block = xcmalloc(sizeof(*block), "block");
8656         block->first = block->last = first;
8657         block->vertex = state->last_vertex;
8658         ptr = first;
8659         do {
8660                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
8661                         break;
8662                 }
8663                 block->last = ptr;
8664                 /* If ptr->u is not used remember where the baic block is */
8665                 if (!is_const(ptr)) {
8666                         ptr->u.block = block;
8667                 }
8668                 if (ptr->op == OP_BRANCH) {
8669                         break;
8670                 }
8671                 ptr = ptr->next;
8672         } while (ptr != RHS(state->main_function, 0));
8673         if (ptr == RHS(state->main_function, 0))
8674                 return block;
8675         op = ptr->op;
8676         if (op == OP_LABEL) {
8677                 block->left = basic_block(state, ptr);
8678                 block->right = 0;
8679                 use_block(block->left, block);
8680         }
8681         else if (op == OP_BRANCH) {
8682                 block->left = 0;
8683                 /* Trace the branch target */
8684                 block->right = basic_block(state, TARG(ptr, 0));
8685                 use_block(block->right, block);
8686                 /* If there is a test trace the branch as well */
8687                 if (TRIPLE_RHS(ptr->sizes)) {
8688                         block->left = basic_block(state, ptr->next);
8689                         use_block(block->left, block);
8690                 }
8691         }
8692         else {
8693                 internal_error(state, 0, "Bad basic block split");
8694         }
8695         return block;
8696 }
8697
8698
8699 static void walk_blocks(struct compile_state *state,
8700         void (*cb)(struct compile_state *state, struct block *block, void *arg),
8701         void *arg)
8702 {
8703         struct triple *ptr, *first;
8704         struct block *last_block;
8705         last_block = 0;
8706         first = RHS(state->main_function, 0);
8707         ptr = first;
8708         do {
8709                 struct block *block;
8710                 if (ptr->op == OP_LABEL) {
8711                         block = ptr->u.block;
8712                         if (block && (block != last_block)) {
8713                                 cb(state, block, arg);
8714                         }
8715                         last_block = block;
8716                 }
8717                 ptr = ptr->next;
8718         } while(ptr != first);
8719 }
8720
8721 static void print_block(
8722         struct compile_state *state, struct block *block, void *arg)
8723 {
8724         struct triple *ptr;
8725
8726         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
8727                 block, 
8728                 block->vertex,
8729                 block->left, 
8730                 block->left && block->left->use?block->left->use->member : 0,
8731                 block->right, 
8732                 block->right && block->right->use?block->right->use->member : 0);
8733         if (block->first->op == OP_LABEL) {
8734                 printf("%p:\n", block->first);
8735         }
8736         for(ptr = block->first; ; ptr = ptr->next) {
8737                 struct triple_set *user;
8738                 int op = ptr->op;
8739                 
8740                 if (!IS_CONST_OP(op)) {
8741                         if (ptr->u.block != block) {
8742                                 internal_error(state, ptr, 
8743                                         "Wrong block pointer: %p\n",
8744                                         ptr->u.block);
8745                         }
8746                 }
8747                 if (op == OP_ADECL) {
8748                         for(user = ptr->use; user; user = user->next) {
8749                                 if (!user->member->u.block) {
8750                                         internal_error(state, user->member, 
8751                                                 "Use %p not in a block?\n",
8752                                                 user->member);
8753                                 }
8754                         }
8755                 }
8756                 display_triple(stdout, ptr);
8757
8758                 /* Sanity checks... */
8759                 valid_ins(state, ptr);
8760                 for(user = ptr->use; user; user = user->next) {
8761                         struct triple *use;
8762                         use = user->member;
8763                         valid_ins(state, use);
8764                         if (!IS_CONST_OP(user->member->op) &&
8765                                 !user->member->u.block) {
8766                                 internal_error(state, user->member,
8767                                         "Use %p not in a block?",
8768                                         user->member);
8769                         }
8770                 }
8771
8772                 if (ptr == block->last)
8773                         break;
8774         }
8775         printf("\n");
8776 }
8777
8778
8779 static void print_blocks(struct compile_state *state)
8780 {
8781         printf("--------------- blocks ---------------\n");
8782         walk_blocks(state, print_block, 0);
8783 }
8784
8785 static void prune_nonblock_triples(struct compile_state *state)
8786 {
8787         struct block *block;
8788         struct triple *first, *ins;
8789         /* Delete the triples not in a basic block */
8790         first = RHS(state->main_function, 0);
8791         block = 0;
8792         ins = first;
8793         do {
8794                 if (ins->op == OP_LABEL) {
8795                         block = ins->u.block;
8796                 }
8797                 ins = ins->next;
8798                 if (!block) {
8799                         release_triple(state, ins->prev);
8800                 }
8801         } while(ins != first);
8802 }
8803
8804 static void setup_basic_blocks(struct compile_state *state)
8805 {
8806         /* Find the basic blocks */
8807         state->last_vertex = 0;
8808         state->first_block = basic_block(state, RHS(state->main_function,0));
8809         /* Delete the triples not in a basic block */
8810         prune_nonblock_triples(state);
8811         /* Find the last basic block */
8812         state->last_block = RHS(state->main_function, 0)->prev->u.block;
8813         if (!state->last_block) {
8814                 internal_error(state, 0, "end not used?");
8815         }
8816         /* Insert an extra unused edge from start to the end 
8817          * This helps with reverse control flow calculations.
8818          */
8819         use_block(state->first_block, state->last_block);
8820         /* If we are debugging print what I have just done */
8821         if (state->debug & DEBUG_BASIC_BLOCKS) {
8822                 print_blocks(state);
8823                 print_control_flow(state);
8824         }
8825 }
8826
8827 static void free_basic_block(struct compile_state *state, struct block *block)
8828 {
8829         struct block_set *entry, *next;
8830         struct block *child;
8831         if (!block) {
8832                 return;
8833         }
8834         if (block->vertex == -1) {
8835                 return;
8836         }
8837         block->vertex = -1;
8838         if (block->left) {
8839                 unuse_block(block->left, block);
8840         }
8841         if (block->right) {
8842                 unuse_block(block->right, block);
8843         }
8844         if (block->idom) {
8845                 unidom_block(block->idom, block);
8846         }
8847         block->idom = 0;
8848         if (block->ipdom) {
8849                 unipdom_block(block->ipdom, block);
8850         }
8851         block->ipdom = 0;
8852         for(entry = block->use; entry; entry = next) {
8853                 next = entry->next;
8854                 child = entry->member;
8855                 unuse_block(block, child);
8856                 if (child->left == block) {
8857                         child->left = 0;
8858                 }
8859                 if (child->right == block) {
8860                         child->right = 0;
8861                 }
8862         }
8863         for(entry = block->idominates; entry; entry = next) {
8864                 next = entry->next;
8865                 child = entry->member;
8866                 unidom_block(block, child);
8867                 child->idom = 0;
8868         }
8869         for(entry = block->domfrontier; entry; entry = next) {
8870                 next = entry->next;
8871                 child = entry->member;
8872                 undomf_block(block, child);
8873         }
8874         for(entry = block->ipdominates; entry; entry = next) {
8875                 next = entry->next;
8876                 child = entry->member;
8877                 unipdom_block(block, child);
8878                 child->ipdom = 0;
8879         }
8880         for(entry = block->ipdomfrontier; entry; entry = next) {
8881                 next = entry->next;
8882                 child = entry->member;
8883                 unipdomf_block(block, child);
8884         }
8885         if (block->users != 0) {
8886                 internal_error(state, 0, "block still has users");
8887         }
8888         free_basic_block(state, block->left);
8889         block->left = 0;
8890         free_basic_block(state, block->right);
8891         block->right = 0;
8892         memset(block, -1, sizeof(*block));
8893         xfree(block);
8894 }
8895
8896 static void free_basic_blocks(struct compile_state *state)
8897 {
8898         struct triple *first, *ins;
8899         free_basic_block(state, state->first_block);
8900         state->last_vertex = 0;
8901         state->first_block = state->last_block = 0;
8902         first = RHS(state->main_function, 0);
8903         ins = first;
8904         do {
8905                 if (!is_const(ins)) {
8906                         ins->u.block = 0;
8907                 }
8908                 ins = ins->next;
8909         } while(ins != first);
8910         
8911 }
8912
8913 struct sdom_block {
8914         struct block *block;
8915         struct sdom_block *sdominates;
8916         struct sdom_block *sdom_next;
8917         struct sdom_block *sdom;
8918         struct sdom_block *label;
8919         struct sdom_block *parent;
8920         struct sdom_block *ancestor;
8921         int vertex;
8922 };
8923
8924
8925 static void unsdom_block(struct sdom_block *block)
8926 {
8927         struct sdom_block **ptr;
8928         if (!block->sdom_next) {
8929                 return;
8930         }
8931         ptr = &block->sdom->sdominates;
8932         while(*ptr) {
8933                 if ((*ptr) == block) {
8934                         *ptr = block->sdom_next;
8935                         return;
8936                 }
8937                 ptr = &(*ptr)->sdom_next;
8938         }
8939 }
8940
8941 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
8942 {
8943         unsdom_block(block);
8944         block->sdom = sdom;
8945         block->sdom_next = sdom->sdominates;
8946         sdom->sdominates = block;
8947 }
8948
8949
8950
8951 static int initialize_sdblock(struct sdom_block *sd,
8952         struct block *parent, struct block *block, int vertex)
8953 {
8954         if (!block || (sd[block->vertex].block == block)) {
8955                 return vertex;
8956         }
8957         vertex += 1;
8958         /* Renumber the blocks in a convinient fashion */
8959         block->vertex = vertex;
8960         sd[vertex].block    = block;
8961         sd[vertex].sdom     = &sd[vertex];
8962         sd[vertex].label    = &sd[vertex];
8963         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
8964         sd[vertex].ancestor = 0;
8965         sd[vertex].vertex   = vertex;
8966         vertex = initialize_sdblock(sd, block, block->left, vertex);
8967         vertex = initialize_sdblock(sd, block, block->right, vertex);
8968         return vertex;
8969 }
8970
8971 static int initialize_sdpblock(struct sdom_block *sd,
8972         struct block *parent, struct block *block, int vertex)
8973 {
8974         struct block_set *user;
8975         if (!block || (sd[block->vertex].block == block)) {
8976                 return vertex;
8977         }
8978         vertex += 1;
8979         /* Renumber the blocks in a convinient fashion */
8980         block->vertex = vertex;
8981         sd[vertex].block    = block;
8982         sd[vertex].sdom     = &sd[vertex];
8983         sd[vertex].label    = &sd[vertex];
8984         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
8985         sd[vertex].ancestor = 0;
8986         sd[vertex].vertex   = vertex;
8987         for(user = block->use; user; user = user->next) {
8988                 vertex = initialize_sdpblock(sd, block, user->member, vertex);
8989         }
8990         return vertex;
8991 }
8992
8993 static void compress_ancestors(struct sdom_block *v)
8994 {
8995         /* This procedure assumes ancestor(v) != 0 */
8996         /* if (ancestor(ancestor(v)) != 0) {
8997          *      compress(ancestor(ancestor(v)));
8998          *      if (semi(label(ancestor(v))) < semi(label(v))) {
8999          *              label(v) = label(ancestor(v));
9000          *      }
9001          *      ancestor(v) = ancestor(ancestor(v));
9002          * }
9003          */
9004         if (!v->ancestor) {
9005                 return;
9006         }
9007         if (v->ancestor->ancestor) {
9008                 compress_ancestors(v->ancestor->ancestor);
9009                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9010                         v->label = v->ancestor->label;
9011                 }
9012                 v->ancestor = v->ancestor->ancestor;
9013         }
9014 }
9015
9016 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9017 {
9018         int i;
9019         /* // step 2 
9020          *  for each v <= pred(w) {
9021          *      u = EVAL(v);
9022          *      if (semi[u] < semi[w] { 
9023          *              semi[w] = semi[u]; 
9024          *      } 
9025          * }
9026          * add w to bucket(vertex(semi[w]));
9027          * LINK(parent(w), w);
9028          *
9029          * // step 3
9030          * for each v <= bucket(parent(w)) {
9031          *      delete v from bucket(parent(w));
9032          *      u = EVAL(v);
9033          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9034          * }
9035          */
9036         for(i = state->last_vertex; i >= 2; i--) {
9037                 struct sdom_block *v, *parent, *next;
9038                 struct block_set *user;
9039                 struct block *block;
9040                 block = sd[i].block;
9041                 parent = sd[i].parent;
9042                 /* Step 2 */
9043                 for(user = block->use; user; user = user->next) {
9044                         struct sdom_block *v, *u;
9045                         v = &sd[user->member->vertex];
9046                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9047                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9048                                 sd[i].sdom = u->sdom;
9049                         }
9050                 }
9051                 sdom_block(sd[i].sdom, &sd[i]);
9052                 sd[i].ancestor = parent;
9053                 /* Step 3 */
9054                 for(v = parent->sdominates; v; v = next) {
9055                         struct sdom_block *u;
9056                         next = v->sdom_next;
9057                         unsdom_block(v);
9058                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9059                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
9060                                 u->block : parent->block;
9061                 }
9062         }
9063 }
9064
9065 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9066 {
9067         int i;
9068         /* // step 2 
9069          *  for each v <= pred(w) {
9070          *      u = EVAL(v);
9071          *      if (semi[u] < semi[w] { 
9072          *              semi[w] = semi[u]; 
9073          *      } 
9074          * }
9075          * add w to bucket(vertex(semi[w]));
9076          * LINK(parent(w), w);
9077          *
9078          * // step 3
9079          * for each v <= bucket(parent(w)) {
9080          *      delete v from bucket(parent(w));
9081          *      u = EVAL(v);
9082          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9083          * }
9084          */
9085         for(i = state->last_vertex; i >= 2; i--) {
9086                 struct sdom_block *u, *v, *parent, *next;
9087                 struct block *block;
9088                 block = sd[i].block;
9089                 parent = sd[i].parent;
9090                 /* Step 2 */
9091                 if (block->left) {
9092                         v = &sd[block->left->vertex];
9093                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9094                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9095                                 sd[i].sdom = u->sdom;
9096                         }
9097                 }
9098                 if (block->right && (block->right != block->left)) {
9099                         v = &sd[block->right->vertex];
9100                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9101                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9102                                 sd[i].sdom = u->sdom;
9103                         }
9104                 }
9105                 sdom_block(sd[i].sdom, &sd[i]);
9106                 sd[i].ancestor = parent;
9107                 /* Step 3 */
9108                 for(v = parent->sdominates; v; v = next) {
9109                         struct sdom_block *u;
9110                         next = v->sdom_next;
9111                         unsdom_block(v);
9112                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9113                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
9114                                 u->block : parent->block;
9115                 }
9116         }
9117 }
9118
9119 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9120 {
9121         int i;
9122         for(i = 2; i <= state->last_vertex; i++) {
9123                 struct block *block;
9124                 block = sd[i].block;
9125                 if (block->idom->vertex != sd[i].sdom->vertex) {
9126                         block->idom = block->idom->idom;
9127                 }
9128                 idom_block(block->idom, block);
9129         }
9130         sd[1].block->idom = 0;
9131 }
9132
9133 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9134 {
9135         int i;
9136         for(i = 2; i <= state->last_vertex; i++) {
9137                 struct block *block;
9138                 block = sd[i].block;
9139                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9140                         block->ipdom = block->ipdom->ipdom;
9141                 }
9142                 ipdom_block(block->ipdom, block);
9143         }
9144         sd[1].block->ipdom = 0;
9145 }
9146
9147         /* Theorem 1:
9148          *   Every vertex of a flowgraph G = (V, E, r) except r has
9149          *   a unique immediate dominator.  
9150          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9151          *   rooted at r, called the dominator tree of G, such that 
9152          *   v dominates w if and only if v is a proper ancestor of w in
9153          *   the dominator tree.
9154          */
9155         /* Lemma 1:  
9156          *   If v and w are vertices of G such that v <= w,
9157          *   than any path from v to w must contain a common ancestor
9158          *   of v and w in T.
9159          */
9160         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
9161         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
9162         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
9163         /* Theorem 2:
9164          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
9165          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
9166          */
9167         /* Theorem 3:
9168          *   Let w != r and let u be a vertex for which sdom(u) is 
9169          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9170          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9171          */
9172         /* Lemma 5:  Let vertices v,w satisfy v -> w.
9173          *           Then v -> idom(w) or idom(w) -> idom(v)
9174          */
9175
9176 static void find_immediate_dominators(struct compile_state *state)
9177 {
9178         struct sdom_block *sd;
9179         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9180          *           vi > w for (1 <= i <= k - 1}
9181          */
9182         /* Theorem 4:
9183          *   For any vertex w != r.
9184          *   sdom(w) = min(
9185          *                 {v|(v,w) <= E  and v < w } U 
9186          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9187          */
9188         /* Corollary 1:
9189          *   Let w != r and let u be a vertex for which sdom(u) is 
9190          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9191          *   Then:
9192          *                   { sdom(w) if sdom(w) = sdom(u),
9193          *        idom(w) = {
9194          *                   { idom(u) otherwise
9195          */
9196         /* The algorithm consists of the following 4 steps.
9197          * Step 1.  Carry out a depth-first search of the problem graph.  
9198          *    Number the vertices from 1 to N as they are reached during
9199          *    the search.  Initialize the variables used in succeeding steps.
9200          * Step 2.  Compute the semidominators of all vertices by applying
9201          *    theorem 4.   Carry out the computation vertex by vertex in
9202          *    decreasing order by number.
9203          * Step 3.  Implicitly define the immediate dominator of each vertex
9204          *    by applying Corollary 1.
9205          * Step 4.  Explicitly define the immediate dominator of each vertex,
9206          *    carrying out the computation vertex by vertex in increasing order
9207          *    by number.
9208          */
9209         /* Step 1 initialize the basic block information */
9210         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9211         initialize_sdblock(sd, 0, state->first_block, 0);
9212 #if 0
9213         sd[1].size  = 0;
9214         sd[1].label = 0;
9215         sd[1].sdom  = 0;
9216 #endif
9217         /* Step 2 compute the semidominators */
9218         /* Step 3 implicitly define the immediate dominator of each vertex */
9219         compute_sdom(state, sd);
9220         /* Step 4 explicitly define the immediate dominator of each vertex */
9221         compute_idom(state, sd);
9222         xfree(sd);
9223 }
9224
9225 static void find_post_dominators(struct compile_state *state)
9226 {
9227         struct sdom_block *sd;
9228         /* Step 1 initialize the basic block information */
9229         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9230
9231         initialize_sdpblock(sd, 0, state->last_block, 0);
9232
9233         /* Step 2 compute the semidominators */
9234         /* Step 3 implicitly define the immediate dominator of each vertex */
9235         compute_spdom(state, sd);
9236         /* Step 4 explicitly define the immediate dominator of each vertex */
9237         compute_ipdom(state, sd);
9238         xfree(sd);
9239 }
9240
9241
9242
9243 static void find_block_domf(struct compile_state *state, struct block *block)
9244 {
9245         struct block *child;
9246         struct block_set *user;
9247         if (block->domfrontier != 0) {
9248                 internal_error(state, block->first, "domfrontier present?");
9249         }
9250         for(user = block->idominates; user; user = user->next) {
9251                 child = user->member;
9252                 if (child->idom != block) {
9253                         internal_error(state, block->first, "bad idom");
9254                 }
9255                 find_block_domf(state, child);
9256         }
9257         if (block->left && block->left->idom != block) {
9258                 domf_block(block, block->left);
9259         }
9260         if (block->right && block->right->idom != block) {
9261                 domf_block(block, block->right);
9262         }
9263         for(user = block->idominates; user; user = user->next) {
9264                 struct block_set *frontier;
9265                 child = user->member;
9266                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9267                         if (frontier->member->idom != block) {
9268                                 domf_block(block, frontier->member);
9269                         }
9270                 }
9271         }
9272 }
9273
9274 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9275 {
9276         struct block *child;
9277         struct block_set *user;
9278         if (block->ipdomfrontier != 0) {
9279                 internal_error(state, block->first, "ipdomfrontier present?");
9280         }
9281         for(user = block->ipdominates; user; user = user->next) {
9282                 child = user->member;
9283                 if (child->ipdom != block) {
9284                         internal_error(state, block->first, "bad ipdom");
9285                 }
9286                 find_block_ipdomf(state, child);
9287         }
9288         if (block->left && block->left->ipdom != block) {
9289                 ipdomf_block(block, block->left);
9290         }
9291         if (block->right && block->right->ipdom != block) {
9292                 ipdomf_block(block, block->right);
9293         }
9294         for(user = block->idominates; user; user = user->next) {
9295                 struct block_set *frontier;
9296                 child = user->member;
9297                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9298                         if (frontier->member->ipdom != block) {
9299                                 ipdomf_block(block, frontier->member);
9300                         }
9301                 }
9302         }
9303 }
9304
9305 static int print_dominated(
9306         struct compile_state *state, struct block *block, int vertex)
9307 {
9308         struct block_set *user;
9309
9310         if (!block || (block->vertex != vertex + 1)) {
9311                 return vertex;
9312         }
9313         vertex += 1;
9314
9315         printf("%d:", block->vertex);
9316         for(user = block->idominates; user; user = user->next) {
9317                 printf(" %d", user->member->vertex);
9318                 if (user->member->idom != block) {
9319                         internal_error(state, user->member->first, "bad idom");
9320                 }
9321         }
9322         printf("\n");
9323         vertex = print_dominated(state, block->left, vertex);
9324         vertex = print_dominated(state, block->right, vertex);
9325         return vertex;
9326 }
9327
9328 static void print_dominators(struct compile_state *state)
9329 {
9330         printf("\ndominates\n");
9331         print_dominated(state, state->first_block, 0);
9332 }
9333
9334
9335 static int print_frontiers(
9336         struct compile_state *state, struct block *block, int vertex)
9337 {
9338         struct block_set *user;
9339
9340         if (!block || (block->vertex != vertex + 1)) {
9341                 return vertex;
9342         }
9343         vertex += 1;
9344
9345         printf("%d:", block->vertex);
9346         for(user = block->domfrontier; user; user = user->next) {
9347                 printf(" %d", user->member->vertex);
9348         }
9349         printf("\n");
9350
9351         vertex = print_frontiers(state, block->left, vertex);
9352         vertex = print_frontiers(state, block->right, vertex);
9353         return vertex;
9354 }
9355 static void print_dominance_frontiers(struct compile_state *state)
9356 {
9357         printf("\ndominance frontiers\n");
9358         print_frontiers(state, state->first_block, 0);
9359         
9360 }
9361
9362 static void analyze_idominators(struct compile_state *state)
9363 {
9364         /* Find the immediate dominators */
9365         find_immediate_dominators(state);
9366         /* Find the dominance frontiers */
9367         find_block_domf(state, state->first_block);
9368         /* If debuging print the print what I have just found */
9369         if (state->debug & DEBUG_FDOMINATORS) {
9370                 print_dominators(state);
9371                 print_dominance_frontiers(state);
9372                 print_control_flow(state);
9373         }
9374 }
9375
9376
9377
9378 static int print_ipdominated(
9379         struct compile_state *state, struct block *block, int vertex)
9380 {
9381         struct block_set *user;
9382
9383         if (!block || (block->vertex != vertex + 1)) {
9384                 return vertex;
9385         }
9386         vertex += 1;
9387
9388         printf("%d:", block->vertex);
9389         for(user = block->ipdominates; user; user = user->next) {
9390                 printf(" %d", user->member->vertex);
9391                 if (user->member->ipdom != block) {
9392                         internal_error(state, user->member->first, "bad ipdom");
9393                 }
9394         }
9395         printf("\n");
9396         for(user = block->use; user; user = user->next) {
9397                 vertex = print_ipdominated(state, user->member, vertex);
9398         }
9399         return vertex;
9400 }
9401
9402 static void print_ipdominators(struct compile_state *state)
9403 {
9404         printf("\nipdominates\n");
9405         print_ipdominated(state, state->last_block, 0);
9406 }
9407
9408 static int print_pfrontiers(
9409         struct compile_state *state, struct block *block, int vertex)
9410 {
9411         struct block_set *user;
9412
9413         if (!block || (block->vertex != vertex + 1)) {
9414                 return vertex;
9415         }
9416         vertex += 1;
9417
9418         printf("%d:", block->vertex);
9419         for(user = block->ipdomfrontier; user; user = user->next) {
9420                 printf(" %d", user->member->vertex);
9421         }
9422         printf("\n");
9423         for(user = block->use; user; user = user->next) {
9424                 vertex = print_pfrontiers(state, user->member, vertex);
9425         }
9426         return vertex;
9427 }
9428 static void print_ipdominance_frontiers(struct compile_state *state)
9429 {
9430         printf("\nipdominance frontiers\n");
9431         print_pfrontiers(state, state->last_block, 0);
9432         
9433 }
9434
9435 static void analyze_ipdominators(struct compile_state *state)
9436 {
9437         /* Find the post dominators */
9438         find_post_dominators(state);
9439         /* Find the control dependencies (post dominance frontiers) */
9440         find_block_ipdomf(state, state->last_block);
9441         /* If debuging print the print what I have just found */
9442         if (state->debug & DEBUG_RDOMINATORS) {
9443                 print_ipdominators(state);
9444                 print_ipdominance_frontiers(state);
9445                 print_control_flow(state);
9446         }
9447 }
9448
9449
9450 static void insert_phi_operations(struct compile_state *state)
9451 {
9452         size_t size;
9453         struct triple *first;
9454         int *has_already, *work;
9455         struct block *work_list, **work_list_tail;
9456         int iter;
9457         struct triple *var;
9458
9459         size = sizeof(int) * (state->last_vertex + 1);
9460         has_already = xcmalloc(size, "has_already");
9461         work =        xcmalloc(size, "work");
9462         iter = 0;
9463
9464         first = RHS(state->main_function, 0);
9465         for(var = first->next; var != first ; var = var->next) {
9466                 struct block *block;
9467                 struct triple_set *user;
9468                 if ((var->op != OP_ADECL) || !var->use) {
9469                         continue;
9470                 }
9471                 iter += 1;
9472                 work_list = 0;
9473                 work_list_tail = &work_list;
9474                 for(user = var->use; user; user = user->next) {
9475                         if (user->member->op == OP_READ) {
9476                                 continue;
9477                         }
9478                         if (user->member->op != OP_WRITE) {
9479                                 internal_error(state, user->member, 
9480                                         "bad variable access");
9481                         }
9482                         block = user->member->u.block;
9483                         if (!block) {
9484                                 warning(state, user->member, "dead code");
9485                         }
9486                         work[block->vertex] = iter;
9487                         *work_list_tail = block;
9488                         block->work_next = 0;
9489                         work_list_tail = &block->work_next;
9490                 }
9491                 for(block = work_list; block; block = block->work_next) {
9492                         struct block_set *df;
9493                         for(df = block->domfrontier; df; df = df->next) {
9494                                 struct triple *phi;
9495                                 struct block *front;
9496                                 int in_edges;
9497                                 front = df->member;
9498
9499                                 if (has_already[front->vertex] >= iter) {
9500                                         continue;
9501                                 }
9502                                 /* Count how many edges flow into this block */
9503                                 in_edges = front->users;
9504                                 /* Insert a phi function for this variable */
9505                                 phi = alloc_triple(
9506                                         state, OP_PHI, var->type, in_edges, 
9507                                         front->first->filename, 
9508                                         front->first->line,
9509                                         front->first->col);
9510                                 phi->u.block = front;
9511                                 MISC(phi, 0) = var;
9512                                 use_triple(var, phi);
9513                                 /* Insert the phi functions immediately after the label */
9514                                 insert_triple(state, front->first->next, phi);
9515                                 if (front->first == front->last) {
9516                                         front->last = front->first->next;
9517                                 }
9518                                 has_already[front->vertex] = iter;
9519                                 
9520                                 /* If necessary plan to visit the basic block */
9521                                 if (work[front->vertex] >= iter) {
9522                                         continue;
9523                                 }
9524                                 work[front->vertex] = iter;
9525                                 *work_list_tail = front;
9526                                 front->work_next = 0;
9527                                 work_list_tail = &front->work_next;
9528                         }
9529                 }
9530         }
9531         xfree(has_already);
9532         xfree(work);
9533 }
9534
9535 /*
9536  * C(V)
9537  * S(V)
9538  */
9539 static void fixup_block_phi_variables(
9540         struct compile_state *state, struct block *parent, struct block *block)
9541 {
9542         struct block_set *set;
9543         struct triple *ptr;
9544         int edge;
9545         if (!parent || !block)
9546                 return;
9547         /* Find the edge I am coming in on */
9548         edge = 0;
9549         for(set = block->use; set; set = set->next, edge++) {
9550                 if (set->member == parent) {
9551                         break;
9552                 }
9553         }
9554         if (!set) {
9555                 internal_error(state, 0, "phi input is not on a control predecessor");
9556         }
9557         for(ptr = block->first; ; ptr = ptr->next) {
9558                 if (ptr->op == OP_PHI) {
9559                         struct triple *var, *val, **slot;
9560                         var = MISC(ptr, 0);
9561                         /* Find the current value of the variable */
9562                         val = var->use->member;
9563                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9564                                 internal_error(state, val, "bad value in phi");
9565                         }
9566                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
9567                                 internal_error(state, ptr, "edges > phi rhs");
9568                         }
9569                         slot = &RHS(ptr, edge);
9570                         if ((*slot != 0) && (*slot != val)) {
9571                                 internal_error(state, ptr, "phi already bound on this edge");
9572                         }
9573                         *slot = val;
9574                         use_triple(val, ptr);
9575                 }
9576                 if (ptr == block->last) {
9577                         break;
9578                 }
9579         }
9580 }
9581
9582
9583 static void rename_block_variables(
9584         struct compile_state *state, struct block *block)
9585 {
9586         struct block_set *user;
9587         struct triple *ptr, *next, *last;
9588         int done;
9589         if (!block)
9590                 return;
9591         last = block->first;
9592         done = 0;
9593         for(ptr = block->first; !done; ptr = next) {
9594                 next = ptr->next;
9595                 if (ptr == block->last) {
9596                         done = 1;
9597                 }
9598                 /* RHS(A) */
9599                 if (ptr->op == OP_READ) {
9600                         struct triple *var, *val;
9601                         var = RHS(ptr, 0);
9602                         unuse_triple(var, ptr);
9603                         if (!var->use) {
9604                                 error(state, ptr, "variable used without being set");
9605                         }
9606                         /* Find the current value of the variable */
9607                         val = var->use->member;
9608                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9609                                 internal_error(state, val, "bad value in read");
9610                         }
9611                         propogate_use(state, ptr, val);
9612                         release_triple(state, ptr);
9613                         continue;
9614                 }
9615                 /* LHS(A) */
9616                 if (ptr->op == OP_WRITE) {
9617                         struct triple *var, *val;
9618                         var = LHS(ptr, 0);
9619                         val = RHS(ptr, 0);
9620                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
9621                                 internal_error(state, val, "bad value in write");
9622                         }
9623                         propogate_use(state, ptr, val);
9624                         unuse_triple(var, ptr);
9625                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
9626                         push_triple(var, val);
9627                 }
9628                 if (ptr->op == OP_PHI) {
9629                         struct triple *var;
9630                         var = MISC(ptr, 0);
9631                         /* Push OP_PHI onto a stack of variable uses */
9632                         push_triple(var, ptr);
9633                 }
9634                 last = ptr;
9635         }
9636         block->last = last;
9637
9638         /* Fixup PHI functions in the cf successors */
9639         fixup_block_phi_variables(state, block, block->left);
9640         fixup_block_phi_variables(state, block, block->right);
9641         /* rename variables in the dominated nodes */
9642         for(user = block->idominates; user; user = user->next) {
9643                 rename_block_variables(state, user->member);
9644         }
9645         /* pop the renamed variable stack */
9646         last = block->first;
9647         done = 0;
9648         for(ptr = block->first; !done ; ptr = next) {
9649                 next = ptr->next;
9650                 if (ptr == block->last) {
9651                         done = 1;
9652                 }
9653                 if (ptr->op == OP_WRITE) {
9654                         struct triple *var;
9655                         var = LHS(ptr, 0);
9656                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
9657                         pop_triple(var, RHS(ptr, 0));
9658                         release_triple(state, ptr);
9659                         continue;
9660                 }
9661                 if (ptr->op == OP_PHI) {
9662                         struct triple *var;
9663                         var = MISC(ptr, 0);
9664                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
9665                         pop_triple(var, ptr);
9666                 }
9667                 last = ptr;
9668         }
9669         block->last = last;
9670 }
9671
9672 static void prune_block_variables(struct compile_state *state,
9673         struct block *block)
9674 {
9675         struct block_set *user;
9676         struct triple *next, *last, *ptr;
9677         int done;
9678         last = block->first;
9679         done = 0;
9680         for(ptr = block->first; !done; ptr = next) {
9681                 next = ptr->next;
9682                 if (ptr == block->last) {
9683                         done = 1;
9684                 }
9685                 if (ptr->op == OP_ADECL) {
9686                         struct triple_set *user, *next;
9687                         for(user = ptr->use; user; user = next) {
9688                                 struct triple *use;
9689                                 next = user->next;
9690                                 use = user->member;
9691                                 if (use->op != OP_PHI) {
9692                                         internal_error(state, use, "decl still used");
9693                                 }
9694                                 if (MISC(use, 0) != ptr) {
9695                                         internal_error(state, use, "bad phi use of decl");
9696                                 }
9697                                 unuse_triple(ptr, use);
9698                                 MISC(use, 0) = 0;
9699                         }
9700                         release_triple(state, ptr);
9701                         continue;
9702                 }
9703                 last = ptr;
9704         }
9705         block->last = last;
9706         for(user = block->idominates; user; user = user->next) {
9707                 prune_block_variables(state, user->member);
9708         }
9709 }
9710
9711 static void transform_to_ssa_form(struct compile_state *state)
9712 {
9713         insert_phi_operations(state);
9714 #if 0
9715         printf("@%s:%d\n", __FILE__, __LINE__);
9716         print_blocks(state);
9717 #endif
9718         rename_block_variables(state, state->first_block);
9719         prune_block_variables(state, state->first_block);
9720 }
9721
9722
9723 static void transform_from_ssa_form(struct compile_state *state)
9724 {
9725         /* To get out of ssa form we insert moves on the incoming
9726          * edges to blocks containting phi functions.
9727          */
9728         struct triple *first;
9729         struct triple *phi, *next;
9730
9731         /* Walk all of the operations to find the phi functions */
9732         first = RHS(state->main_function, 0);
9733         for(phi = first->next; phi != first ; phi = next) {
9734                 struct block_set *set;
9735                 struct block *block;
9736                 struct triple **slot;
9737                 struct triple *var, *read;
9738                 int edge;
9739                 next = phi->next;
9740                 if (phi->op != OP_PHI) {
9741                         continue;
9742                 }
9743                 block = phi->u.block;
9744                 slot  = &RHS(phi, 0);
9745
9746                 /* A variable to replace the phi function */
9747                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
9748                 /* A read of the single value that is set into the variable */
9749                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
9750                 use_triple(var, read);
9751
9752                 /* Replaces uses of the phi with variable reads */
9753                 propogate_use(state, phi, read);
9754
9755                 /* Walk all of the incoming edges/blocks and insert moves.
9756                  */
9757                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9758                         struct block *eblock;
9759                         struct triple *move;
9760                         struct triple *val;
9761                         eblock = set->member;
9762                         val = slot[edge];
9763                         unuse_triple(val, phi);
9764
9765                         if (val == phi) {
9766                                 continue;
9767                         }
9768
9769                         move = post_triple(state, 
9770                                 val, OP_WRITE, phi->type, var, val);
9771                         use_triple(val, move);
9772                         use_triple(var, move);
9773                 }
9774                 release_triple(state, phi);
9775         }
9776         
9777 }
9778
9779 static void insert_copies_to_phi(struct compile_state *state)
9780 {
9781         /* To get out of ssa form we insert moves on the incoming
9782          * edges to blocks containting phi functions.
9783          */
9784         struct triple *first;
9785         struct triple *phi;
9786
9787         /* Walk all of the operations to find the phi functions */
9788         first = RHS(state->main_function, 0);
9789         for(phi = first->next; phi != first ; phi = phi->next) {
9790                 struct block_set *set;
9791                 struct block *block;
9792                 struct triple **slot;
9793                 int edge;
9794                 if (phi->op != OP_PHI) {
9795                         continue;
9796                 }
9797                 if (ID_REG(phi->id) == REG_UNSET) {
9798                         phi->id = MK_REG_ID(alloc_virtual_reg(), 
9799                                 ID_REG_CLASSES(phi->id));
9800                 }
9801                 block = phi->u.block;
9802                 slot  = &RHS(phi, 0);
9803                 /* Walk all of the incoming edges/blocks and insert moves.
9804                  */
9805                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
9806                         struct block *eblock;
9807                         struct triple *move;
9808                         struct triple *val;
9809                         struct triple *ptr;
9810                         eblock = set->member;
9811                         val = slot[edge];
9812
9813                         if (val == phi) {
9814                                 continue;
9815                         }
9816
9817                         move = build_triple(state, OP_COPY, phi->type, val, 0,
9818                                 val->filename, val->line, val->col);
9819                         move->u.block = eblock;
9820                         move->id = phi->id;
9821                         use_triple(val, move);
9822                         
9823                         slot[edge] = move;
9824                         unuse_triple(val, phi);
9825                         use_triple(move, phi);
9826
9827                         /* Walk through the block backwards to find
9828                          * an appropriate location for the OP_COPY.
9829                          */
9830                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
9831                                 struct triple **expr;
9832                                 if ((ptr == phi) || (ptr == val)) {
9833                                         goto out;
9834                                 }
9835                                 expr = triple_rhs(state, ptr, 0);
9836                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
9837                                         if ((*expr) == phi) {
9838                                                 goto out;
9839                                         }
9840                                 }
9841                         }
9842                 out:
9843                         if (triple_is_branch(state, ptr)) {
9844                                 internal_error(state, ptr,
9845                                         "Could not insert write to phi");
9846                         }
9847                         insert_triple(state, ptr->next, move);
9848                         if (eblock->last == ptr) {
9849                                 eblock->last = move;
9850                         }
9851                 }
9852         }
9853 }
9854
9855 struct triple_reg_set {
9856         struct triple_reg_set *next;
9857         struct triple *member;
9858         struct triple *new;
9859 };
9860
9861 struct reg_block {
9862         struct block *block;
9863         struct triple_reg_set *in;
9864         struct triple_reg_set *out;
9865         int vertex;
9866 };
9867
9868 static int do_triple_set(struct triple_reg_set **head, 
9869         struct triple *member, struct triple *new_member)
9870 {
9871         struct triple_reg_set **ptr, *new;
9872         if (!member)
9873                 return 0;
9874         ptr = head;
9875         while(*ptr) {
9876                 if ((*ptr)->member == member) {
9877                         return 0;
9878                 }
9879                 ptr = &(*ptr)->next;
9880         }
9881         new = xcmalloc(sizeof(*new), "triple_set");
9882         new->member = member;
9883         new->new    = new_member;
9884         new->next   = *head;
9885         *head       = new;
9886         return 1;
9887 }
9888
9889 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
9890 {
9891         struct triple_reg_set *entry, **ptr;
9892         ptr = head;
9893         while(*ptr) {
9894                 entry = *ptr;
9895                 if (entry->member == member) {
9896                         *ptr = entry->next;
9897                         xfree(entry);
9898                         return;
9899                 }
9900                 else {
9901                         ptr = &entry->next;
9902                 }
9903         }
9904 }
9905
9906 static int in_triple(struct reg_block *rb, struct triple *in)
9907 {
9908         return do_triple_set(&rb->in, in, 0);
9909 }
9910 static void unin_triple(struct reg_block *rb, struct triple *unin)
9911 {
9912         do_triple_unset(&rb->in, unin);
9913 }
9914
9915 static int out_triple(struct reg_block *rb, struct triple *out)
9916 {
9917         return do_triple_set(&rb->out, out, 0);
9918 }
9919 static void unout_triple(struct reg_block *rb, struct triple *unout)
9920 {
9921         do_triple_unset(&rb->out, unout);
9922 }
9923
9924 static int initialize_regblock(struct reg_block *blocks,
9925         struct block *block, int vertex)
9926 {
9927         struct block_set *user;
9928         if (!block || (blocks[block->vertex].block == block)) {
9929                 return vertex;
9930         }
9931         vertex += 1;
9932         /* Renumber the blocks in a convinient fashion */
9933         block->vertex = vertex;
9934         blocks[vertex].block    = block;
9935         blocks[vertex].vertex   = vertex;
9936         for(user = block->use; user; user = user->next) {
9937                 vertex = initialize_regblock(blocks, user->member, vertex);
9938         }
9939         return vertex;
9940 }
9941
9942 static int phi_in(struct compile_state *state, struct reg_block *blocks,
9943         struct reg_block *rb, struct block *suc)
9944 {
9945         /* Read the conditional input set of a successor block
9946          * (i.e. the input to the phi nodes) and place it in the
9947          * current blocks output set.
9948          */
9949         struct block_set *set;
9950         struct triple *ptr;
9951         int edge;
9952         int done, change;
9953         change = 0;
9954         /* Find the edge I am coming in on */
9955         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
9956                 if (set->member == rb->block) {
9957                         break;
9958                 }
9959         }
9960         if (!set) {
9961                 internal_error(state, 0, "Not coming on a control edge?");
9962         }
9963         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
9964                 struct triple **slot, *expr, *ptr2;
9965                 int out_change, done2;
9966                 done = (ptr == suc->last);
9967                 if (ptr->op != OP_PHI) {
9968                         continue;
9969                 }
9970                 slot = &RHS(ptr, 0);
9971                 expr = slot[edge];
9972                 out_change = out_triple(rb, expr);
9973                 if (!out_change) {
9974                         continue;
9975                 }
9976                 /* If we don't define the variable also plast it
9977                  * in the current blocks input set.
9978                  */
9979                 ptr2 = rb->block->first;
9980                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
9981                         if (ptr2 == expr) {
9982                                 break;
9983                         }
9984                         done2 = (ptr2 == rb->block->last);
9985                 }
9986                 if (!done2) {
9987                         continue;
9988                 }
9989                 change |= in_triple(rb, expr);
9990         }
9991         return change;
9992 }
9993
9994 static int reg_in(struct compile_state *state, struct reg_block *blocks,
9995         struct reg_block *rb, struct block *suc)
9996 {
9997         struct triple_reg_set *in_set;
9998         int change;
9999         change = 0;
10000         /* Read the input set of a successor block
10001          * and place it in the current blocks output set.
10002          */
10003         in_set = blocks[suc->vertex].in;
10004         for(; in_set; in_set = in_set->next) {
10005                 int out_change, done;
10006                 struct triple *first, *last, *ptr;
10007                 out_change = out_triple(rb, in_set->member);
10008                 if (!out_change) {
10009                         continue;
10010                 }
10011                 /* If we don't define the variable also place it
10012                  * in the current blocks input set.
10013                  */
10014                 first = rb->block->first;
10015                 last = rb->block->last;
10016                 done = 0;
10017                 for(ptr = first; !done; ptr = ptr->next) {
10018                         if (ptr == in_set->member) {
10019                                 break;
10020                         }
10021                         done = (ptr == last);
10022                 }
10023                 if (!done) {
10024                         continue;
10025                 }
10026                 change |= in_triple(rb, in_set->member);
10027         }
10028         change |= phi_in(state, blocks, rb, suc);
10029         return change;
10030 }
10031
10032
10033 static int use_in(struct compile_state *state, struct reg_block *rb)
10034 {
10035         /* Find the variables we use but don't define and add
10036          * it to the current blocks input set.
10037          */
10038 #warning "FIXME is this O(N^2) algorithm bad?"
10039         struct block *block;
10040         struct triple *ptr;
10041         int done;
10042         int change;
10043         block = rb->block;
10044         change = 0;
10045         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10046                 struct triple **expr;
10047                 done = (ptr == block->first);
10048                 /* The variable a phi function uses depends on the
10049                  * control flow, and is handled in phi_in, not
10050                  * here.
10051                  */
10052                 if (ptr->op == OP_PHI) {
10053                         continue;
10054                 }
10055                 expr = triple_rhs(state, ptr, 0);
10056                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10057                         struct triple *rhs, *test;
10058                         int tdone;
10059                         rhs = *expr;
10060                         if (!rhs) {
10061                                 continue;
10062                         }
10063                         /* See if rhs is defined in this block */
10064                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10065                                 tdone = (test == block->first);
10066                                 if (test == rhs) {
10067                                         rhs = 0;
10068                                         break;
10069                                 }
10070                         }
10071                         /* If the triple is not a definition skip it. */
10072                         if (!triple_is_def(state, ptr)) {
10073                                 continue;
10074                         }
10075                         /* If I still have a valid rhs add it to in */
10076                         change |= in_triple(rb, rhs);
10077                 }
10078         }
10079         return change;
10080 }
10081
10082 static struct reg_block *compute_variable_lifetimes(
10083         struct compile_state *state)
10084 {
10085         struct reg_block *blocks;
10086         int change;
10087         blocks = xcmalloc(
10088                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10089         initialize_regblock(blocks, state->last_block, 0);
10090         do {
10091                 int i;
10092                 change = 0;
10093                 for(i = 1; i <= state->last_vertex; i++) {
10094                         struct reg_block *rb;
10095                         rb = &blocks[i];
10096                         /* Add the left successor's input set to in */
10097                         if (rb->block->left) {
10098                                 change |= reg_in(state, blocks, rb, rb->block->left);
10099                         }
10100                         /* Add the right successor's input set to in */
10101                         if ((rb->block->right) && 
10102                                 (rb->block->right != rb->block->left)) {
10103                                 change |= reg_in(state, blocks, rb, rb->block->right);
10104                         }
10105                         /* Add use to in... */
10106                         change |= use_in(state, rb);
10107                 }
10108         } while(change);
10109         return blocks;
10110 }
10111
10112 static void free_variable_lifetimes(
10113         struct compile_state *state, struct reg_block *blocks)
10114 {
10115         int i;
10116         /* free in_set && out_set on each block */
10117         for(i = 1; i <= state->last_vertex; i++) {
10118                 struct triple_reg_set *entry, *next;
10119                 struct reg_block *rb;
10120                 rb = &blocks[i];
10121                 for(entry = rb->in; entry ; entry = next) {
10122                         next = entry->next;
10123                         do_triple_unset(&rb->in, entry->member);
10124                 }
10125                 for(entry = rb->out; entry; entry = next) {
10126                         next = entry->next;
10127                         do_triple_unset(&rb->out, entry->member);
10128                 }
10129         }
10130         xfree(blocks);
10131
10132 }
10133
10134 typedef struct triple *(*wvl_cb_t)(
10135         struct compile_state *state, 
10136         struct reg_block *blocks, struct triple_reg_set *live, 
10137         struct reg_block *rb, struct triple *ins, void *arg);
10138
10139 static void walk_variable_lifetimes(struct compile_state *state,
10140         struct reg_block *blocks, wvl_cb_t cb, void *arg)
10141 {
10142         int i;
10143         
10144         for(i = 1; i <= state->last_vertex; i++) {
10145                 struct triple_reg_set *live;
10146                 struct triple_reg_set *entry, *next;
10147                 struct triple *ptr, *prev;
10148                 struct reg_block *rb;
10149                 struct block *block;
10150                 int done;
10151
10152                 /* Get the blocks */
10153                 rb = &blocks[i];
10154                 block = rb->block;
10155
10156                 /* Copy out into live */
10157                 live = 0;
10158                 for(entry = rb->out; entry; entry = next) {
10159                         next = entry->next;
10160                         do_triple_set(&live, entry->member, entry->new);
10161                 }
10162                 /* Walk through the basic block calculating live */
10163                 for(done = 0, ptr = block->last; !done; ptr = prev) {
10164                         struct triple **expr;
10165
10166                         prev = ptr->prev;
10167                         done = (ptr == block->first);
10168                         
10169                         /* Remove the current definition from live */
10170                         do_triple_unset(&live, ptr);
10171                         
10172                         /* If the current instruction was deleted continue */
10173                         if (!cb(state, blocks, live, rb, ptr, arg)) {
10174                                 if (block->last == ptr) {
10175                                         block->last = prev;
10176                                 }
10177                                 continue;
10178                         }
10179                         
10180                         /* Add the current uses to live.
10181                          *
10182                          * It is safe to skip phi functions because they do
10183                          * not have any block local uses, and the block
10184                          * output sets already properly account for what
10185                          * control flow depedent uses phi functions do have.
10186                          */
10187                         if (ptr->op == OP_PHI) {
10188                                 continue;
10189                         }
10190                         expr = triple_rhs(state, ptr, 0);
10191                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
10192                                 /* If the triple is not a definition skip it. */
10193                                 if (!*expr || !triple_is_def(state, *expr)) {
10194                                         continue;
10195                                 }
10196                                 do_triple_set(&live, *expr, 0);
10197                         }
10198                         expr = triple_lhs(state, ptr, 0);
10199                         for(;expr; expr = triple_lhs(state, ptr, expr)) {
10200                                 /* If the triple is not a definition skip it. */
10201                                 if (!*expr || !triple_is_def(state, *expr)) {
10202                                         continue;
10203                                 }
10204                                 do_triple_set(&live, *expr, 0);
10205                         }
10206
10207                 }
10208                 /* Free live */
10209                 for(entry = live; entry; entry = next) {
10210                         next = entry->next;
10211                         do_triple_unset(&live, entry->member);
10212                 }
10213         }
10214 }
10215
10216 static int count_triples(struct compile_state *state)
10217 {
10218         struct triple *first, *ins;
10219         int triples = 0;
10220         first = RHS(state->main_function, 0);
10221         ins = first;
10222         do {
10223                 triples++;
10224                 ins = ins->next;
10225         } while (ins != first);
10226         return triples;
10227 }
10228 struct dead_triple {
10229         struct triple *triple;
10230         struct dead_triple *work_next;
10231         struct block *block;
10232         int color;
10233         int flags;
10234 #define TRIPLE_FLAG_ALIVE 1
10235 };
10236
10237
10238 static void awaken(
10239         struct compile_state *state,
10240         struct dead_triple *dtriple, struct triple **expr,
10241         struct dead_triple ***work_list_tail)
10242 {
10243         struct triple *triple;
10244         struct dead_triple *dt;
10245         if (!expr) {
10246                 return;
10247         }
10248         triple = *expr;
10249         if (!triple) {
10250                 return;
10251         }
10252         if (triple->id <= 0)  {
10253                 internal_error(state, triple, "bad triple id: %d",
10254                         triple->id);
10255         }
10256         if (triple->op == OP_NOOP) {
10257                 internal_warning(state, triple, "awakening noop?");
10258                 return;
10259         }
10260         dt = &dtriple[triple->id];
10261         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10262                 dt->flags |= TRIPLE_FLAG_ALIVE;
10263                 if (!dt->work_next) {
10264                         **work_list_tail = dt;
10265                         *work_list_tail = &dt->work_next;
10266                 }
10267         }
10268 }
10269
10270 static void eliminate_inefectual_code(struct compile_state *state)
10271 {
10272         struct block *block;
10273         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
10274         int triples, i;
10275         struct triple *first, *ins;
10276
10277         /* Setup the work list */
10278         work_list = 0;
10279         work_list_tail = &work_list;
10280
10281         first = RHS(state->main_function, 0);
10282
10283         /* Count how many triples I have */
10284         triples = count_triples(state);
10285
10286         /* Now put then in an array and mark all of the triples dead */
10287         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
10288         
10289         ins = first;
10290         i = 1;
10291         block = 0;
10292         do {
10293                 if (ins->op == OP_LABEL) {
10294                         block = ins->u.block;
10295                 }
10296                 dtriple[i].triple = ins;
10297                 dtriple[i].block  = block;
10298                 dtriple[i].flags  = 0;
10299                 dtriple[i].color  = ins->id;
10300                 ins->id = i;
10301                 /* See if it is an operation we always keep */
10302 #warning "FIXME handle the case of killing a branch instruction"
10303                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
10304                         awaken(state, dtriple, &ins, &work_list_tail);
10305                 }
10306                 i++;
10307                 ins = ins->next;
10308         } while(ins != first);
10309         while(work_list) {
10310                 struct dead_triple *dt;
10311                 struct block_set *user;
10312                 struct triple **expr;
10313                 dt = work_list;
10314                 work_list = dt->work_next;
10315                 if (!work_list) {
10316                         work_list_tail = &work_list;
10317                 }
10318                 /* Wake up the data depencencies of this triple */
10319                 expr = 0;
10320                 do {
10321                         expr = triple_rhs(state, dt->triple, expr);
10322                         awaken(state, dtriple, expr, &work_list_tail);
10323                 } while(expr);
10324                 do {
10325                         expr = triple_lhs(state, dt->triple, expr);
10326                         awaken(state, dtriple, expr, &work_list_tail);
10327                 } while(expr);
10328                 /* Wake up the forward control dependencies */
10329                 do {
10330                         expr = triple_targ(state, dt->triple, expr);
10331                         awaken(state, dtriple, expr, &work_list_tail);
10332                 } while(expr);
10333                 /* Wake up the reverse control dependencies of this triple */
10334                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
10335                         awaken(state, dtriple, &user->member->last, &work_list_tail);
10336                 }
10337         }
10338         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
10339                 if ((dt->triple->op == OP_NOOP) && 
10340                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
10341                         internal_error(state, dt->triple, "noop effective?");
10342                 }
10343                 dt->triple->id = dt->color;     /* Restore the color */
10344                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
10345 #warning "FIXME handle the case of killing a basic block"
10346                         if (dt->block->first == dt->triple) {
10347                                 continue;
10348                         }
10349                         if (dt->block->last == dt->triple) {
10350                                 dt->block->last = dt->triple->prev;
10351                         }
10352                         release_triple(state, dt->triple);
10353                 }
10354         }
10355         xfree(dtriple);
10356 }
10357
10358
10359 struct live_range_edge;
10360 struct live_range {
10361         struct live_range_edge *edges;
10362         struct triple *def;
10363         unsigned color;
10364         unsigned classes;
10365         unsigned degree;
10366         struct live_range *group_next, **group_prev;
10367 };
10368
10369 struct live_range_edge {
10370         struct live_range_edge *next;
10371         struct live_range *node;
10372 };
10373
10374 #define LRE_HASH_SIZE 2048
10375 struct lre_hash {
10376         struct lre_hash *next;
10377         struct live_range *left;
10378         struct live_range *right;
10379 };
10380
10381
10382 struct reg_state {
10383         struct lre_hash *hash[LRE_HASH_SIZE];
10384         struct reg_block *blocks;
10385         struct live_range *lr;
10386         struct live_range *low, **low_tail;
10387         struct live_range *high, **high_tail;
10388         unsigned ranges;
10389 };
10390
10391
10392 static unsigned regc_max_size(struct compile_state *state, int classes)
10393 {
10394         unsigned max_size;
10395         int i;
10396         max_size = 0;
10397         for(i = 0; i < MAX_REGC; i++) {
10398                 if (classes & (1 << i)) {
10399                         unsigned size;
10400                         size = arch_regc_size(state, i);
10401                         if (size > max_size) {
10402                                 max_size = size;
10403                         }
10404                 }
10405         }
10406         return max_size;
10407 }
10408
10409 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
10410 {
10411         unsigned equivs[MAX_REG_EQUIVS];
10412         int i;
10413         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
10414                 internal_error(state, 0, "invalid register");
10415         }
10416         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
10417                 internal_error(state, 0, "invalid register");
10418         }
10419         arch_reg_equivs(state, equivs, reg1);
10420         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
10421                 if (equivs[i] == reg2) {
10422                         return 1;
10423                 }
10424         }
10425         return 0;
10426 }
10427
10428 static void reg_fill_used(struct compile_state *state, char *used, int reg)
10429 {
10430         unsigned equivs[MAX_REG_EQUIVS];
10431         int i;
10432         arch_reg_equivs(state, equivs, reg);
10433         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
10434                 used[equivs[i]] = 1;
10435         }
10436         return;
10437 }
10438
10439 static unsigned int hash_live_edge(
10440         struct live_range *left, struct live_range *right)
10441 {
10442         unsigned int hash, val;
10443         unsigned long lval, rval;
10444         lval = ((unsigned long)left)/sizeof(struct live_range);
10445         rval = ((unsigned long)right)/sizeof(struct live_range);
10446         hash = 0;
10447         while(lval) {
10448                 val = lval & 0xff;
10449                 lval >>= 8;
10450                 hash = (hash *263) + val;
10451         }
10452         while(rval) {
10453                 val = rval & 0xff;
10454                 rval >>= 8;
10455                 hash = (hash *263) + val;
10456         }
10457         hash = hash & (LRE_HASH_SIZE - 1);
10458         return hash;
10459 }
10460
10461 static struct lre_hash **lre_probe(struct reg_state *rstate,
10462         struct live_range *left, struct live_range *right)
10463 {
10464         struct lre_hash **ptr;
10465         unsigned int index;
10466         /* Ensure left <= right */
10467         if (left > right) {
10468                 struct live_range *tmp;
10469                 tmp = left;
10470                 left = right;
10471                 right = tmp;
10472         }
10473         index = hash_live_edge(left, right);
10474         
10475         ptr = &rstate->hash[index];
10476         while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
10477                 ptr = &(*ptr)->next;
10478         }
10479         return ptr;
10480 }
10481
10482 static int interfere(struct reg_state *rstate,
10483         struct live_range *left, struct live_range *right)
10484 {
10485         struct lre_hash **ptr;
10486         ptr = lre_probe(rstate, left, right);
10487         return ptr && *ptr;
10488 }
10489
10490 static void add_live_edge(struct reg_state *rstate, 
10491         struct live_range *left, struct live_range *right)
10492 {
10493         /* FIXME the memory allocation overhead is noticeable here... */
10494         struct lre_hash **ptr, *new_hash;
10495         struct live_range_edge *edge;
10496
10497         if (left == right) {
10498                 return;
10499         }
10500         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
10501                 return;
10502         }
10503         /* Ensure left <= right */
10504         if (left > right) {
10505                 struct live_range *tmp;
10506                 tmp = left;
10507                 left = right;
10508                 right = tmp;
10509         }
10510         ptr = lre_probe(rstate, left, right);
10511         if (*ptr) {
10512                 return;
10513         }
10514         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
10515         new_hash->next  = *ptr;
10516         new_hash->left  = left;
10517         new_hash->right = right;
10518         *ptr = new_hash;
10519
10520         edge = xmalloc(sizeof(*edge), "live_range_edge");
10521         edge->next   = left->edges;
10522         edge->node   = right;
10523         left->edges  = edge;
10524         left->degree += 1;
10525         
10526         edge = xmalloc(sizeof(*edge), "live_range_edge");
10527         edge->next    = right->edges;
10528         edge->node    = left;
10529         right->edges  = edge;
10530         right->degree += 1;
10531 }
10532
10533 static void remove_live_edge(struct reg_state *rstate,
10534         struct live_range *left, struct live_range *right)
10535 {
10536         struct live_range_edge *edge, **ptr;
10537         struct lre_hash **hptr, *entry;
10538         hptr = lre_probe(rstate, left, right);
10539         if (!hptr || !*hptr) {
10540                 return;
10541         }
10542         entry = *hptr;
10543         *hptr = entry->next;
10544         xfree(entry);
10545
10546         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
10547                 edge = *ptr;
10548                 if (edge->node == right) {
10549                         *ptr = edge->next;
10550                         memset(edge, 0, sizeof(*edge));
10551                         xfree(edge);
10552                         break;
10553                 }
10554         }
10555         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
10556                 edge = *ptr;
10557                 if (edge->node == left) {
10558                         *ptr = edge->next;
10559                         memset(edge, 0, sizeof(*edge));
10560                         xfree(edge);
10561                         break;
10562                 }
10563         }
10564 }
10565
10566 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
10567 {
10568         struct live_range_edge *edge, *next;
10569         for(edge = range->edges; edge; edge = next) {
10570                 next = edge->next;
10571                 remove_live_edge(rstate, range, edge->node);
10572         }
10573 }
10574
10575
10576 /* Interference graph...
10577  * 
10578  * new(n) --- Return a graph with n nodes but no edges.
10579  * add(g,x,y) --- Return a graph including g with an between x and y
10580  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
10581  *                x and y in the graph g
10582  * degree(g, x) --- Return the degree of the node x in the graph g
10583  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
10584  *
10585  * Implement with a hash table && a set of adjcency vectors.
10586  * The hash table supports constant time implementations of add and interfere.
10587  * The adjacency vectors support an efficient implementation of neighbors.
10588  */
10589
10590 /* 
10591  *     +---------------------------------------------------+
10592  *     |         +--------------+                          |
10593  *     v         v              |                          |
10594  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
10595  *
10596  * -- In simplify implment optimistic coloring... (No backtracking)
10597  * -- Implement Rematerialization it is the only form of spilling we can perform
10598  *    Essentially this means dropping a constant from a register because
10599  *    we can regenerate it later.
10600  *
10601  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
10602  *     coalesce at phi points...
10603  * --- Bias coloring if at all possible do the coalesing a compile time.
10604  *
10605  *
10606  */
10607
10608 static void different_colored(
10609         struct compile_state *state, struct reg_state *rstate, 
10610         struct triple *parent, struct triple *ins)
10611 {
10612         struct live_range *lr;
10613         struct triple **expr;
10614         lr = &rstate->lr[ins->id];
10615         expr = triple_rhs(state, ins, 0);
10616         for(;expr; expr = triple_rhs(state, ins, expr)) {
10617                 struct live_range *lr2;
10618                 if (!*expr || (*expr == parent) || (*expr == ins)) {
10619                         continue;
10620                 }
10621                 lr2 = &rstate->lr[(*expr)->id];
10622                 if (lr->color == lr2->color) {
10623                         internal_error(state, ins, "live range too big");
10624                 }
10625         }
10626 }
10627
10628 static void initialize_live_ranges(
10629         struct compile_state *state, struct reg_state *rstate)
10630 {
10631         struct triple *ins, *first;
10632         size_t size;
10633         int i;
10634
10635         first = RHS(state->main_function, 0);
10636         /* First count how many live ranges I will need.
10637          */
10638         rstate->ranges = count_triples(state);
10639         size = sizeof(rstate->lr[0]) * (rstate->ranges + 1);
10640         rstate->lr = xcmalloc(size, "live_range");
10641         /* Setup the dummy live range */
10642         rstate->lr[0].classes = 0;
10643         rstate->lr[0].color = REG_UNSET;
10644         rstate->lr[0].def = 0;
10645         i = 0;
10646         ins = first;
10647         do {
10648                 unsigned color, classes;
10649                 /* Find the architecture specific color information */
10650                 color = ID_REG(ins->id);
10651                 classes = ID_REG_CLASSES(ins->id);
10652                 if ((color != REG_UNSET) && (color < MAX_REGISTERS)) {
10653                         classes = arch_reg_regcm(state, color);
10654                 }
10655
10656                 /* If the triple is a variable definition give it a live range. */
10657                 if (triple_is_def(state, ins)) {
10658                         i++;
10659                         ins->id = i;
10660                         rstate->lr[i].def     = ins;
10661                         rstate->lr[i].color   = color;
10662                         rstate->lr[i].classes = classes;
10663                         rstate->lr[i].degree  = 0;
10664                         if (!classes) {
10665                                 internal_error(state, ins, 
10666                                         "live range without a class");
10667                         }
10668                 }
10669                 /* Otherwise give the triple the dummy live range. */
10670                 else {
10671                         ins->id = 0;
10672                 }
10673                 ins = ins->next;
10674         } while(ins != first);
10675         rstate->ranges = i;
10676         /* Make a second pass to handle achitecture specific register
10677          * constraints.
10678          */
10679         ins = first;
10680         do {
10681                 struct live_range *lr;
10682                 lr = &rstate->lr[ins->id];
10683                 if (lr->color != REG_UNSET) {
10684                         struct triple **expr;
10685                         /* This assumes the virtual register is only
10686                          * used by one input operation.
10687                          */
10688                         expr = triple_rhs(state, ins, 0);
10689                         for(;expr; expr = triple_rhs(state, ins, expr)) {
10690                                 struct live_range *lr2;
10691                                 if (!*expr || (ins == *expr)) {
10692                                         continue;
10693                                 }
10694                                 lr2 = &rstate->lr[(*expr)->id];
10695                                 if (lr->color == lr2->color) {
10696                                         different_colored(state, rstate, 
10697                                                 ins, *expr);
10698                                         (*expr)->id = ins->id;
10699                                         
10700                                 }
10701                         }
10702                 }
10703                 ins = ins->next;
10704         } while(ins != first);
10705
10706         /* Make a third pass and forget the virtual registers */
10707         for(i = 1; i <= rstate->ranges; i++) {
10708                 if (rstate->lr[i].color >= MAX_REGISTERS) {
10709                         rstate->lr[i].color = REG_UNSET;
10710                 }
10711         }
10712 }
10713
10714 static struct triple *graph_ins(
10715         struct compile_state *state, 
10716         struct reg_block *blocks, struct triple_reg_set *live, 
10717         struct reg_block *rb, struct triple *ins, void *arg)
10718 {
10719         struct reg_state *rstate = arg;
10720         struct live_range *def;
10721         struct triple_reg_set *entry;
10722
10723         /* If the triple does not start a live range
10724          * we do not have a definition to add to
10725          * the interference graph.
10726          */
10727         if (ins->id <= 0) {
10728                 return ins;
10729         }
10730         def = &rstate->lr[ins->id];
10731         
10732         /* Create an edge between ins and everything that is
10733          * alive, unless the live_range cannot share
10734          * a physical register with ins.
10735          */
10736         for(entry = live; entry; entry = entry->next) {
10737                 struct live_range *lr;
10738                 lr= &rstate->lr[entry->member->id];
10739                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
10740                         continue;
10741                 }
10742                 add_live_edge(rstate, def, lr);
10743         }
10744         return ins;
10745 }
10746
10747
10748 static struct triple *print_interference_ins(
10749         struct compile_state *state, 
10750         struct reg_block *blocks, struct triple_reg_set *live, 
10751         struct reg_block *rb, struct triple *ins, void *arg)
10752 {
10753         struct reg_state *rstate = arg;
10754         struct live_range *lr;
10755
10756         lr = &rstate->lr[ins->id];
10757         display_triple(stdout, ins);
10758         if (live) {
10759                 struct triple_reg_set *entry;
10760                 printf("        live:");
10761                 for(entry = live; entry; entry = entry->next) {
10762                         printf(" %-10p", entry->member);
10763                 }
10764                 printf("\n");
10765         }
10766         if (lr->edges) {
10767                 struct live_range_edge *entry;
10768                 printf("        edges:");
10769                 for(entry = lr->edges; entry; entry = entry->next) {
10770                         printf(" %-10p", entry->node->def);
10771                 }
10772                 printf("\n");
10773         }
10774         if (triple_is_branch(state, ins)) {
10775                 printf("\n");
10776         }
10777         return ins;
10778 }
10779
10780 #if DEBUG_COLOR_GRAPH > 1
10781 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
10782 #define cgdebug_flush() fflush(stdout)
10783 #elif DEBUG_COLOR_GRAPH == 1
10784 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
10785 #define cgdebug_flush() fflush(stderr)
10786 #else
10787 #define cgdebug_printf(...)
10788 #define cgdebug_flush()
10789 #endif
10790
10791 static void select_free_color(struct compile_state *state, 
10792         struct reg_state *rstate, struct live_range *range)
10793 {
10794         struct triple_set *entry;
10795         struct live_range *phi;
10796         struct live_range_edge *edge;
10797         char used[MAX_REGISTERS];
10798         struct triple **expr;
10799
10800         /* If a color is already assigned don't change it */
10801         if (range->color != REG_UNSET) {
10802                 return;
10803         }
10804         /* Instead of doing just the trivial color select here I try
10805          * a few extra things because a good color selection will help reduce
10806          * copies.
10807          */
10808
10809         /* Find the registers currently in use */
10810         memset(used, 0, sizeof(used));
10811         for(edge = range->edges; edge; edge = edge->next) {
10812                 if (edge->node->color == REG_UNSET) {
10813                         continue;
10814                 }
10815                 reg_fill_used(state, used, edge->node->color);
10816         }
10817 #if DEBUG_COLOR_GRAPH > 1
10818         {
10819                 int i;
10820                 i = 0;
10821                 for(edge = range->edges; edge; edge = edge->next) {
10822                         i++;
10823                 }
10824                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
10825                         tops(range->def->op), i, 
10826                         range->def->filename, range->def->line, range->def->col);
10827                 for(i = 0; i < MAX_REGISTERS; i++) {
10828                         if (used[i]) {
10829                                 cgdebug_printf("used: %s\n",
10830                                         arch_reg_str(i));
10831                         }
10832                 }
10833         }       
10834 #endif
10835
10836         /* If I feed into an expression reuse it's color.
10837          * This should help remove copies in the case of 2 register instructions
10838          * and phi functions.
10839          */
10840         phi = 0;
10841         entry = range->def->use;
10842         for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
10843                 struct live_range *lr;
10844                 lr = &rstate->lr[entry->member->id];
10845                 if (entry->member->id == 0) {
10846                         continue;
10847                 }
10848                 if (!phi && (lr->def->op == OP_PHI) && 
10849                         !interfere(rstate, range, lr)) {
10850                         phi = lr;
10851                 }
10852                 if ((lr->color == REG_UNSET) ||
10853                         ((lr->classes & range->classes) == 0) ||
10854                         (used[lr->color])) {
10855                         continue;
10856                 }
10857                 if (interfere(rstate, range, lr)) {
10858                         continue;
10859                 }
10860                 range->color = lr->color;
10861         }
10862         /* If I feed into a phi function reuse it's color of the color
10863          * of something else that feeds into the phi function.
10864          */
10865         if (phi) {
10866                 if (phi->color != REG_UNSET) {
10867                         if (used[phi->color]) {
10868                                 range->color = phi->color;
10869                         }
10870                 }
10871                 else {
10872                         expr = triple_rhs(state, phi->def, 0);
10873                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
10874                                 struct live_range *lr;
10875                                 if (!*expr) {
10876                                         continue;
10877                                 }
10878                                 lr = &rstate->lr[(*expr)->id];
10879                                 if ((lr->color == REG_UNSET) || 
10880                                         ((lr->classes & range->classes) == 0) ||
10881                                         (used[lr->color])) {
10882                                         continue;
10883                                 }
10884                                 if (interfere(rstate, range, lr)) {
10885                                         continue;
10886                                 }
10887                                 range->color = lr->color;
10888                         }
10889                 }
10890         }
10891         /* If I don't interfere with a rhs node reuse it's color */
10892         if (range->color == REG_UNSET) {
10893                 expr = triple_rhs(state, range->def, 0);
10894                 for(; expr; expr = triple_rhs(state, range->def, expr)) {
10895                         struct live_range *lr;
10896                         if (!*expr) {
10897                                 continue;
10898                         }
10899                         lr = &rstate->lr[(*expr)->id];
10900                         if ((lr->color == -1) || 
10901                                 ((lr->classes & range->classes) == 0) ||
10902                                 (used[lr->color])) {
10903                                 continue;
10904                         }
10905                         if (interfere(rstate, range, lr)) {
10906                                 continue;
10907                         }
10908                         range->color = lr->color;
10909                         break;
10910                 }
10911         }
10912         /* If I have not opportunitically picked a useful color
10913          * pick the first color that is free.
10914          */
10915         if (range->color == REG_UNSET) {
10916                 range->color = 
10917                         arch_select_free_register(state, used, range->classes);
10918         }
10919         if (range->color == REG_UNSET) {
10920                 int i;
10921                 for(edge = range->edges; edge; edge = edge->next) {
10922                         if (edge->node->color == REG_UNSET) {
10923                                 continue;
10924                         }
10925                         warning(state, edge->node->def, "reg %s", 
10926                                 arch_reg_str(edge->node->color));
10927                 }
10928                 warning(state, range->def, "classes: %x",
10929                         range->classes);
10930                 for(i = 0; i < MAX_REGISTERS; i++) {
10931                         if (used[i]) {
10932                                 warning(state, range->def, "used: %s",
10933                                         arch_reg_str(i));
10934                         }
10935                 }
10936 #if DEBUG_COLOR_GRAPH < 2
10937                 error(state, range->def, "too few registers");
10938 #else
10939                 internal_error(state, range->def, "too few registers");
10940 #endif
10941         }
10942         range->classes = arch_reg_regcm(state, range->color);
10943         return;
10944 }
10945
10946 static void color_graph(struct compile_state *state, struct reg_state *rstate)
10947 {
10948         struct live_range_edge *edge;
10949         struct live_range *range;
10950         if (rstate->low) {
10951                 cgdebug_printf("Lo: ");
10952                 range = rstate->low;
10953                 if (*range->group_prev != range) {
10954                         internal_error(state, 0, "lo: *prev != range?");
10955                 }
10956                 *range->group_prev = range->group_next;
10957                 if (range->group_next) {
10958                         range->group_next->group_prev = range->group_prev;
10959                 }
10960                 if (&range->group_next == rstate->low_tail) {
10961                         rstate->low_tail = range->group_prev;
10962                 }
10963                 if (rstate->low == range) {
10964                         internal_error(state, 0, "low: next != prev?");
10965                 }
10966         }
10967         else if (rstate->high) {
10968                 cgdebug_printf("Hi: ");
10969                 range = rstate->high;
10970                 if (*range->group_prev != range) {
10971                         internal_error(state, 0, "hi: *prev != range?");
10972                 }
10973                 *range->group_prev = range->group_next;
10974                 if (range->group_next) {
10975                         range->group_next->group_prev = range->group_prev;
10976                 }
10977                 if (&range->group_next == rstate->high_tail) {
10978                         rstate->high_tail = range->group_prev;
10979                 }
10980                 if (rstate->high == range) {
10981                         internal_error(state, 0, "high: next != prev?");
10982                 }
10983         }
10984         else {
10985                 return;
10986         }
10987         cgdebug_printf(" %d\n", range - rstate->lr);
10988         range->group_prev = 0;
10989         for(edge = range->edges; edge; edge = edge->next) {
10990                 struct live_range *node;
10991                 node = edge->node;
10992                 /* Move nodes from the high to the low list */
10993                 if (node->group_prev && (node->color == REG_UNSET) &&
10994                         (node->degree == regc_max_size(state, node->classes))) {
10995                         if (*node->group_prev != node) {
10996                                 internal_error(state, 0, "move: *prev != node?");
10997                         }
10998                         *node->group_prev = node->group_next;
10999                         if (node->group_next) {
11000                                 node->group_next->group_prev = node->group_prev;
11001                         }
11002                         if (&node->group_next == rstate->high_tail) {
11003                                 rstate->high_tail = node->group_prev;
11004                         }
11005                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
11006                         node->group_prev  = rstate->low_tail;
11007                         node->group_next  = 0;
11008                         *rstate->low_tail = node;
11009                         rstate->low_tail  = &node->group_next;
11010                         if (*node->group_prev != node) {
11011                                 internal_error(state, 0, "move2: *prev != node?");
11012                         }
11013                 }
11014                 node->degree -= 1;
11015         }
11016         color_graph(state, rstate);
11017         cgdebug_printf("Coloring %d @%s:%d.%d:", 
11018                 range - rstate->lr,
11019                 range->def->filename, range->def->line, range->def->col);
11020         cgdebug_flush();
11021         select_free_color(state, rstate, range);
11022         if (range->color == -1) {
11023                 internal_error(state, range->def, "select_free_color did not?");
11024         }
11025         cgdebug_printf(" %s\n", arch_reg_str(range->color));
11026 }
11027
11028 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
11029 {
11030         struct live_range *lr;
11031         struct live_range_edge *edge;
11032         struct triple *ins, *first;
11033         char used[MAX_REGISTERS];
11034         first = RHS(state->main_function, 0);
11035         ins = first;
11036         do {
11037                 if (triple_is_def(state, ins)) {
11038                         if ((ins->id < 0) || (ins->id > rstate->ranges)) {
11039                                 internal_error(state, ins, 
11040                                         "triple without a live range");
11041                         }
11042                         lr = &rstate->lr[ins->id];
11043                         if (lr->color == REG_UNSET) {
11044                                 internal_error(state, ins,
11045                                         "triple without a color");
11046                         }
11047                         /* Find the registers used by the edges */
11048                         memset(used, 0, sizeof(used));
11049                         for(edge = lr->edges; edge; edge = edge->next) {
11050                                 if (edge->node->color == REG_UNSET) {
11051                                         internal_error(state, 0,
11052                                                 "live range without a color");
11053                         }
11054                                 reg_fill_used(state, used, edge->node->color);
11055                         }
11056                         if (used[lr->color]) {
11057                                 internal_error(state, ins,
11058                                         "triple with already used color");
11059                         }
11060                 }
11061                 ins = ins->next;
11062         } while(ins != first);
11063 }
11064
11065 static void color_triples(struct compile_state *state, struct reg_state *rstate)
11066 {
11067         struct live_range *lr;
11068         struct triple *first, *ins;
11069         first = RHS(state->main_function, 0);
11070         ins = first;
11071         do {
11072                 if ((ins->id < 0) || (ins->id > rstate->ranges)) {
11073                         internal_error(state, ins, 
11074                                 "triple without a live range");
11075                 }
11076                 lr = &rstate->lr[ins->id];
11077                 ins->id = MK_REG_ID(lr->color, 0);
11078                 ins = ins->next;
11079         } while (ins != first);
11080 }
11081
11082 static void print_interference_block(
11083         struct compile_state *state, struct block *block, void *arg)
11084
11085 {
11086         struct reg_state *rstate = arg;
11087         struct reg_block *rb;
11088         struct triple *ptr;
11089         int phi_present;
11090         int done;
11091         rb = &rstate->blocks[block->vertex];
11092
11093         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
11094                 block, 
11095                 block->vertex,
11096                 block->left, 
11097                 block->left && block->left->use?block->left->use->member : 0,
11098                 block->right, 
11099                 block->right && block->right->use?block->right->use->member : 0);
11100         if (rb->in) {
11101                 struct triple_reg_set *in_set;
11102                 printf("        in:");
11103                 for(in_set = rb->in; in_set; in_set = in_set->next) {
11104                         printf(" %-10p", in_set->member);
11105                 }
11106                 printf("\n");
11107         }
11108         phi_present = 0;
11109         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11110                 done = (ptr == block->last);
11111                 if (ptr->op == OP_PHI) {
11112                         phi_present = 1;
11113                         break;
11114                 }
11115         }
11116         if (phi_present) {
11117                 int edge;
11118                 for(edge = 0; edge < block->users; edge++) {
11119                         printf("     in(%d):", edge);
11120                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11121                                 struct triple **slot;
11122                                 done = (ptr == block->last);
11123                                 if (ptr->op != OP_PHI) {
11124                                         continue;
11125                                 }
11126                                 slot = &RHS(ptr, 0);
11127                                 printf(" %-10p", slot[edge]);
11128                         }
11129                         printf("\n");
11130                 }
11131         }
11132         if (block->first->op == OP_LABEL) {
11133                 printf("%p:\n", block->first);
11134         }
11135         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11136                 struct triple_set *user;
11137                 struct live_range *lr;
11138                 unsigned id;
11139                 int op;
11140                 op = ptr->op;
11141                 done = (ptr == block->last);
11142                 lr = &rstate->lr[ptr->id];
11143                 
11144                 if (!IS_CONST_OP(op)) {
11145                         if (ptr->u.block != block) {
11146                                 internal_error(state, ptr, 
11147                                         "Wrong block pointer: %p",
11148                                         ptr->u.block);
11149                         }
11150                 }
11151                 if (op == OP_ADECL) {
11152                         for(user = ptr->use; user; user = user->next) {
11153                                 struct live_range *lr;
11154                                 lr = &rstate->lr[user->member->id];
11155                                 if (!user->member->u.block) {
11156                                         internal_error(state, user->member, 
11157                                                 "Use %p not in a block?",
11158                                                 user->member);
11159                                 }
11160                                 
11161                         }
11162                 }
11163                 id = ptr->id;
11164                 ptr->id = MK_REG_ID(lr->color, 0);
11165                 display_triple(stdout, ptr);
11166                 ptr->id = id;
11167
11168                 if (lr->edges > 0) {
11169                         struct live_range_edge *edge;
11170                         printf("           ");
11171                         for(edge = lr->edges; edge; edge = edge->next) {
11172                                 printf(" %-10p", edge->node->def);
11173                         }
11174                         printf("\n");
11175                 }
11176                 /* Do a bunch of sanity checks */
11177                 valid_ins(state, ptr);
11178                 if ((ptr->id < 0) || (ptr->id > rstate->ranges)) {
11179                         internal_error(state, ptr, "Invalid triple id: %d",
11180                                 ptr->id);
11181                 }
11182                 for(user = ptr->use; user; user = user->next) {
11183                         struct triple *use;
11184                         struct live_range *ulr;
11185                         use = user->member;
11186                         valid_ins(state, use);
11187                         if ((use->id < 0) || (use->id > rstate->ranges)) {
11188                                 internal_error(state, use, "Invalid triple id: %d",
11189                                         use->id);
11190                         }
11191                         ulr = &rstate->lr[user->member->id];
11192                         if (!IS_CONST_OP(user->member->op) &&
11193                                 !user->member->u.block) {
11194                                 internal_error(state, user->member,
11195                                         "Use %p not in a block?",
11196                                         user->member);
11197                         }
11198                 }
11199         }
11200         if (rb->out) {
11201                 struct triple_reg_set *out_set;
11202                 printf("       out:");
11203                 for(out_set = rb->out; out_set; out_set = out_set->next) {
11204                         printf(" %-10p", out_set->member);
11205                 }
11206                 printf("\n");
11207         }
11208         printf("\n");
11209 }
11210
11211 static struct live_range *merge_sort_lr(
11212         struct live_range *first, struct live_range *last)
11213 {
11214         struct live_range *mid, *join, **join_tail, *pick;
11215         size_t size;
11216         size = (last - first) + 1;
11217         if (size >= 2) {
11218                 mid = first + size/2;
11219                 first = merge_sort_lr(first, mid -1);
11220                 mid   = merge_sort_lr(mid, last);
11221                 
11222                 join = 0;
11223                 join_tail = &join;
11224                 /* merge the two lists */
11225                 while(first && mid) {
11226                         if (first->degree <= mid->degree) {
11227                                 pick = first;
11228                                 first = first->group_next;
11229                                 if (first) {
11230                                         first->group_prev = 0;
11231                                 }
11232                         }
11233                         else {
11234                                 pick = mid;
11235                                 mid = mid->group_next;
11236                                 if (mid) {
11237                                         mid->group_prev = 0;
11238                                 }
11239                         }
11240                         pick->group_next = 0;
11241                         pick->group_prev = join_tail;
11242                         *join_tail = pick;
11243                         join_tail = &pick->group_next;
11244                 }
11245                 /* Splice the remaining list */
11246                 pick = (first)? first : mid;
11247                 *join_tail = pick;
11248                 pick->group_prev = join_tail;
11249         }
11250         else {
11251                 if (!first->def) {
11252                         first = 0;
11253                 }
11254                 join = first;
11255         }
11256         return join;
11257 }
11258
11259 static void allocate_registers(struct compile_state *state)
11260 {
11261         struct reg_state rstate;
11262         struct live_range **point, **next;
11263         int i;
11264
11265         /* Clear out the reg_state */
11266         memset(&rstate, 0, sizeof(rstate));
11267
11268         /* Compute the variable lifetimes */
11269         rstate.blocks = compute_variable_lifetimes(state);
11270
11271         /* Allocate and initialize the live ranges */
11272         initialize_live_ranges(state, &rstate);
11273
11274         /* Compute the interference graph */
11275         walk_variable_lifetimes(
11276                 state, rstate.blocks, graph_ins, &rstate);
11277
11278         /* Display the interference graph if desired */
11279         if (state->debug & DEBUG_INTERFERENCE) {
11280                 printf("\nlive variables by block\n");
11281                 walk_blocks(state, print_interference_block, &rstate);
11282                 printf("\nlive variables by instruction\n");
11283                 walk_variable_lifetimes(
11284                         state, rstate.blocks, 
11285                         print_interference_ins, &rstate);
11286         }
11287
11288         /* Do not perform coalescing!  It is a neat idea but it limits what
11289          * we can do later.  It has no benefits that decrease register pressure.
11290          * It only decreases instruction count.
11291          *
11292          * It might be worth testing this reducing the number of
11293          * live_ragnes as opposed to splitting them seems to help.
11294          */
11295
11296         /* Build the groups low and high.  But with the nodes
11297          * first sorted by degree order.
11298          */
11299         rstate.low_tail  = &rstate.low;
11300         rstate.high_tail = &rstate.high;
11301         rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
11302         if (rstate.high) {
11303                 rstate.high->group_prev = &rstate.high;
11304         }
11305         for(point = &rstate.high; *point; point = &(*point)->group_next)
11306                 ;
11307         rstate.high_tail = point;
11308         /* Walk through the high list and move everything that needs
11309          * to be onto low.
11310          */
11311         for(point = &rstate.high; *point; point = next) {
11312                 struct live_range *range;
11313                 next = &(*point)->group_next;
11314                 range = *point;
11315
11316                 /* If it has a low degree or it already has a color
11317                  * place the node in low.
11318                  */
11319                 if ((range->degree < regc_max_size(state, range->classes)) ||
11320                         (range->color != REG_UNSET)) {
11321                         cgdebug_printf("Lo: %5d degree %5d%s\n", 
11322                                 range - rstate.lr, range->degree,
11323                                 (range->color != REG_UNSET) ? " (colored)": "");
11324                         *range->group_prev = range->group_next;
11325                         if (range->group_next) {
11326                                 range->group_next->group_prev = range->group_prev;
11327                         }
11328                         if (&range->group_next == rstate.high_tail) {
11329                                 rstate.high_tail = range->group_prev;
11330                         }
11331                         range->group_prev  = rstate.low_tail;
11332                         range->group_next  = 0;
11333                         *rstate.low_tail   = range;
11334                         rstate.low_tail    = &range->group_next;
11335                         next = point;
11336                 }
11337                 else {
11338                         cgdebug_printf("hi: %5d degree %5d%s\n", 
11339                                 range - rstate.lr, range->degree,
11340                                 (range->color != REG_UNSET) ? " (colored)": "");
11341                 }
11342                 
11343         }
11344         /* Color the live_ranges */
11345         color_graph(state, &rstate);
11346
11347         /* Verify the graph was properly colored */
11348         verify_colors(state, &rstate);
11349
11350         /* Move the colors from the graph to the triples */
11351         color_triples(state, &rstate);
11352
11353         /* Free the edges on each node */
11354         for(i = 1; i <= rstate.ranges; i++) {
11355                 remove_live_edges(&rstate, &rstate.lr[i]);
11356         }
11357         xfree(rstate.lr);
11358
11359         /* Free the variable lifetime information */
11360         free_variable_lifetimes(state, rstate.blocks);
11361
11362 }
11363
11364 /* Sparce Conditional Constant Propogation
11365  * =========================================
11366  */
11367 struct ssa_edge;
11368 struct flow_block;
11369 struct lattice_node {
11370         struct triple *def;
11371         struct ssa_edge *out;
11372         struct flow_block *fblock;
11373         struct triple *val;
11374         /* lattice high   val && !is_const(val) 
11375          * lattice const  is_const(val)
11376          * lattice low    val == 0
11377          */
11378 };
11379 struct ssa_edge {
11380         struct lattice_node *src;
11381         struct lattice_node *dst;
11382         struct ssa_edge *work_next;
11383         struct ssa_edge *work_prev;
11384         struct ssa_edge *out_next;
11385 };
11386 struct flow_edge {
11387         struct flow_block *src;
11388         struct flow_block *dst;
11389         struct flow_edge *work_next;
11390         struct flow_edge *work_prev;
11391         struct flow_edge *in_next;
11392         struct flow_edge *out_next;
11393         int executable;
11394 };
11395 struct flow_block {
11396         struct block *block;
11397         struct flow_edge *in;
11398         struct flow_edge *out;
11399         struct flow_edge left, right;
11400 };
11401
11402 struct scc_state {
11403         int ins_count;
11404         struct lattice_node *lattice;
11405         struct ssa_edge     *ssa_edges;
11406         struct flow_block   *flow_blocks;
11407         struct flow_edge    *flow_work_list;
11408         struct ssa_edge     *ssa_work_list;
11409 };
11410
11411
11412 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
11413         struct flow_edge *fedge)
11414 {
11415         if (!scc->flow_work_list) {
11416                 scc->flow_work_list = fedge;
11417                 fedge->work_next = fedge->work_prev = fedge;
11418         }
11419         else {
11420                 struct flow_edge *ftail;
11421                 ftail = scc->flow_work_list->work_prev;
11422                 fedge->work_next = ftail->work_next;
11423                 fedge->work_prev = ftail;
11424                 fedge->work_next->work_prev = fedge;
11425                 fedge->work_prev->work_next = fedge;
11426         }
11427 }
11428
11429 static struct flow_edge *scc_next_fedge(
11430         struct compile_state *state, struct scc_state *scc)
11431 {
11432         struct flow_edge *fedge;
11433         fedge = scc->flow_work_list;
11434         if (fedge) {
11435                 fedge->work_next->work_prev = fedge->work_prev;
11436                 fedge->work_prev->work_next = fedge->work_next;
11437                 if (fedge->work_next != fedge) {
11438                         scc->flow_work_list = fedge->work_next;
11439                 } else {
11440                         scc->flow_work_list = 0;
11441                 }
11442         }
11443         return fedge;
11444 }
11445
11446 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
11447         struct ssa_edge *sedge)
11448 {
11449         if (!scc->ssa_work_list) {
11450                 scc->ssa_work_list = sedge;
11451                 sedge->work_next = sedge->work_prev = sedge;
11452         }
11453         else {
11454                 struct ssa_edge *stail;
11455                 stail = scc->ssa_work_list->work_prev;
11456                 sedge->work_next = stail->work_next;
11457                 sedge->work_prev = stail;
11458                 sedge->work_next->work_prev = sedge;
11459                 sedge->work_prev->work_next = sedge;
11460         }
11461 }
11462
11463 static struct ssa_edge *scc_next_sedge(
11464         struct compile_state *state, struct scc_state *scc)
11465 {
11466         struct ssa_edge *sedge;
11467         sedge = scc->ssa_work_list;
11468         if (sedge) {
11469                 sedge->work_next->work_prev = sedge->work_prev;
11470                 sedge->work_prev->work_next = sedge->work_next;
11471                 if (sedge->work_next != sedge) {
11472                         scc->ssa_work_list = sedge->work_next;
11473                 } else {
11474                         scc->ssa_work_list = 0;
11475                 }
11476         }
11477         return sedge;
11478 }
11479
11480 static void initialize_scc_state(
11481         struct compile_state *state, struct scc_state *scc)
11482 {
11483         int ins_count, ssa_edge_count;
11484         int ins_index, ssa_edge_index, fblock_index;
11485         struct triple *first, *ins;
11486         struct block *block;
11487         struct flow_block *fblock;
11488
11489         memset(scc, 0, sizeof(*scc));
11490
11491         /* Inialize pass zero find out how much memory we need */
11492         first = RHS(state->main_function, 0);
11493         ins = first;
11494         ins_count = ssa_edge_count = 0;
11495         do {
11496                 struct triple_set *edge;
11497                 ins_count += 1;
11498                 for(edge = ins->use; edge; edge = edge->next) {
11499                         ssa_edge_count++;
11500                 }
11501                 ins = ins->next;
11502         } while(ins != first);
11503 #if DEBUG_SCC
11504         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
11505                 ins_count, ssa_edge_count, state->last_vertex);
11506 #endif
11507         scc->ins_count   = ins_count;
11508         scc->lattice     = 
11509                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
11510         scc->ssa_edges   = 
11511                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
11512         scc->flow_blocks = 
11513                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
11514                         "flow_blocks");
11515
11516         /* Initialize pass one collect up the nodes */
11517         fblock = 0;
11518         block = 0;
11519         ins_index = ssa_edge_index = fblock_index = 0;
11520         ins = first;
11521         do {
11522                 ins->id = 0;
11523                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11524                         block = ins->u.block;
11525                         if (!block) {
11526                                 internal_error(state, ins, "label without block");
11527                         }
11528                         fblock_index += 1;
11529                         block->vertex = fblock_index;
11530                         fblock = &scc->flow_blocks[fblock_index];
11531                         fblock->block = block;
11532                 }
11533                 {
11534                         struct lattice_node *lnode;
11535                         ins_index += 1;
11536                         ins->id = ins_index;
11537                         lnode = &scc->lattice[ins_index];
11538                         lnode->def = ins;
11539                         lnode->out = 0;
11540                         lnode->fblock = fblock;
11541                         lnode->val = ins; /* LATTICE HIGH */
11542                 }
11543                 ins = ins->next;
11544         } while(ins != first);
11545         /* Initialize pass two collect up the edges */
11546         block = 0;
11547         fblock = 0;
11548         ins = first;
11549         do {
11550                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
11551                         struct flow_edge *fedge, **ftail;
11552                         struct block_set *bedge;
11553                         block = ins->u.block;
11554                         fblock = &scc->flow_blocks[block->vertex];
11555                         fblock->in = 0;
11556                         fblock->out = 0;
11557                         ftail = &fblock->out;
11558                         if (block->left) {
11559                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
11560                                 if (fblock->left.dst->block != block->left) {
11561                                         internal_error(state, 0, "block mismatch");
11562                                 }
11563                                 fblock->left.out_next = 0;
11564                                 *ftail = &fblock->left;
11565                                 ftail = &fblock->left.out_next;
11566                         }
11567                         if (block->right) {
11568                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
11569                                 if (fblock->right.dst->block != block->right) {
11570                                         internal_error(state, 0, "block mismatch");
11571                                 }
11572                                 fblock->right.out_next = 0;
11573                                 *ftail = &fblock->right;
11574                                 ftail = &fblock->right.out_next;
11575                         }
11576                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
11577                                 fedge->src = fblock;
11578                                 fedge->work_next = fedge->work_prev = fedge;
11579                                 fedge->executable = 0;
11580                         }
11581                         ftail = &fblock->in;
11582                         for(bedge = block->use; bedge; bedge = bedge->next) {
11583                                 struct block *src_block;
11584                                 struct flow_block *sfblock;
11585                                 struct flow_edge *sfedge;
11586                                 src_block = bedge->member;
11587                                 sfblock = &scc->flow_blocks[src_block->vertex];
11588                                 sfedge = 0;
11589                                 if (src_block->left == block) {
11590                                         sfedge = &sfblock->left;
11591                                 } else {
11592                                         sfedge = &sfblock->right;
11593                                 }
11594                                 *ftail = sfedge;
11595                                 ftail = &sfedge->in_next;
11596                                 sfedge->in_next = 0;
11597                         }
11598                 }
11599                 {
11600                         struct triple_set *edge;
11601                         struct ssa_edge **stail;
11602                         struct lattice_node *lnode;
11603                         lnode = &scc->lattice[ins->id];
11604                         lnode->out = 0;
11605                         stail = &lnode->out;
11606                         for(edge = ins->use; edge; edge = edge->next) {
11607                                 struct ssa_edge *sedge;
11608                                 ssa_edge_index += 1;
11609                                 sedge = &scc->ssa_edges[ssa_edge_index];
11610                                 *stail = sedge;
11611                                 stail = &sedge->out_next;
11612                                 sedge->src = lnode;
11613                                 sedge->dst = &scc->lattice[edge->member->id];
11614                                 sedge->work_next = sedge->work_prev = sedge;
11615                                 sedge->out_next = 0;
11616                         }
11617                 }
11618                 ins = ins->next;
11619         } while(ins != first);
11620         /* Setup a dummy block 0 as a node above the start node */
11621         {
11622                 struct flow_block *fblock, *dst;
11623                 struct flow_edge *fedge;
11624                 fblock = &scc->flow_blocks[0];
11625                 fblock->block = 0;
11626                 fblock->in = 0;
11627                 fblock->out = &fblock->left;
11628                 dst = &scc->flow_blocks[state->first_block->vertex];
11629                 fedge = &fblock->left;
11630                 fedge->src        = fblock;
11631                 fedge->dst        = dst;
11632                 fedge->work_next  = fedge;
11633                 fedge->work_prev  = fedge;
11634                 fedge->in_next    = fedge->dst->in;
11635                 fedge->out_next   = 0;
11636                 fedge->executable = 0;
11637                 fedge->dst->in = fedge;
11638                 
11639                 /* Initialize the work lists */
11640                 scc->flow_work_list = 0;
11641                 scc->ssa_work_list  = 0;
11642                 scc_add_fedge(state, scc, fedge);
11643         }
11644 #if DEBUG_SCC
11645         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
11646                 ins_index, ssa_edge_index, fblock_index);
11647 #endif
11648 }
11649
11650         
11651 static void free_scc_state(
11652         struct compile_state *state, struct scc_state *scc)
11653 {
11654         int i;
11655         for(i = 0; i < scc->ins_count; i++) {
11656                 if (scc->lattice[i].val && 
11657                         (scc->lattice[i].val != scc->lattice[i].def)) {
11658                         xfree(scc->lattice[i].val);
11659                 }
11660         }
11661         xfree(scc->flow_blocks);
11662         xfree(scc->ssa_edges);
11663         xfree(scc->lattice);
11664         
11665 }
11666
11667 static struct lattice_node *triple_to_lattice(
11668         struct compile_state *state, struct scc_state *scc, struct triple *ins)
11669 {
11670         if (ins->id <= 0) {
11671                 internal_error(state, ins, "bad id");
11672         }
11673         return &scc->lattice[ins->id];
11674 }
11675
11676 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
11677         struct lattice_node *lnode)
11678 {
11679         struct lattice_node *tmp;
11680         struct triple **slot;
11681         struct flow_edge *fedge;
11682         int index;
11683         if (lnode->def->op != OP_PHI) {
11684                 internal_error(state, lnode->def, "not phi");
11685         }
11686         /* default to lattice high */
11687         lnode->val = lnode->def;
11688         slot = &RHS(lnode->def, 0);
11689         index = 0;
11690         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
11691                 if (!fedge->executable) {
11692                         continue;
11693                 }
11694                 if (!slot[index]) {
11695                         internal_error(state, lnode->def, "no phi value");
11696                 }
11697                 tmp = triple_to_lattice(state, scc, slot[index]);
11698                 /* meet(X, lattice low) = lattice low */
11699                 if (!tmp->val) {
11700                         lnode->val = 0;
11701                 }
11702                 /* meet(X, lattice high) = X */
11703                 else if (!tmp->val) {
11704                         lnode->val = lnode->val;
11705                 }
11706                 /* meet(lattice high, X) = X */
11707                 else if (!is_const(lnode->val)) {
11708                         lnode->val = tmp->val;
11709                 }
11710                 /* meet(const, const) = const or lattice low */
11711                 else if (!constants_equal(state, lnode->val, tmp->val)) {
11712                         lnode->val = 0;
11713                 }
11714                 if (!lnode->val) {
11715                         break;
11716                 }
11717         }
11718         /* Do I need to update any work lists here? */
11719 #if DEBUG_SCC
11720         fprintf(stderr, "phi: %d -> %s\n",
11721                 lnode->def->id,
11722                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11723 #endif
11724 }
11725
11726 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
11727         struct lattice_node *lnode)
11728 {
11729         int changed;
11730         struct triple *old, *scratch;
11731         struct triple **dexpr, **vexpr;
11732         int count, i;
11733         
11734         if (lnode->def->op != OP_STORE) {
11735                 check_lhs(state,  lnode->def);
11736         }
11737
11738         /* Store the original value */
11739         if (lnode->val) {
11740                 old = dup_triple(state, lnode->val);
11741                 if (lnode->val != lnode->def) {
11742                         xfree(lnode->val);
11743                 }
11744                 lnode->val = 0;
11745
11746         } else {
11747                 old = 0;
11748         }
11749         /* Reinitialize the value */
11750         lnode->val = scratch = dup_triple(state, lnode->def);
11751         scratch->next     = scratch;
11752         scratch->prev     = scratch;
11753         scratch->use      = 0;
11754
11755         count = TRIPLE_SIZE(scratch->sizes);
11756         for(i = 0; i < count; i++) {
11757                 struct lattice_node *tmp;
11758                 dexpr = &lnode->def->param[i];
11759                 vexpr = &scratch->param[i];
11760                 *vexpr = 0;
11761                 if (*dexpr) {
11762                         tmp = triple_to_lattice(state, scc, *dexpr);
11763                         *vexpr = (tmp->val)? tmp->val : tmp->def;
11764                 }
11765         }
11766         if (scratch->op == OP_BRANCH) {
11767                 scratch->next = lnode->def->next;
11768         }
11769         /* Recompute the value */
11770 #warning "FIXME see if simplify does anything bad"
11771         /* So far it looks like only the strength reduction
11772          * optimization are things I need to worry about.
11773          */
11774         simplify(state, scratch);
11775         /* Cleanup my value */
11776         if (scratch->use) {
11777                 internal_error(state, lnode->def, "scratch used?");
11778         }
11779         if ((scratch->prev != scratch) ||
11780                 ((scratch->next != scratch) &&
11781                         ((lnode->def->op != OP_BRANCH) ||
11782                                 (scratch->next != lnode->def->next)))) {
11783                 internal_error(state, lnode->def, "scratch in list?");
11784         }
11785         /* undo any uses... */
11786         count = TRIPLE_SIZE(scratch->sizes);
11787         for(i = 0; i < count; i++) {
11788                 vexpr = &scratch->param[i];
11789                 if (*vexpr) {
11790                         unuse_triple(*vexpr, scratch);
11791                 }
11792         }
11793         if (!is_const(scratch)) {
11794                 for(i = 0; i < count; i++) {
11795                         dexpr = &lnode->def->param[i];
11796                         if (*dexpr) {
11797                                 struct lattice_node *tmp;
11798                                 tmp = triple_to_lattice(state, scc, *dexpr);
11799                                 if (!tmp->val) {
11800                                         lnode->val = 0;
11801                                 }
11802                         }
11803                 }
11804         }
11805         if (lnode->val && 
11806                 (lnode->val->op == lnode->def->op) &&
11807                 (memcmp(lnode->val->param, lnode->def->param, 
11808                         count * sizeof(lnode->val->param[0])) == 0) &&
11809                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
11810                 lnode->val = lnode->def;
11811         }
11812         /* Find the cases that are always lattice lo */
11813         if (lnode->val && 
11814                 triple_is_def(state, lnode->val) &&
11815                 !triple_is_pure(state, lnode->val)) {
11816                 lnode->val = 0;
11817         }
11818 #if 1
11819         if (lnode->val && 
11820                 (lnode->val->op == OP_SDECL) && 
11821                 (lnode->val != lnode->def)) {
11822                 internal_error(state, lnode->def, "bad sdecl");
11823         }
11824 #endif
11825         /* See if the lattice value has changed */
11826         changed = 1;
11827         if (!old && !lnode->val) {
11828                 changed = 0;
11829         }
11830         if (changed && lnode->val && !is_const(lnode->val)) {
11831                 changed = 0;
11832         }
11833         if (changed &&
11834                 lnode->val && old &&
11835                 (lnode->val->op == old->op) &&
11836                 (memcmp(lnode->val->param, old->param,
11837                         count * sizeof(lnode->val->param[0])) == 0) &&
11838                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
11839                 changed = 0;
11840         }
11841         if (old) {
11842                 xfree(old);
11843         }
11844         if (lnode->val != scratch) {
11845                 xfree(scratch);
11846         }
11847         return changed;
11848 }
11849
11850 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
11851         struct lattice_node *lnode)
11852 {
11853         struct lattice_node *cond;
11854 #if DEBUG_SCC
11855         {
11856                 struct flow_edge *fedge;
11857                 fprintf(stderr, "branch: %d (",
11858                         lnode->def->id);
11859                 
11860                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
11861                         fprintf(stderr, " %d", fedge->dst->block->vertex);
11862                 }
11863                 fprintf(stderr, " )");
11864                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
11865                         fprintf(stderr, " <- %d",
11866                                 RHS(lnode->def)->id);
11867                 }
11868                 fprintf(stderr, "\n");
11869         }
11870 #endif
11871         if (lnode->def->op != OP_BRANCH) {
11872                 internal_error(state, lnode->def, "not branch");
11873         }
11874         /* This only applies to conditional branches */
11875         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
11876                 return;
11877         }
11878         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
11879         if (cond->val && !is_const(cond->val)) {
11880 #warning "FIXME do I need to do something here?"
11881                 warning(state, cond->def, "condition not constant?");
11882                 return;
11883         }
11884         if (cond->val == 0) {
11885                 scc_add_fedge(state, scc, cond->fblock->out);
11886                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11887         }
11888         else if (cond->val->u.cval) {
11889                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
11890                 
11891         } else {
11892                 scc_add_fedge(state, scc, cond->fblock->out);
11893         }
11894
11895 }
11896
11897 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
11898         struct lattice_node *lnode)
11899 {
11900         int changed;
11901
11902         changed = compute_lnode_val(state, scc, lnode);
11903 #if DEBUG_SCC
11904         {
11905                 struct triple **expr;
11906                 fprintf(stderr, "expr: %3d %10s (",
11907                         lnode->def->id, tops(lnode->def->op));
11908                 expr = triple_rhs(state, lnode->def, 0);
11909                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
11910                         if (*expr) {
11911                                 fprintf(stderr, " %d", (*expr)->id);
11912                         }
11913                 }
11914                 fprintf(stderr, " ) -> %s\n",
11915                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
11916         }
11917 #endif
11918         if (lnode->def->op == OP_BRANCH) {
11919                 scc_visit_branch(state, scc, lnode);
11920
11921         }
11922         else if (changed) {
11923                 struct ssa_edge *sedge;
11924                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
11925                         scc_add_sedge(state, scc, sedge);
11926                 }
11927         }
11928 }
11929
11930 static void scc_writeback_values(
11931         struct compile_state *state, struct scc_state *scc)
11932 {
11933         struct triple *first, *ins;
11934         first = RHS(state->main_function, 0);
11935         ins = first;
11936         do {
11937                 struct lattice_node *lnode;
11938                 lnode = triple_to_lattice(state, scc, ins);
11939 #if DEBUG_SCC
11940                 if (lnode->val && !is_const(lnode->val)) {
11941                         warning(state, lnode->def, 
11942                                 "lattice node still high?");
11943                 }
11944 #endif
11945                 if (lnode->val && (lnode->val != ins)) {
11946                         /* See if it something I know how to write back */
11947                         switch(lnode->val->op) {
11948                         case OP_INTCONST:
11949                                 mkconst(state, ins, lnode->val->u.cval);
11950                                 break;
11951                         case OP_ADDRCONST:
11952                                 mkaddr_const(state, ins, 
11953                                         RHS(lnode->val, 0), lnode->val->u.cval);
11954                                 break;
11955                         default:
11956                                 /* By default don't copy the changes,
11957                                  * recompute them in place instead.
11958                                  */
11959                                 simplify(state, ins);
11960                                 break;
11961                         }
11962                 }
11963                 ins = ins->next;
11964         } while(ins != first);
11965 }
11966
11967 static void scc_transform(struct compile_state *state)
11968 {
11969         struct scc_state scc;
11970
11971         initialize_scc_state(state, &scc);
11972
11973         while(scc.flow_work_list || scc.ssa_work_list) {
11974                 struct flow_edge *fedge;
11975                 struct ssa_edge *sedge;
11976                 struct flow_edge *fptr;
11977                 while((fedge = scc_next_fedge(state, &scc))) {
11978                         struct block *block;
11979                         struct triple *ptr;
11980                         struct flow_block *fblock;
11981                         int time;
11982                         int done;
11983                         if (fedge->executable) {
11984                                 continue;
11985                         }
11986                         if (!fedge->dst) {
11987                                 internal_error(state, 0, "fedge without dst");
11988                         }
11989                         if (!fedge->src) {
11990                                 internal_error(state, 0, "fedge without src");
11991                         }
11992                         fedge->executable = 1;
11993                         fblock = fedge->dst;
11994                         block = fblock->block;
11995                         time = 0;
11996                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
11997                                 if (fptr->executable) {
11998                                         time++;
11999                                 }
12000                         }
12001 #if DEBUG_SCC
12002                         fprintf(stderr, "vertex: %d time: %d\n", 
12003                                 block->vertex, time);
12004                         
12005 #endif
12006                         done = 0;
12007                         for(ptr = block->first; !done; ptr = ptr->next) {
12008                                 struct lattice_node *lnode;
12009                                 done = (ptr == block->last);
12010                                 lnode = &scc.lattice[ptr->id];
12011                                 if (ptr->op == OP_PHI) {
12012                                         scc_visit_phi(state, &scc, lnode);
12013                                 }
12014                                 else if (time == 1) {
12015                                         scc_visit_expr(state, &scc, lnode);
12016                                 }
12017                         }
12018                         if (fblock->out && !fblock->out->out_next) {
12019                                 scc_add_fedge(state, &scc, fblock->out);
12020                         }
12021                 }
12022                 while((sedge = scc_next_sedge(state, &scc))) {
12023                         struct lattice_node *lnode;
12024                         struct flow_block *fblock;
12025                         lnode = sedge->dst;
12026                         fblock = lnode->fblock;
12027 #if DEBUG_SCC
12028                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
12029                                 sedge - scc.ssa_edges,
12030                                 sedge->src->def->id,
12031                                 sedge->dst->def->id);
12032 #endif
12033                         if (lnode->def->op == OP_PHI) {
12034                                 scc_visit_phi(state, &scc, lnode);
12035                         }
12036                         else {
12037                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
12038                                         if (fptr->executable) {
12039                                                 break;
12040                                         }
12041                                 }
12042                                 if (fptr) {
12043                                         scc_visit_expr(state, &scc, lnode);
12044                                 }
12045                         }
12046                 }
12047         }
12048         
12049         scc_writeback_values(state, &scc);
12050         free_scc_state(state, &scc);
12051 }
12052
12053
12054 static void transform_to_arch_instructions(struct compile_state *state);
12055
12056
12057 static void optimize(struct compile_state *state)
12058 {
12059         if (state->debug & DEBUG_TRIPLES) {
12060                 print_triples(state);
12061         }
12062         /* Replace structures with simpler data types */
12063         flatten_structures(state);
12064         if (state->debug & DEBUG_TRIPLES) {
12065                 print_triples(state);
12066         }
12067         /* Analize the intermediate code */
12068         setup_basic_blocks(state);
12069         analyze_idominators(state);
12070         analyze_ipdominators(state);
12071         /* Transform the code to ssa form */
12072         transform_to_ssa_form(state);
12073         /* Do strength reduction and simple constant optimizations */
12074         if (state->optimize >= 1) {
12075                 simplify_all(state);
12076         }
12077         /* Propogate constants throughout the code */
12078         if (state->optimize >= 2) {
12079                 scc_transform(state);
12080                 transform_from_ssa_form(state);
12081                 free_basic_blocks(state);
12082                 setup_basic_blocks(state);
12083                 analyze_idominators(state);
12084                 analyze_ipdominators(state);
12085                 transform_to_ssa_form(state);
12086                 
12087         }
12088 #warning "WISHLIST implement single use constants (least possible register pressure)"
12089 #warning "WISHLIST implement induction variable elimination"
12090 #warning "WISHLIST implement strength reduction"
12091         /* Select architecture instructions and an initial partial
12092          * coloring based on architecture constraints.
12093          */
12094         transform_to_arch_instructions(state);
12095         if (state->debug & DEBUG_ARCH_CODE) {
12096                 printf("After transform_to_arch_instructions\n");
12097                 print_blocks(state);
12098                 print_control_flow(state);
12099         }
12100         eliminate_inefectual_code(state);
12101         if (state->debug & DEBUG_CODE_ELIMINATION) {
12102                 printf("After eliminate_inefectual_code\n");
12103                 print_blocks(state);
12104                 print_control_flow(state);
12105         }
12106         /* Color all of the variables to see if they will fit in registers */
12107         insert_copies_to_phi(state);
12108         allocate_registers(state);
12109         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
12110                 print_blocks(state);
12111         }
12112         if (state->debug & DEBUG_CONTROL_FLOW) {
12113                 print_control_flow(state);
12114         }
12115         /* Remove the optimization information.
12116          * This is more to check for memory consistency than to free memory.
12117          */
12118         free_basic_blocks(state);
12119 }
12120
12121 /* The x86 register classes */
12122 #define REGC_FLAGS   0
12123 #define REGC_GPR8    1
12124 #define REGC_GPR16   2
12125 #define REGC_GPR32   3
12126 #define REGC_GPR64   4
12127 #define REGC_MMX     5
12128 #define REGC_XMM     6
12129 #define REGC_GPR32_8 7
12130 #define REGC_GPR16_8 8
12131 #define LAST_REGC  REGC_GPR16_8
12132 #if LAST_REGC >= MAX_REGC
12133 #error "MAX_REGC is to low"
12134 #endif
12135
12136 /* Register class masks */
12137 #define REGCM_FLAGS   (1 << REGC_FLAGS)
12138 #define REGCM_GPR8    (1 << REGC_GPR8)
12139 #define REGCM_GPR16   (1 << REGC_GPR16)
12140 #define REGCM_GPR32   (1 << REGC_GPR32)
12141 #define REGCM_GPR64   (1 << REGC_GPR64)
12142 #define REGCM_MMX     (1 << REGC_MMX)
12143 #define REGCM_XMM     (1 << REGC_XMM)
12144 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
12145 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
12146
12147 /* The x86 registers */
12148 #define REG_EFLAGS  1
12149 #define REGC_FLAGS_FIRST REG_EFLAGS
12150 #define REGC_FLAGS_LAST  REG_EFLAGS
12151 #define REG_AL      2
12152 #define REG_BL      3
12153 #define REG_CL      4
12154 #define REG_DL      5
12155 #define REG_AH      6
12156 #define REG_BH      7
12157 #define REG_CH      8
12158 #define REG_DH      9
12159 #define REGC_GPR8_FIRST  REG_AL
12160 #if X86_4_8BIT_GPRS
12161 #define REGC_GPR8_LAST   REG_DL
12162 #else 
12163 #define REGC_GPR8_LAST   REG_DH
12164 #endif
12165 #define REG_AX     10
12166 #define REG_BX     11
12167 #define REG_CX     12
12168 #define REG_DX     13
12169 #define REG_SI     14
12170 #define REG_DI     15
12171 #define REG_BP     16
12172 #define REG_SP     17
12173 #define REGC_GPR16_FIRST REG_AX
12174 #define REGC_GPR16_LAST  REG_SP
12175 #define REG_EAX    18
12176 #define REG_EBX    19
12177 #define REG_ECX    20
12178 #define REG_EDX    21
12179 #define REG_ESI    22
12180 #define REG_EDI    23
12181 #define REG_EBP    24
12182 #define REG_ESP    25
12183 #define REGC_GPR32_FIRST REG_EAX
12184 #define REGC_GPR32_LAST  REG_ESP
12185 #define REG_EDXEAX 26
12186 #define REGC_GPR64_FIRST REG_EDXEAX
12187 #define REGC_GPR64_LAST  REG_EDXEAX
12188 #define REG_MMX0   27
12189 #define REG_MMX1   28
12190 #define REG_MMX2   29
12191 #define REG_MMX3   30
12192 #define REG_MMX4   31
12193 #define REG_MMX5   32
12194 #define REG_MMX6   33
12195 #define REG_MMX7   34
12196 #define REGC_MMX_FIRST REG_MMX0
12197 #define REGC_MMX_LAST  REG_MMX7
12198 #define REG_XMM0   35
12199 #define REG_XMM1   36
12200 #define REG_XMM2   37
12201 #define REG_XMM3   38
12202 #define REG_XMM4   39
12203 #define REG_XMM5   40
12204 #define REG_XMM6   41
12205 #define REG_XMM7   42
12206 #define REGC_XMM_FIRST REG_XMM0
12207 #define REGC_XMM_LAST  REG_XMM7
12208 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
12209 #define LAST_REG   REG_XMM7
12210
12211 #define REGC_GPR32_8_FIRST REG_EAX
12212 #define REGC_GPR32_8_LAST  REG_EDX
12213 #define REGC_GPR16_8_FIRST REG_AX
12214 #define REGC_GPR16_8_LAST  REG_DX
12215
12216 #if LAST_REG >= MAX_REGISTERS
12217 #error "MAX_REGISTERS to low"
12218 #endif
12219
12220 static unsigned arch_regc_size(struct compile_state *state, int class)
12221 {
12222         static unsigned regc_size[LAST_REGC +1] = {
12223                 [REGC_FLAGS]   = REGC_FLAGS_LAST   - REGC_FLAGS_FIRST + 1,
12224                 [REGC_GPR8]    = REGC_GPR8_LAST    - REGC_GPR8_FIRST + 1,
12225                 [REGC_GPR16]   = REGC_GPR16_LAST   - REGC_GPR16_FIRST + 1,
12226                 [REGC_GPR32]   = REGC_GPR32_LAST   - REGC_GPR32_FIRST + 1,
12227                 [REGC_GPR64]   = REGC_GPR64_LAST   - REGC_GPR64_FIRST + 1,
12228                 [REGC_MMX]     = REGC_MMX_LAST     - REGC_MMX_FIRST + 1,
12229                 [REGC_XMM]     = REGC_XMM_LAST     - REGC_XMM_FIRST + 1,
12230                 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
12231                 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
12232         };
12233         if ((class < 0) || (class > LAST_REGC)) {
12234                 return 0;
12235         }
12236         return regc_size[class];
12237 }
12238 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
12239 {
12240         /* See if two register classes may have overlapping registers */
12241         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
12242                 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
12243
12244         return (regcm1 & regcm2) ||
12245                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
12246 }
12247
12248 static void arch_reg_equivs(
12249         struct compile_state *state, unsigned *equiv, int reg)
12250 {
12251         if ((reg < 0) || (reg > LAST_REG)) {
12252                 internal_error(state, 0, "invalid register");
12253         }
12254         *equiv++ = reg;
12255         switch(reg) {
12256         case REG_AL:
12257         case REG_AH:
12258                 *equiv++ = REG_AX;
12259                 *equiv++ = REG_EAX;
12260                 *equiv++ = REG_EDXEAX;
12261                 break;
12262         case REG_BL:  
12263         case REG_BH:
12264                 *equiv++ = REG_BX;
12265                 *equiv++ = REG_EBX;
12266                 break;
12267         case REG_CL:
12268         case REG_CH:
12269                 *equiv++ = REG_CX;
12270                 *equiv++ = REG_ECX;
12271                 break;
12272         case REG_DL:
12273         case REG_DH:
12274                 *equiv++ = REG_DX;
12275                 *equiv++ = REG_EDX;
12276                 *equiv++ = REG_EDXEAX;
12277                 break;
12278         case REG_AX:
12279                 *equiv++ = REG_AL;
12280                 *equiv++ = REG_AH;
12281                 *equiv++ = REG_EAX;
12282                 *equiv++ = REG_EDXEAX;
12283                 break;
12284         case REG_BX:
12285                 *equiv++ = REG_BL;
12286                 *equiv++ = REG_BH;
12287                 *equiv++ = REG_EBX;
12288                 break;
12289         case REG_CX:  
12290                 *equiv++ = REG_CL;
12291                 *equiv++ = REG_CH;
12292                 *equiv++ = REG_ECX;
12293                 break;
12294         case REG_DX:  
12295                 *equiv++ = REG_DL;
12296                 *equiv++ = REG_DH;
12297                 *equiv++ = REG_EDX;
12298                 *equiv++ = REG_EDXEAX;
12299                 break;
12300         case REG_SI:  
12301                 *equiv++ = REG_ESI;
12302                 break;
12303         case REG_DI:
12304                 *equiv++ = REG_EDI;
12305                 break;
12306         case REG_BP:
12307                 *equiv++ = REG_EBP;
12308                 break;
12309         case REG_SP:
12310                 *equiv++ = REG_ESP;
12311                 break;
12312         case REG_EAX:
12313                 *equiv++ = REG_AL;
12314                 *equiv++ = REG_AH;
12315                 *equiv++ = REG_AX;
12316                 *equiv++ = REG_EDXEAX;
12317                 break;
12318         case REG_EBX:
12319                 *equiv++ = REG_BL;
12320                 *equiv++ = REG_BH;
12321                 *equiv++ = REG_BX;
12322                 break;
12323         case REG_ECX:
12324                 *equiv++ = REG_CL;
12325                 *equiv++ = REG_CH;
12326                 *equiv++ = REG_CX;
12327                 break;
12328         case REG_EDX:
12329                 *equiv++ = REG_DL;
12330                 *equiv++ = REG_DH;
12331                 *equiv++ = REG_DX;
12332                 *equiv++ = REG_EDXEAX;
12333                 break;
12334         case REG_ESI: 
12335                 *equiv++ = REG_SI;
12336                 break;
12337         case REG_EDI: 
12338                 *equiv++ = REG_DI;
12339                 break;
12340         case REG_EBP: 
12341                 *equiv++ = REG_BP;
12342                 break;
12343         case REG_ESP: 
12344                 *equiv++ = REG_SP;
12345                 break;
12346         case REG_EDXEAX: 
12347                 *equiv++ = REG_AL;
12348                 *equiv++ = REG_AH;
12349                 *equiv++ = REG_DL;
12350                 *equiv++ = REG_DH;
12351                 *equiv++ = REG_AX;
12352                 *equiv++ = REG_DX;
12353                 *equiv++ = REG_EAX;
12354                 *equiv++ = REG_EDX;
12355                 break;
12356         }
12357         *equiv++ = REG_UNSET; 
12358 }
12359
12360
12361 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
12362 {
12363         static const struct {
12364                 int first, last;
12365         } bound[LAST_REGC + 1] = {
12366                 [REGC_FLAGS]   = { REGC_FLAGS_FIRST,   REGC_FLAGS_LAST },
12367                 [REGC_GPR8]    = { REGC_GPR8_FIRST,    REGC_GPR8_LAST },
12368                 [REGC_GPR16]   = { REGC_GPR16_FIRST,   REGC_GPR16_LAST },
12369                 [REGC_GPR32]   = { REGC_GPR32_FIRST,   REGC_GPR32_LAST },
12370                 [REGC_GPR64]   = { REGC_GPR64_FIRST,   REGC_GPR64_LAST },
12371                 [REGC_MMX]     = { REGC_MMX_FIRST,     REGC_MMX_LAST },
12372                 [REGC_XMM]     = { REGC_XMM_FIRST,     REGC_XMM_LAST },
12373                 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
12374                 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
12375         };
12376         unsigned mask;
12377         int class;
12378         mask = 0;
12379         for(class = 0; class <= LAST_REGC; class++) {
12380                 if ((reg >= bound[class].first) &&
12381                         (reg <= bound[class].last)) {
12382                         mask |= (1 << class);
12383                 }
12384         }
12385         if (!mask) {
12386                 internal_error(state, 0, "reg %d not in any class", reg);
12387         }
12388         return mask;
12389 }
12390
12391 static int do_select_reg(struct compile_state *state, 
12392         char *used, int reg, unsigned classes)
12393 {
12394         unsigned mask;
12395         if (used[reg]) {
12396                 return REG_UNSET;
12397         }
12398         mask = arch_reg_regcm(state, reg);
12399         return (classes & mask) ? reg : REG_UNSET;
12400 }
12401
12402 static int arch_select_free_register(
12403         struct compile_state *state, char *used, int classes)
12404 {
12405         /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
12406          * other types of registers.
12407          */
12408         int i, reg;
12409         reg = REG_UNSET;
12410         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
12411                 reg = do_select_reg(state, used, i, classes);
12412         }
12413         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
12414                 reg = do_select_reg(state, used, i, classes);
12415         }
12416         for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
12417                 reg = do_select_reg(state, used, i, classes);
12418         }
12419         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
12420                 reg = do_select_reg(state, used, i, classes);
12421         }
12422         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
12423                 reg = do_select_reg(state, used, i, classes);
12424         }
12425         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
12426                 reg = do_select_reg(state, used, i, classes);
12427         }
12428         for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
12429                 reg = do_select_reg(state, used, i, classes);
12430         }
12431         return reg;
12432 }
12433
12434 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
12435 {
12436 #warning "FIXME force types smaller (if legal) before I get here"
12437         int use_mmx = 0;
12438         int use_sse = 0;
12439         unsigned avail_mask;
12440         unsigned mask;
12441         avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 | 
12442                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64;
12443 #if 1
12444         /* Don't enable 8 bit values until I can force both operands
12445          * to be 8bits simultaneously.
12446          */
12447         avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
12448 #endif
12449         if (use_mmx) {
12450                 avail_mask |= REGCM_MMX;
12451         }
12452         if (use_sse) {
12453                 avail_mask |= REGCM_XMM;
12454         }
12455         mask = 0;
12456         switch(type->type & TYPE_MASK) {
12457         case TYPE_ARRAY:
12458         case TYPE_VOID: 
12459                 mask = 0; 
12460                 break;
12461         case TYPE_CHAR:
12462         case TYPE_UCHAR:
12463                 mask = REGCM_GPR8 | 
12464                         REGCM_GPR16_8 | REGCM_GPR16 | 
12465                         REGCM_GPR32 | REGCM_GPR32_8 |
12466                         REGCM_GPR64 |
12467                         REGCM_MMX | REGCM_XMM;
12468                 break;
12469         case TYPE_SHORT:
12470         case TYPE_USHORT:
12471                 mask = REGCM_GPR16 | REGCM_GPR16_8 |
12472                         REGCM_GPR32 | REGCM_GPR32_8 |
12473                         REGCM_GPR64 |
12474                         REGCM_MMX | REGCM_XMM;
12475                 break;
12476         case TYPE_INT:
12477         case TYPE_UINT:
12478         case TYPE_LONG:
12479         case TYPE_ULONG:
12480         case TYPE_POINTER:
12481                 mask = REGCM_GPR32 | REGCM_GPR32_8 |
12482                         REGCM_GPR64 | REGCM_MMX | REGCM_XMM;
12483                 break;
12484         default:
12485                 internal_error(state, 0, "no register class for type");
12486                 break;
12487         }
12488         mask &= avail_mask;
12489         return mask;
12490 }
12491
12492 static void get_imm32(struct triple *ins, struct triple **expr)
12493 {
12494         struct triple *imm;
12495         if ((*expr)->op != OP_COPY) {
12496                 return;
12497         }
12498         imm = RHS((*expr), 0);
12499         while(imm->op == OP_COPY) {
12500                 imm = RHS(imm, 0);
12501         }
12502         if (imm->op != OP_INTCONST) {
12503                 return;
12504         }
12505         *expr = imm;
12506         unuse_triple(*expr, ins);
12507         use_triple(*expr, ins);
12508 }
12509
12510 static void get_imm8(struct triple *ins, struct triple **expr)
12511 {
12512         struct triple *imm;
12513         if ((*expr)->op != OP_COPY) {
12514                 return;
12515         }
12516         imm = RHS((*expr), 0);
12517         while(imm->op == OP_COPY) {
12518                 imm = RHS(imm, 0);
12519         }
12520         if (imm->op != OP_INTCONST) {
12521                 return;
12522         }
12523         /* For imm8 only a sufficienlty small constant can be used */
12524         if (imm->u.cval > 0xff) {
12525                 return;
12526         }
12527         *expr = imm;
12528         unuse_triple(*expr, ins);
12529         use_triple(*expr, ins);
12530 }
12531
12532 static struct triple *pre_copy(struct compile_state *state, 
12533         struct triple *ins, struct triple **expr,
12534         unsigned reg, unsigned mask)
12535 {
12536         /* Carefully insert enough operations so that I can
12537          * enter any operation with a GPR32.
12538          */
12539         struct triple *in;
12540         /* See if I can directly reach the result from a GPR32 */
12541         if (mask & (REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)) {
12542                 in = triple(state, OP_COPY, (*expr)->type, *expr,  0);
12543         }
12544         /* If it is a byte value force a earlier copy to a GPR32_8 */
12545         else if (mask & REGCM_GPR8) {
12546                 struct triple *tmp;
12547                 tmp = triple(state, OP_COPY, (*expr)->type, *expr, 0);
12548                 tmp->filename = ins->filename;
12549                 tmp->line     = ins->line;
12550                 tmp->col      = ins->col;
12551                 tmp->u.block  = ins->u.block;
12552                 tmp->id = MK_REG_ID(REG_UNSET, REGCM_GPR32_8 | REGCM_GPR16_8);
12553                 use_triple(RHS(tmp, 0), tmp);
12554                 insert_triple(state, ins, tmp);
12555
12556                 in = triple(state, OP_COPY, tmp->type, tmp, 0);
12557         }
12558         else {
12559                 internal_error(state, ins, "bad copy type");
12560                 in = 0;
12561         }
12562         in->filename  = ins->filename;
12563         in->line      = ins->line;
12564         in->col       = ins->col;
12565         in->u.block   = ins->u.block;
12566         in->id        = MK_REG_ID(reg, mask);
12567         unuse_triple(*expr, ins);
12568         *expr = in;
12569         use_triple(RHS(in, 0), in);
12570         use_triple(in, ins);
12571         insert_triple(state, ins, in);
12572         return in;
12573 }
12574
12575 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
12576 {
12577         struct triple_set *entry, *next;
12578         struct triple *out, *label;
12579         struct block *block;
12580         label = ins;
12581         while(label->op != OP_LABEL) {
12582                 label = label->prev;
12583         }
12584         block = label->u.block;
12585         out = triple(state, OP_COPY, ins->type, ins, 0);
12586         out->filename = ins->filename;
12587         out->line     = ins->line;
12588         out->col      = ins->col;
12589         out->u.block  = block;
12590         out->id       = MK_REG_ID(REG_UNSET, 
12591                 arch_type_to_regcm(state, ins->type));
12592         use_triple(ins, out);
12593         insert_triple(state, ins->next, out);
12594         if (block->last == ins) {
12595                 block->last = out;
12596         }
12597         /* Get the users of ins to use out instead */
12598         for(entry = ins->use; entry; entry = next) {
12599                 next = entry->next;
12600                 if (entry->member == out) {
12601                         continue;
12602                 }
12603                 replace_rhs_use(state, ins, out, entry->member);
12604         }
12605         return out;
12606 }
12607
12608 static void fixup_branches(struct compile_state *state,
12609         struct triple *cmp, struct triple *use, int jmp_op)
12610 {
12611         struct triple_set *entry, *next;
12612         for(entry = use->use; entry; entry = next) {
12613                 next = entry->next;
12614                 if (entry->member->op == OP_COPY) {
12615                         fixup_branches(state, cmp, entry->member, jmp_op);
12616                 }
12617                 else if (entry->member->op == OP_BRANCH) {
12618                         struct triple *branch, *test;
12619                         struct triple *left, *right;
12620                         left = right = 0;
12621                         left = RHS(cmp, 0);
12622                         if (TRIPLE_RHS(cmp->sizes) > 1) {
12623                                 right = RHS(cmp, 1);
12624                         }
12625                         branch = entry->member;
12626                         test = pre_triple(state, branch,
12627                                 cmp->op, cmp->type, left, right);
12628                         test->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12629                         unuse_triple(RHS(branch, 0), branch);
12630                         RHS(branch, 0) = test;
12631                         branch->op = jmp_op;
12632                         use_triple(RHS(branch, 0), branch);
12633                 }
12634         }
12635 }
12636
12637 static void bool_cmp(struct compile_state *state, 
12638         struct triple *ins, int cmp_op, int jmp_op, int set_op)
12639 {
12640         struct block *block;
12641         struct triple_set *entry, *next;
12642         struct triple *set, *tmp1, *tmp2;
12643
12644 #warning "WISHLIST implement an expression simplifier to reduce the use of set?"
12645
12646         block = ins->u.block;
12647
12648         /* Put a barrier up before the cmp which preceeds the
12649          * copy instruction.  If a set actually occurs this gives
12650          * us a chance to move variables in registers out of the way.
12651          */
12652
12653         /* Modify the comparison operator */
12654         ins->op = cmp_op;
12655         ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12656         if (cmp_op == OP_CMP) {
12657                 get_imm32(ins, &RHS(ins, 1));
12658         }
12659         /* Generate the instruction sequence that will transform the
12660          * result of the comparison into a logical value.
12661          */
12662         tmp1 = triple(state, set_op, ins->type, ins, 0);
12663         tmp1->filename = ins->filename;
12664         tmp1->line     = ins->line;
12665         tmp1->col      = ins->col;
12666         tmp1->u.block  = block;
12667         tmp1->id       = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12668         use_triple(ins, tmp1);
12669         insert_triple(state, ins->next, tmp1);
12670         
12671         tmp2 = triple(state, OP_COPY, ins->type, tmp1, 0);
12672         tmp2->filename = ins->filename;
12673         tmp2->line     = ins->line;
12674         tmp2->col      = ins->col;
12675         tmp2->u.block  = block;
12676         tmp2->id       = MK_REG_ID(REG_UNSET, 
12677                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR16 | REGCM_GPR16_8 | REGCM_GPR8);
12678         use_triple(tmp1, tmp2);
12679         insert_triple(state, tmp1->next, tmp2);
12680
12681         if (block->last == ins) {
12682                 block->last = tmp2;
12683         }
12684
12685         set = tmp2;
12686         for(entry = ins->use; entry; entry = next) {
12687                 next = entry->next;
12688                 if (entry->member == tmp1) {
12689                         continue;
12690                 }
12691                 replace_rhs_use(state, ins, set, entry->member);
12692         }
12693         fixup_branches(state, ins, set, jmp_op);
12694 }
12695
12696 static void verify_lhs(struct compile_state *state, struct triple *ins)
12697 {
12698         struct triple *next;
12699         int lhs, i;
12700         lhs = TRIPLE_LHS(ins->sizes);
12701         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
12702                 if (next != LHS(ins, i)) {
12703                         internal_error(state, ins, "malformed lhs on %s",
12704                                 tops(ins->op));
12705                 }
12706         }
12707 }
12708
12709 static void transform_to_arch_instructions(struct compile_state *state)
12710 {
12711         /* Transform from generic 3 address instructions
12712          * to archtecture specific instructions.
12713          * And apply architecture specific constrains to instructions.
12714          * Copies are inserted to preserve the register flexibility
12715          * of 3 address instructions.
12716          */
12717         struct triple *ins, *first, *next;
12718         struct triple *in, *in2;
12719         first = RHS(state->main_function, 0);
12720         ins = first;
12721         do {
12722                 next = ins->next;
12723                 ins->id = MK_REG_ID(REG_UNSET, arch_type_to_regcm(state, ins->type));
12724                 switch(ins->op) {
12725                 case OP_INTCONST:
12726                 case OP_ADDRCONST:
12727                         ins->id = 0;
12728                         post_copy(state, ins);
12729                         break;
12730                 case OP_NOOP:
12731                 case OP_SDECL:
12732                 case OP_BLOBCONST:
12733                 case OP_LABEL:
12734                         ins->id = 0;
12735                         break;
12736                         /* instructions that can be used as is */
12737                 case OP_COPY:
12738                 case OP_PHI:
12739                         break;
12740                 case OP_STORE:
12741                 {
12742                         unsigned mask;
12743                         ins->id = 0;
12744                         switch(ins->type->type & TYPE_MASK) {
12745                         case TYPE_CHAR:    case TYPE_UCHAR:
12746                                 mask = REGCM_GPR8;
12747                                 break;
12748                         case TYPE_SHORT:   case TYPE_USHORT:
12749                                 mask = REGCM_GPR16;
12750                                 break;
12751                         case TYPE_INT:     case TYPE_UINT:
12752                         case TYPE_LONG:    case TYPE_ULONG:
12753                         case TYPE_POINTER:
12754                                 mask  = REGCM_GPR32;
12755                                 break;
12756                         default:
12757                                 internal_error(state, ins, "unknown type in store");
12758                                 mask = 0;
12759                                 break;
12760                         }
12761                         in = pre_copy(state, ins, &RHS(ins, 0), REG_UNSET, mask);
12762                         break;
12763                 }
12764                 case OP_LOAD:
12765                         switch(ins->type->type & TYPE_MASK) {
12766                         case TYPE_CHAR:   case TYPE_UCHAR:
12767                                 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR8);
12768                                 break;
12769                         case TYPE_SHORT:
12770                         case TYPE_USHORT:
12771                                 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR16);
12772                                 break;
12773                         case TYPE_INT:
12774                         case TYPE_UINT:
12775                         case TYPE_LONG:
12776                         case TYPE_ULONG:
12777                         case TYPE_POINTER:
12778                                 ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32);
12779                                 break;
12780                         default:
12781                                 internal_error(state, ins, "unknown type in load");
12782                                 break;
12783                         }
12784                         break;
12785                 case OP_ADD:
12786                 case OP_SUB:
12787                 case OP_AND:
12788                 case OP_XOR:
12789                 case OP_OR:
12790                         get_imm32(ins, &RHS(ins, 1));
12791                         in = pre_copy(state, ins, &RHS(ins, 0),
12792                                 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12793                         ins->id = in->id;
12794                         break;
12795                 case OP_SL:
12796                 case OP_SSR:
12797                 case OP_USR:
12798                         get_imm8(ins, &RHS(ins, 1));
12799                         in = pre_copy(state, ins, &RHS(ins, 0),
12800                                 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12801                         ins->id = in->id;
12802                         if (!is_const(RHS(ins, 1))) {
12803                                 in2 = pre_copy(state, ins, &RHS(ins, 1),
12804                                         REG_CL, REGCM_GPR8);
12805                         }
12806                         break;
12807                 case OP_INVERT:
12808                 case OP_NEG:
12809                         in = pre_copy(state, ins, &RHS(ins, 0),
12810                                 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12811                         ins->id = in->id;
12812                         break;
12813                 case OP_SMUL:
12814                         get_imm32(ins, &RHS(ins, 1));
12815                         in = pre_copy(state, ins, &RHS(ins, 0),
12816                                 alloc_virtual_reg(), ID_REG_CLASSES(ins->id));
12817                         ins->id = in->id;
12818                         if (!is_const(RHS(ins, 1))) {
12819                                 in2 = pre_copy(state, ins, &RHS(ins, 1),
12820                                         REG_UNSET, REGCM_GPR32);
12821                         }
12822                         break;
12823                 case OP_EQ: 
12824                         bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
12825                         break;
12826                 case OP_NOTEQ:
12827                         bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12828                         break;
12829                 case OP_SLESS:
12830                         bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
12831                         break;
12832                 case OP_ULESS:
12833                         bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
12834                         break;
12835                 case OP_SMORE:
12836                         bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
12837                         break;
12838                 case OP_UMORE:
12839                         bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
12840                         break;
12841                 case OP_SLESSEQ:
12842                         bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
12843                         break;
12844                 case OP_ULESSEQ:
12845                         bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
12846                         break;
12847                 case OP_SMOREEQ:
12848                         bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
12849                         break;
12850                 case OP_UMOREEQ:
12851                         bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
12852                         break;
12853                 case OP_LTRUE:
12854                         bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
12855                         break;
12856                 case OP_LFALSE:
12857                         bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
12858                         break;
12859                 case OP_BRANCH:
12860                         if (TRIPLE_RHS(ins->sizes) > 0) {
12861                                 internal_error(state, ins, "bad branch test");
12862                         }
12863                         ins->op = OP_JMP;
12864                         break;
12865
12866                 case OP_INB:
12867                 case OP_INW:
12868                 case OP_INL:
12869                         get_imm8(ins, &RHS(ins, 0));
12870                         switch(ins->op) {
12871                         case OP_INB: ins->id = MK_REG_ID(REG_AL,  REGCM_GPR8); break;
12872                         case OP_INW: ins->id = MK_REG_ID(REG_AX,  REGCM_GPR16); break;
12873                         case OP_INL: ins->id = MK_REG_ID(REG_EAX, REGCM_GPR32); break;
12874                         }
12875                         if (!is_const(RHS(ins, 0))) {
12876                                 in = pre_copy(state, ins, &RHS(ins, 0),
12877                                         REG_DX, REGCM_GPR16);
12878                         }
12879                         break;
12880                 case OP_OUTB:
12881                 case OP_OUTW:
12882                 case OP_OUTL:
12883                 {
12884                         unsigned reg, mask;
12885                         get_imm8(ins, &RHS(ins, 1));
12886                         switch(ins->op) {
12887                         case OP_OUTB: reg = REG_AL;  mask = REGCM_GPR8; break;
12888                         case OP_OUTW: reg = REG_AX;  mask = REGCM_GPR16; break;
12889                         case OP_OUTL: reg = REG_EAX; mask = REGCM_GPR32; break;
12890                         default: reg = REG_UNSET; mask = 0; break;
12891                         }
12892                         in = pre_copy(state, ins, &RHS(ins, 0), reg, mask);
12893                         if (!is_const(RHS(ins, 1))) {
12894                                 in2 = pre_copy(state, ins, &RHS(ins, 1),
12895                                         REG_DX, REGCM_GPR16);
12896                         }
12897                         break;
12898                 }
12899                 case OP_BSF:
12900                 case OP_BSR:
12901                         in = pre_copy(state, ins, &RHS(ins, 0),
12902                                 REG_UNSET, REGCM_GPR32);
12903                         ins->id = MK_REG_ID(REG_UNSET, REGCM_GPR32 | REGCM_GPR32_8);
12904                         break;
12905                 case OP_RDMSR:
12906                         in = pre_copy(state, ins, &RHS(ins, 0),
12907                                 REG_ECX, REGCM_GPR32);
12908                         verify_lhs(state, ins);
12909                         LHS(ins,0)->id = MK_REG_ID(REG_EAX, REGCM_GPR32);
12910                         LHS(ins,1)->id = MK_REG_ID(REG_EDX, REGCM_GPR32);
12911                         next = ins->next->next->next;
12912                         break;
12913                 case OP_WRMSR:
12914                         pre_copy(state, ins, &RHS(ins, 0), REG_ECX, REGCM_GPR32);
12915                         pre_copy(state, ins, &RHS(ins, 1), REG_EAX, REGCM_GPR32);
12916                         pre_copy(state, ins, &RHS(ins, 2), REG_EDX, REGCM_GPR32);
12917                         break;
12918                 case OP_HLT:
12919                         break;
12920                         /* Already transformed instructions */
12921                 case OP_CMP:
12922                 case OP_TEST:
12923                         ins->id = MK_REG_ID(REG_EFLAGS, REGCM_FLAGS);
12924                         break;
12925                 case OP_JMP_EQ:      case OP_JMP_NOTEQ:
12926                 case OP_JMP_SLESS:   case OP_JMP_ULESS:
12927                 case OP_JMP_SMORE:   case OP_JMP_UMORE:
12928                 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
12929                 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
12930                 case OP_SET_EQ:      case OP_SET_NOTEQ:
12931                 case OP_SET_SLESS:   case OP_SET_ULESS:
12932                 case OP_SET_SMORE:   case OP_SET_UMORE:
12933                 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
12934                 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
12935                         break;
12936                         /* Unhandled instructions */
12937                 case OP_PIECE:
12938                 default:
12939                         internal_error(state, ins, "unhandled ins: %d %s\n",
12940                                 ins->op, tops(ins->op));
12941                         break;
12942                 }
12943                 ins = next;
12944         } while(ins != first);
12945 }
12946
12947 static void generate_local_labels(struct compile_state *state)
12948 {
12949         struct triple *first, *label;
12950         int label_counter;
12951         label_counter = 0;
12952         first = RHS(state->main_function, 0);
12953         label = first;
12954         do {
12955                 if ((label->op == OP_LABEL) || 
12956                         (label->op == OP_SDECL)) {
12957                         if (label->use) {
12958                                 label->u.cval = ++label_counter;
12959                         } else {
12960                                 label->u.cval = 0;
12961                         }
12962                         
12963                 }
12964                 label = label->next;
12965         } while(label != first);
12966 }
12967
12968 static int check_reg(struct compile_state *state, 
12969         struct triple *triple, int classes)
12970 {
12971         unsigned mask;
12972         int reg;
12973         reg = ID_REG(triple->id);
12974         if (reg == REG_UNSET) {
12975                 internal_error(state, triple, "register not set");
12976         }
12977         if (ID_REG_CLASSES(triple->id)) {
12978                 internal_error(state, triple, "class specifier present");
12979         }
12980         mask = arch_reg_regcm(state, reg);
12981         if (!(classes & mask)) {
12982                 internal_error(state, triple, "reg %d in wrong class",
12983                         reg);
12984         }
12985         return reg;
12986 }
12987
12988 static const char *arch_reg_str(int reg)
12989 {
12990         static const char *regs[] = {
12991                 "%bad_register",
12992                 "%eflags",
12993                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
12994                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
12995                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
12996                 "%edx:%eax",
12997                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
12998                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
12999                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
13000         };
13001         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
13002                 reg = 0;
13003         }
13004         return regs[reg];
13005 }
13006
13007 static const char *reg(struct compile_state *state, struct triple *triple,
13008         int classes)
13009 {
13010         int reg;
13011         reg = check_reg(state, triple, classes);
13012         return arch_reg_str(reg);
13013 }
13014
13015 const char *type_suffix(struct compile_state *state, struct type *type)
13016 {
13017         const char *suffix;
13018         switch(size_of(state, type)) {
13019         case 1: suffix = "b"; break;
13020         case 2: suffix = "w"; break;
13021         case 4: suffix = "l"; break;
13022         default:
13023                 internal_error(state, 0, "unknown suffix");
13024                 suffix = 0;
13025                 break;
13026         }
13027         return suffix;
13028 }
13029
13030 static void print_binary_op(struct compile_state *state,
13031         const char *op, struct triple *ins, FILE *fp) 
13032 {
13033         unsigned mask;
13034         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13035         if (RHS(ins, 0)->id != ins->id) {
13036                 internal_error(state, ins, "invalid register assignment");
13037         }
13038         if (is_const(RHS(ins, 1))) {
13039                 fprintf(fp, "\t%s $%lu, %s\n",
13040                         op,
13041                         RHS(ins, 1)->u.cval,
13042                         reg(state, RHS(ins, 0), mask));
13043                 
13044         }
13045         else {
13046                 unsigned lmask, rmask;
13047                 int lreg, rreg;
13048                 lreg = check_reg(state, RHS(ins, 0), mask);
13049                 rreg = check_reg(state, RHS(ins, 1), mask);
13050                 lmask = arch_reg_regcm(state, lreg);
13051                 rmask = arch_reg_regcm(state, rreg);
13052                 mask = lmask & rmask;
13053                 fprintf(fp, "\t%s %s, %s\n",
13054                         op,
13055                         reg(state, RHS(ins, 1), mask),
13056                         reg(state, RHS(ins, 0), mask));
13057         }
13058 }
13059 static void print_unary_op(struct compile_state *state, 
13060         const char *op, struct triple *ins, FILE *fp)
13061 {
13062         unsigned mask;
13063         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13064         fprintf(fp, "\t%s %s\n",
13065                 op,
13066                 reg(state, RHS(ins, 0), mask));
13067 }
13068
13069 static void print_op_shift(struct compile_state *state,
13070         const char *op, struct triple *ins, FILE *fp)
13071 {
13072         unsigned mask;
13073         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13074         if (RHS(ins, 0)->id != ins->id) {
13075                 internal_error(state, ins, "invalid register assignment");
13076         }
13077         if (is_const(RHS(ins, 1))) {
13078                 fprintf(fp, "\t%s $%lu, %s\n",
13079                         op,
13080                         RHS(ins, 1)->u.cval,
13081                         reg(state, RHS(ins, 0), mask));
13082                 
13083         }
13084         else {
13085                 fprintf(fp, "\t%s %s, %s\n",
13086                         op,
13087                         reg(state, RHS(ins, 1), REGCM_GPR8),
13088                         reg(state, RHS(ins, 0), mask));
13089         }
13090 }
13091
13092 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
13093 {
13094         const char *op;
13095         int mask;
13096         int dreg;
13097         mask = 0;
13098         switch(ins->op) {
13099         case OP_INB: op = "inb", mask = REGCM_GPR8; break;
13100         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
13101         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
13102         default:
13103                 internal_error(state, ins, "not an in operation");
13104                 op = 0;
13105                 break;
13106         }
13107         dreg = check_reg(state, ins, mask);
13108         if (!reg_is_reg(state, dreg, REG_EAX)) {
13109                 internal_error(state, ins, "dst != %%eax");
13110         }
13111         if (is_const(RHS(ins, 0))) {
13112                 fprintf(fp, "\t%s $%lu, %s\n",
13113                         op, RHS(ins, 0)->u.cval, 
13114                         reg(state, ins, mask));
13115         }
13116         else {
13117                 int addr_reg;
13118                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
13119                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13120                         internal_error(state, ins, "src != %%dx");
13121                 }
13122                 fprintf(fp, "\t%s %s, %s\n",
13123                         op, 
13124                         reg(state, RHS(ins, 0), REGCM_GPR16),
13125                         reg(state, ins, mask));
13126         }
13127 }
13128
13129 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
13130 {
13131         const char *op;
13132         int mask;
13133         int lreg;
13134         mask = 0;
13135         switch(ins->op) {
13136         case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
13137         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
13138         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
13139         default:
13140                 internal_error(state, ins, "not an out operation");
13141                 op = 0;
13142                 break;
13143         }
13144         lreg = check_reg(state, RHS(ins, 0), mask);
13145         if (!reg_is_reg(state, lreg, REG_EAX)) {
13146                 internal_error(state, ins, "src != %%eax");
13147         }
13148         if (is_const(RHS(ins, 1))) {
13149                 fprintf(fp, "\t%s %s, $%lu\n",
13150                         op, reg(state, RHS(ins, 0), mask),
13151                         RHS(ins, 1)->u.cval);
13152         }
13153         else {
13154                 int addr_reg;
13155                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
13156                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
13157                         internal_error(state, ins, "dst != %%dx");
13158                 }
13159                 fprintf(fp, "\t%s %s, %s\n",
13160                         op, 
13161                         reg(state, RHS(ins, 0), mask),
13162                         reg(state, RHS(ins, 1), REGCM_GPR16));
13163         }
13164 }
13165
13166 static void print_op_move(struct compile_state *state,
13167         struct triple *ins, FILE *fp)
13168 {
13169         /* op_move is complex because there are many types
13170          * of registers we can move between.
13171          */
13172         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
13173         struct triple *dst, *src;
13174         if (ins->op == OP_COPY) {
13175                 src = RHS(ins, 0);
13176                 dst = ins;
13177         }
13178         else if (ins->op == OP_WRITE) {
13179                 dst = LHS(ins, 0);
13180                 src = RHS(ins, 0);
13181         }
13182         else {
13183                 internal_error(state, ins, "unknown move operation");
13184                 src = dst = 0;
13185         }
13186         if (!is_const(src)) {
13187                 int src_reg, dst_reg;
13188                 int src_regcm, dst_regcm;
13189                 src_reg = ID_REG(src->id);
13190                 dst_reg   = ID_REG(dst->id);
13191                 src_regcm = arch_reg_regcm(state, src_reg);
13192                 dst_regcm   = arch_reg_regcm(state, dst_reg);
13193                 /* If the class is the same just move the register */
13194                 if (src_regcm & dst_regcm & 
13195                         (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
13196                         if ((src_reg != dst_reg) || !omit_copy) {
13197                                 fprintf(fp, "\tmov %s, %s\n",
13198                                         reg(state, src, src_regcm),
13199                                         reg(state, dst, dst_regcm));
13200                         }
13201                 }
13202                 /* Move 32bit to 16bit */
13203                 else if ((src_regcm & REGCM_GPR32) &&
13204                         (dst_regcm & REGCM_GPR16)) {
13205                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
13206                         if ((src_reg != dst_reg) || !omit_copy) {
13207                                 fprintf(fp, "\tmovw %s, %s\n",
13208                                         arch_reg_str(src_reg), 
13209                                         arch_reg_str(dst_reg));
13210                         }
13211                 }
13212                 /* Move 32bit to 8bit */
13213                 else if ((src_regcm & REGCM_GPR32_8) &&
13214                         (dst_regcm & REGCM_GPR8))
13215                 {
13216                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
13217                         if ((src_reg != dst_reg) || !omit_copy) {
13218                                 fprintf(fp, "\tmovb %s, %s\n",
13219                                         arch_reg_str(src_reg),
13220                                         arch_reg_str(dst_reg));
13221                         }
13222                 }
13223                 /* Move 16bit to 8bit */
13224                 else if ((src_regcm & REGCM_GPR16_8) &&
13225                         (dst_regcm & REGCM_GPR8))
13226                 {
13227                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
13228                         if ((src_reg != dst_reg) || !omit_copy) {
13229                                 fprintf(fp, "\tmovb %s, %s\n",
13230                                         arch_reg_str(src_reg),
13231                                         arch_reg_str(dst_reg));
13232                         }
13233                 }
13234                 /* Move 8/16bit to 16/32bit */
13235                 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
13236                         (dst_regcm & (REGC_GPR16 | REGCM_GPR32))) {
13237                         const char *op;
13238                         op = is_signed(src->type)? "movsx": "movzx";
13239                         fprintf(fp, "\t%s %s, %s\n",
13240                                 op,
13241                                 reg(state, src, src_regcm),
13242                                 reg(state, dst, dst_regcm));
13243                 }
13244                 /* Move between sse registers */
13245                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
13246                         if ((src_reg != dst_reg) || !omit_copy) {
13247                                 fprintf(fp, "\tmovdqa %s %s\n",
13248                                         reg(state, src, src_regcm),
13249                                         reg(state, dst, dst_regcm));
13250                         }
13251                 }
13252                 /* Move between mmx registers or mmx & sse  registers */
13253                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
13254                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
13255                         if ((src_reg != dst_reg) || !omit_copy) {
13256                                 fprintf(fp, "\tmovq %s %s\n",
13257                                         reg(state, src, src_regcm),
13258                                         reg(state, dst, dst_regcm));
13259                         }
13260                 }
13261                 /* Move between 32bit gprs & mmx/sse registers */
13262                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
13263                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
13264                         fprintf(fp, "\tmovd %s, %s\n",
13265                                 reg(state, src, src_regcm),
13266                                 reg(state, dst, dst_regcm));
13267                 }
13268                 else {
13269                         internal_error(state, ins, "unknown copy type");
13270                 }
13271         }
13272         else switch(src->op) {
13273         case OP_INTCONST:
13274         {
13275                 long_t value;
13276                 value = (long_t)(src->u.cval);
13277                 fprintf(fp, "\tmov $%ld, %s\n",
13278                         value,
13279                         reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
13280                 break;
13281         }
13282         case OP_ADDRCONST:
13283                 fprintf(fp, "\tmov $L%lu+%lu, %s\n",
13284                         RHS(src, 0)->u.cval,
13285                         src->u.cval,
13286                         reg(state, dst, REGCM_GPR32));
13287                 break;
13288         default:
13289                 internal_error(state, ins, "uknown copy operation");
13290         }
13291 }
13292
13293 static void print_op_load(struct compile_state *state,
13294         struct triple *ins, FILE *fp)
13295 {
13296         struct triple *dst, *src;
13297         dst = ins;
13298         src = RHS(ins, 0);
13299         if (is_const(src) || is_const(dst)) {
13300                 internal_error(state, ins, "unknown load operation");
13301         }
13302         fprintf(fp, "\tmov (%s), %s\n",
13303                 reg(state, src, REGCM_GPR32),
13304                 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
13305 }
13306
13307
13308 static void print_op_store(struct compile_state *state,
13309         struct triple *ins, FILE *fp)
13310 {
13311         struct triple *dst, *src;
13312         dst = LHS(ins, 0);
13313         src = RHS(ins, 0);
13314         if (is_const(src) && (src->op == OP_INTCONST)) {
13315                 long_t value;
13316                 value = (long_t)(src->u.cval);
13317                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
13318                         type_suffix(state, src->type),
13319                         value,
13320                         reg(state, dst, REGCM_GPR32));
13321         }
13322         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
13323                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
13324                         type_suffix(state, src->type),
13325                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
13326                         dst->u.cval);
13327         }
13328         else {
13329                 if (is_const(src) || is_const(dst)) {
13330                         internal_error(state, ins, "unknown store operation");
13331                 }
13332                 fprintf(fp, "\tmov%s %s, (%s)\n",
13333                         type_suffix(state, src->type),
13334                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
13335                         reg(state, dst, REGCM_GPR32));
13336         }
13337         
13338         
13339 }
13340
13341 static void print_op_smul(struct compile_state *state,
13342         struct triple *ins, FILE *fp)
13343 {
13344         if (!is_const(RHS(ins, 1))) {
13345                 fprintf(fp, "\timul %s, %s\n",
13346                         reg(state, RHS(ins, 1), REGCM_GPR32),
13347                         reg(state, RHS(ins, 0), REGCM_GPR32));
13348         }
13349         else {
13350                 fprintf(fp, "\timul $%ld, %s\n",
13351                         RHS(ins, 1)->u.cval,
13352                         reg(state, RHS(ins, 0), REGCM_GPR32));
13353         }
13354 }
13355
13356 static void print_op_cmp(struct compile_state *state,
13357         struct triple *ins, FILE *fp)
13358 {
13359         unsigned mask;
13360         int dreg;
13361         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13362         dreg = check_reg(state, ins, REGCM_FLAGS);
13363         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
13364                 internal_error(state, ins, "bad dest register for cmp");
13365         }
13366         if (is_const(RHS(ins, 1))) {
13367                 fprintf(fp, "\tcmp $%lu, %s\n",
13368                         RHS(ins, 1)->u.cval,
13369                         reg(state, RHS(ins, 0), mask));
13370         }
13371         else {
13372                 unsigned lmask, rmask;
13373                 int lreg, rreg;
13374                 lreg = check_reg(state, RHS(ins, 0), mask);
13375                 rreg = check_reg(state, RHS(ins, 1), mask);
13376                 lmask = arch_reg_regcm(state, lreg);
13377                 rmask = arch_reg_regcm(state, rreg);
13378                 mask = lmask & rmask;
13379                 fprintf(fp, "\tcmp %s, %s\n",
13380                         reg(state, RHS(ins, 1), mask),
13381                         reg(state, RHS(ins, 0), mask));
13382         }
13383 }
13384
13385 static void print_op_test(struct compile_state *state,
13386         struct triple *ins, FILE *fp)
13387 {
13388         unsigned mask;
13389         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
13390         fprintf(fp, "\ttest %s, %s\n",
13391                 reg(state, RHS(ins, 0), mask),
13392                 reg(state, RHS(ins, 0), mask));
13393 }
13394
13395 static void print_op_branch(struct compile_state *state,
13396         struct triple *branch, FILE *fp)
13397 {
13398         const char *bop = "j";
13399         if (branch->op == OP_JMP) {
13400                 if (TRIPLE_RHS(branch->sizes) != 0) {
13401                         internal_error(state, branch, "jmp with condition?");
13402                 }
13403                 bop = "jmp";
13404         }
13405         else {
13406                 if (TRIPLE_RHS(branch->sizes) != 1) {
13407                         internal_error(state, branch, "jmpcc without condition?");
13408                 }
13409                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
13410                 if ((RHS(branch, 0)->op != OP_CMP) &&
13411                         (RHS(branch, 0)->op != OP_TEST)) {
13412                         internal_error(state, branch, "bad branch test");
13413                 }
13414 #warning "FIXME I have observed instructions between the test and branch instructions"
13415                 if (RHS(branch, 0)->next != branch) {
13416                         internal_error(state, branch, "branch does not follow test");
13417                 }
13418                 switch(branch->op) {
13419                 case OP_JMP_EQ:       bop = "jz";  break;
13420                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
13421                 case OP_JMP_SLESS:    bop = "jl";  break;
13422                 case OP_JMP_ULESS:    bop = "jb";  break;
13423                 case OP_JMP_SMORE:    bop = "jg";  break;
13424                 case OP_JMP_UMORE:    bop = "ja";  break;
13425                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
13426                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
13427                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
13428                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
13429                 default:
13430                         internal_error(state, branch, "Invalid branch op");
13431                         break;
13432                 }
13433                 
13434         }
13435         fprintf(fp, "\t%s L%lu\n",
13436                 bop, TARG(branch, 0)->u.cval);
13437 }
13438
13439 static void print_op_set(struct compile_state *state,
13440         struct triple *set, FILE *fp)
13441 {
13442         const char *sop = "set";
13443         if (TRIPLE_RHS(set->sizes) != 1) {
13444                 internal_error(state, set, "setcc without condition?");
13445         }
13446         check_reg(state, RHS(set, 0), REGCM_FLAGS);
13447         if ((RHS(set, 0)->op != OP_CMP) &&
13448                 (RHS(set, 0)->op != OP_TEST)) {
13449                 internal_error(state, set, "bad set test");
13450         }
13451         if (RHS(set, 0)->next != set) {
13452                 internal_error(state, set, "set does not follow test");
13453         }
13454         switch(set->op) {
13455         case OP_SET_EQ:       sop = "setz";  break;
13456         case OP_SET_NOTEQ:    sop = "setnz"; break;
13457         case OP_SET_SLESS:    sop = "setl";  break;
13458         case OP_SET_ULESS:    sop = "setb";  break;
13459         case OP_SET_SMORE:    sop = "setg";  break;
13460         case OP_SET_UMORE:    sop = "seta";  break;
13461         case OP_SET_SLESSEQ:  sop = "setle"; break;
13462         case OP_SET_ULESSEQ:  sop = "setbe"; break;
13463         case OP_SET_SMOREEQ:  sop = "setge"; break;
13464         case OP_SET_UMOREEQ:  sop = "setae"; break;
13465         default:
13466                 internal_error(state, set, "Invalid set op");
13467                 break;
13468         }
13469         fprintf(fp, "\t%s %s\n",
13470                 sop, reg(state, set, REGCM_GPR8));
13471 }
13472
13473 static void print_op_bit_scan(struct compile_state *state, 
13474         struct triple *ins, FILE *fp) 
13475 {
13476         const char *op;
13477         switch(ins->op) {
13478         case OP_BSF: op = "bsf"; break;
13479         case OP_BSR: op = "bsr"; break;
13480         default: 
13481                 internal_error(state, ins, "unknown bit scan");
13482                 op = 0;
13483                 break;
13484         }
13485         fprintf(fp, 
13486                 "\t%s %s, %s\n"
13487                 "\tjnz 1f\n"
13488                 "\tmovl $-1, %s\n"
13489                 "1:\n",
13490                 op,
13491                 reg(state, RHS(ins, 0), REGCM_GPR32),
13492                 reg(state, ins, REGCM_GPR32),
13493                 reg(state, ins, REGCM_GPR32));
13494 }
13495
13496 static void print_const(struct compile_state *state,
13497         struct triple *ins, FILE *fp)
13498 {
13499         switch(ins->op) {
13500         case OP_INTCONST:
13501                 switch(ins->type->type & TYPE_MASK) {
13502                 case TYPE_CHAR:
13503                 case TYPE_UCHAR:
13504                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
13505                         break;
13506                 case TYPE_SHORT:
13507                 case TYPE_USHORT:
13508                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
13509                         break;
13510                 case TYPE_INT:
13511                 case TYPE_UINT:
13512                 case TYPE_LONG:
13513                 case TYPE_ULONG:
13514                         fprintf(fp, ".int %lu\n", ins->u.cval);
13515                         break;
13516                 default:
13517                         internal_error(state, ins, "Unknown constant type");
13518                 }
13519                 break;
13520         case OP_BLOBCONST:
13521         {
13522                 unsigned char *blob;
13523                 size_t size, i;
13524                 size = size_of(state, ins->type);
13525                 blob = ins->u.blob;
13526                 for(i = 0; i < size; i++) {
13527                         fprintf(fp, ".byte 0x%02x\n",
13528                                 blob[i]);
13529                 }
13530                 break;
13531         }
13532 #if 0
13533         case OP_ADDRCONST:
13534                 fprintf(fp, ".int $L%lu+%lu",
13535                         ins->left->u.cval,
13536                         ins->u.cval);
13537                 break;
13538 #endif
13539         default:
13540                 internal_error(state, ins, "Unknown constant type");
13541                 break;
13542         }
13543 }
13544
13545 static void print_sdecl(struct compile_state *state,
13546         struct triple *ins, FILE *fp)
13547 {
13548         fprintf(fp, ".section \".rom.data\"\n");
13549         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
13550         fprintf(fp, "L%lu:\n", ins->u.cval);
13551         print_const(state, MISC(ins, 0), fp);
13552         fprintf(fp, ".section \".rom.text\"\n");
13553                 
13554 }
13555
13556 static void print_instruction(struct compile_state *state,
13557         struct triple *ins, FILE *fp)
13558 {
13559         /* Assumption: after I have exted the register allocator
13560          * everything is in a valid register. 
13561          */
13562         switch(ins->op) {
13563         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
13564         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
13565         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
13566         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
13567         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
13568         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
13569         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
13570         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
13571         case OP_POS:    break;
13572         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
13573         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
13574         case OP_INTCONST:
13575         case OP_ADDRCONST:
13576                 /* Don't generate anything here for constants */
13577         case OP_PHI:
13578                 /* Don't generate anything for variable declarations. */
13579                 break;
13580         case OP_SDECL:
13581                 print_sdecl(state, ins, fp);
13582                 break;
13583         case OP_WRITE: 
13584         case OP_COPY:   
13585                 print_op_move(state, ins, fp);
13586                 break;
13587         case OP_LOAD:
13588                 print_op_load(state, ins, fp);
13589                 break;
13590         case OP_STORE:
13591                 print_op_store(state, ins, fp);
13592                 break;
13593         case OP_SMUL:
13594                 print_op_smul(state, ins, fp);
13595                 break;
13596         case OP_CMP:    print_op_cmp(state, ins, fp); break;
13597         case OP_TEST:   print_op_test(state, ins, fp); break;
13598         case OP_JMP:
13599         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
13600         case OP_JMP_SLESS:   case OP_JMP_ULESS:
13601         case OP_JMP_SMORE:   case OP_JMP_UMORE:
13602         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
13603         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
13604                 print_op_branch(state, ins, fp);
13605                 break;
13606         case OP_SET_EQ:      case OP_SET_NOTEQ:
13607         case OP_SET_SLESS:   case OP_SET_ULESS:
13608         case OP_SET_SMORE:   case OP_SET_UMORE:
13609         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
13610         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
13611                 print_op_set(state, ins, fp);
13612                 break;
13613         case OP_INB:  case OP_INW:  case OP_INL:
13614                 print_op_in(state, ins, fp); 
13615                 break;
13616         case OP_OUTB: case OP_OUTW: case OP_OUTL:
13617                 print_op_out(state, ins, fp); 
13618                 break;
13619         case OP_BSF:
13620         case OP_BSR:
13621                 print_op_bit_scan(state, ins, fp);
13622                 break;
13623         case OP_RDMSR:
13624                 verify_lhs(state, ins);
13625                 fprintf(fp, "\trdmsr\n");
13626                 break;
13627         case OP_WRMSR:
13628                 fprintf(fp, "\twrmsr\n");
13629                 break;
13630         case OP_HLT:
13631                 fprintf(fp, "\thlt\n");
13632                 break;
13633         case OP_LABEL:
13634                 if (!ins->use) {
13635                         return;
13636                 }
13637                 fprintf(fp, "L%lu:\n", ins->u.cval);
13638                 break;
13639                 /* Ignore OP_PIECE */
13640         case OP_PIECE:
13641                 break;
13642                 /* Operations I am not yet certain how to handle */
13643         case OP_UMUL:
13644         case OP_SDIV: case OP_UDIV:
13645         case OP_SMOD: case OP_UMOD:
13646                 /* Operations that should never get here */
13647         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
13648         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
13649         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
13650         default:
13651                 internal_error(state, ins, "unknown op: %d %s",
13652                         ins->op, tops(ins->op));
13653                 break;
13654         }
13655 }
13656
13657 static void print_instructions(struct compile_state *state)
13658 {
13659         struct triple *first, *ins;
13660         int print_location;
13661         int last_line;
13662         int last_col;
13663         const char *last_filename;
13664         FILE *fp;
13665         print_location = 1;
13666         last_line = -1;
13667         last_col  = -1;
13668         last_filename = 0;
13669         fp = stdout;
13670         fprintf(fp, ".section \".rom.text\"\n");
13671         first = RHS(state->main_function, 0);
13672         ins = first;
13673         do {
13674                 if (print_location &&
13675                         ((last_filename != ins->filename) ||
13676                                 (last_line != ins->line) ||
13677                                 (last_col  != ins->col))) {
13678                         fprintf(fp, "\t/* %s:%d */\n",
13679                                 ins->filename, ins->line);
13680                         last_filename = ins->filename;
13681                         last_line = ins->line;
13682                         last_col  = ins->col;
13683                 }
13684
13685                 print_instruction(state, ins, fp);
13686                 ins = ins->next;
13687         } while(ins != first);
13688         
13689 }
13690 static void generate_code(struct compile_state *state)
13691 {
13692         generate_local_labels(state);
13693         print_instructions(state);
13694         
13695 }
13696
13697 static void print_tokens(struct compile_state *state)
13698 {
13699         struct token *tk;
13700         tk = &state->token[0];
13701         do {
13702 #if 1
13703                 token(state, 0);
13704 #else
13705                 next_token(state, 0);
13706 #endif
13707                 loc(stdout, state, 0);
13708                 printf("%s <- `%s'\n",
13709                         tokens[tk->tok],
13710                         tk->ident ? tk->ident->name :
13711                         tk->str_len ? tk->val.str : "");
13712                 
13713         } while(tk->tok != TOK_EOF);
13714 }
13715
13716 static void compile(char *filename, int debug, int opt)
13717 {
13718         int i;
13719         struct compile_state state;
13720         memset(&state, 0, sizeof(state));
13721         state.file = 0;
13722         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
13723                 memset(&state.token[i], 0, sizeof(state.token[i]));
13724                 state.token[i].tok = -1;
13725         }
13726         /* Remember the debug settings */
13727         state.debug = debug;
13728         state.optimize = opt;
13729         /* Prep the preprocessor */
13730         state.if_depth = 0;
13731         state.if_value = 0;
13732         /* register the C keywords */
13733         register_keywords(&state);
13734         /* register the keywords the macro preprocessor knows */
13735         register_macro_keywords(&state);
13736         /* Memorize where some special keywords are. */
13737         state.i_continue = lookup(&state, "continue", 8);
13738         state.i_break    = lookup(&state, "break", 5);
13739         /* Enter the globl definition scope */
13740         start_scope(&state);
13741         register_builtins(&state);
13742         compile_file(&state, filename, 1);
13743 #if 0
13744         print_tokens(&state);
13745 #endif  
13746         decls(&state);
13747         /* Exit the global definition scope */
13748         end_scope(&state);
13749
13750         /* Now that basic compilation has happened 
13751          * optimize the intermediate code 
13752          */
13753         optimize(&state);
13754         generate_code(&state);
13755         if (state.debug) {
13756                 fprintf(stderr, "done\n");
13757         }
13758 }
13759
13760 static void version(void)
13761 {
13762         printf("romcc " VERSION " released " RELEASE_DATE "\n");
13763 }
13764
13765 static void usage(void)
13766 {
13767         version();
13768         printf(
13769                 "Usage: romcc <source>.c\n"
13770                 "Compile a C source file without using ram\n"
13771         );
13772 }
13773
13774 static void arg_error(char *fmt, ...)
13775 {
13776         va_list args;
13777         va_start(args, fmt);
13778         vfprintf(stderr, fmt, args);
13779         va_end(args);
13780         usage();
13781         exit(1);
13782 }
13783
13784 int main(int argc, char **argv)
13785 {
13786         char *filename;
13787         int last_argc;
13788         int debug;
13789         int optimize;
13790         optimize = 0;
13791         debug = 0;
13792         last_argc = -1;
13793         while((argc > 1) && (argc != last_argc)) {
13794                 last_argc = argc;
13795                 if (strncmp(argv[1], "--debug=", 8) == 0) {
13796                         debug = atoi(argv[1] + 8);
13797                         argv++;
13798                         argc--;
13799                 }
13800                 else if ((strcmp(argv[1],"-O") == 0) ||
13801                         (strcmp(argv[1], "-O1") == 0)) {
13802                         optimize = 1;
13803                         argv++;
13804                         argc--;
13805                 }
13806                 else if (strcmp(argv[1],"-O2") == 0) {
13807                         optimize = 2;
13808                         argv++;
13809                         argc--;
13810                 }
13811         }
13812         if (argc != 2) {
13813                 arg_error("Wrong argument count %d\n", argc);
13814         }
13815         filename = argv[1];
13816         compile(filename, debug, optimize);
13817
13818         return 0;
13819 }