- Error on function prototypes
[coreboot.git] / util / romcc / romcc.c
1 #include <stdarg.h>
2 #include <errno.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <limits.h>
13
14 #define DEBUG_ERROR_MESSAGES 0
15 #define DEBUG_COLOR_GRAPH 0
16 #define DEBUG_SCC 0
17 #define DEBUG_CONSISTENCY 2
18
19 #warning "FIXME boundary cases with small types in larger registers"
20 #warning "FIXME give clear error messages about unused variables"
21
22 /*  Control flow graph of a loop without goto.
23  * 
24  *        AAA
25  *   +---/
26  *  /
27  * / +--->CCC
28  * | |    / \
29  * | |  DDD EEE    break;
30  * | |    \    \
31  * | |    FFF   \
32  *  \|    / \    \
33  *   |\ GGG HHH   |   continue;
34  *   | \  \   |   |
35  *   |  \ III |  /
36  *   |   \ | /  / 
37  *   |    vvv  /  
38  *   +----BBB /   
39  *         | /
40  *         vv
41  *        JJJ
42  *
43  * 
44  *             AAA
45  *     +-----+  |  +----+
46  *     |      \ | /     |
47  *     |       BBB  +-+ |
48  *     |       / \ /  | |
49  *     |     CCC JJJ / /
50  *     |     / \    / / 
51  *     |   DDD EEE / /  
52  *     |    |   +-/ /
53  *     |   FFF     /    
54  *     |   / \    /     
55  *     | GGG HHH /      
56  *     |  |   +-/
57  *     | III
58  *     +--+ 
59  *
60  * 
61  * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
62  * DFup(Z)    = { Y <- DF(Z) | idom(Y) != X }
63  *
64  *
65  * [] == DFlocal(X) U DF(X)
66  * () == DFup(X)
67  *
68  * Dominator graph of the same nodes.
69  *
70  *           AAA     AAA: [ ] ()
71  *          /   \
72  *        BBB    JJJ BBB: [ JJJ ] ( JJJ )  JJJ: [ ] ()
73  *         |
74  *        CCC        CCC: [ ] ( BBB, JJJ )
75  *        / \
76  *     DDD   EEE     DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
77  *      |
78  *     FFF           FFF: [ ] ( BBB )
79  *     / \         
80  *  GGG   HHH        GGG: [ ] ( BBB ) HHH: [ BBB ] ()
81  *   |
82  *  III              III: [ BBB ] ()
83  *
84  *
85  * BBB and JJJ are definitely the dominance frontier.
86  * Where do I place phi functions and how do I make that decision.
87  *   
88  */
89 static void die(char *fmt, ...)
90 {
91         va_list args;
92
93         va_start(args, fmt);
94         vfprintf(stderr, fmt, args);
95         va_end(args);
96         fflush(stdout);
97         fflush(stderr);
98         exit(1);
99 }
100
101 #define MALLOC_STRONG_DEBUG
102 static void *xmalloc(size_t size, const char *name)
103 {
104         void *buf;
105         buf = malloc(size);
106         if (!buf) {
107                 die("Cannot malloc %ld bytes to hold %s: %s\n",
108                         size + 0UL, name, strerror(errno));
109         }
110         return buf;
111 }
112
113 static void *xcmalloc(size_t size, const char *name)
114 {
115         void *buf;
116         buf = xmalloc(size, name);
117         memset(buf, 0, size);
118         return buf;
119 }
120
121 static void xfree(const void *ptr)
122 {
123         free((void *)ptr);
124 }
125
126 static char *xstrdup(const char *str)
127 {
128         char *new;
129         int len;
130         len = strlen(str);
131         new = xmalloc(len + 1, "xstrdup string");
132         memcpy(new, str, len);
133         new[len] = '\0';
134         return new;
135 }
136
137 static void xchdir(const char *path)
138 {
139         if (chdir(path) != 0) {
140                 die("chdir to %s failed: %s\n",
141                         path, strerror(errno));
142         }
143 }
144
145 static int exists(const char *dirname, const char *filename)
146 {
147         int does_exist = 1;
148         xchdir(dirname);
149         if (access(filename, O_RDONLY) < 0) {
150                 if ((errno != EACCES) && (errno != EROFS)) {
151                         does_exist = 0;
152                 }
153         }
154         return does_exist;
155 }
156
157
158 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
159 {
160         int fd;
161         char *buf;
162         off_t size, progress;
163         ssize_t result;
164         struct stat stats;
165         
166         if (!filename) {
167                 *r_size = 0;
168                 return 0;
169         }
170         xchdir(dirname);
171         fd = open(filename, O_RDONLY);
172         if (fd < 0) {
173                 die("Cannot open '%s' : %s\n",
174                         filename, strerror(errno));
175         }
176         result = fstat(fd, &stats);
177         if (result < 0) {
178                 die("Cannot stat: %s: %s\n",
179                         filename, strerror(errno));
180         }
181         size = stats.st_size;
182         *r_size = size +1;
183         buf = xmalloc(size +2, filename);
184         buf[size] = '\n'; /* Make certain the file is newline terminated */
185         buf[size+1] = '\0'; /* Null terminate the file for good measure */
186         progress = 0;
187         while(progress < size) {
188                 result = read(fd, buf + progress, size - progress);
189                 if (result < 0) {
190                         if ((errno == EINTR) || (errno == EAGAIN))
191                                 continue;
192                         die("read on %s of %ld bytes failed: %s\n",
193                                 filename, (size - progress)+ 0UL, strerror(errno));
194                 }
195                 progress += result;
196         }
197         result = close(fd);
198         if (result < 0) {
199                 die("Close of %s failed: %s\n",
200                         filename, strerror(errno));
201         }
202         return buf;
203 }
204
205 /* Long on the destination platform */
206 typedef unsigned long ulong_t;
207 typedef long long_t;
208
209 struct file_state {
210         struct file_state *prev;
211         const char *basename;
212         char *dirname;
213         char *buf;
214         off_t size;
215         char *pos;
216         int line;
217         char *line_start;
218         int report_line;
219         const char *report_name;
220         const char *report_dir;
221 };
222 struct hash_entry;
223 struct token {
224         int tok;
225         struct hash_entry *ident;
226         int str_len;
227         union {
228                 ulong_t integer;
229                 const char *str;
230         } val;
231 };
232
233 /* I have two classes of types:
234  * Operational types.
235  * Logical types.  (The type the C standard says the operation is of)
236  *
237  * The operational types are:
238  * chars
239  * shorts
240  * ints
241  * longs
242  *
243  * floats
244  * doubles
245  * long doubles
246  *
247  * pointer
248  */
249
250
251 /* Machine model.
252  * No memory is useable by the compiler.
253  * There is no floating point support.
254  * All operations take place in general purpose registers.
255  * There is one type of general purpose register.
256  * Unsigned longs are stored in that general purpose register.
257  */
258
259 /* Operations on general purpose registers.
260  */
261
262 #define OP_SMUL       0
263 #define OP_UMUL       1
264 #define OP_SDIV       2
265 #define OP_UDIV       3
266 #define OP_SMOD       4
267 #define OP_UMOD       5
268 #define OP_ADD        6
269 #define OP_SUB        7
270 #define OP_SL         8
271 #define OP_USR        9
272 #define OP_SSR       10 
273 #define OP_AND       11 
274 #define OP_XOR       12
275 #define OP_OR        13
276 #define OP_POS       14 /* Dummy positive operator don't use it */
277 #define OP_NEG       15
278 #define OP_INVERT    16
279                      
280 #define OP_EQ        20
281 #define OP_NOTEQ     21
282 #define OP_SLESS     22
283 #define OP_ULESS     23
284 #define OP_SMORE     24
285 #define OP_UMORE     25
286 #define OP_SLESSEQ   26
287 #define OP_ULESSEQ   27
288 #define OP_SMOREEQ   28
289 #define OP_UMOREEQ   29
290                      
291 #define OP_LFALSE    30  /* Test if the expression is logically false */
292 #define OP_LTRUE     31  /* Test if the expression is logcially true */
293
294 #define OP_LOAD      32
295 #define OP_STORE     33
296
297 #define OP_NOOP      34
298
299 #define OP_MIN_CONST 50
300 #define OP_MAX_CONST 59
301 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
302 #define OP_INTCONST  50
303 #define OP_BLOBCONST 51
304 /* For OP_BLOBCONST ->type holds the layout and size
305  * information.  u.blob holds a pointer to the raw binary
306  * data for the constant initializer.
307  */
308 #define OP_ADDRCONST 52
309 /* For OP_ADDRCONST ->type holds the type.
310  * MISC(0) holds the reference to the static variable.
311  * ->u.cval holds an offset from that value.
312  */
313
314 #define OP_WRITE     60 
315 /* OP_WRITE moves one pseudo register to another.
316  * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
317  * RHS(0) holds the psuedo to move.
318  */
319
320 #define OP_READ      61
321 /* OP_READ reads the value of a variable and makes
322  * it available for the pseudo operation.
323  * Useful for things like def-use chains.
324  * RHS(0) holds points to the triple to read from.
325  */
326 #define OP_COPY      62
327 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
328  */
329 #define OP_PIECE     63
330 /* OP_PIECE returns one piece of a instruction that returns a structure.
331  * MISC(0) is the instruction
332  * u.cval is the LHS piece of the instruction to return.
333  */
334 #define OP_ASM       64
335 /* OP_ASM holds a sequence of assembly instructions, the result
336  * of a C asm directive.
337  * RHS(x) holds input value x to the assembly sequence.
338  * LHS(x) holds the output value x from the assembly sequence.
339  * u.blob holds the string of assembly instructions.
340  */
341
342 #define OP_DEREF     65
343 /* OP_DEREF generates an lvalue from a pointer.
344  * RHS(0) holds the pointer value.
345  * OP_DEREF serves as a place holder to indicate all necessary
346  * checks have been done to indicate a value is an lvalue.
347  */
348 #define OP_DOT       66
349 /* OP_DOT references a submember of a structure lvalue.
350  * RHS(0) holds the lvalue.
351  * ->u.field holds the name of the field we want.
352  *
353  * Not seen outside of expressions.
354  */
355 #define OP_VAL       67
356 /* OP_VAL returns the value of a subexpression of the current expression.
357  * Useful for operators that have side effects.
358  * RHS(0) holds the expression.
359  * MISC(0) holds the subexpression of RHS(0) that is the
360  * value of the expression.
361  *
362  * Not seen outside of expressions.
363  */
364 #define OP_LAND      68
365 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
366  * Not seen outside of expressions.
367  */
368 #define OP_LOR       69
369 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
370  * Not seen outside of expressions.
371  */
372 #define OP_COND      70
373 /* OP_CODE performas a C ? : operation. 
374  * RHS(0) holds the test.
375  * RHS(1) holds the expression to evaluate if the test returns true.
376  * RHS(2) holds the expression to evaluate if the test returns false.
377  * Not seen outside of expressions.
378  */
379 #define OP_COMMA     71
380 /* OP_COMMA performacs a C comma operation.
381  * That is RHS(0) is evaluated, then RHS(1)
382  * and the value of RHS(1) is returned.
383  * Not seen outside of expressions.
384  */
385
386 #define OP_CALL      72
387 /* OP_CALL performs a procedure call. 
388  * MISC(0) holds a pointer to the OP_LIST of a function
389  * RHS(x) holds argument x of a function
390  * 
391  * Currently not seen outside of expressions.
392  */
393 #define OP_VAL_VEC   74
394 /* OP_VAL_VEC is an array of triples that are either variable
395  * or values for a structure or an array.
396  * RHS(x) holds element x of the vector.
397  * triple->type->elements holds the size of the vector.
398  */
399
400 /* statements */
401 #define OP_LIST      80
402 /* OP_LIST Holds a list of statements, and a result value.
403  * RHS(0) holds the list of statements.
404  * MISC(0) holds the value of the statements.
405  */
406
407 #define OP_BRANCH    81 /* branch */
408 /* For branch instructions
409  * TARG(0) holds the branch target.
410  * RHS(0) if present holds the branch condition.
411  * ->next holds where to branch to if the branch is not taken.
412  * The branch target can only be a decl...
413  */
414
415 #define OP_LABEL     83
416 /* OP_LABEL is a triple that establishes an target for branches.
417  * ->use is the list of all branches that use this label.
418  */
419
420 #define OP_ADECL     84 
421 /* OP_DECL is a triple that establishes an lvalue for assignments.
422  * ->use is a list of statements that use the variable.
423  */
424
425 #define OP_SDECL     85
426 /* OP_SDECL is a triple that establishes a variable of static
427  * storage duration.
428  * ->use is a list of statements that use the variable.
429  * MISC(0) holds the initializer expression.
430  */
431
432
433 #define OP_PHI       86
434 /* OP_PHI is a triple used in SSA form code.  
435  * It is used when multiple code paths merge and a variable needs
436  * a single assignment from any of those code paths.
437  * The operation is a cross between OP_DECL and OP_WRITE, which
438  * is what OP_PHI is geneared from.
439  * 
440  * RHS(x) points to the value from code path x
441  * The number of RHS entries is the number of control paths into the block
442  * in which OP_PHI resides.  The elements of the array point to point
443  * to the variables OP_PHI is derived from.
444  *
445  * MISC(0) holds a pointer to the orginal OP_DECL node.
446  */
447
448 /* Architecture specific instructions */
449 #define OP_CMP         100
450 #define OP_TEST        101
451 #define OP_SET_EQ      102
452 #define OP_SET_NOTEQ   103
453 #define OP_SET_SLESS   104
454 #define OP_SET_ULESS   105
455 #define OP_SET_SMORE   106
456 #define OP_SET_UMORE   107
457 #define OP_SET_SLESSEQ 108
458 #define OP_SET_ULESSEQ 109
459 #define OP_SET_SMOREEQ 110
460 #define OP_SET_UMOREEQ 111
461
462 #define OP_JMP         112
463 #define OP_JMP_EQ      113
464 #define OP_JMP_NOTEQ   114
465 #define OP_JMP_SLESS   115
466 #define OP_JMP_ULESS   116
467 #define OP_JMP_SMORE   117
468 #define OP_JMP_UMORE   118
469 #define OP_JMP_SLESSEQ 119
470 #define OP_JMP_ULESSEQ 120
471 #define OP_JMP_SMOREEQ 121
472 #define OP_JMP_UMOREEQ 122
473
474 /* Builtin operators that it is just simpler to use the compiler for */
475 #define OP_INB         130
476 #define OP_INW         131
477 #define OP_INL         132
478 #define OP_OUTB        133
479 #define OP_OUTW        134
480 #define OP_OUTL        135
481 #define OP_BSF         136
482 #define OP_BSR         137
483 #define OP_RDMSR       138
484 #define OP_WRMSR       139
485 #define OP_HLT         140
486
487 struct op_info {
488         const char *name;
489         unsigned flags;
490 #define PURE   1
491 #define IMPURE 2
492 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
493 #define DEF    4
494 #define BLOCK  8 /* Triple stores the current block */
495         unsigned char lhs, rhs, misc, targ;
496 };
497
498 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
499         .name = (NAME), \
500         .flags = (FLAGS), \
501         .lhs = (LHS), \
502         .rhs = (RHS), \
503         .misc = (MISC), \
504         .targ = (TARG), \
505          }
506 static const struct op_info table_ops[] = {
507 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
508 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
509 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
510 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
511 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
512 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
513 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
514 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
515 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
516 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
517 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
518 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
519 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
520 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
521 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
522 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
523 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
524
525 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
526 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
527 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
528 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
529 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
530 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
531 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
532 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
533 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
534 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
535 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
536 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
537
538 [OP_LOAD       ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "load"),
539 [OP_STORE      ] = OP( 1,  1, 0, 0, IMPURE | BLOCK , "store"),
540
541 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK, "noop"),
542
543 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
544 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE, "blobconst"),
545 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
546
547 [OP_WRITE      ] = OP( 1,  1, 0, 0, PURE | BLOCK, "write"),
548 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
549 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
550 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF, "piece"),
551 [OP_ASM        ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
552 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"), 
553 [OP_DOT        ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "dot"),
554
555 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
556 [OP_LAND       ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "land"),
557 [OP_LOR        ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "lor"),
558 [OP_COND       ] = OP( 0,  3, 0, 0, 0 | DEF | BLOCK, "cond"),
559 [OP_COMMA      ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "comma"),
560 /* Call is special most it can stand in for anything so it depends on context */
561 [OP_CALL       ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
562 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
563 [OP_VAL_VEC    ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
564
565 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF, "list"),
566 /* The number of targets for OP_BRANCH depends on context */
567 [OP_BRANCH     ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
568 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "label"),
569 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "adecl"),
570 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK, "sdecl"),
571 /* The number of RHS elements of OP_PHI depend upon context */
572 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
573
574 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
575 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
576 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
577 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
578 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
579 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
580 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
581 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
582 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
583 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
584 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
585 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
586 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK, "jmp"),
587 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_eq"),
588 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_noteq"),
589 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_sless"),
590 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_uless"),
591 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smore"),
592 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umore"),
593 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
594 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
595 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
596 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
597
598 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
599 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
600 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
601 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
602 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
603 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
604 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
605 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
606 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
607 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
608 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
609 };
610 #undef OP
611 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
612
613 static const char *tops(int index) 
614 {
615         static const char unknown[] = "unknown op";
616         if (index < 0) {
617                 return unknown;
618         }
619         if (index > OP_MAX) {
620                 return unknown;
621         }
622         return table_ops[index].name;
623 }
624
625 struct asm_info;
626 struct triple;
627 struct block;
628 struct triple_set {
629         struct triple_set *next;
630         struct triple *member;
631 };
632
633 #define MAX_LHS  15
634 #define MAX_RHS  15
635 #define MAX_MISC 15
636 #define MAX_TARG 15
637
638 struct occurance {
639         int count;
640         const char *filename;
641         const char *function;
642         int line;
643         int col;
644         struct occurance *parent;
645 };
646 struct triple {
647         struct triple *next, *prev;
648         struct triple_set *use;
649         struct type *type;
650         unsigned char op;
651         unsigned char template_id;
652         unsigned short sizes;
653 #define TRIPLE_LHS(SIZES)  (((SIZES) >>  0) & 0x0f)
654 #define TRIPLE_RHS(SIZES)  (((SIZES) >>  4) & 0x0f)
655 #define TRIPLE_MISC(SIZES) (((SIZES) >>  8) & 0x0f)
656 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
657 #define TRIPLE_SIZE(SIZES) \
658         ((((SIZES) >> 0) & 0x0f) + \
659         (((SIZES) >>  4) & 0x0f) + \
660         (((SIZES) >>  8) & 0x0f) + \
661         (((SIZES) >> 12) & 0x0f))
662 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
663         ((((LHS) & 0x0f) <<  0) | \
664         (((RHS) & 0x0f)  <<  4) | \
665         (((MISC) & 0x0f) <<  8) | \
666         (((TARG) & 0x0f) << 12))
667 #define TRIPLE_LHS_OFF(SIZES)  (0)
668 #define TRIPLE_RHS_OFF(SIZES)  (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
669 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
670 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
671 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
672 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
673 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
674 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
675         unsigned id; /* A scratch value and finally the register */
676 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
677 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
678 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
679         struct occurance *occurance;
680         union {
681                 ulong_t cval;
682                 struct block  *block;
683                 void *blob;
684                 struct hash_entry *field;
685                 struct asm_info *ainfo;
686         } u;
687         struct triple *param[2];
688 };
689
690 struct reg_info {
691         unsigned reg;
692         unsigned regcm;
693 };
694 struct ins_template {
695         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
696 };
697
698 struct asm_info {
699         struct ins_template tmpl;
700         char *str;
701 };
702
703 struct block_set {
704         struct block_set *next;
705         struct block *member;
706 };
707 struct block {
708         struct block *work_next;
709         struct block *left, *right;
710         struct triple *first, *last;
711         int users;
712         struct block_set *use;
713         struct block_set *idominates;
714         struct block_set *domfrontier;
715         struct block *idom;
716         struct block_set *ipdominates;
717         struct block_set *ipdomfrontier;
718         struct block *ipdom;
719         int vertex;
720         
721 };
722
723 struct symbol {
724         struct symbol *next;
725         struct hash_entry *ident;
726         struct triple *def;
727         struct type *type;
728         int scope_depth;
729 };
730
731 struct macro {
732         struct hash_entry *ident;
733         char *buf;
734         int buf_len;
735 };
736
737 struct hash_entry {
738         struct hash_entry *next;
739         const char *name;
740         int name_len;
741         int tok;
742         struct macro *sym_define;
743         struct symbol *sym_label;
744         struct symbol *sym_struct;
745         struct symbol *sym_ident;
746 };
747
748 #define HASH_TABLE_SIZE 2048
749
750 struct compile_state {
751         const char *label_prefix;
752         const char *ofilename;
753         FILE *output;
754         struct file_state *file;
755         struct occurance *last_occurance;
756         const char *function;
757         struct token token[4];
758         struct hash_entry *hash_table[HASH_TABLE_SIZE];
759         struct hash_entry *i_continue;
760         struct hash_entry *i_break;
761         int scope_depth;
762         int if_depth, if_value;
763         int macro_line;
764         struct file_state *macro_file;
765         struct triple *main_function;
766         struct block *first_block, *last_block;
767         int last_vertex;
768         int cpu;
769         int debug;
770         int optimize;
771 };
772
773 /* visibility global/local */
774 /* static/auto duration */
775 /* typedef, register, inline */
776 #define STOR_SHIFT         0
777 #define STOR_MASK     0x000f
778 /* Visibility */
779 #define STOR_GLOBAL   0x0001
780 /* Duration */
781 #define STOR_PERM     0x0002
782 /* Storage specifiers */
783 #define STOR_AUTO     0x0000
784 #define STOR_STATIC   0x0002
785 #define STOR_EXTERN   0x0003
786 #define STOR_REGISTER 0x0004
787 #define STOR_TYPEDEF  0x0008
788 #define STOR_INLINE   0x000c
789
790 #define QUAL_SHIFT         4
791 #define QUAL_MASK     0x0070
792 #define QUAL_NONE     0x0000
793 #define QUAL_CONST    0x0010
794 #define QUAL_VOLATILE 0x0020
795 #define QUAL_RESTRICT 0x0040
796
797 #define TYPE_SHIFT         8
798 #define TYPE_MASK     0x1f00
799 #define TYPE_INTEGER(TYPE)    (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
800 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
801 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
802 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
803 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
804 #define TYPE_RANK(TYPE)       ((TYPE) & ~0x0100)
805 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
806 #define TYPE_DEFAULT  0x0000
807 #define TYPE_VOID     0x0100
808 #define TYPE_CHAR     0x0200
809 #define TYPE_UCHAR    0x0300
810 #define TYPE_SHORT    0x0400
811 #define TYPE_USHORT   0x0500
812 #define TYPE_INT      0x0600
813 #define TYPE_UINT     0x0700
814 #define TYPE_LONG     0x0800
815 #define TYPE_ULONG    0x0900
816 #define TYPE_LLONG    0x0a00 /* long long */
817 #define TYPE_ULLONG   0x0b00
818 #define TYPE_FLOAT    0x0c00
819 #define TYPE_DOUBLE   0x0d00
820 #define TYPE_LDOUBLE  0x0e00 /* long double */
821 #define TYPE_STRUCT   0x1000
822 #define TYPE_ENUM     0x1100
823 #define TYPE_POINTER  0x1200 
824 /* For TYPE_POINTER:
825  * type->left holds the type pointed to.
826  */
827 #define TYPE_FUNCTION 0x1300 
828 /* For TYPE_FUNCTION:
829  * type->left holds the return type.
830  * type->right holds the...
831  */
832 #define TYPE_PRODUCT  0x1400
833 /* TYPE_PRODUCT is a basic building block when defining structures
834  * type->left holds the type that appears first in memory.
835  * type->right holds the type that appears next in memory.
836  */
837 #define TYPE_OVERLAP  0x1500
838 /* TYPE_OVERLAP is a basic building block when defining unions
839  * type->left and type->right holds to types that overlap
840  * each other in memory.
841  */
842 #define TYPE_ARRAY    0x1600
843 /* TYPE_ARRAY is a basic building block when definitng arrays.
844  * type->left holds the type we are an array of.
845  * type-> holds the number of elements.
846  */
847
848 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
849
850 struct type {
851         unsigned int type;
852         struct type *left, *right;
853         ulong_t elements;
854         struct hash_entry *field_ident;
855         struct hash_entry *type_ident;
856 };
857
858 #define MAX_REGISTERS      75
859 #define MAX_REG_EQUIVS     16
860 #define REGISTER_BITS      16
861 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
862 #define TEMPLATE_BITS      6
863 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
864 #define MAX_REGC           12
865 #define REG_UNSET          0
866 #define REG_UNNEEDED       1
867 #define REG_VIRT0          (MAX_REGISTERS + 0)
868 #define REG_VIRT1          (MAX_REGISTERS + 1)
869 #define REG_VIRT2          (MAX_REGISTERS + 2)
870 #define REG_VIRT3          (MAX_REGISTERS + 3)
871 #define REG_VIRT4          (MAX_REGISTERS + 4)
872 #define REG_VIRT5          (MAX_REGISTERS + 5)
873 #define REG_VIRT6          (MAX_REGISTERS + 5)
874 #define REG_VIRT7          (MAX_REGISTERS + 5)
875 #define REG_VIRT8          (MAX_REGISTERS + 5)
876 #define REG_VIRT9          (MAX_REGISTERS + 5)
877
878 /* Provision for 8 register classes */
879 #define REG_SHIFT  0
880 #define REGC_SHIFT REGISTER_BITS
881 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
882 #define REG_MASK (MAX_VIRT_REGISTERS -1)
883 #define ID_REG(ID)              ((ID) & REG_MASK)
884 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
885 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
886 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
887 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
888                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
889
890 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
891 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
892 static void arch_reg_equivs(
893         struct compile_state *state, unsigned *equiv, int reg);
894 static int arch_select_free_register(
895         struct compile_state *state, char *used, int classes);
896 static unsigned arch_regc_size(struct compile_state *state, int class);
897 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
898 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
899 static const char *arch_reg_str(int reg);
900 static struct reg_info arch_reg_constraint(
901         struct compile_state *state, struct type *type, const char *constraint);
902 static struct reg_info arch_reg_clobber(
903         struct compile_state *state, const char *clobber);
904 static struct reg_info arch_reg_lhs(struct compile_state *state, 
905         struct triple *ins, int index);
906 static struct reg_info arch_reg_rhs(struct compile_state *state, 
907         struct triple *ins, int index);
908 static struct triple *transform_to_arch_instruction(
909         struct compile_state *state, struct triple *ins);
910
911
912
913 #define DEBUG_ABORT_ON_ERROR    0x0001
914 #define DEBUG_INTERMEDIATE_CODE 0x0002
915 #define DEBUG_CONTROL_FLOW      0x0004
916 #define DEBUG_BASIC_BLOCKS      0x0008
917 #define DEBUG_FDOMINATORS       0x0010
918 #define DEBUG_RDOMINATORS       0x0020
919 #define DEBUG_TRIPLES           0x0040
920 #define DEBUG_INTERFERENCE      0x0080
921 #define DEBUG_ARCH_CODE         0x0100
922 #define DEBUG_CODE_ELIMINATION  0x0200
923 #define DEBUG_INSERTED_COPIES   0x0400
924
925 #define GLOBAL_SCOPE_DEPTH   1
926 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
927
928 static void compile_file(struct compile_state *old_state, const char *filename, int local);
929
930 static void do_cleanup(struct compile_state *state)
931 {
932         if (state->output) {
933                 fclose(state->output);
934                 unlink(state->ofilename);
935         }
936 }
937
938 static int get_col(struct file_state *file)
939 {
940         int col;
941         char *ptr, *end;
942         ptr = file->line_start;
943         end = file->pos;
944         for(col = 0; ptr < end; ptr++) {
945                 if (*ptr != '\t') {
946                         col++;
947                 } 
948                 else {
949                         col = (col & ~7) + 8;
950                 }
951         }
952         return col;
953 }
954
955 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
956 {
957         int col;
958         if (triple) {
959                 struct occurance *spot;
960                 spot = triple->occurance;
961                 while(spot->parent) {
962                         spot = spot->parent;
963                 }
964                 fprintf(fp, "%s:%d.%d: ", 
965                         spot->filename, spot->line, spot->col);
966                 return;
967         }
968         if (!state->file) {
969                 return;
970         }
971         col = get_col(state->file);
972         fprintf(fp, "%s:%d.%d: ", 
973                 state->file->report_name, state->file->report_line, col);
974 }
975
976 static void __internal_error(struct compile_state *state, struct triple *ptr, 
977         char *fmt, ...)
978 {
979         va_list args;
980         va_start(args, fmt);
981         loc(stderr, state, ptr);
982         if (ptr) {
983                 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
984         }
985         fprintf(stderr, "Internal compiler error: ");
986         vfprintf(stderr, fmt, args);
987         fprintf(stderr, "\n");
988         va_end(args);
989         do_cleanup(state);
990         abort();
991 }
992
993
994 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
995         char *fmt, ...)
996 {
997         va_list args;
998         va_start(args, fmt);
999         loc(stderr, state, ptr);
1000         fprintf(stderr, "Internal compiler warning: ");
1001         vfprintf(stderr, fmt, args);
1002         fprintf(stderr, "\n");
1003         va_end(args);
1004 }
1005
1006
1007
1008 static void __error(struct compile_state *state, struct triple *ptr, 
1009         char *fmt, ...)
1010 {
1011         va_list args;
1012         va_start(args, fmt);
1013         loc(stderr, state, ptr);
1014         vfprintf(stderr, fmt, args);
1015         va_end(args);
1016         fprintf(stderr, "\n");
1017         do_cleanup(state);
1018         if (state->debug & DEBUG_ABORT_ON_ERROR) {
1019                 abort();
1020         }
1021         exit(1);
1022 }
1023
1024 static void __warning(struct compile_state *state, struct triple *ptr, 
1025         char *fmt, ...)
1026 {
1027         va_list args;
1028         va_start(args, fmt);
1029         loc(stderr, state, ptr);
1030         fprintf(stderr, "warning: "); 
1031         vfprintf(stderr, fmt, args);
1032         fprintf(stderr, "\n");
1033         va_end(args);
1034 }
1035
1036 #if DEBUG_ERROR_MESSAGES 
1037 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1038 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1039 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1040 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1041 #else
1042 #  define internal_error __internal_error
1043 #  define internal_warning __internal_warning
1044 #  define error __error
1045 #  define warning __warning
1046 #endif
1047 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1048
1049 static void valid_op(struct compile_state *state, int op)
1050 {
1051         char *fmt = "invalid op: %d";
1052         if (op >= OP_MAX) {
1053                 internal_error(state, 0, fmt, op);
1054         }
1055         if (op < 0) {
1056                 internal_error(state, 0, fmt, op);
1057         }
1058 }
1059
1060 static void valid_ins(struct compile_state *state, struct triple *ptr)
1061 {
1062         valid_op(state, ptr->op);
1063 }
1064
1065 static void process_trigraphs(struct compile_state *state)
1066 {
1067         char *src, *dest, *end;
1068         struct file_state *file;
1069         file = state->file;
1070         src = dest = file->buf;
1071         end = file->buf + file->size;
1072         while((end - src) >= 3) {
1073                 if ((src[0] == '?') && (src[1] == '?')) {
1074                         int c = -1;
1075                         switch(src[2]) {
1076                         case '=': c = '#'; break;
1077                         case '/': c = '\\'; break;
1078                         case '\'': c = '^'; break;
1079                         case '(': c = '['; break;
1080                         case ')': c = ']'; break;
1081                         case '!': c = '!'; break;
1082                         case '<': c = '{'; break;
1083                         case '>': c = '}'; break;
1084                         case '-': c = '~'; break;
1085                         }
1086                         if (c != -1) {
1087                                 *dest++ = c;
1088                                 src += 3;
1089                         }
1090                         else {
1091                                 *dest++ = *src++;
1092                         }
1093                 }
1094                 else {
1095                         *dest++ = *src++;
1096                 }
1097         }
1098         while(src != end) {
1099                 *dest++ = *src++;
1100         }
1101         file->size = dest - file->buf;
1102 }
1103
1104 static void splice_lines(struct compile_state *state)
1105 {
1106         char *src, *dest, *end;
1107         struct file_state *file;
1108         file = state->file;
1109         src = dest = file->buf;
1110         end = file->buf + file->size;
1111         while((end - src) >= 2) {
1112                 if ((src[0] == '\\') && (src[1] == '\n')) {
1113                         src += 2;
1114                 }
1115                 else {
1116                         *dest++ = *src++;
1117                 }
1118         }
1119         while(src != end) {
1120                 *dest++ = *src++;
1121         }
1122         file->size = dest - file->buf;
1123 }
1124
1125 static struct type void_type;
1126 static void use_triple(struct triple *used, struct triple *user)
1127 {
1128         struct triple_set **ptr, *new;
1129         if (!used)
1130                 return;
1131         if (!user)
1132                 return;
1133         ptr = &used->use;
1134         while(*ptr) {
1135                 if ((*ptr)->member == user) {
1136                         return;
1137                 }
1138                 ptr = &(*ptr)->next;
1139         }
1140         /* Append new to the head of the list, 
1141          * copy_func and rename_block_variables
1142          * depends on this.
1143          */
1144         new = xcmalloc(sizeof(*new), "triple_set");
1145         new->member = user;
1146         new->next   = used->use;
1147         used->use   = new;
1148 }
1149
1150 static void unuse_triple(struct triple *used, struct triple *unuser)
1151 {
1152         struct triple_set *use, **ptr;
1153         if (!used) {
1154                 return;
1155         }
1156         ptr = &used->use;
1157         while(*ptr) {
1158                 use = *ptr;
1159                 if (use->member == unuser) {
1160                         *ptr = use->next;
1161                         xfree(use);
1162                 }
1163                 else {
1164                         ptr = &use->next;
1165                 }
1166         }
1167 }
1168
1169 static void push_triple(struct triple *used, struct triple *user)
1170 {
1171         struct triple_set *new;
1172         if (!used)
1173                 return;
1174         if (!user)
1175                 return;
1176         /* Append new to the head of the list,
1177          * it's the only sensible behavoir for a stack.
1178          */
1179         new = xcmalloc(sizeof(*new), "triple_set");
1180         new->member = user;
1181         new->next   = used->use;
1182         used->use   = new;
1183 }
1184
1185 static void pop_triple(struct triple *used, struct triple *unuser)
1186 {
1187         struct triple_set *use, **ptr;
1188         ptr = &used->use;
1189         while(*ptr) {
1190                 use = *ptr;
1191                 if (use->member == unuser) {
1192                         *ptr = use->next;
1193                         xfree(use);
1194                         /* Only free one occurance from the stack */
1195                         return;
1196                 }
1197                 else {
1198                         ptr = &use->next;
1199                 }
1200         }
1201 }
1202
1203 static void put_occurance(struct occurance *occurance)
1204 {
1205         occurance->count -= 1;
1206         if (occurance->count <= 0) {
1207                 if (occurance->parent) {
1208                         put_occurance(occurance->parent);
1209                 }
1210                 xfree(occurance);
1211         }
1212 }
1213
1214 static void get_occurance(struct occurance *occurance)
1215 {
1216         occurance->count += 1;
1217 }
1218
1219
1220 static struct occurance *new_occurance(struct compile_state *state)
1221 {
1222         struct occurance *result, *last;
1223         const char *filename;
1224         const char *function;
1225         int line, col;
1226
1227         function = "";
1228         filename = 0;
1229         line = 0;
1230         col  = 0;
1231         if (state->file) {
1232                 filename = state->file->report_name;
1233                 line     = state->file->report_line;
1234                 col      = get_col(state->file);
1235         }
1236         if (state->function) {
1237                 function = state->function;
1238         }
1239         last = state->last_occurance;
1240         if (last &&
1241                 (last->col == col) &&
1242                 (last->line == line) &&
1243                 (last->function == function) &&
1244                 (strcmp(last->filename, filename) == 0)) {
1245                 get_occurance(last);
1246                 return last;
1247         }
1248         if (last) {
1249                 state->last_occurance = 0;
1250                 put_occurance(last);
1251         }
1252         result = xmalloc(sizeof(*result), "occurance");
1253         result->count    = 2;
1254         result->filename = filename;
1255         result->function = function;
1256         result->line     = line;
1257         result->col      = col;
1258         result->parent   = 0;
1259         state->last_occurance = result;
1260         return result;
1261 }
1262
1263 static struct occurance *inline_occurance(struct compile_state *state,
1264         struct occurance *new, struct occurance *orig)
1265 {
1266         struct occurance *result, *last;
1267         last = state->last_occurance;
1268         if (last &&
1269                 (last->parent   == orig) &&
1270                 (last->col      == new->col) &&
1271                 (last->line     == new->line) &&
1272                 (last->function == new->function) &&
1273                 (last->filename == new->filename)) {
1274                 get_occurance(last);
1275                 return last;
1276         }
1277         if (last) {
1278                 state->last_occurance = 0;
1279                 put_occurance(last);
1280         }
1281         get_occurance(orig);
1282         result = xmalloc(sizeof(*result), "occurance");
1283         result->count    = 2;
1284         result->filename = new->filename;
1285         result->function = new->function;
1286         result->line     = new->line;
1287         result->col      = new->col;
1288         result->parent   = orig;
1289         state->last_occurance = result;
1290         return result;
1291 }
1292         
1293
1294 static struct occurance dummy_occurance = {
1295         .count    = 2,
1296         .filename = __FILE__,
1297         .function = "",
1298         .line     = __LINE__,
1299         .col      = 0,
1300         .parent   = 0,
1301 };
1302
1303 /* The zero triple is used as a place holder when we are removing pointers
1304  * from a triple.  Having allows certain sanity checks to pass even
1305  * when the original triple that was pointed to is gone.
1306  */
1307 static struct triple zero_triple = {
1308         .next      = &zero_triple,
1309         .prev      = &zero_triple,
1310         .use       = 0,
1311         .op        = OP_INTCONST,
1312         .sizes     = TRIPLE_SIZES(0, 0, 0, 0),
1313         .id        = -1, /* An invalid id */
1314         .u = { .cval   = 0, },
1315         .occurance = &dummy_occurance,
1316         .param { [0] = 0, [1] = 0, },
1317 };
1318
1319
1320 static unsigned short triple_sizes(struct compile_state *state,
1321         int op, struct type *type, int lhs_wanted, int rhs_wanted)
1322 {
1323         int lhs, rhs, misc, targ;
1324         valid_op(state, op);
1325         lhs = table_ops[op].lhs;
1326         rhs = table_ops[op].rhs;
1327         misc = table_ops[op].misc;
1328         targ = table_ops[op].targ;
1329         
1330         
1331         if (op == OP_CALL) {
1332                 struct type *param;
1333                 rhs = 0;
1334                 param = type->right;
1335                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1336                         rhs++;
1337                         param = param->right;
1338                 }
1339                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1340                         rhs++;
1341                 }
1342                 lhs = 0;
1343                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1344                         lhs = type->left->elements;
1345                 }
1346         }
1347         else if (op == OP_VAL_VEC) {
1348                 rhs = type->elements;
1349         }
1350         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1351                 rhs = rhs_wanted;
1352         }
1353         else if (op == OP_ASM) {
1354                 rhs = rhs_wanted;
1355                 lhs = lhs_wanted;
1356         }
1357         if ((rhs < 0) || (rhs > MAX_RHS)) {
1358                 internal_error(state, 0, "bad rhs");
1359         }
1360         if ((lhs < 0) || (lhs > MAX_LHS)) {
1361                 internal_error(state, 0, "bad lhs");
1362         }
1363         if ((misc < 0) || (misc > MAX_MISC)) {
1364                 internal_error(state, 0, "bad misc");
1365         }
1366         if ((targ < 0) || (targ > MAX_TARG)) {
1367                 internal_error(state, 0, "bad targs");
1368         }
1369         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1370 }
1371
1372 static struct triple *alloc_triple(struct compile_state *state, 
1373         int op, struct type *type, int lhs, int rhs,
1374         struct occurance *occurance)
1375 {
1376         size_t size, sizes, extra_count, min_count;
1377         struct triple *ret;
1378         sizes = triple_sizes(state, op, type, lhs, rhs);
1379
1380         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1381         extra_count = TRIPLE_SIZE(sizes);
1382         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1383
1384         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1385         ret = xcmalloc(size, "tripple");
1386         ret->op        = op;
1387         ret->sizes     = sizes;
1388         ret->type      = type;
1389         ret->next      = ret;
1390         ret->prev      = ret;
1391         ret->occurance = occurance;
1392         return ret;
1393 }
1394
1395 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1396 {
1397         struct triple *dup;
1398         int src_lhs, src_rhs, src_size;
1399         src_lhs = TRIPLE_LHS(src->sizes);
1400         src_rhs = TRIPLE_RHS(src->sizes);
1401         src_size = TRIPLE_SIZE(src->sizes);
1402         get_occurance(src->occurance);
1403         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1404                 src->occurance);
1405         memcpy(dup, src, sizeof(*src));
1406         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1407         return dup;
1408 }
1409
1410 static struct triple *new_triple(struct compile_state *state, 
1411         int op, struct type *type, int lhs, int rhs)
1412 {
1413         struct triple *ret;
1414         struct occurance *occurance;
1415         occurance = new_occurance(state);
1416         ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1417         return ret;
1418 }
1419
1420 static struct triple *build_triple(struct compile_state *state, 
1421         int op, struct type *type, struct triple *left, struct triple *right,
1422         struct occurance *occurance)
1423 {
1424         struct triple *ret;
1425         size_t count;
1426         ret = alloc_triple(state, op, type, -1, -1, occurance);
1427         count = TRIPLE_SIZE(ret->sizes);
1428         if (count > 0) {
1429                 ret->param[0] = left;
1430         }
1431         if (count > 1) {
1432                 ret->param[1] = right;
1433         }
1434         return ret;
1435 }
1436
1437 static struct triple *triple(struct compile_state *state, 
1438         int op, struct type *type, struct triple *left, struct triple *right)
1439 {
1440         struct triple *ret;
1441         size_t count;
1442         ret = new_triple(state, op, type, -1, -1);
1443         count = TRIPLE_SIZE(ret->sizes);
1444         if (count >= 1) {
1445                 ret->param[0] = left;
1446         }
1447         if (count >= 2) {
1448                 ret->param[1] = right;
1449         }
1450         return ret;
1451 }
1452
1453 static struct triple *branch(struct compile_state *state, 
1454         struct triple *targ, struct triple *test)
1455 {
1456         struct triple *ret;
1457         ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1458         if (test) {
1459                 RHS(ret, 0) = test;
1460         }
1461         TARG(ret, 0) = targ;
1462         /* record the branch target was used */
1463         if (!targ || (targ->op != OP_LABEL)) {
1464                 internal_error(state, 0, "branch not to label");
1465                 use_triple(targ, ret);
1466         }
1467         return ret;
1468 }
1469
1470
1471 static void insert_triple(struct compile_state *state,
1472         struct triple *first, struct triple *ptr)
1473 {
1474         if (ptr) {
1475                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1476                         internal_error(state, ptr, "expression already used");
1477                 }
1478                 ptr->next       = first;
1479                 ptr->prev       = first->prev;
1480                 ptr->prev->next = ptr;
1481                 ptr->next->prev = ptr;
1482                 if ((ptr->prev->op == OP_BRANCH) && 
1483                         TRIPLE_RHS(ptr->prev->sizes)) {
1484                         unuse_triple(first, ptr->prev);
1485                         use_triple(ptr, ptr->prev);
1486                 }
1487         }
1488 }
1489
1490 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1491 {
1492         /* This function is used to determine if u.block 
1493          * is utilized to store the current block number.
1494          */
1495         int stores_block;
1496         valid_ins(state, ins);
1497         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1498         return stores_block;
1499 }
1500
1501 static struct block *block_of_triple(struct compile_state *state, 
1502         struct triple *ins)
1503 {
1504         struct triple *first;
1505         first = RHS(state->main_function, 0);
1506         while(ins != first && !triple_stores_block(state, ins)) {
1507                 if (ins == ins->prev) {
1508                         internal_error(state, 0, "ins == ins->prev?");
1509                 }
1510                 ins = ins->prev;
1511         }
1512         if (!triple_stores_block(state, ins)) {
1513                 internal_error(state, ins, "Cannot find block");
1514         }
1515         return ins->u.block;
1516 }
1517
1518 static struct triple *pre_triple(struct compile_state *state,
1519         struct triple *base,
1520         int op, struct type *type, struct triple *left, struct triple *right)
1521 {
1522         struct block *block;
1523         struct triple *ret;
1524         /* If I am an OP_PIECE jump to the real instruction */
1525         if (base->op == OP_PIECE) {
1526                 base = MISC(base, 0);
1527         }
1528         block = block_of_triple(state, base);
1529         get_occurance(base->occurance);
1530         ret = build_triple(state, op, type, left, right, base->occurance);
1531         if (triple_stores_block(state, ret)) {
1532                 ret->u.block = block;
1533         }
1534         insert_triple(state, base, ret);
1535         if (block->first == base) {
1536                 block->first = ret;
1537         }
1538         return ret;
1539 }
1540
1541 static struct triple *post_triple(struct compile_state *state,
1542         struct triple *base,
1543         int op, struct type *type, struct triple *left, struct triple *right)
1544 {
1545         struct block *block;
1546         struct triple *ret;
1547         int zlhs;
1548         /* If I am an OP_PIECE jump to the real instruction */
1549         if (base->op == OP_PIECE) {
1550                 base = MISC(base, 0);
1551         }
1552         /* If I have a left hand side skip over it */
1553         zlhs = TRIPLE_LHS(base->sizes);
1554         if (zlhs && (base->op != OP_WRITE) && (base->op != OP_STORE)) {
1555                 base = LHS(base, zlhs - 1);
1556         }
1557
1558         block = block_of_triple(state, base);
1559         get_occurance(base->occurance);
1560         ret = build_triple(state, op, type, left, right, base->occurance);
1561         if (triple_stores_block(state, ret)) {
1562                 ret->u.block = block;
1563         }
1564         insert_triple(state, base->next, ret);
1565         if (block->last == base) {
1566                 block->last = ret;
1567         }
1568         return ret;
1569 }
1570
1571 static struct triple *label(struct compile_state *state)
1572 {
1573         /* Labels don't get a type */
1574         struct triple *result;
1575         result = triple(state, OP_LABEL, &void_type, 0, 0);
1576         return result;
1577 }
1578
1579 static void display_triple(FILE *fp, struct triple *ins)
1580 {
1581         struct occurance *ptr;
1582         const char *reg;
1583         char pre, post;
1584         pre = post = ' ';
1585         if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1586                 pre = '^';
1587         }
1588         if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1589                 post = 'v';
1590         }
1591         reg = arch_reg_str(ID_REG(ins->id));
1592         if (ins->op == OP_INTCONST) {
1593                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx>         ",
1594                         ins, pre, post, reg, ins->template_id, tops(ins->op), 
1595                         ins->u.cval);
1596         }
1597         else if (ins->op == OP_ADDRCONST) {
1598                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1599                         ins, pre, post, reg, ins->template_id, tops(ins->op), 
1600                         MISC(ins, 0), ins->u.cval);
1601         }
1602         else {
1603                 int i, count;
1604                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s", 
1605                         ins, pre, post, reg, ins->template_id, tops(ins->op));
1606                 count = TRIPLE_SIZE(ins->sizes);
1607                 for(i = 0; i < count; i++) {
1608                         fprintf(fp, " %-10p", ins->param[i]);
1609                 }
1610                 for(; i < 2; i++) {
1611                         fprintf(fp, "           ");
1612                 }
1613         }
1614         fprintf(fp, " @");
1615         for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1616                 fprintf(fp, " %s,%s:%d.%d",
1617                         ptr->function, 
1618                         ptr->filename,
1619                         ptr->line, 
1620                         ptr->col);
1621         }
1622         fprintf(fp, "\n");
1623         fflush(fp);
1624 }
1625
1626 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1627 {
1628         /* Does the triple have no side effects.
1629          * I.e. Rexecuting the triple with the same arguments 
1630          * gives the same value.
1631          */
1632         unsigned pure;
1633         valid_ins(state, ins);
1634         pure = PURE_BITS(table_ops[ins->op].flags);
1635         if ((pure != PURE) && (pure != IMPURE)) {
1636                 internal_error(state, 0, "Purity of %s not known\n",
1637                         tops(ins->op));
1638         }
1639         return pure == PURE;
1640 }
1641
1642 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1643 {
1644         /* This function is used to determine which triples need
1645          * a register.
1646          */
1647         int is_branch;
1648         valid_ins(state, ins);
1649         is_branch = (table_ops[ins->op].targ != 0);
1650         return is_branch;
1651 }
1652
1653 static int triple_is_def(struct compile_state *state, struct triple *ins)
1654 {
1655         /* This function is used to determine which triples need
1656          * a register.
1657          */
1658         int is_def;
1659         valid_ins(state, ins);
1660         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1661         return is_def;
1662 }
1663
1664 static struct triple **triple_iter(struct compile_state *state,
1665         size_t count, struct triple **vector,
1666         struct triple *ins, struct triple **last)
1667 {
1668         struct triple **ret;
1669         ret = 0;
1670         if (count) {
1671                 if (!last) {
1672                         ret = vector;
1673                 }
1674                 else if ((last >= vector) && (last < (vector + count - 1))) {
1675                         ret = last + 1;
1676                 }
1677         }
1678         return ret;
1679         
1680 }
1681
1682 static struct triple **triple_lhs(struct compile_state *state,
1683         struct triple *ins, struct triple **last)
1684 {
1685         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1686                 ins, last);
1687 }
1688
1689 static struct triple **triple_rhs(struct compile_state *state,
1690         struct triple *ins, struct triple **last)
1691 {
1692         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1693                 ins, last);
1694 }
1695
1696 static struct triple **triple_misc(struct compile_state *state,
1697         struct triple *ins, struct triple **last)
1698 {
1699         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1700                 ins, last);
1701 }
1702
1703 static struct triple **triple_targ(struct compile_state *state,
1704         struct triple *ins, struct triple **last)
1705 {
1706         size_t count;
1707         struct triple **ret, **vector;
1708         ret = 0;
1709         count = TRIPLE_TARG(ins->sizes);
1710         vector = &TARG(ins, 0);
1711         if (count) {
1712                 if (!last) {
1713                         ret = vector;
1714                 }
1715                 else if ((last >= vector) && (last < (vector + count - 1))) {
1716                         ret = last + 1;
1717                 }
1718                 else if ((last == (vector + count - 1)) && 
1719                         TRIPLE_RHS(ins->sizes)) {
1720                         ret = &ins->next;
1721                 }
1722         }
1723         return ret;
1724 }
1725
1726
1727 static void verify_use(struct compile_state *state,
1728         struct triple *user, struct triple *used)
1729 {
1730         int size, i;
1731         size = TRIPLE_SIZE(user->sizes);
1732         for(i = 0; i < size; i++) {
1733                 if (user->param[i] == used) {
1734                         break;
1735                 }
1736         }
1737         if (triple_is_branch(state, user)) {
1738                 if (user->next == used) {
1739                         i = -1;
1740                 }
1741         }
1742         if (i == size) {
1743                 internal_error(state, user, "%s(%p) does not use %s(%p)",
1744                         tops(user->op), user, tops(used->op), used);
1745         }
1746 }
1747
1748 static int find_rhs_use(struct compile_state *state, 
1749         struct triple *user, struct triple *used)
1750 {
1751         struct triple **param;
1752         int size, i;
1753         verify_use(state, user, used);
1754         size = TRIPLE_RHS(user->sizes);
1755         param = &RHS(user, 0);
1756         for(i = 0; i < size; i++) {
1757                 if (param[i] == used) {
1758                         return i;
1759                 }
1760         }
1761         return -1;
1762 }
1763
1764 static void free_triple(struct compile_state *state, struct triple *ptr)
1765 {
1766         size_t size;
1767         size = sizeof(*ptr) - sizeof(ptr->param) +
1768                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1769         ptr->prev->next = ptr->next;
1770         ptr->next->prev = ptr->prev;
1771         if (ptr->use) {
1772                 internal_error(state, ptr, "ptr->use != 0");
1773         }
1774         put_occurance(ptr->occurance);
1775         memset(ptr, -1, size);
1776         xfree(ptr);
1777 }
1778
1779 static void release_triple(struct compile_state *state, struct triple *ptr)
1780 {
1781         struct triple_set *set, *next;
1782         struct triple **expr;
1783         /* Remove ptr from use chains where it is the user */
1784         expr = triple_rhs(state, ptr, 0);
1785         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1786                 if (*expr) {
1787                         unuse_triple(*expr, ptr);
1788                 }
1789         }
1790         expr = triple_lhs(state, ptr, 0);
1791         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1792                 if (*expr) {
1793                         unuse_triple(*expr, ptr);
1794                 }
1795         }
1796         expr = triple_misc(state, ptr, 0);
1797         for(; expr; expr = triple_misc(state, ptr, expr)) {
1798                 if (*expr) {
1799                         unuse_triple(*expr, ptr);
1800                 }
1801         }
1802         expr = triple_targ(state, ptr, 0);
1803         for(; expr; expr = triple_targ(state, ptr, expr)) {
1804                 if (*expr) {
1805                         unuse_triple(*expr, ptr);
1806                 }
1807         }
1808         /* Reomve ptr from use chains where it is used */
1809         for(set = ptr->use; set; set = next) {
1810                 next = set->next;
1811                 expr = triple_rhs(state, set->member, 0);
1812                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1813                         if (*expr == ptr) {
1814                                 *expr = &zero_triple;
1815                         }
1816                 }
1817                 expr = triple_lhs(state, set->member, 0);
1818                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1819                         if (*expr == ptr) {
1820                                 *expr = &zero_triple;
1821                         }
1822                 }
1823                 expr = triple_misc(state, set->member, 0);
1824                 for(; expr; expr = triple_misc(state, set->member, expr)) {
1825                         if (*expr == ptr) {
1826                                 *expr = &zero_triple;
1827                         }
1828                 }
1829                 expr = triple_targ(state, set->member, 0);
1830                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1831                         if (*expr == ptr) {
1832                                 *expr = &zero_triple;
1833                         }
1834                 }
1835                 unuse_triple(ptr, set->member);
1836         }
1837         free_triple(state, ptr);
1838 }
1839
1840 static void print_triple(struct compile_state *state, struct triple *ptr);
1841
1842 #define TOK_UNKNOWN     0
1843 #define TOK_SPACE       1
1844 #define TOK_SEMI        2
1845 #define TOK_LBRACE      3
1846 #define TOK_RBRACE      4
1847 #define TOK_COMMA       5
1848 #define TOK_EQ          6
1849 #define TOK_COLON       7
1850 #define TOK_LBRACKET    8
1851 #define TOK_RBRACKET    9
1852 #define TOK_LPAREN      10
1853 #define TOK_RPAREN      11
1854 #define TOK_STAR        12
1855 #define TOK_DOTS        13
1856 #define TOK_MORE        14
1857 #define TOK_LESS        15
1858 #define TOK_TIMESEQ     16
1859 #define TOK_DIVEQ       17
1860 #define TOK_MODEQ       18
1861 #define TOK_PLUSEQ      19
1862 #define TOK_MINUSEQ     20
1863 #define TOK_SLEQ        21
1864 #define TOK_SREQ        22
1865 #define TOK_ANDEQ       23
1866 #define TOK_XOREQ       24
1867 #define TOK_OREQ        25
1868 #define TOK_EQEQ        26
1869 #define TOK_NOTEQ       27
1870 #define TOK_QUEST       28
1871 #define TOK_LOGOR       29
1872 #define TOK_LOGAND      30
1873 #define TOK_OR          31
1874 #define TOK_AND         32
1875 #define TOK_XOR         33
1876 #define TOK_LESSEQ      34
1877 #define TOK_MOREEQ      35
1878 #define TOK_SL          36
1879 #define TOK_SR          37
1880 #define TOK_PLUS        38
1881 #define TOK_MINUS       39
1882 #define TOK_DIV         40
1883 #define TOK_MOD         41
1884 #define TOK_PLUSPLUS    42
1885 #define TOK_MINUSMINUS  43
1886 #define TOK_BANG        44
1887 #define TOK_ARROW       45
1888 #define TOK_DOT         46
1889 #define TOK_TILDE       47
1890 #define TOK_LIT_STRING  48
1891 #define TOK_LIT_CHAR    49
1892 #define TOK_LIT_INT     50
1893 #define TOK_LIT_FLOAT   51
1894 #define TOK_MACRO       52
1895 #define TOK_CONCATENATE 53
1896
1897 #define TOK_IDENT       54
1898 #define TOK_STRUCT_NAME 55
1899 #define TOK_ENUM_CONST  56
1900 #define TOK_TYPE_NAME   57
1901
1902 #define TOK_AUTO        58
1903 #define TOK_BREAK       59
1904 #define TOK_CASE        60
1905 #define TOK_CHAR        61
1906 #define TOK_CONST       62
1907 #define TOK_CONTINUE    63
1908 #define TOK_DEFAULT     64
1909 #define TOK_DO          65
1910 #define TOK_DOUBLE      66
1911 #define TOK_ELSE        67
1912 #define TOK_ENUM        68
1913 #define TOK_EXTERN      69
1914 #define TOK_FLOAT       70
1915 #define TOK_FOR         71
1916 #define TOK_GOTO        72
1917 #define TOK_IF          73
1918 #define TOK_INLINE      74
1919 #define TOK_INT         75
1920 #define TOK_LONG        76
1921 #define TOK_REGISTER    77
1922 #define TOK_RESTRICT    78
1923 #define TOK_RETURN      79
1924 #define TOK_SHORT       80
1925 #define TOK_SIGNED      81
1926 #define TOK_SIZEOF      82
1927 #define TOK_STATIC      83
1928 #define TOK_STRUCT      84
1929 #define TOK_SWITCH      85
1930 #define TOK_TYPEDEF     86
1931 #define TOK_UNION       87
1932 #define TOK_UNSIGNED    88
1933 #define TOK_VOID        89
1934 #define TOK_VOLATILE    90
1935 #define TOK_WHILE       91
1936 #define TOK_ASM         92
1937 #define TOK_ATTRIBUTE   93
1938 #define TOK_ALIGNOF     94
1939 #define TOK_FIRST_KEYWORD TOK_AUTO
1940 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1941
1942 #define TOK_DEFINE      100
1943 #define TOK_UNDEF       101
1944 #define TOK_INCLUDE     102
1945 #define TOK_LINE        103
1946 #define TOK_ERROR       104
1947 #define TOK_WARNING     105
1948 #define TOK_PRAGMA      106
1949 #define TOK_IFDEF       107
1950 #define TOK_IFNDEF      108
1951 #define TOK_ELIF        109
1952 #define TOK_ENDIF       110
1953
1954 #define TOK_FIRST_MACRO TOK_DEFINE
1955 #define TOK_LAST_MACRO  TOK_ENDIF
1956          
1957 #define TOK_EOF         111
1958
1959 static const char *tokens[] = {
1960 [TOK_UNKNOWN     ] = "unknown",
1961 [TOK_SPACE       ] = ":space:",
1962 [TOK_SEMI        ] = ";",
1963 [TOK_LBRACE      ] = "{",
1964 [TOK_RBRACE      ] = "}",
1965 [TOK_COMMA       ] = ",",
1966 [TOK_EQ          ] = "=",
1967 [TOK_COLON       ] = ":",
1968 [TOK_LBRACKET    ] = "[",
1969 [TOK_RBRACKET    ] = "]",
1970 [TOK_LPAREN      ] = "(",
1971 [TOK_RPAREN      ] = ")",
1972 [TOK_STAR        ] = "*",
1973 [TOK_DOTS        ] = "...",
1974 [TOK_MORE        ] = ">",
1975 [TOK_LESS        ] = "<",
1976 [TOK_TIMESEQ     ] = "*=",
1977 [TOK_DIVEQ       ] = "/=",
1978 [TOK_MODEQ       ] = "%=",
1979 [TOK_PLUSEQ      ] = "+=",
1980 [TOK_MINUSEQ     ] = "-=",
1981 [TOK_SLEQ        ] = "<<=",
1982 [TOK_SREQ        ] = ">>=",
1983 [TOK_ANDEQ       ] = "&=",
1984 [TOK_XOREQ       ] = "^=",
1985 [TOK_OREQ        ] = "|=",
1986 [TOK_EQEQ        ] = "==",
1987 [TOK_NOTEQ       ] = "!=",
1988 [TOK_QUEST       ] = "?",
1989 [TOK_LOGOR       ] = "||",
1990 [TOK_LOGAND      ] = "&&",
1991 [TOK_OR          ] = "|",
1992 [TOK_AND         ] = "&",
1993 [TOK_XOR         ] = "^",
1994 [TOK_LESSEQ      ] = "<=",
1995 [TOK_MOREEQ      ] = ">=",
1996 [TOK_SL          ] = "<<",
1997 [TOK_SR          ] = ">>",
1998 [TOK_PLUS        ] = "+",
1999 [TOK_MINUS       ] = "-",
2000 [TOK_DIV         ] = "/",
2001 [TOK_MOD         ] = "%",
2002 [TOK_PLUSPLUS    ] = "++",
2003 [TOK_MINUSMINUS  ] = "--",
2004 [TOK_BANG        ] = "!",
2005 [TOK_ARROW       ] = "->",
2006 [TOK_DOT         ] = ".",
2007 [TOK_TILDE       ] = "~",
2008 [TOK_LIT_STRING  ] = ":string:",
2009 [TOK_IDENT       ] = ":ident:",
2010 [TOK_TYPE_NAME   ] = ":typename:",
2011 [TOK_LIT_CHAR    ] = ":char:",
2012 [TOK_LIT_INT     ] = ":integer:",
2013 [TOK_LIT_FLOAT   ] = ":float:",
2014 [TOK_MACRO       ] = "#",
2015 [TOK_CONCATENATE ] = "##",
2016
2017 [TOK_AUTO        ] = "auto",
2018 [TOK_BREAK       ] = "break",
2019 [TOK_CASE        ] = "case",
2020 [TOK_CHAR        ] = "char",
2021 [TOK_CONST       ] = "const",
2022 [TOK_CONTINUE    ] = "continue",
2023 [TOK_DEFAULT     ] = "default",
2024 [TOK_DO          ] = "do",
2025 [TOK_DOUBLE      ] = "double",
2026 [TOK_ELSE        ] = "else",
2027 [TOK_ENUM        ] = "enum",
2028 [TOK_EXTERN      ] = "extern",
2029 [TOK_FLOAT       ] = "float",
2030 [TOK_FOR         ] = "for",
2031 [TOK_GOTO        ] = "goto",
2032 [TOK_IF          ] = "if",
2033 [TOK_INLINE      ] = "inline",
2034 [TOK_INT         ] = "int",
2035 [TOK_LONG        ] = "long",
2036 [TOK_REGISTER    ] = "register",
2037 [TOK_RESTRICT    ] = "restrict",
2038 [TOK_RETURN      ] = "return",
2039 [TOK_SHORT       ] = "short",
2040 [TOK_SIGNED      ] = "signed",
2041 [TOK_SIZEOF      ] = "sizeof",
2042 [TOK_STATIC      ] = "static",
2043 [TOK_STRUCT      ] = "struct",
2044 [TOK_SWITCH      ] = "switch",
2045 [TOK_TYPEDEF     ] = "typedef",
2046 [TOK_UNION       ] = "union",
2047 [TOK_UNSIGNED    ] = "unsigned",
2048 [TOK_VOID        ] = "void",
2049 [TOK_VOLATILE    ] = "volatile",
2050 [TOK_WHILE       ] = "while",
2051 [TOK_ASM         ] = "asm",
2052 [TOK_ATTRIBUTE   ] = "__attribute__",
2053 [TOK_ALIGNOF     ] = "__alignof__",
2054
2055 [TOK_DEFINE      ] = "define",
2056 [TOK_UNDEF       ] = "undef",
2057 [TOK_INCLUDE     ] = "include",
2058 [TOK_LINE        ] = "line",
2059 [TOK_ERROR       ] = "error",
2060 [TOK_WARNING     ] = "warning",
2061 [TOK_PRAGMA      ] = "pragma",
2062 [TOK_IFDEF       ] = "ifdef",
2063 [TOK_IFNDEF      ] = "ifndef",
2064 [TOK_ELIF        ] = "elif",
2065 [TOK_ENDIF       ] = "endif",
2066
2067 [TOK_EOF         ] = "EOF",
2068 };
2069
2070 static unsigned int hash(const char *str, int str_len)
2071 {
2072         unsigned int hash;
2073         const char *end;
2074         end = str + str_len;
2075         hash = 0;
2076         for(; str < end; str++) {
2077                 hash = (hash *263) + *str;
2078         }
2079         hash = hash & (HASH_TABLE_SIZE -1);
2080         return hash;
2081 }
2082
2083 static struct hash_entry *lookup(
2084         struct compile_state *state, const char *name, int name_len)
2085 {
2086         struct hash_entry *entry;
2087         unsigned int index;
2088         index = hash(name, name_len);
2089         entry = state->hash_table[index];
2090         while(entry && 
2091                 ((entry->name_len != name_len) ||
2092                         (memcmp(entry->name, name, name_len) != 0))) {
2093                 entry = entry->next;
2094         }
2095         if (!entry) {
2096                 char *new_name;
2097                 /* Get a private copy of the name */
2098                 new_name = xmalloc(name_len + 1, "hash_name");
2099                 memcpy(new_name, name, name_len);
2100                 new_name[name_len] = '\0';
2101
2102                 /* Create a new hash entry */
2103                 entry = xcmalloc(sizeof(*entry), "hash_entry");
2104                 entry->next = state->hash_table[index];
2105                 entry->name = new_name;
2106                 entry->name_len = name_len;
2107
2108                 /* Place the new entry in the hash table */
2109                 state->hash_table[index] = entry;
2110         }
2111         return entry;
2112 }
2113
2114 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2115 {
2116         struct hash_entry *entry;
2117         entry = tk->ident;
2118         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2119                 (entry->tok == TOK_ENUM_CONST) ||
2120                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
2121                         (entry->tok <= TOK_LAST_KEYWORD)))) {
2122                 tk->tok = entry->tok;
2123         }
2124 }
2125
2126 static void ident_to_macro(struct compile_state *state, struct token *tk)
2127 {
2128         struct hash_entry *entry;
2129         entry = tk->ident;
2130         if (entry && 
2131                 (entry->tok >= TOK_FIRST_MACRO) &&
2132                 (entry->tok <= TOK_LAST_MACRO)) {
2133                 tk->tok = entry->tok;
2134         }
2135 }
2136
2137 static void hash_keyword(
2138         struct compile_state *state, const char *keyword, int tok)
2139 {
2140         struct hash_entry *entry;
2141         entry = lookup(state, keyword, strlen(keyword));
2142         if (entry && entry->tok != TOK_UNKNOWN) {
2143                 die("keyword %s already hashed", keyword);
2144         }
2145         entry->tok  = tok;
2146 }
2147
2148 static void symbol(
2149         struct compile_state *state, struct hash_entry *ident,
2150         struct symbol **chain, struct triple *def, struct type *type)
2151 {
2152         struct symbol *sym;
2153         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2154                 error(state, 0, "%s already defined", ident->name);
2155         }
2156         sym = xcmalloc(sizeof(*sym), "symbol");
2157         sym->ident = ident;
2158         sym->def   = def;
2159         sym->type  = type;
2160         sym->scope_depth = state->scope_depth;
2161         sym->next = *chain;
2162         *chain    = sym;
2163 }
2164
2165 static void label_symbol(struct compile_state *state, 
2166         struct hash_entry *ident, struct triple *label)
2167 {
2168         struct symbol *sym;
2169         if (ident->sym_label) {
2170                 error(state, 0, "label %s already defined", ident->name);
2171         }
2172         sym = xcmalloc(sizeof(*sym), "label");
2173         sym->ident = ident;
2174         sym->def   = label;
2175         sym->type  = &void_type;
2176         sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2177         sym->next  = 0;
2178         ident->sym_label = sym;
2179 }
2180
2181 static void start_scope(struct compile_state *state)
2182 {
2183         state->scope_depth++;
2184 }
2185
2186 static void end_scope_syms(struct symbol **chain, int depth)
2187 {
2188         struct symbol *sym, *next;
2189         sym = *chain;
2190         while(sym && (sym->scope_depth == depth)) {
2191                 next = sym->next;
2192                 xfree(sym);
2193                 sym = next;
2194         }
2195         *chain = sym;
2196 }
2197
2198 static void end_scope(struct compile_state *state)
2199 {
2200         int i;
2201         int depth;
2202         /* Walk through the hash table and remove all symbols
2203          * in the current scope. 
2204          */
2205         depth = state->scope_depth;
2206         for(i = 0; i < HASH_TABLE_SIZE; i++) {
2207                 struct hash_entry *entry;
2208                 entry = state->hash_table[i];
2209                 while(entry) {
2210                         end_scope_syms(&entry->sym_label,  depth);
2211                         end_scope_syms(&entry->sym_struct, depth);
2212                         end_scope_syms(&entry->sym_ident,  depth);
2213                         entry = entry->next;
2214                 }
2215         }
2216         state->scope_depth = depth - 1;
2217 }
2218
2219 static void register_keywords(struct compile_state *state)
2220 {
2221         hash_keyword(state, "auto",          TOK_AUTO);
2222         hash_keyword(state, "break",         TOK_BREAK);
2223         hash_keyword(state, "case",          TOK_CASE);
2224         hash_keyword(state, "char",          TOK_CHAR);
2225         hash_keyword(state, "const",         TOK_CONST);
2226         hash_keyword(state, "continue",      TOK_CONTINUE);
2227         hash_keyword(state, "default",       TOK_DEFAULT);
2228         hash_keyword(state, "do",            TOK_DO);
2229         hash_keyword(state, "double",        TOK_DOUBLE);
2230         hash_keyword(state, "else",          TOK_ELSE);
2231         hash_keyword(state, "enum",          TOK_ENUM);
2232         hash_keyword(state, "extern",        TOK_EXTERN);
2233         hash_keyword(state, "float",         TOK_FLOAT);
2234         hash_keyword(state, "for",           TOK_FOR);
2235         hash_keyword(state, "goto",          TOK_GOTO);
2236         hash_keyword(state, "if",            TOK_IF);
2237         hash_keyword(state, "inline",        TOK_INLINE);
2238         hash_keyword(state, "int",           TOK_INT);
2239         hash_keyword(state, "long",          TOK_LONG);
2240         hash_keyword(state, "register",      TOK_REGISTER);
2241         hash_keyword(state, "restrict",      TOK_RESTRICT);
2242         hash_keyword(state, "return",        TOK_RETURN);
2243         hash_keyword(state, "short",         TOK_SHORT);
2244         hash_keyword(state, "signed",        TOK_SIGNED);
2245         hash_keyword(state, "sizeof",        TOK_SIZEOF);
2246         hash_keyword(state, "static",        TOK_STATIC);
2247         hash_keyword(state, "struct",        TOK_STRUCT);
2248         hash_keyword(state, "switch",        TOK_SWITCH);
2249         hash_keyword(state, "typedef",       TOK_TYPEDEF);
2250         hash_keyword(state, "union",         TOK_UNION);
2251         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
2252         hash_keyword(state, "void",          TOK_VOID);
2253         hash_keyword(state, "volatile",      TOK_VOLATILE);
2254         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
2255         hash_keyword(state, "while",         TOK_WHILE);
2256         hash_keyword(state, "asm",           TOK_ASM);
2257         hash_keyword(state, "__asm__",       TOK_ASM);
2258         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2259         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
2260 }
2261
2262 static void register_macro_keywords(struct compile_state *state)
2263 {
2264         hash_keyword(state, "define",        TOK_DEFINE);
2265         hash_keyword(state, "undef",         TOK_UNDEF);
2266         hash_keyword(state, "include",       TOK_INCLUDE);
2267         hash_keyword(state, "line",          TOK_LINE);
2268         hash_keyword(state, "error",         TOK_ERROR);
2269         hash_keyword(state, "warning",       TOK_WARNING);
2270         hash_keyword(state, "pragma",        TOK_PRAGMA);
2271         hash_keyword(state, "ifdef",         TOK_IFDEF);
2272         hash_keyword(state, "ifndef",        TOK_IFNDEF);
2273         hash_keyword(state, "elif",          TOK_ELIF);
2274         hash_keyword(state, "endif",         TOK_ENDIF);
2275 }
2276
2277 static int spacep(int c)
2278 {
2279         int ret = 0;
2280         switch(c) {
2281         case ' ':
2282         case '\t':
2283         case '\f':
2284         case '\v':
2285         case '\r':
2286         case '\n':
2287                 ret = 1;
2288                 break;
2289         }
2290         return ret;
2291 }
2292
2293 static int digitp(int c)
2294 {
2295         int ret = 0;
2296         switch(c) {
2297         case '0': case '1': case '2': case '3': case '4': 
2298         case '5': case '6': case '7': case '8': case '9':
2299                 ret = 1;
2300                 break;
2301         }
2302         return ret;
2303 }
2304 static int digval(int c)
2305 {
2306         int val = -1;
2307         if ((c >= '0') && (c <= '9')) {
2308                 val = c - '0';
2309         }
2310         return val;
2311 }
2312
2313 static int hexdigitp(int c)
2314 {
2315         int ret = 0;
2316         switch(c) {
2317         case '0': case '1': case '2': case '3': case '4': 
2318         case '5': case '6': case '7': case '8': case '9':
2319         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2320         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2321                 ret = 1;
2322                 break;
2323         }
2324         return ret;
2325 }
2326 static int hexdigval(int c) 
2327 {
2328         int val = -1;
2329         if ((c >= '0') && (c <= '9')) {
2330                 val = c - '0';
2331         }
2332         else if ((c >= 'A') && (c <= 'F')) {
2333                 val = 10 + (c - 'A');
2334         }
2335         else if ((c >= 'a') && (c <= 'f')) {
2336                 val = 10 + (c - 'a');
2337         }
2338         return val;
2339 }
2340
2341 static int octdigitp(int c)
2342 {
2343         int ret = 0;
2344         switch(c) {
2345         case '0': case '1': case '2': case '3': 
2346         case '4': case '5': case '6': case '7':
2347                 ret = 1;
2348                 break;
2349         }
2350         return ret;
2351 }
2352 static int octdigval(int c)
2353 {
2354         int val = -1;
2355         if ((c >= '0') && (c <= '7')) {
2356                 val = c - '0';
2357         }
2358         return val;
2359 }
2360
2361 static int letterp(int c)
2362 {
2363         int ret = 0;
2364         switch(c) {
2365         case 'a': case 'b': case 'c': case 'd': case 'e':
2366         case 'f': case 'g': case 'h': case 'i': case 'j':
2367         case 'k': case 'l': case 'm': case 'n': case 'o':
2368         case 'p': case 'q': case 'r': case 's': case 't':
2369         case 'u': case 'v': case 'w': case 'x': case 'y':
2370         case 'z':
2371         case 'A': case 'B': case 'C': case 'D': case 'E':
2372         case 'F': case 'G': case 'H': case 'I': case 'J':
2373         case 'K': case 'L': case 'M': case 'N': case 'O':
2374         case 'P': case 'Q': case 'R': case 'S': case 'T':
2375         case 'U': case 'V': case 'W': case 'X': case 'Y':
2376         case 'Z':
2377         case '_':
2378                 ret = 1;
2379                 break;
2380         }
2381         return ret;
2382 }
2383
2384 static int char_value(struct compile_state *state,
2385         const signed char **strp, const signed char *end)
2386 {
2387         const signed char *str;
2388         int c;
2389         str = *strp;
2390         c = *str++;
2391         if ((c == '\\') && (str < end)) {
2392                 switch(*str) {
2393                 case 'n':  c = '\n'; str++; break;
2394                 case 't':  c = '\t'; str++; break;
2395                 case 'v':  c = '\v'; str++; break;
2396                 case 'b':  c = '\b'; str++; break;
2397                 case 'r':  c = '\r'; str++; break;
2398                 case 'f':  c = '\f'; str++; break;
2399                 case 'a':  c = '\a'; str++; break;
2400                 case '\\': c = '\\'; str++; break;
2401                 case '?':  c = '?';  str++; break;
2402                 case '\'': c = '\''; str++; break;
2403                 case '"':  c = '"';  break;
2404                 case 'x': 
2405                         c = 0;
2406                         str++;
2407                         while((str < end) && hexdigitp(*str)) {
2408                                 c <<= 4;
2409                                 c += hexdigval(*str);
2410                                 str++;
2411                         }
2412                         break;
2413                 case '0': case '1': case '2': case '3': 
2414                 case '4': case '5': case '6': case '7':
2415                         c = 0;
2416                         while((str < end) && octdigitp(*str)) {
2417                                 c <<= 3;
2418                                 c += octdigval(*str);
2419                                 str++;
2420                         }
2421                         break;
2422                 default:
2423                         error(state, 0, "Invalid character constant");
2424                         break;
2425                 }
2426         }
2427         *strp = str;
2428         return c;
2429 }
2430
2431 static char *after_digits(char *ptr, char *end)
2432 {
2433         while((ptr < end) && digitp(*ptr)) {
2434                 ptr++;
2435         }
2436         return ptr;
2437 }
2438
2439 static char *after_octdigits(char *ptr, char *end)
2440 {
2441         while((ptr < end) && octdigitp(*ptr)) {
2442                 ptr++;
2443         }
2444         return ptr;
2445 }
2446
2447 static char *after_hexdigits(char *ptr, char *end)
2448 {
2449         while((ptr < end) && hexdigitp(*ptr)) {
2450                 ptr++;
2451         }
2452         return ptr;
2453 }
2454
2455 static void save_string(struct compile_state *state, 
2456         struct token *tk, char *start, char *end, const char *id)
2457 {
2458         char *str;
2459         int str_len;
2460         /* Create a private copy of the string */
2461         str_len = end - start + 1;
2462         str = xmalloc(str_len + 1, id);
2463         memcpy(str, start, str_len);
2464         str[str_len] = '\0';
2465
2466         /* Store the copy in the token */
2467         tk->val.str = str;
2468         tk->str_len = str_len;
2469 }
2470 static void next_token(struct compile_state *state, int index)
2471 {
2472         struct file_state *file;
2473         struct token *tk;
2474         char *token;
2475         int c, c1, c2, c3;
2476         char *tokp, *end;
2477         int tok;
2478 next_token:
2479         file = state->file;
2480         tk = &state->token[index];
2481         tk->str_len = 0;
2482         tk->ident = 0;
2483         token = tokp = file->pos;
2484         end = file->buf + file->size;
2485         tok = TOK_UNKNOWN;
2486         c = -1;
2487         if (tokp < end) {
2488                 c = *tokp;
2489         }
2490         c1 = -1;
2491         if ((tokp + 1) < end) {
2492                 c1 = tokp[1];
2493         }
2494         c2 = -1;
2495         if ((tokp + 2) < end) {
2496                 c2 = tokp[2];
2497         }
2498         c3 = -1;
2499         if ((tokp + 3) < end) {
2500                 c3 = tokp[3];
2501         }
2502         if (tokp >= end) {
2503                 tok = TOK_EOF;
2504                 tokp = end;
2505         }
2506         /* Whitespace */
2507         else if (spacep(c)) {
2508                 tok = TOK_SPACE;
2509                 while ((tokp < end) && spacep(c)) {
2510                         if (c == '\n') {
2511                                 file->line++;
2512                                 file->report_line++;
2513                                 file->line_start = tokp + 1;
2514                         }
2515                         c = *(++tokp);
2516                 }
2517                 if (!spacep(c)) {
2518                         tokp--;
2519                 }
2520         }
2521         /* EOL Comments */
2522         else if ((c == '/') && (c1 == '/')) {
2523                 tok = TOK_SPACE;
2524                 for(tokp += 2; tokp < end; tokp++) {
2525                         c = *tokp;
2526                         if (c == '\n') {
2527                                 file->line++;
2528                                 file->report_line++;
2529                                 file->line_start = tokp +1;
2530                                 break;
2531                         }
2532                 }
2533         }
2534         /* Comments */
2535         else if ((c == '/') && (c1 == '*')) {
2536                 int line;
2537                 char *line_start;
2538                 line = file->line;
2539                 line_start = file->line_start;
2540                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2541                         c = *tokp;
2542                         if (c == '\n') {
2543                                 line++;
2544                                 line_start = tokp +1;
2545                         }
2546                         else if ((c == '*') && (tokp[1] == '/')) {
2547                                 tok = TOK_SPACE;
2548                                 tokp += 1;
2549                                 break;
2550                         }
2551                 }
2552                 if (tok == TOK_UNKNOWN) {
2553                         error(state, 0, "unterminated comment");
2554                 }
2555                 file->report_line += line - file->line;
2556                 file->line = line;
2557                 file->line_start = line_start;
2558         }
2559         /* string constants */
2560         else if ((c == '"') ||
2561                 ((c == 'L') && (c1 == '"'))) {
2562                 int line;
2563                 char *line_start;
2564                 int wchar;
2565                 line = file->line;
2566                 line_start = file->line_start;
2567                 wchar = 0;
2568                 if (c == 'L') {
2569                         wchar = 1;
2570                         tokp++;
2571                 }
2572                 for(tokp += 1; tokp < end; tokp++) {
2573                         c = *tokp;
2574                         if (c == '\n') {
2575                                 line++;
2576                                 line_start = tokp + 1;
2577                         }
2578                         else if ((c == '\\') && (tokp +1 < end)) {
2579                                 tokp++;
2580                         }
2581                         else if (c == '"') {
2582                                 tok = TOK_LIT_STRING;
2583                                 break;
2584                         }
2585                 }
2586                 if (tok == TOK_UNKNOWN) {
2587                         error(state, 0, "unterminated string constant");
2588                 }
2589                 if (line != file->line) {
2590                         warning(state, 0, "multiline string constant");
2591                 }
2592                 file->report_line += line - file->line;
2593                 file->line = line;
2594                 file->line_start = line_start;
2595
2596                 /* Save the string value */
2597                 save_string(state, tk, token, tokp, "literal string");
2598         }
2599         /* character constants */
2600         else if ((c == '\'') ||
2601                 ((c == 'L') && (c1 == '\''))) {
2602                 int line;
2603                 char *line_start;
2604                 int wchar;
2605                 line = file->line;
2606                 line_start = file->line_start;
2607                 wchar = 0;
2608                 if (c == 'L') {
2609                         wchar = 1;
2610                         tokp++;
2611                 }
2612                 for(tokp += 1; tokp < end; tokp++) {
2613                         c = *tokp;
2614                         if (c == '\n') {
2615                                 line++;
2616                                 line_start = tokp + 1;
2617                         }
2618                         else if ((c == '\\') && (tokp +1 < end)) {
2619                                 tokp++;
2620                         }
2621                         else if (c == '\'') {
2622                                 tok = TOK_LIT_CHAR;
2623                                 break;
2624                         }
2625                 }
2626                 if (tok == TOK_UNKNOWN) {
2627                         error(state, 0, "unterminated character constant");
2628                 }
2629                 if (line != file->line) {
2630                         warning(state, 0, "multiline character constant");
2631                 }
2632                 file->report_line += line - file->line;
2633                 file->line = line;
2634                 file->line_start = line_start;
2635
2636                 /* Save the character value */
2637                 save_string(state, tk, token, tokp, "literal character");
2638         }
2639         /* integer and floating constants 
2640          * Integer Constants
2641          * {digits}
2642          * 0[Xx]{hexdigits}
2643          * 0{octdigit}+
2644          * 
2645          * Floating constants
2646          * {digits}.{digits}[Ee][+-]?{digits}
2647          * {digits}.{digits}
2648          * {digits}[Ee][+-]?{digits}
2649          * .{digits}[Ee][+-]?{digits}
2650          * .{digits}
2651          */
2652         
2653         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2654                 char *next, *new;
2655                 int is_float;
2656                 is_float = 0;
2657                 if (c != '.') {
2658                         next = after_digits(tokp, end);
2659                 }
2660                 else {
2661                         next = tokp;
2662                 }
2663                 if (next[0] == '.') {
2664                         new = after_digits(next, end);
2665                         is_float = (new != next);
2666                         next = new;
2667                 }
2668                 if ((next[0] == 'e') || (next[0] == 'E')) {
2669                         if (((next + 1) < end) && 
2670                                 ((next[1] == '+') || (next[1] == '-'))) {
2671                                 next++;
2672                         }
2673                         new = after_digits(next, end);
2674                         is_float = (new != next);
2675                         next = new;
2676                 }
2677                 if (is_float) {
2678                         tok = TOK_LIT_FLOAT;
2679                         if ((next < end) && (
2680                                 (next[0] == 'f') ||
2681                                 (next[0] == 'F') ||
2682                                 (next[0] == 'l') ||
2683                                 (next[0] == 'L'))
2684                                 ) {
2685                                 next++;
2686                         }
2687                 }
2688                 if (!is_float && digitp(c)) {
2689                         tok = TOK_LIT_INT;
2690                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2691                                 next = after_hexdigits(tokp + 2, end);
2692                         }
2693                         else if (c == '0') {
2694                                 next = after_octdigits(tokp, end);
2695                         }
2696                         else {
2697                                 next = after_digits(tokp, end);
2698                         }
2699                         /* crazy integer suffixes */
2700                         if ((next < end) && 
2701                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2702                                 next++;
2703                                 if ((next < end) &&
2704                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2705                                         next++;
2706                                 }
2707                         }
2708                         else if ((next < end) &&
2709                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2710                                 next++;
2711                                 if ((next < end) && 
2712                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2713                                         next++;
2714                                 }
2715                         }
2716                 }
2717                 tokp = next - 1;
2718
2719                 /* Save the integer/floating point value */
2720                 save_string(state, tk, token, tokp, "literal number");
2721         }
2722         /* identifiers */
2723         else if (letterp(c)) {
2724                 tok = TOK_IDENT;
2725                 for(tokp += 1; tokp < end; tokp++) {
2726                         c = *tokp;
2727                         if (!letterp(c) && !digitp(c)) {
2728                                 break;
2729                         }
2730                 }
2731                 tokp -= 1;
2732                 tk->ident = lookup(state, token, tokp +1 - token);
2733         }
2734         /* C99 alternate macro characters */
2735         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2736                 tokp += 3; 
2737                 tok = TOK_CONCATENATE; 
2738         }
2739         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2740         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2741         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2742         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2743         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2744         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2745         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2746         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2747         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2748         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2749         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2750         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2751         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2752         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2753         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2754         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2755         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2756         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2757         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2758         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2759         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2760         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2761         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2762         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2763         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2764         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2765         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2766         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2767         else if (c == ';') { tok = TOK_SEMI; }
2768         else if (c == '{') { tok = TOK_LBRACE; }
2769         else if (c == '}') { tok = TOK_RBRACE; }
2770         else if (c == ',') { tok = TOK_COMMA; }
2771         else if (c == '=') { tok = TOK_EQ; }
2772         else if (c == ':') { tok = TOK_COLON; }
2773         else if (c == '[') { tok = TOK_LBRACKET; }
2774         else if (c == ']') { tok = TOK_RBRACKET; }
2775         else if (c == '(') { tok = TOK_LPAREN; }
2776         else if (c == ')') { tok = TOK_RPAREN; }
2777         else if (c == '*') { tok = TOK_STAR; }
2778         else if (c == '>') { tok = TOK_MORE; }
2779         else if (c == '<') { tok = TOK_LESS; }
2780         else if (c == '?') { tok = TOK_QUEST; }
2781         else if (c == '|') { tok = TOK_OR; }
2782         else if (c == '&') { tok = TOK_AND; }
2783         else if (c == '^') { tok = TOK_XOR; }
2784         else if (c == '+') { tok = TOK_PLUS; }
2785         else if (c == '-') { tok = TOK_MINUS; }
2786         else if (c == '/') { tok = TOK_DIV; }
2787         else if (c == '%') { tok = TOK_MOD; }
2788         else if (c == '!') { tok = TOK_BANG; }
2789         else if (c == '.') { tok = TOK_DOT; }
2790         else if (c == '~') { tok = TOK_TILDE; }
2791         else if (c == '#') { tok = TOK_MACRO; }
2792         if (tok == TOK_MACRO) {
2793                 /* Only match preprocessor directives at the start of a line */
2794                 char *ptr;
2795                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2796                         ;
2797                 if (ptr != tokp) {
2798                         tok = TOK_UNKNOWN;
2799                 }
2800         }
2801         if (tok == TOK_UNKNOWN) {
2802                 error(state, 0, "unknown token");
2803         }
2804
2805         file->pos = tokp + 1;
2806         tk->tok = tok;
2807         if (tok == TOK_IDENT) {
2808                 ident_to_keyword(state, tk);
2809         }
2810         /* Don't return space tokens. */
2811         if (tok == TOK_SPACE) {
2812                 goto next_token;
2813         }
2814 }
2815
2816 static void compile_macro(struct compile_state *state, struct token *tk)
2817 {
2818         struct file_state *file;
2819         struct hash_entry *ident;
2820         ident = tk->ident;
2821         file = xmalloc(sizeof(*file), "file_state");
2822         file->basename = xstrdup(tk->ident->name);
2823         file->dirname = xstrdup("");
2824         file->size = ident->sym_define->buf_len;
2825         file->buf = xmalloc(file->size +2,  file->basename);
2826         memcpy(file->buf, ident->sym_define->buf, file->size);
2827         file->buf[file->size] = '\n';
2828         file->buf[file->size + 1] = '\0';
2829         file->pos = file->buf;
2830         file->line_start = file->pos;
2831         file->line = 1;
2832         file->report_line = 1;
2833         file->report_name = file->basename;
2834         file->report_dir  = file->dirname;
2835         file->prev = state->file;
2836         state->file = file;
2837 }
2838
2839
2840 static int mpeek(struct compile_state *state, int index)
2841 {
2842         struct token *tk;
2843         int rescan;
2844         tk = &state->token[index + 1];
2845         if (tk->tok == -1) {
2846                 next_token(state, index + 1);
2847         }
2848         do {
2849                 rescan = 0;
2850                 if ((tk->tok == TOK_EOF) && 
2851                         (state->file != state->macro_file) &&
2852                         (state->file->prev)) {
2853                         struct file_state *file = state->file;
2854                         state->file = file->prev;
2855                         /* file->basename is used keep it */
2856                         if (file->report_dir != file->dirname) {
2857                                 xfree(file->report_dir);
2858                         }
2859                         xfree(file->dirname);
2860                         xfree(file->buf);
2861                         xfree(file);
2862                         next_token(state, index + 1);
2863                         rescan = 1;
2864                 }
2865                 else if (tk->ident && tk->ident->sym_define) {
2866                         compile_macro(state, tk);
2867                         next_token(state, index + 1);
2868                         rescan = 1;
2869                 }
2870         } while(rescan);
2871         /* Don't show the token on the next line */
2872         if (state->macro_line < state->macro_file->line) {
2873                 return TOK_EOF;
2874         }
2875         return state->token[index +1].tok;
2876 }
2877
2878 static void meat(struct compile_state *state, int index, int tok)
2879 {
2880         int next_tok;
2881         int i;
2882         next_tok = mpeek(state, index);
2883         if (next_tok != tok) {
2884                 const char *name1, *name2;
2885                 name1 = tokens[next_tok];
2886                 name2 = "";
2887                 if (next_tok == TOK_IDENT) {
2888                         name2 = state->token[index + 1].ident->name;
2889                 }
2890                 error(state, 0, "found %s %s expected %s", 
2891                         name1, name2, tokens[tok]);
2892         }
2893         /* Free the old token value */
2894         if (state->token[index].str_len) {
2895                 memset((void *)(state->token[index].val.str), -1, 
2896                         state->token[index].str_len);
2897                 xfree(state->token[index].val.str);
2898         }
2899         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2900                 state->token[i] = state->token[i + 1];
2901         }
2902         memset(&state->token[i], 0, sizeof(state->token[i]));
2903         state->token[i].tok = -1;
2904 }
2905
2906 static long_t mcexpr(struct compile_state *state, int index);
2907
2908 static long_t mprimary_expr(struct compile_state *state, int index)
2909 {
2910         long_t val;
2911         int tok;
2912         tok = mpeek(state, index);
2913         while(state->token[index + 1].ident && 
2914                 state->token[index + 1].ident->sym_define) {
2915                 meat(state, index, tok);
2916                 compile_macro(state, &state->token[index]);
2917                 tok = mpeek(state, index);
2918         }
2919         switch(tok) {
2920         case TOK_LPAREN:
2921                 meat(state, index, TOK_LPAREN);
2922                 val = mcexpr(state, index);
2923                 meat(state, index, TOK_RPAREN);
2924                 break;
2925         case TOK_LIT_INT:
2926         {
2927                 char *end;
2928                 meat(state, index, TOK_LIT_INT);
2929                 errno = 0;
2930                 val = strtol(state->token[index].val.str, &end, 0);
2931                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2932                         (errno == ERANGE)) {
2933                         error(state, 0, "Integer constant to large");
2934                 }
2935                 break;
2936         }
2937         default:
2938                 meat(state, index, TOK_LIT_INT);
2939                 val = 0;
2940         }
2941         return val;
2942 }
2943 static long_t munary_expr(struct compile_state *state, int index)
2944 {
2945         long_t val;
2946         switch(mpeek(state, index)) {
2947         case TOK_PLUS:
2948                 meat(state, index, TOK_PLUS);
2949                 val = munary_expr(state, index);
2950                 val = + val;
2951                 break;
2952         case TOK_MINUS:
2953                 meat(state, index, TOK_MINUS);
2954                 val = munary_expr(state, index);
2955                 val = - val;
2956                 break;
2957         case TOK_TILDE:
2958                 meat(state, index, TOK_BANG);
2959                 val = munary_expr(state, index);
2960                 val = ~ val;
2961                 break;
2962         case TOK_BANG:
2963                 meat(state, index, TOK_BANG);
2964                 val = munary_expr(state, index);
2965                 val = ! val;
2966                 break;
2967         default:
2968                 val = mprimary_expr(state, index);
2969                 break;
2970         }
2971         return val;
2972         
2973 }
2974 static long_t mmul_expr(struct compile_state *state, int index)
2975 {
2976         long_t val;
2977         int done;
2978         val = munary_expr(state, index);
2979         do {
2980                 long_t right;
2981                 done = 0;
2982                 switch(mpeek(state, index)) {
2983                 case TOK_STAR:
2984                         meat(state, index, TOK_STAR);
2985                         right = munary_expr(state, index);
2986                         val = val * right;
2987                         break;
2988                 case TOK_DIV:
2989                         meat(state, index, TOK_DIV);
2990                         right = munary_expr(state, index);
2991                         val = val / right;
2992                         break;
2993                 case TOK_MOD:
2994                         meat(state, index, TOK_MOD);
2995                         right = munary_expr(state, index);
2996                         val = val % right;
2997                         break;
2998                 default:
2999                         done = 1;
3000                         break;
3001                 }
3002         } while(!done);
3003
3004         return val;
3005 }
3006
3007 static long_t madd_expr(struct compile_state *state, int index)
3008 {
3009         long_t val;
3010         int done;
3011         val = mmul_expr(state, index);
3012         do {
3013                 long_t right;
3014                 done = 0;
3015                 switch(mpeek(state, index)) {
3016                 case TOK_PLUS:
3017                         meat(state, index, TOK_PLUS);
3018                         right = mmul_expr(state, index);
3019                         val = val + right;
3020                         break;
3021                 case TOK_MINUS:
3022                         meat(state, index, TOK_MINUS);
3023                         right = mmul_expr(state, index);
3024                         val = val - right;
3025                         break;
3026                 default:
3027                         done = 1;
3028                         break;
3029                 }
3030         } while(!done);
3031
3032         return val;
3033 }
3034
3035 static long_t mshift_expr(struct compile_state *state, int index)
3036 {
3037         long_t val;
3038         int done;
3039         val = madd_expr(state, index);
3040         do {
3041                 long_t right;
3042                 done = 0;
3043                 switch(mpeek(state, index)) {
3044                 case TOK_SL:
3045                         meat(state, index, TOK_SL);
3046                         right = madd_expr(state, index);
3047                         val = val << right;
3048                         break;
3049                 case TOK_SR:
3050                         meat(state, index, TOK_SR);
3051                         right = madd_expr(state, index);
3052                         val = val >> right;
3053                         break;
3054                 default:
3055                         done = 1;
3056                         break;
3057                 }
3058         } while(!done);
3059
3060         return val;
3061 }
3062
3063 static long_t mrel_expr(struct compile_state *state, int index)
3064 {
3065         long_t val;
3066         int done;
3067         val = mshift_expr(state, index);
3068         do {
3069                 long_t right;
3070                 done = 0;
3071                 switch(mpeek(state, index)) {
3072                 case TOK_LESS:
3073                         meat(state, index, TOK_LESS);
3074                         right = mshift_expr(state, index);
3075                         val = val < right;
3076                         break;
3077                 case TOK_MORE:
3078                         meat(state, index, TOK_MORE);
3079                         right = mshift_expr(state, index);
3080                         val = val > right;
3081                         break;
3082                 case TOK_LESSEQ:
3083                         meat(state, index, TOK_LESSEQ);
3084                         right = mshift_expr(state, index);
3085                         val = val <= right;
3086                         break;
3087                 case TOK_MOREEQ:
3088                         meat(state, index, TOK_MOREEQ);
3089                         right = mshift_expr(state, index);
3090                         val = val >= right;
3091                         break;
3092                 default:
3093                         done = 1;
3094                         break;
3095                 }
3096         } while(!done);
3097         return val;
3098 }
3099
3100 static long_t meq_expr(struct compile_state *state, int index)
3101 {
3102         long_t val;
3103         int done;
3104         val = mrel_expr(state, index);
3105         do {
3106                 long_t right;
3107                 done = 0;
3108                 switch(mpeek(state, index)) {
3109                 case TOK_EQEQ:
3110                         meat(state, index, TOK_EQEQ);
3111                         right = mrel_expr(state, index);
3112                         val = val == right;
3113                         break;
3114                 case TOK_NOTEQ:
3115                         meat(state, index, TOK_NOTEQ);
3116                         right = mrel_expr(state, index);
3117                         val = val != right;
3118                         break;
3119                 default:
3120                         done = 1;
3121                         break;
3122                 }
3123         } while(!done);
3124         return val;
3125 }
3126
3127 static long_t mand_expr(struct compile_state *state, int index)
3128 {
3129         long_t val;
3130         val = meq_expr(state, index);
3131         if (mpeek(state, index) == TOK_AND) {
3132                 long_t right;
3133                 meat(state, index, TOK_AND);
3134                 right = meq_expr(state, index);
3135                 val = val & right;
3136         }
3137         return val;
3138 }
3139
3140 static long_t mxor_expr(struct compile_state *state, int index)
3141 {
3142         long_t val;
3143         val = mand_expr(state, index);
3144         if (mpeek(state, index) == TOK_XOR) {
3145                 long_t right;
3146                 meat(state, index, TOK_XOR);
3147                 right = mand_expr(state, index);
3148                 val = val ^ right;
3149         }
3150         return val;
3151 }
3152
3153 static long_t mor_expr(struct compile_state *state, int index)
3154 {
3155         long_t val;
3156         val = mxor_expr(state, index);
3157         if (mpeek(state, index) == TOK_OR) {
3158                 long_t right;
3159                 meat(state, index, TOK_OR);
3160                 right = mxor_expr(state, index);
3161                 val = val | right;
3162         }
3163         return val;
3164 }
3165
3166 static long_t mland_expr(struct compile_state *state, int index)
3167 {
3168         long_t val;
3169         val = mor_expr(state, index);
3170         if (mpeek(state, index) == TOK_LOGAND) {
3171                 long_t right;
3172                 meat(state, index, TOK_LOGAND);
3173                 right = mor_expr(state, index);
3174                 val = val && right;
3175         }
3176         return val;
3177 }
3178 static long_t mlor_expr(struct compile_state *state, int index)
3179 {
3180         long_t val;
3181         val = mland_expr(state, index);
3182         if (mpeek(state, index) == TOK_LOGOR) {
3183                 long_t right;
3184                 meat(state, index, TOK_LOGOR);
3185                 right = mland_expr(state, index);
3186                 val = val || right;
3187         }
3188         return val;
3189 }
3190
3191 static long_t mcexpr(struct compile_state *state, int index)
3192 {
3193         return mlor_expr(state, index);
3194 }
3195 static void preprocess(struct compile_state *state, int index)
3196 {
3197         /* Doing much more with the preprocessor would require
3198          * a parser and a major restructuring.
3199          * Postpone that for later.
3200          */
3201         struct file_state *file;
3202         struct token *tk;
3203         int line;
3204         int tok;
3205         
3206         file = state->file;
3207         tk = &state->token[index];
3208         state->macro_line = line = file->line;
3209         state->macro_file = file;
3210
3211         next_token(state, index);
3212         ident_to_macro(state, tk);
3213         if (tk->tok == TOK_IDENT) {
3214                 error(state, 0, "undefined preprocessing directive `%s'",
3215                         tk->ident->name);
3216         }
3217         switch(tk->tok) {
3218         case TOK_LIT_INT:
3219         {
3220                 int override_line;
3221                 override_line = strtoul(tk->val.str, 0, 10);
3222                 next_token(state, index);
3223                 /* I have a cpp line marker parse it */
3224                 if (tk->tok == TOK_LIT_STRING) {
3225                         const char *token, *base;
3226                         char *name, *dir;
3227                         int name_len, dir_len;
3228                         name = xmalloc(tk->str_len, "report_name");
3229                         token = tk->val.str + 1;
3230                         base = strrchr(token, '/');
3231                         name_len = tk->str_len -2;
3232                         if (base != 0) {
3233                                 dir_len = base - token;
3234                                 base++;
3235                                 name_len -= base - token;
3236                         } else {
3237                                 dir_len = 0;
3238                                 base = token;
3239                         }
3240                         memcpy(name, base, name_len);
3241                         name[name_len] = '\0';
3242                         dir = xmalloc(dir_len + 1, "report_dir");
3243                         memcpy(dir, token, dir_len);
3244                         dir[dir_len] = '\0';
3245                         file->report_line = override_line - 1;
3246                         file->report_name = name;
3247                         file->report_dir = dir;
3248                 }
3249         }
3250                 break;
3251         case TOK_LINE:
3252                 meat(state, index, TOK_LINE);
3253                 meat(state, index, TOK_LIT_INT);
3254                 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3255                 if (mpeek(state, index) == TOK_LIT_STRING) {
3256                         const char *token, *base;
3257                         char *name, *dir;
3258                         int name_len, dir_len;
3259                         meat(state, index, TOK_LIT_STRING);
3260                         name = xmalloc(tk->str_len, "report_name");
3261                         token = tk->val.str + 1;
3262                         name_len = tk->str_len - 2;
3263                         if (base != 0) {
3264                                 dir_len = base - token;
3265                                 base++;
3266                                 name_len -= base - token;
3267                         } else {
3268                                 dir_len = 0;
3269                                 base = token;
3270                         }
3271                         memcpy(name, base, name_len);
3272                         name[name_len] = '\0';
3273                         dir = xmalloc(dir_len + 1, "report_dir");
3274                         memcpy(dir, token, dir_len);
3275                         dir[dir_len] = '\0';
3276                         file->report_name = name;
3277                         file->report_dir = dir;
3278                 }
3279                 break;
3280         case TOK_UNDEF:
3281         case TOK_PRAGMA:
3282                 if (state->if_value < 0) {
3283                         break;
3284                 }
3285                 warning(state, 0, "Ignoring preprocessor directive: %s", 
3286                         tk->ident->name);
3287                 break;
3288         case TOK_ELIF:
3289                 error(state, 0, "#elif not supported");
3290 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3291                 if (state->if_depth == 0) {
3292                         error(state, 0, "#elif without #if");
3293                 }
3294                 /* If the #if was taken the #elif just disables the following code */
3295                 if (state->if_value >= 0) {
3296                         state->if_value = - state->if_value;
3297                 }
3298                 /* If the previous #if was not taken see if the #elif enables the 
3299                  * trailing code.
3300                  */
3301                 else if ((state->if_value < 0) && 
3302                         (state->if_depth == - state->if_value))
3303                 {
3304                         if (mcexpr(state, index) != 0) {
3305                                 state->if_value = state->if_depth;
3306                         }
3307                         else {
3308                                 state->if_value = - state->if_depth;
3309                         }
3310                 }
3311                 break;
3312         case TOK_IF:
3313                 state->if_depth++;
3314                 if (state->if_value < 0) {
3315                         break;
3316                 }
3317                 if (mcexpr(state, index) != 0) {
3318                         state->if_value = state->if_depth;
3319                 }
3320                 else {
3321                         state->if_value = - state->if_depth;
3322                 }
3323                 break;
3324         case TOK_IFNDEF:
3325                 state->if_depth++;
3326                 if (state->if_value < 0) {
3327                         break;
3328                 }
3329                 next_token(state, index);
3330                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3331                         error(state, 0, "Invalid macro name");
3332                 }
3333                 if (tk->ident->sym_define == 0) {
3334                         state->if_value = state->if_depth;
3335                 } 
3336                 else {
3337                         state->if_value = - state->if_depth;
3338                 }
3339                 break;
3340         case TOK_IFDEF:
3341                 state->if_depth++;
3342                 if (state->if_value < 0) {
3343                         break;
3344                 }
3345                 next_token(state, index);
3346                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3347                         error(state, 0, "Invalid macro name");
3348                 }
3349                 if (tk->ident->sym_define != 0) {
3350                         state->if_value = state->if_depth;
3351                 }
3352                 else {
3353                         state->if_value = - state->if_depth;
3354                 }
3355                 break;
3356         case TOK_ELSE:
3357                 if (state->if_depth == 0) {
3358                         error(state, 0, "#else without #if");
3359                 }
3360                 if ((state->if_value >= 0) ||
3361                         ((state->if_value < 0) && 
3362                                 (state->if_depth == -state->if_value)))
3363                 {
3364                         state->if_value = - state->if_value;
3365                 }
3366                 break;
3367         case TOK_ENDIF:
3368                 if (state->if_depth == 0) {
3369                         error(state, 0, "#endif without #if");
3370                 }
3371                 if ((state->if_value >= 0) ||
3372                         ((state->if_value < 0) &&
3373                                 (state->if_depth == -state->if_value))) 
3374                 {
3375                         state->if_value = state->if_depth - 1;
3376                 }
3377                 state->if_depth--;
3378                 break;
3379         case TOK_DEFINE:
3380         {
3381                 struct hash_entry *ident;
3382                 struct macro *macro;
3383                 char *ptr;
3384                 
3385                 if (state->if_value < 0) /* quit early when #if'd out */
3386                         break;
3387
3388                 meat(state, index, TOK_IDENT);
3389                 ident = tk->ident;
3390                 
3391
3392                 if (*file->pos == '(') {
3393 #warning "FIXME macros with arguments not supported"
3394                         error(state, 0, "Macros with arguments not supported");
3395                 }
3396
3397                 /* Find the end of the line to get an estimate of
3398                  * the macro's length.
3399                  */
3400                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
3401                         ;
3402
3403                 if (ident->sym_define != 0) {
3404                         error(state, 0, "macro %s already defined\n", ident->name);
3405                 }
3406                 macro = xmalloc(sizeof(*macro), "macro");
3407                 macro->ident = ident;
3408                 macro->buf_len = ptr - file->pos +1;
3409                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3410
3411                 memcpy(macro->buf, file->pos, macro->buf_len);
3412                 macro->buf[macro->buf_len] = '\n';
3413                 macro->buf[macro->buf_len +1] = '\0';
3414
3415                 ident->sym_define = macro;
3416                 break;
3417         }
3418         case TOK_ERROR:
3419         {
3420                 char *end;
3421                 int len;
3422                 /* Find the end of the line */
3423                 for(end = file->pos; *end != '\n'; end++)
3424                         ;
3425                 len = (end - file->pos);
3426                 if (state->if_value >= 0) {
3427                         error(state, 0, "%*.*s", len, len, file->pos);
3428                 }
3429                 file->pos = end;
3430                 break;
3431         }
3432         case TOK_WARNING:
3433         {
3434                 char *end;
3435                 int len;
3436                 /* Find the end of the line */
3437                 for(end = file->pos; *end != '\n'; end++)
3438                         ;
3439                 len = (end - file->pos);
3440                 if (state->if_value >= 0) {
3441                         warning(state, 0, "%*.*s", len, len, file->pos);
3442                 }
3443                 file->pos = end;
3444                 break;
3445         }
3446         case TOK_INCLUDE:
3447         {
3448                 char *name;
3449                 char *ptr;
3450                 int local;
3451                 local = 0;
3452                 name = 0;
3453                 next_token(state, index);
3454                 if (tk->tok == TOK_LIT_STRING) {
3455                         const char *token;
3456                         int name_len;
3457                         name = xmalloc(tk->str_len, "include");
3458                         token = tk->val.str +1;
3459                         name_len = tk->str_len -2;
3460                         if (*token == '"') {
3461                                 token++;
3462                                 name_len--;
3463                         }
3464                         memcpy(name, token, name_len);
3465                         name[name_len] = '\0';
3466                         local = 1;
3467                 }
3468                 else if (tk->tok == TOK_LESS) {
3469                         char *start, *end;
3470                         start = file->pos;
3471                         for(end = start; *end != '\n'; end++) {
3472                                 if (*end == '>') {
3473                                         break;
3474                                 }
3475                         }
3476                         if (*end == '\n') {
3477                                 error(state, 0, "Unterminated included directive");
3478                         }
3479                         name = xmalloc(end - start + 1, "include");
3480                         memcpy(name, start, end - start);
3481                         name[end - start] = '\0';
3482                         file->pos = end +1;
3483                         local = 0;
3484                 }
3485                 else {
3486                         error(state, 0, "Invalid include directive");
3487                 }
3488                 /* Error if there are any characters after the include */
3489                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3490                         switch(*ptr) {
3491                         case ' ':
3492                         case '\t':
3493                         case '\v':
3494                                 break;
3495                         default:
3496                                 error(state, 0, "garbage after include directive");
3497                         }
3498                 }
3499                 if (state->if_value >= 0) {
3500                         compile_file(state, name, local);
3501                 }
3502                 xfree(name);
3503                 next_token(state, index);
3504                 return;
3505         }
3506         default:
3507                 /* Ignore # without a following ident */
3508                 if (tk->tok == TOK_IDENT) {
3509                         error(state, 0, "Invalid preprocessor directive: %s", 
3510                                 tk->ident->name);
3511                 }
3512                 break;
3513         }
3514         /* Consume the rest of the macro line */
3515         do {
3516                 tok = mpeek(state, index);
3517                 meat(state, index, tok);
3518         } while(tok != TOK_EOF);
3519         return;
3520 }
3521
3522 static void token(struct compile_state *state, int index)
3523 {
3524         struct file_state *file;
3525         struct token *tk;
3526         int rescan;
3527
3528         tk = &state->token[index];
3529         next_token(state, index);
3530         do {
3531                 rescan = 0;
3532                 file = state->file;
3533                 if (tk->tok == TOK_EOF && file->prev) {
3534                         state->file = file->prev;
3535                         /* file->basename is used keep it */
3536                         xfree(file->dirname);
3537                         xfree(file->buf);
3538                         xfree(file);
3539                         next_token(state, index);
3540                         rescan = 1;
3541                 }
3542                 else if (tk->tok == TOK_MACRO) {
3543                         preprocess(state, index);
3544                         rescan = 1;
3545                 }
3546                 else if (tk->ident && tk->ident->sym_define) {
3547                         compile_macro(state, tk);
3548                         next_token(state, index);
3549                         rescan = 1;
3550                 }
3551                 else if (state->if_value < 0) {
3552                         next_token(state, index);
3553                         rescan = 1;
3554                 }
3555         } while(rescan);
3556 }
3557
3558 static int peek(struct compile_state *state)
3559 {
3560         if (state->token[1].tok == -1) {
3561                 token(state, 1);
3562         }
3563         return state->token[1].tok;
3564 }
3565
3566 static int peek2(struct compile_state *state)
3567 {
3568         if (state->token[1].tok == -1) {
3569                 token(state, 1);
3570         }
3571         if (state->token[2].tok == -1) {
3572                 token(state, 2);
3573         }
3574         return state->token[2].tok;
3575 }
3576
3577 static void eat(struct compile_state *state, int tok)
3578 {
3579         int next_tok;
3580         int i;
3581         next_tok = peek(state);
3582         if (next_tok != tok) {
3583                 const char *name1, *name2;
3584                 name1 = tokens[next_tok];
3585                 name2 = "";
3586                 if (next_tok == TOK_IDENT) {
3587                         name2 = state->token[1].ident->name;
3588                 }
3589                 error(state, 0, "\tfound %s %s expected %s",
3590                         name1, name2 ,tokens[tok]);
3591         }
3592         /* Free the old token value */
3593         if (state->token[0].str_len) {
3594                 xfree((void *)(state->token[0].val.str));
3595         }
3596         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3597                 state->token[i] = state->token[i + 1];
3598         }
3599         memset(&state->token[i], 0, sizeof(state->token[i]));
3600         state->token[i].tok = -1;
3601 }
3602
3603 #warning "FIXME do not hardcode the include paths"
3604 static char *include_paths[] = {
3605         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3606         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3607         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3608         0
3609 };
3610
3611 static void compile_file(struct compile_state *state, const char *filename, int local)
3612 {
3613         char cwd[4096];
3614         const char *subdir, *base;
3615         int subdir_len;
3616         struct file_state *file;
3617         char *basename;
3618         file = xmalloc(sizeof(*file), "file_state");
3619
3620         base = strrchr(filename, '/');
3621         subdir = filename;
3622         if (base != 0) {
3623                 subdir_len = base - filename;
3624                 base++;
3625         }
3626         else {
3627                 base = filename;
3628                 subdir_len = 0;
3629         }
3630         basename = xmalloc(strlen(base) +1, "basename");
3631         strcpy(basename, base);
3632         file->basename = basename;
3633
3634         if (getcwd(cwd, sizeof(cwd)) == 0) {
3635                 die("cwd buffer to small");
3636         }
3637         
3638         if (subdir[0] == '/') {
3639                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3640                 memcpy(file->dirname, subdir, subdir_len);
3641                 file->dirname[subdir_len] = '\0';
3642         }
3643         else {
3644                 char *dir;
3645                 int dirlen;
3646                 char **path;
3647                 /* Find the appropriate directory... */
3648                 dir = 0;
3649                 if (!state->file && exists(cwd, filename)) {
3650                         dir = cwd;
3651                 }
3652                 if (local && state->file && exists(state->file->dirname, filename)) {
3653                         dir = state->file->dirname;
3654                 }
3655                 for(path = include_paths; !dir && *path; path++) {
3656                         if (exists(*path, filename)) {
3657                                 dir = *path;
3658                         }
3659                 }
3660                 if (!dir) {
3661                         error(state, 0, "Cannot find `%s'\n", filename);
3662                 }
3663                 dirlen = strlen(dir);
3664                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3665                 memcpy(file->dirname, dir, dirlen);
3666                 file->dirname[dirlen] = '/';
3667                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3668                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3669         }
3670         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3671         xchdir(cwd);
3672
3673         file->pos = file->buf;
3674         file->line_start = file->pos;
3675         file->line = 1;
3676
3677         file->report_line = 1;
3678         file->report_name = file->basename;
3679         file->report_dir  = file->dirname;
3680
3681         file->prev = state->file;
3682         state->file = file;
3683         
3684         process_trigraphs(state);
3685         splice_lines(state);
3686 }
3687
3688 /* Type helper functions */
3689
3690 static struct type *new_type(
3691         unsigned int type, struct type *left, struct type *right)
3692 {
3693         struct type *result;
3694         result = xmalloc(sizeof(*result), "type");
3695         result->type = type;
3696         result->left = left;
3697         result->right = right;
3698         result->field_ident = 0;
3699         result->type_ident = 0;
3700         return result;
3701 }
3702
3703 static struct type *clone_type(unsigned int specifiers, struct type *old)
3704 {
3705         struct type *result;
3706         result = xmalloc(sizeof(*result), "type");
3707         memcpy(result, old, sizeof(*result));
3708         result->type &= TYPE_MASK;
3709         result->type |= specifiers;
3710         return result;
3711 }
3712
3713 #define SIZEOF_SHORT 2
3714 #define SIZEOF_INT   4
3715 #define SIZEOF_LONG  (sizeof(long_t))
3716
3717 #define ALIGNOF_SHORT 2
3718 #define ALIGNOF_INT   4
3719 #define ALIGNOF_LONG  (sizeof(long_t))
3720
3721 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3722 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3723 static inline ulong_t mask_uint(ulong_t x)
3724 {
3725         if (SIZEOF_INT < SIZEOF_LONG) {
3726                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3727                 x &= mask;
3728         }
3729         return x;
3730 }
3731 #define MASK_UINT(X)      (mask_uint(X))
3732 #define MASK_ULONG(X)    (X)
3733
3734 static struct type void_type   = { .type  = TYPE_VOID };
3735 static struct type char_type   = { .type  = TYPE_CHAR };
3736 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3737 static struct type short_type  = { .type  = TYPE_SHORT };
3738 static struct type ushort_type = { .type  = TYPE_USHORT };
3739 static struct type int_type    = { .type  = TYPE_INT };
3740 static struct type uint_type   = { .type  = TYPE_UINT };
3741 static struct type long_type   = { .type  = TYPE_LONG };
3742 static struct type ulong_type  = { .type  = TYPE_ULONG };
3743
3744 static struct triple *variable(struct compile_state *state, struct type *type)
3745 {
3746         struct triple *result;
3747         if ((type->type & STOR_MASK) != STOR_PERM) {
3748                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3749                         result = triple(state, OP_ADECL, type, 0, 0);
3750                 } else {
3751                         struct type *field;
3752                         struct triple **vector;
3753                         ulong_t index;
3754                         result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3755                         vector = &result->param[0];
3756
3757                         field = type->left;
3758                         index = 0;
3759                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3760                                 vector[index] = variable(state, field->left);
3761                                 field = field->right;
3762                                 index++;
3763                         }
3764                         vector[index] = variable(state, field);
3765                 }
3766         }
3767         else {
3768                 result = triple(state, OP_SDECL, type, 0, 0);
3769         }
3770         return result;
3771 }
3772
3773 static void stor_of(FILE *fp, struct type *type)
3774 {
3775         switch(type->type & STOR_MASK) {
3776         case STOR_AUTO:
3777                 fprintf(fp, "auto ");
3778                 break;
3779         case STOR_STATIC:
3780                 fprintf(fp, "static ");
3781                 break;
3782         case STOR_EXTERN:
3783                 fprintf(fp, "extern ");
3784                 break;
3785         case STOR_REGISTER:
3786                 fprintf(fp, "register ");
3787                 break;
3788         case STOR_TYPEDEF:
3789                 fprintf(fp, "typedef ");
3790                 break;
3791         case STOR_INLINE:
3792                 fprintf(fp, "inline ");
3793                 break;
3794         }
3795 }
3796 static void qual_of(FILE *fp, struct type *type)
3797 {
3798         if (type->type & QUAL_CONST) {
3799                 fprintf(fp, " const");
3800         }
3801         if (type->type & QUAL_VOLATILE) {
3802                 fprintf(fp, " volatile");
3803         }
3804         if (type->type & QUAL_RESTRICT) {
3805                 fprintf(fp, " restrict");
3806         }
3807 }
3808
3809 static void name_of(FILE *fp, struct type *type)
3810 {
3811         stor_of(fp, type);
3812         switch(type->type & TYPE_MASK) {
3813         case TYPE_VOID:
3814                 fprintf(fp, "void");
3815                 qual_of(fp, type);
3816                 break;
3817         case TYPE_CHAR:
3818                 fprintf(fp, "signed char");
3819                 qual_of(fp, type);
3820                 break;
3821         case TYPE_UCHAR:
3822                 fprintf(fp, "unsigned char");
3823                 qual_of(fp, type);
3824                 break;
3825         case TYPE_SHORT:
3826                 fprintf(fp, "signed short");
3827                 qual_of(fp, type);
3828                 break;
3829         case TYPE_USHORT:
3830                 fprintf(fp, "unsigned short");
3831                 qual_of(fp, type);
3832                 break;
3833         case TYPE_INT:
3834                 fprintf(fp, "signed int");
3835                 qual_of(fp, type);
3836                 break;
3837         case TYPE_UINT:
3838                 fprintf(fp, "unsigned int");
3839                 qual_of(fp, type);
3840                 break;
3841         case TYPE_LONG:
3842                 fprintf(fp, "signed long");
3843                 qual_of(fp, type);
3844                 break;
3845         case TYPE_ULONG:
3846                 fprintf(fp, "unsigned long");
3847                 qual_of(fp, type);
3848                 break;
3849         case TYPE_POINTER:
3850                 name_of(fp, type->left);
3851                 fprintf(fp, " * ");
3852                 qual_of(fp, type);
3853                 break;
3854         case TYPE_PRODUCT:
3855         case TYPE_OVERLAP:
3856                 name_of(fp, type->left);
3857                 fprintf(fp, ", ");
3858                 name_of(fp, type->right);
3859                 break;
3860         case TYPE_ENUM:
3861                 fprintf(fp, "enum %s", type->type_ident->name);
3862                 qual_of(fp, type);
3863                 break;
3864         case TYPE_STRUCT:
3865                 fprintf(fp, "struct %s", type->type_ident->name);
3866                 qual_of(fp, type);
3867                 break;
3868         case TYPE_FUNCTION:
3869         {
3870                 name_of(fp, type->left);
3871                 fprintf(fp, " (*)(");
3872                 name_of(fp, type->right);
3873                 fprintf(fp, ")");
3874                 break;
3875         }
3876         case TYPE_ARRAY:
3877                 name_of(fp, type->left);
3878                 fprintf(fp, " [%ld]", type->elements);
3879                 break;
3880         default:
3881                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3882                 break;
3883         }
3884 }
3885
3886 static size_t align_of(struct compile_state *state, struct type *type)
3887 {
3888         size_t align;
3889         align = 0;
3890         switch(type->type & TYPE_MASK) {
3891         case TYPE_VOID:
3892                 align = 1;
3893                 break;
3894         case TYPE_CHAR:
3895         case TYPE_UCHAR:
3896                 align = 1;
3897                 break;
3898         case TYPE_SHORT:
3899         case TYPE_USHORT:
3900                 align = ALIGNOF_SHORT;
3901                 break;
3902         case TYPE_INT:
3903         case TYPE_UINT:
3904         case TYPE_ENUM:
3905                 align = ALIGNOF_INT;
3906                 break;
3907         case TYPE_LONG:
3908         case TYPE_ULONG:
3909         case TYPE_POINTER:
3910                 align = ALIGNOF_LONG;
3911                 break;
3912         case TYPE_PRODUCT:
3913         case TYPE_OVERLAP:
3914         {
3915                 size_t left_align, right_align;
3916                 left_align  = align_of(state, type->left);
3917                 right_align = align_of(state, type->right);
3918                 align = (left_align >= right_align) ? left_align : right_align;
3919                 break;
3920         }
3921         case TYPE_ARRAY:
3922                 align = align_of(state, type->left);
3923                 break;
3924         case TYPE_STRUCT:
3925                 align = align_of(state, type->left);
3926                 break;
3927         default:
3928                 error(state, 0, "alignof not yet defined for type\n");
3929                 break;
3930         }
3931         return align;
3932 }
3933
3934 static size_t needed_padding(size_t offset, size_t align)
3935 {
3936         size_t padding;
3937         padding = 0;
3938         if (offset % align) {
3939                 padding = align - (offset % align);
3940         }
3941         return padding;
3942 }
3943 static size_t size_of(struct compile_state *state, struct type *type)
3944 {
3945         size_t size;
3946         size = 0;
3947         switch(type->type & TYPE_MASK) {
3948         case TYPE_VOID:
3949                 size = 0;
3950                 break;
3951         case TYPE_CHAR:
3952         case TYPE_UCHAR:
3953                 size = 1;
3954                 break;
3955         case TYPE_SHORT:
3956         case TYPE_USHORT:
3957                 size = SIZEOF_SHORT;
3958                 break;
3959         case TYPE_INT:
3960         case TYPE_UINT:
3961         case TYPE_ENUM:
3962                 size = SIZEOF_INT;
3963                 break;
3964         case TYPE_LONG:
3965         case TYPE_ULONG:
3966         case TYPE_POINTER:
3967                 size = SIZEOF_LONG;
3968                 break;
3969         case TYPE_PRODUCT:
3970         {
3971                 size_t align, pad;
3972                 size = 0;
3973                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3974                         align = align_of(state, type->left);
3975                         pad = needed_padding(size, align);
3976                         size = size + pad + size_of(state, type->left);
3977                         type = type->right;
3978                 }
3979                 align = align_of(state, type);
3980                 pad = needed_padding(size, align);
3981                 size = size + pad + sizeof(type);
3982                 break;
3983         }
3984         case TYPE_OVERLAP:
3985         {
3986                 size_t size_left, size_right;
3987                 size_left = size_of(state, type->left);
3988                 size_right = size_of(state, type->right);
3989                 size = (size_left >= size_right)? size_left : size_right;
3990                 break;
3991         }
3992         case TYPE_ARRAY:
3993                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3994                         internal_error(state, 0, "Invalid array type");
3995                 } else {
3996                         size = size_of(state, type->left) * type->elements;
3997                 }
3998                 break;
3999         case TYPE_STRUCT:
4000                 size = size_of(state, type->left);
4001                 break;
4002         default:
4003                 error(state, 0, "sizeof not yet defined for type\n");
4004                 break;
4005         }
4006         return size;
4007 }
4008
4009 static size_t field_offset(struct compile_state *state, 
4010         struct type *type, struct hash_entry *field)
4011 {
4012         struct type *member;
4013         size_t size, align;
4014         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4015                 internal_error(state, 0, "field_offset only works on structures");
4016         }
4017         size = 0;
4018         member = type->left;
4019         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4020                 align = align_of(state, member->left);
4021                 size += needed_padding(size, align);
4022                 if (member->left->field_ident == field) {
4023                         member = member->left;
4024                         break;
4025                 }
4026                 size += size_of(state, member->left);
4027                 member = member->right;
4028         }
4029         align = align_of(state, member);
4030         size += needed_padding(size, align);
4031         if (member->field_ident != field) {
4032                 error(state, 0, "member %s not present", field->name);
4033         }
4034         return size;
4035 }
4036
4037 static struct type *field_type(struct compile_state *state, 
4038         struct type *type, struct hash_entry *field)
4039 {
4040         struct type *member;
4041         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4042                 internal_error(state, 0, "field_type only works on structures");
4043         }
4044         member = type->left;
4045         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4046                 if (member->left->field_ident == field) {
4047                         member = member->left;
4048                         break;
4049                 }
4050                 member = member->right;
4051         }
4052         if (member->field_ident != field) {
4053                 error(state, 0, "member %s not present", field->name);
4054         }
4055         return member;
4056 }
4057
4058 static struct type *next_field(struct compile_state *state,
4059         struct type *type, struct type *prev_member) 
4060 {
4061         struct type *member;
4062         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4063                 internal_error(state, 0, "next_field only works on structures");
4064         }
4065         member = type->left;
4066         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4067                 if (!prev_member) {
4068                         member = member->left;
4069                         break;
4070                 }
4071                 if (member->left == prev_member) {
4072                         prev_member = 0;
4073                 }
4074                 member = member->right;
4075         }
4076         if (member == prev_member) {
4077                 prev_member = 0;
4078         }
4079         if (prev_member) {
4080                 internal_error(state, 0, "prev_member %s not present", 
4081                         prev_member->field_ident->name);
4082         }
4083         return member;
4084 }
4085
4086 static struct triple *struct_field(struct compile_state *state,
4087         struct triple *decl, struct hash_entry *field)
4088 {
4089         struct triple **vector;
4090         struct type *type;
4091         ulong_t index;
4092         type = decl->type;
4093         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4094                 return decl;
4095         }
4096         if (decl->op != OP_VAL_VEC) {
4097                 internal_error(state, 0, "Invalid struct variable");
4098         }
4099         if (!field) {
4100                 internal_error(state, 0, "Missing structure field");
4101         }
4102         type = type->left;
4103         vector = &RHS(decl, 0);
4104         index = 0;
4105         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4106                 if (type->left->field_ident == field) {
4107                         type = type->left;
4108                         break;
4109                 }
4110                 index += 1;
4111                 type = type->right;
4112         }
4113         if (type->field_ident != field) {
4114                 internal_error(state, 0, "field %s not found?", field->name);
4115         }
4116         return vector[index];
4117 }
4118
4119 static void arrays_complete(struct compile_state *state, struct type *type)
4120 {
4121         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4122                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4123                         error(state, 0, "array size not specified");
4124                 }
4125                 arrays_complete(state, type->left);
4126         }
4127 }
4128
4129 static unsigned int do_integral_promotion(unsigned int type)
4130 {
4131         type &= TYPE_MASK;
4132         if (TYPE_INTEGER(type) && 
4133                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4134                 type = TYPE_INT;
4135         }
4136         return type;
4137 }
4138
4139 static unsigned int do_arithmetic_conversion(
4140         unsigned int left, unsigned int right)
4141 {
4142         left &= TYPE_MASK;
4143         right &= TYPE_MASK;
4144         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4145                 return TYPE_LDOUBLE;
4146         }
4147         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4148                 return TYPE_DOUBLE;
4149         }
4150         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4151                 return TYPE_FLOAT;
4152         }
4153         left = do_integral_promotion(left);
4154         right = do_integral_promotion(right);
4155         /* If both operands have the same size done */
4156         if (left == right) {
4157                 return left;
4158         }
4159         /* If both operands have the same signedness pick the larger */
4160         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4161                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4162         }
4163         /* If the signed type can hold everything use it */
4164         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4165                 return left;
4166         }
4167         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4168                 return right;
4169         }
4170         /* Convert to the unsigned type with the same rank as the signed type */
4171         else if (TYPE_SIGNED(left)) {
4172                 return TYPE_MKUNSIGNED(left);
4173         }
4174         else {
4175                 return TYPE_MKUNSIGNED(right);
4176         }
4177 }
4178
4179 /* see if two types are the same except for qualifiers */
4180 static int equiv_types(struct type *left, struct type *right)
4181 {
4182         unsigned int type;
4183         /* Error if the basic types do not match */
4184         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4185                 return 0;
4186         }
4187         type = left->type & TYPE_MASK;
4188         /* if the basic types match and it is an arithmetic type we are done */
4189         if (TYPE_ARITHMETIC(type)) {
4190                 return 1;
4191         }
4192         /* If it is a pointer type recurse and keep testing */
4193         if (type == TYPE_POINTER) {
4194                 return equiv_types(left->left, right->left);
4195         }
4196         else if (type == TYPE_ARRAY) {
4197                 return (left->elements == right->elements) &&
4198                         equiv_types(left->left, right->left);
4199         }
4200         /* test for struct/union equality */
4201         else if (type == TYPE_STRUCT) {
4202                 return left->type_ident == right->type_ident;
4203         }
4204         /* Test for equivalent functions */
4205         else if (type == TYPE_FUNCTION) {
4206                 return equiv_types(left->left, right->left) &&
4207                         equiv_types(left->right, right->right);
4208         }
4209         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4210         else if (type == TYPE_PRODUCT) {
4211                 return equiv_types(left->left, right->left) &&
4212                         equiv_types(left->right, right->right);
4213         }
4214         /* We should see TYPE_OVERLAP */
4215         else {
4216                 return 0;
4217         }
4218 }
4219
4220 static int equiv_ptrs(struct type *left, struct type *right)
4221 {
4222         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4223                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4224                 return 0;
4225         }
4226         return equiv_types(left->left, right->left);
4227 }
4228
4229 static struct type *compatible_types(struct type *left, struct type *right)
4230 {
4231         struct type *result;
4232         unsigned int type, qual_type;
4233         /* Error if the basic types do not match */
4234         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4235                 return 0;
4236         }
4237         type = left->type & TYPE_MASK;
4238         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4239         result = 0;
4240         /* if the basic types match and it is an arithmetic type we are done */
4241         if (TYPE_ARITHMETIC(type)) {
4242                 result = new_type(qual_type, 0, 0);
4243         }
4244         /* If it is a pointer type recurse and keep testing */
4245         else if (type == TYPE_POINTER) {
4246                 result = compatible_types(left->left, right->left);
4247                 if (result) {
4248                         result = new_type(qual_type, result, 0);
4249                 }
4250         }
4251         /* test for struct/union equality */
4252         else if (type == TYPE_STRUCT) {
4253                 if (left->type_ident == right->type_ident) {
4254                         result = left;
4255                 }
4256         }
4257         /* Test for equivalent functions */
4258         else if (type == TYPE_FUNCTION) {
4259                 struct type *lf, *rf;
4260                 lf = compatible_types(left->left, right->left);
4261                 rf = compatible_types(left->right, right->right);
4262                 if (lf && rf) {
4263                         result = new_type(qual_type, lf, rf);
4264                 }
4265         }
4266         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4267         else if (type == TYPE_PRODUCT) {
4268                 struct type *lf, *rf;
4269                 lf = compatible_types(left->left, right->left);
4270                 rf = compatible_types(left->right, right->right);
4271                 if (lf && rf) {
4272                         result = new_type(qual_type, lf, rf);
4273                 }
4274         }
4275         else {
4276                 /* Nothing else is compatible */
4277         }
4278         return result;
4279 }
4280
4281 static struct type *compatible_ptrs(struct type *left, struct type *right)
4282 {
4283         struct type *result;
4284         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4285                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4286                 return 0;
4287         }
4288         result = compatible_types(left->left, right->left);
4289         if (result) {
4290                 unsigned int qual_type;
4291                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4292                 result = new_type(qual_type, result, 0);
4293         }
4294         return result;
4295         
4296 }
4297 static struct triple *integral_promotion(
4298         struct compile_state *state, struct triple *def)
4299 {
4300         struct type *type;
4301         type = def->type;
4302         /* As all operations are carried out in registers
4303          * the values are converted on load I just convert
4304          * logical type of the operand.
4305          */
4306         if (TYPE_INTEGER(type->type)) {
4307                 unsigned int int_type;
4308                 int_type = type->type & ~TYPE_MASK;
4309                 int_type |= do_integral_promotion(type->type);
4310                 if (int_type != type->type) {
4311                         def->type = new_type(int_type, 0, 0);
4312                 }
4313         }
4314         return def;
4315 }
4316
4317
4318 static void arithmetic(struct compile_state *state, struct triple *def)
4319 {
4320         if (!TYPE_ARITHMETIC(def->type->type)) {
4321                 error(state, 0, "arithmetic type expexted");
4322         }
4323 }
4324
4325 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4326 {
4327         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4328                 error(state, def, "pointer or arithmetic type expected");
4329         }
4330 }
4331
4332 static int is_integral(struct triple *ins)
4333 {
4334         return TYPE_INTEGER(ins->type->type);
4335 }
4336
4337 static void integral(struct compile_state *state, struct triple *def)
4338 {
4339         if (!is_integral(def)) {
4340                 error(state, 0, "integral type expected");
4341         }
4342 }
4343
4344
4345 static void bool(struct compile_state *state, struct triple *def)
4346 {
4347         if (!TYPE_ARITHMETIC(def->type->type) &&
4348                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4349                 error(state, 0, "arithmetic or pointer type expected");
4350         }
4351 }
4352
4353 static int is_signed(struct type *type)
4354 {
4355         return !!TYPE_SIGNED(type->type);
4356 }
4357
4358 /* Is this value located in a register otherwise it must be in memory */
4359 static int is_in_reg(struct compile_state *state, struct triple *def)
4360 {
4361         int in_reg;
4362         if (def->op == OP_ADECL) {
4363                 in_reg = 1;
4364         }
4365         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4366                 in_reg = 0;
4367         }
4368         else if (def->op == OP_VAL_VEC) {
4369                 in_reg = is_in_reg(state, RHS(def, 0));
4370         }
4371         else if (def->op == OP_DOT) {
4372                 in_reg = is_in_reg(state, RHS(def, 0));
4373         }
4374         else {
4375                 internal_error(state, 0, "unknown expr storage location");
4376                 in_reg = -1;
4377         }
4378         return in_reg;
4379 }
4380
4381 /* Is this a stable variable location otherwise it must be a temporary */
4382 static int is_stable(struct compile_state *state, struct triple *def)
4383 {
4384         int ret;
4385         ret = 0;
4386         if (!def) {
4387                 return 0;
4388         }
4389         if ((def->op == OP_ADECL) || 
4390                 (def->op == OP_SDECL) || 
4391                 (def->op == OP_DEREF) ||
4392                 (def->op == OP_BLOBCONST)) {
4393                 ret = 1;
4394         }
4395         else if (def->op == OP_DOT) {
4396                 ret = is_stable(state, RHS(def, 0));
4397         }
4398         else if (def->op == OP_VAL_VEC) {
4399                 struct triple **vector;
4400                 ulong_t i;
4401                 ret = 1;
4402                 vector = &RHS(def, 0);
4403                 for(i = 0; i < def->type->elements; i++) {
4404                         if (!is_stable(state, vector[i])) {
4405                                 ret = 0;
4406                                 break;
4407                         }
4408                 }
4409         }
4410         return ret;
4411 }
4412
4413 static int is_lvalue(struct compile_state *state, struct triple *def)
4414 {
4415         int ret;
4416         ret = 1;
4417         if (!def) {
4418                 return 0;
4419         }
4420         if (!is_stable(state, def)) {
4421                 return 0;
4422         }
4423         if (def->op == OP_DOT) {
4424                 ret = is_lvalue(state, RHS(def, 0));
4425         }
4426         return ret;
4427 }
4428
4429 static void clvalue(struct compile_state *state, struct triple *def)
4430 {
4431         if (!def) {
4432                 internal_error(state, def, "nothing where lvalue expected?");
4433         }
4434         if (!is_lvalue(state, def)) { 
4435                 error(state, def, "lvalue expected");
4436         }
4437 }
4438 static void lvalue(struct compile_state *state, struct triple *def)
4439 {
4440         clvalue(state, def);
4441         if (def->type->type & QUAL_CONST) {
4442                 error(state, def, "modifable lvalue expected");
4443         }
4444 }
4445
4446 static int is_pointer(struct triple *def)
4447 {
4448         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4449 }
4450
4451 static void pointer(struct compile_state *state, struct triple *def)
4452 {
4453         if (!is_pointer(def)) {
4454                 error(state, def, "pointer expected");
4455         }
4456 }
4457
4458 static struct triple *int_const(
4459         struct compile_state *state, struct type *type, ulong_t value)
4460 {
4461         struct triple *result;
4462         switch(type->type & TYPE_MASK) {
4463         case TYPE_CHAR:
4464         case TYPE_INT:   case TYPE_UINT:
4465         case TYPE_LONG:  case TYPE_ULONG:
4466                 break;
4467         default:
4468                 internal_error(state, 0, "constant for unkown type");
4469         }
4470         result = triple(state, OP_INTCONST, type, 0, 0);
4471         result->u.cval = value;
4472         return result;
4473 }
4474
4475
4476 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4477         struct triple *expr, struct type *type, ulong_t offset)
4478 {
4479         struct triple *result;
4480         clvalue(state, expr);
4481
4482         type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
4483
4484         result = 0;
4485         if (expr->op == OP_ADECL) {
4486                 error(state, expr, "address of auto variables not supported");
4487         }
4488         else if (expr->op == OP_SDECL) {
4489                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4490                 MISC(result, 0) = expr;
4491                 result->u.cval = offset;
4492         }
4493         else if (expr->op == OP_DEREF) {
4494                 result = triple(state, OP_ADD, type,
4495                         RHS(expr, 0),
4496                         int_const(state, &ulong_type, offset));
4497         }
4498         return result;
4499 }
4500
4501 static struct triple *mk_addr_expr(
4502         struct compile_state *state, struct triple *expr, ulong_t offset)
4503 {
4504         return do_mk_addr_expr(state, expr, expr->type, offset);
4505 }
4506
4507 static struct triple *mk_deref_expr(
4508         struct compile_state *state, struct triple *expr)
4509 {
4510         struct type *base_type;
4511         pointer(state, expr);
4512         base_type = expr->type->left;
4513         return triple(state, OP_DEREF, base_type, expr, 0);
4514 }
4515
4516 static struct triple *array_to_pointer(struct compile_state *state, struct triple *def)
4517 {
4518         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4519                 struct type *type;
4520                 struct triple *addrconst;
4521                 type = new_type(
4522                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4523                         def->type->left, 0);
4524                 addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
4525                 MISC(addrconst, 0) = def;
4526                 def = addrconst;
4527         }
4528         return def;
4529 }
4530
4531 static struct triple *deref_field(
4532         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4533 {
4534         struct triple *result;
4535         struct type *type, *member;
4536         if (!field) {
4537                 internal_error(state, 0, "No field passed to deref_field");
4538         }
4539         result = 0;
4540         type = expr->type;
4541         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4542                 error(state, 0, "request for member %s in something not a struct or union",
4543                         field->name);
4544         }
4545         member = field_type(state, type, field);
4546         if ((type->type & STOR_MASK) == STOR_PERM) {
4547                 /* Do the pointer arithmetic to get a deref the field */
4548                 ulong_t offset;
4549                 offset = field_offset(state, type, field);
4550                 result = do_mk_addr_expr(state, expr, member, offset);
4551                 result = mk_deref_expr(state, result);
4552         }
4553         else {
4554                 /* Find the variable for the field I want. */
4555                 result = triple(state, OP_DOT, member, expr, 0);
4556                 result->u.field = field;
4557         }
4558         return result;
4559 }
4560
4561 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4562 {
4563         int op;
4564         if  (!def) {
4565                 return 0;
4566         }
4567         if (!is_stable(state, def)) {
4568                 return def;
4569         }
4570         /* Tranform an array to a pointer to the first element */
4571         
4572 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4573         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4574                 return array_to_pointer(state, def);
4575         }
4576         if (is_in_reg(state, def)) {
4577                 op = OP_READ;
4578         } else {
4579                 op = OP_LOAD;
4580         }
4581         return triple(state, op, def->type, def, 0);
4582 }
4583
4584 static void write_compatible(struct compile_state *state,
4585         struct type *dest, struct type *rval)
4586 {
4587         int compatible = 0;
4588         /* Both operands have arithmetic type */
4589         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4590                 compatible = 1;
4591         }
4592         /* One operand is a pointer and the other is a pointer to void */
4593         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4594                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4595                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4596                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4597                 compatible = 1;
4598         }
4599         /* If both types are the same without qualifiers we are good */
4600         else if (equiv_ptrs(dest, rval)) {
4601                 compatible = 1;
4602         }
4603         /* test for struct/union equality  */
4604         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4605                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4606                 (dest->type_ident == rval->type_ident)) {
4607                 compatible = 1;
4608         }
4609         if (!compatible) {
4610                 error(state, 0, "Incompatible types in assignment");
4611         }
4612 }
4613
4614 static struct triple *write_expr(
4615         struct compile_state *state, struct triple *dest, struct triple *rval)
4616 {
4617         struct triple *def;
4618         int op;
4619
4620         def = 0;
4621         if (!rval) {
4622                 internal_error(state, 0, "missing rval");
4623         }
4624
4625         if (rval->op == OP_LIST) {
4626                 internal_error(state, 0, "expression of type OP_LIST?");
4627         }
4628         if (!is_lvalue(state, dest)) {
4629                 internal_error(state, 0, "writing to a non lvalue?");
4630         }
4631         if (dest->type->type & QUAL_CONST) {
4632                 internal_error(state, 0, "modifable lvalue expexted");
4633         }
4634
4635         write_compatible(state, dest->type, rval->type);
4636
4637         /* Now figure out which assignment operator to use */
4638         op = -1;
4639         if (is_in_reg(state, dest)) {
4640                 op = OP_WRITE;
4641         } else {
4642                 op = OP_STORE;
4643         }
4644         def = triple(state, op, dest->type, dest, rval);
4645         return def;
4646 }
4647
4648 static struct triple *init_expr(
4649         struct compile_state *state, struct triple *dest, struct triple *rval)
4650 {
4651         struct triple *def;
4652
4653         def = 0;
4654         if (!rval) {
4655                 internal_error(state, 0, "missing rval");
4656         }
4657         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4658                 rval = read_expr(state, rval);
4659                 def = write_expr(state, dest, rval);
4660         }
4661         else {
4662                 /* Fill in the array size if necessary */
4663                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4664                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4665                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4666                                 dest->type->elements = rval->type->elements;
4667                         }
4668                 }
4669                 if (!equiv_types(dest->type, rval->type)) {
4670                         error(state, 0, "Incompatible types in inializer");
4671                 }
4672                 MISC(dest, 0) = rval;
4673                 insert_triple(state, dest, rval);
4674                 rval->id |= TRIPLE_FLAG_FLATTENED;
4675                 use_triple(MISC(dest, 0), dest);
4676         }
4677         return def;
4678 }
4679
4680 struct type *arithmetic_result(
4681         struct compile_state *state, struct triple *left, struct triple *right)
4682 {
4683         struct type *type;
4684         /* Sanity checks to ensure I am working with arithmetic types */
4685         arithmetic(state, left);
4686         arithmetic(state, right);
4687         type = new_type(
4688                 do_arithmetic_conversion(
4689                         left->type->type, 
4690                         right->type->type), 0, 0);
4691         return type;
4692 }
4693
4694 struct type *ptr_arithmetic_result(
4695         struct compile_state *state, struct triple *left, struct triple *right)
4696 {
4697         struct type *type;
4698         /* Sanity checks to ensure I am working with the proper types */
4699         ptr_arithmetic(state, left);
4700         arithmetic(state, right);
4701         if (TYPE_ARITHMETIC(left->type->type) && 
4702                 TYPE_ARITHMETIC(right->type->type)) {
4703                 type = arithmetic_result(state, left, right);
4704         }
4705         else if (TYPE_PTR(left->type->type)) {
4706                 type = left->type;
4707         }
4708         else {
4709                 internal_error(state, 0, "huh?");
4710                 type = 0;
4711         }
4712         return type;
4713 }
4714
4715
4716 /* boolean helper function */
4717
4718 static struct triple *ltrue_expr(struct compile_state *state, 
4719         struct triple *expr)
4720 {
4721         switch(expr->op) {
4722         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4723         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4724         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4725                 /* If the expression is already boolean do nothing */
4726                 break;
4727         default:
4728                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4729                 break;
4730         }
4731         return expr;
4732 }
4733
4734 static struct triple *lfalse_expr(struct compile_state *state, 
4735         struct triple *expr)
4736 {
4737         return triple(state, OP_LFALSE, &int_type, expr, 0);
4738 }
4739
4740 static struct triple *cond_expr(
4741         struct compile_state *state, 
4742         struct triple *test, struct triple *left, struct triple *right)
4743 {
4744         struct triple *def;
4745         struct type *result_type;
4746         unsigned int left_type, right_type;
4747         bool(state, test);
4748         left_type = left->type->type;
4749         right_type = right->type->type;
4750         result_type = 0;
4751         /* Both operands have arithmetic type */
4752         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4753                 result_type = arithmetic_result(state, left, right);
4754         }
4755         /* Both operands have void type */
4756         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4757                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4758                 result_type = &void_type;
4759         }
4760         /* pointers to the same type... */
4761         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4762                 ;
4763         }
4764         /* Both operands are pointers and left is a pointer to void */
4765         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4766                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4767                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4768                 result_type = right->type;
4769         }
4770         /* Both operands are pointers and right is a pointer to void */
4771         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4772                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4773                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4774                 result_type = left->type;
4775         }
4776         if (!result_type) {
4777                 error(state, 0, "Incompatible types in conditional expression");
4778         }
4779         /* Cleanup and invert the test */
4780         test = lfalse_expr(state, read_expr(state, test));
4781         def = new_triple(state, OP_COND, result_type, 0, 3);
4782         def->param[0] = test;
4783         def->param[1] = left;
4784         def->param[2] = right;
4785         return def;
4786 }
4787
4788
4789 static int expr_depth(struct compile_state *state, struct triple *ins)
4790 {
4791         int count;
4792         count = 0;
4793         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4794                 count = 0;
4795         }
4796         else if (ins->op == OP_DEREF) {
4797                 count = expr_depth(state, RHS(ins, 0)) - 1;
4798         }
4799         else if (ins->op == OP_VAL) {
4800                 count = expr_depth(state, RHS(ins, 0)) - 1;
4801         }
4802         else if (ins->op == OP_COMMA) {
4803                 int ldepth, rdepth;
4804                 ldepth = expr_depth(state, RHS(ins, 0));
4805                 rdepth = expr_depth(state, RHS(ins, 1));
4806                 count = (ldepth >= rdepth)? ldepth : rdepth;
4807         }
4808         else if (ins->op == OP_CALL) {
4809                 /* Don't figure the depth of a call just guess it is huge */
4810                 count = 1000;
4811         }
4812         else {
4813                 struct triple **expr;
4814                 expr = triple_rhs(state, ins, 0);
4815                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4816                         if (*expr) {
4817                                 int depth;
4818                                 depth = expr_depth(state, *expr);
4819                                 if (depth > count) {
4820                                         count = depth;
4821                                 }
4822                         }
4823                 }
4824         }
4825         return count + 1;
4826 }
4827
4828 static struct triple *flatten(
4829         struct compile_state *state, struct triple *first, struct triple *ptr);
4830
4831 static struct triple *flatten_generic(
4832         struct compile_state *state, struct triple *first, struct triple *ptr)
4833 {
4834         struct rhs_vector {
4835                 int depth;
4836                 struct triple **ins;
4837         } vector[MAX_RHS];
4838         int i, rhs, lhs;
4839         /* Only operations with just a rhs should come here */
4840         rhs = TRIPLE_RHS(ptr->sizes);
4841         lhs = TRIPLE_LHS(ptr->sizes);
4842         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4843                 internal_error(state, ptr, "unexpected args for: %d %s",
4844                         ptr->op, tops(ptr->op));
4845         }
4846         /* Find the depth of the rhs elements */
4847         for(i = 0; i < rhs; i++) {
4848                 vector[i].ins = &RHS(ptr, i);
4849                 vector[i].depth = expr_depth(state, *vector[i].ins);
4850         }
4851         /* Selection sort the rhs */
4852         for(i = 0; i < rhs; i++) {
4853                 int j, max = i;
4854                 for(j = i + 1; j < rhs; j++ ) {
4855                         if (vector[j].depth > vector[max].depth) {
4856                                 max = j;
4857                         }
4858                 }
4859                 if (max != i) {
4860                         struct rhs_vector tmp;
4861                         tmp = vector[i];
4862                         vector[i] = vector[max];
4863                         vector[max] = tmp;
4864                 }
4865         }
4866         /* Now flatten the rhs elements */
4867         for(i = 0; i < rhs; i++) {
4868                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4869                 use_triple(*vector[i].ins, ptr);
4870         }
4871         
4872         /* Now flatten the lhs elements */
4873         for(i = 0; i < lhs; i++) {
4874                 struct triple **ins = &LHS(ptr, i);
4875                 *ins = flatten(state, first, *ins);
4876                 use_triple(*ins, ptr);
4877         }
4878         return ptr;
4879 }
4880
4881 static struct triple *flatten_land(
4882         struct compile_state *state, struct triple *first, struct triple *ptr)
4883 {
4884         struct triple *left, *right;
4885         struct triple *val, *test, *jmp, *label1, *end;
4886
4887         /* Find the triples */
4888         left = RHS(ptr, 0);
4889         right = RHS(ptr, 1);
4890
4891         /* Generate the needed triples */
4892         end = label(state);
4893
4894         /* Thread the triples together */
4895         val          = flatten(state, first, variable(state, ptr->type));
4896         left         = flatten(state, first, write_expr(state, val, left));
4897         test         = flatten(state, first, 
4898                 lfalse_expr(state, read_expr(state, val)));
4899         jmp          = flatten(state, first, branch(state, end, test));
4900         label1       = flatten(state, first, label(state));
4901         right        = flatten(state, first, write_expr(state, val, right));
4902         TARG(jmp, 0) = flatten(state, first, end); 
4903         
4904         /* Now give the caller something to chew on */
4905         return read_expr(state, val);
4906 }
4907
4908 static struct triple *flatten_lor(
4909         struct compile_state *state, struct triple *first, struct triple *ptr)
4910 {
4911         struct triple *left, *right;
4912         struct triple *val, *jmp, *label1, *end;
4913
4914         /* Find the triples */
4915         left = RHS(ptr, 0);
4916         right = RHS(ptr, 1);
4917
4918         /* Generate the needed triples */
4919         end = label(state);
4920
4921         /* Thread the triples together */
4922         val          = flatten(state, first, variable(state, ptr->type));
4923         left         = flatten(state, first, write_expr(state, val, left));
4924         jmp          = flatten(state, first, branch(state, end, left));
4925         label1       = flatten(state, first, label(state));
4926         right        = flatten(state, first, write_expr(state, val, right));
4927         TARG(jmp, 0) = flatten(state, first, end);
4928        
4929         
4930         /* Now give the caller something to chew on */
4931         return read_expr(state, val);
4932 }
4933
4934 static struct triple *flatten_cond(
4935         struct compile_state *state, struct triple *first, struct triple *ptr)
4936 {
4937         struct triple *test, *left, *right;
4938         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4939
4940         /* Find the triples */
4941         test = RHS(ptr, 0);
4942         left = RHS(ptr, 1);
4943         right = RHS(ptr, 2);
4944
4945         /* Generate the needed triples */
4946         end = label(state);
4947         middle = label(state);
4948
4949         /* Thread the triples together */
4950         val           = flatten(state, first, variable(state, ptr->type));
4951         test          = flatten(state, first, test);
4952         jmp1          = flatten(state, first, branch(state, middle, test));
4953         label1        = flatten(state, first, label(state));
4954         left          = flatten(state, first, left);
4955         mv1           = flatten(state, first, write_expr(state, val, left));
4956         jmp2          = flatten(state, first, branch(state, end, 0));
4957         TARG(jmp1, 0) = flatten(state, first, middle);
4958         right         = flatten(state, first, right);
4959         mv2           = flatten(state, first, write_expr(state, val, right));
4960         TARG(jmp2, 0) = flatten(state, first, end);
4961         
4962         /* Now give the caller something to chew on */
4963         return read_expr(state, val);
4964 }
4965
4966 struct triple *copy_func(struct compile_state *state, struct triple *ofunc, 
4967         struct occurance *base_occurance)
4968 {
4969         struct triple *nfunc;
4970         struct triple *nfirst, *ofirst;
4971         struct triple *new, *old;
4972
4973 #if 0
4974         fprintf(stdout, "\n");
4975         loc(stdout, state, 0);
4976         fprintf(stdout, "\n__________ copy_func _________\n");
4977         print_triple(state, ofunc);
4978         fprintf(stdout, "__________ copy_func _________ done\n\n");
4979 #endif
4980
4981         /* Make a new copy of the old function */
4982         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4983         nfirst = 0;
4984         ofirst = old = RHS(ofunc, 0);
4985         do {
4986                 struct triple *new;
4987                 struct occurance *occurance;
4988                 int old_lhs, old_rhs;
4989                 old_lhs = TRIPLE_LHS(old->sizes);
4990                 old_rhs = TRIPLE_RHS(old->sizes);
4991                 occurance = inline_occurance(state, base_occurance, old->occurance);
4992                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4993                         occurance);
4994                 if (!triple_stores_block(state, new)) {
4995                         memcpy(&new->u, &old->u, sizeof(new->u));
4996                 }
4997                 if (!nfirst) {
4998                         RHS(nfunc, 0) = nfirst = new;
4999                 }
5000                 else {
5001                         insert_triple(state, nfirst, new);
5002                 }
5003                 new->id |= TRIPLE_FLAG_FLATTENED;
5004                 
5005                 /* During the copy remember new as user of old */
5006                 use_triple(old, new);
5007
5008                 /* Populate the return type if present */
5009                 if (old == MISC(ofunc, 0)) {
5010                         MISC(nfunc, 0) = new;
5011                 }
5012                 old = old->next;
5013         } while(old != ofirst);
5014
5015         /* Make a second pass to fix up any unresolved references */
5016         old = ofirst;
5017         new = nfirst;
5018         do {
5019                 struct triple **oexpr, **nexpr;
5020                 int count, i;
5021                 /* Lookup where the copy is, to join pointers */
5022                 count = TRIPLE_SIZE(old->sizes);
5023                 for(i = 0; i < count; i++) {
5024                         oexpr = &old->param[i];
5025                         nexpr = &new->param[i];
5026                         if (!*nexpr && *oexpr && (*oexpr)->use) {
5027                                 *nexpr = (*oexpr)->use->member;
5028                                 if (*nexpr == old) {
5029                                         internal_error(state, 0, "new == old?");
5030                                 }
5031                                 use_triple(*nexpr, new);
5032                         }
5033                         if (!*nexpr && *oexpr) {
5034                                 internal_error(state, 0, "Could not copy %d\n", i);
5035                         }
5036                 }
5037                 old = old->next;
5038                 new = new->next;
5039         } while((old != ofirst) && (new != nfirst));
5040         
5041         /* Make a third pass to cleanup the extra useses */
5042         old = ofirst;
5043         new = nfirst;
5044         do {
5045                 unuse_triple(old, new);
5046                 old = old->next;
5047                 new = new->next;
5048         } while ((old != ofirst) && (new != nfirst));
5049         return nfunc;
5050 }
5051
5052 static struct triple *flatten_call(
5053         struct compile_state *state, struct triple *first, struct triple *ptr)
5054 {
5055         /* Inline the function call */
5056         struct type *ptype;
5057         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5058         struct triple *end, *nend;
5059         int pvals, i;
5060
5061         /* Find the triples */
5062         ofunc = MISC(ptr, 0);
5063         if (ofunc->op != OP_LIST) {
5064                 internal_error(state, 0, "improper function");
5065         }
5066         nfunc = copy_func(state, ofunc, ptr->occurance);
5067         nfirst = RHS(nfunc, 0)->next;
5068         /* Prepend the parameter reading into the new function list */
5069         ptype = nfunc->type->right;
5070         param = RHS(nfunc, 0)->next;
5071         pvals = TRIPLE_RHS(ptr->sizes);
5072         for(i = 0; i < pvals; i++) {
5073                 struct type *atype;
5074                 struct triple *arg;
5075                 atype = ptype;
5076                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5077                         atype = ptype->left;
5078                 }
5079                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5080                         param = param->next;
5081                 }
5082                 arg = RHS(ptr, i);
5083                 flatten(state, nfirst, write_expr(state, param, arg));
5084                 ptype = ptype->right;
5085                 param = param->next;
5086         }
5087         result = 0;
5088         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5089                 result = read_expr(state, MISC(nfunc,0));
5090         }
5091 #if 0
5092         fprintf(stdout, "\n");
5093         loc(stdout, state, 0);
5094         fprintf(stdout, "\n__________ flatten_call _________\n");
5095         print_triple(state, nfunc);
5096         fprintf(stdout, "__________ flatten_call _________ done\n\n");
5097 #endif
5098
5099         /* Get rid of the extra triples */
5100         nfirst = RHS(nfunc, 0)->next;
5101         free_triple(state, RHS(nfunc, 0));
5102         RHS(nfunc, 0) = 0;
5103         free_triple(state, nfunc);
5104
5105         /* Append the new function list onto the return list */
5106         end = first->prev;
5107         nend = nfirst->prev;
5108         end->next    = nfirst;
5109         nfirst->prev = end;
5110         nend->next   = first;
5111         first->prev  = nend;
5112
5113         return result;
5114 }
5115
5116 static struct triple *flatten(
5117         struct compile_state *state, struct triple *first, struct triple *ptr)
5118 {
5119         struct triple *orig_ptr;
5120         if (!ptr)
5121                 return 0;
5122         do {
5123                 orig_ptr = ptr;
5124                 /* Only flatten triples once */
5125                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5126                         return ptr;
5127                 }
5128                 switch(ptr->op) {
5129                 case OP_WRITE:
5130                 case OP_STORE:
5131                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5132                         LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
5133                         use_triple(LHS(ptr, 0), ptr);
5134                         use_triple(RHS(ptr, 0), ptr);
5135                         break;
5136                 case OP_COMMA:
5137                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5138                         ptr = RHS(ptr, 1);
5139                         break;
5140                 case OP_VAL:
5141                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5142                         return MISC(ptr, 0);
5143                         break;
5144                 case OP_LAND:
5145                         ptr = flatten_land(state, first, ptr);
5146                         break;
5147                 case OP_LOR:
5148                         ptr = flatten_lor(state, first, ptr);
5149                         break;
5150                 case OP_COND:
5151                         ptr = flatten_cond(state, first, ptr);
5152                         break;
5153                 case OP_CALL:
5154                         ptr = flatten_call(state, first, ptr);
5155                         break;
5156                 case OP_READ:
5157                 case OP_LOAD:
5158                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5159                         use_triple(RHS(ptr, 0), ptr);
5160                         break;
5161                 case OP_BRANCH:
5162                         use_triple(TARG(ptr, 0), ptr);
5163                         if (TRIPLE_RHS(ptr->sizes)) {
5164                                 use_triple(RHS(ptr, 0), ptr);
5165                                 if (ptr->next != ptr) {
5166                                         use_triple(ptr->next, ptr);
5167                                 }
5168                         }
5169                         break;
5170                 case OP_BLOBCONST:
5171                         insert_triple(state, first, ptr);
5172                         ptr->id |= TRIPLE_FLAG_FLATTENED;
5173                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5174                         use_triple(MISC(ptr, 0), ptr);
5175                         break;
5176                 case OP_DEREF:
5177                         /* Since OP_DEREF is just a marker delete it when I flatten it */
5178                         ptr = RHS(ptr, 0);
5179                         RHS(orig_ptr, 0) = 0;
5180                         free_triple(state, orig_ptr);
5181                         break;
5182                 case OP_DOT:
5183                 {
5184                         struct triple *base;
5185                         base = RHS(ptr, 0);
5186                         if (base->op == OP_DEREF) {
5187                                 struct triple *left;
5188                                 ulong_t offset;
5189                                 offset = field_offset(state, base->type, ptr->u.field);
5190                                 left = RHS(base, 0);
5191                                 ptr = triple(state, OP_ADD, left->type, 
5192                                         read_expr(state, left),
5193                                         int_const(state, &ulong_type, offset));
5194                                 free_triple(state, base);
5195                         }
5196                         else if (base->op == OP_VAL_VEC) {
5197                                 base = flatten(state, first, base);
5198                                 ptr = struct_field(state, base, ptr->u.field);
5199                         }
5200                         break;
5201                 }
5202                 case OP_PIECE:
5203                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5204                         use_triple(MISC(ptr, 0), ptr);
5205                         use_triple(ptr, MISC(ptr, 0));
5206                         break;
5207                 case OP_ADDRCONST:
5208                 case OP_SDECL:
5209                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5210                         use_triple(MISC(ptr, 0), ptr);
5211                         break;
5212                 case OP_ADECL:
5213                         break;
5214                 default:
5215                         /* Flatten the easy cases we don't override */
5216                         ptr = flatten_generic(state, first, ptr);
5217                         break;
5218                 }
5219         } while(ptr && (ptr != orig_ptr));
5220         if (ptr) {
5221                 insert_triple(state, first, ptr);
5222                 ptr->id |= TRIPLE_FLAG_FLATTENED;
5223         }
5224         return ptr;
5225 }
5226
5227 static void release_expr(struct compile_state *state, struct triple *expr)
5228 {
5229         struct triple *head;
5230         head = label(state);
5231         flatten(state, head, expr);
5232         while(head->next != head) {
5233                 release_triple(state, head->next);
5234         }
5235         free_triple(state, head);
5236 }
5237
5238 static int replace_rhs_use(struct compile_state *state,
5239         struct triple *orig, struct triple *new, struct triple *use)
5240 {
5241         struct triple **expr;
5242         int found;
5243         found = 0;
5244         expr = triple_rhs(state, use, 0);
5245         for(;expr; expr = triple_rhs(state, use, expr)) {
5246                 if (*expr == orig) {
5247                         *expr = new;
5248                         found = 1;
5249                 }
5250         }
5251         if (found) {
5252                 unuse_triple(orig, use);
5253                 use_triple(new, use);
5254         }
5255         return found;
5256 }
5257
5258 static int replace_lhs_use(struct compile_state *state,
5259         struct triple *orig, struct triple *new, struct triple *use)
5260 {
5261         struct triple **expr;
5262         int found;
5263         found = 0;
5264         expr = triple_lhs(state, use, 0);
5265         for(;expr; expr = triple_lhs(state, use, expr)) {
5266                 if (*expr == orig) {
5267                         *expr = new;
5268                         found = 1;
5269                 }
5270         }
5271         if (found) {
5272                 unuse_triple(orig, use);
5273                 use_triple(new, use);
5274         }
5275         return found;
5276 }
5277
5278 static void propogate_use(struct compile_state *state,
5279         struct triple *orig, struct triple *new)
5280 {
5281         struct triple_set *user, *next;
5282         for(user = orig->use; user; user = next) {
5283                 struct triple *use;
5284                 int found;
5285                 next = user->next;
5286                 use = user->member;
5287                 found = 0;
5288                 found |= replace_rhs_use(state, orig, new, use);
5289                 found |= replace_lhs_use(state, orig, new, use);
5290                 if (!found) {
5291                         internal_error(state, use, "use without use");
5292                 }
5293         }
5294         if (orig->use) {
5295                 internal_error(state, orig, "used after propogate_use");
5296         }
5297 }
5298
5299 /*
5300  * Code generators
5301  * ===========================
5302  */
5303
5304 static struct triple *mk_add_expr(
5305         struct compile_state *state, struct triple *left, struct triple *right)
5306 {
5307         struct type *result_type;
5308         /* Put pointer operands on the left */
5309         if (is_pointer(right)) {
5310                 struct triple *tmp;
5311                 tmp = left;
5312                 left = right;
5313                 right = tmp;
5314         }
5315         left  = read_expr(state, left);
5316         right = read_expr(state, right);
5317         result_type = ptr_arithmetic_result(state, left, right);
5318         if (is_pointer(left)) {
5319                 right = triple(state, 
5320                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5321                         &ulong_type, 
5322                         right, 
5323                         int_const(state, &ulong_type, 
5324                                 size_of(state, left->type->left)));
5325         }
5326         return triple(state, OP_ADD, result_type, left, right);
5327 }
5328
5329 static struct triple *mk_sub_expr(
5330         struct compile_state *state, struct triple *left, struct triple *right)
5331 {
5332         struct type *result_type;
5333         result_type = ptr_arithmetic_result(state, left, right);
5334         left  = read_expr(state, left);
5335         right = read_expr(state, right);
5336         if (is_pointer(left)) {
5337                 right = triple(state, 
5338                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5339                         &ulong_type, 
5340                         right, 
5341                         int_const(state, &ulong_type, 
5342                                 size_of(state, left->type->left)));
5343         }
5344         return triple(state, OP_SUB, result_type, left, right);
5345 }
5346
5347 static struct triple *mk_pre_inc_expr(
5348         struct compile_state *state, struct triple *def)
5349 {
5350         struct triple *val;
5351         lvalue(state, def);
5352         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5353         return triple(state, OP_VAL, def->type,
5354                 write_expr(state, def, val),
5355                 val);
5356 }
5357
5358 static struct triple *mk_pre_dec_expr(
5359         struct compile_state *state, struct triple *def)
5360 {
5361         struct triple *val;
5362         lvalue(state, def);
5363         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5364         return triple(state, OP_VAL, def->type,
5365                 write_expr(state, def, val),
5366                 val);
5367 }
5368
5369 static struct triple *mk_post_inc_expr(
5370         struct compile_state *state, struct triple *def)
5371 {
5372         struct triple *val;
5373         lvalue(state, def);
5374         val = read_expr(state, def);
5375         return triple(state, OP_VAL, def->type,
5376                 write_expr(state, def,
5377                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
5378                 , val);
5379 }
5380
5381 static struct triple *mk_post_dec_expr(
5382         struct compile_state *state, struct triple *def)
5383 {
5384         struct triple *val;
5385         lvalue(state, def);
5386         val = read_expr(state, def);
5387         return triple(state, OP_VAL, def->type, 
5388                 write_expr(state, def,
5389                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5390                 , val);
5391 }
5392
5393 static struct triple *mk_subscript_expr(
5394         struct compile_state *state, struct triple *left, struct triple *right)
5395 {
5396         left  = read_expr(state, left);
5397         right = read_expr(state, right);
5398         if (!is_pointer(left) && !is_pointer(right)) {
5399                 error(state, left, "subscripted value is not a pointer");
5400         }
5401         return mk_deref_expr(state, mk_add_expr(state, left, right));
5402 }
5403
5404 /*
5405  * Compile time evaluation
5406  * ===========================
5407  */
5408 static int is_const(struct triple *ins)
5409 {
5410         return IS_CONST_OP(ins->op);
5411 }
5412
5413 static int constants_equal(struct compile_state *state, 
5414         struct triple *left, struct triple *right)
5415 {
5416         int equal;
5417         if (!is_const(left) || !is_const(right)) {
5418                 equal = 0;
5419         }
5420         else if (left->op != right->op) {
5421                 equal = 0;
5422         }
5423         else if (!equiv_types(left->type, right->type)) {
5424                 equal = 0;
5425         }
5426         else {
5427                 equal = 0;
5428                 switch(left->op) {
5429                 case OP_INTCONST:
5430                         if (left->u.cval == right->u.cval) {
5431                                 equal = 1;
5432                         }
5433                         break;
5434                 case OP_BLOBCONST:
5435                 {
5436                         size_t lsize, rsize;
5437                         lsize = size_of(state, left->type);
5438                         rsize = size_of(state, right->type);
5439                         if (lsize != rsize) {
5440                                 break;
5441                         }
5442                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5443                                 equal = 1;
5444                         }
5445                         break;
5446                 }
5447                 case OP_ADDRCONST:
5448                         if ((MISC(left, 0) == MISC(right, 0)) &&
5449                                 (left->u.cval == right->u.cval)) {
5450                                 equal = 1;
5451                         }
5452                         break;
5453                 default:
5454                         internal_error(state, left, "uknown constant type");
5455                         break;
5456                 }
5457         }
5458         return equal;
5459 }
5460
5461 static int is_zero(struct triple *ins)
5462 {
5463         return is_const(ins) && (ins->u.cval == 0);
5464 }
5465
5466 static int is_one(struct triple *ins)
5467 {
5468         return is_const(ins) && (ins->u.cval == 1);
5469 }
5470
5471 static long_t bsr(ulong_t value)
5472 {
5473         int i;
5474         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5475                 ulong_t mask;
5476                 mask = 1;
5477                 mask <<= i;
5478                 if (value & mask) {
5479                         return i;
5480                 }
5481         }
5482         return -1;
5483 }
5484
5485 static long_t bsf(ulong_t value)
5486 {
5487         int i;
5488         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5489                 ulong_t mask;
5490                 mask = 1;
5491                 mask <<= 1;
5492                 if (value & mask) {
5493                         return i;
5494                 }
5495         }
5496         return -1;
5497 }
5498
5499 static long_t log2(ulong_t value)
5500 {
5501         return bsr(value);
5502 }
5503
5504 static long_t tlog2(struct triple *ins)
5505 {
5506         return log2(ins->u.cval);
5507 }
5508
5509 static int is_pow2(struct triple *ins)
5510 {
5511         ulong_t value, mask;
5512         long_t log;
5513         if (!is_const(ins)) {
5514                 return 0;
5515         }
5516         value = ins->u.cval;
5517         log = log2(value);
5518         if (log == -1) {
5519                 return 0;
5520         }
5521         mask = 1;
5522         mask <<= log;
5523         return  ((value & mask) == value);
5524 }
5525
5526 static ulong_t read_const(struct compile_state *state,
5527         struct triple *ins, struct triple **expr)
5528 {
5529         struct triple *rhs;
5530         rhs = *expr;
5531         switch(rhs->type->type &TYPE_MASK) {
5532         case TYPE_CHAR:   
5533         case TYPE_SHORT:
5534         case TYPE_INT:
5535         case TYPE_LONG:
5536         case TYPE_UCHAR:   
5537         case TYPE_USHORT:  
5538         case TYPE_UINT:
5539         case TYPE_ULONG:
5540         case TYPE_POINTER:
5541                 break;
5542         default:
5543                 internal_error(state, rhs, "bad type to read_const\n");
5544                 break;
5545         }
5546         return rhs->u.cval;
5547 }
5548
5549 static long_t read_sconst(struct triple *ins, struct triple **expr)
5550 {
5551         struct triple *rhs;
5552         rhs = *expr;
5553         return (long_t)(rhs->u.cval);
5554 }
5555
5556 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5557 {
5558         struct triple **expr;
5559         expr = triple_rhs(state, ins, 0);
5560         for(;expr;expr = triple_rhs(state, ins, expr)) {
5561                 if (*expr) {
5562                         unuse_triple(*expr, ins);
5563                         *expr = 0;
5564                 }
5565         }
5566 }
5567
5568 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5569 {
5570         struct triple **expr;
5571         expr = triple_lhs(state, ins, 0);
5572         for(;expr;expr = triple_lhs(state, ins, expr)) {
5573                 unuse_triple(*expr, ins);
5574                 *expr = 0;
5575         }
5576 }
5577
5578 static void check_lhs(struct compile_state *state, struct triple *ins)
5579 {
5580         struct triple **expr;
5581         expr = triple_lhs(state, ins, 0);
5582         for(;expr;expr = triple_lhs(state, ins, expr)) {
5583                 internal_error(state, ins, "unexpected lhs");
5584         }
5585         
5586 }
5587 static void check_targ(struct compile_state *state, struct triple *ins)
5588 {
5589         struct triple **expr;
5590         expr = triple_targ(state, ins, 0);
5591         for(;expr;expr = triple_targ(state, ins, expr)) {
5592                 internal_error(state, ins, "unexpected targ");
5593         }
5594 }
5595
5596 static void wipe_ins(struct compile_state *state, struct triple *ins)
5597 {
5598         /* Becareful which instructions you replace the wiped
5599          * instruction with, as there are not enough slots
5600          * in all instructions to hold all others.
5601          */
5602         check_targ(state, ins);
5603         unuse_rhs(state, ins);
5604         unuse_lhs(state, ins);
5605 }
5606
5607 static void mkcopy(struct compile_state *state, 
5608         struct triple *ins, struct triple *rhs)
5609 {
5610         wipe_ins(state, ins);
5611         ins->op = OP_COPY;
5612         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5613         RHS(ins, 0) = rhs;
5614         use_triple(RHS(ins, 0), ins);
5615 }
5616
5617 static void mkconst(struct compile_state *state, 
5618         struct triple *ins, ulong_t value)
5619 {
5620         if (!is_integral(ins) && !is_pointer(ins)) {
5621                 internal_error(state, ins, "unknown type to make constant\n");
5622         }
5623         wipe_ins(state, ins);
5624         ins->op = OP_INTCONST;
5625         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5626         ins->u.cval = value;
5627 }
5628
5629 static void mkaddr_const(struct compile_state *state,
5630         struct triple *ins, struct triple *sdecl, ulong_t value)
5631 {
5632         wipe_ins(state, ins);
5633         ins->op = OP_ADDRCONST;
5634         ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5635         MISC(ins, 0) = sdecl;
5636         ins->u.cval = value;
5637         use_triple(sdecl, ins);
5638 }
5639
5640 /* Transform multicomponent variables into simple register variables */
5641 static void flatten_structures(struct compile_state *state)
5642 {
5643         struct triple *ins, *first;
5644         first = RHS(state->main_function, 0);
5645         ins = first;
5646         /* Pass one expand structure values into valvecs.
5647          */
5648         ins = first;
5649         do {
5650                 struct triple *next;
5651                 next = ins->next;
5652                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5653                         if (ins->op == OP_VAL_VEC) {
5654                                 /* Do nothing */
5655                         }
5656                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5657                                 struct triple *def, **vector;
5658                                 struct type *tptr;
5659                                 int op;
5660                                 ulong_t i;
5661
5662                                 op = ins->op;
5663                                 def = RHS(ins, 0);
5664                                 get_occurance(ins->occurance);
5665                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5666                                         ins->occurance);
5667
5668                                 vector = &RHS(next, 0);
5669                                 tptr = next->type->left;
5670                                 for(i = 0; i < next->type->elements; i++) {
5671                                         struct triple *sfield;
5672                                         struct type *mtype;
5673                                         mtype = tptr;
5674                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5675                                                 mtype = mtype->left;
5676                                         }
5677                                         sfield = deref_field(state, def, mtype->field_ident);
5678                                         
5679                                         vector[i] = triple(
5680                                                 state, op, mtype, sfield, 0);
5681                                         put_occurance(vector[i]->occurance);
5682                                         get_occurance(next->occurance);
5683                                         vector[i]->occurance = next->occurance;
5684                                         tptr = tptr->right;
5685                                 }
5686                                 propogate_use(state, ins, next);
5687                                 flatten(state, ins, next);
5688                                 free_triple(state, ins);
5689                         }
5690                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5691                                 struct triple *src, *dst, **vector;
5692                                 struct type *tptr;
5693                                 int op;
5694                                 ulong_t i;
5695
5696                                 op = ins->op;
5697                                 src = RHS(ins, 0);
5698                                 dst = LHS(ins, 0);
5699                                 get_occurance(ins->occurance);
5700                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5701                                         ins->occurance);
5702                                 
5703                                 vector = &RHS(next, 0);
5704                                 tptr = next->type->left;
5705                                 for(i = 0; i < ins->type->elements; i++) {
5706                                         struct triple *dfield, *sfield;
5707                                         struct type *mtype;
5708                                         mtype = tptr;
5709                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5710                                                 mtype = mtype->left;
5711                                         }
5712                                         sfield = deref_field(state, src, mtype->field_ident);
5713                                         dfield = deref_field(state, dst, mtype->field_ident);
5714                                         vector[i] = triple(
5715                                                 state, op, mtype, dfield, sfield);
5716                                         put_occurance(vector[i]->occurance);
5717                                         get_occurance(next->occurance);
5718                                         vector[i]->occurance = next->occurance;
5719                                         tptr = tptr->right;
5720                                 }
5721                                 propogate_use(state, ins, next);
5722                                 flatten(state, ins, next);
5723                                 free_triple(state, ins);
5724                         }
5725                 }
5726                 ins = next;
5727         } while(ins != first);
5728         /* Pass two flatten the valvecs.
5729          */
5730         ins = first;
5731         do {
5732                 struct triple *next;
5733                 next = ins->next;
5734                 if (ins->op == OP_VAL_VEC) {
5735                         release_triple(state, ins);
5736                 } 
5737                 ins = next;
5738         } while(ins != first);
5739         /* Pass three verify the state and set ->id to 0.
5740          */
5741         ins = first;
5742         do {
5743                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5744                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5745                         internal_error(state, ins, "STRUCT_TYPE remains?");
5746                 }
5747                 if (ins->op == OP_DOT) {
5748                         internal_error(state, ins, "OP_DOT remains?");
5749                 }
5750                 if (ins->op == OP_VAL_VEC) {
5751                         internal_error(state, ins, "OP_VAL_VEC remains?");
5752                 }
5753                 ins = ins->next;
5754         } while(ins != first);
5755 }
5756
5757 /* For those operations that cannot be simplified */
5758 static void simplify_noop(struct compile_state *state, struct triple *ins)
5759 {
5760         return;
5761 }
5762
5763 static void simplify_smul(struct compile_state *state, struct triple *ins)
5764 {
5765         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5766                 struct triple *tmp;
5767                 tmp = RHS(ins, 0);
5768                 RHS(ins, 0) = RHS(ins, 1);
5769                 RHS(ins, 1) = tmp;
5770         }
5771         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5772                 long_t left, right;
5773                 left  = read_sconst(ins, &RHS(ins, 0));
5774                 right = read_sconst(ins, &RHS(ins, 1));
5775                 mkconst(state, ins, left * right);
5776         }
5777         else if (is_zero(RHS(ins, 1))) {
5778                 mkconst(state, ins, 0);
5779         }
5780         else if (is_one(RHS(ins, 1))) {
5781                 mkcopy(state, ins, RHS(ins, 0));
5782         }
5783         else if (is_pow2(RHS(ins, 1))) {
5784                 struct triple *val;
5785                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5786                 ins->op = OP_SL;
5787                 insert_triple(state, ins, val);
5788                 unuse_triple(RHS(ins, 1), ins);
5789                 use_triple(val, ins);
5790                 RHS(ins, 1) = val;
5791         }
5792 }
5793
5794 static void simplify_umul(struct compile_state *state, struct triple *ins)
5795 {
5796         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5797                 struct triple *tmp;
5798                 tmp = RHS(ins, 0);
5799                 RHS(ins, 0) = RHS(ins, 1);
5800                 RHS(ins, 1) = tmp;
5801         }
5802         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5803                 ulong_t left, right;
5804                 left  = read_const(state, ins, &RHS(ins, 0));
5805                 right = read_const(state, ins, &RHS(ins, 1));
5806                 mkconst(state, ins, left * right);
5807         }
5808         else if (is_zero(RHS(ins, 1))) {
5809                 mkconst(state, ins, 0);
5810         }
5811         else if (is_one(RHS(ins, 1))) {
5812                 mkcopy(state, ins, RHS(ins, 0));
5813         }
5814         else if (is_pow2(RHS(ins, 1))) {
5815                 struct triple *val;
5816                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5817                 ins->op = OP_SL;
5818                 insert_triple(state, ins, val);
5819                 unuse_triple(RHS(ins, 1), ins);
5820                 use_triple(val, ins);
5821                 RHS(ins, 1) = val;
5822         }
5823 }
5824
5825 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5826 {
5827         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5828                 long_t left, right;
5829                 left  = read_sconst(ins, &RHS(ins, 0));
5830                 right = read_sconst(ins, &RHS(ins, 1));
5831                 mkconst(state, ins, left / right);
5832         }
5833         else if (is_zero(RHS(ins, 0))) {
5834                 mkconst(state, ins, 0);
5835         }
5836         else if (is_zero(RHS(ins, 1))) {
5837                 error(state, ins, "division by zero");
5838         }
5839         else if (is_one(RHS(ins, 1))) {
5840                 mkcopy(state, ins, RHS(ins, 0));
5841         }
5842         else if (is_pow2(RHS(ins, 1))) {
5843                 struct triple *val;
5844                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5845                 ins->op = OP_SSR;
5846                 insert_triple(state, ins, val);
5847                 unuse_triple(RHS(ins, 1), ins);
5848                 use_triple(val, ins);
5849                 RHS(ins, 1) = val;
5850         }
5851 }
5852
5853 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5854 {
5855         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5856                 ulong_t left, right;
5857                 left  = read_const(state, ins, &RHS(ins, 0));
5858                 right = read_const(state, ins, &RHS(ins, 1));
5859                 mkconst(state, ins, left / right);
5860         }
5861         else if (is_zero(RHS(ins, 0))) {
5862                 mkconst(state, ins, 0);
5863         }
5864         else if (is_zero(RHS(ins, 1))) {
5865                 error(state, ins, "division by zero");
5866         }
5867         else if (is_one(RHS(ins, 1))) {
5868                 mkcopy(state, ins, RHS(ins, 0));
5869         }
5870         else if (is_pow2(RHS(ins, 1))) {
5871                 struct triple *val;
5872                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5873                 ins->op = OP_USR;
5874                 insert_triple(state, ins, val);
5875                 unuse_triple(RHS(ins, 1), ins);
5876                 use_triple(val, ins);
5877                 RHS(ins, 1) = val;
5878         }
5879 }
5880
5881 static void simplify_smod(struct compile_state *state, struct triple *ins)
5882 {
5883         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5884                 long_t left, right;
5885                 left  = read_const(state, ins, &RHS(ins, 0));
5886                 right = read_const(state, ins, &RHS(ins, 1));
5887                 mkconst(state, ins, left % right);
5888         }
5889         else if (is_zero(RHS(ins, 0))) {
5890                 mkconst(state, ins, 0);
5891         }
5892         else if (is_zero(RHS(ins, 1))) {
5893                 error(state, ins, "division by zero");
5894         }
5895         else if (is_one(RHS(ins, 1))) {
5896                 mkconst(state, ins, 0);
5897         }
5898         else if (is_pow2(RHS(ins, 1))) {
5899                 struct triple *val;
5900                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5901                 ins->op = OP_AND;
5902                 insert_triple(state, ins, val);
5903                 unuse_triple(RHS(ins, 1), ins);
5904                 use_triple(val, ins);
5905                 RHS(ins, 1) = val;
5906         }
5907 }
5908 static void simplify_umod(struct compile_state *state, struct triple *ins)
5909 {
5910         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5911                 ulong_t left, right;
5912                 left  = read_const(state, ins, &RHS(ins, 0));
5913                 right = read_const(state, ins, &RHS(ins, 1));
5914                 mkconst(state, ins, left % right);
5915         }
5916         else if (is_zero(RHS(ins, 0))) {
5917                 mkconst(state, ins, 0);
5918         }
5919         else if (is_zero(RHS(ins, 1))) {
5920                 error(state, ins, "division by zero");
5921         }
5922         else if (is_one(RHS(ins, 1))) {
5923                 mkconst(state, ins, 0);
5924         }
5925         else if (is_pow2(RHS(ins, 1))) {
5926                 struct triple *val;
5927                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5928                 ins->op = OP_AND;
5929                 insert_triple(state, ins, val);
5930                 unuse_triple(RHS(ins, 1), ins);
5931                 use_triple(val, ins);
5932                 RHS(ins, 1) = val;
5933         }
5934 }
5935
5936 static void simplify_add(struct compile_state *state, struct triple *ins)
5937 {
5938         /* start with the pointer on the left */
5939         if (is_pointer(RHS(ins, 1))) {
5940                 struct triple *tmp;
5941                 tmp = RHS(ins, 0);
5942                 RHS(ins, 0) = RHS(ins, 1);
5943                 RHS(ins, 1) = tmp;
5944         }
5945         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5946                 if (!is_pointer(RHS(ins, 0))) {
5947                         ulong_t left, right;
5948                         left  = read_const(state, ins, &RHS(ins, 0));
5949                         right = read_const(state, ins, &RHS(ins, 1));
5950                         mkconst(state, ins, left + right);
5951                 }
5952                 else /* op == OP_ADDRCONST */ {
5953                         struct triple *sdecl;
5954                         ulong_t left, right;
5955                         sdecl = MISC(RHS(ins, 0), 0);
5956                         left  = RHS(ins, 0)->u.cval;
5957                         right = RHS(ins, 1)->u.cval;
5958                         mkaddr_const(state, ins, sdecl, left + right);
5959                 }
5960         }
5961         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5962                 struct triple *tmp;
5963                 tmp = RHS(ins, 1);
5964                 RHS(ins, 1) = RHS(ins, 0);
5965                 RHS(ins, 0) = tmp;
5966         }
5967 }
5968
5969 static void simplify_sub(struct compile_state *state, struct triple *ins)
5970 {
5971         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5972                 if (!is_pointer(RHS(ins, 0))) {
5973                         ulong_t left, right;
5974                         left  = read_const(state, ins, &RHS(ins, 0));
5975                         right = read_const(state, ins, &RHS(ins, 1));
5976                         mkconst(state, ins, left - right);
5977                 }
5978                 else /* op == OP_ADDRCONST */ {
5979                         struct triple *sdecl;
5980                         ulong_t left, right;
5981                         sdecl = MISC(RHS(ins, 0), 0);
5982                         left  = RHS(ins, 0)->u.cval;
5983                         right = RHS(ins, 1)->u.cval;
5984                         mkaddr_const(state, ins, sdecl, left - right);
5985                 }
5986         }
5987 }
5988
5989 static void simplify_sl(struct compile_state *state, struct triple *ins)
5990 {
5991         if (is_const(RHS(ins, 1))) {
5992                 ulong_t right;
5993                 right = read_const(state, ins, &RHS(ins, 1));
5994                 if (right >= (size_of(state, ins->type)*8)) {
5995                         warning(state, ins, "left shift count >= width of type");
5996                 }
5997         }
5998         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5999                 ulong_t left, right;
6000                 left  = read_const(state, ins, &RHS(ins, 0));
6001                 right = read_const(state, ins, &RHS(ins, 1));
6002                 mkconst(state, ins,  left << right);
6003         }
6004 }
6005
6006 static void simplify_usr(struct compile_state *state, struct triple *ins)
6007 {
6008         if (is_const(RHS(ins, 1))) {
6009                 ulong_t right;
6010                 right = read_const(state, ins, &RHS(ins, 1));
6011                 if (right >= (size_of(state, ins->type)*8)) {
6012                         warning(state, ins, "right shift count >= width of type");
6013                 }
6014         }
6015         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6016                 ulong_t left, right;
6017                 left  = read_const(state, ins, &RHS(ins, 0));
6018                 right = read_const(state, ins, &RHS(ins, 1));
6019                 mkconst(state, ins, left >> right);
6020         }
6021 }
6022
6023 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6024 {
6025         if (is_const(RHS(ins, 1))) {
6026                 ulong_t right;
6027                 right = read_const(state, ins, &RHS(ins, 1));
6028                 if (right >= (size_of(state, ins->type)*8)) {
6029                         warning(state, ins, "right shift count >= width of type");
6030                 }
6031         }
6032         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6033                 long_t left, right;
6034                 left  = read_sconst(ins, &RHS(ins, 0));
6035                 right = read_sconst(ins, &RHS(ins, 1));
6036                 mkconst(state, ins, left >> right);
6037         }
6038 }
6039
6040 static void simplify_and(struct compile_state *state, struct triple *ins)
6041 {
6042         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6043                 ulong_t left, right;
6044                 left  = read_const(state, ins, &RHS(ins, 0));
6045                 right = read_const(state, ins, &RHS(ins, 1));
6046                 mkconst(state, ins, left & right);
6047         }
6048 }
6049
6050 static void simplify_or(struct compile_state *state, struct triple *ins)
6051 {
6052         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6053                 ulong_t left, right;
6054                 left  = read_const(state, ins, &RHS(ins, 0));
6055                 right = read_const(state, ins, &RHS(ins, 1));
6056                 mkconst(state, ins, left | right);
6057         }
6058 }
6059
6060 static void simplify_xor(struct compile_state *state, struct triple *ins)
6061 {
6062         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6063                 ulong_t left, right;
6064                 left  = read_const(state, ins, &RHS(ins, 0));
6065                 right = read_const(state, ins, &RHS(ins, 1));
6066                 mkconst(state, ins, left ^ right);
6067         }
6068 }
6069
6070 static void simplify_pos(struct compile_state *state, struct triple *ins)
6071 {
6072         if (is_const(RHS(ins, 0))) {
6073                 mkconst(state, ins, RHS(ins, 0)->u.cval);
6074         }
6075         else {
6076                 mkcopy(state, ins, RHS(ins, 0));
6077         }
6078 }
6079
6080 static void simplify_neg(struct compile_state *state, struct triple *ins)
6081 {
6082         if (is_const(RHS(ins, 0))) {
6083                 ulong_t left;
6084                 left = read_const(state, ins, &RHS(ins, 0));
6085                 mkconst(state, ins, -left);
6086         }
6087         else if (RHS(ins, 0)->op == OP_NEG) {
6088                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6089         }
6090 }
6091
6092 static void simplify_invert(struct compile_state *state, struct triple *ins)
6093 {
6094         if (is_const(RHS(ins, 0))) {
6095                 ulong_t left;
6096                 left = read_const(state, ins, &RHS(ins, 0));
6097                 mkconst(state, ins, ~left);
6098         }
6099 }
6100
6101 static void simplify_eq(struct compile_state *state, struct triple *ins)
6102 {
6103         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6104                 ulong_t left, right;
6105                 left  = read_const(state, ins, &RHS(ins, 0));
6106                 right = read_const(state, ins, &RHS(ins, 1));
6107                 mkconst(state, ins, left == right);
6108         }
6109         else if (RHS(ins, 0) == RHS(ins, 1)) {
6110                 mkconst(state, ins, 1);
6111         }
6112 }
6113
6114 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6115 {
6116         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6117                 ulong_t left, right;
6118                 left  = read_const(state, ins, &RHS(ins, 0));
6119                 right = read_const(state, ins, &RHS(ins, 1));
6120                 mkconst(state, ins, left != right);
6121         }
6122         else if (RHS(ins, 0) == RHS(ins, 1)) {
6123                 mkconst(state, ins, 0);
6124         }
6125 }
6126
6127 static void simplify_sless(struct compile_state *state, struct triple *ins)
6128 {
6129         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6130                 long_t left, right;
6131                 left  = read_sconst(ins, &RHS(ins, 0));
6132                 right = read_sconst(ins, &RHS(ins, 1));
6133                 mkconst(state, ins, left < right);
6134         }
6135         else if (RHS(ins, 0) == RHS(ins, 1)) {
6136                 mkconst(state, ins, 0);
6137         }
6138 }
6139
6140 static void simplify_uless(struct compile_state *state, struct triple *ins)
6141 {
6142         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6143                 ulong_t left, right;
6144                 left  = read_const(state, ins, &RHS(ins, 0));
6145                 right = read_const(state, ins, &RHS(ins, 1));
6146                 mkconst(state, ins, left < right);
6147         }
6148         else if (is_zero(RHS(ins, 0))) {
6149                 mkconst(state, ins, 1);
6150         }
6151         else if (RHS(ins, 0) == RHS(ins, 1)) {
6152                 mkconst(state, ins, 0);
6153         }
6154 }
6155
6156 static void simplify_smore(struct compile_state *state, struct triple *ins)
6157 {
6158         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6159                 long_t left, right;
6160                 left  = read_sconst(ins, &RHS(ins, 0));
6161                 right = read_sconst(ins, &RHS(ins, 1));
6162                 mkconst(state, ins, left > right);
6163         }
6164         else if (RHS(ins, 0) == RHS(ins, 1)) {
6165                 mkconst(state, ins, 0);
6166         }
6167 }
6168
6169 static void simplify_umore(struct compile_state *state, struct triple *ins)
6170 {
6171         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6172                 ulong_t left, right;
6173                 left  = read_const(state, ins, &RHS(ins, 0));
6174                 right = read_const(state, ins, &RHS(ins, 1));
6175                 mkconst(state, ins, left > right);
6176         }
6177         else if (is_zero(RHS(ins, 1))) {
6178                 mkconst(state, ins, 1);
6179         }
6180         else if (RHS(ins, 0) == RHS(ins, 1)) {
6181                 mkconst(state, ins, 0);
6182         }
6183 }
6184
6185
6186 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6187 {
6188         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6189                 long_t left, right;
6190                 left  = read_sconst(ins, &RHS(ins, 0));
6191                 right = read_sconst(ins, &RHS(ins, 1));
6192                 mkconst(state, ins, left <= right);
6193         }
6194         else if (RHS(ins, 0) == RHS(ins, 1)) {
6195                 mkconst(state, ins, 1);
6196         }
6197 }
6198
6199 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6200 {
6201         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6202                 ulong_t left, right;
6203                 left  = read_const(state, ins, &RHS(ins, 0));
6204                 right = read_const(state, ins, &RHS(ins, 1));
6205                 mkconst(state, ins, left <= right);
6206         }
6207         else if (is_zero(RHS(ins, 0))) {
6208                 mkconst(state, ins, 1);
6209         }
6210         else if (RHS(ins, 0) == RHS(ins, 1)) {
6211                 mkconst(state, ins, 1);
6212         }
6213 }
6214
6215 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6216 {
6217         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6218                 long_t left, right;
6219                 left  = read_sconst(ins, &RHS(ins, 0));
6220                 right = read_sconst(ins, &RHS(ins, 1));
6221                 mkconst(state, ins, left >= right);
6222         }
6223         else if (RHS(ins, 0) == RHS(ins, 1)) {
6224                 mkconst(state, ins, 1);
6225         }
6226 }
6227
6228 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6229 {
6230         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6231                 ulong_t left, right;
6232                 left  = read_const(state, ins, &RHS(ins, 0));
6233                 right = read_const(state, ins, &RHS(ins, 1));
6234                 mkconst(state, ins, left >= right);
6235         }
6236         else if (is_zero(RHS(ins, 1))) {
6237                 mkconst(state, ins, 1);
6238         }
6239         else if (RHS(ins, 0) == RHS(ins, 1)) {
6240                 mkconst(state, ins, 1);
6241         }
6242 }
6243
6244 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6245 {
6246         if (is_const(RHS(ins, 0))) {
6247                 ulong_t left;
6248                 left = read_const(state, ins, &RHS(ins, 0));
6249                 mkconst(state, ins, left == 0);
6250         }
6251         /* Otherwise if I am the only user... */
6252         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6253                 int need_copy = 1;
6254                 /* Invert a boolean operation */
6255                 switch(RHS(ins, 0)->op) {
6256                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
6257                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
6258                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
6259                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
6260                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
6261                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
6262                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
6263                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
6264                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
6265                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
6266                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
6267                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
6268                 default:
6269                         need_copy = 0;
6270                         break;
6271                 }
6272                 if (need_copy) {
6273                         mkcopy(state, ins, RHS(ins, 0));
6274                 }
6275         }
6276 }
6277
6278 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6279 {
6280         if (is_const(RHS(ins, 0))) {
6281                 ulong_t left;
6282                 left = read_const(state, ins, &RHS(ins, 0));
6283                 mkconst(state, ins, left != 0);
6284         }
6285         else switch(RHS(ins, 0)->op) {
6286         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
6287         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
6288         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6289                 mkcopy(state, ins, RHS(ins, 0));
6290         }
6291
6292 }
6293
6294 static void simplify_copy(struct compile_state *state, struct triple *ins)
6295 {
6296         if (is_const(RHS(ins, 0))) {
6297                 switch(RHS(ins, 0)->op) {
6298                 case OP_INTCONST:
6299                 {
6300                         ulong_t left;
6301                         left = read_const(state, ins, &RHS(ins, 0));
6302                         mkconst(state, ins, left);
6303                         break;
6304                 }
6305                 case OP_ADDRCONST:
6306                 {
6307                         struct triple *sdecl;
6308                         ulong_t offset;
6309                         sdecl  = MISC(RHS(ins, 0), 0);
6310                         offset = RHS(ins, 0)->u.cval;
6311                         mkaddr_const(state, ins, sdecl, offset);
6312                         break;
6313                 }
6314                 default:
6315                         internal_error(state, ins, "uknown constant");
6316                         break;
6317                 }
6318         }
6319 }
6320
6321 static void simplify_branch(struct compile_state *state, struct triple *ins)
6322 {
6323         struct block *block;
6324         if (ins->op != OP_BRANCH) {
6325                 internal_error(state, ins, "not branch");
6326         }
6327         if (ins->use != 0) {
6328                 internal_error(state, ins, "branch use");
6329         }
6330 #warning "FIXME implement simplify branch."
6331         /* The challenge here with simplify branch is that I need to 
6332          * make modifications to the control flow graph as well
6333          * as to the branch instruction itself.
6334          */
6335         block = ins->u.block;
6336         
6337         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6338                 struct triple *targ;
6339                 ulong_t value;
6340                 value = read_const(state, ins, &RHS(ins, 0));
6341                 unuse_triple(RHS(ins, 0), ins);
6342                 targ = TARG(ins, 0);
6343                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6344                 if (value) {
6345                         unuse_triple(ins->next, ins);
6346                         TARG(ins, 0) = targ;
6347                 }
6348                 else {
6349                         unuse_triple(targ, ins);
6350                         TARG(ins, 0) = ins->next;
6351                 }
6352 #warning "FIXME handle the case of making a branch unconditional"
6353         }
6354         if (TARG(ins, 0) == ins->next) {
6355                 unuse_triple(ins->next, ins);
6356                 if (TRIPLE_RHS(ins->sizes)) {
6357                         unuse_triple(RHS(ins, 0), ins);
6358                         unuse_triple(ins->next, ins);
6359                 }
6360                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6361                 ins->op = OP_NOOP;
6362                 if (ins->use) {
6363                         internal_error(state, ins, "noop use != 0");
6364                 }
6365 #warning "FIXME handle the case of killing a branch"
6366         }
6367 }
6368
6369 static void simplify_phi(struct compile_state *state, struct triple *ins)
6370 {
6371         struct triple **expr;
6372         ulong_t value;
6373         expr = triple_rhs(state, ins, 0);
6374         if (!*expr || !is_const(*expr)) {
6375                 return;
6376         }
6377         value = read_const(state, ins, expr);
6378         for(;expr;expr = triple_rhs(state, ins, expr)) {
6379                 if (!*expr || !is_const(*expr)) {
6380                         return;
6381                 }
6382                 if (value != read_const(state, ins, expr)) {
6383                         return;
6384                 }
6385         }
6386         mkconst(state, ins, value);
6387 }
6388
6389
6390 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6391 {
6392         if (is_const(RHS(ins, 0))) {
6393                 ulong_t left;
6394                 left = read_const(state, ins, &RHS(ins, 0));
6395                 mkconst(state, ins, bsf(left));
6396         }
6397 }
6398
6399 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6400 {
6401         if (is_const(RHS(ins, 0))) {
6402                 ulong_t left;
6403                 left = read_const(state, ins, &RHS(ins, 0));
6404                 mkconst(state, ins, bsr(left));
6405         }
6406 }
6407
6408
6409 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6410 static const simplify_t table_simplify[] = {
6411 #if 0
6412 #define simplify_smul     simplify_noop
6413 #define simplify_umul     simplify_noop
6414 #define simplify_sdiv     simplify_noop
6415 #define simplify_udiv     simplify_noop
6416 #define simplify_smod     simplify_noop
6417 #define simplify_umod     simplify_noop
6418 #endif
6419 #if 0
6420 #define simplify_add      simplify_noop
6421 #define simplify_sub      simplify_noop
6422 #endif
6423 #if 0
6424 #define simplify_sl       simplify_noop
6425 #define simplify_usr      simplify_noop
6426 #define simplify_ssr      simplify_noop
6427 #endif
6428 #if 0
6429 #define simplify_and      simplify_noop
6430 #define simplify_xor      simplify_noop
6431 #define simplify_or       simplify_noop
6432 #endif
6433 #if 0
6434 #define simplify_pos      simplify_noop
6435 #define simplify_neg      simplify_noop
6436 #define simplify_invert   simplify_noop
6437 #endif
6438
6439 #if 0
6440 #define simplify_eq       simplify_noop
6441 #define simplify_noteq    simplify_noop
6442 #endif
6443 #if 0
6444 #define simplify_sless    simplify_noop
6445 #define simplify_uless    simplify_noop
6446 #define simplify_smore    simplify_noop
6447 #define simplify_umore    simplify_noop
6448 #endif
6449 #if 0
6450 #define simplify_slesseq  simplify_noop
6451 #define simplify_ulesseq  simplify_noop
6452 #define simplify_smoreeq  simplify_noop
6453 #define simplify_umoreeq  simplify_noop
6454 #endif
6455 #if 0
6456 #define simplify_lfalse   simplify_noop
6457 #endif
6458 #if 0
6459 #define simplify_ltrue    simplify_noop
6460 #endif
6461
6462 #if 0
6463 #define simplify_copy     simplify_noop
6464 #endif
6465
6466 #if 0
6467 #define simplify_branch   simplify_noop
6468 #endif
6469
6470 #if 0
6471 #define simplify_phi      simplify_noop
6472 #endif
6473
6474 #if 0
6475 #define simplify_bsf      simplify_noop
6476 #define simplify_bsr      simplify_noop
6477 #endif
6478
6479 [OP_SMUL       ] = simplify_smul,
6480 [OP_UMUL       ] = simplify_umul,
6481 [OP_SDIV       ] = simplify_sdiv,
6482 [OP_UDIV       ] = simplify_udiv,
6483 [OP_SMOD       ] = simplify_smod,
6484 [OP_UMOD       ] = simplify_umod,
6485 [OP_ADD        ] = simplify_add,
6486 [OP_SUB        ] = simplify_sub,
6487 [OP_SL         ] = simplify_sl,
6488 [OP_USR        ] = simplify_usr,
6489 [OP_SSR        ] = simplify_ssr,
6490 [OP_AND        ] = simplify_and,
6491 [OP_XOR        ] = simplify_xor,
6492 [OP_OR         ] = simplify_or,
6493 [OP_POS        ] = simplify_pos,
6494 [OP_NEG        ] = simplify_neg,
6495 [OP_INVERT     ] = simplify_invert,
6496
6497 [OP_EQ         ] = simplify_eq,
6498 [OP_NOTEQ      ] = simplify_noteq,
6499 [OP_SLESS      ] = simplify_sless,
6500 [OP_ULESS      ] = simplify_uless,
6501 [OP_SMORE      ] = simplify_smore,
6502 [OP_UMORE      ] = simplify_umore,
6503 [OP_SLESSEQ    ] = simplify_slesseq,
6504 [OP_ULESSEQ    ] = simplify_ulesseq,
6505 [OP_SMOREEQ    ] = simplify_smoreeq,
6506 [OP_UMOREEQ    ] = simplify_umoreeq,
6507 [OP_LFALSE     ] = simplify_lfalse,
6508 [OP_LTRUE      ] = simplify_ltrue,
6509
6510 [OP_LOAD       ] = simplify_noop,
6511 [OP_STORE      ] = simplify_noop,
6512
6513 [OP_NOOP       ] = simplify_noop,
6514
6515 [OP_INTCONST   ] = simplify_noop,
6516 [OP_BLOBCONST  ] = simplify_noop,
6517 [OP_ADDRCONST  ] = simplify_noop,
6518
6519 [OP_WRITE      ] = simplify_noop,
6520 [OP_READ       ] = simplify_noop,
6521 [OP_COPY       ] = simplify_copy,
6522 [OP_PIECE      ] = simplify_noop,
6523 [OP_ASM        ] = simplify_noop,
6524
6525 [OP_DOT        ] = simplify_noop,
6526 [OP_VAL_VEC    ] = simplify_noop,
6527
6528 [OP_LIST       ] = simplify_noop,
6529 [OP_BRANCH     ] = simplify_branch,
6530 [OP_LABEL      ] = simplify_noop,
6531 [OP_ADECL      ] = simplify_noop,
6532 [OP_SDECL      ] = simplify_noop,
6533 [OP_PHI        ] = simplify_phi,
6534
6535 [OP_INB        ] = simplify_noop,
6536 [OP_INW        ] = simplify_noop,
6537 [OP_INL        ] = simplify_noop,
6538 [OP_OUTB       ] = simplify_noop,
6539 [OP_OUTW       ] = simplify_noop,
6540 [OP_OUTL       ] = simplify_noop,
6541 [OP_BSF        ] = simplify_bsf,
6542 [OP_BSR        ] = simplify_bsr,
6543 [OP_RDMSR      ] = simplify_noop,
6544 [OP_WRMSR      ] = simplify_noop,                    
6545 [OP_HLT        ] = simplify_noop,
6546 };
6547
6548 static void simplify(struct compile_state *state, struct triple *ins)
6549 {
6550         int op;
6551         simplify_t do_simplify;
6552         do {
6553                 op = ins->op;
6554                 do_simplify = 0;
6555                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6556                         do_simplify = 0;
6557                 }
6558                 else {
6559                         do_simplify = table_simplify[op];
6560                 }
6561                 if (!do_simplify) {
6562                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6563                                 op, tops(op));
6564                         return;
6565                 }
6566                 do_simplify(state, ins);
6567         } while(ins->op != op);
6568 }
6569
6570 static void simplify_all(struct compile_state *state)
6571 {
6572         struct triple *ins, *first;
6573         first = RHS(state->main_function, 0);
6574         ins = first;
6575         do {
6576                 simplify(state, ins);
6577                 ins = ins->next;
6578         } while(ins != first);
6579 }
6580
6581 /*
6582  * Builtins....
6583  * ============================
6584  */
6585
6586 static void register_builtin_function(struct compile_state *state,
6587         const char *name, int op, struct type *rtype, ...)
6588 {
6589         struct type *ftype, *atype, *param, **next;
6590         struct triple *def, *arg, *result, *work, *last, *first;
6591         struct hash_entry *ident;
6592         struct file_state file;
6593         int parameters;
6594         int name_len;
6595         va_list args;
6596         int i;
6597
6598         /* Dummy file state to get debug handling right */
6599         memset(&file, 0, sizeof(file));
6600         file.basename = "<built-in>";
6601         file.line = 1;
6602         file.report_line = 1;
6603         file.report_name = file.basename;
6604         file.prev = state->file;
6605         state->file = &file;
6606         state->function = name;
6607
6608         /* Find the Parameter count */
6609         valid_op(state, op);
6610         parameters = table_ops[op].rhs;
6611         if (parameters < 0 ) {
6612                 internal_error(state, 0, "Invalid builtin parameter count");
6613         }
6614
6615         /* Find the function type */
6616         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6617         next = &ftype->right;
6618         va_start(args, rtype);
6619         for(i = 0; i < parameters; i++) {
6620                 atype = va_arg(args, struct type *);
6621                 if (!*next) {
6622                         *next = atype;
6623                 } else {
6624                         *next = new_type(TYPE_PRODUCT, *next, atype);
6625                         next = &((*next)->right);
6626                 }
6627         }
6628         if (!*next) {
6629                 *next = &void_type;
6630         }
6631         va_end(args);
6632
6633         /* Generate the needed triples */
6634         def = triple(state, OP_LIST, ftype, 0, 0);
6635         first = label(state);
6636         RHS(def, 0) = first;
6637
6638         /* Now string them together */
6639         param = ftype->right;
6640         for(i = 0; i < parameters; i++) {
6641                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6642                         atype = param->left;
6643                 } else {
6644                         atype = param;
6645                 }
6646                 arg = flatten(state, first, variable(state, atype));
6647                 param = param->right;
6648         }
6649         result = 0;
6650         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6651                 result = flatten(state, first, variable(state, rtype));
6652         }
6653         MISC(def, 0) = result;
6654         work = new_triple(state, op, rtype, -1, parameters);
6655         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6656                 RHS(work, i) = read_expr(state, arg);
6657         }
6658         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6659                 struct triple *val;
6660                 /* Populate the LHS with the target registers */
6661                 work = flatten(state, first, work);
6662                 work->type = &void_type;
6663                 param = rtype->left;
6664                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6665                         internal_error(state, 0, "Invalid result type");
6666                 }
6667                 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6668                 for(i = 0; i < rtype->elements; i++) {
6669                         struct triple *piece;
6670                         atype = param;
6671                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6672                                 atype = param->left;
6673                         }
6674                         if (!TYPE_ARITHMETIC(atype->type) &&
6675                                 !TYPE_PTR(atype->type)) {
6676                                 internal_error(state, 0, "Invalid lhs type");
6677                         }
6678                         piece = triple(state, OP_PIECE, atype, work, 0);
6679                         piece->u.cval = i;
6680                         LHS(work, i) = piece;
6681                         RHS(val, i) = piece;
6682                 }
6683                 work = val;
6684         }
6685         if (result) {
6686                 work = write_expr(state, result, work);
6687         }
6688         work = flatten(state, first, work);
6689         last = flatten(state, first, label(state));
6690         name_len = strlen(name);
6691         ident = lookup(state, name, name_len);
6692         symbol(state, ident, &ident->sym_ident, def, ftype);
6693         
6694         state->file = file.prev;
6695         state->function = 0;
6696 #if 0
6697         fprintf(stdout, "\n");
6698         loc(stdout, state, 0);
6699         fprintf(stdout, "\n__________ builtin_function _________\n");
6700         print_triple(state, def);
6701         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6702 #endif
6703 }
6704
6705 static struct type *partial_struct(struct compile_state *state,
6706         const char *field_name, struct type *type, struct type *rest)
6707 {
6708         struct hash_entry *field_ident;
6709         struct type *result;
6710         int field_name_len;
6711
6712         field_name_len = strlen(field_name);
6713         field_ident = lookup(state, field_name, field_name_len);
6714
6715         result = clone_type(0, type);
6716         result->field_ident = field_ident;
6717
6718         if (rest) {
6719                 result = new_type(TYPE_PRODUCT, result, rest);
6720         }
6721         return result;
6722 }
6723
6724 static struct type *register_builtin_type(struct compile_state *state,
6725         const char *name, struct type *type)
6726 {
6727         struct hash_entry *ident;
6728         int name_len;
6729
6730         name_len = strlen(name);
6731         ident = lookup(state, name, name_len);
6732         
6733         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6734                 ulong_t elements = 0;
6735                 struct type *field;
6736                 type = new_type(TYPE_STRUCT, type, 0);
6737                 field = type->left;
6738                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6739                         elements++;
6740                         field = field->right;
6741                 }
6742                 elements++;
6743                 symbol(state, ident, &ident->sym_struct, 0, type);
6744                 type->type_ident = ident;
6745                 type->elements = elements;
6746         }
6747         symbol(state, ident, &ident->sym_ident, 0, type);
6748         ident->tok = TOK_TYPE_NAME;
6749         return type;
6750 }
6751
6752
6753 static void register_builtins(struct compile_state *state)
6754 {
6755         struct type *msr_type;
6756
6757         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6758                 &ushort_type);
6759         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6760                 &ushort_type);
6761         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6762                 &ushort_type);
6763
6764         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6765                 &uchar_type, &ushort_type);
6766         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6767                 &ushort_type, &ushort_type);
6768         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6769                 &uint_type, &ushort_type);
6770         
6771         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6772                 &int_type);
6773         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6774                 &int_type);
6775
6776         msr_type = register_builtin_type(state, "__builtin_msr_t",
6777                 partial_struct(state, "lo", &ulong_type,
6778                 partial_struct(state, "hi", &ulong_type, 0)));
6779
6780         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6781                 &ulong_type);
6782         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6783                 &ulong_type, &ulong_type, &ulong_type);
6784         
6785         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6786                 &void_type);
6787 }
6788
6789 static struct type *declarator(
6790         struct compile_state *state, struct type *type, 
6791         struct hash_entry **ident, int need_ident);
6792 static void decl(struct compile_state *state, struct triple *first);
6793 static struct type *specifier_qualifier_list(struct compile_state *state);
6794 static int isdecl_specifier(int tok);
6795 static struct type *decl_specifiers(struct compile_state *state);
6796 static int istype(int tok);
6797 static struct triple *expr(struct compile_state *state);
6798 static struct triple *assignment_expr(struct compile_state *state);
6799 static struct type *type_name(struct compile_state *state);
6800 static void statement(struct compile_state *state, struct triple *fist);
6801
6802 static struct triple *call_expr(
6803         struct compile_state *state, struct triple *func)
6804 {
6805         struct triple *def;
6806         struct type *param, *type;
6807         ulong_t pvals, index;
6808
6809         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6810                 error(state, 0, "Called object is not a function");
6811         }
6812         if (func->op != OP_LIST) {
6813                 internal_error(state, 0, "improper function");
6814         }
6815         eat(state, TOK_LPAREN);
6816         /* Find the return type without any specifiers */
6817         type = clone_type(0, func->type->left);
6818         def = new_triple(state, OP_CALL, func->type, -1, -1);
6819         def->type = type;
6820
6821         pvals = TRIPLE_RHS(def->sizes);
6822         MISC(def, 0) = func;
6823
6824         param = func->type->right;
6825         for(index = 0; index < pvals; index++) {
6826                 struct triple *val;
6827                 struct type *arg_type;
6828                 val = read_expr(state, assignment_expr(state));
6829                 arg_type = param;
6830                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6831                         arg_type = param->left;
6832                 }
6833                 write_compatible(state, arg_type, val->type);
6834                 RHS(def, index) = val;
6835                 if (index != (pvals - 1)) {
6836                         eat(state, TOK_COMMA);
6837                         param = param->right;
6838                 }
6839         }
6840         eat(state, TOK_RPAREN);
6841         return def;
6842 }
6843
6844
6845 static struct triple *character_constant(struct compile_state *state)
6846 {
6847         struct triple *def;
6848         struct token *tk;
6849         const signed char *str, *end;
6850         int c;
6851         int str_len;
6852         eat(state, TOK_LIT_CHAR);
6853         tk = &state->token[0];
6854         str = tk->val.str + 1;
6855         str_len = tk->str_len - 2;
6856         if (str_len <= 0) {
6857                 error(state, 0, "empty character constant");
6858         }
6859         end = str + str_len;
6860         c = char_value(state, &str, end);
6861         if (str != end) {
6862                 error(state, 0, "multibyte character constant not supported");
6863         }
6864         def = int_const(state, &char_type, (ulong_t)((long_t)c));
6865         return def;
6866 }
6867
6868 static struct triple *string_constant(struct compile_state *state)
6869 {
6870         struct triple *def;
6871         struct token *tk;
6872         struct type *type;
6873         const signed char *str, *end;
6874         signed char *buf, *ptr;
6875         int str_len;
6876
6877         buf = 0;
6878         type = new_type(TYPE_ARRAY, &char_type, 0);
6879         type->elements = 0;
6880         /* The while loop handles string concatenation */
6881         do {
6882                 eat(state, TOK_LIT_STRING);
6883                 tk = &state->token[0];
6884                 str = tk->val.str + 1;
6885                 str_len = tk->str_len - 2;
6886                 if (str_len < 0) {
6887                         error(state, 0, "negative string constant length");
6888                 }
6889                 end = str + str_len;
6890                 ptr = buf;
6891                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6892                 memcpy(buf, ptr, type->elements);
6893                 ptr = buf + type->elements;
6894                 do {
6895                         *ptr++ = char_value(state, &str, end);
6896                 } while(str < end);
6897                 type->elements = ptr - buf;
6898         } while(peek(state) == TOK_LIT_STRING);
6899         *ptr = '\0';
6900         type->elements += 1;
6901         def = triple(state, OP_BLOBCONST, type, 0, 0);
6902         def->u.blob = buf;
6903         return def;
6904 }
6905
6906
6907 static struct triple *integer_constant(struct compile_state *state)
6908 {
6909         struct triple *def;
6910         unsigned long val;
6911         struct token *tk;
6912         char *end;
6913         int u, l, decimal;
6914         struct type *type;
6915
6916         eat(state, TOK_LIT_INT);
6917         tk = &state->token[0];
6918         errno = 0;
6919         decimal = (tk->val.str[0] != '0');
6920         val = strtoul(tk->val.str, &end, 0);
6921         if ((val == ULONG_MAX) && (errno == ERANGE)) {
6922                 error(state, 0, "Integer constant to large");
6923         }
6924         u = l = 0;
6925         if ((*end == 'u') || (*end == 'U')) {
6926                 u = 1;
6927                         end++;
6928         }
6929         if ((*end == 'l') || (*end == 'L')) {
6930                 l = 1;
6931                 end++;
6932         }
6933         if ((*end == 'u') || (*end == 'U')) {
6934                 u = 1;
6935                 end++;
6936         }
6937         if (*end) {
6938                 error(state, 0, "Junk at end of integer constant");
6939         }
6940         if (u && l)  {
6941                 type = &ulong_type;
6942         }
6943         else if (l) {
6944                 type = &long_type;
6945                 if (!decimal && (val > LONG_MAX)) {
6946                         type = &ulong_type;
6947                 }
6948         }
6949         else if (u) {
6950                 type = &uint_type;
6951                 if (val > UINT_MAX) {
6952                         type = &ulong_type;
6953                 }
6954         }
6955         else {
6956                 type = &int_type;
6957                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6958                         type = &uint_type;
6959                 }
6960                 else if (!decimal && (val > LONG_MAX)) {
6961                         type = &ulong_type;
6962                 }
6963                 else if (val > INT_MAX) {
6964                         type = &long_type;
6965                 }
6966         }
6967         def = int_const(state, type, val);
6968         return def;
6969 }
6970
6971 static struct triple *primary_expr(struct compile_state *state)
6972 {
6973         struct triple *def;
6974         int tok;
6975         tok = peek(state);
6976         switch(tok) {
6977         case TOK_IDENT:
6978         {
6979                 struct hash_entry *ident;
6980                 /* Here ident is either:
6981                  * a varable name
6982                  * a function name
6983                  * an enumeration constant.
6984                  */
6985                 eat(state, TOK_IDENT);
6986                 ident = state->token[0].ident;
6987                 if (!ident->sym_ident) {
6988                         error(state, 0, "%s undeclared", ident->name);
6989                 }
6990                 def = ident->sym_ident->def;
6991                 break;
6992         }
6993         case TOK_ENUM_CONST:
6994                 /* Here ident is an enumeration constant */
6995                 eat(state, TOK_ENUM_CONST);
6996                 def = 0;
6997                 FINISHME();
6998                 break;
6999         case TOK_LPAREN:
7000                 eat(state, TOK_LPAREN);
7001                 def = expr(state);
7002                 eat(state, TOK_RPAREN);
7003                 break;
7004         case TOK_LIT_INT:
7005                 def = integer_constant(state);
7006                 break;
7007         case TOK_LIT_FLOAT:
7008                 eat(state, TOK_LIT_FLOAT);
7009                 error(state, 0, "Floating point constants not supported");
7010                 def = 0;
7011                 FINISHME();
7012                 break;
7013         case TOK_LIT_CHAR:
7014                 def = character_constant(state);
7015                 break;
7016         case TOK_LIT_STRING:
7017                 def = string_constant(state);
7018                 break;
7019         default:
7020                 def = 0;
7021                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7022         }
7023         return def;
7024 }
7025
7026 static struct triple *postfix_expr(struct compile_state *state)
7027 {
7028         struct triple *def;
7029         int postfix;
7030         def = primary_expr(state);
7031         do {
7032                 struct triple *left;
7033                 int tok;
7034                 postfix = 1;
7035                 left = def;
7036                 switch((tok = peek(state))) {
7037                 case TOK_LBRACKET:
7038                         eat(state, TOK_LBRACKET);
7039                         def = mk_subscript_expr(state, left, expr(state));
7040                         eat(state, TOK_RBRACKET);
7041                         break;
7042                 case TOK_LPAREN:
7043                         def = call_expr(state, def);
7044                         break;
7045                 case TOK_DOT:
7046                 {
7047                         struct hash_entry *field;
7048                         eat(state, TOK_DOT);
7049                         eat(state, TOK_IDENT);
7050                         field = state->token[0].ident;
7051                         def = deref_field(state, def, field);
7052                         break;
7053                 }
7054                 case TOK_ARROW:
7055                 {
7056                         struct hash_entry *field;
7057                         eat(state, TOK_ARROW);
7058                         eat(state, TOK_IDENT);
7059                         field = state->token[0].ident;
7060                         def = mk_deref_expr(state, read_expr(state, def));
7061                         def = deref_field(state, def, field);
7062                         break;
7063                 }
7064                 case TOK_PLUSPLUS:
7065                         eat(state, TOK_PLUSPLUS);
7066                         def = mk_post_inc_expr(state, left);
7067                         break;
7068                 case TOK_MINUSMINUS:
7069                         eat(state, TOK_MINUSMINUS);
7070                         def = mk_post_dec_expr(state, left);
7071                         break;
7072                 default:
7073                         postfix = 0;
7074                         break;
7075                 }
7076         } while(postfix);
7077         return def;
7078 }
7079
7080 static struct triple *cast_expr(struct compile_state *state);
7081
7082 static struct triple *unary_expr(struct compile_state *state)
7083 {
7084         struct triple *def, *right;
7085         int tok;
7086         switch((tok = peek(state))) {
7087         case TOK_PLUSPLUS:
7088                 eat(state, TOK_PLUSPLUS);
7089                 def = mk_pre_inc_expr(state, unary_expr(state));
7090                 break;
7091         case TOK_MINUSMINUS:
7092                 eat(state, TOK_MINUSMINUS);
7093                 def = mk_pre_dec_expr(state, unary_expr(state));
7094                 break;
7095         case TOK_AND:
7096                 eat(state, TOK_AND);
7097                 def = mk_addr_expr(state, cast_expr(state), 0);
7098                 break;
7099         case TOK_STAR:
7100                 eat(state, TOK_STAR);
7101                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7102                 break;
7103         case TOK_PLUS:
7104                 eat(state, TOK_PLUS);
7105                 right = read_expr(state, cast_expr(state));
7106                 arithmetic(state, right);
7107                 def = integral_promotion(state, right);
7108                 break;
7109         case TOK_MINUS:
7110                 eat(state, TOK_MINUS);
7111                 right = read_expr(state, cast_expr(state));
7112                 arithmetic(state, right);
7113                 def = integral_promotion(state, right);
7114                 def = triple(state, OP_NEG, def->type, def, 0);
7115                 break;
7116         case TOK_TILDE:
7117                 eat(state, TOK_TILDE);
7118                 right = read_expr(state, cast_expr(state));
7119                 integral(state, right);
7120                 def = integral_promotion(state, right);
7121                 def = triple(state, OP_INVERT, def->type, def, 0);
7122                 break;
7123         case TOK_BANG:
7124                 eat(state, TOK_BANG);
7125                 right = read_expr(state, cast_expr(state));
7126                 bool(state, right);
7127                 def = lfalse_expr(state, right);
7128                 break;
7129         case TOK_SIZEOF:
7130         {
7131                 struct type *type;
7132                 int tok1, tok2;
7133                 eat(state, TOK_SIZEOF);
7134                 tok1 = peek(state);
7135                 tok2 = peek2(state);
7136                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7137                         eat(state, TOK_LPAREN);
7138                         type = type_name(state);
7139                         eat(state, TOK_RPAREN);
7140                 }
7141                 else {
7142                         struct triple *expr;
7143                         expr = unary_expr(state);
7144                         type = expr->type;
7145                         release_expr(state, expr);
7146                 }
7147                 def = int_const(state, &ulong_type, size_of(state, type));
7148                 break;
7149         }
7150         case TOK_ALIGNOF:
7151         {
7152                 struct type *type;
7153                 int tok1, tok2;
7154                 eat(state, TOK_ALIGNOF);
7155                 tok1 = peek(state);
7156                 tok2 = peek2(state);
7157                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7158                         eat(state, TOK_LPAREN);
7159                         type = type_name(state);
7160                         eat(state, TOK_RPAREN);
7161                 }
7162                 else {
7163                         struct triple *expr;
7164                         expr = unary_expr(state);
7165                         type = expr->type;
7166                         release_expr(state, expr);
7167                 }
7168                 def = int_const(state, &ulong_type, align_of(state, type));
7169                 break;
7170         }
7171         default:
7172                 def = postfix_expr(state);
7173                 break;
7174         }
7175         return def;
7176 }
7177
7178 static struct triple *cast_expr(struct compile_state *state)
7179 {
7180         struct triple *def;
7181         int tok1, tok2;
7182         tok1 = peek(state);
7183         tok2 = peek2(state);
7184         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7185                 struct type *type;
7186                 eat(state, TOK_LPAREN);
7187                 type = type_name(state);
7188                 eat(state, TOK_RPAREN);
7189                 def = read_expr(state, cast_expr(state));
7190                 def = triple(state, OP_COPY, type, def, 0);
7191         }
7192         else {
7193                 def = unary_expr(state);
7194         }
7195         return def;
7196 }
7197
7198 static struct triple *mult_expr(struct compile_state *state)
7199 {
7200         struct triple *def;
7201         int done;
7202         def = cast_expr(state);
7203         do {
7204                 struct triple *left, *right;
7205                 struct type *result_type;
7206                 int tok, op, sign;
7207                 done = 0;
7208                 switch(tok = (peek(state))) {
7209                 case TOK_STAR:
7210                 case TOK_DIV:
7211                 case TOK_MOD:
7212                         left = read_expr(state, def);
7213                         arithmetic(state, left);
7214
7215                         eat(state, tok);
7216
7217                         right = read_expr(state, cast_expr(state));
7218                         arithmetic(state, right);
7219
7220                         result_type = arithmetic_result(state, left, right);
7221                         sign = is_signed(result_type);
7222                         op = -1;
7223                         switch(tok) {
7224                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7225                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
7226                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
7227                         }
7228                         def = triple(state, op, result_type, left, right);
7229                         break;
7230                 default:
7231                         done = 1;
7232                         break;
7233                 }
7234         } while(!done);
7235         return def;
7236 }
7237
7238 static struct triple *add_expr(struct compile_state *state)
7239 {
7240         struct triple *def;
7241         int done;
7242         def = mult_expr(state);
7243         do {
7244                 done = 0;
7245                 switch( peek(state)) {
7246                 case TOK_PLUS:
7247                         eat(state, TOK_PLUS);
7248                         def = mk_add_expr(state, def, mult_expr(state));
7249                         break;
7250                 case TOK_MINUS:
7251                         eat(state, TOK_MINUS);
7252                         def = mk_sub_expr(state, def, mult_expr(state));
7253                         break;
7254                 default:
7255                         done = 1;
7256                         break;
7257                 }
7258         } while(!done);
7259         return def;
7260 }
7261
7262 static struct triple *shift_expr(struct compile_state *state)
7263 {
7264         struct triple *def;
7265         int done;
7266         def = add_expr(state);
7267         do {
7268                 struct triple *left, *right;
7269                 int tok, op;
7270                 done = 0;
7271                 switch((tok = peek(state))) {
7272                 case TOK_SL:
7273                 case TOK_SR:
7274                         left = read_expr(state, def);
7275                         integral(state, left);
7276                         left = integral_promotion(state, left);
7277
7278                         eat(state, tok);
7279
7280                         right = read_expr(state, add_expr(state));
7281                         integral(state, right);
7282                         right = integral_promotion(state, right);
7283                         
7284                         op = (tok == TOK_SL)? OP_SL : 
7285                                 is_signed(left->type)? OP_SSR: OP_USR;
7286
7287                         def = triple(state, op, left->type, left, right);
7288                         break;
7289                 default:
7290                         done = 1;
7291                         break;
7292                 }
7293         } while(!done);
7294         return def;
7295 }
7296
7297 static struct triple *relational_expr(struct compile_state *state)
7298 {
7299 #warning "Extend relational exprs to work on more than arithmetic types"
7300         struct triple *def;
7301         int done;
7302         def = shift_expr(state);
7303         do {
7304                 struct triple *left, *right;
7305                 struct type *arg_type;
7306                 int tok, op, sign;
7307                 done = 0;
7308                 switch((tok = peek(state))) {
7309                 case TOK_LESS:
7310                 case TOK_MORE:
7311                 case TOK_LESSEQ:
7312                 case TOK_MOREEQ:
7313                         left = read_expr(state, def);
7314                         arithmetic(state, left);
7315
7316                         eat(state, tok);
7317
7318                         right = read_expr(state, shift_expr(state));
7319                         arithmetic(state, right);
7320
7321                         arg_type = arithmetic_result(state, left, right);
7322                         sign = is_signed(arg_type);
7323                         op = -1;
7324                         switch(tok) {
7325                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
7326                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
7327                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7328                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7329                         }
7330                         def = triple(state, op, &int_type, left, right);
7331                         break;
7332                 default:
7333                         done = 1;
7334                         break;
7335                 }
7336         } while(!done);
7337         return def;
7338 }
7339
7340 static struct triple *equality_expr(struct compile_state *state)
7341 {
7342 #warning "Extend equality exprs to work on more than arithmetic types"
7343         struct triple *def;
7344         int done;
7345         def = relational_expr(state);
7346         do {
7347                 struct triple *left, *right;
7348                 int tok, op;
7349                 done = 0;
7350                 switch((tok = peek(state))) {
7351                 case TOK_EQEQ:
7352                 case TOK_NOTEQ:
7353                         left = read_expr(state, def);
7354                         arithmetic(state, left);
7355                         eat(state, tok);
7356                         right = read_expr(state, relational_expr(state));
7357                         arithmetic(state, right);
7358                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7359                         def = triple(state, op, &int_type, left, right);
7360                         break;
7361                 default:
7362                         done = 1;
7363                         break;
7364                 }
7365         } while(!done);
7366         return def;
7367 }
7368
7369 static struct triple *and_expr(struct compile_state *state)
7370 {
7371         struct triple *def;
7372         def = equality_expr(state);
7373         while(peek(state) == TOK_AND) {
7374                 struct triple *left, *right;
7375                 struct type *result_type;
7376                 left = read_expr(state, def);
7377                 integral(state, left);
7378                 eat(state, TOK_AND);
7379                 right = read_expr(state, equality_expr(state));
7380                 integral(state, right);
7381                 result_type = arithmetic_result(state, left, right);
7382                 def = triple(state, OP_AND, result_type, left, right);
7383         }
7384         return def;
7385 }
7386
7387 static struct triple *xor_expr(struct compile_state *state)
7388 {
7389         struct triple *def;
7390         def = and_expr(state);
7391         while(peek(state) == TOK_XOR) {
7392                 struct triple *left, *right;
7393                 struct type *result_type;
7394                 left = read_expr(state, def);
7395                 integral(state, left);
7396                 eat(state, TOK_XOR);
7397                 right = read_expr(state, and_expr(state));
7398                 integral(state, right);
7399                 result_type = arithmetic_result(state, left, right);
7400                 def = triple(state, OP_XOR, result_type, left, right);
7401         }
7402         return def;
7403 }
7404
7405 static struct triple *or_expr(struct compile_state *state)
7406 {
7407         struct triple *def;
7408         def = xor_expr(state);
7409         while(peek(state) == TOK_OR) {
7410                 struct triple *left, *right;
7411                 struct type *result_type;
7412                 left = read_expr(state, def);
7413                 integral(state, left);
7414                 eat(state, TOK_OR);
7415                 right = read_expr(state, xor_expr(state));
7416                 integral(state, right);
7417                 result_type = arithmetic_result(state, left, right);
7418                 def = triple(state, OP_OR, result_type, left, right);
7419         }
7420         return def;
7421 }
7422
7423 static struct triple *land_expr(struct compile_state *state)
7424 {
7425         struct triple *def;
7426         def = or_expr(state);
7427         while(peek(state) == TOK_LOGAND) {
7428                 struct triple *left, *right;
7429                 left = read_expr(state, def);
7430                 bool(state, left);
7431                 eat(state, TOK_LOGAND);
7432                 right = read_expr(state, or_expr(state));
7433                 bool(state, right);
7434
7435                 def = triple(state, OP_LAND, &int_type,
7436                         ltrue_expr(state, left),
7437                         ltrue_expr(state, right));
7438         }
7439         return def;
7440 }
7441
7442 static struct triple *lor_expr(struct compile_state *state)
7443 {
7444         struct triple *def;
7445         def = land_expr(state);
7446         while(peek(state) == TOK_LOGOR) {
7447                 struct triple *left, *right;
7448                 left = read_expr(state, def);
7449                 bool(state, left);
7450                 eat(state, TOK_LOGOR);
7451                 right = read_expr(state, land_expr(state));
7452                 bool(state, right);
7453                 
7454                 def = triple(state, OP_LOR, &int_type,
7455                         ltrue_expr(state, left),
7456                         ltrue_expr(state, right));
7457         }
7458         return def;
7459 }
7460
7461 static struct triple *conditional_expr(struct compile_state *state)
7462 {
7463         struct triple *def;
7464         def = lor_expr(state);
7465         if (peek(state) == TOK_QUEST) {
7466                 struct triple *test, *left, *right;
7467                 bool(state, def);
7468                 test = ltrue_expr(state, read_expr(state, def));
7469                 eat(state, TOK_QUEST);
7470                 left = read_expr(state, expr(state));
7471                 eat(state, TOK_COLON);
7472                 right = read_expr(state, conditional_expr(state));
7473
7474                 def = cond_expr(state, test, left, right);
7475         }
7476         return def;
7477 }
7478
7479 static struct triple *eval_const_expr(
7480         struct compile_state *state, struct triple *expr)
7481 {
7482         struct triple *def;
7483         if (is_const(expr)) {
7484                 def = expr;
7485         } 
7486         else {
7487                 /* If we don't start out as a constant simplify into one */
7488                 struct triple *head, *ptr;
7489                 head = label(state); /* dummy initial triple */
7490                 flatten(state, head, expr);
7491                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7492                         simplify(state, ptr);
7493                 }
7494                 /* Remove the constant value the tail of the list */
7495                 def = head->prev;
7496                 def->prev->next = def->next;
7497                 def->next->prev = def->prev;
7498                 def->next = def->prev = def;
7499                 if (!is_const(def)) {
7500                         error(state, 0, "Not a constant expression");
7501                 }
7502                 /* Free the intermediate expressions */
7503                 while(head->next != head) {
7504                         release_triple(state, head->next);
7505                 }
7506                 free_triple(state, head);
7507         }
7508         return def;
7509 }
7510
7511 static struct triple *constant_expr(struct compile_state *state)
7512 {
7513         return eval_const_expr(state, conditional_expr(state));
7514 }
7515
7516 static struct triple *assignment_expr(struct compile_state *state)
7517 {
7518         struct triple *def, *left, *right;
7519         int tok, op, sign;
7520         /* The C grammer in K&R shows assignment expressions
7521          * only taking unary expressions as input on their
7522          * left hand side.  But specifies the precedence of
7523          * assignemnt as the lowest operator except for comma.
7524          *
7525          * Allowing conditional expressions on the left hand side
7526          * of an assignement results in a grammar that accepts
7527          * a larger set of statements than standard C.   As long
7528          * as the subset of the grammar that is standard C behaves
7529          * correctly this should cause no problems.
7530          * 
7531          * For the extra token strings accepted by the grammar
7532          * none of them should produce a valid lvalue, so they
7533          * should not produce functioning programs.
7534          *
7535          * GCC has this bug as well, so surprises should be minimal.
7536          */
7537         def = conditional_expr(state);
7538         left = def;
7539         switch((tok = peek(state))) {
7540         case TOK_EQ:
7541                 lvalue(state, left);
7542                 eat(state, TOK_EQ);
7543                 def = write_expr(state, left, 
7544                         read_expr(state, assignment_expr(state)));
7545                 break;
7546         case TOK_TIMESEQ:
7547         case TOK_DIVEQ:
7548         case TOK_MODEQ:
7549                 lvalue(state, left);
7550                 arithmetic(state, left);
7551                 eat(state, tok);
7552                 right = read_expr(state, assignment_expr(state));
7553                 arithmetic(state, right);
7554
7555                 sign = is_signed(left->type);
7556                 op = -1;
7557                 switch(tok) {
7558                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7559                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7560                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7561                 }
7562                 def = write_expr(state, left,
7563                         triple(state, op, left->type, 
7564                                 read_expr(state, left), right));
7565                 break;
7566         case TOK_PLUSEQ:
7567                 lvalue(state, left);
7568                 eat(state, TOK_PLUSEQ);
7569                 def = write_expr(state, left,
7570                         mk_add_expr(state, left, assignment_expr(state)));
7571                 break;
7572         case TOK_MINUSEQ:
7573                 lvalue(state, left);
7574                 eat(state, TOK_MINUSEQ);
7575                 def = write_expr(state, left,
7576                         mk_sub_expr(state, left, assignment_expr(state)));
7577                 break;
7578         case TOK_SLEQ:
7579         case TOK_SREQ:
7580         case TOK_ANDEQ:
7581         case TOK_XOREQ:
7582         case TOK_OREQ:
7583                 lvalue(state, left);
7584                 integral(state, left);
7585                 eat(state, tok);
7586                 right = read_expr(state, assignment_expr(state));
7587                 integral(state, right);
7588                 right = integral_promotion(state, right);
7589                 sign = is_signed(left->type);
7590                 op = -1;
7591                 switch(tok) {
7592                 case TOK_SLEQ:  op = OP_SL; break;
7593                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7594                 case TOK_ANDEQ: op = OP_AND; break;
7595                 case TOK_XOREQ: op = OP_XOR; break;
7596                 case TOK_OREQ:  op = OP_OR; break;
7597                 }
7598                 def = write_expr(state, left,
7599                         triple(state, op, left->type, 
7600                                 read_expr(state, left), right));
7601                 break;
7602         }
7603         return def;
7604 }
7605
7606 static struct triple *expr(struct compile_state *state)
7607 {
7608         struct triple *def;
7609         def = assignment_expr(state);
7610         while(peek(state) == TOK_COMMA) {
7611                 struct triple *left, *right;
7612                 left = def;
7613                 eat(state, TOK_COMMA);
7614                 right = assignment_expr(state);
7615                 def = triple(state, OP_COMMA, right->type, left, right);
7616         }
7617         return def;
7618 }
7619
7620 static void expr_statement(struct compile_state *state, struct triple *first)
7621 {
7622         if (peek(state) != TOK_SEMI) {
7623                 flatten(state, first, expr(state));
7624         }
7625         eat(state, TOK_SEMI);
7626 }
7627
7628 static void if_statement(struct compile_state *state, struct triple *first)
7629 {
7630         struct triple *test, *jmp1, *jmp2, *middle, *end;
7631
7632         jmp1 = jmp2 = middle = 0;
7633         eat(state, TOK_IF);
7634         eat(state, TOK_LPAREN);
7635         test = expr(state);
7636         bool(state, test);
7637         /* Cleanup and invert the test */
7638         test = lfalse_expr(state, read_expr(state, test));
7639         eat(state, TOK_RPAREN);
7640         /* Generate the needed pieces */
7641         middle = label(state);
7642         jmp1 = branch(state, middle, test);
7643         /* Thread the pieces together */
7644         flatten(state, first, test);
7645         flatten(state, first, jmp1);
7646         flatten(state, first, label(state));
7647         statement(state, first);
7648         if (peek(state) == TOK_ELSE) {
7649                 eat(state, TOK_ELSE);
7650                 /* Generate the rest of the pieces */
7651                 end = label(state);
7652                 jmp2 = branch(state, end, 0);
7653                 /* Thread them together */
7654                 flatten(state, first, jmp2);
7655                 flatten(state, first, middle);
7656                 statement(state, first);
7657                 flatten(state, first, end);
7658         }
7659         else {
7660                 flatten(state, first, middle);
7661         }
7662 }
7663
7664 static void for_statement(struct compile_state *state, struct triple *first)
7665 {
7666         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7667         struct triple *label1, *label2, *label3;
7668         struct hash_entry *ident;
7669
7670         eat(state, TOK_FOR);
7671         eat(state, TOK_LPAREN);
7672         head = test = tail = jmp1 = jmp2 = 0;
7673         if (peek(state) != TOK_SEMI) {
7674                 head = expr(state);
7675         } 
7676         eat(state, TOK_SEMI);
7677         if (peek(state) != TOK_SEMI) {
7678                 test = expr(state);
7679                 bool(state, test);
7680                 test = ltrue_expr(state, read_expr(state, test));
7681         }
7682         eat(state, TOK_SEMI);
7683         if (peek(state) != TOK_RPAREN) {
7684                 tail = expr(state);
7685         }
7686         eat(state, TOK_RPAREN);
7687         /* Generate the needed pieces */
7688         label1 = label(state);
7689         label2 = label(state);
7690         label3 = label(state);
7691         if (test) {
7692                 jmp1 = branch(state, label3, 0);
7693                 jmp2 = branch(state, label1, test);
7694         }
7695         else {
7696                 jmp2 = branch(state, label1, 0);
7697         }
7698         end = label(state);
7699         /* Remember where break and continue go */
7700         start_scope(state);
7701         ident = state->i_break;
7702         symbol(state, ident, &ident->sym_ident, end, end->type);
7703         ident = state->i_continue;
7704         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7705         /* Now include the body */
7706         flatten(state, first, head);
7707         flatten(state, first, jmp1);
7708         flatten(state, first, label1);
7709         statement(state, first);
7710         flatten(state, first, label2);
7711         flatten(state, first, tail);
7712         flatten(state, first, label3);
7713         flatten(state, first, test);
7714         flatten(state, first, jmp2);
7715         flatten(state, first, end);
7716         /* Cleanup the break/continue scope */
7717         end_scope(state);
7718 }
7719
7720 static void while_statement(struct compile_state *state, struct triple *first)
7721 {
7722         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7723         struct hash_entry *ident;
7724         eat(state, TOK_WHILE);
7725         eat(state, TOK_LPAREN);
7726         test = expr(state);
7727         bool(state, test);
7728         test = ltrue_expr(state, read_expr(state, test));
7729         eat(state, TOK_RPAREN);
7730         /* Generate the needed pieces */
7731         label1 = label(state);
7732         label2 = label(state);
7733         jmp1 = branch(state, label2, 0);
7734         jmp2 = branch(state, label1, test);
7735         end = label(state);
7736         /* Remember where break and continue go */
7737         start_scope(state);
7738         ident = state->i_break;
7739         symbol(state, ident, &ident->sym_ident, end, end->type);
7740         ident = state->i_continue;
7741         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7742         /* Thread them together */
7743         flatten(state, first, jmp1);
7744         flatten(state, first, label1);
7745         statement(state, first);
7746         flatten(state, first, label2);
7747         flatten(state, first, test);
7748         flatten(state, first, jmp2);
7749         flatten(state, first, end);
7750         /* Cleanup the break/continue scope */
7751         end_scope(state);
7752 }
7753
7754 static void do_statement(struct compile_state *state, struct triple *first)
7755 {
7756         struct triple *label1, *label2, *test, *end;
7757         struct hash_entry *ident;
7758         eat(state, TOK_DO);
7759         /* Generate the needed pieces */
7760         label1 = label(state);
7761         label2 = label(state);
7762         end = label(state);
7763         /* Remember where break and continue go */
7764         start_scope(state);
7765         ident = state->i_break;
7766         symbol(state, ident, &ident->sym_ident, end, end->type);
7767         ident = state->i_continue;
7768         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7769         /* Now include the body */
7770         flatten(state, first, label1);
7771         statement(state, first);
7772         /* Cleanup the break/continue scope */
7773         end_scope(state);
7774         /* Eat the rest of the loop */
7775         eat(state, TOK_WHILE);
7776         eat(state, TOK_LPAREN);
7777         test = read_expr(state, expr(state));
7778         bool(state, test);
7779         eat(state, TOK_RPAREN);
7780         eat(state, TOK_SEMI);
7781         /* Thread the pieces together */
7782         test = ltrue_expr(state, test);
7783         flatten(state, first, label2);
7784         flatten(state, first, test);
7785         flatten(state, first, branch(state, label1, test));
7786         flatten(state, first, end);
7787 }
7788
7789
7790 static void return_statement(struct compile_state *state, struct triple *first)
7791 {
7792         struct triple *jmp, *mv, *dest, *var, *val;
7793         int last;
7794         eat(state, TOK_RETURN);
7795
7796 #warning "FIXME implement a more general excess branch elimination"
7797         val = 0;
7798         /* If we have a return value do some more work */
7799         if (peek(state) != TOK_SEMI) {
7800                 val = read_expr(state, expr(state));
7801         }
7802         eat(state, TOK_SEMI);
7803
7804         /* See if this last statement in a function */
7805         last = ((peek(state) == TOK_RBRACE) && 
7806                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7807
7808         /* Find the return variable */
7809         var = MISC(state->main_function, 0);
7810         /* Find the return destination */
7811         dest = RHS(state->main_function, 0)->prev;
7812         mv = jmp = 0;
7813         /* If needed generate a jump instruction */
7814         if (!last) {
7815                 jmp = branch(state, dest, 0);
7816         }
7817         /* If needed generate an assignment instruction */
7818         if (val) {
7819                 mv = write_expr(state, var, val);
7820         }
7821         /* Now put the code together */
7822         if (mv) {
7823                 flatten(state, first, mv);
7824                 flatten(state, first, jmp);
7825         }
7826         else if (jmp) {
7827                 flatten(state, first, jmp);
7828         }
7829 }
7830
7831 static void break_statement(struct compile_state *state, struct triple *first)
7832 {
7833         struct triple *dest;
7834         eat(state, TOK_BREAK);
7835         eat(state, TOK_SEMI);
7836         if (!state->i_break->sym_ident) {
7837                 error(state, 0, "break statement not within loop or switch");
7838         }
7839         dest = state->i_break->sym_ident->def;
7840         flatten(state, first, branch(state, dest, 0));
7841 }
7842
7843 static void continue_statement(struct compile_state *state, struct triple *first)
7844 {
7845         struct triple *dest;
7846         eat(state, TOK_CONTINUE);
7847         eat(state, TOK_SEMI);
7848         if (!state->i_continue->sym_ident) {
7849                 error(state, 0, "continue statement outside of a loop");
7850         }
7851         dest = state->i_continue->sym_ident->def;
7852         flatten(state, first, branch(state, dest, 0));
7853 }
7854
7855 static void goto_statement(struct compile_state *state, struct triple *first)
7856 {
7857         struct hash_entry *ident;
7858         eat(state, TOK_GOTO);
7859         eat(state, TOK_IDENT);
7860         ident = state->token[0].ident;
7861         if (!ident->sym_label) {
7862                 /* If this is a forward branch allocate the label now,
7863                  * it will be flattend in the appropriate location later.
7864                  */
7865                 struct triple *ins;
7866                 ins = label(state);
7867                 label_symbol(state, ident, ins);
7868         }
7869         eat(state, TOK_SEMI);
7870
7871         flatten(state, first, branch(state, ident->sym_label->def, 0));
7872 }
7873
7874 static void labeled_statement(struct compile_state *state, struct triple *first)
7875 {
7876         struct triple *ins;
7877         struct hash_entry *ident;
7878         eat(state, TOK_IDENT);
7879
7880         ident = state->token[0].ident;
7881         if (ident->sym_label && ident->sym_label->def) {
7882                 ins = ident->sym_label->def;
7883                 put_occurance(ins->occurance);
7884                 ins->occurance = new_occurance(state);
7885         }
7886         else {
7887                 ins = label(state);
7888                 label_symbol(state, ident, ins);
7889         }
7890         if (ins->id & TRIPLE_FLAG_FLATTENED) {
7891                 error(state, 0, "label %s already defined", ident->name);
7892         }
7893         flatten(state, first, ins);
7894
7895         eat(state, TOK_COLON);
7896         statement(state, first);
7897 }
7898
7899 static void switch_statement(struct compile_state *state, struct triple *first)
7900 {
7901         FINISHME();
7902         eat(state, TOK_SWITCH);
7903         eat(state, TOK_LPAREN);
7904         expr(state);
7905         eat(state, TOK_RPAREN);
7906         statement(state, first);
7907         error(state, 0, "switch statements are not implemented");
7908         FINISHME();
7909 }
7910
7911 static void case_statement(struct compile_state *state, struct triple *first)
7912 {
7913         FINISHME();
7914         eat(state, TOK_CASE);
7915         constant_expr(state);
7916         eat(state, TOK_COLON);
7917         statement(state, first);
7918         error(state, 0, "case statements are not implemented");
7919         FINISHME();
7920 }
7921
7922 static void default_statement(struct compile_state *state, struct triple *first)
7923 {
7924         FINISHME();
7925         eat(state, TOK_DEFAULT);
7926         eat(state, TOK_COLON);
7927         statement(state, first);
7928         error(state, 0, "default statements are not implemented");
7929         FINISHME();
7930 }
7931
7932 static void asm_statement(struct compile_state *state, struct triple *first)
7933 {
7934         struct asm_info *info;
7935         struct {
7936                 struct triple *constraint;
7937                 struct triple *expr;
7938         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7939         struct triple *def, *asm_str;
7940         int out, in, clobbers, more, colons, i;
7941
7942         eat(state, TOK_ASM);
7943         /* For now ignore the qualifiers */
7944         switch(peek(state)) {
7945         case TOK_CONST:
7946                 eat(state, TOK_CONST);
7947                 break;
7948         case TOK_VOLATILE:
7949                 eat(state, TOK_VOLATILE);
7950                 break;
7951         }
7952         eat(state, TOK_LPAREN);
7953         asm_str = string_constant(state);
7954
7955         colons = 0;
7956         out = in = clobbers = 0;
7957         /* Outputs */
7958         if ((colons == 0) && (peek(state) == TOK_COLON)) {
7959                 eat(state, TOK_COLON);
7960                 colons++;
7961                 more = (peek(state) == TOK_LIT_STRING);
7962                 while(more) {
7963                         struct triple *var;
7964                         struct triple *constraint;
7965                         char *str;
7966                         more = 0;
7967                         if (out > MAX_LHS) {
7968                                 error(state, 0, "Maximum output count exceeded.");
7969                         }
7970                         constraint = string_constant(state);
7971                         str = constraint->u.blob;
7972                         if (str[0] != '=') {
7973                                 error(state, 0, "Output constraint does not start with =");
7974                         }
7975                         constraint->u.blob = str + 1;
7976                         eat(state, TOK_LPAREN);
7977                         var = conditional_expr(state);
7978                         eat(state, TOK_RPAREN);
7979
7980                         lvalue(state, var);
7981                         out_param[out].constraint = constraint;
7982                         out_param[out].expr       = var;
7983                         if (peek(state) == TOK_COMMA) {
7984                                 eat(state, TOK_COMMA);
7985                                 more = 1;
7986                         }
7987                         out++;
7988                 }
7989         }
7990         /* Inputs */
7991         if ((colons == 1) && (peek(state) == TOK_COLON)) {
7992                 eat(state, TOK_COLON);
7993                 colons++;
7994                 more = (peek(state) == TOK_LIT_STRING);
7995                 while(more) {
7996                         struct triple *val;
7997                         struct triple *constraint;
7998                         char *str;
7999                         more = 0;
8000                         if (in > MAX_RHS) {
8001                                 error(state, 0, "Maximum input count exceeded.");
8002                         }
8003                         constraint = string_constant(state);
8004                         str = constraint->u.blob;
8005                         if (digitp(str[0] && str[1] == '\0')) {
8006                                 int val;
8007                                 val = digval(str[0]);
8008                                 if ((val < 0) || (val >= out)) {
8009                                         error(state, 0, "Invalid input constraint %d", val);
8010                                 }
8011                         }
8012                         eat(state, TOK_LPAREN);
8013                         val = conditional_expr(state);
8014                         eat(state, TOK_RPAREN);
8015
8016                         in_param[in].constraint = constraint;
8017                         in_param[in].expr       = val;
8018                         if (peek(state) == TOK_COMMA) {
8019                                 eat(state, TOK_COMMA);
8020                                 more = 1;
8021                         }
8022                         in++;
8023                 }
8024         }
8025
8026         /* Clobber */
8027         if ((colons == 2) && (peek(state) == TOK_COLON)) {
8028                 eat(state, TOK_COLON);
8029                 colons++;
8030                 more = (peek(state) == TOK_LIT_STRING);
8031                 while(more) {
8032                         struct triple *clobber;
8033                         more = 0;
8034                         if ((clobbers + out) > MAX_LHS) {
8035                                 error(state, 0, "Maximum clobber limit exceeded.");
8036                         }
8037                         clobber = string_constant(state);
8038                         eat(state, TOK_RPAREN);
8039
8040                         clob_param[clobbers].constraint = clobber;
8041                         if (peek(state) == TOK_COMMA) {
8042                                 eat(state, TOK_COMMA);
8043                                 more = 1;
8044                         }
8045                         clobbers++;
8046                 }
8047         }
8048         eat(state, TOK_RPAREN);
8049         eat(state, TOK_SEMI);
8050
8051
8052         info = xcmalloc(sizeof(*info), "asm_info");
8053         info->str = asm_str->u.blob;
8054         free_triple(state, asm_str);
8055
8056         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8057         def->u.ainfo = info;
8058
8059         /* Find the register constraints */
8060         for(i = 0; i < out; i++) {
8061                 struct triple *constraint;
8062                 constraint = out_param[i].constraint;
8063                 info->tmpl.lhs[i] = arch_reg_constraint(state, 
8064                         out_param[i].expr->type, constraint->u.blob);
8065                 free_triple(state, constraint);
8066         }
8067         for(; i - out < clobbers; i++) {
8068                 struct triple *constraint;
8069                 constraint = clob_param[i - out].constraint;
8070                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8071                 free_triple(state, constraint);
8072         }
8073         for(i = 0; i < in; i++) {
8074                 struct triple *constraint;
8075                 const char *str;
8076                 constraint = in_param[i].constraint;
8077                 str = constraint->u.blob;
8078                 if (digitp(str[0]) && str[1] == '\0') {
8079                         struct reg_info cinfo;
8080                         int val;
8081                         val = digval(str[0]);
8082                         cinfo.reg = info->tmpl.lhs[val].reg;
8083                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8084                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
8085                         if (cinfo.reg == REG_UNSET) {
8086                                 cinfo.reg = REG_VIRT0 + val;
8087                         }
8088                         if (cinfo.regcm == 0) {
8089                                 error(state, 0, "No registers for %d", val);
8090                         }
8091                         info->tmpl.lhs[val] = cinfo;
8092                         info->tmpl.rhs[i]   = cinfo;
8093                                 
8094                 } else {
8095                         info->tmpl.rhs[i] = arch_reg_constraint(state, 
8096                                 in_param[i].expr->type, str);
8097                 }
8098                 free_triple(state, constraint);
8099         }
8100
8101         /* Now build the helper expressions */
8102         for(i = 0; i < in; i++) {
8103                 RHS(def, i) = read_expr(state,in_param[i].expr);
8104         }
8105         flatten(state, first, def);
8106         for(i = 0; i < out; i++) {
8107                 struct triple *piece;
8108                 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8109                 piece->u.cval = i;
8110                 LHS(def, i) = piece;
8111                 flatten(state, first,
8112                         write_expr(state, out_param[i].expr, piece));
8113         }
8114         for(; i - out < clobbers; i++) {
8115                 struct triple *piece;
8116                 piece = triple(state, OP_PIECE, &void_type, def, 0);
8117                 piece->u.cval = i;
8118                 LHS(def, i) = piece;
8119                 flatten(state, first, piece);
8120         }
8121 }
8122
8123
8124 static int isdecl(int tok)
8125 {
8126         switch(tok) {
8127         case TOK_AUTO:
8128         case TOK_REGISTER:
8129         case TOK_STATIC:
8130         case TOK_EXTERN:
8131         case TOK_TYPEDEF:
8132         case TOK_CONST:
8133         case TOK_RESTRICT:
8134         case TOK_VOLATILE:
8135         case TOK_VOID:
8136         case TOK_CHAR:
8137         case TOK_SHORT:
8138         case TOK_INT:
8139         case TOK_LONG:
8140         case TOK_FLOAT:
8141         case TOK_DOUBLE:
8142         case TOK_SIGNED:
8143         case TOK_UNSIGNED:
8144         case TOK_STRUCT:
8145         case TOK_UNION:
8146         case TOK_ENUM:
8147         case TOK_TYPE_NAME: /* typedef name */
8148                 return 1;
8149         default:
8150                 return 0;
8151         }
8152 }
8153
8154 static void compound_statement(struct compile_state *state, struct triple *first)
8155 {
8156         eat(state, TOK_LBRACE);
8157         start_scope(state);
8158
8159         /* statement-list opt */
8160         while (peek(state) != TOK_RBRACE) {
8161                 statement(state, first);
8162         }
8163         end_scope(state);
8164         eat(state, TOK_RBRACE);
8165 }
8166
8167 static void statement(struct compile_state *state, struct triple *first)
8168 {
8169         int tok;
8170         tok = peek(state);
8171         if (tok == TOK_LBRACE) {
8172                 compound_statement(state, first);
8173         }
8174         else if (tok == TOK_IF) {
8175                 if_statement(state, first); 
8176         }
8177         else if (tok == TOK_FOR) {
8178                 for_statement(state, first);
8179         }
8180         else if (tok == TOK_WHILE) {
8181                 while_statement(state, first);
8182         }
8183         else if (tok == TOK_DO) {
8184                 do_statement(state, first);
8185         }
8186         else if (tok == TOK_RETURN) {
8187                 return_statement(state, first);
8188         }
8189         else if (tok == TOK_BREAK) {
8190                 break_statement(state, first);
8191         }
8192         else if (tok == TOK_CONTINUE) {
8193                 continue_statement(state, first);
8194         }
8195         else if (tok == TOK_GOTO) {
8196                 goto_statement(state, first);
8197         }
8198         else if (tok == TOK_SWITCH) {
8199                 switch_statement(state, first);
8200         }
8201         else if (tok == TOK_ASM) {
8202                 asm_statement(state, first);
8203         }
8204         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8205                 labeled_statement(state, first); 
8206         }
8207         else if (tok == TOK_CASE) {
8208                 case_statement(state, first);
8209         }
8210         else if (tok == TOK_DEFAULT) {
8211                 default_statement(state, first);
8212         }
8213         else if (isdecl(tok)) {
8214                 /* This handles C99 intermixing of statements and decls */
8215                 decl(state, first);
8216         }
8217         else {
8218                 expr_statement(state, first);
8219         }
8220 }
8221
8222 static struct type *param_decl(struct compile_state *state)
8223 {
8224         struct type *type;
8225         struct hash_entry *ident;
8226         /* Cheat so the declarator will know we are not global */
8227         start_scope(state); 
8228         ident = 0;
8229         type = decl_specifiers(state);
8230         type = declarator(state, type, &ident, 0);
8231         type->field_ident = ident;
8232         end_scope(state);
8233         return type;
8234 }
8235
8236 static struct type *param_type_list(struct compile_state *state, struct type *type)
8237 {
8238         struct type *ftype, **next;
8239         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8240         next = &ftype->right;
8241         while(peek(state) == TOK_COMMA) {
8242                 eat(state, TOK_COMMA);
8243                 if (peek(state) == TOK_DOTS) {
8244                         eat(state, TOK_DOTS);
8245                         error(state, 0, "variadic functions not supported");
8246                 }
8247                 else {
8248                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8249                         next = &((*next)->right);
8250                 }
8251         }
8252         return ftype;
8253 }
8254
8255
8256 static struct type *type_name(struct compile_state *state)
8257 {
8258         struct type *type;
8259         type = specifier_qualifier_list(state);
8260         /* abstract-declarator (may consume no tokens) */
8261         type = declarator(state, type, 0, 0);
8262         return type;
8263 }
8264
8265 static struct type *direct_declarator(
8266         struct compile_state *state, struct type *type, 
8267         struct hash_entry **ident, int need_ident)
8268 {
8269         struct type *outer;
8270         int op;
8271         outer = 0;
8272         arrays_complete(state, type);
8273         switch(peek(state)) {
8274         case TOK_IDENT:
8275                 eat(state, TOK_IDENT);
8276                 if (!ident) {
8277                         error(state, 0, "Unexpected identifier found");
8278                 }
8279                 /* The name of what we are declaring */
8280                 *ident = state->token[0].ident;
8281                 break;
8282         case TOK_LPAREN:
8283                 eat(state, TOK_LPAREN);
8284                 outer = declarator(state, type, ident, need_ident);
8285                 eat(state, TOK_RPAREN);
8286                 break;
8287         default:
8288                 if (need_ident) {
8289                         error(state, 0, "Identifier expected");
8290                 }
8291                 break;
8292         }
8293         do {
8294                 op = 1;
8295                 arrays_complete(state, type);
8296                 switch(peek(state)) {
8297                 case TOK_LPAREN:
8298                         eat(state, TOK_LPAREN);
8299                         type = param_type_list(state, type);
8300                         eat(state, TOK_RPAREN);
8301                         break;
8302                 case TOK_LBRACKET:
8303                 {
8304                         unsigned int qualifiers;
8305                         struct triple *value;
8306                         value = 0;
8307                         eat(state, TOK_LBRACKET);
8308                         if (peek(state) != TOK_RBRACKET) {
8309                                 value = constant_expr(state);
8310                                 integral(state, value);
8311                         }
8312                         eat(state, TOK_RBRACKET);
8313
8314                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8315                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8316                         if (value) {
8317                                 type->elements = value->u.cval;
8318                                 free_triple(state, value);
8319                         } else {
8320                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8321                                 op = 0;
8322                         }
8323                 }
8324                         break;
8325                 default:
8326                         op = 0;
8327                         break;
8328                 }
8329         } while(op);
8330         if (outer) {
8331                 struct type *inner;
8332                 arrays_complete(state, type);
8333                 FINISHME();
8334                 for(inner = outer; inner->left; inner = inner->left)
8335                         ;
8336                 inner->left = type;
8337                 type = outer;
8338         }
8339         return type;
8340 }
8341
8342 static struct type *declarator(
8343         struct compile_state *state, struct type *type, 
8344         struct hash_entry **ident, int need_ident)
8345 {
8346         while(peek(state) == TOK_STAR) {
8347                 eat(state, TOK_STAR);
8348                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8349         }
8350         type = direct_declarator(state, type, ident, need_ident);
8351         return type;
8352 }
8353
8354
8355 static struct type *typedef_name(
8356         struct compile_state *state, unsigned int specifiers)
8357 {
8358         struct hash_entry *ident;
8359         struct type *type;
8360         eat(state, TOK_TYPE_NAME);
8361         ident = state->token[0].ident;
8362         type = ident->sym_ident->type;
8363         specifiers |= type->type & QUAL_MASK;
8364         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
8365                 (type->type & (STOR_MASK | QUAL_MASK))) {
8366                 type = clone_type(specifiers, type);
8367         }
8368         return type;
8369 }
8370
8371 static struct type *enum_specifier(
8372         struct compile_state *state, unsigned int specifiers)
8373 {
8374         int tok;
8375         struct type *type;
8376         type = 0;
8377         FINISHME();
8378         eat(state, TOK_ENUM);
8379         tok = peek(state);
8380         if (tok == TOK_IDENT) {
8381                 eat(state, TOK_IDENT);
8382         }
8383         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8384                 eat(state, TOK_LBRACE);
8385                 do {
8386                         eat(state, TOK_IDENT);
8387                         if (peek(state) == TOK_EQ) {
8388                                 eat(state, TOK_EQ);
8389                                 constant_expr(state);
8390                         }
8391                         if (peek(state) == TOK_COMMA) {
8392                                 eat(state, TOK_COMMA);
8393                         }
8394                 } while(peek(state) != TOK_RBRACE);
8395                 eat(state, TOK_RBRACE);
8396         }
8397         FINISHME();
8398         return type;
8399 }
8400
8401 #if 0
8402 static struct type *struct_declarator(
8403         struct compile_state *state, struct type *type, struct hash_entry **ident)
8404 {
8405         int tok;
8406 #warning "struct_declarator is complicated because of bitfields, kill them?"
8407         tok = peek(state);
8408         if (tok != TOK_COLON) {
8409                 type = declarator(state, type, ident, 1);
8410         }
8411         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8412                 eat(state, TOK_COLON);
8413                 constant_expr(state);
8414         }
8415         FINISHME();
8416         return type;
8417 }
8418 #endif
8419
8420 static struct type *struct_or_union_specifier(
8421         struct compile_state *state, unsigned int spec)
8422 {
8423         struct type *struct_type;
8424         struct hash_entry *ident;
8425         unsigned int type_join;
8426         int tok;
8427         struct_type = 0;
8428         ident = 0;
8429         switch(peek(state)) {
8430         case TOK_STRUCT:
8431                 eat(state, TOK_STRUCT);
8432                 type_join = TYPE_PRODUCT;
8433                 break;
8434         case TOK_UNION:
8435                 eat(state, TOK_UNION);
8436                 type_join = TYPE_OVERLAP;
8437                 error(state, 0, "unions not yet supported\n");
8438                 break;
8439         default:
8440                 eat(state, TOK_STRUCT);
8441                 type_join = TYPE_PRODUCT;
8442                 break;
8443         }
8444         tok = peek(state);
8445         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8446                 eat(state, tok);
8447                 ident = state->token[0].ident;
8448         }
8449         if (!ident || (peek(state) == TOK_LBRACE)) {
8450                 ulong_t elements;
8451                 struct type **next;
8452                 elements = 0;
8453                 eat(state, TOK_LBRACE);
8454                 next = &struct_type;
8455                 do {
8456                         struct type *base_type;
8457                         int done;
8458                         base_type = specifier_qualifier_list(state);
8459                         do {
8460                                 struct type *type;
8461                                 struct hash_entry *fident;
8462                                 done = 1;
8463                                 type = declarator(state, base_type, &fident, 1);
8464                                 elements++;
8465                                 if (peek(state) == TOK_COMMA) {
8466                                         done = 0;
8467                                         eat(state, TOK_COMMA);
8468                                 }
8469                                 type = clone_type(0, type);
8470                                 type->field_ident = fident;
8471                                 if (*next) {
8472                                         *next = new_type(type_join, *next, type);
8473                                         next = &((*next)->right);
8474                                 } else {
8475                                         *next = type;
8476                                 }
8477                         } while(!done);
8478                         eat(state, TOK_SEMI);
8479                 } while(peek(state) != TOK_RBRACE);
8480                 eat(state, TOK_RBRACE);
8481                 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8482                 struct_type->type_ident = ident;
8483                 struct_type->elements = elements;
8484                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8485         }
8486         if (ident && ident->sym_struct) {
8487                 struct_type = clone_type(spec,  ident->sym_struct->type);
8488         }
8489         else if (ident && !ident->sym_struct) {
8490                 error(state, 0, "struct %s undeclared", ident->name);
8491         }
8492         return struct_type;
8493 }
8494
8495 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8496 {
8497         unsigned int specifiers;
8498         switch(peek(state)) {
8499         case TOK_AUTO:
8500                 eat(state, TOK_AUTO);
8501                 specifiers = STOR_AUTO;
8502                 break;
8503         case TOK_REGISTER:
8504                 eat(state, TOK_REGISTER);
8505                 specifiers = STOR_REGISTER;
8506                 break;
8507         case TOK_STATIC:
8508                 eat(state, TOK_STATIC);
8509                 specifiers = STOR_STATIC;
8510                 break;
8511         case TOK_EXTERN:
8512                 eat(state, TOK_EXTERN);
8513                 specifiers = STOR_EXTERN;
8514                 break;
8515         case TOK_TYPEDEF:
8516                 eat(state, TOK_TYPEDEF);
8517                 specifiers = STOR_TYPEDEF;
8518                 break;
8519         default:
8520                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8521                         specifiers = STOR_STATIC;
8522                 }
8523                 else {
8524                         specifiers = STOR_AUTO;
8525                 }
8526         }
8527         return specifiers;
8528 }
8529
8530 static unsigned int function_specifier_opt(struct compile_state *state)
8531 {
8532         /* Ignore the inline keyword */
8533         unsigned int specifiers;
8534         specifiers = 0;
8535         switch(peek(state)) {
8536         case TOK_INLINE:
8537                 eat(state, TOK_INLINE);
8538                 specifiers = STOR_INLINE;
8539         }
8540         return specifiers;
8541 }
8542
8543 static unsigned int type_qualifiers(struct compile_state *state)
8544 {
8545         unsigned int specifiers;
8546         int done;
8547         done = 0;
8548         specifiers = QUAL_NONE;
8549         do {
8550                 switch(peek(state)) {
8551                 case TOK_CONST:
8552                         eat(state, TOK_CONST);
8553                         specifiers = QUAL_CONST;
8554                         break;
8555                 case TOK_VOLATILE:
8556                         eat(state, TOK_VOLATILE);
8557                         specifiers = QUAL_VOLATILE;
8558                         break;
8559                 case TOK_RESTRICT:
8560                         eat(state, TOK_RESTRICT);
8561                         specifiers = QUAL_RESTRICT;
8562                         break;
8563                 default:
8564                         done = 1;
8565                         break;
8566                 }
8567         } while(!done);
8568         return specifiers;
8569 }
8570
8571 static struct type *type_specifier(
8572         struct compile_state *state, unsigned int spec)
8573 {
8574         struct type *type;
8575         type = 0;
8576         switch(peek(state)) {
8577         case TOK_VOID:
8578                 eat(state, TOK_VOID);
8579                 type = new_type(TYPE_VOID | spec, 0, 0);
8580                 break;
8581         case TOK_CHAR:
8582                 eat(state, TOK_CHAR);
8583                 type = new_type(TYPE_CHAR | spec, 0, 0);
8584                 break;
8585         case TOK_SHORT:
8586                 eat(state, TOK_SHORT);
8587                 if (peek(state) == TOK_INT) {
8588                         eat(state, TOK_INT);
8589                 }
8590                 type = new_type(TYPE_SHORT | spec, 0, 0);
8591                 break;
8592         case TOK_INT:
8593                 eat(state, TOK_INT);
8594                 type = new_type(TYPE_INT | spec, 0, 0);
8595                 break;
8596         case TOK_LONG:
8597                 eat(state, TOK_LONG);
8598                 switch(peek(state)) {
8599                 case TOK_LONG:
8600                         eat(state, TOK_LONG);
8601                         error(state, 0, "long long not supported");
8602                         break;
8603                 case TOK_DOUBLE:
8604                         eat(state, TOK_DOUBLE);
8605                         error(state, 0, "long double not supported");
8606                         break;
8607                 case TOK_INT:
8608                         eat(state, TOK_INT);
8609                         type = new_type(TYPE_LONG | spec, 0, 0);
8610                         break;
8611                 default:
8612                         type = new_type(TYPE_LONG | spec, 0, 0);
8613                         break;
8614                 }
8615                 break;
8616         case TOK_FLOAT:
8617                 eat(state, TOK_FLOAT);
8618                 error(state, 0, "type float not supported");
8619                 break;
8620         case TOK_DOUBLE:
8621                 eat(state, TOK_DOUBLE);
8622                 error(state, 0, "type double not supported");
8623                 break;
8624         case TOK_SIGNED:
8625                 eat(state, TOK_SIGNED);
8626                 switch(peek(state)) {
8627                 case TOK_LONG:
8628                         eat(state, TOK_LONG);
8629                         switch(peek(state)) {
8630                         case TOK_LONG:
8631                                 eat(state, TOK_LONG);
8632                                 error(state, 0, "type long long not supported");
8633                                 break;
8634                         case TOK_INT:
8635                                 eat(state, TOK_INT);
8636                                 type = new_type(TYPE_LONG | spec, 0, 0);
8637                                 break;
8638                         default:
8639                                 type = new_type(TYPE_LONG | spec, 0, 0);
8640                                 break;
8641                         }
8642                         break;
8643                 case TOK_INT:
8644                         eat(state, TOK_INT);
8645                         type = new_type(TYPE_INT | spec, 0, 0);
8646                         break;
8647                 case TOK_SHORT:
8648                         eat(state, TOK_SHORT);
8649                         type = new_type(TYPE_SHORT | spec, 0, 0);
8650                         break;
8651                 case TOK_CHAR:
8652                         eat(state, TOK_CHAR);
8653                         type = new_type(TYPE_CHAR | spec, 0, 0);
8654                         break;
8655                 default:
8656                         type = new_type(TYPE_INT | spec, 0, 0);
8657                         break;
8658                 }
8659                 break;
8660         case TOK_UNSIGNED:
8661                 eat(state, TOK_UNSIGNED);
8662                 switch(peek(state)) {
8663                 case TOK_LONG:
8664                         eat(state, TOK_LONG);
8665                         switch(peek(state)) {
8666                         case TOK_LONG:
8667                                 eat(state, TOK_LONG);
8668                                 error(state, 0, "unsigned long long not supported");
8669                                 break;
8670                         case TOK_INT:
8671                                 eat(state, TOK_INT);
8672                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8673                                 break;
8674                         default:
8675                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8676                                 break;
8677                         }
8678                         break;
8679                 case TOK_INT:
8680                         eat(state, TOK_INT);
8681                         type = new_type(TYPE_UINT | spec, 0, 0);
8682                         break;
8683                 case TOK_SHORT:
8684                         eat(state, TOK_SHORT);
8685                         type = new_type(TYPE_USHORT | spec, 0, 0);
8686                         break;
8687                 case TOK_CHAR:
8688                         eat(state, TOK_CHAR);
8689                         type = new_type(TYPE_UCHAR | spec, 0, 0);
8690                         break;
8691                 default:
8692                         type = new_type(TYPE_UINT | spec, 0, 0);
8693                         break;
8694                 }
8695                 break;
8696                 /* struct or union specifier */
8697         case TOK_STRUCT:
8698         case TOK_UNION:
8699                 type = struct_or_union_specifier(state, spec);
8700                 break;
8701                 /* enum-spefifier */
8702         case TOK_ENUM:
8703                 type = enum_specifier(state, spec);
8704                 break;
8705                 /* typedef name */
8706         case TOK_TYPE_NAME:
8707                 type = typedef_name(state, spec);
8708                 break;
8709         default:
8710                 error(state, 0, "bad type specifier %s", 
8711                         tokens[peek(state)]);
8712                 break;
8713         }
8714         return type;
8715 }
8716
8717 static int istype(int tok)
8718 {
8719         switch(tok) {
8720         case TOK_CONST:
8721         case TOK_RESTRICT:
8722         case TOK_VOLATILE:
8723         case TOK_VOID:
8724         case TOK_CHAR:
8725         case TOK_SHORT:
8726         case TOK_INT:
8727         case TOK_LONG:
8728         case TOK_FLOAT:
8729         case TOK_DOUBLE:
8730         case TOK_SIGNED:
8731         case TOK_UNSIGNED:
8732         case TOK_STRUCT:
8733         case TOK_UNION:
8734         case TOK_ENUM:
8735         case TOK_TYPE_NAME:
8736                 return 1;
8737         default:
8738                 return 0;
8739         }
8740 }
8741
8742
8743 static struct type *specifier_qualifier_list(struct compile_state *state)
8744 {
8745         struct type *type;
8746         unsigned int specifiers = 0;
8747
8748         /* type qualifiers */
8749         specifiers |= type_qualifiers(state);
8750
8751         /* type specifier */
8752         type = type_specifier(state, specifiers);
8753
8754         return type;
8755 }
8756
8757 static int isdecl_specifier(int tok)
8758 {
8759         switch(tok) {
8760                 /* storage class specifier */
8761         case TOK_AUTO:
8762         case TOK_REGISTER:
8763         case TOK_STATIC:
8764         case TOK_EXTERN:
8765         case TOK_TYPEDEF:
8766                 /* type qualifier */
8767         case TOK_CONST:
8768         case TOK_RESTRICT:
8769         case TOK_VOLATILE:
8770                 /* type specifiers */
8771         case TOK_VOID:
8772         case TOK_CHAR:
8773         case TOK_SHORT:
8774         case TOK_INT:
8775         case TOK_LONG:
8776         case TOK_FLOAT:
8777         case TOK_DOUBLE:
8778         case TOK_SIGNED:
8779         case TOK_UNSIGNED:
8780                 /* struct or union specifier */
8781         case TOK_STRUCT:
8782         case TOK_UNION:
8783                 /* enum-spefifier */
8784         case TOK_ENUM:
8785                 /* typedef name */
8786         case TOK_TYPE_NAME:
8787                 /* function specifiers */
8788         case TOK_INLINE:
8789                 return 1;
8790         default:
8791                 return 0;
8792         }
8793 }
8794
8795 static struct type *decl_specifiers(struct compile_state *state)
8796 {
8797         struct type *type;
8798         unsigned int specifiers;
8799         /* I am overly restrictive in the arragement of specifiers supported.
8800          * C is overly flexible in this department it makes interpreting
8801          * the parse tree difficult.
8802          */
8803         specifiers = 0;
8804
8805         /* storage class specifier */
8806         specifiers |= storage_class_specifier_opt(state);
8807
8808         /* function-specifier */
8809         specifiers |= function_specifier_opt(state);
8810
8811         /* type qualifier */
8812         specifiers |= type_qualifiers(state);
8813
8814         /* type specifier */
8815         type = type_specifier(state, specifiers);
8816         return type;
8817 }
8818
8819 struct field_info {
8820         struct type *type;
8821         size_t offset;
8822 };
8823
8824 static struct field_info designator(struct compile_state *state, struct type *type)
8825 {
8826         int tok;
8827         struct field_info info;
8828         info.offset = ~0U;
8829         info.type = 0;
8830         do {
8831                 switch(peek(state)) {
8832                 case TOK_LBRACKET:
8833                 {
8834                         struct triple *value;
8835                         if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
8836                                 error(state, 0, "Array designator not in array initializer");
8837                         }
8838                         eat(state, TOK_LBRACKET);
8839                         value = constant_expr(state);
8840                         eat(state, TOK_RBRACKET);
8841
8842                         info.type = type->left;
8843                         info.offset = value->u.cval * size_of(state, info.type);
8844                         break;
8845                 }
8846                 case TOK_DOT:
8847                 {
8848                         struct hash_entry *field;
8849                         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
8850                                 error(state, 0, "Struct designator not in struct initializer");
8851                         }
8852                         eat(state, TOK_DOT);
8853                         eat(state, TOK_IDENT);
8854                         field = state->token[0].ident;
8855                         info.offset = field_offset(state, type, field);
8856                         info.type   = field_type(state, type, field);
8857                         break;
8858                 }
8859                 default:
8860                         error(state, 0, "Invalid designator");
8861                 }
8862                 tok = peek(state);
8863         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8864         eat(state, TOK_EQ);
8865         return info;
8866 }
8867
8868 static struct triple *initializer(
8869         struct compile_state *state, struct type *type)
8870 {
8871         struct triple *result;
8872         if (peek(state) != TOK_LBRACE) {
8873                 result = assignment_expr(state);
8874         }
8875         else {
8876                 int comma;
8877                 size_t max_offset;
8878                 struct field_info info;
8879                 void *buf;
8880                 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
8881                         ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
8882                         internal_error(state, 0, "unknown initializer type");
8883                 }
8884                 info.offset = 0;
8885                 info.type = type->left;
8886                 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8887                         info.type = next_field(state, type, 0);
8888                 }
8889                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8890                         max_offset = 0;
8891                 } else {
8892                         max_offset = size_of(state, type);
8893                 }
8894                 buf = xcmalloc(max_offset, "initializer");
8895                 eat(state, TOK_LBRACE);
8896                 do {
8897                         struct triple *value;
8898                         struct type *value_type;
8899                         size_t value_size;
8900                         void *dest;
8901                         int tok;
8902                         comma = 0;
8903                         tok = peek(state);
8904                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8905                                 info = designator(state, type);
8906                         }
8907                         if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
8908                                 (info.offset >= max_offset)) {
8909                                 error(state, 0, "element beyond bounds");
8910                         }
8911                         value_type = info.type;
8912                         value = eval_const_expr(state, initializer(state, value_type));
8913                         value_size = size_of(state, value_type);
8914                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8915                                 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8916                                 (max_offset <= info.offset)) {
8917                                 void *old_buf;
8918                                 size_t old_size;
8919                                 old_buf = buf;
8920                                 old_size = max_offset;
8921                                 max_offset = info.offset + value_size;
8922                                 buf = xmalloc(max_offset, "initializer");
8923                                 memcpy(buf, old_buf, old_size);
8924                                 xfree(old_buf);
8925                         }
8926                         dest = ((char *)buf) + info.offset;
8927                         if (value->op == OP_BLOBCONST) {
8928                                 memcpy(dest, value->u.blob, value_size);
8929                         }
8930                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8931                                 *((uint8_t *)dest) = value->u.cval & 0xff;
8932                         }
8933                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8934                                 *((uint16_t *)dest) = value->u.cval & 0xffff;
8935                         }
8936                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8937                                 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
8938                         }
8939                         else {
8940                                 internal_error(state, 0, "unhandled constant initializer");
8941                         }
8942                         free_triple(state, value);
8943                         if (peek(state) == TOK_COMMA) {
8944                                 eat(state, TOK_COMMA);
8945                                 comma = 1;
8946                         }
8947                         info.offset += value_size;
8948                         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
8949                                 info.type = next_field(state, type, info.type);
8950                                 info.offset = field_offset(state, type, 
8951                                         info.type->field_ident);
8952                         }
8953                 } while(comma && (peek(state) != TOK_RBRACE));
8954                 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
8955                         ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
8956                         type->elements = max_offset / size_of(state, type->left);
8957                 }
8958                 eat(state, TOK_RBRACE);
8959                 result = triple(state, OP_BLOBCONST, type, 0, 0);
8960                 result->u.blob = buf;
8961         }
8962         return result;
8963 }
8964
8965 static void resolve_branches(struct compile_state *state)
8966 {
8967         /* Make a second pass and finish anything outstanding
8968          * with respect to branches.  The only outstanding item
8969          * is to see if there are goto to labels that have not
8970          * been defined and to error about them.
8971          */
8972         int i;
8973         for(i = 0; i < HASH_TABLE_SIZE; i++) {
8974                 struct hash_entry *entry;
8975                 for(entry = state->hash_table[i]; entry; entry = entry->next) {
8976                         struct triple *ins;
8977                         if (!entry->sym_label) {
8978                                 continue;
8979                         }
8980                         ins = entry->sym_label->def;
8981                         if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
8982                                 error(state, ins, "label `%s' used but not defined",
8983                                         entry->name);
8984                         }
8985                 }
8986         }
8987 }
8988
8989 static struct triple *function_definition(
8990         struct compile_state *state, struct type *type)
8991 {
8992         struct triple *def, *tmp, *first, *end;
8993         struct hash_entry *ident;
8994         struct type *param;
8995         int i;
8996         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8997                 error(state, 0, "Invalid function header");
8998         }
8999
9000         /* Verify the function type */
9001         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
9002                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
9003                 (type->right->field_ident == 0)) {
9004                 error(state, 0, "Invalid function parameters");
9005         }
9006         param = type->right;
9007         i = 0;
9008         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9009                 i++;
9010                 if (!param->left->field_ident) {
9011                         error(state, 0, "No identifier for parameter %d\n", i);
9012                 }
9013                 param = param->right;
9014         }
9015         i++;
9016         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9017                 error(state, 0, "No identifier for paramter %d\n", i);
9018         }
9019         
9020         /* Get a list of statements for this function. */
9021         def = triple(state, OP_LIST, type, 0, 0);
9022
9023         /* Start a new scope for the passed parameters */
9024         start_scope(state);
9025
9026         /* Put a label at the very start of a function */
9027         first = label(state);
9028         RHS(def, 0) = first;
9029
9030         /* Put a label at the very end of a function */
9031         end = label(state);
9032         flatten(state, first, end);
9033
9034         /* Walk through the parameters and create symbol table entries
9035          * for them.
9036          */
9037         param = type->right;
9038         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9039                 ident = param->left->field_ident;
9040                 tmp = variable(state, param->left);
9041                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9042                 flatten(state, end, tmp);
9043                 param = param->right;
9044         }
9045         if ((param->type & TYPE_MASK) != TYPE_VOID) {
9046                 /* And don't forget the last parameter */
9047                 ident = param->field_ident;
9048                 tmp = variable(state, param);
9049                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9050                 flatten(state, end, tmp);
9051         }
9052         /* Add a variable for the return value */
9053         MISC(def, 0) = 0;
9054         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9055                 /* Remove all type qualifiers from the return type */
9056                 tmp = variable(state, clone_type(0, type->left));
9057                 flatten(state, end, tmp);
9058                 /* Remember where the return value is */
9059                 MISC(def, 0) = tmp;
9060         }
9061
9062         /* Remember which function I am compiling.
9063          * Also assume the last defined function is the main function.
9064          */
9065         state->main_function = def;
9066
9067         /* Now get the actual function definition */
9068         compound_statement(state, end);
9069
9070         /* Finish anything unfinished with branches */
9071         resolve_branches(state);
9072
9073         /* Remove the parameter scope */
9074         end_scope(state);
9075
9076 #if 0
9077         fprintf(stdout, "\n");
9078         loc(stdout, state, 0);
9079         fprintf(stdout, "\n__________ function_definition _________\n");
9080         print_triple(state, def);
9081         fprintf(stdout, "__________ function_definition _________ done\n\n");
9082 #endif
9083
9084         return def;
9085 }
9086
9087 static struct triple *do_decl(struct compile_state *state, 
9088         struct type *type, struct hash_entry *ident)
9089 {
9090         struct triple *def;
9091         def = 0;
9092         /* Clean up the storage types used */
9093         switch (type->type & STOR_MASK) {
9094         case STOR_AUTO:
9095         case STOR_STATIC:
9096                 /* These are the good types I am aiming for */
9097                 break;
9098         case STOR_REGISTER:
9099                 type->type &= ~STOR_MASK;
9100                 type->type |= STOR_AUTO;
9101                 break;
9102         case STOR_EXTERN:
9103                 type->type &= ~STOR_MASK;
9104                 type->type |= STOR_STATIC;
9105                 break;
9106         case STOR_TYPEDEF:
9107                 if (!ident) {
9108                         error(state, 0, "typedef without name");
9109                 }
9110                 symbol(state, ident, &ident->sym_ident, 0, type);
9111                 ident->tok = TOK_TYPE_NAME;
9112                 return 0;
9113                 break;
9114         default:
9115                 internal_error(state, 0, "Undefined storage class");
9116         }
9117         if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
9118                 error(state, 0, "Function prototypes not supported");
9119         }
9120         if (ident && 
9121                 ((type->type & STOR_MASK) == STOR_STATIC) &&
9122                 ((type->type & QUAL_CONST) == 0)) {
9123                 error(state, 0, "non const static variables not supported");
9124         }
9125         if (ident) {
9126                 def = variable(state, type);
9127                 symbol(state, ident, &ident->sym_ident, def, type);
9128         }
9129         return def;
9130 }
9131
9132 static void decl(struct compile_state *state, struct triple *first)
9133 {
9134         struct type *base_type, *type;
9135         struct hash_entry *ident;
9136         struct triple *def;
9137         int global;
9138         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9139         base_type = decl_specifiers(state);
9140         ident = 0;
9141         type = declarator(state, base_type, &ident, 0);
9142         if (global && ident && (peek(state) == TOK_LBRACE)) {
9143                 /* function */
9144                 state->function = ident->name;
9145                 def = function_definition(state, type);
9146                 symbol(state, ident, &ident->sym_ident, def, type);
9147                 state->function = 0;
9148         }
9149         else {
9150                 int done;
9151                 flatten(state, first, do_decl(state, type, ident));
9152                 /* type or variable definition */
9153                 do {
9154                         done = 1;
9155                         if (peek(state) == TOK_EQ) {
9156                                 if (!ident) {
9157                                         error(state, 0, "cannot assign to a type");
9158                                 }
9159                                 eat(state, TOK_EQ);
9160                                 flatten(state, first,
9161                                         init_expr(state, 
9162                                                 ident->sym_ident->def, 
9163                                                 initializer(state, type)));
9164                         }
9165                         arrays_complete(state, type);
9166                         if (peek(state) == TOK_COMMA) {
9167                                 eat(state, TOK_COMMA);
9168                                 ident = 0;
9169                                 type = declarator(state, base_type, &ident, 0);
9170                                 flatten(state, first, do_decl(state, type, ident));
9171                                 done = 0;
9172                         }
9173                 } while(!done);
9174                 eat(state, TOK_SEMI);
9175         }
9176 }
9177
9178 static void decls(struct compile_state *state)
9179 {
9180         struct triple *list;
9181         int tok;
9182         list = label(state);
9183         while(1) {
9184                 tok = peek(state);
9185                 if (tok == TOK_EOF) {
9186                         return;
9187                 }
9188                 if (tok == TOK_SPACE) {
9189                         eat(state, TOK_SPACE);
9190                 }
9191                 decl(state, list);
9192                 if (list->next != list) {
9193                         error(state, 0, "global variables not supported");
9194                 }
9195         }
9196 }
9197
9198 /*
9199  * Data structurs for optimation.
9200  */
9201
9202 static void do_use_block(
9203         struct block *used, struct block_set **head, struct block *user, 
9204         int front)
9205 {
9206         struct block_set **ptr, *new;
9207         if (!used)
9208                 return;
9209         if (!user)
9210                 return;
9211         ptr = head;
9212         while(*ptr) {
9213                 if ((*ptr)->member == user) {
9214                         return;
9215                 }
9216                 ptr = &(*ptr)->next;
9217         }
9218         new = xcmalloc(sizeof(*new), "block_set");
9219         new->member = user;
9220         if (front) {
9221                 new->next = *head;
9222                 *head = new;
9223         }
9224         else {
9225                 new->next = 0;
9226                 *ptr = new;
9227         }
9228 }
9229 static void do_unuse_block(
9230         struct block *used, struct block_set **head, struct block *unuser)
9231 {
9232         struct block_set *use, **ptr;
9233         ptr = head;
9234         while(*ptr) {
9235                 use = *ptr;
9236                 if (use->member == unuser) {
9237                         *ptr = use->next;
9238                         memset(use, -1, sizeof(*use));
9239                         xfree(use);
9240                 }
9241                 else {
9242                         ptr = &use->next;
9243                 }
9244         }
9245 }
9246
9247 static void use_block(struct block *used, struct block *user)
9248 {
9249         /* Append new to the head of the list, print_block
9250          * depends on this.
9251          */
9252         do_use_block(used, &used->use, user, 1); 
9253         used->users++;
9254 }
9255 static void unuse_block(struct block *used, struct block *unuser)
9256 {
9257         do_unuse_block(used, &used->use, unuser); 
9258         used->users--;
9259 }
9260
9261 static void idom_block(struct block *idom, struct block *user)
9262 {
9263         do_use_block(idom, &idom->idominates, user, 0);
9264 }
9265
9266 static void unidom_block(struct block *idom, struct block *unuser)
9267 {
9268         do_unuse_block(idom, &idom->idominates, unuser);
9269 }
9270
9271 static void domf_block(struct block *block, struct block *domf)
9272 {
9273         do_use_block(block, &block->domfrontier, domf, 0);
9274 }
9275
9276 static void undomf_block(struct block *block, struct block *undomf)
9277 {
9278         do_unuse_block(block, &block->domfrontier, undomf);
9279 }
9280
9281 static void ipdom_block(struct block *ipdom, struct block *user)
9282 {
9283         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9284 }
9285
9286 static void unipdom_block(struct block *ipdom, struct block *unuser)
9287 {
9288         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9289 }
9290
9291 static void ipdomf_block(struct block *block, struct block *ipdomf)
9292 {
9293         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9294 }
9295
9296 static void unipdomf_block(struct block *block, struct block *unipdomf)
9297 {
9298         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9299 }
9300
9301
9302
9303 static int do_walk_triple(struct compile_state *state,
9304         struct triple *ptr, int depth,
9305         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
9306 {
9307         int result;
9308         result = cb(state, ptr, depth);
9309         if ((result == 0) && (ptr->op == OP_LIST)) {
9310                 struct triple *list;
9311                 list = ptr;
9312                 ptr = RHS(list, 0);
9313                 do {
9314                         result = do_walk_triple(state, ptr, depth + 1, cb);
9315                         if (ptr->next->prev != ptr) {
9316                                 internal_error(state, ptr->next, "bad prev");
9317                         }
9318                         ptr = ptr->next;
9319                         
9320                 } while((result == 0) && (ptr != RHS(list, 0)));
9321         }
9322         return result;
9323 }
9324
9325 static int walk_triple(
9326         struct compile_state *state, 
9327         struct triple *ptr, 
9328         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9329 {
9330         return do_walk_triple(state, ptr, 0, cb);
9331 }
9332
9333 static void do_print_prefix(int depth)
9334 {
9335         int i;
9336         for(i = 0; i < depth; i++) {
9337                 printf("  ");
9338         }
9339 }
9340
9341 #define PRINT_LIST 1
9342 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9343 {
9344         int op;
9345         op = ins->op;
9346         if (op == OP_LIST) {
9347 #if !PRINT_LIST
9348                 return 0;
9349 #endif
9350         }
9351         if ((op == OP_LABEL) && (ins->use)) {
9352                 printf("\n%p:\n", ins);
9353         }
9354         do_print_prefix(depth);
9355         display_triple(stdout, ins);
9356
9357         if ((ins->op == OP_BRANCH) && ins->use) {
9358                 internal_error(state, ins, "branch used?");
9359         }
9360 #if 0
9361         {
9362                 struct triple_set *user;
9363                 for(user = ins->use; user; user = user->next) {
9364                         printf("use: %p\n", user->member);
9365                 }
9366         }
9367 #endif
9368         if (triple_is_branch(state, ins)) {
9369                 printf("\n");
9370         }
9371         return 0;
9372 }
9373
9374 static void print_triple(struct compile_state *state, struct triple *ins)
9375 {
9376         walk_triple(state, ins, do_print_triple);
9377 }
9378
9379 static void print_triples(struct compile_state *state)
9380 {
9381         print_triple(state, state->main_function);
9382 }
9383
9384 struct cf_block {
9385         struct block *block;
9386 };
9387 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9388 {
9389         if (!block || (cf[block->vertex].block == block)) {
9390                 return;
9391         }
9392         cf[block->vertex].block = block;
9393         find_cf_blocks(cf, block->left);
9394         find_cf_blocks(cf, block->right);
9395 }
9396
9397 static void print_control_flow(struct compile_state *state)
9398 {
9399         struct cf_block *cf;
9400         int i;
9401         printf("\ncontrol flow\n");
9402         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9403         find_cf_blocks(cf, state->first_block);
9404
9405         for(i = 1; i <= state->last_vertex; i++) {
9406                 struct block *block;
9407                 block = cf[i].block;
9408                 if (!block)
9409                         continue;
9410                 printf("(%p) %d:", block, block->vertex);
9411                 if (block->left) {
9412                         printf(" %d", block->left->vertex);
9413                 }
9414                 if (block->right && (block->right != block->left)) {
9415                         printf(" %d", block->right->vertex);
9416                 }
9417                 printf("\n");
9418         }
9419
9420         xfree(cf);
9421 }
9422
9423
9424 static struct block *basic_block(struct compile_state *state,
9425         struct triple *first)
9426 {
9427         struct block *block;
9428         struct triple *ptr;
9429         int op;
9430         if (first->op != OP_LABEL) {
9431                 internal_error(state, 0, "block does not start with a label");
9432         }
9433         /* See if this basic block has already been setup */
9434         if (first->u.block != 0) {
9435                 return first->u.block;
9436         }
9437         /* Allocate another basic block structure */
9438         state->last_vertex += 1;
9439         block = xcmalloc(sizeof(*block), "block");
9440         block->first = block->last = first;
9441         block->vertex = state->last_vertex;
9442         ptr = first;
9443         do {
9444                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9445                         break;
9446                 }
9447                 block->last = ptr;
9448                 /* If ptr->u is not used remember where the baic block is */
9449                 if (triple_stores_block(state, ptr)) {
9450                         ptr->u.block = block;
9451                 }
9452                 if (ptr->op == OP_BRANCH) {
9453                         break;
9454                 }
9455                 ptr = ptr->next;
9456         } while (ptr != RHS(state->main_function, 0));
9457         if (ptr == RHS(state->main_function, 0))
9458                 return block;
9459         op = ptr->op;
9460         if (op == OP_LABEL) {
9461                 block->left = basic_block(state, ptr);
9462                 block->right = 0;
9463                 use_block(block->left, block);
9464         }
9465         else if (op == OP_BRANCH) {
9466                 block->left = 0;
9467                 /* Trace the branch target */
9468                 block->right = basic_block(state, TARG(ptr, 0));
9469                 use_block(block->right, block);
9470                 /* If there is a test trace the branch as well */
9471                 if (TRIPLE_RHS(ptr->sizes)) {
9472                         block->left = basic_block(state, ptr->next);
9473                         use_block(block->left, block);
9474                 }
9475         }
9476         else {
9477                 internal_error(state, 0, "Bad basic block split");
9478         }
9479         return block;
9480 }
9481
9482
9483 static void walk_blocks(struct compile_state *state,
9484         void (*cb)(struct compile_state *state, struct block *block, void *arg),
9485         void *arg)
9486 {
9487         struct triple *ptr, *first;
9488         struct block *last_block;
9489         last_block = 0;
9490         first = RHS(state->main_function, 0);
9491         ptr = first;
9492         do {
9493                 struct block *block;
9494                 if (ptr->op == OP_LABEL) {
9495                         block = ptr->u.block;
9496                         if (block && (block != last_block)) {
9497                                 cb(state, block, arg);
9498                         }
9499                         last_block = block;
9500                 }
9501                 ptr = ptr->next;
9502         } while(ptr != first);
9503 }
9504
9505 static void print_block(
9506         struct compile_state *state, struct block *block, void *arg)
9507 {
9508         struct triple *ptr;
9509         FILE *fp = arg;
9510
9511         fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n", 
9512                 block, 
9513                 block->vertex,
9514                 block->left, 
9515                 block->left && block->left->use?block->left->use->member : 0,
9516                 block->right, 
9517                 block->right && block->right->use?block->right->use->member : 0);
9518         if (block->first->op == OP_LABEL) {
9519                 fprintf(fp, "%p:\n", block->first);
9520         }
9521         for(ptr = block->first; ; ptr = ptr->next) {
9522                 struct triple_set *user;
9523                 int op = ptr->op;
9524                 
9525                 if (triple_stores_block(state, ptr)) {
9526                         if (ptr->u.block != block) {
9527                                 internal_error(state, ptr, 
9528                                         "Wrong block pointer: %p\n",
9529                                         ptr->u.block);
9530                         }
9531                 }
9532                 if (op == OP_ADECL) {
9533                         for(user = ptr->use; user; user = user->next) {
9534                                 if (!user->member->u.block) {
9535                                         internal_error(state, user->member, 
9536                                                 "Use %p not in a block?\n",
9537                                                 user->member);
9538                                 }
9539                         }
9540                 }
9541                 display_triple(fp, ptr);
9542
9543 #if 0
9544                 for(user = ptr->use; user; user = user->next) {
9545                         fprintf(fp, "use: %p\n", user->member);
9546                 }
9547 #endif
9548
9549                 /* Sanity checks... */
9550                 valid_ins(state, ptr);
9551                 for(user = ptr->use; user; user = user->next) {
9552                         struct triple *use;
9553                         use = user->member;
9554                         valid_ins(state, use);
9555                         if (triple_stores_block(state, user->member) &&
9556                                 !user->member->u.block) {
9557                                 internal_error(state, user->member,
9558                                         "Use %p not in a block?",
9559                                         user->member);
9560                         }
9561                 }
9562
9563                 if (ptr == block->last)
9564                         break;
9565         }
9566         fprintf(fp,"\n");
9567 }
9568
9569
9570 static void print_blocks(struct compile_state *state, FILE *fp)
9571 {
9572         fprintf(fp, "--------------- blocks ---------------\n");
9573         walk_blocks(state, print_block, fp);
9574 }
9575
9576 static void prune_nonblock_triples(struct compile_state *state)
9577 {
9578         struct block *block;
9579         struct triple *first, *ins, *next;
9580         /* Delete the triples not in a basic block */
9581         first = RHS(state->main_function, 0);
9582         block = 0;
9583         ins = first;
9584         do {
9585                 next = ins->next;
9586                 if (ins->op == OP_LABEL) {
9587                         block = ins->u.block;
9588                 }
9589                 if (!block) {
9590                         release_triple(state, ins);
9591                 }
9592                 ins = next;
9593         } while(ins != first);
9594 }
9595
9596 static void setup_basic_blocks(struct compile_state *state)
9597 {
9598         if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9599                 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9600                 internal_error(state, 0, "ins will not store block?");
9601         }
9602         /* Find the basic blocks */
9603         state->last_vertex = 0;
9604         state->first_block = basic_block(state, RHS(state->main_function,0));
9605         /* Delete the triples not in a basic block */
9606         prune_nonblock_triples(state);
9607         /* Find the last basic block */
9608         state->last_block = RHS(state->main_function, 0)->prev->u.block;
9609         if (!state->last_block) {
9610                 internal_error(state, 0, "end not used?");
9611         }
9612         /* Insert an extra unused edge from start to the end 
9613          * This helps with reverse control flow calculations.
9614          */
9615         use_block(state->first_block, state->last_block);
9616         /* If we are debugging print what I have just done */
9617         if (state->debug & DEBUG_BASIC_BLOCKS) {
9618                 print_blocks(state, stdout);
9619                 print_control_flow(state);
9620         }
9621 }
9622
9623 static void free_basic_block(struct compile_state *state, struct block *block)
9624 {
9625         struct block_set *entry, *next;
9626         struct block *child;
9627         if (!block) {
9628                 return;
9629         }
9630         if (block->vertex == -1) {
9631                 return;
9632         }
9633         block->vertex = -1;
9634         if (block->left) {
9635                 unuse_block(block->left, block);
9636         }
9637         if (block->right) {
9638                 unuse_block(block->right, block);
9639         }
9640         if (block->idom) {
9641                 unidom_block(block->idom, block);
9642         }
9643         block->idom = 0;
9644         if (block->ipdom) {
9645                 unipdom_block(block->ipdom, block);
9646         }
9647         block->ipdom = 0;
9648         for(entry = block->use; entry; entry = next) {
9649                 next = entry->next;
9650                 child = entry->member;
9651                 unuse_block(block, child);
9652                 if (child->left == block) {
9653                         child->left = 0;
9654                 }
9655                 if (child->right == block) {
9656                         child->right = 0;
9657                 }
9658         }
9659         for(entry = block->idominates; entry; entry = next) {
9660                 next = entry->next;
9661                 child = entry->member;
9662                 unidom_block(block, child);
9663                 child->idom = 0;
9664         }
9665         for(entry = block->domfrontier; entry; entry = next) {
9666                 next = entry->next;
9667                 child = entry->member;
9668                 undomf_block(block, child);
9669         }
9670         for(entry = block->ipdominates; entry; entry = next) {
9671                 next = entry->next;
9672                 child = entry->member;
9673                 unipdom_block(block, child);
9674                 child->ipdom = 0;
9675         }
9676         for(entry = block->ipdomfrontier; entry; entry = next) {
9677                 next = entry->next;
9678                 child = entry->member;
9679                 unipdomf_block(block, child);
9680         }
9681         if (block->users != 0) {
9682                 internal_error(state, 0, "block still has users");
9683         }
9684         free_basic_block(state, block->left);
9685         block->left = 0;
9686         free_basic_block(state, block->right);
9687         block->right = 0;
9688         memset(block, -1, sizeof(*block));
9689         xfree(block);
9690 }
9691
9692 static void free_basic_blocks(struct compile_state *state)
9693 {
9694         struct triple *first, *ins;
9695         free_basic_block(state, state->first_block);
9696         state->last_vertex = 0;
9697         state->first_block = state->last_block = 0;
9698         first = RHS(state->main_function, 0);
9699         ins = first;
9700         do {
9701                 if (triple_stores_block(state, ins)) {
9702                         ins->u.block = 0;
9703                 }
9704                 ins = ins->next;
9705         } while(ins != first);
9706         
9707 }
9708
9709 struct sdom_block {
9710         struct block *block;
9711         struct sdom_block *sdominates;
9712         struct sdom_block *sdom_next;
9713         struct sdom_block *sdom;
9714         struct sdom_block *label;
9715         struct sdom_block *parent;
9716         struct sdom_block *ancestor;
9717         int vertex;
9718 };
9719
9720
9721 static void unsdom_block(struct sdom_block *block)
9722 {
9723         struct sdom_block **ptr;
9724         if (!block->sdom_next) {
9725                 return;
9726         }
9727         ptr = &block->sdom->sdominates;
9728         while(*ptr) {
9729                 if ((*ptr) == block) {
9730                         *ptr = block->sdom_next;
9731                         return;
9732                 }
9733                 ptr = &(*ptr)->sdom_next;
9734         }
9735 }
9736
9737 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9738 {
9739         unsdom_block(block);
9740         block->sdom = sdom;
9741         block->sdom_next = sdom->sdominates;
9742         sdom->sdominates = block;
9743 }
9744
9745
9746
9747 static int initialize_sdblock(struct sdom_block *sd,
9748         struct block *parent, struct block *block, int vertex)
9749 {
9750         if (!block || (sd[block->vertex].block == block)) {
9751                 return vertex;
9752         }
9753         vertex += 1;
9754         /* Renumber the blocks in a convinient fashion */
9755         block->vertex = vertex;
9756         sd[vertex].block    = block;
9757         sd[vertex].sdom     = &sd[vertex];
9758         sd[vertex].label    = &sd[vertex];
9759         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9760         sd[vertex].ancestor = 0;
9761         sd[vertex].vertex   = vertex;
9762         vertex = initialize_sdblock(sd, block, block->left, vertex);
9763         vertex = initialize_sdblock(sd, block, block->right, vertex);
9764         return vertex;
9765 }
9766
9767 static int initialize_sdpblock(struct sdom_block *sd,
9768         struct block *parent, struct block *block, int vertex)
9769 {
9770         struct block_set *user;
9771         if (!block || (sd[block->vertex].block == block)) {
9772                 return vertex;
9773         }
9774         vertex += 1;
9775         /* Renumber the blocks in a convinient fashion */
9776         block->vertex = vertex;
9777         sd[vertex].block    = block;
9778         sd[vertex].sdom     = &sd[vertex];
9779         sd[vertex].label    = &sd[vertex];
9780         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9781         sd[vertex].ancestor = 0;
9782         sd[vertex].vertex   = vertex;
9783         for(user = block->use; user; user = user->next) {
9784                 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9785         }
9786         return vertex;
9787 }
9788
9789 static void compress_ancestors(struct sdom_block *v)
9790 {
9791         /* This procedure assumes ancestor(v) != 0 */
9792         /* if (ancestor(ancestor(v)) != 0) {
9793          *      compress(ancestor(ancestor(v)));
9794          *      if (semi(label(ancestor(v))) < semi(label(v))) {
9795          *              label(v) = label(ancestor(v));
9796          *      }
9797          *      ancestor(v) = ancestor(ancestor(v));
9798          * }
9799          */
9800         if (!v->ancestor) {
9801                 return;
9802         }
9803         if (v->ancestor->ancestor) {
9804                 compress_ancestors(v->ancestor->ancestor);
9805                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9806                         v->label = v->ancestor->label;
9807                 }
9808                 v->ancestor = v->ancestor->ancestor;
9809         }
9810 }
9811
9812 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9813 {
9814         int i;
9815         /* // step 2 
9816          *  for each v <= pred(w) {
9817          *      u = EVAL(v);
9818          *      if (semi[u] < semi[w] { 
9819          *              semi[w] = semi[u]; 
9820          *      } 
9821          * }
9822          * add w to bucket(vertex(semi[w]));
9823          * LINK(parent(w), w);
9824          *
9825          * // step 3
9826          * for each v <= bucket(parent(w)) {
9827          *      delete v from bucket(parent(w));
9828          *      u = EVAL(v);
9829          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9830          * }
9831          */
9832         for(i = state->last_vertex; i >= 2; i--) {
9833                 struct sdom_block *v, *parent, *next;
9834                 struct block_set *user;
9835                 struct block *block;
9836                 block = sd[i].block;
9837                 parent = sd[i].parent;
9838                 /* Step 2 */
9839                 for(user = block->use; user; user = user->next) {
9840                         struct sdom_block *v, *u;
9841                         v = &sd[user->member->vertex];
9842                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9843                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9844                                 sd[i].sdom = u->sdom;
9845                         }
9846                 }
9847                 sdom_block(sd[i].sdom, &sd[i]);
9848                 sd[i].ancestor = parent;
9849                 /* Step 3 */
9850                 for(v = parent->sdominates; v; v = next) {
9851                         struct sdom_block *u;
9852                         next = v->sdom_next;
9853                         unsdom_block(v);
9854                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9855                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
9856                                 u->block : parent->block;
9857                 }
9858         }
9859 }
9860
9861 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9862 {
9863         int i;
9864         /* // step 2 
9865          *  for each v <= pred(w) {
9866          *      u = EVAL(v);
9867          *      if (semi[u] < semi[w] { 
9868          *              semi[w] = semi[u]; 
9869          *      } 
9870          * }
9871          * add w to bucket(vertex(semi[w]));
9872          * LINK(parent(w), w);
9873          *
9874          * // step 3
9875          * for each v <= bucket(parent(w)) {
9876          *      delete v from bucket(parent(w));
9877          *      u = EVAL(v);
9878          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9879          * }
9880          */
9881         for(i = state->last_vertex; i >= 2; i--) {
9882                 struct sdom_block *u, *v, *parent, *next;
9883                 struct block *block;
9884                 block = sd[i].block;
9885                 parent = sd[i].parent;
9886                 /* Step 2 */
9887                 if (block->left) {
9888                         v = &sd[block->left->vertex];
9889                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9890                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9891                                 sd[i].sdom = u->sdom;
9892                         }
9893                 }
9894                 if (block->right && (block->right != block->left)) {
9895                         v = &sd[block->right->vertex];
9896                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9897                         if (u->sdom->vertex < sd[i].sdom->vertex) {
9898                                 sd[i].sdom = u->sdom;
9899                         }
9900                 }
9901                 sdom_block(sd[i].sdom, &sd[i]);
9902                 sd[i].ancestor = parent;
9903                 /* Step 3 */
9904                 for(v = parent->sdominates; v; v = next) {
9905                         struct sdom_block *u;
9906                         next = v->sdom_next;
9907                         unsdom_block(v);
9908                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9909                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
9910                                 u->block : parent->block;
9911                 }
9912         }
9913 }
9914
9915 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9916 {
9917         int i;
9918         for(i = 2; i <= state->last_vertex; i++) {
9919                 struct block *block;
9920                 block = sd[i].block;
9921                 if (block->idom->vertex != sd[i].sdom->vertex) {
9922                         block->idom = block->idom->idom;
9923                 }
9924                 idom_block(block->idom, block);
9925         }
9926         sd[1].block->idom = 0;
9927 }
9928
9929 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9930 {
9931         int i;
9932         for(i = 2; i <= state->last_vertex; i++) {
9933                 struct block *block;
9934                 block = sd[i].block;
9935                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9936                         block->ipdom = block->ipdom->ipdom;
9937                 }
9938                 ipdom_block(block->ipdom, block);
9939         }
9940         sd[1].block->ipdom = 0;
9941 }
9942
9943         /* Theorem 1:
9944          *   Every vertex of a flowgraph G = (V, E, r) except r has
9945          *   a unique immediate dominator.  
9946          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9947          *   rooted at r, called the dominator tree of G, such that 
9948          *   v dominates w if and only if v is a proper ancestor of w in
9949          *   the dominator tree.
9950          */
9951         /* Lemma 1:  
9952          *   If v and w are vertices of G such that v <= w,
9953          *   than any path from v to w must contain a common ancestor
9954          *   of v and w in T.
9955          */
9956         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
9957         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
9958         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
9959         /* Theorem 2:
9960          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
9961          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
9962          */
9963         /* Theorem 3:
9964          *   Let w != r and let u be a vertex for which sdom(u) is 
9965          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9966          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9967          */
9968         /* Lemma 5:  Let vertices v,w satisfy v -> w.
9969          *           Then v -> idom(w) or idom(w) -> idom(v)
9970          */
9971
9972 static void find_immediate_dominators(struct compile_state *state)
9973 {
9974         struct sdom_block *sd;
9975         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9976          *           vi > w for (1 <= i <= k - 1}
9977          */
9978         /* Theorem 4:
9979          *   For any vertex w != r.
9980          *   sdom(w) = min(
9981          *                 {v|(v,w) <= E  and v < w } U 
9982          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9983          */
9984         /* Corollary 1:
9985          *   Let w != r and let u be a vertex for which sdom(u) is 
9986          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
9987          *   Then:
9988          *                   { sdom(w) if sdom(w) = sdom(u),
9989          *        idom(w) = {
9990          *                   { idom(u) otherwise
9991          */
9992         /* The algorithm consists of the following 4 steps.
9993          * Step 1.  Carry out a depth-first search of the problem graph.  
9994          *    Number the vertices from 1 to N as they are reached during
9995          *    the search.  Initialize the variables used in succeeding steps.
9996          * Step 2.  Compute the semidominators of all vertices by applying
9997          *    theorem 4.   Carry out the computation vertex by vertex in
9998          *    decreasing order by number.
9999          * Step 3.  Implicitly define the immediate dominator of each vertex
10000          *    by applying Corollary 1.
10001          * Step 4.  Explicitly define the immediate dominator of each vertex,
10002          *    carrying out the computation vertex by vertex in increasing order
10003          *    by number.
10004          */
10005         /* Step 1 initialize the basic block information */
10006         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10007         initialize_sdblock(sd, 0, state->first_block, 0);
10008 #if 0
10009         sd[1].size  = 0;
10010         sd[1].label = 0;
10011         sd[1].sdom  = 0;
10012 #endif
10013         /* Step 2 compute the semidominators */
10014         /* Step 3 implicitly define the immediate dominator of each vertex */
10015         compute_sdom(state, sd);
10016         /* Step 4 explicitly define the immediate dominator of each vertex */
10017         compute_idom(state, sd);
10018         xfree(sd);
10019 }
10020
10021 static void find_post_dominators(struct compile_state *state)
10022 {
10023         struct sdom_block *sd;
10024         /* Step 1 initialize the basic block information */
10025         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10026
10027         initialize_sdpblock(sd, 0, state->last_block, 0);
10028
10029         /* Step 2 compute the semidominators */
10030         /* Step 3 implicitly define the immediate dominator of each vertex */
10031         compute_spdom(state, sd);
10032         /* Step 4 explicitly define the immediate dominator of each vertex */
10033         compute_ipdom(state, sd);
10034         xfree(sd);
10035 }
10036
10037
10038
10039 static void find_block_domf(struct compile_state *state, struct block *block)
10040 {
10041         struct block *child;
10042         struct block_set *user;
10043         if (block->domfrontier != 0) {
10044                 internal_error(state, block->first, "domfrontier present?");
10045         }
10046         for(user = block->idominates; user; user = user->next) {
10047                 child = user->member;
10048                 if (child->idom != block) {
10049                         internal_error(state, block->first, "bad idom");
10050                 }
10051                 find_block_domf(state, child);
10052         }
10053         if (block->left && block->left->idom != block) {
10054                 domf_block(block, block->left);
10055         }
10056         if (block->right && block->right->idom != block) {
10057                 domf_block(block, block->right);
10058         }
10059         for(user = block->idominates; user; user = user->next) {
10060                 struct block_set *frontier;
10061                 child = user->member;
10062                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10063                         if (frontier->member->idom != block) {
10064                                 domf_block(block, frontier->member);
10065                         }
10066                 }
10067         }
10068 }
10069
10070 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10071 {
10072         struct block *child;
10073         struct block_set *user;
10074         if (block->ipdomfrontier != 0) {
10075                 internal_error(state, block->first, "ipdomfrontier present?");
10076         }
10077         for(user = block->ipdominates; user; user = user->next) {
10078                 child = user->member;
10079                 if (child->ipdom != block) {
10080                         internal_error(state, block->first, "bad ipdom");
10081                 }
10082                 find_block_ipdomf(state, child);
10083         }
10084         if (block->left && block->left->ipdom != block) {
10085                 ipdomf_block(block, block->left);
10086         }
10087         if (block->right && block->right->ipdom != block) {
10088                 ipdomf_block(block, block->right);
10089         }
10090         for(user = block->idominates; user; user = user->next) {
10091                 struct block_set *frontier;
10092                 child = user->member;
10093                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10094                         if (frontier->member->ipdom != block) {
10095                                 ipdomf_block(block, frontier->member);
10096                         }
10097                 }
10098         }
10099 }
10100
10101 static void print_dominated(
10102         struct compile_state *state, struct block *block, void *arg)
10103 {
10104         struct block_set *user;
10105         FILE *fp = arg;
10106
10107         fprintf(fp, "%d:", block->vertex);
10108         for(user = block->idominates; user; user = user->next) {
10109                 fprintf(fp, " %d", user->member->vertex);
10110                 if (user->member->idom != block) {
10111                         internal_error(state, user->member->first, "bad idom");
10112                 }
10113         }
10114         fprintf(fp,"\n");
10115 }
10116
10117 static void print_dominators(struct compile_state *state, FILE *fp)
10118 {
10119         fprintf(fp, "\ndominates\n");
10120         walk_blocks(state, print_dominated, fp);
10121 }
10122
10123
10124 static int print_frontiers(
10125         struct compile_state *state, struct block *block, int vertex)
10126 {
10127         struct block_set *user;
10128
10129         if (!block || (block->vertex != vertex + 1)) {
10130                 return vertex;
10131         }
10132         vertex += 1;
10133
10134         printf("%d:", block->vertex);
10135         for(user = block->domfrontier; user; user = user->next) {
10136                 printf(" %d", user->member->vertex);
10137         }
10138         printf("\n");
10139
10140         vertex = print_frontiers(state, block->left, vertex);
10141         vertex = print_frontiers(state, block->right, vertex);
10142         return vertex;
10143 }
10144 static void print_dominance_frontiers(struct compile_state *state)
10145 {
10146         printf("\ndominance frontiers\n");
10147         print_frontiers(state, state->first_block, 0);
10148         
10149 }
10150
10151 static void analyze_idominators(struct compile_state *state)
10152 {
10153         /* Find the immediate dominators */
10154         find_immediate_dominators(state);
10155         /* Find the dominance frontiers */
10156         find_block_domf(state, state->first_block);
10157         /* If debuging print the print what I have just found */
10158         if (state->debug & DEBUG_FDOMINATORS) {
10159                 print_dominators(state, stdout);
10160                 print_dominance_frontiers(state);
10161                 print_control_flow(state);
10162         }
10163 }
10164
10165
10166
10167 static void print_ipdominated(
10168         struct compile_state *state, struct block *block, void *arg)
10169 {
10170         struct block_set *user;
10171         FILE *fp = arg;
10172
10173         fprintf(fp, "%d:", block->vertex);
10174         for(user = block->ipdominates; user; user = user->next) {
10175                 fprintf(fp, " %d", user->member->vertex);
10176                 if (user->member->ipdom != block) {
10177                         internal_error(state, user->member->first, "bad ipdom");
10178                 }
10179         }
10180         fprintf(fp, "\n");
10181 }
10182
10183 static void print_ipdominators(struct compile_state *state, FILE *fp)
10184 {
10185         fprintf(fp, "\nipdominates\n");
10186         walk_blocks(state, print_ipdominated, fp);
10187 }
10188
10189 static int print_pfrontiers(
10190         struct compile_state *state, struct block *block, int vertex)
10191 {
10192         struct block_set *user;
10193
10194         if (!block || (block->vertex != vertex + 1)) {
10195                 return vertex;
10196         }
10197         vertex += 1;
10198
10199         printf("%d:", block->vertex);
10200         for(user = block->ipdomfrontier; user; user = user->next) {
10201                 printf(" %d", user->member->vertex);
10202         }
10203         printf("\n");
10204         for(user = block->use; user; user = user->next) {
10205                 vertex = print_pfrontiers(state, user->member, vertex);
10206         }
10207         return vertex;
10208 }
10209 static void print_ipdominance_frontiers(struct compile_state *state)
10210 {
10211         printf("\nipdominance frontiers\n");
10212         print_pfrontiers(state, state->last_block, 0);
10213         
10214 }
10215
10216 static void analyze_ipdominators(struct compile_state *state)
10217 {
10218         /* Find the post dominators */
10219         find_post_dominators(state);
10220         /* Find the control dependencies (post dominance frontiers) */
10221         find_block_ipdomf(state, state->last_block);
10222         /* If debuging print the print what I have just found */
10223         if (state->debug & DEBUG_RDOMINATORS) {
10224                 print_ipdominators(state, stdout);
10225                 print_ipdominance_frontiers(state);
10226                 print_control_flow(state);
10227         }
10228 }
10229
10230 static int bdominates(struct compile_state *state,
10231         struct block *dom, struct block *sub)
10232 {
10233         while(sub && (sub != dom)) {
10234                 sub = sub->idom;
10235         }
10236         return sub == dom;
10237 }
10238
10239 static int tdominates(struct compile_state *state,
10240         struct triple *dom, struct triple *sub)
10241 {
10242         struct block *bdom, *bsub;
10243         int result;
10244         bdom = block_of_triple(state, dom);
10245         bsub = block_of_triple(state, sub);
10246         if (bdom != bsub) {
10247                 result = bdominates(state, bdom, bsub);
10248         } 
10249         else {
10250                 struct triple *ins;
10251                 ins = sub;
10252                 while((ins != bsub->first) && (ins != dom)) {
10253                         ins = ins->prev;
10254                 }
10255                 result = (ins == dom);
10256         }
10257         return result;
10258 }
10259
10260 static void insert_phi_operations(struct compile_state *state)
10261 {
10262         size_t size;
10263         struct triple *first;
10264         int *has_already, *work;
10265         struct block *work_list, **work_list_tail;
10266         int iter;
10267         struct triple *var;
10268
10269         size = sizeof(int) * (state->last_vertex + 1);
10270         has_already = xcmalloc(size, "has_already");
10271         work =        xcmalloc(size, "work");
10272         iter = 0;
10273
10274         first = RHS(state->main_function, 0);
10275         for(var = first->next; var != first ; var = var->next) {
10276                 struct block *block;
10277                 struct triple_set *user;
10278                 if ((var->op != OP_ADECL) || !var->use) {
10279                         continue;
10280                 }
10281                 iter += 1;
10282                 work_list = 0;
10283                 work_list_tail = &work_list;
10284                 for(user = var->use; user; user = user->next) {
10285                         if (user->member->op == OP_READ) {
10286                                 continue;
10287                         }
10288                         if (user->member->op != OP_WRITE) {
10289                                 internal_error(state, user->member, 
10290                                         "bad variable access");
10291                         }
10292                         block = user->member->u.block;
10293                         if (!block) {
10294                                 warning(state, user->member, "dead code");
10295                         }
10296                         if (work[block->vertex] >= iter) {
10297                                 continue;
10298                         }
10299                         work[block->vertex] = iter;
10300                         *work_list_tail = block;
10301                         block->work_next = 0;
10302                         work_list_tail = &block->work_next;
10303                 }
10304                 for(block = work_list; block; block = block->work_next) {
10305                         struct block_set *df;
10306                         for(df = block->domfrontier; df; df = df->next) {
10307                                 struct triple *phi;
10308                                 struct block *front;
10309                                 int in_edges;
10310                                 front = df->member;
10311
10312                                 if (has_already[front->vertex] >= iter) {
10313                                         continue;
10314                                 }
10315                                 /* Count how many edges flow into this block */
10316                                 in_edges = front->users;
10317                                 /* Insert a phi function for this variable */
10318                                 get_occurance(front->first->occurance);
10319                                 phi = alloc_triple(
10320                                         state, OP_PHI, var->type, -1, in_edges, 
10321                                         front->first->occurance);
10322                                 phi->u.block = front;
10323                                 MISC(phi, 0) = var;
10324                                 use_triple(var, phi);
10325                                 /* Insert the phi functions immediately after the label */
10326                                 insert_triple(state, front->first->next, phi);
10327                                 if (front->first == front->last) {
10328                                         front->last = front->first->next;
10329                                 }
10330                                 has_already[front->vertex] = iter;
10331
10332                                 /* If necessary plan to visit the basic block */
10333                                 if (work[front->vertex] >= iter) {
10334                                         continue;
10335                                 }
10336                                 work[front->vertex] = iter;
10337                                 *work_list_tail = front;
10338                                 front->work_next = 0;
10339                                 work_list_tail = &front->work_next;
10340                         }
10341                 }
10342         }
10343         xfree(has_already);
10344         xfree(work);
10345 }
10346
10347 /*
10348  * C(V)
10349  * S(V)
10350  */
10351 static void fixup_block_phi_variables(
10352         struct compile_state *state, struct block *parent, struct block *block)
10353 {
10354         struct block_set *set;
10355         struct triple *ptr;
10356         int edge;
10357         if (!parent || !block)
10358                 return;
10359         /* Find the edge I am coming in on */
10360         edge = 0;
10361         for(set = block->use; set; set = set->next, edge++) {
10362                 if (set->member == parent) {
10363                         break;
10364                 }
10365         }
10366         if (!set) {
10367                 internal_error(state, 0, "phi input is not on a control predecessor");
10368         }
10369         for(ptr = block->first; ; ptr = ptr->next) {
10370                 if (ptr->op == OP_PHI) {
10371                         struct triple *var, *val, **slot;
10372                         var = MISC(ptr, 0);
10373                         if (!var) {
10374                                 internal_error(state, ptr, "no var???");
10375                         }
10376                         /* Find the current value of the variable */
10377                         val = var->use->member;
10378                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10379                                 internal_error(state, val, "bad value in phi");
10380                         }
10381                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
10382                                 internal_error(state, ptr, "edges > phi rhs");
10383                         }
10384                         slot = &RHS(ptr, edge);
10385                         if ((*slot != 0) && (*slot != val)) {
10386                                 internal_error(state, ptr, "phi already bound on this edge");
10387                         }
10388                         *slot = val;
10389                         use_triple(val, ptr);
10390                 }
10391                 if (ptr == block->last) {
10392                         break;
10393                 }
10394         }
10395 }
10396
10397
10398 static void rename_block_variables(
10399         struct compile_state *state, struct block *block)
10400 {
10401         struct block_set *user;
10402         struct triple *ptr, *next, *last;
10403         int done;
10404         if (!block)
10405                 return;
10406         last = block->first;
10407         done = 0;
10408         for(ptr = block->first; !done; ptr = next) {
10409                 next = ptr->next;
10410                 if (ptr == block->last) {
10411                         done = 1;
10412                 }
10413                 /* RHS(A) */
10414                 if (ptr->op == OP_READ) {
10415                         struct triple *var, *val;
10416                         var = RHS(ptr, 0);
10417                         unuse_triple(var, ptr);
10418                         if (!var->use) {
10419                                 error(state, ptr, "variable used without being set");
10420                         }
10421                         /* Find the current value of the variable */
10422                         val = var->use->member;
10423                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10424                                 internal_error(state, val, "bad value in read");
10425                         }
10426                         propogate_use(state, ptr, val);
10427                         release_triple(state, ptr);
10428                         continue;
10429                 }
10430                 /* LHS(A) */
10431                 if (ptr->op == OP_WRITE) {
10432                         struct triple *var, *val;
10433                         var = LHS(ptr, 0);
10434                         val = RHS(ptr, 0);
10435                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10436                                 internal_error(state, val, "bad value in write");
10437                         }
10438                         propogate_use(state, ptr, val);
10439                         unuse_triple(var, ptr);
10440                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
10441                         push_triple(var, val);
10442                 }
10443                 if (ptr->op == OP_PHI) {
10444                         struct triple *var;
10445                         var = MISC(ptr, 0);
10446                         /* Push OP_PHI onto a stack of variable uses */
10447                         push_triple(var, ptr);
10448                 }
10449                 last = ptr;
10450         }
10451         block->last = last;
10452
10453         /* Fixup PHI functions in the cf successors */
10454         fixup_block_phi_variables(state, block, block->left);
10455         fixup_block_phi_variables(state, block, block->right);
10456         /* rename variables in the dominated nodes */
10457         for(user = block->idominates; user; user = user->next) {
10458                 rename_block_variables(state, user->member);
10459         }
10460         /* pop the renamed variable stack */
10461         last = block->first;
10462         done = 0;
10463         for(ptr = block->first; !done ; ptr = next) {
10464                 next = ptr->next;
10465                 if (ptr == block->last) {
10466                         done = 1;
10467                 }
10468                 if (ptr->op == OP_WRITE) {
10469                         struct triple *var;
10470                         var = LHS(ptr, 0);
10471                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10472                         pop_triple(var, RHS(ptr, 0));
10473                         release_triple(state, ptr);
10474                         continue;
10475                 }
10476                 if (ptr->op == OP_PHI) {
10477                         struct triple *var;
10478                         var = MISC(ptr, 0);
10479                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10480                         pop_triple(var, ptr);
10481                 }
10482                 last = ptr;
10483         }
10484         block->last = last;
10485 }
10486
10487 static void prune_block_variables(struct compile_state *state,
10488         struct block *block)
10489 {
10490         struct block_set *user;
10491         struct triple *next, *last, *ptr;
10492         int done;
10493         last = block->first;
10494         done = 0;
10495         for(ptr = block->first; !done; ptr = next) {
10496                 next = ptr->next;
10497                 if (ptr == block->last) {
10498                         done = 1;
10499                 }
10500                 if (ptr->op == OP_ADECL) {
10501                         struct triple_set *user, *next;
10502                         for(user = ptr->use; user; user = next) {
10503                                 struct triple *use;
10504                                 next = user->next;
10505                                 use = user->member;
10506                                 if (use->op != OP_PHI) {
10507                                         internal_error(state, use, "decl still used");
10508                                 }
10509                                 if (MISC(use, 0) != ptr) {
10510                                         internal_error(state, use, "bad phi use of decl");
10511                                 }
10512                                 unuse_triple(ptr, use);
10513                                 MISC(use, 0) = 0;
10514                         }
10515                         release_triple(state, ptr);
10516                         continue;
10517                 }
10518                 last = ptr;
10519         }
10520         block->last = last;
10521         for(user = block->idominates; user; user = user->next) {
10522                 prune_block_variables(state, user->member);
10523         }
10524 }
10525
10526 static void transform_to_ssa_form(struct compile_state *state)
10527 {
10528         insert_phi_operations(state);
10529 #if 0
10530         printf("@%s:%d\n", __FILE__, __LINE__);
10531         print_blocks(state, stdout);
10532 #endif
10533         rename_block_variables(state, state->first_block);
10534         prune_block_variables(state, state->first_block);
10535 }
10536
10537
10538 static void clear_vertex(
10539         struct compile_state *state, struct block *block, void *arg)
10540 {
10541         block->vertex = 0;
10542 }
10543
10544 static void mark_live_block(
10545         struct compile_state *state, struct block *block, int *next_vertex)
10546 {
10547         /* See if this is a block that has not been marked */
10548         if (block->vertex != 0) {
10549                 return;
10550         }
10551         block->vertex = *next_vertex;
10552         *next_vertex += 1;
10553         if (triple_is_branch(state, block->last)) {
10554                 struct triple **targ;
10555                 targ = triple_targ(state, block->last, 0);
10556                 for(; targ; targ = triple_targ(state, block->last, targ)) {
10557                         if (!*targ) {
10558                                 continue;
10559                         }
10560                         if (!triple_stores_block(state, *targ)) {
10561                                 internal_error(state, 0, "bad targ");
10562                         }
10563                         mark_live_block(state, (*targ)->u.block, next_vertex);
10564                 }
10565         }
10566         else if (block->last->next != RHS(state->main_function, 0)) {
10567                 struct triple *ins;
10568                 ins = block->last->next;
10569                 if (!triple_stores_block(state, ins)) {
10570                         internal_error(state, 0, "bad block start");
10571                 }
10572                 mark_live_block(state, ins->u.block, next_vertex);
10573         }
10574 }
10575
10576 static void transform_from_ssa_form(struct compile_state *state)
10577 {
10578         /* To get out of ssa form we insert moves on the incoming
10579          * edges to blocks containting phi functions.
10580          */
10581         struct triple *first;
10582         struct triple *phi, *next;
10583         int next_vertex;
10584
10585         /* Walk the control flow to see which blocks remain alive */
10586         walk_blocks(state, clear_vertex, 0);
10587         next_vertex = 1;
10588         mark_live_block(state, state->first_block, &next_vertex);
10589
10590         /* Walk all of the operations to find the phi functions */
10591         first = RHS(state->main_function, 0);
10592         for(phi = first->next; phi != first ; phi = next) {
10593                 struct block_set *set;
10594                 struct block *block;
10595                 struct triple **slot;
10596                 struct triple *var, *read;
10597                 struct triple_set *use, *use_next;
10598                 int edge, used;
10599                 next = phi->next;
10600                 if (phi->op != OP_PHI) {
10601                         continue;
10602                 }
10603                 block = phi->u.block;
10604                 slot  = &RHS(phi, 0);
10605
10606                 /* Forget uses from code in dead blocks */
10607                 for(use = phi->use; use; use = use_next) {
10608                         struct block *ublock;
10609                         struct triple **expr;
10610                         use_next = use->next;
10611                         ublock = block_of_triple(state, use->member);
10612                         if ((use->member == phi) || (ublock->vertex != 0)) {
10613                                 continue;
10614                         }
10615                         expr = triple_rhs(state, use->member, 0);
10616                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
10617                                 if (*expr == phi) {
10618                                         *expr = 0;
10619                                 }
10620                         }
10621                         unuse_triple(phi, use->member);
10622                 }
10623
10624                 /* A variable to replace the phi function */
10625                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10626                 /* A read of the single value that is set into the variable */
10627                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10628                 use_triple(var, read);
10629
10630                 /* Replaces uses of the phi with variable reads */
10631                 propogate_use(state, phi, read);
10632
10633                 /* Walk all of the incoming edges/blocks and insert moves.
10634                  */
10635                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10636                         struct block *eblock;
10637                         struct triple *move;
10638                         struct triple *val;
10639                         eblock = set->member;
10640                         val = slot[edge];
10641                         slot[edge] = 0;
10642                         unuse_triple(val, phi);
10643
10644                         if (!val || (val == &zero_triple) ||
10645                                 (block->vertex == 0) || (eblock->vertex == 0) ||
10646                                 (val == phi) || (val == read)) {
10647                                 continue;
10648                         }
10649                         
10650                         move = post_triple(state, 
10651                                 val, OP_WRITE, phi->type, var, val);
10652                         use_triple(val, move);
10653                         use_triple(var, move);
10654                 }               
10655                 /* See if there are any writers of var */
10656                 used = 0;
10657                 for(use = var->use; use; use = use->next) {
10658                         struct triple **expr;
10659                         expr = triple_lhs(state, use->member, 0);
10660                         for(; expr; expr = triple_lhs(state, use->member, expr)) {
10661                                 if (*expr == var) {
10662                                         used = 1;
10663                                 }
10664                         }
10665                 }
10666                 /* If var is not used free it */
10667                 if (!used) {
10668                         unuse_triple(var, read);
10669                         free_triple(state, read);
10670                         free_triple(state, var);
10671                 }
10672
10673                 /* Release the phi function */
10674                 release_triple(state, phi);
10675         }
10676         
10677 }
10678
10679
10680 /* 
10681  * Register conflict resolution
10682  * =========================================================
10683  */
10684
10685 static struct reg_info find_def_color(
10686         struct compile_state *state, struct triple *def)
10687 {
10688         struct triple_set *set;
10689         struct reg_info info;
10690         info.reg = REG_UNSET;
10691         info.regcm = 0;
10692         if (!triple_is_def(state, def)) {
10693                 return info;
10694         }
10695         info = arch_reg_lhs(state, def, 0);
10696         if (info.reg >= MAX_REGISTERS) {
10697                 info.reg = REG_UNSET;
10698         }
10699         for(set = def->use; set; set = set->next) {
10700                 struct reg_info tinfo;
10701                 int i;
10702                 i = find_rhs_use(state, set->member, def);
10703                 if (i < 0) {
10704                         continue;
10705                 }
10706                 tinfo = arch_reg_rhs(state, set->member, i);
10707                 if (tinfo.reg >= MAX_REGISTERS) {
10708                         tinfo.reg = REG_UNSET;
10709                 }
10710                 if ((tinfo.reg != REG_UNSET) && 
10711                         (info.reg != REG_UNSET) &&
10712                         (tinfo.reg != info.reg)) {
10713                         internal_error(state, def, "register conflict");
10714                 }
10715                 if ((info.regcm & tinfo.regcm) == 0) {
10716                         internal_error(state, def, "regcm conflict %x & %x == 0",
10717                                 info.regcm, tinfo.regcm);
10718                 }
10719                 if (info.reg == REG_UNSET) {
10720                         info.reg = tinfo.reg;
10721                 }
10722                 info.regcm &= tinfo.regcm;
10723         }
10724         if (info.reg >= MAX_REGISTERS) {
10725                 internal_error(state, def, "register out of range");
10726         }
10727         return info;
10728 }
10729
10730 static struct reg_info find_lhs_pre_color(
10731         struct compile_state *state, struct triple *ins, int index)
10732 {
10733         struct reg_info info;
10734         int zlhs, zrhs, i;
10735         zrhs = TRIPLE_RHS(ins->sizes);
10736         zlhs = TRIPLE_LHS(ins->sizes);
10737         if (!zlhs && triple_is_def(state, ins)) {
10738                 zlhs = 1;
10739         }
10740         if (index >= zlhs) {
10741                 internal_error(state, ins, "Bad lhs %d", index);
10742         }
10743         info = arch_reg_lhs(state, ins, index);
10744         for(i = 0; i < zrhs; i++) {
10745                 struct reg_info rinfo;
10746                 rinfo = arch_reg_rhs(state, ins, i);
10747                 if ((info.reg == rinfo.reg) &&
10748                         (rinfo.reg >= MAX_REGISTERS)) {
10749                         struct reg_info tinfo;
10750                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10751                         info.reg = tinfo.reg;
10752                         info.regcm &= tinfo.regcm;
10753                         break;
10754                 }
10755         }
10756         if (info.reg >= MAX_REGISTERS) {
10757                 info.reg = REG_UNSET;
10758         }
10759         return info;
10760 }
10761
10762 static struct reg_info find_rhs_post_color(
10763         struct compile_state *state, struct triple *ins, int index);
10764
10765 static struct reg_info find_lhs_post_color(
10766         struct compile_state *state, struct triple *ins, int index)
10767 {
10768         struct triple_set *set;
10769         struct reg_info info;
10770         struct triple *lhs;
10771 #if 0
10772         fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10773                 ins, index);
10774 #endif
10775         if ((index == 0) && triple_is_def(state, ins)) {
10776                 lhs = ins;
10777         }
10778         else if (index < TRIPLE_LHS(ins->sizes)) {
10779                 lhs = LHS(ins, index);
10780         }
10781         else {
10782                 internal_error(state, ins, "Bad lhs %d", index);
10783                 lhs = 0;
10784         }
10785         info = arch_reg_lhs(state, ins, index);
10786         if (info.reg >= MAX_REGISTERS) {
10787                 info.reg = REG_UNSET;
10788         }
10789         for(set = lhs->use; set; set = set->next) {
10790                 struct reg_info rinfo;
10791                 struct triple *user;
10792                 int zrhs, i;
10793                 user = set->member;
10794                 zrhs = TRIPLE_RHS(user->sizes);
10795                 for(i = 0; i < zrhs; i++) {
10796                         if (RHS(user, i) != lhs) {
10797                                 continue;
10798                         }
10799                         rinfo = find_rhs_post_color(state, user, i);
10800                         if ((info.reg != REG_UNSET) &&
10801                                 (rinfo.reg != REG_UNSET) &&
10802                                 (info.reg != rinfo.reg)) {
10803                                 internal_error(state, ins, "register conflict");
10804                         }
10805                         if ((info.regcm & rinfo.regcm) == 0) {
10806                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
10807                                         info.regcm, rinfo.regcm);
10808                         }
10809                         if (info.reg == REG_UNSET) {
10810                                 info.reg = rinfo.reg;
10811                         }
10812                         info.regcm &= rinfo.regcm;
10813                 }
10814         }
10815 #if 0
10816         fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10817                 ins, index, info.reg, info.regcm);
10818 #endif
10819         return info;
10820 }
10821
10822 static struct reg_info find_rhs_post_color(
10823         struct compile_state *state, struct triple *ins, int index)
10824 {
10825         struct reg_info info, rinfo;
10826         int zlhs, i;
10827 #if 0
10828         fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10829                 ins, index);
10830 #endif
10831         rinfo = arch_reg_rhs(state, ins, index);
10832         zlhs = TRIPLE_LHS(ins->sizes);
10833         if (!zlhs && triple_is_def(state, ins)) {
10834                 zlhs = 1;
10835         }
10836         info = rinfo;
10837         if (info.reg >= MAX_REGISTERS) {
10838                 info.reg = REG_UNSET;
10839         }
10840         for(i = 0; i < zlhs; i++) {
10841                 struct reg_info linfo;
10842                 linfo = arch_reg_lhs(state, ins, i);
10843                 if ((linfo.reg == rinfo.reg) &&
10844                         (linfo.reg >= MAX_REGISTERS)) {
10845                         struct reg_info tinfo;
10846                         tinfo = find_lhs_post_color(state, ins, i);
10847                         if (tinfo.reg >= MAX_REGISTERS) {
10848                                 tinfo.reg = REG_UNSET;
10849                         }
10850                         info.regcm &= linfo.reg;
10851                         info.regcm &= tinfo.regcm;
10852                         if (info.reg != REG_UNSET) {
10853                                 internal_error(state, ins, "register conflict");
10854                         }
10855                         if (info.regcm == 0) {
10856                                 internal_error(state, ins, "regcm conflict");
10857                         }
10858                         info.reg = tinfo.reg;
10859                 }
10860         }
10861 #if 0
10862         fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10863                 ins, index, info.reg, info.regcm);
10864 #endif
10865         return info;
10866 }
10867
10868 static struct reg_info find_lhs_color(
10869         struct compile_state *state, struct triple *ins, int index)
10870 {
10871         struct reg_info pre, post, info;
10872 #if 0
10873         fprintf(stderr, "find_lhs_color(%p, %d)\n",
10874                 ins, index);
10875 #endif
10876         pre = find_lhs_pre_color(state, ins, index);
10877         post = find_lhs_post_color(state, ins, index);
10878         if ((pre.reg != post.reg) &&
10879                 (pre.reg != REG_UNSET) &&
10880                 (post.reg != REG_UNSET)) {
10881                 internal_error(state, ins, "register conflict");
10882         }
10883         info.regcm = pre.regcm & post.regcm;
10884         info.reg = pre.reg;
10885         if (info.reg == REG_UNSET) {
10886                 info.reg = post.reg;
10887         }
10888 #if 0
10889         fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10890                 ins, index, info.reg, info.regcm);
10891 #endif
10892         return info;
10893 }
10894
10895 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10896 {
10897         struct triple_set *entry, *next;
10898         struct triple *out;
10899         struct reg_info info, rinfo;
10900
10901         info = arch_reg_lhs(state, ins, 0);
10902         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10903         use_triple(RHS(out, 0), out);
10904         /* Get the users of ins to use out instead */
10905         for(entry = ins->use; entry; entry = next) {
10906                 int i;
10907                 next = entry->next;
10908                 if (entry->member == out) {
10909                         continue;
10910                 }
10911                 i = find_rhs_use(state, entry->member, ins);
10912                 if (i < 0) {
10913                         continue;
10914                 }
10915                 rinfo = arch_reg_rhs(state, entry->member, i);
10916                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10917                         continue;
10918                 }
10919                 replace_rhs_use(state, ins, out, entry->member);
10920         }
10921         transform_to_arch_instruction(state, out);
10922         return out;
10923 }
10924
10925 static struct triple *pre_copy(
10926         struct compile_state *state, struct triple *ins, int index)
10927 {
10928         /* Carefully insert enough operations so that I can
10929          * enter any operation with a GPR32.
10930          */
10931         struct triple *in;
10932         struct triple **expr;
10933         if (ins->op == OP_PHI) {
10934                 internal_error(state, ins, "pre_copy on a phi?");
10935         }
10936         expr = &RHS(ins, index);
10937         in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10938         unuse_triple(*expr, ins);
10939         *expr = in;
10940         use_triple(RHS(in, 0), in);
10941         use_triple(in, ins);
10942         transform_to_arch_instruction(state, in);
10943         return in;
10944 }
10945
10946
10947 static void insert_copies_to_phi(struct compile_state *state)
10948 {
10949         /* To get out of ssa form we insert moves on the incoming
10950          * edges to blocks containting phi functions.
10951          */
10952         struct triple *first;
10953         struct triple *phi;
10954
10955         /* Walk all of the operations to find the phi functions */
10956         first = RHS(state->main_function, 0);
10957         for(phi = first->next; phi != first ; phi = phi->next) {
10958                 struct block_set *set;
10959                 struct block *block;
10960                 struct triple **slot;
10961                 int edge;
10962                 if (phi->op != OP_PHI) {
10963                         continue;
10964                 }
10965                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10966                 block = phi->u.block;
10967                 slot  = &RHS(phi, 0);
10968                 /* Walk all of the incoming edges/blocks and insert moves.
10969                  */
10970                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10971                         struct block *eblock;
10972                         struct triple *move;
10973                         struct triple *val;
10974                         struct triple *ptr;
10975                         eblock = set->member;
10976                         val = slot[edge];
10977
10978                         if (val == phi) {
10979                                 continue;
10980                         }
10981
10982                         get_occurance(val->occurance);
10983                         move = build_triple(state, OP_COPY, phi->type, val, 0,
10984                                 val->occurance);
10985                         move->u.block = eblock;
10986                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
10987                         use_triple(val, move);
10988                         
10989                         slot[edge] = move;
10990                         unuse_triple(val, phi);
10991                         use_triple(move, phi);
10992
10993                         /* Walk through the block backwards to find
10994                          * an appropriate location for the OP_COPY.
10995                          */
10996                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10997                                 struct triple **expr;
10998                                 if ((ptr == phi) || (ptr == val)) {
10999                                         goto out;
11000                                 }
11001                                 expr = triple_rhs(state, ptr, 0);
11002                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11003                                         if ((*expr) == phi) {
11004                                                 goto out;
11005                                         }
11006                                 }
11007                         }
11008                 out:
11009                         if (triple_is_branch(state, ptr)) {
11010                                 internal_error(state, ptr,
11011                                         "Could not insert write to phi");
11012                         }
11013                         insert_triple(state, ptr->next, move);
11014                         if (eblock->last == ptr) {
11015                                 eblock->last = move;
11016                         }
11017                         transform_to_arch_instruction(state, move);
11018                 }
11019         }
11020 }
11021
11022 struct triple_reg_set {
11023         struct triple_reg_set *next;
11024         struct triple *member;
11025         struct triple *new;
11026 };
11027
11028 struct reg_block {
11029         struct block *block;
11030         struct triple_reg_set *in;
11031         struct triple_reg_set *out;
11032         int vertex;
11033 };
11034
11035 static int do_triple_set(struct triple_reg_set **head, 
11036         struct triple *member, struct triple *new_member)
11037 {
11038         struct triple_reg_set **ptr, *new;
11039         if (!member)
11040                 return 0;
11041         ptr = head;
11042         while(*ptr) {
11043                 if ((*ptr)->member == member) {
11044                         return 0;
11045                 }
11046                 ptr = &(*ptr)->next;
11047         }
11048         new = xcmalloc(sizeof(*new), "triple_set");
11049         new->member = member;
11050         new->new    = new_member;
11051         new->next   = *head;
11052         *head       = new;
11053         return 1;
11054 }
11055
11056 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11057 {
11058         struct triple_reg_set *entry, **ptr;
11059         ptr = head;
11060         while(*ptr) {
11061                 entry = *ptr;
11062                 if (entry->member == member) {
11063                         *ptr = entry->next;
11064                         xfree(entry);
11065                         return;
11066                 }
11067                 else {
11068                         ptr = &entry->next;
11069                 }
11070         }
11071 }
11072
11073 static int in_triple(struct reg_block *rb, struct triple *in)
11074 {
11075         return do_triple_set(&rb->in, in, 0);
11076 }
11077 static void unin_triple(struct reg_block *rb, struct triple *unin)
11078 {
11079         do_triple_unset(&rb->in, unin);
11080 }
11081
11082 static int out_triple(struct reg_block *rb, struct triple *out)
11083 {
11084         return do_triple_set(&rb->out, out, 0);
11085 }
11086 static void unout_triple(struct reg_block *rb, struct triple *unout)
11087 {
11088         do_triple_unset(&rb->out, unout);
11089 }
11090
11091 static int initialize_regblock(struct reg_block *blocks,
11092         struct block *block, int vertex)
11093 {
11094         struct block_set *user;
11095         if (!block || (blocks[block->vertex].block == block)) {
11096                 return vertex;
11097         }
11098         vertex += 1;
11099         /* Renumber the blocks in a convinient fashion */
11100         block->vertex = vertex;
11101         blocks[vertex].block    = block;
11102         blocks[vertex].vertex   = vertex;
11103         for(user = block->use; user; user = user->next) {
11104                 vertex = initialize_regblock(blocks, user->member, vertex);
11105         }
11106         return vertex;
11107 }
11108
11109 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11110         struct reg_block *rb, struct block *suc)
11111 {
11112         /* Read the conditional input set of a successor block
11113          * (i.e. the input to the phi nodes) and place it in the
11114          * current blocks output set.
11115          */
11116         struct block_set *set;
11117         struct triple *ptr;
11118         int edge;
11119         int done, change;
11120         change = 0;
11121         /* Find the edge I am coming in on */
11122         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11123                 if (set->member == rb->block) {
11124                         break;
11125                 }
11126         }
11127         if (!set) {
11128                 internal_error(state, 0, "Not coming on a control edge?");
11129         }
11130         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11131                 struct triple **slot, *expr, *ptr2;
11132                 int out_change, done2;
11133                 done = (ptr == suc->last);
11134                 if (ptr->op != OP_PHI) {
11135                         continue;
11136                 }
11137                 slot = &RHS(ptr, 0);
11138                 expr = slot[edge];
11139                 out_change = out_triple(rb, expr);
11140                 if (!out_change) {
11141                         continue;
11142                 }
11143                 /* If we don't define the variable also plast it
11144                  * in the current blocks input set.
11145                  */
11146                 ptr2 = rb->block->first;
11147                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11148                         if (ptr2 == expr) {
11149                                 break;
11150                         }
11151                         done2 = (ptr2 == rb->block->last);
11152                 }
11153                 if (!done2) {
11154                         continue;
11155                 }
11156                 change |= in_triple(rb, expr);
11157         }
11158         return change;
11159 }
11160
11161 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11162         struct reg_block *rb, struct block *suc)
11163 {
11164         struct triple_reg_set *in_set;
11165         int change;
11166         change = 0;
11167         /* Read the input set of a successor block
11168          * and place it in the current blocks output set.
11169          */
11170         in_set = blocks[suc->vertex].in;
11171         for(; in_set; in_set = in_set->next) {
11172                 int out_change, done;
11173                 struct triple *first, *last, *ptr;
11174                 out_change = out_triple(rb, in_set->member);
11175                 if (!out_change) {
11176                         continue;
11177                 }
11178                 /* If we don't define the variable also place it
11179                  * in the current blocks input set.
11180                  */
11181                 first = rb->block->first;
11182                 last = rb->block->last;
11183                 done = 0;
11184                 for(ptr = first; !done; ptr = ptr->next) {
11185                         if (ptr == in_set->member) {
11186                                 break;
11187                         }
11188                         done = (ptr == last);
11189                 }
11190                 if (!done) {
11191                         continue;
11192                 }
11193                 change |= in_triple(rb, in_set->member);
11194         }
11195         change |= phi_in(state, blocks, rb, suc);
11196         return change;
11197 }
11198
11199
11200 static int use_in(struct compile_state *state, struct reg_block *rb)
11201 {
11202         /* Find the variables we use but don't define and add
11203          * it to the current blocks input set.
11204          */
11205 #warning "FIXME is this O(N^2) algorithm bad?"
11206         struct block *block;
11207         struct triple *ptr;
11208         int done;
11209         int change;
11210         block = rb->block;
11211         change = 0;
11212         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11213                 struct triple **expr;
11214                 done = (ptr == block->first);
11215                 /* The variable a phi function uses depends on the
11216                  * control flow, and is handled in phi_in, not
11217                  * here.
11218                  */
11219                 if (ptr->op == OP_PHI) {
11220                         continue;
11221                 }
11222                 expr = triple_rhs(state, ptr, 0);
11223                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11224                         struct triple *rhs, *test;
11225                         int tdone;
11226                         rhs = *expr;
11227                         if (!rhs) {
11228                                 continue;
11229                         }
11230                         /* See if rhs is defined in this block */
11231                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11232                                 tdone = (test == block->first);
11233                                 if (test == rhs) {
11234                                         rhs = 0;
11235                                         break;
11236                                 }
11237                         }
11238                         /* If I still have a valid rhs add it to in */
11239                         change |= in_triple(rb, rhs);
11240                 }
11241         }
11242         return change;
11243 }
11244
11245 static struct reg_block *compute_variable_lifetimes(
11246         struct compile_state *state)
11247 {
11248         struct reg_block *blocks;
11249         int change;
11250         blocks = xcmalloc(
11251                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11252         initialize_regblock(blocks, state->last_block, 0);
11253         do {
11254                 int i;
11255                 change = 0;
11256                 for(i = 1; i <= state->last_vertex; i++) {
11257                         struct reg_block *rb;
11258                         rb = &blocks[i];
11259                         /* Add the left successor's input set to in */
11260                         if (rb->block->left) {
11261                                 change |= reg_in(state, blocks, rb, rb->block->left);
11262                         }
11263                         /* Add the right successor's input set to in */
11264                         if ((rb->block->right) && 
11265                                 (rb->block->right != rb->block->left)) {
11266                                 change |= reg_in(state, blocks, rb, rb->block->right);
11267                         }
11268                         /* Add use to in... */
11269                         change |= use_in(state, rb);
11270                 }
11271         } while(change);
11272         return blocks;
11273 }
11274
11275 static void free_variable_lifetimes(
11276         struct compile_state *state, struct reg_block *blocks)
11277 {
11278         int i;
11279         /* free in_set && out_set on each block */
11280         for(i = 1; i <= state->last_vertex; i++) {
11281                 struct triple_reg_set *entry, *next;
11282                 struct reg_block *rb;
11283                 rb = &blocks[i];
11284                 for(entry = rb->in; entry ; entry = next) {
11285                         next = entry->next;
11286                         do_triple_unset(&rb->in, entry->member);
11287                 }
11288                 for(entry = rb->out; entry; entry = next) {
11289                         next = entry->next;
11290                         do_triple_unset(&rb->out, entry->member);
11291                 }
11292         }
11293         xfree(blocks);
11294
11295 }
11296
11297 typedef void (*wvl_cb_t)(
11298         struct compile_state *state, 
11299         struct reg_block *blocks, struct triple_reg_set *live, 
11300         struct reg_block *rb, struct triple *ins, void *arg);
11301
11302 static void walk_variable_lifetimes(struct compile_state *state,
11303         struct reg_block *blocks, wvl_cb_t cb, void *arg)
11304 {
11305         int i;
11306         
11307         for(i = 1; i <= state->last_vertex; i++) {
11308                 struct triple_reg_set *live;
11309                 struct triple_reg_set *entry, *next;
11310                 struct triple *ptr, *prev;
11311                 struct reg_block *rb;
11312                 struct block *block;
11313                 int done;
11314
11315                 /* Get the blocks */
11316                 rb = &blocks[i];
11317                 block = rb->block;
11318
11319                 /* Copy out into live */
11320                 live = 0;
11321                 for(entry = rb->out; entry; entry = next) {
11322                         next = entry->next;
11323                         do_triple_set(&live, entry->member, entry->new);
11324                 }
11325                 /* Walk through the basic block calculating live */
11326                 for(done = 0, ptr = block->last; !done; ptr = prev) {
11327                         struct triple **expr;
11328
11329                         prev = ptr->prev;
11330                         done = (ptr == block->first);
11331
11332                         /* Ensure the current definition is in live */
11333                         if (triple_is_def(state, ptr)) {
11334                                 do_triple_set(&live, ptr, 0);
11335                         }
11336
11337                         /* Inform the callback function of what is
11338                          * going on.
11339                          */
11340                          cb(state, blocks, live, rb, ptr, arg);
11341                         
11342                         /* Remove the current definition from live */
11343                         do_triple_unset(&live, ptr);
11344
11345                         /* Add the current uses to live.
11346                          *
11347                          * It is safe to skip phi functions because they do
11348                          * not have any block local uses, and the block
11349                          * output sets already properly account for what
11350                          * control flow depedent uses phi functions do have.
11351                          */
11352                         if (ptr->op == OP_PHI) {
11353                                 continue;
11354                         }
11355                         expr = triple_rhs(state, ptr, 0);
11356                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
11357                                 /* If the triple is not a definition skip it. */
11358                                 if (!*expr || !triple_is_def(state, *expr)) {
11359                                         continue;
11360                                 }
11361                                 do_triple_set(&live, *expr, 0);
11362                         }
11363                 }
11364                 /* Free live */
11365                 for(entry = live; entry; entry = next) {
11366                         next = entry->next;
11367                         do_triple_unset(&live, entry->member);
11368                 }
11369         }
11370 }
11371
11372 static int count_triples(struct compile_state *state)
11373 {
11374         struct triple *first, *ins;
11375         int triples = 0;
11376         first = RHS(state->main_function, 0);
11377         ins = first;
11378         do {
11379                 triples++;
11380                 ins = ins->next;
11381         } while (ins != first);
11382         return triples;
11383 }
11384 struct dead_triple {
11385         struct triple *triple;
11386         struct dead_triple *work_next;
11387         struct block *block;
11388         int color;
11389         int flags;
11390 #define TRIPLE_FLAG_ALIVE 1
11391 };
11392
11393
11394 static void awaken(
11395         struct compile_state *state,
11396         struct dead_triple *dtriple, struct triple **expr,
11397         struct dead_triple ***work_list_tail)
11398 {
11399         struct triple *triple;
11400         struct dead_triple *dt;
11401         if (!expr) {
11402                 return;
11403         }
11404         triple = *expr;
11405         if (!triple) {
11406                 return;
11407         }
11408         if (triple->id <= 0)  {
11409                 internal_error(state, triple, "bad triple id: %d",
11410                         triple->id);
11411         }
11412         if (triple->op == OP_NOOP) {
11413                 internal_warning(state, triple, "awakening noop?");
11414                 return;
11415         }
11416         dt = &dtriple[triple->id];
11417         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11418                 dt->flags |= TRIPLE_FLAG_ALIVE;
11419                 if (!dt->work_next) {
11420                         **work_list_tail = dt;
11421                         *work_list_tail = &dt->work_next;
11422                 }
11423         }
11424 }
11425
11426 static void eliminate_inefectual_code(struct compile_state *state)
11427 {
11428         struct block *block;
11429         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11430         int triples, i;
11431         struct triple *first, *ins;
11432
11433         /* Setup the work list */
11434         work_list = 0;
11435         work_list_tail = &work_list;
11436
11437         first = RHS(state->main_function, 0);
11438
11439         /* Count how many triples I have */
11440         triples = count_triples(state);
11441
11442         /* Now put then in an array and mark all of the triples dead */
11443         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11444         
11445         ins = first;
11446         i = 1;
11447         block = 0;
11448         do {
11449                 if (ins->op == OP_LABEL) {
11450                         block = ins->u.block;
11451                 }
11452                 dtriple[i].triple = ins;
11453                 dtriple[i].block  = block;
11454                 dtriple[i].flags  = 0;
11455                 dtriple[i].color  = ins->id;
11456                 ins->id = i;
11457                 /* See if it is an operation we always keep */
11458 #warning "FIXME handle the case of killing a branch instruction"
11459                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11460                         awaken(state, dtriple, &ins, &work_list_tail);
11461                 }
11462                 i++;
11463                 ins = ins->next;
11464         } while(ins != first);
11465         while(work_list) {
11466                 struct dead_triple *dt;
11467                 struct block_set *user;
11468                 struct triple **expr;
11469                 dt = work_list;
11470                 work_list = dt->work_next;
11471                 if (!work_list) {
11472                         work_list_tail = &work_list;
11473                 }
11474                 /* Wake up the data depencencies of this triple */
11475                 expr = 0;
11476                 do {
11477                         expr = triple_rhs(state, dt->triple, expr);
11478                         awaken(state, dtriple, expr, &work_list_tail);
11479                 } while(expr);
11480                 do {
11481                         expr = triple_lhs(state, dt->triple, expr);
11482                         awaken(state, dtriple, expr, &work_list_tail);
11483                 } while(expr);
11484                 do {
11485                         expr = triple_misc(state, dt->triple, expr);
11486                         awaken(state, dtriple, expr, &work_list_tail);
11487                 } while(expr);
11488                 /* Wake up the forward control dependencies */
11489                 do {
11490                         expr = triple_targ(state, dt->triple, expr);
11491                         awaken(state, dtriple, expr, &work_list_tail);
11492                 } while(expr);
11493                 /* Wake up the reverse control dependencies of this triple */
11494                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11495                         awaken(state, dtriple, &user->member->last, &work_list_tail);
11496                 }
11497         }
11498         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11499                 if ((dt->triple->op == OP_NOOP) && 
11500                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
11501                         internal_error(state, dt->triple, "noop effective?");
11502                 }
11503                 dt->triple->id = dt->color;     /* Restore the color */
11504                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11505 #warning "FIXME handle the case of killing a basic block"
11506                         if (dt->block->first == dt->triple) {
11507                                 continue;
11508                         }
11509                         if (dt->block->last == dt->triple) {
11510                                 dt->block->last = dt->triple->prev;
11511                         }
11512                         release_triple(state, dt->triple);
11513                 }
11514         }
11515         xfree(dtriple);
11516 }
11517
11518
11519 static void insert_mandatory_copies(struct compile_state *state)
11520 {
11521         struct triple *ins, *first;
11522
11523         /* The object is with a minimum of inserted copies,
11524          * to resolve in fundamental register conflicts between
11525          * register value producers and consumers.
11526          * Theoretically we may be greater than minimal when we
11527          * are inserting copies before instructions but that
11528          * case should be rare.
11529          */
11530         first = RHS(state->main_function, 0);
11531         ins = first;
11532         do {
11533                 struct triple_set *entry, *next;
11534                 struct triple *tmp;
11535                 struct reg_info info;
11536                 unsigned reg, regcm;
11537                 int do_post_copy, do_pre_copy;
11538                 tmp = 0;
11539                 if (!triple_is_def(state, ins)) {
11540                         goto next;
11541                 }
11542                 /* Find the architecture specific color information */
11543                 info = arch_reg_lhs(state, ins, 0);
11544                 if (info.reg >= MAX_REGISTERS) {
11545                         info.reg = REG_UNSET;
11546                 }
11547                 
11548                 reg = REG_UNSET;
11549                 regcm = arch_type_to_regcm(state, ins->type);
11550                 do_post_copy = do_pre_copy = 0;
11551
11552                 /* Walk through the uses of ins and check for conflicts */
11553                 for(entry = ins->use; entry; entry = next) {
11554                         struct reg_info rinfo;
11555                         int i;
11556                         next = entry->next;
11557                         i = find_rhs_use(state, entry->member, ins);
11558                         if (i < 0) {
11559                                 continue;
11560                         }
11561                         
11562                         /* Find the users color requirements */
11563                         rinfo = arch_reg_rhs(state, entry->member, i);
11564                         if (rinfo.reg >= MAX_REGISTERS) {
11565                                 rinfo.reg = REG_UNSET;
11566                         }
11567                         
11568                         /* See if I need a pre_copy */
11569                         if (rinfo.reg != REG_UNSET) {
11570                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11571                                         do_pre_copy = 1;
11572                                 }
11573                                 reg = rinfo.reg;
11574                         }
11575                         regcm &= rinfo.regcm;
11576                         regcm = arch_regcm_normalize(state, regcm);
11577                         if (regcm == 0) {
11578                                 do_pre_copy = 1;
11579                         }
11580                 }
11581                 do_post_copy =
11582                         !do_pre_copy &&
11583                         (((info.reg != REG_UNSET) && 
11584                                 (reg != REG_UNSET) &&
11585                                 (info.reg != reg)) ||
11586                         ((info.regcm & regcm) == 0));
11587
11588                 reg = info.reg;
11589                 regcm = info.regcm;
11590                 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11591                 for(entry = ins->use; entry; entry = next) {
11592                         struct reg_info rinfo;
11593                         int i;
11594                         next = entry->next;
11595                         i = find_rhs_use(state, entry->member, ins);
11596                         if (i < 0) {
11597                                 continue;
11598                         }
11599                         
11600                         /* Find the users color requirements */
11601                         rinfo = arch_reg_rhs(state, entry->member, i);
11602                         if (rinfo.reg >= MAX_REGISTERS) {
11603                                 rinfo.reg = REG_UNSET;
11604                         }
11605
11606                         /* Now see if it is time to do the pre_copy */
11607                         if (rinfo.reg != REG_UNSET) {
11608                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11609                                         ((regcm & rinfo.regcm) == 0) ||
11610                                         /* Don't let a mandatory coalesce sneak
11611                                          * into a operation that is marked to prevent
11612                                          * coalescing.
11613                                          */
11614                                         ((reg != REG_UNNEEDED) &&
11615                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11616                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11617                                         ) {
11618                                         if (do_pre_copy) {
11619                                                 struct triple *user;
11620                                                 user = entry->member;
11621                                                 if (RHS(user, i) != ins) {
11622                                                         internal_error(state, user, "bad rhs");
11623                                                 }
11624                                                 tmp = pre_copy(state, user, i);
11625                                                 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11626                                                 continue;
11627                                         } else {
11628                                                 do_post_copy = 1;
11629                                         }
11630                                 }
11631                                 reg = rinfo.reg;
11632                         }
11633                         if ((regcm & rinfo.regcm) == 0) {
11634                                 if (do_pre_copy) {
11635                                         struct triple *user;
11636                                         user = entry->member;
11637                                         if (RHS(user, i) != ins) {
11638                                                 internal_error(state, user, "bad rhs");
11639                                         }
11640                                         tmp = pre_copy(state, user, i);
11641                                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11642                                         continue;
11643                                 } else {
11644                                         do_post_copy = 1;
11645                                 }
11646                         }
11647                         regcm &= rinfo.regcm;
11648                         
11649                 }
11650                 if (do_post_copy) {
11651                         struct reg_info pre, post;
11652                         tmp = post_copy(state, ins);
11653                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11654                         pre = arch_reg_lhs(state, ins, 0);
11655                         post = arch_reg_lhs(state, tmp, 0);
11656                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11657                                 internal_error(state, tmp, "useless copy");
11658                         }
11659                 }
11660         next:
11661                 ins = ins->next;
11662         } while(ins != first);
11663 }
11664
11665
11666 struct live_range_edge;
11667 struct live_range_def;
11668 struct live_range {
11669         struct live_range_edge *edges;
11670         struct live_range_def *defs;
11671 /* Note. The list pointed to by defs is kept in order.
11672  * That is baring splits in the flow control
11673  * defs dominates defs->next wich dominates defs->next->next
11674  * etc.
11675  */
11676         unsigned color;
11677         unsigned classes;
11678         unsigned degree;
11679         unsigned length;
11680         struct live_range *group_next, **group_prev;
11681 };
11682
11683 struct live_range_edge {
11684         struct live_range_edge *next;
11685         struct live_range *node;
11686 };
11687
11688 struct live_range_def {
11689         struct live_range_def *next;
11690         struct live_range_def *prev;
11691         struct live_range *lr;
11692         struct triple *def;
11693         unsigned orig_id;
11694 };
11695
11696 #define LRE_HASH_SIZE 2048
11697 struct lre_hash {
11698         struct lre_hash *next;
11699         struct live_range *left;
11700         struct live_range *right;
11701 };
11702
11703
11704 struct reg_state {
11705         struct lre_hash *hash[LRE_HASH_SIZE];
11706         struct reg_block *blocks;
11707         struct live_range_def *lrd;
11708         struct live_range *lr;
11709         struct live_range *low, **low_tail;
11710         struct live_range *high, **high_tail;
11711         unsigned defs;
11712         unsigned ranges;
11713         int passes, max_passes;
11714 #define MAX_ALLOCATION_PASSES 100
11715 };
11716
11717
11718 static unsigned regc_max_size(struct compile_state *state, int classes)
11719 {
11720         unsigned max_size;
11721         int i;
11722         max_size = 0;
11723         for(i = 0; i < MAX_REGC; i++) {
11724                 if (classes & (1 << i)) {
11725                         unsigned size;
11726                         size = arch_regc_size(state, i);
11727                         if (size > max_size) {
11728                                 max_size = size;
11729                         }
11730                 }
11731         }
11732         return max_size;
11733 }
11734
11735 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11736 {
11737         unsigned equivs[MAX_REG_EQUIVS];
11738         int i;
11739         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11740                 internal_error(state, 0, "invalid register");
11741         }
11742         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11743                 internal_error(state, 0, "invalid register");
11744         }
11745         arch_reg_equivs(state, equivs, reg1);
11746         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11747                 if (equivs[i] == reg2) {
11748                         return 1;
11749                 }
11750         }
11751         return 0;
11752 }
11753
11754 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11755 {
11756         unsigned equivs[MAX_REG_EQUIVS];
11757         int i;
11758         if (reg == REG_UNNEEDED) {
11759                 return;
11760         }
11761         arch_reg_equivs(state, equivs, reg);
11762         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11763                 used[equivs[i]] = 1;
11764         }
11765         return;
11766 }
11767
11768 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11769 {
11770         unsigned equivs[MAX_REG_EQUIVS];
11771         int i;
11772         if (reg == REG_UNNEEDED) {
11773                 return;
11774         }
11775         arch_reg_equivs(state, equivs, reg);
11776         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11777                 used[equivs[i]] += 1;
11778         }
11779         return;
11780 }
11781
11782 static unsigned int hash_live_edge(
11783         struct live_range *left, struct live_range *right)
11784 {
11785         unsigned int hash, val;
11786         unsigned long lval, rval;
11787         lval = ((unsigned long)left)/sizeof(struct live_range);
11788         rval = ((unsigned long)right)/sizeof(struct live_range);
11789         hash = 0;
11790         while(lval) {
11791                 val = lval & 0xff;
11792                 lval >>= 8;
11793                 hash = (hash *263) + val;
11794         }
11795         while(rval) {
11796                 val = rval & 0xff;
11797                 rval >>= 8;
11798                 hash = (hash *263) + val;
11799         }
11800         hash = hash & (LRE_HASH_SIZE - 1);
11801         return hash;
11802 }
11803
11804 static struct lre_hash **lre_probe(struct reg_state *rstate,
11805         struct live_range *left, struct live_range *right)
11806 {
11807         struct lre_hash **ptr;
11808         unsigned int index;
11809         /* Ensure left <= right */
11810         if (left > right) {
11811                 struct live_range *tmp;
11812                 tmp = left;
11813                 left = right;
11814                 right = tmp;
11815         }
11816         index = hash_live_edge(left, right);
11817         
11818         ptr = &rstate->hash[index];
11819         while(*ptr) {
11820                 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
11821                         break;
11822                 }
11823                 ptr = &(*ptr)->next;
11824         }
11825         return ptr;
11826 }
11827
11828 static int interfere(struct reg_state *rstate,
11829         struct live_range *left, struct live_range *right)
11830 {
11831         struct lre_hash **ptr;
11832         ptr = lre_probe(rstate, left, right);
11833         return ptr && *ptr;
11834 }
11835
11836 static void add_live_edge(struct reg_state *rstate, 
11837         struct live_range *left, struct live_range *right)
11838 {
11839         /* FIXME the memory allocation overhead is noticeable here... */
11840         struct lre_hash **ptr, *new_hash;
11841         struct live_range_edge *edge;
11842
11843         if (left == right) {
11844                 return;
11845         }
11846         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11847                 return;
11848         }
11849         /* Ensure left <= right */
11850         if (left > right) {
11851                 struct live_range *tmp;
11852                 tmp = left;
11853                 left = right;
11854                 right = tmp;
11855         }
11856         ptr = lre_probe(rstate, left, right);
11857         if (*ptr) {
11858                 return;
11859         }
11860 #if 0
11861         fprintf(stderr, "new_live_edge(%p, %p)\n",
11862                 left, right);
11863 #endif
11864         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11865         new_hash->next  = *ptr;
11866         new_hash->left  = left;
11867         new_hash->right = right;
11868         *ptr = new_hash;
11869
11870         edge = xmalloc(sizeof(*edge), "live_range_edge");
11871         edge->next   = left->edges;
11872         edge->node   = right;
11873         left->edges  = edge;
11874         left->degree += 1;
11875         
11876         edge = xmalloc(sizeof(*edge), "live_range_edge");
11877         edge->next    = right->edges;
11878         edge->node    = left;
11879         right->edges  = edge;
11880         right->degree += 1;
11881 }
11882
11883 static void remove_live_edge(struct reg_state *rstate,
11884         struct live_range *left, struct live_range *right)
11885 {
11886         struct live_range_edge *edge, **ptr;
11887         struct lre_hash **hptr, *entry;
11888         hptr = lre_probe(rstate, left, right);
11889         if (!hptr || !*hptr) {
11890                 return;
11891         }
11892         entry = *hptr;
11893         *hptr = entry->next;
11894         xfree(entry);
11895
11896         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11897                 edge = *ptr;
11898                 if (edge->node == right) {
11899                         *ptr = edge->next;
11900                         memset(edge, 0, sizeof(*edge));
11901                         xfree(edge);
11902                         right->degree--;
11903                         break;
11904                 }
11905         }
11906         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11907                 edge = *ptr;
11908                 if (edge->node == left) {
11909                         *ptr = edge->next;
11910                         memset(edge, 0, sizeof(*edge));
11911                         xfree(edge);
11912                         left->degree--;
11913                         break;
11914                 }
11915         }
11916 }
11917
11918 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11919 {
11920         struct live_range_edge *edge, *next;
11921         for(edge = range->edges; edge; edge = next) {
11922                 next = edge->next;
11923                 remove_live_edge(rstate, range, edge->node);
11924         }
11925 }
11926
11927 static void transfer_live_edges(struct reg_state *rstate, 
11928         struct live_range *dest, struct live_range *src)
11929 {
11930         struct live_range_edge *edge, *next;
11931         for(edge = src->edges; edge; edge = next) {
11932                 struct live_range *other;
11933                 next = edge->next;
11934                 other = edge->node;
11935                 remove_live_edge(rstate, src, other);
11936                 add_live_edge(rstate, dest, other);
11937         }
11938 }
11939
11940
11941 /* Interference graph...
11942  * 
11943  * new(n) --- Return a graph with n nodes but no edges.
11944  * add(g,x,y) --- Return a graph including g with an between x and y
11945  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11946  *                x and y in the graph g
11947  * degree(g, x) --- Return the degree of the node x in the graph g
11948  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11949  *
11950  * Implement with a hash table && a set of adjcency vectors.
11951  * The hash table supports constant time implementations of add and interfere.
11952  * The adjacency vectors support an efficient implementation of neighbors.
11953  */
11954
11955 /* 
11956  *     +---------------------------------------------------+
11957  *     |         +--------------+                          |
11958  *     v         v              |                          |
11959  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
11960  *
11961  * -- In simplify implment optimistic coloring... (No backtracking)
11962  * -- Implement Rematerialization it is the only form of spilling we can perform
11963  *    Essentially this means dropping a constant from a register because
11964  *    we can regenerate it later.
11965  *
11966  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11967  *     coalesce at phi points...
11968  * --- Bias coloring if at all possible do the coalesing a compile time.
11969  *
11970  *
11971  */
11972
11973 static void different_colored(
11974         struct compile_state *state, struct reg_state *rstate, 
11975         struct triple *parent, struct triple *ins)
11976 {
11977         struct live_range *lr;
11978         struct triple **expr;
11979         lr = rstate->lrd[ins->id].lr;
11980         expr = triple_rhs(state, ins, 0);
11981         for(;expr; expr = triple_rhs(state, ins, expr)) {
11982                 struct live_range *lr2;
11983                 if (!*expr || (*expr == parent) || (*expr == ins)) {
11984                         continue;
11985                 }
11986                 lr2 = rstate->lrd[(*expr)->id].lr;
11987                 if (lr->color == lr2->color) {
11988                         internal_error(state, ins, "live range too big");
11989                 }
11990         }
11991 }
11992
11993
11994 static struct live_range *coalesce_ranges(
11995         struct compile_state *state, struct reg_state *rstate,
11996         struct live_range *lr1, struct live_range *lr2)
11997 {
11998         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11999         unsigned color;
12000         unsigned classes;
12001         if (lr1 == lr2) {
12002                 return lr1;
12003         }
12004         if (!lr1->defs || !lr2->defs) {
12005                 internal_error(state, 0,
12006                         "cannot coalese dead live ranges");
12007         }
12008         if ((lr1->color == REG_UNNEEDED) ||
12009                 (lr2->color == REG_UNNEEDED)) {
12010                 internal_error(state, 0, 
12011                         "cannot coalesce live ranges without a possible color");
12012         }
12013         if ((lr1->color != lr2->color) &&
12014                 (lr1->color != REG_UNSET) &&
12015                 (lr2->color != REG_UNSET)) {
12016                 internal_error(state, lr1->defs->def, 
12017                         "cannot coalesce live ranges of different colors");
12018         }
12019         color = lr1->color;
12020         if (color == REG_UNSET) {
12021                 color = lr2->color;
12022         }
12023         classes = lr1->classes & lr2->classes;
12024         if (!classes) {
12025                 internal_error(state, lr1->defs->def,
12026                         "cannot coalesce live ranges with dissimilar register classes");
12027         }
12028         /* If there is a clear dominate live range put it in lr1,
12029          * For purposes of this test phi functions are
12030          * considered dominated by the definitions that feed into
12031          * them. 
12032          */
12033         if ((lr1->defs->prev->def->op == OP_PHI) ||
12034                 ((lr2->defs->prev->def->op != OP_PHI) &&
12035                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12036                 struct live_range *tmp;
12037                 tmp = lr1;
12038                 lr1 = lr2;
12039                 lr2 = tmp;
12040         }
12041 #if 0
12042         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
12043                 fprintf(stderr, "lr1 post\n");
12044         }
12045         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12046                 fprintf(stderr, "lr1 pre\n");
12047         }
12048         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
12049                 fprintf(stderr, "lr2 post\n");
12050         }
12051         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12052                 fprintf(stderr, "lr2 pre\n");
12053         }
12054 #endif
12055 #if 0
12056         fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12057                 lr1->defs->def,
12058                 lr1->color,
12059                 lr2->defs->def,
12060                 lr2->color);
12061 #endif
12062         
12063         lr1->classes = classes;
12064         /* Append lr2 onto lr1 */
12065 #warning "FIXME should this be a merge instead of a splice?"
12066         /* This FIXME item applies to the correctness of live_range_end 
12067          * and to the necessity of making multiple passes of coalesce_live_ranges.
12068          * A failure to find some coalesce opportunities in coaleace_live_ranges
12069          * does not impact the correct of the compiler just the efficiency with
12070          * which registers are allocated.
12071          */
12072         head = lr1->defs;
12073         mid1 = lr1->defs->prev;
12074         mid2 = lr2->defs;
12075         end  = lr2->defs->prev;
12076         
12077         head->prev = end;
12078         end->next  = head;
12079
12080         mid1->next = mid2;
12081         mid2->prev = mid1;
12082
12083         /* Fixup the live range in the added live range defs */
12084         lrd = head;
12085         do {
12086                 lrd->lr = lr1;
12087                 lrd = lrd->next;
12088         } while(lrd != head);
12089
12090         /* Mark lr2 as free. */
12091         lr2->defs = 0;
12092         lr2->color = REG_UNNEEDED;
12093         lr2->classes = 0;
12094
12095         if (!lr1->defs) {
12096                 internal_error(state, 0, "lr1->defs == 0 ?");
12097         }
12098
12099         lr1->color   = color;
12100         lr1->classes = classes;
12101
12102         /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12103         transfer_live_edges(rstate, lr1, lr2);
12104
12105         return lr1;
12106 }
12107
12108 static struct live_range_def *live_range_head(
12109         struct compile_state *state, struct live_range *lr,
12110         struct live_range_def *last)
12111 {
12112         struct live_range_def *result;
12113         result = 0;
12114         if (last == 0) {
12115                 result = lr->defs;
12116         }
12117         else if (!tdominates(state, lr->defs->def, last->next->def)) {
12118                 result = last->next;
12119         }
12120         return result;
12121 }
12122
12123 static struct live_range_def *live_range_end(
12124         struct compile_state *state, struct live_range *lr,
12125         struct live_range_def *last)
12126 {
12127         struct live_range_def *result;
12128         result = 0;
12129         if (last == 0) {
12130                 result = lr->defs->prev;
12131         }
12132         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12133                 result = last->prev;
12134         }
12135         return result;
12136 }
12137
12138
12139 static void initialize_live_ranges(
12140         struct compile_state *state, struct reg_state *rstate)
12141 {
12142         struct triple *ins, *first;
12143         size_t count, size;
12144         int i, j;
12145
12146         first = RHS(state->main_function, 0);
12147         /* First count how many instructions I have.
12148          */
12149         count = count_triples(state);
12150         /* Potentially I need one live range definitions for each
12151          * instruction, plus an extra for the split routines.
12152          */
12153         rstate->defs = count + 1;
12154         /* Potentially I need one live range for each instruction
12155          * plus an extra for the dummy live range.
12156          */
12157         rstate->ranges = count + 1;
12158         size = sizeof(rstate->lrd[0]) * rstate->defs;
12159         rstate->lrd = xcmalloc(size, "live_range_def");
12160         size = sizeof(rstate->lr[0]) * rstate->ranges;
12161         rstate->lr  = xcmalloc(size, "live_range");
12162
12163         /* Setup the dummy live range */
12164         rstate->lr[0].classes = 0;
12165         rstate->lr[0].color = REG_UNSET;
12166         rstate->lr[0].defs = 0;
12167         i = j = 0;
12168         ins = first;
12169         do {
12170                 /* If the triple is a variable give it a live range */
12171                 if (triple_is_def(state, ins)) {
12172                         struct reg_info info;
12173                         /* Find the architecture specific color information */
12174                         info = find_def_color(state, ins);
12175
12176                         i++;
12177                         rstate->lr[i].defs    = &rstate->lrd[j];
12178                         rstate->lr[i].color   = info.reg;
12179                         rstate->lr[i].classes = info.regcm;
12180                         rstate->lr[i].degree  = 0;
12181                         rstate->lrd[j].lr = &rstate->lr[i];
12182                 } 
12183                 /* Otherwise give the triple the dummy live range. */
12184                 else {
12185                         rstate->lrd[j].lr = &rstate->lr[0];
12186                 }
12187
12188                 /* Initalize the live_range_def */
12189                 rstate->lrd[j].next    = &rstate->lrd[j];
12190                 rstate->lrd[j].prev    = &rstate->lrd[j];
12191                 rstate->lrd[j].def     = ins;
12192                 rstate->lrd[j].orig_id = ins->id;
12193                 ins->id = j;
12194
12195                 j++;
12196                 ins = ins->next;
12197         } while(ins != first);
12198         rstate->ranges = i;
12199         rstate->defs -= 1;
12200
12201         /* Make a second pass to handle achitecture specific register
12202          * constraints.
12203          */
12204         ins = first;
12205         do {
12206                 int zlhs, zrhs, i, j;
12207                 if (ins->id > rstate->defs) {
12208                         internal_error(state, ins, "bad id");
12209                 }
12210                 
12211                 /* Walk through the template of ins and coalesce live ranges */
12212                 zlhs = TRIPLE_LHS(ins->sizes);
12213                 if ((zlhs == 0) && triple_is_def(state, ins)) {
12214                         zlhs = 1;
12215                 }
12216                 zrhs = TRIPLE_RHS(ins->sizes);
12217                 
12218                 for(i = 0; i < zlhs; i++) {
12219                         struct reg_info linfo;
12220                         struct live_range_def *lhs;
12221                         linfo = arch_reg_lhs(state, ins, i);
12222                         if (linfo.reg < MAX_REGISTERS) {
12223                                 continue;
12224                         }
12225                         if (triple_is_def(state, ins)) {
12226                                 lhs = &rstate->lrd[ins->id];
12227                         } else {
12228                                 lhs = &rstate->lrd[LHS(ins, i)->id];
12229                         }
12230                         for(j = 0; j < zrhs; j++) {
12231                                 struct reg_info rinfo;
12232                                 struct live_range_def *rhs;
12233                                 rinfo = arch_reg_rhs(state, ins, j);
12234                                 if (rinfo.reg < MAX_REGISTERS) {
12235                                         continue;
12236                                 }
12237                                 rhs = &rstate->lrd[RHS(ins, i)->id];
12238                                 if (rinfo.reg == linfo.reg) {
12239                                         coalesce_ranges(state, rstate, 
12240                                                 lhs->lr, rhs->lr);
12241                                 }
12242                         }
12243                 }
12244                 ins = ins->next;
12245         } while(ins != first);
12246 }
12247
12248 static void graph_ins(
12249         struct compile_state *state, 
12250         struct reg_block *blocks, struct triple_reg_set *live, 
12251         struct reg_block *rb, struct triple *ins, void *arg)
12252 {
12253         struct reg_state *rstate = arg;
12254         struct live_range *def;
12255         struct triple_reg_set *entry;
12256
12257         /* If the triple is not a definition
12258          * we do not have a definition to add to
12259          * the interference graph.
12260          */
12261         if (!triple_is_def(state, ins)) {
12262                 return;
12263         }
12264         def = rstate->lrd[ins->id].lr;
12265         
12266         /* Create an edge between ins and everything that is
12267          * alive, unless the live_range cannot share
12268          * a physical register with ins.
12269          */
12270         for(entry = live; entry; entry = entry->next) {
12271                 struct live_range *lr;
12272                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12273                         internal_error(state, 0, "bad entry?");
12274                 }
12275                 lr = rstate->lrd[entry->member->id].lr;
12276                 if (def == lr) {
12277                         continue;
12278                 }
12279                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12280                         continue;
12281                 }
12282                 add_live_edge(rstate, def, lr);
12283         }
12284         return;
12285 }
12286
12287 static struct live_range *get_verify_live_range(
12288         struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12289 {
12290         struct live_range *lr;
12291         struct live_range_def *lrd;
12292         int ins_found;
12293         if ((ins->id < 0) || (ins->id > rstate->defs)) {
12294                 internal_error(state, ins, "bad ins?");
12295         }
12296         lr = rstate->lrd[ins->id].lr;
12297         ins_found = 0;
12298         lrd = lr->defs;
12299         do {
12300                 if (lrd->def == ins) {
12301                         ins_found = 1;
12302                 }
12303                 lrd = lrd->next;
12304         } while(lrd != lr->defs);
12305         if (!ins_found) {
12306                 internal_error(state, ins, "ins not in live range");
12307         }
12308         return lr;
12309 }
12310
12311 static void verify_graph_ins(
12312         struct compile_state *state, 
12313         struct reg_block *blocks, struct triple_reg_set *live, 
12314         struct reg_block *rb, struct triple *ins, void *arg)
12315 {
12316         struct reg_state *rstate = arg;
12317         struct triple_reg_set *entry1, *entry2;
12318
12319
12320         /* Compare live against edges and make certain the code is working */
12321         for(entry1 = live; entry1; entry1 = entry1->next) {
12322                 struct live_range *lr1;
12323                 lr1 = get_verify_live_range(state, rstate, entry1->member);
12324                 for(entry2 = live; entry2; entry2 = entry2->next) {
12325                         struct live_range *lr2;
12326                         struct live_range_edge *edge2;
12327                         int lr1_found;
12328                         int lr2_degree;
12329                         if (entry2 == entry1) {
12330                                 continue;
12331                         }
12332                         lr2 = get_verify_live_range(state, rstate, entry2->member);
12333                         if (lr1 == lr2) {
12334                                 internal_error(state, entry2->member, 
12335                                         "live range with 2 values simultaneously alive");
12336                         }
12337                         if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12338                                 continue;
12339                         }
12340                         if (!interfere(rstate, lr1, lr2)) {
12341                                 internal_error(state, entry2->member, 
12342                                         "edges don't interfere?");
12343                         }
12344                                 
12345                         lr1_found = 0;
12346                         lr2_degree = 0;
12347                         for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12348                                 lr2_degree++;
12349                                 if (edge2->node == lr1) {
12350                                         lr1_found = 1;
12351                                 }
12352                         }
12353                         if (lr2_degree != lr2->degree) {
12354                                 internal_error(state, entry2->member,
12355                                         "computed degree: %d does not match reported degree: %d\n",
12356                                         lr2_degree, lr2->degree);
12357                         }
12358                         if (!lr1_found) {
12359                                 internal_error(state, entry2->member, "missing edge");
12360                         }
12361                 }
12362         }
12363         return;
12364 }
12365
12366
12367 static void print_interference_ins(
12368         struct compile_state *state, 
12369         struct reg_block *blocks, struct triple_reg_set *live, 
12370         struct reg_block *rb, struct triple *ins, void *arg)
12371 {
12372         struct reg_state *rstate = arg;
12373         struct live_range *lr;
12374         unsigned id;
12375
12376         lr = rstate->lrd[ins->id].lr;
12377         id = ins->id;
12378         ins->id = rstate->lrd[id].orig_id;
12379         SET_REG(ins->id, lr->color);
12380         display_triple(stdout, ins);
12381         ins->id = id;
12382
12383         if (lr->defs) {
12384                 struct live_range_def *lrd;
12385                 printf("       range:");
12386                 lrd = lr->defs;
12387                 do {
12388                         printf(" %-10p", lrd->def);
12389                         lrd = lrd->next;
12390                 } while(lrd != lr->defs);
12391                 printf("\n");
12392         }
12393         if (live) {
12394                 struct triple_reg_set *entry;
12395                 printf("        live:");
12396                 for(entry = live; entry; entry = entry->next) {
12397                         printf(" %-10p", entry->member);
12398                 }
12399                 printf("\n");
12400         }
12401         if (lr->edges) {
12402                 struct live_range_edge *entry;
12403                 printf("       edges:");
12404                 for(entry = lr->edges; entry; entry = entry->next) {
12405                         struct live_range_def *lrd;
12406                         lrd = entry->node->defs;
12407                         do {
12408                                 printf(" %-10p", lrd->def);
12409                                 lrd = lrd->next;
12410                         } while(lrd != entry->node->defs);
12411                         printf("|");
12412                 }
12413                 printf("\n");
12414         }
12415         if (triple_is_branch(state, ins)) {
12416                 printf("\n");
12417         }
12418         return;
12419 }
12420
12421 static int coalesce_live_ranges(
12422         struct compile_state *state, struct reg_state *rstate)
12423 {
12424         /* At the point where a value is moved from one
12425          * register to another that value requires two
12426          * registers, thus increasing register pressure.
12427          * Live range coaleescing reduces the register
12428          * pressure by keeping a value in one register
12429          * longer.
12430          *
12431          * In the case of a phi function all paths leading
12432          * into it must be allocated to the same register
12433          * otherwise the phi function may not be removed.
12434          *
12435          * Forcing a value to stay in a single register
12436          * for an extended period of time does have
12437          * limitations when applied to non homogenous
12438          * register pool.  
12439          *
12440          * The two cases I have identified are:
12441          * 1) Two forced register assignments may
12442          *    collide.
12443          * 2) Registers may go unused because they
12444          *    are only good for storing the value
12445          *    and not manipulating it.
12446          *
12447          * Because of this I need to split live ranges,
12448          * even outside of the context of coalesced live
12449          * ranges.  The need to split live ranges does
12450          * impose some constraints on live range coalescing.
12451          *
12452          * - Live ranges may not be coalesced across phi
12453          *   functions.  This creates a 2 headed live
12454          *   range that cannot be sanely split.
12455          *
12456          * - phi functions (coalesced in initialize_live_ranges) 
12457          *   are handled as pre split live ranges so we will
12458          *   never attempt to split them.
12459          */
12460         int coalesced;
12461         int i;
12462
12463         coalesced = 0;
12464         for(i = 0; i <= rstate->ranges; i++) {
12465                 struct live_range *lr1;
12466                 struct live_range_def *lrd1;
12467                 lr1 = &rstate->lr[i];
12468                 if (!lr1->defs) {
12469                         continue;
12470                 }
12471                 lrd1 = live_range_end(state, lr1, 0);
12472                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12473                         struct triple_set *set;
12474                         if (lrd1->def->op != OP_COPY) {
12475                                 continue;
12476                         }
12477                         /* Skip copies that are the result of a live range split. */
12478                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12479                                 continue;
12480                         }
12481                         for(set = lrd1->def->use; set; set = set->next) {
12482                                 struct live_range_def *lrd2;
12483                                 struct live_range *lr2, *res;
12484
12485                                 lrd2 = &rstate->lrd[set->member->id];
12486
12487                                 /* Don't coalesce with instructions
12488                                  * that are the result of a live range
12489                                  * split.
12490                                  */
12491                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12492                                         continue;
12493                                 }
12494                                 lr2 = rstate->lrd[set->member->id].lr;
12495                                 if (lr1 == lr2) {
12496                                         continue;
12497                                 }
12498                                 if ((lr1->color != lr2->color) &&
12499                                         (lr1->color != REG_UNSET) &&
12500                                         (lr2->color != REG_UNSET)) {
12501                                         continue;
12502                                 }
12503                                 if ((lr1->classes & lr2->classes) == 0) {
12504                                         continue;
12505                                 }
12506                                 
12507                                 if (interfere(rstate, lr1, lr2)) {
12508                                         continue;
12509                                 }
12510
12511                                 res = coalesce_ranges(state, rstate, lr1, lr2);
12512                                 coalesced += 1;
12513                                 if (res != lr1) {
12514                                         goto next;
12515                                 }
12516                         }
12517                 }
12518         next:
12519                 ;
12520         }
12521         return coalesced;
12522 }
12523
12524
12525 static void fix_coalesce_conflicts(struct compile_state *state,
12526         struct reg_block *blocks, struct triple_reg_set *live,
12527         struct reg_block *rb, struct triple *ins, void *arg)
12528 {
12529         int zlhs, zrhs, i, j;
12530
12531         /* See if we have a mandatory coalesce operation between
12532          * a lhs and a rhs value.  If so and the rhs value is also
12533          * alive then this triple needs to be pre copied.  Otherwise
12534          * we would have two definitions in the same live range simultaneously
12535          * alive.
12536          */
12537         zlhs = TRIPLE_LHS(ins->sizes);
12538         if ((zlhs == 0) && triple_is_def(state, ins)) {
12539                 zlhs = 1;
12540         }
12541         zrhs = TRIPLE_RHS(ins->sizes);
12542         for(i = 0; i < zlhs; i++) {
12543                 struct reg_info linfo;
12544                 linfo = arch_reg_lhs(state, ins, i);
12545                 if (linfo.reg < MAX_REGISTERS) {
12546                         continue;
12547                 }
12548                 for(j = 0; j < zrhs; j++) {
12549                         struct reg_info rinfo;
12550                         struct triple *rhs;
12551                         struct triple_reg_set *set;
12552                         int found;
12553                         found = 0;
12554                         rinfo = arch_reg_rhs(state, ins, j);
12555                         if (rinfo.reg != linfo.reg) {
12556                                 continue;
12557                         }
12558                         rhs = RHS(ins, j);
12559                         for(set = live; set && !found; set = set->next) {
12560                                 if (set->member == rhs) {
12561                                         found = 1;
12562                                 }
12563                         }
12564                         if (found) {
12565                                 struct triple *copy;
12566                                 copy = pre_copy(state, ins, j);
12567                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12568                         }
12569                 }
12570         }
12571         return;
12572 }
12573
12574 static void replace_set_use(struct compile_state *state,
12575         struct triple_reg_set *head, struct triple *orig, struct triple *new)
12576 {
12577         struct triple_reg_set *set;
12578         for(set = head; set; set = set->next) {
12579                 if (set->member == orig) {
12580                         set->member = new;
12581                 }
12582         }
12583 }
12584
12585 static void replace_block_use(struct compile_state *state, 
12586         struct reg_block *blocks, struct triple *orig, struct triple *new)
12587 {
12588         int i;
12589 #warning "WISHLIST visit just those blocks that need it *"
12590         for(i = 1; i <= state->last_vertex; i++) {
12591                 struct reg_block *rb;
12592                 rb = &blocks[i];
12593                 replace_set_use(state, rb->in, orig, new);
12594                 replace_set_use(state, rb->out, orig, new);
12595         }
12596 }
12597
12598 static void color_instructions(struct compile_state *state)
12599 {
12600         struct triple *ins, *first;
12601         first = RHS(state->main_function, 0);
12602         ins = first;
12603         do {
12604                 if (triple_is_def(state, ins)) {
12605                         struct reg_info info;
12606                         info = find_lhs_color(state, ins, 0);
12607                         if (info.reg >= MAX_REGISTERS) {
12608                                 info.reg = REG_UNSET;
12609                         }
12610                         SET_INFO(ins->id, info);
12611                 }
12612                 ins = ins->next;
12613         } while(ins != first);
12614 }
12615
12616 static struct reg_info read_lhs_color(
12617         struct compile_state *state, struct triple *ins, int index)
12618 {
12619         struct reg_info info;
12620         if ((index == 0) && triple_is_def(state, ins)) {
12621                 info.reg   = ID_REG(ins->id);
12622                 info.regcm = ID_REGCM(ins->id);
12623         }
12624         else if (index < TRIPLE_LHS(ins->sizes)) {
12625                 info = read_lhs_color(state, LHS(ins, index), 0);
12626         }
12627         else {
12628                 internal_error(state, ins, "Bad lhs %d", index);
12629                 info.reg = REG_UNSET;
12630                 info.regcm = 0;
12631         }
12632         return info;
12633 }
12634
12635 static struct triple *resolve_tangle(
12636         struct compile_state *state, struct triple *tangle)
12637 {
12638         struct reg_info info, uinfo;
12639         struct triple_set *set, *next;
12640         struct triple *copy;
12641
12642 #warning "WISHLIST recalculate all affected instructions colors"
12643         info = find_lhs_color(state, tangle, 0);
12644         for(set = tangle->use; set; set = next) {
12645                 struct triple *user;
12646                 int i, zrhs;
12647                 next = set->next;
12648                 user = set->member;
12649                 zrhs = TRIPLE_RHS(user->sizes);
12650                 for(i = 0; i < zrhs; i++) {
12651                         if (RHS(user, i) != tangle) {
12652                                 continue;
12653                         }
12654                         uinfo = find_rhs_post_color(state, user, i);
12655                         if (uinfo.reg == info.reg) {
12656                                 copy = pre_copy(state, user, i);
12657                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12658                                 SET_INFO(copy->id, uinfo);
12659                         }
12660                 }
12661         }
12662         copy = 0;
12663         uinfo = find_lhs_pre_color(state, tangle, 0);
12664         if (uinfo.reg == info.reg) {
12665                 struct reg_info linfo;
12666                 copy = post_copy(state, tangle);
12667                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12668                 linfo = find_lhs_color(state, copy, 0);
12669                 SET_INFO(copy->id, linfo);
12670         }
12671         info = find_lhs_color(state, tangle, 0);
12672         SET_INFO(tangle->id, info);
12673         
12674         return copy;
12675 }
12676
12677
12678 static void fix_tangles(struct compile_state *state,
12679         struct reg_block *blocks, struct triple_reg_set *live,
12680         struct reg_block *rb, struct triple *ins, void *arg)
12681 {
12682         int *tangles = arg;
12683         struct triple *tangle;
12684         do {
12685                 char used[MAX_REGISTERS];
12686                 struct triple_reg_set *set;
12687                 tangle = 0;
12688
12689                 /* Find out which registers have multiple uses at this point */
12690                 memset(used, 0, sizeof(used));
12691                 for(set = live; set; set = set->next) {
12692                         struct reg_info info;
12693                         info = read_lhs_color(state, set->member, 0);
12694                         if (info.reg == REG_UNSET) {
12695                                 continue;
12696                         }
12697                         reg_inc_used(state, used, info.reg);
12698                 }
12699                 
12700                 /* Now find the least dominated definition of a register in
12701                  * conflict I have seen so far.
12702                  */
12703                 for(set = live; set; set = set->next) {
12704                         struct reg_info info;
12705                         info = read_lhs_color(state, set->member, 0);
12706                         if (used[info.reg] < 2) {
12707                                 continue;
12708                         }
12709                         /* Changing copies that feed into phi functions
12710                          * is incorrect.
12711                          */
12712                         if (set->member->use && 
12713                                 (set->member->use->member->op == OP_PHI)) {
12714                                 continue;
12715                         }
12716                         if (!tangle || tdominates(state, set->member, tangle)) {
12717                                 tangle = set->member;
12718                         }
12719                 }
12720                 /* If I have found a tangle resolve it */
12721                 if (tangle) {
12722                         struct triple *post_copy;
12723                         (*tangles)++;
12724                         post_copy = resolve_tangle(state, tangle);
12725                         if (post_copy) {
12726                                 replace_block_use(state, blocks, tangle, post_copy);
12727                         }
12728                         if (post_copy && (tangle != ins)) {
12729                                 replace_set_use(state, live, tangle, post_copy);
12730                         }
12731                 }
12732         } while(tangle);
12733         return;
12734 }
12735
12736 static int correct_tangles(
12737         struct compile_state *state, struct reg_block *blocks)
12738 {
12739         int tangles;
12740         tangles = 0;
12741         color_instructions(state);
12742         walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
12743         return tangles;
12744 }
12745
12746 struct least_conflict {
12747         struct reg_state *rstate;
12748         struct live_range *ref_range;
12749         struct triple *ins;
12750         struct triple_reg_set *live;
12751         size_t count;
12752         int constraints;
12753 };
12754 static void least_conflict(struct compile_state *state,
12755         struct reg_block *blocks, struct triple_reg_set *live,
12756         struct reg_block *rb, struct triple *ins, void *arg)
12757 {
12758         struct least_conflict *conflict = arg;
12759         struct live_range_edge *edge;
12760         struct triple_reg_set *set;
12761         size_t count;
12762         int constraints;
12763
12764 #warning "FIXME handle instructions with left hand sides..."
12765         /* Only instructions that introduce a new definition
12766          * can be the conflict instruction.
12767          */
12768         if (!triple_is_def(state, ins)) {
12769                 return;
12770         }
12771
12772         /* See if live ranges at this instruction are a
12773          * strict subset of the live ranges that are in conflict.
12774          */
12775         count = 0;
12776         for(set = live; set; set = set->next) {
12777                 struct live_range *lr;
12778                 lr = conflict->rstate->lrd[set->member->id].lr;
12779                 /* Ignore it if there cannot be an edge between these two nodes */
12780                 if (!arch_regcm_intersect(conflict->ref_range->classes, lr->classes)) {
12781                         continue;
12782                 }
12783                 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12784                         if (edge->node == lr) {
12785                                 break;
12786                         }
12787                 }
12788                 if (!edge && (lr != conflict->ref_range)) {
12789                         return;
12790                 }
12791                 count++;
12792         }
12793         if (count <= 1) {
12794                 return;
12795         }
12796
12797 #if 0
12798         /* See if there is an uncolored member in this subset. 
12799          */
12800          for(set = live; set; set = set->next) {
12801                 struct live_range *lr;
12802                 lr = conflict->rstate->lrd[set->member->id].lr;
12803                 if (lr->color == REG_UNSET) {
12804                         break;
12805                 }
12806         }
12807         if (!set && (conflict->ref_range != REG_UNSET)) {
12808                 return;
12809         }
12810 #endif
12811
12812         /* See if any of the live registers are constrained,
12813          * if not it won't be productive to pick this as
12814          * a conflict instruction.
12815          */
12816         constraints = 0;
12817         for(set = live; set; set = set->next) {
12818                 struct triple_set *uset;
12819                 struct reg_info info;
12820                 unsigned classes;
12821                 unsigned cur_size, size;
12822                 /* Skip this instruction */
12823                 if (set->member == ins) {
12824                         continue;
12825                 }
12826                 /* Find how many registers this value can potentially 
12827                  * be assigned to.
12828                  */
12829                 classes = arch_type_to_regcm(state, set->member->type);
12830                 size = regc_max_size(state, classes);
12831                 
12832                 /* Find how many registers we allow this value to
12833                  * be assigned to.
12834                  */
12835                 info = arch_reg_lhs(state, set->member, 0);
12836                 
12837                 /* If the value does not live in a register it
12838                  * isn't constrained.
12839                  */
12840                 if (info.reg == REG_UNNEEDED) {
12841                         continue;
12842                 }
12843                 
12844                 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12845                         cur_size = regc_max_size(state, info.regcm);
12846                 } else {
12847                         cur_size = 1;
12848                 }
12849
12850                 /* If there is no difference between potential and
12851                  * actual register count there is not a constraint
12852                  */
12853                 if (cur_size >= size) {
12854                         continue;
12855                 }
12856                 
12857                 /* If this live_range feeds into conflict->inds
12858                  * it isn't a constraint we can relieve.
12859                  */
12860                 for(uset = set->member->use; uset; uset = uset->next) {
12861                         if (uset->member == ins) {
12862                                 break;
12863                         }
12864                 }
12865                 if (uset) {
12866                         continue;
12867                 }
12868                 constraints = 1;
12869                 break;
12870         }
12871         /* Don't drop canidates with constraints */
12872         if (conflict->constraints && !constraints) {
12873                 return;
12874         }
12875
12876
12877 #if 0
12878         fprintf(stderr, "conflict ins? %p %s count: %d constraints: %d\n",
12879                 ins, tops(ins->op), count, constraints);
12880 #endif
12881         /* Find the instruction with the largest possible subset of
12882          * conflict ranges and that dominates any other instruction
12883          * with an equal sized set of conflicting ranges.
12884          */
12885         if ((count > conflict->count) ||
12886                 ((count == conflict->count) &&
12887                         tdominates(state, ins, conflict->ins))) {
12888                 struct triple_reg_set *next;
12889                 /* Remember the canidate instruction */
12890                 conflict->ins = ins;
12891                 conflict->count = count;
12892                 conflict->constraints = constraints;
12893                 /* Free the old collection of live registers */
12894                 for(set = conflict->live; set; set = next) {
12895                         next = set->next;
12896                         do_triple_unset(&conflict->live, set->member);
12897                 }
12898                 conflict->live = 0;
12899                 /* Rember the registers that are alive but do not feed
12900                  * into or out of conflict->ins.
12901                  */
12902                 for(set = live; set; set = set->next) {
12903                         struct triple **expr;
12904                         if (set->member == ins) {
12905                                 goto next;
12906                         }
12907                         expr = triple_rhs(state, ins, 0);
12908                         for(;expr; expr = triple_rhs(state, ins, expr)) {
12909                                 if (*expr == set->member) {
12910                                         goto next;
12911                                 }
12912                         }
12913                         expr = triple_lhs(state, ins, 0);
12914                         for(; expr; expr = triple_lhs(state, ins, expr)) {
12915                                 if (*expr == set->member) {
12916                                         goto next;
12917                                 }
12918                         }
12919                         do_triple_set(&conflict->live, set->member, set->new);
12920                 next:
12921                         ;
12922                 }
12923         }
12924         return;
12925 }
12926
12927 static void find_range_conflict(struct compile_state *state,
12928         struct reg_state *rstate, char *used, struct live_range *ref_range,
12929         struct least_conflict *conflict)
12930 {
12931
12932         /* there are 3 kinds ways conflicts can occure.
12933          * 1) the life time of 2 values simply overlap.
12934          * 2) the 2 values feed into the same instruction.
12935          * 3) the 2 values feed into a phi function.
12936          */
12937
12938         /* find the instruction where the problematic conflict comes
12939          * into existance.  that the instruction where all of
12940          * the values are alive, and among such instructions it is
12941          * the least dominated one.
12942          *
12943          * a value is alive an an instruction if either;
12944          * 1) the value defintion dominates the instruction and there
12945          *    is a use at or after that instrction
12946          * 2) the value definition feeds into a phi function in the
12947          *    same block as the instruction.  and the phi function
12948          *    is at or after the instruction.
12949          */
12950         memset(conflict, 0, sizeof(*conflict));
12951         conflict->rstate      = rstate;
12952         conflict->ref_range   = ref_range;
12953         conflict->ins         = 0;
12954         conflict->live        = 0;
12955         conflict->count       = 0;
12956         conflict->constraints = 0;
12957         walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12958
12959         if (!conflict->ins) {
12960                 internal_error(state, ref_range->defs->def, "No conflict ins?");
12961         }
12962         if (!conflict->live) {
12963                 internal_error(state, ref_range->defs->def, "No conflict live?");
12964         }
12965 #if 0
12966         fprintf(stderr, "conflict ins: %p %s count: %d constraints: %d\n", 
12967                 conflict->ins, tops(conflict->ins->op),
12968                 conflict->count, conflict->constraints);
12969 #endif
12970         return;
12971 }
12972
12973 static struct triple *split_constrained_range(struct compile_state *state, 
12974         struct reg_state *rstate, char *used, struct least_conflict *conflict)
12975 {
12976         unsigned constrained_size;
12977         struct triple *new, *constrained;
12978         struct triple_reg_set *cset;
12979         /* Find a range that is having problems because it is
12980          * artificially constrained.
12981          */
12982         constrained_size = ~0;
12983         constrained = 0;
12984         new = 0;
12985         for(cset = conflict->live; cset; cset = cset->next) {
12986                 struct triple_set *set;
12987                 struct reg_info info;
12988                 unsigned classes;
12989                 unsigned cur_size, size;
12990                 /* Skip the live range that starts with conflict->ins */
12991                 if (cset->member == conflict->ins) {
12992                         continue;
12993                 }
12994                 /* Find how many registers this value can potentially
12995                  * be assigned to.
12996                  */
12997                 classes = arch_type_to_regcm(state, cset->member->type);
12998                 size = regc_max_size(state, classes);
12999
13000                 /* Find how many registers we allow this value to
13001                  * be assigned to.
13002                  */
13003                 info = arch_reg_lhs(state, cset->member, 0);
13004
13005                 /* If the register doesn't need a register 
13006                  * splitting it can't help.
13007                  */
13008                 if (info.reg == REG_UNNEEDED) {
13009                         continue;
13010                 }
13011 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
13012                 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
13013                         cur_size = regc_max_size(state, info.regcm);
13014                 } else {
13015                         cur_size = 1;
13016                 }
13017                 /* If this live_range feeds into conflict->ins
13018                  * splitting it is unlikely to help.
13019                  */
13020                 for(set = cset->member->use; set; set = set->next) {
13021                         if (set->member == conflict->ins) {
13022                                 goto next;
13023                         }
13024                 }
13025
13026                 /* If there is no difference between potential and
13027                  * actual register count there is nothing to do.
13028                  */
13029                 if (cur_size >= size) {
13030                         continue;
13031                 }
13032                 /* Of the constrained registers deal with the
13033                  * most constrained one first.
13034                  */
13035                 if (!constrained ||
13036                         (size < constrained_size)) {
13037                         constrained = cset->member;
13038                         constrained_size = size;
13039                 }
13040         next:
13041                 ;
13042         }
13043         if (constrained) {
13044                 new = post_copy(state, constrained);
13045                 new->id |= TRIPLE_FLAG_POST_SPLIT;
13046         }
13047         return new;
13048 }
13049
13050 static int split_ranges(
13051         struct compile_state *state, struct reg_state *rstate, 
13052         char *used, struct live_range *range)
13053 {
13054         struct triple *new;
13055
13056 #if 0
13057         fprintf(stderr, "split_ranges %d %s %p\n", 
13058                 rstate->passes, tops(range->defs->def->op), range->defs->def);
13059 #endif
13060         if ((range->color == REG_UNNEEDED) ||
13061                 (rstate->passes >= rstate->max_passes)) {
13062                 return 0;
13063         }
13064         new = 0;
13065         /* If I can't allocate a register something needs to be split */
13066         if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
13067                 struct least_conflict conflict;
13068
13069 #if 0
13070         fprintf(stderr, "find_range_conflict\n");
13071 #endif
13072                 /* Find where in the set of registers the conflict
13073                  * actually occurs.
13074                  */
13075                 find_range_conflict(state, rstate, used, range, &conflict);
13076
13077                 /* If a range has been artifically constrained split it */
13078                 new = split_constrained_range(state, rstate, used, &conflict);
13079                 
13080                 if (!new) {
13081                 /* Ideally I would split the live range that will not be used
13082                  * for the longest period of time in hopes that this will 
13083                  * (a) allow me to spill a register or
13084                  * (b) allow me to place a value in another register.
13085                  *
13086                  * So far I don't have a test case for this, the resolving
13087                  * of mandatory constraints has solved all of my
13088                  * know issues.  So I have choosen not to write any
13089                  * code until I cat get a better feel for cases where
13090                  * it would be useful to have.
13091                  *
13092                  */
13093 #warning "WISHLIST implement live range splitting..."
13094 #if 0
13095                         print_blocks(state, stderr);
13096                         print_dominators(state, stderr);
13097
13098 #endif
13099                         return 0;
13100                 }
13101         }
13102         if (new) {
13103                 rstate->lrd[rstate->defs].orig_id = new->id;
13104                 new->id = rstate->defs;
13105                 rstate->defs++;
13106 #if 0
13107                 fprintf(stderr, "new: %p old: %s %p\n", 
13108                         new, tops(RHS(new, 0)->op), RHS(new, 0));
13109 #endif
13110 #if 0
13111                 print_blocks(state, stderr);
13112                 print_dominators(state, stderr);
13113
13114 #endif
13115                 return 1;
13116         }
13117         return 0;
13118 }
13119
13120 #if DEBUG_COLOR_GRAPH > 1
13121 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13122 #define cgdebug_flush() fflush(stdout)
13123 #elif DEBUG_COLOR_GRAPH == 1
13124 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13125 #define cgdebug_flush() fflush(stderr)
13126 #else
13127 #define cgdebug_printf(...)
13128 #define cgdebug_flush()
13129 #endif
13130
13131         
13132 static int select_free_color(struct compile_state *state, 
13133         struct reg_state *rstate, struct live_range *range)
13134 {
13135         struct triple_set *entry;
13136         struct live_range_def *lrd;
13137         struct live_range_def *phi;
13138         struct live_range_edge *edge;
13139         char used[MAX_REGISTERS];
13140         struct triple **expr;
13141
13142         /* Instead of doing just the trivial color select here I try
13143          * a few extra things because a good color selection will help reduce
13144          * copies.
13145          */
13146
13147         /* Find the registers currently in use */
13148         memset(used, 0, sizeof(used));
13149         for(edge = range->edges; edge; edge = edge->next) {
13150                 if (edge->node->color == REG_UNSET) {
13151                         continue;
13152                 }
13153                 reg_fill_used(state, used, edge->node->color);
13154         }
13155 #if DEBUG_COLOR_GRAPH > 1
13156         {
13157                 int i;
13158                 i = 0;
13159                 for(edge = range->edges; edge; edge = edge->next) {
13160                         i++;
13161                 }
13162                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
13163                         tops(range->def->op), i, 
13164                         range->def->filename, range->def->line, range->def->col);
13165                 for(i = 0; i < MAX_REGISTERS; i++) {
13166                         if (used[i]) {
13167                                 cgdebug_printf("used: %s\n",
13168                                         arch_reg_str(i));
13169                         }
13170                 }
13171         }       
13172 #endif
13173
13174 #warning "FIXME detect conflicts caused by the source and destination being the same register"
13175
13176         /* If a color is already assigned see if it will work */
13177         if (range->color != REG_UNSET) {
13178                 struct live_range_def *lrd;
13179                 if (!used[range->color]) {
13180                         return 1;
13181                 }
13182                 for(edge = range->edges; edge; edge = edge->next) {
13183                         if (edge->node->color != range->color) {
13184                                 continue;
13185                         }
13186                         warning(state, edge->node->defs->def, "edge: ");
13187                         lrd = edge->node->defs;
13188                         do {
13189                                 warning(state, lrd->def, " %p %s",
13190                                         lrd->def, tops(lrd->def->op));
13191                                 lrd = lrd->next;
13192                         } while(lrd != edge->node->defs);
13193                 }
13194                 lrd = range->defs;
13195                 warning(state, range->defs->def, "def: ");
13196                 do {
13197                         warning(state, lrd->def, " %p %s",
13198                                 lrd->def, tops(lrd->def->op));
13199                         lrd = lrd->next;
13200                 } while(lrd != range->defs);
13201                 internal_error(state, range->defs->def,
13202                         "live range with already used color %s",
13203                         arch_reg_str(range->color));
13204         }
13205
13206         /* If I feed into an expression reuse it's color.
13207          * This should help remove copies in the case of 2 register instructions
13208          * and phi functions.
13209          */
13210         phi = 0;
13211         lrd = live_range_end(state, range, 0);
13212         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13213                 entry = lrd->def->use;
13214                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13215                         struct live_range_def *insd;
13216                         insd = &rstate->lrd[entry->member->id];
13217                         if (insd->lr->defs == 0) {
13218                                 continue;
13219                         }
13220                         if (!phi && (insd->def->op == OP_PHI) &&
13221                                 !interfere(rstate, range, insd->lr)) {
13222                                 phi = insd;
13223                         }
13224                         if ((insd->lr->color == REG_UNSET) ||
13225                                 ((insd->lr->classes & range->classes) == 0) ||
13226                                 (used[insd->lr->color])) {
13227                                 continue;
13228                         }
13229                         if (interfere(rstate, range, insd->lr)) {
13230                                 continue;
13231                         }
13232                         range->color = insd->lr->color;
13233                 }
13234         }
13235         /* If I feed into a phi function reuse it's color or the color
13236          * of something else that feeds into the phi function.
13237          */
13238         if (phi) {
13239                 if (phi->lr->color != REG_UNSET) {
13240                         if (used[phi->lr->color]) {
13241                                 range->color = phi->lr->color;
13242                         }
13243                 }
13244                 else {
13245                         expr = triple_rhs(state, phi->def, 0);
13246                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13247                                 struct live_range *lr;
13248                                 if (!*expr) {
13249                                         continue;
13250                                 }
13251                                 lr = rstate->lrd[(*expr)->id].lr;
13252                                 if ((lr->color == REG_UNSET) || 
13253                                         ((lr->classes & range->classes) == 0) ||
13254                                         (used[lr->color])) {
13255                                         continue;
13256                                 }
13257                                 if (interfere(rstate, range, lr)) {
13258                                         continue;
13259                                 }
13260                                 range->color = lr->color;
13261                         }
13262                 }
13263         }
13264         /* If I don't interfere with a rhs node reuse it's color */
13265         lrd = live_range_head(state, range, 0);
13266         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13267                 expr = triple_rhs(state, lrd->def, 0);
13268                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13269                         struct live_range *lr;
13270                         if (!*expr) {
13271                                 continue;
13272                         }
13273                         lr = rstate->lrd[(*expr)->id].lr;
13274                         if ((lr->color == -1) || 
13275                                 ((lr->classes & range->classes) == 0) ||
13276                                 (used[lr->color])) {
13277                                 continue;
13278                         }
13279                         if (interfere(rstate, range, lr)) {
13280                                 continue;
13281                         }
13282                         range->color = lr->color;
13283                         break;
13284                 }
13285         }
13286         /* If I have not opportunitically picked a useful color
13287          * pick the first color that is free.
13288          */
13289         if (range->color == REG_UNSET) {
13290                 range->color = 
13291                         arch_select_free_register(state, used, range->classes);
13292         }
13293         if (range->color == REG_UNSET) {
13294                 struct live_range_def *lrd;
13295                 int i;
13296                 if (split_ranges(state, rstate, used, range)) {
13297                         return 0;
13298                 }
13299                 for(edge = range->edges; edge; edge = edge->next) {
13300                         warning(state, edge->node->defs->def, "edge reg %s",
13301                                 arch_reg_str(edge->node->color));
13302                         lrd = edge->node->defs;
13303                         do {
13304                                 warning(state, lrd->def, " %s",
13305                                         tops(lrd->def->op));
13306                                 lrd = lrd->next;
13307                         } while(lrd != edge->node->defs);
13308                 }
13309                 warning(state, range->defs->def, "range: ");
13310                 lrd = range->defs;
13311                 do {
13312                         warning(state, lrd->def, " %s",
13313                                 tops(lrd->def->op));
13314                         lrd = lrd->next;
13315                 } while(lrd != range->defs);
13316                         
13317                 warning(state, range->defs->def, "classes: %x",
13318                         range->classes);
13319                 for(i = 0; i < MAX_REGISTERS; i++) {
13320                         if (used[i]) {
13321                                 warning(state, range->defs->def, "used: %s",
13322                                         arch_reg_str(i));
13323                         }
13324                 }
13325 #if DEBUG_COLOR_GRAPH < 2
13326                 error(state, range->defs->def, "too few registers");
13327 #else
13328                 internal_error(state, range->defs->def, "too few registers");
13329 #endif
13330         }
13331         range->classes = arch_reg_regcm(state, range->color);
13332         if (range->color == -1) {
13333                 internal_error(state, range->defs->def, "select_free_color did not?");
13334         }
13335         return 1;
13336 }
13337
13338 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13339 {
13340         int colored;
13341         struct live_range_edge *edge;
13342         struct live_range *range;
13343         if (rstate->low) {
13344                 cgdebug_printf("Lo: ");
13345                 range = rstate->low;
13346                 if (*range->group_prev != range) {
13347                         internal_error(state, 0, "lo: *prev != range?");
13348                 }
13349                 *range->group_prev = range->group_next;
13350                 if (range->group_next) {
13351                         range->group_next->group_prev = range->group_prev;
13352                 }
13353                 if (&range->group_next == rstate->low_tail) {
13354                         rstate->low_tail = range->group_prev;
13355                 }
13356                 if (rstate->low == range) {
13357                         internal_error(state, 0, "low: next != prev?");
13358                 }
13359         }
13360         else if (rstate->high) {
13361                 cgdebug_printf("Hi: ");
13362                 range = rstate->high;
13363                 if (*range->group_prev != range) {
13364                         internal_error(state, 0, "hi: *prev != range?");
13365                 }
13366                 *range->group_prev = range->group_next;
13367                 if (range->group_next) {
13368                         range->group_next->group_prev = range->group_prev;
13369                 }
13370                 if (&range->group_next == rstate->high_tail) {
13371                         rstate->high_tail = range->group_prev;
13372                 }
13373                 if (rstate->high == range) {
13374                         internal_error(state, 0, "high: next != prev?");
13375                 }
13376         }
13377         else {
13378                 return 1;
13379         }
13380         cgdebug_printf(" %d\n", range - rstate->lr);
13381         range->group_prev = 0;
13382         for(edge = range->edges; edge; edge = edge->next) {
13383                 struct live_range *node;
13384                 node = edge->node;
13385                 /* Move nodes from the high to the low list */
13386                 if (node->group_prev && (node->color == REG_UNSET) &&
13387                         (node->degree == regc_max_size(state, node->classes))) {
13388                         if (*node->group_prev != node) {
13389                                 internal_error(state, 0, "move: *prev != node?");
13390                         }
13391                         *node->group_prev = node->group_next;
13392                         if (node->group_next) {
13393                                 node->group_next->group_prev = node->group_prev;
13394                         }
13395                         if (&node->group_next == rstate->high_tail) {
13396                                 rstate->high_tail = node->group_prev;
13397                         }
13398                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13399                         node->group_prev  = rstate->low_tail;
13400                         node->group_next  = 0;
13401                         *rstate->low_tail = node;
13402                         rstate->low_tail  = &node->group_next;
13403                         if (*node->group_prev != node) {
13404                                 internal_error(state, 0, "move2: *prev != node?");
13405                         }
13406                 }
13407                 node->degree -= 1;
13408         }
13409         colored = color_graph(state, rstate);
13410         if (colored) {
13411                 cgdebug_printf("Coloring %d @%s:%d.%d:", 
13412                         range - rstate->lr,
13413                         range->def->filename, range->def->line, range->def->col);
13414                 cgdebug_flush();
13415                 colored = select_free_color(state, rstate, range);
13416                 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13417         }
13418         return colored;
13419 }
13420
13421 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13422 {
13423         struct live_range *lr;
13424         struct live_range_edge *edge;
13425         struct triple *ins, *first;
13426         char used[MAX_REGISTERS];
13427         first = RHS(state->main_function, 0);
13428         ins = first;
13429         do {
13430                 if (triple_is_def(state, ins)) {
13431                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
13432                                 internal_error(state, ins, 
13433                                         "triple without a live range def");
13434                         }
13435                         lr = rstate->lrd[ins->id].lr;
13436                         if (lr->color == REG_UNSET) {
13437                                 internal_error(state, ins,
13438                                         "triple without a color");
13439                         }
13440                         /* Find the registers used by the edges */
13441                         memset(used, 0, sizeof(used));
13442                         for(edge = lr->edges; edge; edge = edge->next) {
13443                                 if (edge->node->color == REG_UNSET) {
13444                                         internal_error(state, 0,
13445                                                 "live range without a color");
13446                         }
13447                                 reg_fill_used(state, used, edge->node->color);
13448                         }
13449                         if (used[lr->color]) {
13450                                 internal_error(state, ins,
13451                                         "triple with already used color");
13452                         }
13453                 }
13454                 ins = ins->next;
13455         } while(ins != first);
13456 }
13457
13458 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13459 {
13460         struct live_range *lr;
13461         struct triple *first, *ins;
13462         first = RHS(state->main_function, 0);
13463         ins = first;
13464         do {
13465                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13466                         internal_error(state, ins, 
13467                                 "triple without a live range");
13468                 }
13469                 lr = rstate->lrd[ins->id].lr;
13470                 SET_REG(ins->id, lr->color);
13471                 ins = ins->next;
13472         } while (ins != first);
13473 }
13474
13475 static void print_interference_block(
13476         struct compile_state *state, struct block *block, void *arg)
13477
13478 {
13479         struct reg_state *rstate = arg;
13480         struct reg_block *rb;
13481         struct triple *ptr;
13482         int phi_present;
13483         int done;
13484         rb = &rstate->blocks[block->vertex];
13485
13486         printf("\nblock: %p (%d), %p<-%p %p<-%p\n", 
13487                 block, 
13488                 block->vertex,
13489                 block->left, 
13490                 block->left && block->left->use?block->left->use->member : 0,
13491                 block->right, 
13492                 block->right && block->right->use?block->right->use->member : 0);
13493         if (rb->in) {
13494                 struct triple_reg_set *in_set;
13495                 printf("        in:");
13496                 for(in_set = rb->in; in_set; in_set = in_set->next) {
13497                         printf(" %-10p", in_set->member);
13498                 }
13499                 printf("\n");
13500         }
13501         phi_present = 0;
13502         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13503                 done = (ptr == block->last);
13504                 if (ptr->op == OP_PHI) {
13505                         phi_present = 1;
13506                         break;
13507                 }
13508         }
13509         if (phi_present) {
13510                 int edge;
13511                 for(edge = 0; edge < block->users; edge++) {
13512                         printf("     in(%d):", edge);
13513                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13514                                 struct triple **slot;
13515                                 done = (ptr == block->last);
13516                                 if (ptr->op != OP_PHI) {
13517                                         continue;
13518                                 }
13519                                 slot = &RHS(ptr, 0);
13520                                 printf(" %-10p", slot[edge]);
13521                         }
13522                         printf("\n");
13523                 }
13524         }
13525         if (block->first->op == OP_LABEL) {
13526                 printf("%p:\n", block->first);
13527         }
13528         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13529                 struct triple_set *user;
13530                 struct live_range *lr;
13531                 unsigned id;
13532                 int op;
13533                 op = ptr->op;
13534                 done = (ptr == block->last);
13535                 lr = rstate->lrd[ptr->id].lr;
13536                 
13537                 if (triple_stores_block(state, ptr)) {
13538                         if (ptr->u.block != block) {
13539                                 internal_error(state, ptr, 
13540                                         "Wrong block pointer: %p",
13541                                         ptr->u.block);
13542                         }
13543                 }
13544                 if (op == OP_ADECL) {
13545                         for(user = ptr->use; user; user = user->next) {
13546                                 if (!user->member->u.block) {
13547                                         internal_error(state, user->member, 
13548                                                 "Use %p not in a block?",
13549                                                 user->member);
13550                                 }
13551                                 
13552                         }
13553                 }
13554                 id = ptr->id;
13555                 ptr->id = rstate->lrd[id].orig_id;
13556                 SET_REG(ptr->id, lr->color);
13557                 display_triple(stdout, ptr);
13558                 ptr->id = id;
13559
13560                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
13561                         internal_error(state, ptr, "lr has no defs!");
13562                 }
13563
13564                 if (lr->defs) {
13565                         struct live_range_def *lrd;
13566                         printf("       range:");
13567                         lrd = lr->defs;
13568                         do {
13569                                 printf(" %-10p", lrd->def);
13570                                 lrd = lrd->next;
13571                         } while(lrd != lr->defs);
13572                         printf("\n");
13573                 }
13574                 if (lr->edges > 0) {
13575                         struct live_range_edge *edge;
13576                         printf("       edges:");
13577                         for(edge = lr->edges; edge; edge = edge->next) {
13578                                 struct live_range_def *lrd;
13579                                 lrd = edge->node->defs;
13580                                 do {
13581                                         printf(" %-10p", lrd->def);
13582                                         lrd = lrd->next;
13583                                 } while(lrd != edge->node->defs);
13584                                 printf("|");
13585                         }
13586                         printf("\n");
13587                 }
13588                 /* Do a bunch of sanity checks */
13589                 valid_ins(state, ptr);
13590                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
13591                         internal_error(state, ptr, "Invalid triple id: %d",
13592                                 ptr->id);
13593                 }
13594                 for(user = ptr->use; user; user = user->next) {
13595                         struct triple *use;
13596                         struct live_range *ulr;
13597                         use = user->member;
13598                         valid_ins(state, use);
13599                         if ((use->id < 0) || (use->id > rstate->defs)) {
13600                                 internal_error(state, use, "Invalid triple id: %d",
13601                                         use->id);
13602                         }
13603                         ulr = rstate->lrd[user->member->id].lr;
13604                         if (triple_stores_block(state, user->member) &&
13605                                 !user->member->u.block) {
13606                                 internal_error(state, user->member,
13607                                         "Use %p not in a block?",
13608                                         user->member);
13609                         }
13610                 }
13611         }
13612         if (rb->out) {
13613                 struct triple_reg_set *out_set;
13614                 printf("       out:");
13615                 for(out_set = rb->out; out_set; out_set = out_set->next) {
13616                         printf(" %-10p", out_set->member);
13617                 }
13618                 printf("\n");
13619         }
13620         printf("\n");
13621 }
13622
13623 static struct live_range *merge_sort_lr(
13624         struct live_range *first, struct live_range *last)
13625 {
13626         struct live_range *mid, *join, **join_tail, *pick;
13627         size_t size;
13628         size = (last - first) + 1;
13629         if (size >= 2) {
13630                 mid = first + size/2;
13631                 first = merge_sort_lr(first, mid -1);
13632                 mid   = merge_sort_lr(mid, last);
13633                 
13634                 join = 0;
13635                 join_tail = &join;
13636                 /* merge the two lists */
13637                 while(first && mid) {
13638                         if ((first->degree < mid->degree) ||
13639                                 ((first->degree == mid->degree) &&
13640                                         (first->length < mid->length))) {
13641                                 pick = first;
13642                                 first = first->group_next;
13643                                 if (first) {
13644                                         first->group_prev = 0;
13645                                 }
13646                         }
13647                         else {
13648                                 pick = mid;
13649                                 mid = mid->group_next;
13650                                 if (mid) {
13651                                         mid->group_prev = 0;
13652                                 }
13653                         }
13654                         pick->group_next = 0;
13655                         pick->group_prev = join_tail;
13656                         *join_tail = pick;
13657                         join_tail = &pick->group_next;
13658                 }
13659                 /* Splice the remaining list */
13660                 pick = (first)? first : mid;
13661                 *join_tail = pick;
13662                 if (pick) { 
13663                         pick->group_prev = join_tail;
13664                 }
13665         }
13666         else {
13667                 if (!first->defs) {
13668                         first = 0;
13669                 }
13670                 join = first;
13671         }
13672         return join;
13673 }
13674
13675 static void ids_from_rstate(struct compile_state *state, 
13676         struct reg_state *rstate)
13677 {
13678         struct triple *ins, *first;
13679         if (!rstate->defs) {
13680                 return;
13681         }
13682         /* Display the graph if desired */
13683         if (state->debug & DEBUG_INTERFERENCE) {
13684                 print_blocks(state, stdout);
13685                 print_control_flow(state);
13686         }
13687         first = RHS(state->main_function, 0);
13688         ins = first;
13689         do {
13690                 if (ins->id) {
13691                         struct live_range_def *lrd;
13692                         lrd = &rstate->lrd[ins->id];
13693                         ins->id = lrd->orig_id;
13694                 }
13695                 ins = ins->next;
13696         } while(ins != first);
13697 }
13698
13699 static void cleanup_live_edges(struct reg_state *rstate)
13700 {
13701         int i;
13702         /* Free the edges on each node */
13703         for(i = 1; i <= rstate->ranges; i++) {
13704                 remove_live_edges(rstate, &rstate->lr[i]);
13705         }
13706 }
13707
13708 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13709 {
13710         cleanup_live_edges(rstate);
13711         xfree(rstate->lrd);
13712         xfree(rstate->lr);
13713
13714         /* Free the variable lifetime information */
13715         if (rstate->blocks) {
13716                 free_variable_lifetimes(state, rstate->blocks);
13717         }
13718         rstate->defs = 0;
13719         rstate->ranges = 0;
13720         rstate->lrd = 0;
13721         rstate->lr = 0;
13722         rstate->blocks = 0;
13723 }
13724
13725 static void verify_consistency(struct compile_state *state);
13726 static void allocate_registers(struct compile_state *state)
13727 {
13728         struct reg_state rstate;
13729         int colored;
13730
13731         /* Clear out the reg_state */
13732         memset(&rstate, 0, sizeof(rstate));
13733         rstate.max_passes = MAX_ALLOCATION_PASSES;
13734
13735         do {
13736                 struct live_range **point, **next;
13737                 int tangles;
13738                 int coalesced;
13739
13740 #if 0
13741                 fprintf(stderr, "pass: %d\n", rstate.passes);
13742 #endif
13743
13744                 /* Restore ids */
13745                 ids_from_rstate(state, &rstate);
13746
13747                 /* Cleanup the temporary data structures */
13748                 cleanup_rstate(state, &rstate);
13749
13750                 /* Compute the variable lifetimes */
13751                 rstate.blocks = compute_variable_lifetimes(state);
13752
13753                 /* Fix invalid mandatory live range coalesce conflicts */
13754                 walk_variable_lifetimes(
13755                         state, rstate.blocks, fix_coalesce_conflicts, 0);
13756
13757                 /* Fix two simultaneous uses of the same register.
13758                  * In a few pathlogical cases a partial untangle moves
13759                  * the tangle to a part of the graph we won't revisit.
13760                  * So we keep looping until we have no more tangle fixes
13761                  * to apply.
13762                  */
13763                 do {
13764                         tangles = correct_tangles(state, rstate.blocks);
13765                 } while(tangles);
13766
13767                 if (state->debug & DEBUG_INSERTED_COPIES) {
13768                         printf("After resolve_tangles\n");
13769                         print_blocks(state, stdout);
13770                         print_control_flow(state);
13771                 }
13772                 verify_consistency(state);
13773                 
13774                 /* Allocate and initialize the live ranges */
13775                 initialize_live_ranges(state, &rstate);
13776
13777                 /* Note current doing coalescing in a loop appears to 
13778                  * buys me nothing.  The code is left this way in case
13779                  * there is some value in it.  Or if a future bugfix
13780                  *  yields some benefit.
13781                  */
13782                 do {
13783 #if 0
13784                         fprintf(stderr, "coalescing\n");
13785 #endif                  
13786                         /* Remove any previous live edge calculations */
13787                         cleanup_live_edges(&rstate);
13788
13789                         /* Compute the interference graph */
13790                         walk_variable_lifetimes(
13791                                 state, rstate.blocks, graph_ins, &rstate);
13792                         
13793                         /* Display the interference graph if desired */
13794                         if (state->debug & DEBUG_INTERFERENCE) {
13795                                 printf("\nlive variables by block\n");
13796                                 walk_blocks(state, print_interference_block, &rstate);
13797                                 printf("\nlive variables by instruction\n");
13798                                 walk_variable_lifetimes(
13799                                         state, rstate.blocks, 
13800                                         print_interference_ins, &rstate);
13801                         }
13802                         
13803                         coalesced = coalesce_live_ranges(state, &rstate);
13804
13805 #if 0
13806                         fprintf(stderr, "coalesced: %d\n", coalesced);
13807 #endif
13808                 } while(coalesced);
13809
13810 #if DEBUG_CONSISTENCY > 1
13811 # if 0
13812                 fprintf(stderr, "verify_graph_ins...\n");
13813 # endif
13814                 /* Verify the interference graph */
13815                 walk_variable_lifetimes(
13816                         state, rstate.blocks, verify_graph_ins, &rstate);
13817 # if 0
13818                 fprintf(stderr, "verify_graph_ins done\n");
13819 #endif
13820 #endif
13821                         
13822                 /* Build the groups low and high.  But with the nodes
13823                  * first sorted by degree order.
13824                  */
13825                 rstate.low_tail  = &rstate.low;
13826                 rstate.high_tail = &rstate.high;
13827                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13828                 if (rstate.high) {
13829                         rstate.high->group_prev = &rstate.high;
13830                 }
13831                 for(point = &rstate.high; *point; point = &(*point)->group_next)
13832                         ;
13833                 rstate.high_tail = point;
13834                 /* Walk through the high list and move everything that needs
13835                  * to be onto low.
13836                  */
13837                 for(point = &rstate.high; *point; point = next) {
13838                         struct live_range *range;
13839                         next = &(*point)->group_next;
13840                         range = *point;
13841                         
13842                         /* If it has a low degree or it already has a color
13843                          * place the node in low.
13844                          */
13845                         if ((range->degree < regc_max_size(state, range->classes)) ||
13846                                 (range->color != REG_UNSET)) {
13847                                 cgdebug_printf("Lo: %5d degree %5d%s\n", 
13848                                         range - rstate.lr, range->degree,
13849                                         (range->color != REG_UNSET) ? " (colored)": "");
13850                                 *range->group_prev = range->group_next;
13851                                 if (range->group_next) {
13852                                         range->group_next->group_prev = range->group_prev;
13853                                 }
13854                                 if (&range->group_next == rstate.high_tail) {
13855                                         rstate.high_tail = range->group_prev;
13856                                 }
13857                                 range->group_prev  = rstate.low_tail;
13858                                 range->group_next  = 0;
13859                                 *rstate.low_tail   = range;
13860                                 rstate.low_tail    = &range->group_next;
13861                                 next = point;
13862                         }
13863                         else {
13864                                 cgdebug_printf("hi: %5d degree %5d%s\n", 
13865                                         range - rstate.lr, range->degree,
13866                                         (range->color != REG_UNSET) ? " (colored)": "");
13867                         }
13868                 }
13869                 /* Color the live_ranges */
13870                 colored = color_graph(state, &rstate);
13871                 rstate.passes++;
13872         } while (!colored);
13873
13874         /* Verify the graph was properly colored */
13875         verify_colors(state, &rstate);
13876
13877         /* Move the colors from the graph to the triples */
13878         color_triples(state, &rstate);
13879
13880         /* Cleanup the temporary data structures */
13881         cleanup_rstate(state, &rstate);
13882 }
13883
13884 /* Sparce Conditional Constant Propogation
13885  * =========================================
13886  */
13887 struct ssa_edge;
13888 struct flow_block;
13889 struct lattice_node {
13890         unsigned old_id;
13891         struct triple *def;
13892         struct ssa_edge *out;
13893         struct flow_block *fblock;
13894         struct triple *val;
13895         /* lattice high   val && !is_const(val) 
13896          * lattice const  is_const(val)
13897          * lattice low    val == 0
13898          */
13899 };
13900 struct ssa_edge {
13901         struct lattice_node *src;
13902         struct lattice_node *dst;
13903         struct ssa_edge *work_next;
13904         struct ssa_edge *work_prev;
13905         struct ssa_edge *out_next;
13906 };
13907 struct flow_edge {
13908         struct flow_block *src;
13909         struct flow_block *dst;
13910         struct flow_edge *work_next;
13911         struct flow_edge *work_prev;
13912         struct flow_edge *in_next;
13913         struct flow_edge *out_next;
13914         int executable;
13915 };
13916 struct flow_block {
13917         struct block *block;
13918         struct flow_edge *in;
13919         struct flow_edge *out;
13920         struct flow_edge left, right;
13921 };
13922
13923 struct scc_state {
13924         int ins_count;
13925         struct lattice_node *lattice;
13926         struct ssa_edge     *ssa_edges;
13927         struct flow_block   *flow_blocks;
13928         struct flow_edge    *flow_work_list;
13929         struct ssa_edge     *ssa_work_list;
13930 };
13931
13932
13933 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
13934         struct flow_edge *fedge)
13935 {
13936         if (!scc->flow_work_list) {
13937                 scc->flow_work_list = fedge;
13938                 fedge->work_next = fedge->work_prev = fedge;
13939         }
13940         else {
13941                 struct flow_edge *ftail;
13942                 ftail = scc->flow_work_list->work_prev;
13943                 fedge->work_next = ftail->work_next;
13944                 fedge->work_prev = ftail;
13945                 fedge->work_next->work_prev = fedge;
13946                 fedge->work_prev->work_next = fedge;
13947         }
13948 }
13949
13950 static struct flow_edge *scc_next_fedge(
13951         struct compile_state *state, struct scc_state *scc)
13952 {
13953         struct flow_edge *fedge;
13954         fedge = scc->flow_work_list;
13955         if (fedge) {
13956                 fedge->work_next->work_prev = fedge->work_prev;
13957                 fedge->work_prev->work_next = fedge->work_next;
13958                 if (fedge->work_next != fedge) {
13959                         scc->flow_work_list = fedge->work_next;
13960                 } else {
13961                         scc->flow_work_list = 0;
13962                 }
13963         }
13964         return fedge;
13965 }
13966
13967 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13968         struct ssa_edge *sedge)
13969 {
13970         if (!scc->ssa_work_list) {
13971                 scc->ssa_work_list = sedge;
13972                 sedge->work_next = sedge->work_prev = sedge;
13973         }
13974         else {
13975                 struct ssa_edge *stail;
13976                 stail = scc->ssa_work_list->work_prev;
13977                 sedge->work_next = stail->work_next;
13978                 sedge->work_prev = stail;
13979                 sedge->work_next->work_prev = sedge;
13980                 sedge->work_prev->work_next = sedge;
13981         }
13982 }
13983
13984 static struct ssa_edge *scc_next_sedge(
13985         struct compile_state *state, struct scc_state *scc)
13986 {
13987         struct ssa_edge *sedge;
13988         sedge = scc->ssa_work_list;
13989         if (sedge) {
13990                 sedge->work_next->work_prev = sedge->work_prev;
13991                 sedge->work_prev->work_next = sedge->work_next;
13992                 if (sedge->work_next != sedge) {
13993                         scc->ssa_work_list = sedge->work_next;
13994                 } else {
13995                         scc->ssa_work_list = 0;
13996                 }
13997         }
13998         return sedge;
13999 }
14000
14001 static void initialize_scc_state(
14002         struct compile_state *state, struct scc_state *scc)
14003 {
14004         int ins_count, ssa_edge_count;
14005         int ins_index, ssa_edge_index, fblock_index;
14006         struct triple *first, *ins;
14007         struct block *block;
14008         struct flow_block *fblock;
14009
14010         memset(scc, 0, sizeof(*scc));
14011
14012         /* Inialize pass zero find out how much memory we need */
14013         first = RHS(state->main_function, 0);
14014         ins = first;
14015         ins_count = ssa_edge_count = 0;
14016         do {
14017                 struct triple_set *edge;
14018                 ins_count += 1;
14019                 for(edge = ins->use; edge; edge = edge->next) {
14020                         ssa_edge_count++;
14021                 }
14022                 ins = ins->next;
14023         } while(ins != first);
14024 #if DEBUG_SCC
14025         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
14026                 ins_count, ssa_edge_count, state->last_vertex);
14027 #endif
14028         scc->ins_count   = ins_count;
14029         scc->lattice     = 
14030                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
14031         scc->ssa_edges   = 
14032                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
14033         scc->flow_blocks = 
14034                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
14035                         "flow_blocks");
14036
14037         /* Initialize pass one collect up the nodes */
14038         fblock = 0;
14039         block = 0;
14040         ins_index = ssa_edge_index = fblock_index = 0;
14041         ins = first;
14042         do {
14043                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14044                         block = ins->u.block;
14045                         if (!block) {
14046                                 internal_error(state, ins, "label without block");
14047                         }
14048                         fblock_index += 1;
14049                         block->vertex = fblock_index;
14050                         fblock = &scc->flow_blocks[fblock_index];
14051                         fblock->block = block;
14052                 }
14053                 {
14054                         struct lattice_node *lnode;
14055                         ins_index += 1;
14056                         lnode = &scc->lattice[ins_index];
14057                         lnode->def = ins;
14058                         lnode->out = 0;
14059                         lnode->fblock = fblock;
14060                         lnode->val = ins; /* LATTICE HIGH */
14061                         lnode->old_id = ins->id;
14062                         ins->id = ins_index;
14063                 }
14064                 ins = ins->next;
14065         } while(ins != first);
14066         /* Initialize pass two collect up the edges */
14067         block = 0;
14068         fblock = 0;
14069         ins = first;
14070         do {
14071                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14072                         struct flow_edge *fedge, **ftail;
14073                         struct block_set *bedge;
14074                         block = ins->u.block;
14075                         fblock = &scc->flow_blocks[block->vertex];
14076                         fblock->in = 0;
14077                         fblock->out = 0;
14078                         ftail = &fblock->out;
14079                         if (block->left) {
14080                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
14081                                 if (fblock->left.dst->block != block->left) {
14082                                         internal_error(state, 0, "block mismatch");
14083                                 }
14084                                 fblock->left.out_next = 0;
14085                                 *ftail = &fblock->left;
14086                                 ftail = &fblock->left.out_next;
14087                         }
14088                         if (block->right) {
14089                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
14090                                 if (fblock->right.dst->block != block->right) {
14091                                         internal_error(state, 0, "block mismatch");
14092                                 }
14093                                 fblock->right.out_next = 0;
14094                                 *ftail = &fblock->right;
14095                                 ftail = &fblock->right.out_next;
14096                         }
14097                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
14098                                 fedge->src = fblock;
14099                                 fedge->work_next = fedge->work_prev = fedge;
14100                                 fedge->executable = 0;
14101                         }
14102                         ftail = &fblock->in;
14103                         for(bedge = block->use; bedge; bedge = bedge->next) {
14104                                 struct block *src_block;
14105                                 struct flow_block *sfblock;
14106                                 struct flow_edge *sfedge;
14107                                 src_block = bedge->member;
14108                                 sfblock = &scc->flow_blocks[src_block->vertex];
14109                                 sfedge = 0;
14110                                 if (src_block->left == block) {
14111                                         sfedge = &sfblock->left;
14112                                 } else {
14113                                         sfedge = &sfblock->right;
14114                                 }
14115                                 *ftail = sfedge;
14116                                 ftail = &sfedge->in_next;
14117                                 sfedge->in_next = 0;
14118                         }
14119                 }
14120                 {
14121                         struct triple_set *edge;
14122                         struct ssa_edge **stail;
14123                         struct lattice_node *lnode;
14124                         lnode = &scc->lattice[ins->id];
14125                         lnode->out = 0;
14126                         stail = &lnode->out;
14127                         for(edge = ins->use; edge; edge = edge->next) {
14128                                 struct ssa_edge *sedge;
14129                                 ssa_edge_index += 1;
14130                                 sedge = &scc->ssa_edges[ssa_edge_index];
14131                                 *stail = sedge;
14132                                 stail = &sedge->out_next;
14133                                 sedge->src = lnode;
14134                                 sedge->dst = &scc->lattice[edge->member->id];
14135                                 sedge->work_next = sedge->work_prev = sedge;
14136                                 sedge->out_next = 0;
14137                         }
14138                 }
14139                 ins = ins->next;
14140         } while(ins != first);
14141         /* Setup a dummy block 0 as a node above the start node */
14142         {
14143                 struct flow_block *fblock, *dst;
14144                 struct flow_edge *fedge;
14145                 fblock = &scc->flow_blocks[0];
14146                 fblock->block = 0;
14147                 fblock->in = 0;
14148                 fblock->out = &fblock->left;
14149                 dst = &scc->flow_blocks[state->first_block->vertex];
14150                 fedge = &fblock->left;
14151                 fedge->src        = fblock;
14152                 fedge->dst        = dst;
14153                 fedge->work_next  = fedge;
14154                 fedge->work_prev  = fedge;
14155                 fedge->in_next    = fedge->dst->in;
14156                 fedge->out_next   = 0;
14157                 fedge->executable = 0;
14158                 fedge->dst->in = fedge;
14159                 
14160                 /* Initialize the work lists */
14161                 scc->flow_work_list = 0;
14162                 scc->ssa_work_list  = 0;
14163                 scc_add_fedge(state, scc, fedge);
14164         }
14165 #if DEBUG_SCC
14166         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14167                 ins_index, ssa_edge_index, fblock_index);
14168 #endif
14169 }
14170
14171         
14172 static void free_scc_state(
14173         struct compile_state *state, struct scc_state *scc)
14174 {
14175         xfree(scc->flow_blocks);
14176         xfree(scc->ssa_edges);
14177         xfree(scc->lattice);
14178         
14179 }
14180
14181 static struct lattice_node *triple_to_lattice(
14182         struct compile_state *state, struct scc_state *scc, struct triple *ins)
14183 {
14184         if (ins->id <= 0) {
14185                 internal_error(state, ins, "bad id");
14186         }
14187         return &scc->lattice[ins->id];
14188 }
14189
14190 static struct triple *preserve_lval(
14191         struct compile_state *state, struct lattice_node *lnode)
14192 {
14193         struct triple *old;
14194         /* Preserve the original value */
14195         if (lnode->val) {
14196                 old = dup_triple(state, lnode->val);
14197                 if (lnode->val != lnode->def) {
14198                         xfree(lnode->val);
14199                 }
14200                 lnode->val = 0;
14201         } else {
14202                 old = 0;
14203         }
14204         return old;
14205 }
14206
14207 static int lval_changed(struct compile_state *state, 
14208         struct triple *old, struct lattice_node *lnode)
14209 {
14210         int changed;
14211         /* See if the lattice value has changed */
14212         changed = 1;
14213         if (!old && !lnode->val) {
14214                 changed = 0;
14215         }
14216         if (changed && lnode->val && !is_const(lnode->val)) {
14217                 changed = 0;
14218         }
14219         if (changed &&
14220                 lnode->val && old &&
14221                 (memcmp(lnode->val->param, old->param,
14222                         TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14223                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14224                 changed = 0;
14225         }
14226         if (old) {
14227                 xfree(old);
14228         }
14229         return changed;
14230
14231 }
14232
14233 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
14234         struct lattice_node *lnode)
14235 {
14236         struct lattice_node *tmp;
14237         struct triple **slot, *old;
14238         struct flow_edge *fedge;
14239         int index;
14240         if (lnode->def->op != OP_PHI) {
14241                 internal_error(state, lnode->def, "not phi");
14242         }
14243         /* Store the original value */
14244         old = preserve_lval(state, lnode);
14245
14246         /* default to lattice high */
14247         lnode->val = lnode->def;
14248         slot = &RHS(lnode->def, 0);
14249         index = 0;
14250         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14251                 if (!fedge->executable) {
14252                         continue;
14253                 }
14254                 if (!slot[index]) {
14255                         internal_error(state, lnode->def, "no phi value");
14256                 }
14257                 tmp = triple_to_lattice(state, scc, slot[index]);
14258                 /* meet(X, lattice low) = lattice low */
14259                 if (!tmp->val) {
14260                         lnode->val = 0;
14261                 }
14262                 /* meet(X, lattice high) = X */
14263                 else if (!tmp->val) {
14264                         lnode->val = lnode->val;
14265                 }
14266                 /* meet(lattice high, X) = X */
14267                 else if (!is_const(lnode->val)) {
14268                         lnode->val = dup_triple(state, tmp->val);
14269                         lnode->val->type = lnode->def->type;
14270                 }
14271                 /* meet(const, const) = const or lattice low */
14272                 else if (!constants_equal(state, lnode->val, tmp->val)) {
14273                         lnode->val = 0;
14274                 }
14275                 if (!lnode->val) {
14276                         break;
14277                 }
14278         }
14279 #if DEBUG_SCC
14280         fprintf(stderr, "phi: %d -> %s\n",
14281                 lnode->def->id,
14282                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14283 #endif
14284         /* If the lattice value has changed update the work lists. */
14285         if (lval_changed(state, old, lnode)) {
14286                 struct ssa_edge *sedge;
14287                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14288                         scc_add_sedge(state, scc, sedge);
14289                 }
14290         }
14291 }
14292
14293 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14294         struct lattice_node *lnode)
14295 {
14296         int changed;
14297         struct triple *old, *scratch;
14298         struct triple **dexpr, **vexpr;
14299         int count, i;
14300         
14301         /* Store the original value */
14302         old = preserve_lval(state, lnode);
14303
14304         /* Reinitialize the value */
14305         lnode->val = scratch = dup_triple(state, lnode->def);
14306         scratch->id = lnode->old_id;
14307         scratch->next     = scratch;
14308         scratch->prev     = scratch;
14309         scratch->use      = 0;
14310
14311         count = TRIPLE_SIZE(scratch->sizes);
14312         for(i = 0; i < count; i++) {
14313                 dexpr = &lnode->def->param[i];
14314                 vexpr = &scratch->param[i];
14315                 *vexpr = *dexpr;
14316                 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14317                         (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14318                         *dexpr) {
14319                         struct lattice_node *tmp;
14320                         tmp = triple_to_lattice(state, scc, *dexpr);
14321                         *vexpr = (tmp->val)? tmp->val : tmp->def;
14322                 }
14323         }
14324         if (scratch->op == OP_BRANCH) {
14325                 scratch->next = lnode->def->next;
14326         }
14327         /* Recompute the value */
14328 #warning "FIXME see if simplify does anything bad"
14329         /* So far it looks like only the strength reduction
14330          * optimization are things I need to worry about.
14331          */
14332         simplify(state, scratch);
14333         /* Cleanup my value */
14334         if (scratch->use) {
14335                 internal_error(state, lnode->def, "scratch used?");
14336         }
14337         if ((scratch->prev != scratch) ||
14338                 ((scratch->next != scratch) &&
14339                         ((lnode->def->op != OP_BRANCH) ||
14340                                 (scratch->next != lnode->def->next)))) {
14341                 internal_error(state, lnode->def, "scratch in list?");
14342         }
14343         /* undo any uses... */
14344         count = TRIPLE_SIZE(scratch->sizes);
14345         for(i = 0; i < count; i++) {
14346                 vexpr = &scratch->param[i];
14347                 if (*vexpr) {
14348                         unuse_triple(*vexpr, scratch);
14349                 }
14350         }
14351         if (!is_const(scratch)) {
14352                 for(i = 0; i < count; i++) {
14353                         dexpr = &lnode->def->param[i];
14354                         if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14355                                 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14356                                 *dexpr) {
14357                                 struct lattice_node *tmp;
14358                                 tmp = triple_to_lattice(state, scc, *dexpr);
14359                                 if (!tmp->val) {
14360                                         lnode->val = 0;
14361                                 }
14362                         }
14363                 }
14364         }
14365         if (lnode->val && 
14366                 (lnode->val->op == lnode->def->op) &&
14367                 (memcmp(lnode->val->param, lnode->def->param, 
14368                         count * sizeof(lnode->val->param[0])) == 0) &&
14369                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14370                 lnode->val = lnode->def;
14371         }
14372         /* Find the cases that are always lattice lo */
14373         if (lnode->val && 
14374                 triple_is_def(state, lnode->val) &&
14375                 !triple_is_pure(state, lnode->val)) {
14376                 lnode->val = 0;
14377         }
14378         if (lnode->val && 
14379                 (lnode->val->op == OP_SDECL) && 
14380                 (lnode->val != lnode->def)) {
14381                 internal_error(state, lnode->def, "bad sdecl");
14382         }
14383         /* See if the lattice value has changed */
14384         changed = lval_changed(state, old, lnode);
14385         if (lnode->val != scratch) {
14386                 xfree(scratch);
14387         }
14388         return changed;
14389 }
14390
14391 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14392         struct lattice_node *lnode)
14393 {
14394         struct lattice_node *cond;
14395 #if DEBUG_SCC
14396         {
14397                 struct flow_edge *fedge;
14398                 fprintf(stderr, "branch: %d (",
14399                         lnode->def->id);
14400                 
14401                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14402                         fprintf(stderr, " %d", fedge->dst->block->vertex);
14403                 }
14404                 fprintf(stderr, " )");
14405                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14406                         fprintf(stderr, " <- %d",
14407                                 RHS(lnode->def, 0)->id);
14408                 }
14409                 fprintf(stderr, "\n");
14410         }
14411 #endif
14412         if (lnode->def->op != OP_BRANCH) {
14413                 internal_error(state, lnode->def, "not branch");
14414         }
14415         /* This only applies to conditional branches */
14416         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14417                 return;
14418         }
14419         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14420         if (cond->val && !is_const(cond->val)) {
14421 #warning "FIXME do I need to do something here?"
14422                 warning(state, cond->def, "condition not constant?");
14423                 return;
14424         }
14425         if (cond->val == 0) {
14426                 scc_add_fedge(state, scc, cond->fblock->out);
14427                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14428         }
14429         else if (cond->val->u.cval) {
14430                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14431                 
14432         } else {
14433                 scc_add_fedge(state, scc, cond->fblock->out);
14434         }
14435
14436 }
14437
14438 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14439         struct lattice_node *lnode)
14440 {
14441         int changed;
14442
14443         changed = compute_lnode_val(state, scc, lnode);
14444 #if DEBUG_SCC
14445         {
14446                 struct triple **expr;
14447                 fprintf(stderr, "expr: %3d %10s (",
14448                         lnode->def->id, tops(lnode->def->op));
14449                 expr = triple_rhs(state, lnode->def, 0);
14450                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14451                         if (*expr) {
14452                                 fprintf(stderr, " %d", (*expr)->id);
14453                         }
14454                 }
14455                 fprintf(stderr, " ) -> %s\n",
14456                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14457         }
14458 #endif
14459         if (lnode->def->op == OP_BRANCH) {
14460                 scc_visit_branch(state, scc, lnode);
14461
14462         }
14463         else if (changed) {
14464                 struct ssa_edge *sedge;
14465                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14466                         scc_add_sedge(state, scc, sedge);
14467                 }
14468         }
14469 }
14470
14471 static void scc_writeback_values(
14472         struct compile_state *state, struct scc_state *scc)
14473 {
14474         struct triple *first, *ins;
14475         first = RHS(state->main_function, 0);
14476         ins = first;
14477         do {
14478                 struct lattice_node *lnode;
14479                 lnode = triple_to_lattice(state, scc, ins);
14480                 /* Restore id */
14481                 ins->id = lnode->old_id;
14482 #if DEBUG_SCC
14483                 if (lnode->val && !is_const(lnode->val)) {
14484                         warning(state, lnode->def, 
14485                                 "lattice node still high?");
14486                 }
14487 #endif
14488                 if (lnode->val && (lnode->val != ins)) {
14489                         /* See if it something I know how to write back */
14490                         switch(lnode->val->op) {
14491                         case OP_INTCONST:
14492                                 mkconst(state, ins, lnode->val->u.cval);
14493                                 break;
14494                         case OP_ADDRCONST:
14495                                 mkaddr_const(state, ins, 
14496                                         MISC(lnode->val, 0), lnode->val->u.cval);
14497                                 break;
14498                         default:
14499                                 /* By default don't copy the changes,
14500                                  * recompute them in place instead.
14501                                  */
14502                                 simplify(state, ins);
14503                                 break;
14504                         }
14505                         if (is_const(lnode->val) &&
14506                                 !constants_equal(state, lnode->val, ins)) {
14507                                 internal_error(state, 0, "constants not equal");
14508                         }
14509                         /* Free the lattice nodes */
14510                         xfree(lnode->val);
14511                         lnode->val = 0;
14512                 }
14513                 ins = ins->next;
14514         } while(ins != first);
14515 }
14516
14517 static void scc_transform(struct compile_state *state)
14518 {
14519         struct scc_state scc;
14520
14521         initialize_scc_state(state, &scc);
14522
14523         while(scc.flow_work_list || scc.ssa_work_list) {
14524                 struct flow_edge *fedge;
14525                 struct ssa_edge *sedge;
14526                 struct flow_edge *fptr;
14527                 while((fedge = scc_next_fedge(state, &scc))) {
14528                         struct block *block;
14529                         struct triple *ptr;
14530                         struct flow_block *fblock;
14531                         int time;
14532                         int done;
14533                         if (fedge->executable) {
14534                                 continue;
14535                         }
14536                         if (!fedge->dst) {
14537                                 internal_error(state, 0, "fedge without dst");
14538                         }
14539                         if (!fedge->src) {
14540                                 internal_error(state, 0, "fedge without src");
14541                         }
14542                         fedge->executable = 1;
14543                         fblock = fedge->dst;
14544                         block = fblock->block;
14545                         time = 0;
14546                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14547                                 if (fptr->executable) {
14548                                         time++;
14549                                 }
14550                         }
14551 #if DEBUG_SCC
14552                         fprintf(stderr, "vertex: %d time: %d\n", 
14553                                 block->vertex, time);
14554                         
14555 #endif
14556                         done = 0;
14557                         for(ptr = block->first; !done; ptr = ptr->next) {
14558                                 struct lattice_node *lnode;
14559                                 done = (ptr == block->last);
14560                                 lnode = &scc.lattice[ptr->id];
14561                                 if (ptr->op == OP_PHI) {
14562                                         scc_visit_phi(state, &scc, lnode);
14563                                 }
14564                                 else if (time == 1) {
14565                                         scc_visit_expr(state, &scc, lnode);
14566                                 }
14567                         }
14568                         if (fblock->out && !fblock->out->out_next) {
14569                                 scc_add_fedge(state, &scc, fblock->out);
14570                         }
14571                 }
14572                 while((sedge = scc_next_sedge(state, &scc))) {
14573                         struct lattice_node *lnode;
14574                         struct flow_block *fblock;
14575                         lnode = sedge->dst;
14576                         fblock = lnode->fblock;
14577 #if DEBUG_SCC
14578                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14579                                 sedge - scc.ssa_edges,
14580                                 sedge->src->def->id,
14581                                 sedge->dst->def->id);
14582 #endif
14583                         if (lnode->def->op == OP_PHI) {
14584                                 scc_visit_phi(state, &scc, lnode);
14585                         }
14586                         else {
14587                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14588                                         if (fptr->executable) {
14589                                                 break;
14590                                         }
14591                                 }
14592                                 if (fptr) {
14593                                         scc_visit_expr(state, &scc, lnode);
14594                                 }
14595                         }
14596                 }
14597         }
14598         
14599         scc_writeback_values(state, &scc);
14600         free_scc_state(state, &scc);
14601 }
14602
14603
14604 static void transform_to_arch_instructions(struct compile_state *state)
14605 {
14606         struct triple *ins, *first;
14607         first = RHS(state->main_function, 0);
14608         ins = first;
14609         do {
14610                 ins = transform_to_arch_instruction(state, ins);
14611         } while(ins != first);
14612 }
14613
14614 #if DEBUG_CONSISTENCY
14615 static void verify_uses(struct compile_state *state)
14616 {
14617         struct triple *first, *ins;
14618         struct triple_set *set;
14619         first = RHS(state->main_function, 0);
14620         ins = first;
14621         do {
14622                 struct triple **expr;
14623                 expr = triple_rhs(state, ins, 0);
14624                 for(; expr; expr = triple_rhs(state, ins, expr)) {
14625                         struct triple *rhs;
14626                         rhs = *expr;
14627                         for(set = rhs?rhs->use:0; set; set = set->next) {
14628                                 if (set->member == ins) {
14629                                         break;
14630                                 }
14631                         }
14632                         if (!set) {
14633                                 internal_error(state, ins, "rhs not used");
14634                         }
14635                 }
14636                 expr = triple_lhs(state, ins, 0);
14637                 for(; expr; expr = triple_lhs(state, ins, expr)) {
14638                         struct triple *lhs;
14639                         lhs = *expr;
14640                         for(set =  lhs?lhs->use:0; set; set = set->next) {
14641                                 if (set->member == ins) {
14642                                         break;
14643                                 }
14644                         }
14645                         if (!set) {
14646                                 internal_error(state, ins, "lhs not used");
14647                         }
14648                 }
14649                 ins = ins->next;
14650         } while(ins != first);
14651         
14652 }
14653 static void verify_blocks(struct compile_state *state)
14654 {
14655         struct triple *ins;
14656         struct block *block;
14657         block = state->first_block;
14658         if (!block) {
14659                 return;
14660         }
14661         do {
14662                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14663                         if (!triple_stores_block(state, ins)) {
14664                                 continue;
14665                         }
14666                         if (ins->u.block != block) {
14667                                 internal_error(state, ins, "inconsitent block specified");
14668                         }
14669                 }
14670                 if (!triple_stores_block(state, block->last->next)) {
14671                         internal_error(state, block->last->next, 
14672                                 "cannot find next block");
14673                 }
14674                 block = block->last->next->u.block;
14675                 if (!block) {
14676                         internal_error(state, block->last->next,
14677                                 "bad next block");
14678                 }
14679         } while(block != state->first_block);
14680 }
14681
14682 static void verify_domination(struct compile_state *state)
14683 {
14684         struct triple *first, *ins;
14685         struct triple_set *set;
14686         if (!state->first_block) {
14687                 return;
14688         }
14689         
14690         first = RHS(state->main_function, 0);
14691         ins = first;
14692         do {
14693                 for(set = ins->use; set; set = set->next) {
14694                         struct triple **expr;
14695                         if (set->member->op == OP_PHI) {
14696                                 continue;
14697                         }
14698                         /* See if the use is on the righ hand side */
14699                         expr = triple_rhs(state, set->member, 0);
14700                         for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14701                                 if (*expr == ins) {
14702                                         break;
14703                                 }
14704                         }
14705                         if (expr &&
14706                                 !tdominates(state, ins, set->member)) {
14707                                 internal_error(state, set->member, 
14708                                         "non dominated rhs use?");
14709                         }
14710                 }
14711                 ins = ins->next;
14712         } while(ins != first);
14713 }
14714
14715 static void verify_piece(struct compile_state *state)
14716 {
14717         struct triple *first, *ins;
14718         first = RHS(state->main_function, 0);
14719         ins = first;
14720         do {
14721                 struct triple *ptr;
14722                 int lhs, i;
14723                 lhs = TRIPLE_LHS(ins->sizes);
14724                 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14725                         lhs = 0;
14726                 }
14727                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14728                         if (ptr != LHS(ins, i)) {
14729                                 internal_error(state, ins, "malformed lhs on %s",
14730                                         tops(ins->op));
14731                         }
14732                         if (ptr->op != OP_PIECE) {
14733                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
14734                                         tops(ptr->op), i, tops(ins->op));
14735                         }
14736                         if (ptr->u.cval != i) {
14737                                 internal_error(state, ins, "bad u.cval of %d %d expected",
14738                                         ptr->u.cval, i);
14739                         }
14740                 }
14741                 ins = ins->next;
14742         } while(ins != first);
14743 }
14744 static void verify_ins_colors(struct compile_state *state)
14745 {
14746         struct triple *first, *ins;
14747         
14748         first = RHS(state->main_function, 0);
14749         ins = first;
14750         do {
14751                 ins = ins->next;
14752         } while(ins != first);
14753 }
14754 static void verify_consistency(struct compile_state *state)
14755 {
14756         verify_uses(state);
14757         verify_blocks(state);
14758         verify_domination(state);
14759         verify_piece(state);
14760         verify_ins_colors(state);
14761 }
14762 #else 
14763 static void verify_consistency(struct compile_state *state) {}
14764 #endif /* DEBUG_USES */
14765
14766 static void optimize(struct compile_state *state)
14767 {
14768         if (state->debug & DEBUG_TRIPLES) {
14769                 print_triples(state);
14770         }
14771         /* Replace structures with simpler data types */
14772         flatten_structures(state);
14773         if (state->debug & DEBUG_TRIPLES) {
14774                 print_triples(state);
14775         }
14776         verify_consistency(state);
14777         /* Analize the intermediate code */
14778         setup_basic_blocks(state);
14779         analyze_idominators(state);
14780         analyze_ipdominators(state);
14781         /* Transform the code to ssa form */
14782         transform_to_ssa_form(state);
14783         verify_consistency(state);
14784         if (state->debug & DEBUG_CODE_ELIMINATION) {
14785                 fprintf(stdout, "After transform_to_ssa_form\n");
14786                 print_blocks(state, stdout);
14787         }
14788         /* Do strength reduction and simple constant optimizations */
14789         if (state->optimize >= 1) {
14790                 simplify_all(state);
14791         }
14792         verify_consistency(state);
14793         /* Propogate constants throughout the code */
14794         if (state->optimize >= 2) {
14795 #warning "FIXME fix scc_transform"
14796                 scc_transform(state);
14797                 transform_from_ssa_form(state);
14798                 free_basic_blocks(state);
14799                 setup_basic_blocks(state);
14800                 analyze_idominators(state);
14801                 analyze_ipdominators(state);
14802                 transform_to_ssa_form(state);
14803         }
14804         verify_consistency(state);
14805 #warning "WISHLIST implement single use constants (least possible register pressure)"
14806 #warning "WISHLIST implement induction variable elimination"
14807         /* Select architecture instructions and an initial partial
14808          * coloring based on architecture constraints.
14809          */
14810         transform_to_arch_instructions(state);
14811         verify_consistency(state);
14812         if (state->debug & DEBUG_ARCH_CODE) {
14813                 printf("After transform_to_arch_instructions\n");
14814                 print_blocks(state, stdout);
14815                 print_control_flow(state);
14816         }
14817         eliminate_inefectual_code(state);
14818         verify_consistency(state);
14819         if (state->debug & DEBUG_CODE_ELIMINATION) {
14820                 printf("After eliminate_inefectual_code\n");
14821                 print_blocks(state, stdout);
14822                 print_control_flow(state);
14823         }
14824         verify_consistency(state);
14825         /* Color all of the variables to see if they will fit in registers */
14826         insert_copies_to_phi(state);
14827         if (state->debug & DEBUG_INSERTED_COPIES) {
14828                 printf("After insert_copies_to_phi\n");
14829                 print_blocks(state, stdout);
14830                 print_control_flow(state);
14831         }
14832         verify_consistency(state);
14833         insert_mandatory_copies(state);
14834         if (state->debug & DEBUG_INSERTED_COPIES) {
14835                 printf("After insert_mandatory_copies\n");
14836                 print_blocks(state, stdout);
14837                 print_control_flow(state);
14838         }
14839         verify_consistency(state);
14840         allocate_registers(state);
14841         verify_consistency(state);
14842         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14843                 print_blocks(state, stdout);
14844         }
14845         if (state->debug & DEBUG_CONTROL_FLOW) {
14846                 print_control_flow(state);
14847         }
14848         /* Remove the optimization information.
14849          * This is more to check for memory consistency than to free memory.
14850          */
14851         free_basic_blocks(state);
14852 }
14853
14854 static void print_op_asm(struct compile_state *state,
14855         struct triple *ins, FILE *fp)
14856 {
14857         struct asm_info *info;
14858         const char *ptr;
14859         unsigned lhs, rhs, i;
14860         info = ins->u.ainfo;
14861         lhs = TRIPLE_LHS(ins->sizes);
14862         rhs = TRIPLE_RHS(ins->sizes);
14863         /* Don't count the clobbers in lhs */
14864         for(i = 0; i < lhs; i++) {
14865                 if (LHS(ins, i)->type == &void_type) {
14866                         break;
14867                 }
14868         }
14869         lhs = i;
14870         fprintf(fp, "#ASM\n");
14871         fputc('\t', fp);
14872         for(ptr = info->str; *ptr; ptr++) {
14873                 char *next;
14874                 unsigned long param;
14875                 struct triple *piece;
14876                 if (*ptr != '%') {
14877                         fputc(*ptr, fp);
14878                         continue;
14879                 }
14880                 ptr++;
14881                 if (*ptr == '%') {
14882                         fputc('%', fp);
14883                         continue;
14884                 }
14885                 param = strtoul(ptr, &next, 10);
14886                 if (ptr == next) {
14887                         error(state, ins, "Invalid asm template");
14888                 }
14889                 if (param >= (lhs + rhs)) {
14890                         error(state, ins, "Invalid param %%%u in asm template",
14891                                 param);
14892                 }
14893                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14894                 fprintf(fp, "%s", 
14895                         arch_reg_str(ID_REG(piece->id)));
14896                 ptr = next -1;
14897         }
14898         fprintf(fp, "\n#NOT ASM\n");
14899 }
14900
14901
14902 /* Only use the low x86 byte registers.  This allows me
14903  * allocate the entire register when a byte register is used.
14904  */
14905 #define X86_4_8BIT_GPRS 1
14906
14907 /* Recognized x86 cpu variants */
14908 #define BAD_CPU      0
14909 #define CPU_I386     1
14910 #define CPU_P3       2
14911 #define CPU_P4       3
14912 #define CPU_K7       4
14913 #define CPU_K8       5
14914
14915 #define CPU_DEFAULT  CPU_I386
14916
14917 /* The x86 register classes */
14918 #define REGC_FLAGS    0
14919 #define REGC_GPR8     1
14920 #define REGC_GPR16    2
14921 #define REGC_GPR32    3
14922 #define REGC_GPR64    4
14923 #define REGC_MMX      5
14924 #define REGC_XMM      6
14925 #define REGC_GPR32_8  7
14926 #define REGC_GPR16_8  8
14927 #define REGC_IMM32    9
14928 #define REGC_IMM16   10
14929 #define REGC_IMM8    11
14930 #define LAST_REGC  REGC_IMM8
14931 #if LAST_REGC >= MAX_REGC
14932 #error "MAX_REGC is to low"
14933 #endif
14934
14935 /* Register class masks */
14936 #define REGCM_FLAGS   (1 << REGC_FLAGS)
14937 #define REGCM_GPR8    (1 << REGC_GPR8)
14938 #define REGCM_GPR16   (1 << REGC_GPR16)
14939 #define REGCM_GPR32   (1 << REGC_GPR32)
14940 #define REGCM_GPR64   (1 << REGC_GPR64)
14941 #define REGCM_MMX     (1 << REGC_MMX)
14942 #define REGCM_XMM     (1 << REGC_XMM)
14943 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14944 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14945 #define REGCM_IMM32   (1 << REGC_IMM32)
14946 #define REGCM_IMM16   (1 << REGC_IMM16)
14947 #define REGCM_IMM8    (1 << REGC_IMM8)
14948 #define REGCM_ALL     ((1 << (LAST_REGC + 1)) - 1)
14949
14950 /* The x86 registers */
14951 #define REG_EFLAGS  2
14952 #define REGC_FLAGS_FIRST REG_EFLAGS
14953 #define REGC_FLAGS_LAST  REG_EFLAGS
14954 #define REG_AL      3
14955 #define REG_BL      4
14956 #define REG_CL      5
14957 #define REG_DL      6
14958 #define REG_AH      7
14959 #define REG_BH      8
14960 #define REG_CH      9
14961 #define REG_DH      10
14962 #define REGC_GPR8_FIRST  REG_AL
14963 #if X86_4_8BIT_GPRS
14964 #define REGC_GPR8_LAST   REG_DL
14965 #else 
14966 #define REGC_GPR8_LAST   REG_DH
14967 #endif
14968 #define REG_AX     11
14969 #define REG_BX     12
14970 #define REG_CX     13
14971 #define REG_DX     14
14972 #define REG_SI     15
14973 #define REG_DI     16
14974 #define REG_BP     17
14975 #define REG_SP     18
14976 #define REGC_GPR16_FIRST REG_AX
14977 #define REGC_GPR16_LAST  REG_SP
14978 #define REG_EAX    19
14979 #define REG_EBX    20
14980 #define REG_ECX    21
14981 #define REG_EDX    22
14982 #define REG_ESI    23
14983 #define REG_EDI    24
14984 #define REG_EBP    25
14985 #define REG_ESP    26
14986 #define REGC_GPR32_FIRST REG_EAX
14987 #define REGC_GPR32_LAST  REG_ESP
14988 #define REG_EDXEAX 27
14989 #define REGC_GPR64_FIRST REG_EDXEAX
14990 #define REGC_GPR64_LAST  REG_EDXEAX
14991 #define REG_MMX0   28
14992 #define REG_MMX1   29
14993 #define REG_MMX2   30
14994 #define REG_MMX3   31
14995 #define REG_MMX4   32
14996 #define REG_MMX5   33
14997 #define REG_MMX6   34
14998 #define REG_MMX7   35
14999 #define REGC_MMX_FIRST REG_MMX0
15000 #define REGC_MMX_LAST  REG_MMX7
15001 #define REG_XMM0   36
15002 #define REG_XMM1   37
15003 #define REG_XMM2   38
15004 #define REG_XMM3   39
15005 #define REG_XMM4   40
15006 #define REG_XMM5   41
15007 #define REG_XMM6   42
15008 #define REG_XMM7   43
15009 #define REGC_XMM_FIRST REG_XMM0
15010 #define REGC_XMM_LAST  REG_XMM7
15011 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
15012 #define LAST_REG   REG_XMM7
15013
15014 #define REGC_GPR32_8_FIRST REG_EAX
15015 #define REGC_GPR32_8_LAST  REG_EDX
15016 #define REGC_GPR16_8_FIRST REG_AX
15017 #define REGC_GPR16_8_LAST  REG_DX
15018
15019 #define REGC_IMM8_FIRST    -1
15020 #define REGC_IMM8_LAST     -1
15021 #define REGC_IMM16_FIRST   -2
15022 #define REGC_IMM16_LAST    -1
15023 #define REGC_IMM32_FIRST   -4
15024 #define REGC_IMM32_LAST    -1
15025
15026 #if LAST_REG >= MAX_REGISTERS
15027 #error "MAX_REGISTERS to low"
15028 #endif
15029
15030
15031 static unsigned regc_size[LAST_REGC +1] = {
15032         [REGC_FLAGS]   = REGC_FLAGS_LAST   - REGC_FLAGS_FIRST + 1,
15033         [REGC_GPR8]    = REGC_GPR8_LAST    - REGC_GPR8_FIRST + 1,
15034         [REGC_GPR16]   = REGC_GPR16_LAST   - REGC_GPR16_FIRST + 1,
15035         [REGC_GPR32]   = REGC_GPR32_LAST   - REGC_GPR32_FIRST + 1,
15036         [REGC_GPR64]   = REGC_GPR64_LAST   - REGC_GPR64_FIRST + 1,
15037         [REGC_MMX]     = REGC_MMX_LAST     - REGC_MMX_FIRST + 1,
15038         [REGC_XMM]     = REGC_XMM_LAST     - REGC_XMM_FIRST + 1,
15039         [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
15040         [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
15041         [REGC_IMM32]   = 0,
15042         [REGC_IMM16]   = 0,
15043         [REGC_IMM8]    = 0,
15044 };
15045
15046 static const struct {
15047         int first, last;
15048 } regcm_bound[LAST_REGC + 1] = {
15049         [REGC_FLAGS]   = { REGC_FLAGS_FIRST,   REGC_FLAGS_LAST },
15050         [REGC_GPR8]    = { REGC_GPR8_FIRST,    REGC_GPR8_LAST },
15051         [REGC_GPR16]   = { REGC_GPR16_FIRST,   REGC_GPR16_LAST },
15052         [REGC_GPR32]   = { REGC_GPR32_FIRST,   REGC_GPR32_LAST },
15053         [REGC_GPR64]   = { REGC_GPR64_FIRST,   REGC_GPR64_LAST },
15054         [REGC_MMX]     = { REGC_MMX_FIRST,     REGC_MMX_LAST },
15055         [REGC_XMM]     = { REGC_XMM_FIRST,     REGC_XMM_LAST },
15056         [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
15057         [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
15058         [REGC_IMM32]   = { REGC_IMM32_FIRST,   REGC_IMM32_LAST },
15059         [REGC_IMM16]   = { REGC_IMM16_FIRST,   REGC_IMM16_LAST },
15060         [REGC_IMM8]    = { REGC_IMM8_FIRST,    REGC_IMM8_LAST },
15061 };
15062
15063 static int arch_encode_cpu(const char *cpu)
15064 {
15065         struct cpu {
15066                 const char *name;
15067                 int cpu;
15068         } cpus[] = {
15069                 { "i386", CPU_I386 },
15070                 { "p3",   CPU_P3 },
15071                 { "p4",   CPU_P4 },
15072                 { "k7",   CPU_K7 },
15073                 { "k8",   CPU_K8 },
15074                 {  0,     BAD_CPU }
15075         };
15076         struct cpu *ptr;
15077         for(ptr = cpus; ptr->name; ptr++) {
15078                 if (strcmp(ptr->name, cpu) == 0) {
15079                         break;
15080                 }
15081         }
15082         return ptr->cpu;
15083 }
15084
15085 static unsigned arch_regc_size(struct compile_state *state, int class)
15086 {
15087         if ((class < 0) || (class > LAST_REGC)) {
15088                 return 0;
15089         }
15090         return regc_size[class];
15091 }
15092 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
15093 {
15094         /* See if two register classes may have overlapping registers */
15095         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
15096                 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
15097
15098         /* Special case for the immediates */
15099         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15100                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
15101                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15102                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
15103                 return 0;
15104         }
15105         return (regcm1 & regcm2) ||
15106                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
15107 }
15108
15109 static void arch_reg_equivs(
15110         struct compile_state *state, unsigned *equiv, int reg)
15111 {
15112         if ((reg < 0) || (reg > LAST_REG)) {
15113                 internal_error(state, 0, "invalid register");
15114         }
15115         *equiv++ = reg;
15116         switch(reg) {
15117         case REG_AL:
15118 #if X86_4_8BIT_GPRS
15119                 *equiv++ = REG_AH;
15120 #endif
15121                 *equiv++ = REG_AX;
15122                 *equiv++ = REG_EAX;
15123                 *equiv++ = REG_EDXEAX;
15124                 break;
15125         case REG_AH:
15126 #if X86_4_8BIT_GPRS
15127                 *equiv++ = REG_AL;
15128 #endif
15129                 *equiv++ = REG_AX;
15130                 *equiv++ = REG_EAX;
15131                 *equiv++ = REG_EDXEAX;
15132                 break;
15133         case REG_BL:  
15134 #if X86_4_8BIT_GPRS
15135                 *equiv++ = REG_BH;
15136 #endif
15137                 *equiv++ = REG_BX;
15138                 *equiv++ = REG_EBX;
15139                 break;
15140
15141         case REG_BH:
15142 #if X86_4_8BIT_GPRS
15143                 *equiv++ = REG_BL;
15144 #endif
15145                 *equiv++ = REG_BX;
15146                 *equiv++ = REG_EBX;
15147                 break;
15148         case REG_CL:
15149 #if X86_4_8BIT_GPRS
15150                 *equiv++ = REG_CH;
15151 #endif
15152                 *equiv++ = REG_CX;
15153                 *equiv++ = REG_ECX;
15154                 break;
15155
15156         case REG_CH:
15157 #if X86_4_8BIT_GPRS
15158                 *equiv++ = REG_CL;
15159 #endif
15160                 *equiv++ = REG_CX;
15161                 *equiv++ = REG_ECX;
15162                 break;
15163         case REG_DL:
15164 #if X86_4_8BIT_GPRS
15165                 *equiv++ = REG_DH;
15166 #endif
15167                 *equiv++ = REG_DX;
15168                 *equiv++ = REG_EDX;
15169                 *equiv++ = REG_EDXEAX;
15170                 break;
15171         case REG_DH:
15172 #if X86_4_8BIT_GPRS
15173                 *equiv++ = REG_DL;
15174 #endif
15175                 *equiv++ = REG_DX;
15176                 *equiv++ = REG_EDX;
15177                 *equiv++ = REG_EDXEAX;
15178                 break;
15179         case REG_AX:
15180                 *equiv++ = REG_AL;
15181                 *equiv++ = REG_AH;
15182                 *equiv++ = REG_EAX;
15183                 *equiv++ = REG_EDXEAX;
15184                 break;
15185         case REG_BX:
15186                 *equiv++ = REG_BL;
15187                 *equiv++ = REG_BH;
15188                 *equiv++ = REG_EBX;
15189                 break;
15190         case REG_CX:  
15191                 *equiv++ = REG_CL;
15192                 *equiv++ = REG_CH;
15193                 *equiv++ = REG_ECX;
15194                 break;
15195         case REG_DX:  
15196                 *equiv++ = REG_DL;
15197                 *equiv++ = REG_DH;
15198                 *equiv++ = REG_EDX;
15199                 *equiv++ = REG_EDXEAX;
15200                 break;
15201         case REG_SI:  
15202                 *equiv++ = REG_ESI;
15203                 break;
15204         case REG_DI:
15205                 *equiv++ = REG_EDI;
15206                 break;
15207         case REG_BP:
15208                 *equiv++ = REG_EBP;
15209                 break;
15210         case REG_SP:
15211                 *equiv++ = REG_ESP;
15212                 break;
15213         case REG_EAX:
15214                 *equiv++ = REG_AL;
15215                 *equiv++ = REG_AH;
15216                 *equiv++ = REG_AX;
15217                 *equiv++ = REG_EDXEAX;
15218                 break;
15219         case REG_EBX:
15220                 *equiv++ = REG_BL;
15221                 *equiv++ = REG_BH;
15222                 *equiv++ = REG_BX;
15223                 break;
15224         case REG_ECX:
15225                 *equiv++ = REG_CL;
15226                 *equiv++ = REG_CH;
15227                 *equiv++ = REG_CX;
15228                 break;
15229         case REG_EDX:
15230                 *equiv++ = REG_DL;
15231                 *equiv++ = REG_DH;
15232                 *equiv++ = REG_DX;
15233                 *equiv++ = REG_EDXEAX;
15234                 break;
15235         case REG_ESI: 
15236                 *equiv++ = REG_SI;
15237                 break;
15238         case REG_EDI: 
15239                 *equiv++ = REG_DI;
15240                 break;
15241         case REG_EBP: 
15242                 *equiv++ = REG_BP;
15243                 break;
15244         case REG_ESP: 
15245                 *equiv++ = REG_SP;
15246                 break;
15247         case REG_EDXEAX: 
15248                 *equiv++ = REG_AL;
15249                 *equiv++ = REG_AH;
15250                 *equiv++ = REG_DL;
15251                 *equiv++ = REG_DH;
15252                 *equiv++ = REG_AX;
15253                 *equiv++ = REG_DX;
15254                 *equiv++ = REG_EAX;
15255                 *equiv++ = REG_EDX;
15256                 break;
15257         }
15258         *equiv++ = REG_UNSET; 
15259 }
15260
15261 static unsigned arch_avail_mask(struct compile_state *state)
15262 {
15263         unsigned avail_mask;
15264         avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 | 
15265                 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
15266                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15267         switch(state->cpu) {
15268         case CPU_P3:
15269         case CPU_K7:
15270                 avail_mask |= REGCM_MMX;
15271                 break;
15272         case CPU_P4:
15273         case CPU_K8:
15274                 avail_mask |= REGCM_MMX | REGCM_XMM;
15275                 break;
15276         }
15277 #if 0
15278         /* Don't enable 8 bit values until I can force both operands
15279          * to be 8bits simultaneously.
15280          */
15281         avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
15282 #endif
15283         return avail_mask;
15284 }
15285
15286 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15287 {
15288         unsigned mask, result;
15289         int class, class2;
15290         result = regcm;
15291         result &= arch_avail_mask(state);
15292
15293         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15294                 if ((result & mask) == 0) {
15295                         continue;
15296                 }
15297                 if (class > LAST_REGC) {
15298                         result &= ~mask;
15299                 }
15300                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15301                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15302                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15303                                 result |= (1 << class2);
15304                         }
15305                 }
15306         }
15307         return result;
15308 }
15309
15310 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15311 {
15312         unsigned mask;
15313         int class;
15314         mask = 0;
15315         for(class = 0; class <= LAST_REGC; class++) {
15316                 if ((reg >= regcm_bound[class].first) &&
15317                         (reg <= regcm_bound[class].last)) {
15318                         mask |= (1 << class);
15319                 }
15320         }
15321         if (!mask) {
15322                 internal_error(state, 0, "reg %d not in any class", reg);
15323         }
15324         return mask;
15325 }
15326
15327 static struct reg_info arch_reg_constraint(
15328         struct compile_state *state, struct type *type, const char *constraint)
15329 {
15330         static const struct {
15331                 char class;
15332                 unsigned int mask;
15333                 unsigned int reg;
15334         } constraints[] = {
15335                 { 'r', REGCM_GPR32, REG_UNSET },
15336                 { 'g', REGCM_GPR32, REG_UNSET },
15337                 { 'p', REGCM_GPR32, REG_UNSET },
15338                 { 'q', REGCM_GPR8,  REG_UNSET },
15339                 { 'Q', REGCM_GPR32_8, REG_UNSET },
15340                 { 'x', REGCM_XMM,   REG_UNSET },
15341                 { 'y', REGCM_MMX,   REG_UNSET },
15342                 { 'a', REGCM_GPR32, REG_EAX },
15343                 { 'b', REGCM_GPR32, REG_EBX },
15344                 { 'c', REGCM_GPR32, REG_ECX },
15345                 { 'd', REGCM_GPR32, REG_EDX },
15346                 { 'D', REGCM_GPR32, REG_EDI },
15347                 { 'S', REGCM_GPR32, REG_ESI },
15348                 { '\0', 0, REG_UNSET },
15349         };
15350         unsigned int regcm;
15351         unsigned int mask, reg;
15352         struct reg_info result;
15353         const char *ptr;
15354         regcm = arch_type_to_regcm(state, type);
15355         reg = REG_UNSET;
15356         mask = 0;
15357         for(ptr = constraint; *ptr; ptr++) {
15358                 int i;
15359                 if (*ptr ==  ' ') {
15360                         continue;
15361                 }
15362                 for(i = 0; constraints[i].class != '\0'; i++) {
15363                         if (constraints[i].class == *ptr) {
15364                                 break;
15365                         }
15366                 }
15367                 if (constraints[i].class == '\0') {
15368                         error(state, 0, "invalid register constraint ``%c''", *ptr);
15369                         break;
15370                 }
15371                 if ((constraints[i].mask & regcm) == 0) {
15372                         error(state, 0, "invalid register class %c specified",
15373                                 *ptr);
15374                 }
15375                 mask |= constraints[i].mask;
15376                 if (constraints[i].reg != REG_UNSET) {
15377                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15378                                 error(state, 0, "Only one register may be specified");
15379                         }
15380                         reg = constraints[i].reg;
15381                 }
15382         }
15383         result.reg = reg;
15384         result.regcm = mask;
15385         return result;
15386 }
15387
15388 static struct reg_info arch_reg_clobber(
15389         struct compile_state *state, const char *clobber)
15390 {
15391         struct reg_info result;
15392         if (strcmp(clobber, "memory") == 0) {
15393                 result.reg = REG_UNSET;
15394                 result.regcm = 0;
15395         }
15396         else if (strcmp(clobber, "%eax") == 0) {
15397                 result.reg = REG_EAX;
15398                 result.regcm = REGCM_GPR32;
15399         }
15400         else if (strcmp(clobber, "%ebx") == 0) {
15401                 result.reg = REG_EBX;
15402                 result.regcm = REGCM_GPR32;
15403         }
15404         else if (strcmp(clobber, "%ecx") == 0) {
15405                 result.reg = REG_ECX;
15406                 result.regcm = REGCM_GPR32;
15407         }
15408         else if (strcmp(clobber, "%edx") == 0) {
15409                 result.reg = REG_EDX;
15410                 result.regcm = REGCM_GPR32;
15411         }
15412         else if (strcmp(clobber, "%esi") == 0) {
15413                 result.reg = REG_ESI;
15414                 result.regcm = REGCM_GPR32;
15415         }
15416         else if (strcmp(clobber, "%edi") == 0) {
15417                 result.reg = REG_EDI;
15418                 result.regcm = REGCM_GPR32;
15419         }
15420         else if (strcmp(clobber, "%ebp") == 0) {
15421                 result.reg = REG_EBP;
15422                 result.regcm = REGCM_GPR32;
15423         }
15424         else if (strcmp(clobber, "%esp") == 0) {
15425                 result.reg = REG_ESP;
15426                 result.regcm = REGCM_GPR32;
15427         }
15428         else if (strcmp(clobber, "cc") == 0) {
15429                 result.reg = REG_EFLAGS;
15430                 result.regcm = REGCM_FLAGS;
15431         }
15432         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
15433                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15434                 result.reg = REG_XMM0 + octdigval(clobber[3]);
15435                 result.regcm = REGCM_XMM;
15436         }
15437         else if ((strncmp(clobber, "mmx", 3) == 0) &&
15438                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15439                 result.reg = REG_MMX0 + octdigval(clobber[3]);
15440                 result.regcm = REGCM_MMX;
15441         }
15442         else {
15443                 error(state, 0, "Invalid register clobber");
15444                 result.reg = REG_UNSET;
15445                 result.regcm = 0;
15446         }
15447         return result;
15448 }
15449
15450 static int do_select_reg(struct compile_state *state, 
15451         char *used, int reg, unsigned classes)
15452 {
15453         unsigned mask;
15454         if (used[reg]) {
15455                 return REG_UNSET;
15456         }
15457         mask = arch_reg_regcm(state, reg);
15458         return (classes & mask) ? reg : REG_UNSET;
15459 }
15460
15461 static int arch_select_free_register(
15462         struct compile_state *state, char *used, int classes)
15463 {
15464         /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
15465          * other types of registers.
15466          */
15467         int i, reg;
15468         reg = REG_UNSET;
15469         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15470                 reg = do_select_reg(state, used, i, classes);
15471         }
15472         for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
15473                 reg = do_select_reg(state, used, i, classes);
15474         }
15475         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15476                 reg = do_select_reg(state, used, i, classes);
15477         }
15478         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15479                 reg = do_select_reg(state, used, i, classes);
15480         }
15481         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15482                 reg = do_select_reg(state, used, i, classes);
15483         }
15484         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15485                 reg = do_select_reg(state, used, i, classes);
15486         }
15487         for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
15488                 reg = do_select_reg(state, used, i, classes);
15489         }
15490         return reg;
15491 }
15492
15493
15494 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
15495 {
15496 #warning "FIXME force types smaller (if legal) before I get here"
15497         unsigned avail_mask;
15498         unsigned mask;
15499         mask = 0;
15500         avail_mask = arch_avail_mask(state);
15501         switch(type->type & TYPE_MASK) {
15502         case TYPE_ARRAY:
15503         case TYPE_VOID: 
15504                 mask = 0; 
15505                 break;
15506         case TYPE_CHAR:
15507         case TYPE_UCHAR:
15508                 mask = REGCM_GPR8 | 
15509                         REGCM_GPR16 | REGCM_GPR16_8 | 
15510                         REGCM_GPR32 | REGCM_GPR32_8 |
15511                         REGCM_GPR64 |
15512                         REGCM_MMX | REGCM_XMM |
15513                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15514                 break;
15515         case TYPE_SHORT:
15516         case TYPE_USHORT:
15517                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
15518                         REGCM_GPR32 | REGCM_GPR32_8 |
15519                         REGCM_GPR64 |
15520                         REGCM_MMX | REGCM_XMM |
15521                         REGCM_IMM32 | REGCM_IMM16;
15522                 break;
15523         case TYPE_INT:
15524         case TYPE_UINT:
15525         case TYPE_LONG:
15526         case TYPE_ULONG:
15527         case TYPE_POINTER:
15528                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
15529                         REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15530                         REGCM_IMM32;
15531                 break;
15532         default:
15533                 internal_error(state, 0, "no register class for type");
15534                 break;
15535         }
15536         mask &= avail_mask;
15537         return mask;
15538 }
15539
15540 static int is_imm32(struct triple *imm)
15541 {
15542         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15543                 (imm->op == OP_ADDRCONST);
15544         
15545 }
15546 static int is_imm16(struct triple *imm)
15547 {
15548         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15549 }
15550 static int is_imm8(struct triple *imm)
15551 {
15552         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15553 }
15554
15555 static int get_imm32(struct triple *ins, struct triple **expr)
15556 {
15557         struct triple *imm;
15558         imm = *expr;
15559         while(imm->op == OP_COPY) {
15560                 imm = RHS(imm, 0);
15561         }
15562         if (!is_imm32(imm)) {
15563                 return 0;
15564         }
15565         unuse_triple(*expr, ins);
15566         use_triple(imm, ins);
15567         *expr = imm;
15568         return 1;
15569 }
15570
15571 static int get_imm8(struct triple *ins, struct triple **expr)
15572 {
15573         struct triple *imm;
15574         imm = *expr;
15575         while(imm->op == OP_COPY) {
15576                 imm = RHS(imm, 0);
15577         }
15578         if (!is_imm8(imm)) {
15579                 return 0;
15580         }
15581         unuse_triple(*expr, ins);
15582         use_triple(imm, ins);
15583         *expr = imm;
15584         return 1;
15585 }
15586
15587 #define TEMPLATE_NOP         0
15588 #define TEMPLATE_INTCONST8   1
15589 #define TEMPLATE_INTCONST32  2
15590 #define TEMPLATE_COPY_REG    3
15591 #define TEMPLATE_COPY_IMM32  4
15592 #define TEMPLATE_COPY_IMM16  5
15593 #define TEMPLATE_COPY_IMM8   6
15594 #define TEMPLATE_PHI         7
15595 #define TEMPLATE_STORE8      8
15596 #define TEMPLATE_STORE16     9
15597 #define TEMPLATE_STORE32    10
15598 #define TEMPLATE_LOAD8      11
15599 #define TEMPLATE_LOAD16     12
15600 #define TEMPLATE_LOAD32     13
15601 #define TEMPLATE_BINARY_REG 14
15602 #define TEMPLATE_BINARY_IMM 15
15603 #define TEMPLATE_SL_CL      16
15604 #define TEMPLATE_SL_IMM     17
15605 #define TEMPLATE_UNARY      18
15606 #define TEMPLATE_CMP_REG    19
15607 #define TEMPLATE_CMP_IMM    20
15608 #define TEMPLATE_TEST       21
15609 #define TEMPLATE_SET        22
15610 #define TEMPLATE_JMP        23
15611 #define TEMPLATE_INB_DX     24
15612 #define TEMPLATE_INB_IMM    25
15613 #define TEMPLATE_INW_DX     26
15614 #define TEMPLATE_INW_IMM    27
15615 #define TEMPLATE_INL_DX     28
15616 #define TEMPLATE_INL_IMM    29
15617 #define TEMPLATE_OUTB_DX    30
15618 #define TEMPLATE_OUTB_IMM   31
15619 #define TEMPLATE_OUTW_DX    32
15620 #define TEMPLATE_OUTW_IMM   33
15621 #define TEMPLATE_OUTL_DX    34
15622 #define TEMPLATE_OUTL_IMM   35
15623 #define TEMPLATE_BSF        36
15624 #define TEMPLATE_RDMSR      37
15625 #define TEMPLATE_WRMSR      38
15626 #define LAST_TEMPLATE       TEMPLATE_WRMSR
15627 #if LAST_TEMPLATE >= MAX_TEMPLATES
15628 #error "MAX_TEMPLATES to low"
15629 #endif
15630
15631 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15632 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15633
15634 static struct ins_template templates[] = {
15635         [TEMPLATE_NOP]      = {},
15636         [TEMPLATE_INTCONST8] = { 
15637                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15638         },
15639         [TEMPLATE_INTCONST32] = { 
15640                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15641         },
15642         [TEMPLATE_COPY_REG] = {
15643                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15644                 .rhs = { [0] = { REG_UNSET, COPY_REGCM }  },
15645         },
15646         [TEMPLATE_COPY_IMM32] = {
15647                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15648                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15649         },
15650         [TEMPLATE_COPY_IMM16] = {
15651                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
15652                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
15653         },
15654         [TEMPLATE_COPY_IMM8] = {
15655                 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15656                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15657         },
15658         [TEMPLATE_PHI] = { 
15659                 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
15660                 .rhs = { 
15661                         [ 0] = { REG_VIRT0, COPY_REGCM },
15662                         [ 1] = { REG_VIRT0, COPY_REGCM },
15663                         [ 2] = { REG_VIRT0, COPY_REGCM },
15664                         [ 3] = { REG_VIRT0, COPY_REGCM },
15665                         [ 4] = { REG_VIRT0, COPY_REGCM },
15666                         [ 5] = { REG_VIRT0, COPY_REGCM },
15667                         [ 6] = { REG_VIRT0, COPY_REGCM },
15668                         [ 7] = { REG_VIRT0, COPY_REGCM },
15669                         [ 8] = { REG_VIRT0, COPY_REGCM },
15670                         [ 9] = { REG_VIRT0, COPY_REGCM },
15671                         [10] = { REG_VIRT0, COPY_REGCM },
15672                         [11] = { REG_VIRT0, COPY_REGCM },
15673                         [12] = { REG_VIRT0, COPY_REGCM },
15674                         [13] = { REG_VIRT0, COPY_REGCM },
15675                         [14] = { REG_VIRT0, COPY_REGCM },
15676                         [15] = { REG_VIRT0, COPY_REGCM },
15677                 }, },
15678         [TEMPLATE_STORE8] = {
15679                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15680                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15681         },
15682         [TEMPLATE_STORE16] = {
15683                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15684                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15685         },
15686         [TEMPLATE_STORE32] = {
15687                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15688                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15689         },
15690         [TEMPLATE_LOAD8] = {
15691                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15692                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15693         },
15694         [TEMPLATE_LOAD16] = {
15695                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15696                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15697         },
15698         [TEMPLATE_LOAD32] = {
15699                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15700                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15701         },
15702         [TEMPLATE_BINARY_REG] = {
15703                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15704                 .rhs = { 
15705                         [0] = { REG_VIRT0, REGCM_GPR32 },
15706                         [1] = { REG_UNSET, REGCM_GPR32 },
15707                 },
15708         },
15709         [TEMPLATE_BINARY_IMM] = {
15710                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15711                 .rhs = { 
15712                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15713                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15714                 },
15715         },
15716         [TEMPLATE_SL_CL] = {
15717                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15718                 .rhs = { 
15719                         [0] = { REG_VIRT0, REGCM_GPR32 },
15720                         [1] = { REG_CL, REGCM_GPR8 },
15721                 },
15722         },
15723         [TEMPLATE_SL_IMM] = {
15724                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15725                 .rhs = { 
15726                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15727                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15728                 },
15729         },
15730         [TEMPLATE_UNARY] = {
15731                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15732                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15733         },
15734         [TEMPLATE_CMP_REG] = {
15735                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15736                 .rhs = {
15737                         [0] = { REG_UNSET, REGCM_GPR32 },
15738                         [1] = { REG_UNSET, REGCM_GPR32 },
15739                 },
15740         },
15741         [TEMPLATE_CMP_IMM] = {
15742                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15743                 .rhs = {
15744                         [0] = { REG_UNSET, REGCM_GPR32 },
15745                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15746                 },
15747         },
15748         [TEMPLATE_TEST] = {
15749                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15750                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15751         },
15752         [TEMPLATE_SET] = {
15753                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15754                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15755         },
15756         [TEMPLATE_JMP] = {
15757                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15758         },
15759         [TEMPLATE_INB_DX] = {
15760                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15761                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15762         },
15763         [TEMPLATE_INB_IMM] = {
15764                 .lhs = { [0] = { REG_AL,  REGCM_GPR8 } },  
15765                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15766         },
15767         [TEMPLATE_INW_DX]  = { 
15768                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15769                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15770         },
15771         [TEMPLATE_INW_IMM] = { 
15772                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
15773                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15774         },
15775         [TEMPLATE_INL_DX]  = {
15776                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15777                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15778         },
15779         [TEMPLATE_INL_IMM] = {
15780                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15781                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15782         },
15783         [TEMPLATE_OUTB_DX] = { 
15784                 .rhs = {
15785                         [0] = { REG_AL,  REGCM_GPR8 },
15786                         [1] = { REG_DX, REGCM_GPR16 },
15787                 },
15788         },
15789         [TEMPLATE_OUTB_IMM] = { 
15790                 .rhs = {
15791                         [0] = { REG_AL,  REGCM_GPR8 },  
15792                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15793                 },
15794         },
15795         [TEMPLATE_OUTW_DX] = { 
15796                 .rhs = {
15797                         [0] = { REG_AX,  REGCM_GPR16 },
15798                         [1] = { REG_DX, REGCM_GPR16 },
15799                 },
15800         },
15801         [TEMPLATE_OUTW_IMM] = {
15802                 .rhs = {
15803                         [0] = { REG_AX,  REGCM_GPR16 }, 
15804                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15805                 },
15806         },
15807         [TEMPLATE_OUTL_DX] = { 
15808                 .rhs = {
15809                         [0] = { REG_EAX, REGCM_GPR32 },
15810                         [1] = { REG_DX, REGCM_GPR16 },
15811                 },
15812         },
15813         [TEMPLATE_OUTL_IMM] = { 
15814                 .rhs = {
15815                         [0] = { REG_EAX, REGCM_GPR32 }, 
15816                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15817                 },
15818         },
15819         [TEMPLATE_BSF] = {
15820                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15821                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15822         },
15823         [TEMPLATE_RDMSR] = {
15824                 .lhs = { 
15825                         [0] = { REG_EAX, REGCM_GPR32 },
15826                         [1] = { REG_EDX, REGCM_GPR32 },
15827                 },
15828                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15829         },
15830         [TEMPLATE_WRMSR] = {
15831                 .rhs = {
15832                         [0] = { REG_ECX, REGCM_GPR32 },
15833                         [1] = { REG_EAX, REGCM_GPR32 },
15834                         [2] = { REG_EDX, REGCM_GPR32 },
15835                 },
15836         },
15837 };
15838
15839 static void fixup_branches(struct compile_state *state,
15840         struct triple *cmp, struct triple *use, int jmp_op)
15841 {
15842         struct triple_set *entry, *next;
15843         for(entry = use->use; entry; entry = next) {
15844                 next = entry->next;
15845                 if (entry->member->op == OP_COPY) {
15846                         fixup_branches(state, cmp, entry->member, jmp_op);
15847                 }
15848                 else if (entry->member->op == OP_BRANCH) {
15849                         struct triple *branch, *test;
15850                         struct triple *left, *right;
15851                         left = right = 0;
15852                         left = RHS(cmp, 0);
15853                         if (TRIPLE_RHS(cmp->sizes) > 1) {
15854                                 right = RHS(cmp, 1);
15855                         }
15856                         branch = entry->member;
15857                         test = pre_triple(state, branch,
15858                                 cmp->op, cmp->type, left, right);
15859                         test->template_id = TEMPLATE_TEST; 
15860                         if (cmp->op == OP_CMP) {
15861                                 test->template_id = TEMPLATE_CMP_REG;
15862                                 if (get_imm32(test, &RHS(test, 1))) {
15863                                         test->template_id = TEMPLATE_CMP_IMM;
15864                                 }
15865                         }
15866                         use_triple(RHS(test, 0), test);
15867                         use_triple(RHS(test, 1), test);
15868                         unuse_triple(RHS(branch, 0), branch);
15869                         RHS(branch, 0) = test;
15870                         branch->op = jmp_op;
15871                         branch->template_id = TEMPLATE_JMP;
15872                         use_triple(RHS(branch, 0), branch);
15873                 }
15874         }
15875 }
15876
15877 static void bool_cmp(struct compile_state *state, 
15878         struct triple *ins, int cmp_op, int jmp_op, int set_op)
15879 {
15880         struct triple_set *entry, *next;
15881         struct triple *set;
15882
15883         /* Put a barrier up before the cmp which preceeds the
15884          * copy instruction.  If a set actually occurs this gives
15885          * us a chance to move variables in registers out of the way.
15886          */
15887
15888         /* Modify the comparison operator */
15889         ins->op = cmp_op;
15890         ins->template_id = TEMPLATE_TEST;
15891         if (cmp_op == OP_CMP) {
15892                 ins->template_id = TEMPLATE_CMP_REG;
15893                 if (get_imm32(ins, &RHS(ins, 1))) {
15894                         ins->template_id =  TEMPLATE_CMP_IMM;
15895                 }
15896         }
15897         /* Generate the instruction sequence that will transform the
15898          * result of the comparison into a logical value.
15899          */
15900         set = post_triple(state, ins, set_op, ins->type, ins, 0);
15901         use_triple(ins, set);
15902         set->template_id = TEMPLATE_SET;
15903
15904         for(entry = ins->use; entry; entry = next) {
15905                 next = entry->next;
15906                 if (entry->member == set) {
15907                         continue;
15908                 }
15909                 replace_rhs_use(state, ins, set, entry->member);
15910         }
15911         fixup_branches(state, ins, set, jmp_op);
15912 }
15913
15914 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15915 {
15916         struct triple *next;
15917         int lhs, i;
15918         lhs = TRIPLE_LHS(ins->sizes);
15919         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15920                 if (next != LHS(ins, i)) {
15921                         internal_error(state, ins, "malformed lhs on %s",
15922                                 tops(ins->op));
15923                 }
15924                 if (next->op != OP_PIECE) {
15925                         internal_error(state, ins, "bad lhs op %s at %d on %s",
15926                                 tops(next->op), i, tops(ins->op));
15927                 }
15928                 if (next->u.cval != i) {
15929                         internal_error(state, ins, "bad u.cval of %d %d expected",
15930                                 next->u.cval, i);
15931                 }
15932         }
15933         return next;
15934 }
15935
15936 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15937 {
15938         struct ins_template *template;
15939         struct reg_info result;
15940         int zlhs;
15941         if (ins->op == OP_PIECE) {
15942                 index = ins->u.cval;
15943                 ins = MISC(ins, 0);
15944         }
15945         zlhs = TRIPLE_LHS(ins->sizes);
15946         if (triple_is_def(state, ins)) {
15947                 zlhs = 1;
15948         }
15949         if (index >= zlhs) {
15950                 internal_error(state, ins, "index %d out of range for %s\n",
15951                         index, tops(ins->op));
15952         }
15953         switch(ins->op) {
15954         case OP_ASM:
15955                 template = &ins->u.ainfo->tmpl;
15956                 break;
15957         default:
15958                 if (ins->template_id > LAST_TEMPLATE) {
15959                         internal_error(state, ins, "bad template number %d", 
15960                                 ins->template_id);
15961                 }
15962                 template = &templates[ins->template_id];
15963                 break;
15964         }
15965         result = template->lhs[index];
15966         result.regcm = arch_regcm_normalize(state, result.regcm);
15967         if (result.reg != REG_UNNEEDED) {
15968                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15969         }
15970         if (result.regcm == 0) {
15971                 internal_error(state, ins, "lhs %d regcm == 0", index);
15972         }
15973         return result;
15974 }
15975
15976 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15977 {
15978         struct reg_info result;
15979         struct ins_template *template;
15980         if ((index > TRIPLE_RHS(ins->sizes)) ||
15981                 (ins->op == OP_PIECE)) {
15982                 internal_error(state, ins, "index %d out of range for %s\n",
15983                         index, tops(ins->op));
15984         }
15985         switch(ins->op) {
15986         case OP_ASM:
15987                 template = &ins->u.ainfo->tmpl;
15988                 break;
15989         default:
15990                 if (ins->template_id > LAST_TEMPLATE) {
15991                         internal_error(state, ins, "bad template number %d", 
15992                                 ins->template_id);
15993                 }
15994                 template = &templates[ins->template_id];
15995                 break;
15996         }
15997         result = template->rhs[index];
15998         result.regcm = arch_regcm_normalize(state, result.regcm);
15999         if (result.regcm == 0) {
16000                 internal_error(state, ins, "rhs %d regcm == 0", index);
16001         }
16002         return result;
16003 }
16004
16005 static struct triple *transform_to_arch_instruction(
16006         struct compile_state *state, struct triple *ins)
16007 {
16008         /* Transform from generic 3 address instructions
16009          * to archtecture specific instructions.
16010          * And apply architecture specific constrains to instructions.
16011          * Copies are inserted to preserve the register flexibility
16012          * of 3 address instructions.
16013          */
16014         struct triple *next;
16015         next = ins->next;
16016         switch(ins->op) {
16017         case OP_INTCONST:
16018                 ins->template_id = TEMPLATE_INTCONST32;
16019                 if (ins->u.cval < 256) {
16020                         ins->template_id = TEMPLATE_INTCONST8;
16021                 }
16022                 break;
16023         case OP_ADDRCONST:
16024                 ins->template_id = TEMPLATE_INTCONST32;
16025                 break;
16026         case OP_NOOP:
16027         case OP_SDECL:
16028         case OP_BLOBCONST:
16029         case OP_LABEL:
16030                 ins->template_id = TEMPLATE_NOP;
16031                 break;
16032         case OP_COPY:
16033                 ins->template_id = TEMPLATE_COPY_REG;
16034                 if (is_imm8(RHS(ins, 0))) {
16035                         ins->template_id = TEMPLATE_COPY_IMM8;
16036                 }
16037                 else if (is_imm16(RHS(ins, 0))) {
16038                         ins->template_id = TEMPLATE_COPY_IMM16;
16039                 }
16040                 else if (is_imm32(RHS(ins, 0))) {
16041                         ins->template_id = TEMPLATE_COPY_IMM32;
16042                 }
16043                 else if (is_const(RHS(ins, 0))) {
16044                         internal_error(state, ins, "bad constant passed to copy");
16045                 }
16046                 break;
16047         case OP_PHI:
16048                 ins->template_id = TEMPLATE_PHI;
16049                 break;
16050         case OP_STORE:
16051                 switch(ins->type->type & TYPE_MASK) {
16052                 case TYPE_CHAR:    case TYPE_UCHAR:
16053                         ins->template_id = TEMPLATE_STORE8;
16054                         break;
16055                 case TYPE_SHORT:   case TYPE_USHORT:
16056                         ins->template_id = TEMPLATE_STORE16;
16057                         break;
16058                 case TYPE_INT:     case TYPE_UINT:
16059                 case TYPE_LONG:    case TYPE_ULONG:
16060                 case TYPE_POINTER:
16061                         ins->template_id = TEMPLATE_STORE32;
16062                         break;
16063                 default:
16064                         internal_error(state, ins, "unknown type in store");
16065                         break;
16066                 }
16067                 break;
16068         case OP_LOAD:
16069                 switch(ins->type->type & TYPE_MASK) {
16070                 case TYPE_CHAR:   case TYPE_UCHAR:
16071                         ins->template_id = TEMPLATE_LOAD8;
16072                         break;
16073                 case TYPE_SHORT:
16074                 case TYPE_USHORT:
16075                         ins->template_id = TEMPLATE_LOAD16;
16076                         break;
16077                 case TYPE_INT:
16078                 case TYPE_UINT:
16079                 case TYPE_LONG:
16080                 case TYPE_ULONG:
16081                 case TYPE_POINTER:
16082                         ins->template_id = TEMPLATE_LOAD32;
16083                         break;
16084                 default:
16085                         internal_error(state, ins, "unknown type in load");
16086                         break;
16087                 }
16088                 break;
16089         case OP_ADD:
16090         case OP_SUB:
16091         case OP_AND:
16092         case OP_XOR:
16093         case OP_OR:
16094         case OP_SMUL:
16095                 ins->template_id = TEMPLATE_BINARY_REG;
16096                 if (get_imm32(ins, &RHS(ins, 1))) {
16097                         ins->template_id = TEMPLATE_BINARY_IMM;
16098                 }
16099                 break;
16100         case OP_SL:
16101         case OP_SSR:
16102         case OP_USR:
16103                 ins->template_id = TEMPLATE_SL_CL;
16104                 if (get_imm8(ins, &RHS(ins, 1))) {
16105                         ins->template_id = TEMPLATE_SL_IMM;
16106                 }
16107                 break;
16108         case OP_INVERT:
16109         case OP_NEG:
16110                 ins->template_id = TEMPLATE_UNARY;
16111                 break;
16112         case OP_EQ: 
16113                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
16114                 break;
16115         case OP_NOTEQ:
16116                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16117                 break;
16118         case OP_SLESS:
16119                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16120                 break;
16121         case OP_ULESS:
16122                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16123                 break;
16124         case OP_SMORE:
16125                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16126                 break;
16127         case OP_UMORE:
16128                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16129                 break;
16130         case OP_SLESSEQ:
16131                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16132                 break;
16133         case OP_ULESSEQ:
16134                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16135                 break;
16136         case OP_SMOREEQ:
16137                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16138                 break;
16139         case OP_UMOREEQ:
16140                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16141                 break;
16142         case OP_LTRUE:
16143                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16144                 break;
16145         case OP_LFALSE:
16146                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16147                 break;
16148         case OP_BRANCH:
16149                 if (TRIPLE_RHS(ins->sizes) > 0) {
16150                         internal_error(state, ins, "bad branch test");
16151                 }
16152                 ins->op = OP_JMP;
16153                 ins->template_id = TEMPLATE_NOP;
16154                 break;
16155         case OP_INB:
16156         case OP_INW:
16157         case OP_INL:
16158                 switch(ins->op) {
16159                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16160                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16161                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16162                 }
16163                 if (get_imm8(ins, &RHS(ins, 0))) {
16164                         ins->template_id += 1;
16165                 }
16166                 break;
16167         case OP_OUTB:
16168         case OP_OUTW:
16169         case OP_OUTL:
16170                 switch(ins->op) {
16171                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16172                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16173                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16174                 }
16175                 if (get_imm8(ins, &RHS(ins, 1))) {
16176                         ins->template_id += 1;
16177                 }
16178                 break;
16179         case OP_BSF:
16180         case OP_BSR:
16181                 ins->template_id = TEMPLATE_BSF;
16182                 break;
16183         case OP_RDMSR:
16184                 ins->template_id = TEMPLATE_RDMSR;
16185                 next = after_lhs(state, ins);
16186                 break;
16187         case OP_WRMSR:
16188                 ins->template_id = TEMPLATE_WRMSR;
16189                 break;
16190         case OP_HLT:
16191                 ins->template_id = TEMPLATE_NOP;
16192                 break;
16193         case OP_ASM:
16194                 ins->template_id = TEMPLATE_NOP;
16195                 next = after_lhs(state, ins);
16196                 break;
16197                 /* Already transformed instructions */
16198         case OP_TEST:
16199                 ins->template_id = TEMPLATE_TEST;
16200                 break;
16201         case OP_CMP:
16202                 ins->template_id = TEMPLATE_CMP_REG;
16203                 if (get_imm32(ins, &RHS(ins, 1))) {
16204                         ins->template_id = TEMPLATE_CMP_IMM;
16205                 }
16206                 break;
16207         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16208         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16209         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16210         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16211         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16212                 ins->template_id = TEMPLATE_JMP;
16213                 break;
16214         case OP_SET_EQ:      case OP_SET_NOTEQ:
16215         case OP_SET_SLESS:   case OP_SET_ULESS:
16216         case OP_SET_SMORE:   case OP_SET_UMORE:
16217         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16218         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16219                 ins->template_id = TEMPLATE_SET;
16220                 break;
16221                 /* Unhandled instructions */
16222         case OP_PIECE:
16223         default:
16224                 internal_error(state, ins, "unhandled ins: %d %s\n",
16225                         ins->op, tops(ins->op));
16226                 break;
16227         }
16228         return next;
16229 }
16230
16231 static void generate_local_labels(struct compile_state *state)
16232 {
16233         struct triple *first, *label;
16234         int label_counter;
16235         label_counter = 0;
16236         first = RHS(state->main_function, 0);
16237         label = first;
16238         do {
16239                 if ((label->op == OP_LABEL) || 
16240                         (label->op == OP_SDECL)) {
16241                         if (label->use) {
16242                                 label->u.cval = ++label_counter;
16243                         } else {
16244                                 label->u.cval = 0;
16245                         }
16246                         
16247                 }
16248                 label = label->next;
16249         } while(label != first);
16250 }
16251
16252 static int check_reg(struct compile_state *state, 
16253         struct triple *triple, int classes)
16254 {
16255         unsigned mask;
16256         int reg;
16257         reg = ID_REG(triple->id);
16258         if (reg == REG_UNSET) {
16259                 internal_error(state, triple, "register not set");
16260         }
16261         mask = arch_reg_regcm(state, reg);
16262         if (!(classes & mask)) {
16263                 internal_error(state, triple, "reg %d in wrong class",
16264                         reg);
16265         }
16266         return reg;
16267 }
16268
16269 static const char *arch_reg_str(int reg)
16270 {
16271         static const char *regs[] = {
16272                 "%unset",
16273                 "%unneeded",
16274                 "%eflags",
16275                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16276                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16277                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16278                 "%edx:%eax",
16279                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16280                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
16281                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16282         };
16283         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16284                 reg = 0;
16285         }
16286         return regs[reg];
16287 }
16288
16289
16290 static const char *reg(struct compile_state *state, struct triple *triple,
16291         int classes)
16292 {
16293         int reg;
16294         reg = check_reg(state, triple, classes);
16295         return arch_reg_str(reg);
16296 }
16297
16298 const char *type_suffix(struct compile_state *state, struct type *type)
16299 {
16300         const char *suffix;
16301         switch(size_of(state, type)) {
16302         case 1: suffix = "b"; break;
16303         case 2: suffix = "w"; break;
16304         case 4: suffix = "l"; break;
16305         default:
16306                 internal_error(state, 0, "unknown suffix");
16307                 suffix = 0;
16308                 break;
16309         }
16310         return suffix;
16311 }
16312
16313 static void print_const_val(
16314         struct compile_state *state, struct triple *ins, FILE *fp)
16315 {
16316         switch(ins->op) {
16317         case OP_INTCONST:
16318                 fprintf(fp, " $%ld ", 
16319                         (long_t)(ins->u.cval));
16320                 break;
16321         case OP_ADDRCONST:
16322                 fprintf(fp, " $L%s%lu+%lu ",
16323                         state->label_prefix, 
16324                         MISC(ins, 0)->u.cval,
16325                         ins->u.cval);
16326                 break;
16327         default:
16328                 internal_error(state, ins, "unknown constant type");
16329                 break;
16330         }
16331 }
16332
16333 static void print_binary_op(struct compile_state *state,
16334         const char *op, struct triple *ins, FILE *fp) 
16335 {
16336         unsigned mask;
16337         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16338         if (RHS(ins, 0)->id != ins->id) {
16339                 internal_error(state, ins, "invalid register assignment");
16340         }
16341         if (is_const(RHS(ins, 1))) {
16342                 fprintf(fp, "\t%s ", op);
16343                 print_const_val(state, RHS(ins, 1), fp);
16344                 fprintf(fp, ", %s\n",
16345                         reg(state, RHS(ins, 0), mask));
16346         }
16347         else {
16348                 unsigned lmask, rmask;
16349                 int lreg, rreg;
16350                 lreg = check_reg(state, RHS(ins, 0), mask);
16351                 rreg = check_reg(state, RHS(ins, 1), mask);
16352                 lmask = arch_reg_regcm(state, lreg);
16353                 rmask = arch_reg_regcm(state, rreg);
16354                 mask = lmask & rmask;
16355                 fprintf(fp, "\t%s %s, %s\n",
16356                         op,
16357                         reg(state, RHS(ins, 1), mask),
16358                         reg(state, RHS(ins, 0), mask));
16359         }
16360 }
16361 static void print_unary_op(struct compile_state *state, 
16362         const char *op, struct triple *ins, FILE *fp)
16363 {
16364         unsigned mask;
16365         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16366         fprintf(fp, "\t%s %s\n",
16367                 op,
16368                 reg(state, RHS(ins, 0), mask));
16369 }
16370
16371 static void print_op_shift(struct compile_state *state,
16372         const char *op, struct triple *ins, FILE *fp)
16373 {
16374         unsigned mask;
16375         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16376         if (RHS(ins, 0)->id != ins->id) {
16377                 internal_error(state, ins, "invalid register assignment");
16378         }
16379         if (is_const(RHS(ins, 1))) {
16380                 fprintf(fp, "\t%s ", op);
16381                 print_const_val(state, RHS(ins, 1), fp);
16382                 fprintf(fp, ", %s\n",
16383                         reg(state, RHS(ins, 0), mask));
16384         }
16385         else {
16386                 fprintf(fp, "\t%s %s, %s\n",
16387                         op,
16388                         reg(state, RHS(ins, 1), REGCM_GPR8),
16389                         reg(state, RHS(ins, 0), mask));
16390         }
16391 }
16392
16393 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16394 {
16395         const char *op;
16396         int mask;
16397         int dreg;
16398         mask = 0;
16399         switch(ins->op) {
16400         case OP_INB: op = "inb", mask = REGCM_GPR8; break;
16401         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16402         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16403         default:
16404                 internal_error(state, ins, "not an in operation");
16405                 op = 0;
16406                 break;
16407         }
16408         dreg = check_reg(state, ins, mask);
16409         if (!reg_is_reg(state, dreg, REG_EAX)) {
16410                 internal_error(state, ins, "dst != %%eax");
16411         }
16412         if (is_const(RHS(ins, 0))) {
16413                 fprintf(fp, "\t%s ", op);
16414                 print_const_val(state, RHS(ins, 0), fp);
16415                 fprintf(fp, ", %s\n",
16416                         reg(state, ins, mask));
16417         }
16418         else {
16419                 int addr_reg;
16420                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16421                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16422                         internal_error(state, ins, "src != %%dx");
16423                 }
16424                 fprintf(fp, "\t%s %s, %s\n",
16425                         op, 
16426                         reg(state, RHS(ins, 0), REGCM_GPR16),
16427                         reg(state, ins, mask));
16428         }
16429 }
16430
16431 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16432 {
16433         const char *op;
16434         int mask;
16435         int lreg;
16436         mask = 0;
16437         switch(ins->op) {
16438         case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
16439         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16440         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16441         default:
16442                 internal_error(state, ins, "not an out operation");
16443                 op = 0;
16444                 break;
16445         }
16446         lreg = check_reg(state, RHS(ins, 0), mask);
16447         if (!reg_is_reg(state, lreg, REG_EAX)) {
16448                 internal_error(state, ins, "src != %%eax");
16449         }
16450         if (is_const(RHS(ins, 1))) {
16451                 fprintf(fp, "\t%s %s,", 
16452                         op, reg(state, RHS(ins, 0), mask));
16453                 print_const_val(state, RHS(ins, 1), fp);
16454                 fprintf(fp, "\n");
16455         }
16456         else {
16457                 int addr_reg;
16458                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16459                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16460                         internal_error(state, ins, "dst != %%dx");
16461                 }
16462                 fprintf(fp, "\t%s %s, %s\n",
16463                         op, 
16464                         reg(state, RHS(ins, 0), mask),
16465                         reg(state, RHS(ins, 1), REGCM_GPR16));
16466         }
16467 }
16468
16469 static void print_op_move(struct compile_state *state,
16470         struct triple *ins, FILE *fp)
16471 {
16472         /* op_move is complex because there are many types
16473          * of registers we can move between.
16474          * Because OP_COPY will be introduced in arbitrary locations
16475          * OP_COPY must not affect flags.
16476          */
16477         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
16478         struct triple *dst, *src;
16479         if (ins->op == OP_COPY) {
16480                 src = RHS(ins, 0);
16481                 dst = ins;
16482         }
16483         else if (ins->op == OP_WRITE) {
16484                 dst = LHS(ins, 0);
16485                 src = RHS(ins, 0);
16486         }
16487         else {
16488                 internal_error(state, ins, "unknown move operation");
16489                 src = dst = 0;
16490         }
16491         if (!is_const(src)) {
16492                 int src_reg, dst_reg;
16493                 int src_regcm, dst_regcm;
16494                 src_reg = ID_REG(src->id);
16495                 dst_reg   = ID_REG(dst->id);
16496                 src_regcm = arch_reg_regcm(state, src_reg);
16497                 dst_regcm   = arch_reg_regcm(state, dst_reg);
16498                 /* If the class is the same just move the register */
16499                 if (src_regcm & dst_regcm & 
16500                         (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
16501                         if ((src_reg != dst_reg) || !omit_copy) {
16502                                 fprintf(fp, "\tmov %s, %s\n",
16503                                         reg(state, src, src_regcm),
16504                                         reg(state, dst, dst_regcm));
16505                         }
16506                 }
16507                 /* Move 32bit to 16bit */
16508                 else if ((src_regcm & REGCM_GPR32) &&
16509                         (dst_regcm & REGCM_GPR16)) {
16510                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
16511                         if ((src_reg != dst_reg) || !omit_copy) {
16512                                 fprintf(fp, "\tmovw %s, %s\n",
16513                                         arch_reg_str(src_reg), 
16514                                         arch_reg_str(dst_reg));
16515                         }
16516                 }
16517                 /* Move 32bit to 8bit */
16518                 else if ((src_regcm & REGCM_GPR32_8) &&
16519                         (dst_regcm & REGCM_GPR8))
16520                 {
16521                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
16522                         if ((src_reg != dst_reg) || !omit_copy) {
16523                                 fprintf(fp, "\tmovb %s, %s\n",
16524                                         arch_reg_str(src_reg),
16525                                         arch_reg_str(dst_reg));
16526                         }
16527                 }
16528                 /* Move 16bit to 8bit */
16529                 else if ((src_regcm & REGCM_GPR16_8) &&
16530                         (dst_regcm & REGCM_GPR8))
16531                 {
16532                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16533                         if ((src_reg != dst_reg) || !omit_copy) {
16534                                 fprintf(fp, "\tmovb %s, %s\n",
16535                                         arch_reg_str(src_reg),
16536                                         arch_reg_str(dst_reg));
16537                         }
16538                 }
16539                 /* Move 8/16bit to 16/32bit */
16540                 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) && 
16541                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16542                         const char *op;
16543                         op = is_signed(src->type)? "movsx": "movzx";
16544                         fprintf(fp, "\t%s %s, %s\n",
16545                                 op,
16546                                 reg(state, src, src_regcm),
16547                                 reg(state, dst, dst_regcm));
16548                 }
16549                 /* Move between sse registers */
16550                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16551                         if ((src_reg != dst_reg) || !omit_copy) {
16552                                 fprintf(fp, "\tmovdqa %s, %s\n",
16553                                         reg(state, src, src_regcm),
16554                                         reg(state, dst, dst_regcm));
16555                         }
16556                 }
16557                 /* Move between mmx registers or mmx & sse  registers */
16558                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16559                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16560                         if ((src_reg != dst_reg) || !omit_copy) {
16561                                 fprintf(fp, "\tmovq %s, %s\n",
16562                                         reg(state, src, src_regcm),
16563                                         reg(state, dst, dst_regcm));
16564                         }
16565                 }
16566                 /* Move between 32bit gprs & mmx/sse registers */
16567                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16568                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16569                         fprintf(fp, "\tmovd %s, %s\n",
16570                                 reg(state, src, src_regcm),
16571                                 reg(state, dst, dst_regcm));
16572                 }
16573 #if X86_4_8BIT_GPRS
16574                 /* Move from 8bit gprs to  mmx/sse registers */
16575                 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16576                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16577                         const char *op;
16578                         int mid_reg;
16579                         op = is_signed(src->type)? "movsx":"movzx";
16580                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16581                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16582                                 op,
16583                                 reg(state, src, src_regcm),
16584                                 arch_reg_str(mid_reg),
16585                                 arch_reg_str(mid_reg),
16586                                 reg(state, dst, dst_regcm));
16587                 }
16588                 /* Move from mmx/sse registers and 8bit gprs */
16589                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16590                         (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16591                         int mid_reg;
16592                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16593                         fprintf(fp, "\tmovd %s, %s\n",
16594                                 reg(state, src, src_regcm),
16595                                 arch_reg_str(mid_reg));
16596                 }
16597                 /* Move from 32bit gprs to 16bit gprs */
16598                 else if ((src_regcm & REGCM_GPR32) &&
16599                         (dst_regcm & REGCM_GPR16)) {
16600                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16601                         if ((src_reg != dst_reg) || !omit_copy) {
16602                                 fprintf(fp, "\tmov %s, %s\n",
16603                                         arch_reg_str(src_reg),
16604                                         arch_reg_str(dst_reg));
16605                         }
16606                 }
16607                 /* Move from 32bit gprs to 8bit gprs */
16608                 else if ((src_regcm & REGCM_GPR32) &&
16609                         (dst_regcm & REGCM_GPR8)) {
16610                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16611                         if ((src_reg != dst_reg) || !omit_copy) {
16612                                 fprintf(fp, "\tmov %s, %s\n",
16613                                         arch_reg_str(src_reg),
16614                                         arch_reg_str(dst_reg));
16615                         }
16616                 }
16617                 /* Move from 16bit gprs to 8bit gprs */
16618                 else if ((src_regcm & REGCM_GPR16) &&
16619                         (dst_regcm & REGCM_GPR8)) {
16620                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16621                         if ((src_reg != dst_reg) || !omit_copy) {
16622                                 fprintf(fp, "\tmov %s, %s\n",
16623                                         arch_reg_str(src_reg),
16624                                         arch_reg_str(dst_reg));
16625                         }
16626                 }
16627 #endif /* X86_4_8BIT_GPRS */
16628                 else {
16629                         internal_error(state, ins, "unknown copy type");
16630                 }
16631         }
16632         else {
16633                 fprintf(fp, "\tmov ");
16634                 print_const_val(state, src, fp);
16635                 fprintf(fp, ", %s\n",
16636                         reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16637         }
16638 }
16639
16640 static void print_op_load(struct compile_state *state,
16641         struct triple *ins, FILE *fp)
16642 {
16643         struct triple *dst, *src;
16644         dst = ins;
16645         src = RHS(ins, 0);
16646         if (is_const(src) || is_const(dst)) {
16647                 internal_error(state, ins, "unknown load operation");
16648         }
16649         fprintf(fp, "\tmov (%s), %s\n",
16650                 reg(state, src, REGCM_GPR32),
16651                 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16652 }
16653
16654
16655 static void print_op_store(struct compile_state *state,
16656         struct triple *ins, FILE *fp)
16657 {
16658         struct triple *dst, *src;
16659         dst = LHS(ins, 0);
16660         src = RHS(ins, 0);
16661         if (is_const(src) && (src->op == OP_INTCONST)) {
16662                 long_t value;
16663                 value = (long_t)(src->u.cval);
16664                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16665                         type_suffix(state, src->type),
16666                         value,
16667                         reg(state, dst, REGCM_GPR32));
16668         }
16669         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16670                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16671                         type_suffix(state, src->type),
16672                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16673                         dst->u.cval);
16674         }
16675         else {
16676                 if (is_const(src) || is_const(dst)) {
16677                         internal_error(state, ins, "unknown store operation");
16678                 }
16679                 fprintf(fp, "\tmov%s %s, (%s)\n",
16680                         type_suffix(state, src->type),
16681                         reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16682                         reg(state, dst, REGCM_GPR32));
16683         }
16684         
16685         
16686 }
16687
16688 static void print_op_smul(struct compile_state *state,
16689         struct triple *ins, FILE *fp)
16690 {
16691         if (!is_const(RHS(ins, 1))) {
16692                 fprintf(fp, "\timul %s, %s\n",
16693                         reg(state, RHS(ins, 1), REGCM_GPR32),
16694                         reg(state, RHS(ins, 0), REGCM_GPR32));
16695         }
16696         else {
16697                 fprintf(fp, "\timul ");
16698                 print_const_val(state, RHS(ins, 1), fp);
16699                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16700         }
16701 }
16702
16703 static void print_op_cmp(struct compile_state *state,
16704         struct triple *ins, FILE *fp)
16705 {
16706         unsigned mask;
16707         int dreg;
16708         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16709         dreg = check_reg(state, ins, REGCM_FLAGS);
16710         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16711                 internal_error(state, ins, "bad dest register for cmp");
16712         }
16713         if (is_const(RHS(ins, 1))) {
16714                 fprintf(fp, "\tcmp ");
16715                 print_const_val(state, RHS(ins, 1), fp);
16716                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16717         }
16718         else {
16719                 unsigned lmask, rmask;
16720                 int lreg, rreg;
16721                 lreg = check_reg(state, RHS(ins, 0), mask);
16722                 rreg = check_reg(state, RHS(ins, 1), mask);
16723                 lmask = arch_reg_regcm(state, lreg);
16724                 rmask = arch_reg_regcm(state, rreg);
16725                 mask = lmask & rmask;
16726                 fprintf(fp, "\tcmp %s, %s\n",
16727                         reg(state, RHS(ins, 1), mask),
16728                         reg(state, RHS(ins, 0), mask));
16729         }
16730 }
16731
16732 static void print_op_test(struct compile_state *state,
16733         struct triple *ins, FILE *fp)
16734 {
16735         unsigned mask;
16736         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16737         fprintf(fp, "\ttest %s, %s\n",
16738                 reg(state, RHS(ins, 0), mask),
16739                 reg(state, RHS(ins, 0), mask));
16740 }
16741
16742 static void print_op_branch(struct compile_state *state,
16743         struct triple *branch, FILE *fp)
16744 {
16745         const char *bop = "j";
16746         if (branch->op == OP_JMP) {
16747                 if (TRIPLE_RHS(branch->sizes) != 0) {
16748                         internal_error(state, branch, "jmp with condition?");
16749                 }
16750                 bop = "jmp";
16751         }
16752         else {
16753                 struct triple *ptr;
16754                 if (TRIPLE_RHS(branch->sizes) != 1) {
16755                         internal_error(state, branch, "jmpcc without condition?");
16756                 }
16757                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16758                 if ((RHS(branch, 0)->op != OP_CMP) &&
16759                         (RHS(branch, 0)->op != OP_TEST)) {
16760                         internal_error(state, branch, "bad branch test");
16761                 }
16762 #warning "FIXME I have observed instructions between the test and branch instructions"
16763                 ptr = RHS(branch, 0);
16764                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16765                         if (ptr->op != OP_COPY) {
16766                                 internal_error(state, branch, "branch does not follow test");
16767                         }
16768                 }
16769                 switch(branch->op) {
16770                 case OP_JMP_EQ:       bop = "jz";  break;
16771                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
16772                 case OP_JMP_SLESS:    bop = "jl";  break;
16773                 case OP_JMP_ULESS:    bop = "jb";  break;
16774                 case OP_JMP_SMORE:    bop = "jg";  break;
16775                 case OP_JMP_UMORE:    bop = "ja";  break;
16776                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
16777                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
16778                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
16779                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
16780                 default:
16781                         internal_error(state, branch, "Invalid branch op");
16782                         break;
16783                 }
16784                 
16785         }
16786         fprintf(fp, "\t%s L%s%lu\n",
16787                 bop, 
16788                 state->label_prefix,
16789                 TARG(branch, 0)->u.cval);
16790 }
16791
16792 static void print_op_set(struct compile_state *state,
16793         struct triple *set, FILE *fp)
16794 {
16795         const char *sop = "set";
16796         if (TRIPLE_RHS(set->sizes) != 1) {
16797                 internal_error(state, set, "setcc without condition?");
16798         }
16799         check_reg(state, RHS(set, 0), REGCM_FLAGS);
16800         if ((RHS(set, 0)->op != OP_CMP) &&
16801                 (RHS(set, 0)->op != OP_TEST)) {
16802                 internal_error(state, set, "bad set test");
16803         }
16804         if (RHS(set, 0)->next != set) {
16805                 internal_error(state, set, "set does not follow test");
16806         }
16807         switch(set->op) {
16808         case OP_SET_EQ:       sop = "setz";  break;
16809         case OP_SET_NOTEQ:    sop = "setnz"; break;
16810         case OP_SET_SLESS:    sop = "setl";  break;
16811         case OP_SET_ULESS:    sop = "setb";  break;
16812         case OP_SET_SMORE:    sop = "setg";  break;
16813         case OP_SET_UMORE:    sop = "seta";  break;
16814         case OP_SET_SLESSEQ:  sop = "setle"; break;
16815         case OP_SET_ULESSEQ:  sop = "setbe"; break;
16816         case OP_SET_SMOREEQ:  sop = "setge"; break;
16817         case OP_SET_UMOREEQ:  sop = "setae"; break;
16818         default:
16819                 internal_error(state, set, "Invalid set op");
16820                 break;
16821         }
16822         fprintf(fp, "\t%s %s\n",
16823                 sop, reg(state, set, REGCM_GPR8));
16824 }
16825
16826 static void print_op_bit_scan(struct compile_state *state, 
16827         struct triple *ins, FILE *fp) 
16828 {
16829         const char *op;
16830         switch(ins->op) {
16831         case OP_BSF: op = "bsf"; break;
16832         case OP_BSR: op = "bsr"; break;
16833         default: 
16834                 internal_error(state, ins, "unknown bit scan");
16835                 op = 0;
16836                 break;
16837         }
16838         fprintf(fp, 
16839                 "\t%s %s, %s\n"
16840                 "\tjnz 1f\n"
16841                 "\tmovl $-1, %s\n"
16842                 "1:\n",
16843                 op,
16844                 reg(state, RHS(ins, 0), REGCM_GPR32),
16845                 reg(state, ins, REGCM_GPR32),
16846                 reg(state, ins, REGCM_GPR32));
16847 }
16848
16849 static void print_const(struct compile_state *state,
16850         struct triple *ins, FILE *fp)
16851 {
16852         switch(ins->op) {
16853         case OP_INTCONST:
16854                 switch(ins->type->type & TYPE_MASK) {
16855                 case TYPE_CHAR:
16856                 case TYPE_UCHAR:
16857                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16858                         break;
16859                 case TYPE_SHORT:
16860                 case TYPE_USHORT:
16861                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16862                         break;
16863                 case TYPE_INT:
16864                 case TYPE_UINT:
16865                 case TYPE_LONG:
16866                 case TYPE_ULONG:
16867                         fprintf(fp, ".int %lu\n", ins->u.cval);
16868                         break;
16869                 default:
16870                         internal_error(state, ins, "Unknown constant type");
16871                 }
16872                 break;
16873         case OP_BLOBCONST:
16874         {
16875                 unsigned char *blob;
16876                 size_t size, i;
16877                 size = size_of(state, ins->type);
16878                 blob = ins->u.blob;
16879                 for(i = 0; i < size; i++) {
16880                         fprintf(fp, ".byte 0x%02x\n",
16881                                 blob[i]);
16882                 }
16883                 break;
16884         }
16885         default:
16886                 internal_error(state, ins, "Unknown constant type");
16887                 break;
16888         }
16889 }
16890
16891 #define TEXT_SECTION ".rom.text"
16892 #define DATA_SECTION ".rom.data"
16893
16894 static void print_sdecl(struct compile_state *state,
16895         struct triple *ins, FILE *fp)
16896 {
16897         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16898         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16899         fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16900         print_const(state, MISC(ins, 0), fp);
16901         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16902                 
16903 }
16904
16905 static void print_instruction(struct compile_state *state,
16906         struct triple *ins, FILE *fp)
16907 {
16908         /* Assumption: after I have exted the register allocator
16909          * everything is in a valid register. 
16910          */
16911         switch(ins->op) {
16912         case OP_ASM:
16913                 print_op_asm(state, ins, fp);
16914                 break;
16915         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
16916         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
16917         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
16918         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
16919         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
16920         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
16921         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
16922         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
16923         case OP_POS:    break;
16924         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
16925         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16926         case OP_INTCONST:
16927         case OP_ADDRCONST:
16928         case OP_BLOBCONST:
16929                 /* Don't generate anything here for constants */
16930         case OP_PHI:
16931                 /* Don't generate anything for variable declarations. */
16932                 break;
16933         case OP_SDECL:
16934                 print_sdecl(state, ins, fp);
16935                 break;
16936         case OP_WRITE: 
16937         case OP_COPY:   
16938                 print_op_move(state, ins, fp);
16939                 break;
16940         case OP_LOAD:
16941                 print_op_load(state, ins, fp);
16942                 break;
16943         case OP_STORE:
16944                 print_op_store(state, ins, fp);
16945                 break;
16946         case OP_SMUL:
16947                 print_op_smul(state, ins, fp);
16948                 break;
16949         case OP_CMP:    print_op_cmp(state, ins, fp); break;
16950         case OP_TEST:   print_op_test(state, ins, fp); break;
16951         case OP_JMP:
16952         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16953         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16954         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16955         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16956         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16957                 print_op_branch(state, ins, fp);
16958                 break;
16959         case OP_SET_EQ:      case OP_SET_NOTEQ:
16960         case OP_SET_SLESS:   case OP_SET_ULESS:
16961         case OP_SET_SMORE:   case OP_SET_UMORE:
16962         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16963         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16964                 print_op_set(state, ins, fp);
16965                 break;
16966         case OP_INB:  case OP_INW:  case OP_INL:
16967                 print_op_in(state, ins, fp); 
16968                 break;
16969         case OP_OUTB: case OP_OUTW: case OP_OUTL:
16970                 print_op_out(state, ins, fp); 
16971                 break;
16972         case OP_BSF:
16973         case OP_BSR:
16974                 print_op_bit_scan(state, ins, fp);
16975                 break;
16976         case OP_RDMSR:
16977                 after_lhs(state, ins);
16978                 fprintf(fp, "\trdmsr\n");
16979                 break;
16980         case OP_WRMSR:
16981                 fprintf(fp, "\twrmsr\n");
16982                 break;
16983         case OP_HLT:
16984                 fprintf(fp, "\thlt\n");
16985                 break;
16986         case OP_LABEL:
16987                 if (!ins->use) {
16988                         return;
16989                 }
16990                 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16991                 break;
16992                 /* Ignore OP_PIECE */
16993         case OP_PIECE:
16994                 break;
16995                 /* Operations I am not yet certain how to handle */
16996         case OP_UMUL:
16997         case OP_SDIV: case OP_UDIV:
16998         case OP_SMOD: case OP_UMOD:
16999                 /* Operations that should never get here */
17000         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
17001         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
17002         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
17003         default:
17004                 internal_error(state, ins, "unknown op: %d %s",
17005                         ins->op, tops(ins->op));
17006                 break;
17007         }
17008 }
17009
17010 static void print_instructions(struct compile_state *state)
17011 {
17012         struct triple *first, *ins;
17013         int print_location;
17014         struct occurance *last_occurance;
17015         FILE *fp;
17016         print_location = 1;
17017         last_occurance = 0;
17018         fp = state->output;
17019         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17020         first = RHS(state->main_function, 0);
17021         ins = first;
17022         do {
17023                 if (print_location && 
17024                         last_occurance != ins->occurance) {
17025                         if (!ins->occurance->parent) {
17026                                 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17027                                         ins->occurance->function,
17028                                         ins->occurance->filename,
17029                                         ins->occurance->line,
17030                                         ins->occurance->col);
17031                         }
17032                         else {
17033                                 struct occurance *ptr;
17034                                 fprintf(fp, "\t/*\n");
17035                                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17036                                         fprintf(fp, "\t * %s,%s:%d.%d\n",
17037                                                 ptr->function,
17038                                                 ptr->filename,
17039                                                 ptr->line,
17040                                                 ptr->col);
17041                                 }
17042                                 fprintf(fp, "\t */\n");
17043                                 
17044                         }
17045                         if (last_occurance) {
17046                                 put_occurance(last_occurance);
17047                         }
17048                         get_occurance(ins->occurance);
17049                         last_occurance = ins->occurance;
17050                 }
17051
17052                 print_instruction(state, ins, fp);
17053                 ins = ins->next;
17054         } while(ins != first);
17055         
17056 }
17057 static void generate_code(struct compile_state *state)
17058 {
17059         generate_local_labels(state);
17060         print_instructions(state);
17061         
17062 }
17063
17064 static void print_tokens(struct compile_state *state)
17065 {
17066         struct token *tk;
17067         tk = &state->token[0];
17068         do {
17069 #if 1
17070                 token(state, 0);
17071 #else
17072                 next_token(state, 0);
17073 #endif
17074                 loc(stdout, state, 0);
17075                 printf("%s <- `%s'\n",
17076                         tokens[tk->tok],
17077                         tk->ident ? tk->ident->name :
17078                         tk->str_len ? tk->val.str : "");
17079                 
17080         } while(tk->tok != TOK_EOF);
17081 }
17082
17083 static void compile(const char *filename, const char *ofilename, 
17084         int cpu, int debug, int opt, const char *label_prefix)
17085 {
17086         int i;
17087         struct compile_state state;
17088         memset(&state, 0, sizeof(state));
17089         state.file = 0;
17090         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17091                 memset(&state.token[i], 0, sizeof(state.token[i]));
17092                 state.token[i].tok = -1;
17093         }
17094         /* Remember the debug settings */
17095         state.cpu      = cpu;
17096         state.debug    = debug;
17097         state.optimize = opt;
17098         /* Remember the output filename */
17099         state.ofilename = ofilename;
17100         state.output    = fopen(state.ofilename, "w");
17101         if (!state.output) {
17102                 error(&state, 0, "Cannot open output file %s\n",
17103                         ofilename);
17104         }
17105         /* Remember the label prefix */
17106         state.label_prefix = label_prefix;
17107         /* Prep the preprocessor */
17108         state.if_depth = 0;
17109         state.if_value = 0;
17110         /* register the C keywords */
17111         register_keywords(&state);
17112         /* register the keywords the macro preprocessor knows */
17113         register_macro_keywords(&state);
17114         /* Memorize where some special keywords are. */
17115         state.i_continue = lookup(&state, "continue", 8);
17116         state.i_break    = lookup(&state, "break", 5);
17117         /* Enter the globl definition scope */
17118         start_scope(&state);
17119         register_builtins(&state);
17120         compile_file(&state, filename, 1);
17121 #if 0
17122         print_tokens(&state);
17123 #endif  
17124         decls(&state);
17125         /* Exit the global definition scope */
17126         end_scope(&state);
17127
17128         /* Now that basic compilation has happened 
17129          * optimize the intermediate code 
17130          */
17131         optimize(&state);
17132
17133         generate_code(&state);
17134         if (state.debug) {
17135                 fprintf(stderr, "done\n");
17136         }
17137 }
17138
17139 static void version(void)
17140 {
17141         printf("romcc " VERSION " released " RELEASE_DATE "\n");
17142 }
17143
17144 static void usage(void)
17145 {
17146         version();
17147         printf(
17148                 "Usage: romcc <source>.c\n"
17149                 "Compile a C source file without using ram\n"
17150         );
17151 }
17152
17153 static void arg_error(char *fmt, ...)
17154 {
17155         va_list args;
17156         va_start(args, fmt);
17157         vfprintf(stderr, fmt, args);
17158         va_end(args);
17159         usage();
17160         exit(1);
17161 }
17162
17163 int main(int argc, char **argv)
17164 {
17165         const char *filename;
17166         const char *ofilename;
17167         const char *label_prefix;
17168         int cpu;
17169         int last_argc;
17170         int debug;
17171         int optimize;
17172         cpu = CPU_DEFAULT;
17173         label_prefix = "";
17174         ofilename = "auto.inc";
17175         optimize = 0;
17176         debug = 0;
17177         last_argc = -1;
17178         while((argc > 1) && (argc != last_argc)) {
17179                 last_argc = argc;
17180                 if (strncmp(argv[1], "--debug=", 8) == 0) {
17181                         debug = atoi(argv[1] + 8);
17182                         argv++;
17183                         argc--;
17184                 }
17185                 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17186                         label_prefix= argv[1] + 15;
17187                         argv++;
17188                         argc--;
17189                 }
17190                 else if ((strcmp(argv[1],"-O") == 0) ||
17191                         (strcmp(argv[1], "-O1") == 0)) {
17192                         optimize = 1;
17193                         argv++;
17194                         argc--;
17195                 }
17196                 else if (strcmp(argv[1],"-O2") == 0) {
17197                         optimize = 2;
17198                         argv++;
17199                         argc--;
17200                 }
17201                 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17202                         ofilename = argv[2];
17203                         argv += 2;
17204                         argc -= 2;
17205                 }
17206                 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17207                         cpu = arch_encode_cpu(argv[1] + 6);
17208                         if (cpu == BAD_CPU) {
17209                                 arg_error("Invalid cpu specified: %s\n",
17210                                         argv[1] + 6);
17211                         }
17212                         argv++;
17213                         argc--;
17214                 }
17215         }
17216         if (argc != 2) {
17217                 arg_error("Wrong argument count %d\n", argc);
17218         }
17219         filename = argv[1];
17220         compile(filename, ofilename, cpu, debug, optimize, label_prefix);
17221
17222         return 0;
17223 }