- To reduce confuse rename the parts of linuxbios bios that run from
[coreboot.git] / util / romcc / romcc.c
1 #undef VERSION_MAJOR
2 #undef VERSION_MINOR
3 #undef RELEASE_DATE
4 #undef VERSION
5 #define VERSION_MAJOR "0"
6 #define VERSION_MINOR "64"
7 #define RELEASE_DATE "28 June 2004"
8 #define VERSION VERSION_MAJOR "." VERSION_MINOR
9
10 #include <stdarg.h>
11 #include <errno.h>
12 #include <stdint.h>
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <limits.h>
22 #include <locale.h>
23 #include <time.h>
24
25 #define MAX_CWD_SIZE 4096
26 #define MAX_ALLOCATION_PASSES 100
27
28 #define DEBUG_CONSISTENCY 1
29 #define DEBUG_SDP_BLOCKS 0
30 #define DEBUG_TRIPLE_COLOR 0
31
32 #define DEBUG_DISPLAY_USES 1
33 #define DEBUG_DISPLAY_TYPES 1
34 #define DEBUG_REPLACE_CLOSURE_TYPE_HIRES 0
35 #define DEBUG_DECOMPOSE_PRINT_TUPLES 0
36 #define DEBUG_DECOMPOSE_HIRES  0
37 #define DEBUG_INITIALIZER 0
38 #define DEBUG_UPDATE_CLOSURE_TYPE 0
39 #define DEBUG_LOCAL_TRIPLE 0
40 #define DEBUG_BASIC_BLOCKS_VERBOSE 0
41 #define DEBUG_CPS_RENAME_VARIABLES_HIRES 0
42 #define DEBUG_SIMPLIFY_HIRES 0
43 #define DEBUG_SHRINKING 0
44 #define DEBUG_COALESCE_HITCHES 0
45 #define DEBUG_CODE_ELIMINATION 0
46
47 #define DEBUG_EXPLICIT_CLOSURES 0
48
49 #warning "FIXME give clear error messages about unused variables"
50 #warning "FIXME properly handle multi dimensional arrays"
51 #warning "FIXME handle multiple register sizes"
52
53 /*  Control flow graph of a loop without goto.
54  * 
55  *        AAA
56  *   +---/
57  *  /
58  * / +--->CCC
59  * | |    / \
60  * | |  DDD EEE    break;
61  * | |    \    \
62  * | |    FFF   \
63  *  \|    / \    \
64  *   |\ GGG HHH   |   continue;
65  *   | \  \   |   |
66  *   |  \ III |  /
67  *   |   \ | /  / 
68  *   |    vvv  /  
69  *   +----BBB /   
70  *         | /
71  *         vv
72  *        JJJ
73  *
74  * 
75  *             AAA
76  *     +-----+  |  +----+
77  *     |      \ | /     |
78  *     |       BBB  +-+ |
79  *     |       / \ /  | |
80  *     |     CCC JJJ / /
81  *     |     / \    / / 
82  *     |   DDD EEE / /  
83  *     |    |   +-/ /
84  *     |   FFF     /    
85  *     |   / \    /     
86  *     | GGG HHH /      
87  *     |  |   +-/
88  *     | III
89  *     +--+ 
90  *
91  * 
92  * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
93  * DFup(Z)    = { Y <- DF(Z) | idom(Y) != X }
94  *
95  *
96  * [] == DFlocal(X) U DF(X)
97  * () == DFup(X)
98  *
99  * Dominator graph of the same nodes.
100  *
101  *           AAA     AAA: [ ] ()
102  *          /   \
103  *        BBB    JJJ BBB: [ JJJ ] ( JJJ )  JJJ: [ ] ()
104  *         |
105  *        CCC        CCC: [ ] ( BBB, JJJ )
106  *        / \
107  *     DDD   EEE     DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
108  *      |
109  *     FFF           FFF: [ ] ( BBB )
110  *     / \         
111  *  GGG   HHH        GGG: [ ] ( BBB ) HHH: [ BBB ] ()
112  *   |
113  *  III              III: [ BBB ] ()
114  *
115  *
116  * BBB and JJJ are definitely the dominance frontier.
117  * Where do I place phi functions and how do I make that decision.
118  *   
119  */
120 static void die(char *fmt, ...)
121 {
122         va_list args;
123
124         va_start(args, fmt);
125         vfprintf(stderr, fmt, args);
126         va_end(args);
127         fflush(stdout);
128         fflush(stderr);
129         exit(1);
130 }
131
132 static void *xmalloc(size_t size, const char *name)
133 {
134         void *buf;
135         buf = malloc(size);
136         if (!buf) {
137                 die("Cannot malloc %ld bytes to hold %s: %s\n",
138                         size + 0UL, name, strerror(errno));
139         }
140         return buf;
141 }
142
143 static void *xcmalloc(size_t size, const char *name)
144 {
145         void *buf;
146         buf = xmalloc(size, name);
147         memset(buf, 0, size);
148         return buf;
149 }
150
151 static void *xrealloc(void *ptr, size_t size, const char *name)
152 {
153         void *buf;
154         buf = realloc(ptr, size);
155         if (!buf) {
156                 die("Cannot realloc %ld bytes to hold %s: %s\n",
157                         size + 0UL, name, strerror(errno));
158         }
159         return buf;
160 }
161
162 static void xfree(const void *ptr)
163 {
164         free((void *)ptr);
165 }
166
167 static char *xstrdup(const char *str)
168 {
169         char *new;
170         int len;
171         len = strlen(str);
172         new = xmalloc(len + 1, "xstrdup string");
173         memcpy(new, str, len);
174         new[len] = '\0';
175         return new;
176 }
177
178 static void xchdir(const char *path)
179 {
180         if (chdir(path) != 0) {
181                 die("chdir to `%s' failed: %s\n",
182                         path, strerror(errno));
183         }
184 }
185
186 static int exists(const char *dirname, const char *filename)
187 {
188         char cwd[MAX_CWD_SIZE];
189         int does_exist;
190
191         if (getcwd(cwd, sizeof(cwd)) == 0) {
192                 die("cwd buffer to small");
193         }
194
195         does_exist = 1;
196         if (chdir(dirname) != 0) {
197                 does_exist = 0;
198         }
199         if (does_exist && (access(filename, O_RDONLY) < 0)) {
200                 if ((errno != EACCES) && (errno != EROFS)) {
201                         does_exist = 0;
202                 }
203         }
204         xchdir(cwd);
205         return does_exist;
206 }
207
208
209 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
210 {
211         char cwd[MAX_CWD_SIZE];
212         int fd;
213         char *buf;
214         off_t size, progress;
215         ssize_t result;
216         struct stat stats;
217         
218         if (!filename) {
219                 *r_size = 0;
220                 return 0;
221         }
222         if (getcwd(cwd, sizeof(cwd)) == 0) {
223                 die("cwd buffer to small");
224         }
225         xchdir(dirname);
226         fd = open(filename, O_RDONLY);
227         xchdir(cwd);
228         if (fd < 0) {
229                 die("Cannot open '%s' : %s\n",
230                         filename, strerror(errno));
231         }
232         result = fstat(fd, &stats);
233         if (result < 0) {
234                 die("Cannot stat: %s: %s\n",
235                         filename, strerror(errno));
236         }
237         size = stats.st_size;
238         *r_size = size +1;
239         buf = xmalloc(size +2, filename);
240         buf[size] = '\n'; /* Make certain the file is newline terminated */
241         buf[size+1] = '\0'; /* Null terminate the file for good measure */
242         progress = 0;
243         while(progress < size) {
244                 result = read(fd, buf + progress, size - progress);
245                 if (result < 0) {
246                         if ((errno == EINTR) || (errno == EAGAIN))
247                                 continue;
248                         die("read on %s of %ld bytes failed: %s\n",
249                                 filename, (size - progress)+ 0UL, strerror(errno));
250                 }
251                 progress += result;
252         }
253         result = close(fd);
254         if (result < 0) {
255                 die("Close of %s failed: %s\n",
256                         filename, strerror(errno));
257         }
258         return buf;
259 }
260
261 /* Types on the destination platform */
262 #warning "FIXME this assumes 32bit x86 is the destination"
263 typedef int8_t   schar_t;
264 typedef uint8_t  uchar_t;
265 typedef int8_t   char_t;
266 typedef int16_t  short_t;
267 typedef uint16_t ushort_t;
268 typedef int32_t  int_t;
269 typedef uint32_t uint_t;
270 typedef int32_t  long_t;
271 typedef uint32_t ulong_t;
272
273 #define SCHAR_T_MIN (-128)
274 #define SCHAR_T_MAX 127
275 #define UCHAR_T_MAX 255
276 #define CHAR_T_MIN  SCHAR_T_MIN
277 #define CHAR_T_MAX  SCHAR_T_MAX
278 #define SHRT_T_MIN  (-32768)
279 #define SHRT_T_MAX  32767
280 #define USHRT_T_MAX 65535
281 #define INT_T_MIN   (-LONG_T_MAX - 1)
282 #define INT_T_MAX   2147483647
283 #define UINT_T_MAX  4294967295U
284 #define LONG_T_MIN  (-LONG_T_MAX - 1)
285 #define LONG_T_MAX  2147483647
286 #define ULONG_T_MAX 4294967295U
287
288 #define SIZEOF_I8    8
289 #define SIZEOF_I16   16
290 #define SIZEOF_I32   32
291 #define SIZEOF_I64   64
292
293 #define SIZEOF_CHAR    8
294 #define SIZEOF_SHORT   16
295 #define SIZEOF_INT     32
296 #define SIZEOF_LONG    (sizeof(long_t)*SIZEOF_CHAR)
297
298
299 #define ALIGNOF_CHAR    8
300 #define ALIGNOF_SHORT   16
301 #define ALIGNOF_INT     32
302 #define ALIGNOF_LONG    (sizeof(long_t)*SIZEOF_CHAR)
303
304 #define REG_SIZEOF_REG     32
305 #define REG_SIZEOF_CHAR    REG_SIZEOF_REG
306 #define REG_SIZEOF_SHORT   REG_SIZEOF_REG
307 #define REG_SIZEOF_INT     REG_SIZEOF_REG
308 #define REG_SIZEOF_LONG    REG_SIZEOF_REG
309
310 #define REG_ALIGNOF_REG     REG_SIZEOF_REG
311 #define REG_ALIGNOF_CHAR    REG_SIZEOF_REG
312 #define REG_ALIGNOF_SHORT   REG_SIZEOF_REG
313 #define REG_ALIGNOF_INT     REG_SIZEOF_REG
314 #define REG_ALIGNOF_LONG    REG_SIZEOF_REG
315
316 /* Additional definitions for clarity.
317  * I currently assume a long is the largest native
318  * machine word and that a pointer fits into it.
319  */
320 #define SIZEOF_WORD     SIZEOF_LONG
321 #define SIZEOF_POINTER  SIZEOF_LONG
322 #define ALIGNOF_WORD    ALIGNOF_LONG
323 #define ALIGNOF_POINTER ALIGNOF_LONG
324 #define REG_SIZEOF_POINTER  REG_SIZEOF_LONG
325 #define REG_ALIGNOF_POINTER REG_ALIGNOF_LONG
326
327 struct file_state {
328         struct file_state *prev;
329         const char *basename;
330         char *dirname;
331         char *buf;
332         off_t size;
333         const char *pos;
334         int line;
335         const char *line_start;
336         int report_line;
337         const char *report_name;
338         const char *report_dir;
339 };
340 struct hash_entry;
341 struct token {
342         int tok;
343         struct hash_entry *ident;
344         int str_len;
345         union {
346                 ulong_t integer;
347                 const char *str;
348                 int notmacro;
349         } val;
350 };
351
352 /* I have two classes of types:
353  * Operational types.
354  * Logical types.  (The type the C standard says the operation is of)
355  *
356  * The operational types are:
357  * chars
358  * shorts
359  * ints
360  * longs
361  *
362  * floats
363  * doubles
364  * long doubles
365  *
366  * pointer
367  */
368
369
370 /* Machine model.
371  * No memory is useable by the compiler.
372  * There is no floating point support.
373  * All operations take place in general purpose registers.
374  * There is one type of general purpose register.
375  * Unsigned longs are stored in that general purpose register.
376  */
377
378 /* Operations on general purpose registers.
379  */
380
381 #define OP_SDIVT      0
382 #define OP_UDIVT      1
383 #define OP_SMUL       2
384 #define OP_UMUL       3
385 #define OP_SDIV       4
386 #define OP_UDIV       5
387 #define OP_SMOD       6
388 #define OP_UMOD       7
389 #define OP_ADD        8
390 #define OP_SUB        9
391 #define OP_SL        10
392 #define OP_USR       11
393 #define OP_SSR       12 
394 #define OP_AND       13 
395 #define OP_XOR       14
396 #define OP_OR        15
397 #define OP_POS       16 /* Dummy positive operator don't use it */
398 #define OP_NEG       17
399 #define OP_INVERT    18
400                      
401 #define OP_EQ        20
402 #define OP_NOTEQ     21
403 #define OP_SLESS     22
404 #define OP_ULESS     23
405 #define OP_SMORE     24
406 #define OP_UMORE     25
407 #define OP_SLESSEQ   26
408 #define OP_ULESSEQ   27
409 #define OP_SMOREEQ   28
410 #define OP_UMOREEQ   29
411                      
412 #define OP_LFALSE    30  /* Test if the expression is logically false */
413 #define OP_LTRUE     31  /* Test if the expression is logcially true */
414
415 #define OP_LOAD      32
416 #define OP_STORE     33
417 /* For OP_STORE ->type holds the type
418  * RHS(0) holds the destination address
419  * RHS(1) holds the value to store.
420  */
421
422 #define OP_UEXTRACT  34
423 /* OP_UEXTRACT extracts an unsigned bitfield from a pseudo register
424  * RHS(0) holds the psuedo register to extract from
425  * ->type holds the size of the bitfield.
426  * ->u.bitfield.size holds the size of the bitfield.
427  * ->u.bitfield.offset holds the offset to extract from
428  */
429 #define OP_SEXTRACT  35
430 /* OP_SEXTRACT extracts a signed bitfield from a pseudo register
431  * RHS(0) holds the psuedo register to extract from
432  * ->type holds the size of the bitfield.
433  * ->u.bitfield.size holds the size of the bitfield.
434  * ->u.bitfield.offset holds the offset to extract from
435  */
436 #define OP_DEPOSIT   36
437 /* OP_DEPOSIT replaces a bitfield with a new value.
438  * RHS(0) holds the value to replace a bitifield in.
439  * RHS(1) holds the replacement value
440  * ->u.bitfield.size holds the size of the bitfield.
441  * ->u.bitfield.offset holds the deposit into
442  */
443
444 #define OP_NOOP      37
445
446 #define OP_MIN_CONST 50
447 #define OP_MAX_CONST 58
448 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
449 #define OP_INTCONST  50
450 /* For OP_INTCONST ->type holds the type.
451  * ->u.cval holds the constant value.
452  */
453 #define OP_BLOBCONST 51
454 /* For OP_BLOBCONST ->type holds the layout and size
455  * information.  u.blob holds a pointer to the raw binary
456  * data for the constant initializer.
457  */
458 #define OP_ADDRCONST 52
459 /* For OP_ADDRCONST ->type holds the type.
460  * MISC(0) holds the reference to the static variable.
461  * ->u.cval holds an offset from that value.
462  */
463 #define OP_UNKNOWNVAL 59
464 /* For OP_UNKNOWNAL ->type holds the type.
465  * For some reason we don't know what value this type has.
466  * This allows for variables that have don't have values
467  * assigned yet, or variables whose value we simply do not know.
468  */
469
470 #define OP_WRITE     60 
471 /* OP_WRITE moves one pseudo register to another.
472  * MISC(0) holds the destination pseudo register, which must be an OP_DECL.
473  * RHS(0) holds the psuedo to move.
474  */
475
476 #define OP_READ      61
477 /* OP_READ reads the value of a variable and makes
478  * it available for the pseudo operation.
479  * Useful for things like def-use chains.
480  * RHS(0) holds points to the triple to read from.
481  */
482 #define OP_COPY      62
483 /* OP_COPY makes a copy of the pseudo register or constant in RHS(0).
484  */
485 #define OP_CONVERT   63
486 /* OP_CONVERT makes a copy of the pseudo register or constant in RHS(0).
487  * And then the type is converted appropriately.
488  */
489 #define OP_PIECE     64
490 /* OP_PIECE returns one piece of a instruction that returns a structure.
491  * MISC(0) is the instruction
492  * u.cval is the LHS piece of the instruction to return.
493  */
494 #define OP_ASM       65
495 /* OP_ASM holds a sequence of assembly instructions, the result
496  * of a C asm directive.
497  * RHS(x) holds input value x to the assembly sequence.
498  * LHS(x) holds the output value x from the assembly sequence.
499  * u.blob holds the string of assembly instructions.
500  */
501
502 #define OP_DEREF     66
503 /* OP_DEREF generates an lvalue from a pointer.
504  * RHS(0) holds the pointer value.
505  * OP_DEREF serves as a place holder to indicate all necessary
506  * checks have been done to indicate a value is an lvalue.
507  */
508 #define OP_DOT       67
509 /* OP_DOT references a submember of a structure lvalue.
510  * MISC(0) holds the lvalue.
511  * ->u.field holds the name of the field we want.
512  *
513  * Not seen after structures are flattened.
514  */
515 #define OP_INDEX     68
516 /* OP_INDEX references a submember of a tuple or array lvalue.
517  * MISC(0) holds the lvalue.
518  * ->u.cval holds the index into the lvalue.
519  *
520  * Not seen after structures are flattened.
521  */
522 #define OP_VAL       69
523 /* OP_VAL returns the value of a subexpression of the current expression.
524  * Useful for operators that have side effects.
525  * RHS(0) holds the expression.
526  * MISC(0) holds the subexpression of RHS(0) that is the
527  * value of the expression.
528  *
529  * Not seen outside of expressions.
530  */
531
532 #define OP_TUPLE     70
533 /* OP_TUPLE is an array of triples that are either variable
534  * or values for a structure or an array.  It is used as
535  * a place holder when flattening compound types.
536  * The value represented by an OP_TUPLE is held in N registers.
537  * LHS(0..N-1) refer to those registers.
538  * ->use is a list of statements that use the value.
539  * 
540  * Although OP_TUPLE always has register sized pieces they are not
541  * used until structures are flattened/decomposed into their register
542  * components. 
543  * ???? registers ????
544  */
545
546 #define OP_BITREF    71
547 /* OP_BITREF describes a bitfield as an lvalue.
548  * RHS(0) holds the register value.
549  * ->type holds the type of the bitfield.
550  * ->u.bitfield.size holds the size of the bitfield.
551  * ->u.bitfield.offset holds the offset of the bitfield in the register
552  */
553
554
555 #define OP_FCALL     72
556 /* OP_FCALL performs a procedure call. 
557  * MISC(0) holds a pointer to the OP_LIST of a function
558  * RHS(x) holds argument x of a function
559  * 
560  * Currently not seen outside of expressions.
561  */
562 #define OP_PROG      73
563 /* OP_PROG is an expression that holds a list of statements, or
564  * expressions.  The final expression is the value of the expression.
565  * RHS(0) holds the start of the list.
566  */
567
568 /* statements */
569 #define OP_LIST      80
570 /* OP_LIST Holds a list of statements that compose a function, and a result value.
571  * RHS(0) holds the list of statements.
572  * A list of all functions is maintained.
573  */
574
575 #define OP_BRANCH    81 /* an unconditional branch */
576 /* For branch instructions
577  * TARG(0) holds the branch target.
578  * ->next holds where to branch to if the branch is not taken.
579  * The branch target can only be a label
580  */
581
582 #define OP_CBRANCH   82 /* a conditional branch */
583 /* For conditional branch instructions
584  * RHS(0) holds the branch condition.
585  * TARG(1) holds the branch target.
586  * ->next holds where to branch to if the branch is not taken.
587  * The branch target can only be a label
588  */
589
590 #define OP_CALL      83 /* an uncontional branch that will return */
591 /* For call instructions
592  * MISC(0) holds the OP_RET that returns from the branch
593  * TARG(0) holds the branch target.
594  * ->next holds where to branch to if the branch is not taken.
595  * The branch target can only be a label
596  */
597
598 #define OP_RET       84 /* an uncontinonal branch through a variable back to an OP_CALL */
599 /* For call instructions
600  * RHS(0) holds the variable with the return address
601  * The branch target can only be a label
602  */
603
604 #define OP_LABEL     86
605 /* OP_LABEL is a triple that establishes an target for branches.
606  * ->use is the list of all branches that use this label.
607  */
608
609 #define OP_ADECL     87 
610 /* OP_ADECL is a triple that establishes an lvalue for assignments.
611  * A variable takes N registers to contain.
612  * LHS(0..N-1) refer to an OP_PIECE triple that represents
613  * the Xth register that the variable is stored in.
614  * ->use is a list of statements that use the variable.
615  * 
616  * Although OP_ADECL always has register sized pieces they are not
617  * used until structures are flattened/decomposed into their register
618  * components. 
619  */
620
621 #define OP_SDECL     88
622 /* OP_SDECL is a triple that establishes a variable of static
623  * storage duration.
624  * ->use is a list of statements that use the variable.
625  * MISC(0) holds the initializer expression.
626  */
627
628
629 #define OP_PHI       89
630 /* OP_PHI is a triple used in SSA form code.  
631  * It is used when multiple code paths merge and a variable needs
632  * a single assignment from any of those code paths.
633  * The operation is a cross between OP_DECL and OP_WRITE, which
634  * is what OP_PHI is generated from.
635  * 
636  * RHS(x) points to the value from code path x
637  * The number of RHS entries is the number of control paths into the block
638  * in which OP_PHI resides.  The elements of the array point to point
639  * to the variables OP_PHI is derived from.
640  *
641  * MISC(0) holds a pointer to the orginal OP_DECL node.
642  */
643
644 #if 0
645 /* continuation helpers
646  */
647 #define OP_CPS_BRANCH    90 /* an unconditional branch */
648 /* OP_CPS_BRANCH calls a continuation 
649  * RHS(x) holds argument x of the function
650  * TARG(0) holds OP_CPS_START target
651  */
652 #define OP_CPS_CBRANCH   91  /* a conditional branch */
653 /* OP_CPS_CBRANCH conditionally calls one of two continuations 
654  * RHS(0) holds the branch condition
655  * RHS(x + 1) holds argument x of the function
656  * TARG(0) holds the OP_CPS_START to jump to when true
657  * ->next holds the OP_CPS_START to jump to when false
658  */
659 #define OP_CPS_CALL      92  /* an uncontional branch that will return */
660 /* For OP_CPS_CALL instructions
661  * RHS(x) holds argument x of the function
662  * MISC(0) holds the OP_CPS_RET that returns from the branch
663  * TARG(0) holds the branch target.
664  * ->next holds where the OP_CPS_RET will return to.
665  */
666 #define OP_CPS_RET       93
667 /* OP_CPS_RET conditionally calls one of two continuations 
668  * RHS(0) holds the variable with the return function address
669  * RHS(x + 1) holds argument x of the function
670  * The branch target may be any OP_CPS_START
671  */
672 #define OP_CPS_END       94
673 /* OP_CPS_END is the triple at the end of the program.
674  * For most practical purposes it is a branch.
675  */
676 #define OP_CPS_START     95
677 /* OP_CPS_START is a triple at the start of a continuation
678  * The arguments variables takes N registers to contain.
679  * LHS(0..N-1) refer to an OP_PIECE triple that represents
680  * the Xth register that the arguments are stored in.
681  */
682 #endif
683
684 /* Architecture specific instructions */
685 #define OP_CMP         100
686 #define OP_TEST        101
687 #define OP_SET_EQ      102
688 #define OP_SET_NOTEQ   103
689 #define OP_SET_SLESS   104
690 #define OP_SET_ULESS   105
691 #define OP_SET_SMORE   106
692 #define OP_SET_UMORE   107
693 #define OP_SET_SLESSEQ 108
694 #define OP_SET_ULESSEQ 109
695 #define OP_SET_SMOREEQ 110
696 #define OP_SET_UMOREEQ 111
697
698 #define OP_JMP         112
699 #define OP_JMP_EQ      113
700 #define OP_JMP_NOTEQ   114
701 #define OP_JMP_SLESS   115
702 #define OP_JMP_ULESS   116
703 #define OP_JMP_SMORE   117
704 #define OP_JMP_UMORE   118
705 #define OP_JMP_SLESSEQ 119
706 #define OP_JMP_ULESSEQ 120
707 #define OP_JMP_SMOREEQ 121
708 #define OP_JMP_UMOREEQ 122
709
710 /* Builtin operators that it is just simpler to use the compiler for */
711 #define OP_INB         130
712 #define OP_INW         131
713 #define OP_INL         132
714 #define OP_OUTB        133
715 #define OP_OUTW        134
716 #define OP_OUTL        135
717 #define OP_BSF         136
718 #define OP_BSR         137
719 #define OP_RDMSR       138
720 #define OP_WRMSR       139
721 #define OP_HLT         140
722
723 struct op_info {
724         const char *name;
725         unsigned flags;
726 #define PURE       0x001 /* Triple has no side effects */
727 #define IMPURE     0x002 /* Triple has side effects */
728 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
729 #define DEF        0x004 /* Triple is a variable definition */
730 #define BLOCK      0x008 /* Triple stores the current block */
731 #define STRUCTURAL 0x010 /* Triple does not generate a machine instruction */
732 #define BRANCH_BITS(FLAGS) ((FLAGS) & 0xe0 )
733 #define UBRANCH    0x020 /* Triple is an unconditional branch instruction */
734 #define CBRANCH    0x040 /* Triple is a conditional branch instruction */
735 #define RETBRANCH  0x060 /* Triple is a return instruction */
736 #define CALLBRANCH 0x080 /* Triple is a call instruction */
737 #define ENDBRANCH  0x0a0 /* Triple is an end instruction */
738 #define PART       0x100 /* Triple is really part of another triple */
739 #define BITFIELD   0x200 /* Triple manipulates a bitfield */
740         signed char lhs, rhs, misc, targ;
741 };
742
743 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
744         .name = (NAME), \
745         .flags = (FLAGS), \
746         .lhs = (LHS), \
747         .rhs = (RHS), \
748         .misc = (MISC), \
749         .targ = (TARG), \
750          }
751 static const struct op_info table_ops[] = {
752 [OP_SDIVT      ] = OP( 2,  2, 0, 0, PURE | BLOCK , "sdivt"),
753 [OP_UDIVT      ] = OP( 2,  2, 0, 0, PURE | BLOCK , "udivt"),
754 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
755 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
756 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
757 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
758 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
759 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
760 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
761 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
762 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
763 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
764 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
765 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
766 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
767 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
768 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
769 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
770 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
771
772 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
773 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
774 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
775 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
776 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
777 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
778 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
779 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
780 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
781 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
782 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
783 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
784
785 [OP_LOAD       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "load"),
786 [OP_STORE      ] = OP( 0,  2, 0, 0, PURE | BLOCK , "store"),
787
788 [OP_UEXTRACT   ] = OP( 0,  1, 0, 0, PURE | DEF | BITFIELD, "uextract"),
789 [OP_SEXTRACT   ] = OP( 0,  1, 0, 0, PURE | DEF | BITFIELD, "sextract"),
790 [OP_DEPOSIT    ] = OP( 0,  2, 0, 0, PURE | DEF | BITFIELD, "deposit"),
791
792 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "noop"),
793
794 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
795 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE , "blobconst"),
796 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
797 [OP_UNKNOWNVAL ] = OP( 0,  0, 0, 0, PURE | DEF, "unknown"),
798
799 #warning "FIXME is it correct for OP_WRITE to be a def?  I currently use it as one..."
800 [OP_WRITE      ] = OP( 0,  1, 1, 0, PURE | DEF | BLOCK, "write"),
801 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
802 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
803 [OP_CONVERT    ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "convert"),
804 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF | STRUCTURAL | PART, "piece"),
805 [OP_ASM        ] = OP(-1, -1, 0, 0, PURE, "asm"),
806 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"), 
807 [OP_DOT        ] = OP( 0,  0, 1, 0, PURE | DEF | PART, "dot"),
808 [OP_INDEX      ] = OP( 0,  0, 1, 0, PURE | DEF | PART, "index"),
809
810 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
811 [OP_TUPLE      ] = OP(-1,  0, 0, 0, 0 | PURE | BLOCK | STRUCTURAL, "tuple"),
812 [OP_BITREF     ] = OP( 0,  1, 0, 0, 0 | DEF | PURE | STRUCTURAL | BITFIELD, "bitref"),
813 /* Call is special most it can stand in for anything so it depends on context */
814 [OP_FCALL      ] = OP( 0, -1, 1, 0, 0 | BLOCK | CALLBRANCH, "fcall"),
815 [OP_PROG       ] = OP( 0,  1, 0, 0, 0 | IMPURE | BLOCK | STRUCTURAL, "prog"),
816 /* The sizes of OP_FCALL depends upon context */
817
818 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF | STRUCTURAL, "list"),
819 [OP_BRANCH     ] = OP( 0,  0, 0, 1, PURE | BLOCK | UBRANCH, "branch"),
820 [OP_CBRANCH    ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "cbranch"),
821 [OP_CALL       ] = OP( 0,  0, 1, 1, PURE | BLOCK | CALLBRANCH, "call"),
822 [OP_RET        ] = OP( 0,  1, 0, 0, PURE | BLOCK | RETBRANCH, "ret"),
823 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "label"),
824 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "adecl"),
825 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK | STRUCTURAL, "sdecl"),
826 /* The number of RHS elements of OP_PHI depend upon context */
827 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
828
829 #if 0
830 [OP_CPS_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK | UBRANCH,     "cps_branch"),
831 [OP_CPS_CBRANCH] = OP( 0, -1, 0, 1, PURE | BLOCK | CBRANCH,     "cps_cbranch"),
832 [OP_CPS_CALL   ] = OP( 0, -1, 1, 1, PURE | BLOCK | CALLBRANCH,  "cps_call"),
833 [OP_CPS_RET    ] = OP( 0, -1, 0, 0, PURE | BLOCK | RETBRANCH,   "cps_ret"),
834 [OP_CPS_END    ] = OP( 0, -1, 0, 0, IMPURE | BLOCK | ENDBRANCH, "cps_end"),
835 [OP_CPS_START  ] = OP( -1, 0, 0, 0, PURE | BLOCK | STRUCTURAL,  "cps_start"),
836 #endif
837
838 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
839 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
840 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
841 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
842 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
843 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
844 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
845 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
846 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
847 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
848 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
849 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
850 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK | UBRANCH, "jmp"),
851 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_eq"),
852 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_noteq"),
853 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_sless"),
854 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_uless"),
855 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smore"),
856 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umore"),
857 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_slesseq"),
858 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_ulesseq"),
859 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smoreq"),
860 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umoreq"),
861
862 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
863 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
864 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
865 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
866 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
867 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
868 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
869 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
870 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
871 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
872 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
873 };
874 #undef OP
875 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
876
877 static const char *tops(int index) 
878 {
879         static const char unknown[] = "unknown op";
880         if (index < 0) {
881                 return unknown;
882         }
883         if (index > OP_MAX) {
884                 return unknown;
885         }
886         return table_ops[index].name;
887 }
888
889 struct asm_info;
890 struct triple;
891 struct block;
892 struct triple_set {
893         struct triple_set *next;
894         struct triple *member;
895 };
896
897 #define MAX_LHS  63
898 #define MAX_RHS  127
899 #define MAX_MISC 3
900 #define MAX_TARG 1
901
902 struct occurance {
903         int count;
904         const char *filename;
905         const char *function;
906         int line;
907         int col;
908         struct occurance *parent;
909 };
910 struct bitfield {
911         ulong_t size : 8;
912         ulong_t offset : 24;
913 };
914 struct triple {
915         struct triple *next, *prev;
916         struct triple_set *use;
917         struct type *type;
918         unsigned int op : 8;
919         unsigned int template_id : 7;
920         unsigned int lhs  : 6;
921         unsigned int rhs  : 7;
922         unsigned int misc : 2;
923         unsigned int targ : 1;
924 #define TRIPLE_SIZE(TRIPLE) \
925         ((TRIPLE)->lhs + (TRIPLE)->rhs + (TRIPLE)->misc + (TRIPLE)->targ)
926 #define TRIPLE_LHS_OFF(PTR)  (0)
927 #define TRIPLE_RHS_OFF(PTR)  (TRIPLE_LHS_OFF(PTR) + (PTR)->lhs)
928 #define TRIPLE_MISC_OFF(PTR) (TRIPLE_RHS_OFF(PTR) + (PTR)->rhs)
929 #define TRIPLE_TARG_OFF(PTR) (TRIPLE_MISC_OFF(PTR) + (PTR)->misc)
930 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF(PTR) + (INDEX)])
931 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF(PTR) + (INDEX)])
932 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF(PTR) + (INDEX)])
933 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF(PTR) + (INDEX)])
934         unsigned id; /* A scratch value and finally the register */
935 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
936 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
937 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
938 #define TRIPLE_FLAG_VOLATILE    (1 << 28)
939 #define TRIPLE_FLAG_INLINE      (1 << 27) /* ???? */
940 #define TRIPLE_FLAG_LOCAL       (1 << 26)
941
942 #define TRIPLE_FLAG_COPY TRIPLE_FLAG_VOLATILE
943         struct occurance *occurance;
944         union {
945                 ulong_t cval;
946                 struct bitfield bitfield;
947                 struct block  *block;
948                 void *blob;
949                 struct hash_entry *field;
950                 struct asm_info *ainfo;
951                 struct triple *func;
952                 struct symbol *symbol;
953         } u;
954         struct triple *param[2];
955 };
956
957 struct reg_info {
958         unsigned reg;
959         unsigned regcm;
960 };
961 struct ins_template {
962         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
963 };
964
965 struct asm_info {
966         struct ins_template tmpl;
967         char *str;
968 };
969
970 struct block_set {
971         struct block_set *next;
972         struct block *member;
973 };
974 struct block {
975         struct block *work_next;
976         struct triple *first, *last;
977         int edge_count;
978         struct block_set *edges;
979         int users;
980         struct block_set *use;
981         struct block_set *idominates;
982         struct block_set *domfrontier;
983         struct block *idom;
984         struct block_set *ipdominates;
985         struct block_set *ipdomfrontier;
986         struct block *ipdom;
987         int vertex;
988         
989 };
990
991 struct symbol {
992         struct symbol *next;
993         struct hash_entry *ident;
994         struct triple *def;
995         struct type *type;
996         int scope_depth;
997 };
998
999 struct macro_arg {
1000         struct macro_arg *next;
1001         struct hash_entry *ident;
1002 };
1003 struct macro {
1004         struct hash_entry *ident;
1005         char *buf;
1006         int buf_len;
1007         int buf_off;
1008         struct macro_arg *args;
1009         int argc;
1010 };
1011
1012 struct hash_entry {
1013         struct hash_entry *next;
1014         const char *name;
1015         int name_len;
1016         int tok;
1017         struct macro *sym_define;
1018         struct symbol *sym_label;
1019         struct symbol *sym_tag;
1020         struct symbol *sym_ident;
1021 };
1022
1023 #define HASH_TABLE_SIZE 2048
1024
1025 struct compiler_state {
1026         const char *label_prefix;
1027         const char *ofilename;
1028         unsigned long flags;
1029         unsigned long debug;
1030         unsigned long max_allocation_passes;
1031
1032         size_t include_path_count;
1033         const char **include_paths;
1034
1035         size_t define_count;
1036         const char **defines;
1037
1038         size_t undef_count;
1039         const char **undefs;
1040 };
1041 struct arch_state {
1042         unsigned long features;
1043 };
1044 struct basic_blocks {
1045         struct triple *func;
1046         struct triple *first;
1047         struct block *first_block, *last_block;
1048         int last_vertex;
1049 };
1050 #define MAX_CPP_IF_DEPTH 63
1051 struct compile_state {
1052         struct compiler_state *compiler;
1053         struct arch_state *arch;
1054         FILE *output;
1055         FILE *errout;
1056         FILE *dbgout;
1057         struct file_state *file;
1058         struct occurance *last_occurance;
1059         const char *function;
1060         struct token token[4];
1061         struct hash_entry *hash_table[HASH_TABLE_SIZE];
1062         struct hash_entry *i_switch;
1063         struct hash_entry *i_case;
1064         struct hash_entry *i_continue;
1065         struct hash_entry *i_break;
1066         struct hash_entry *i_default;
1067         struct hash_entry *i_return;
1068         /* Additional hash entries for predefined macros */
1069         struct hash_entry *i_defined;
1070         struct hash_entry *i___VA_ARGS__;
1071         struct hash_entry *i___FILE__;
1072         struct hash_entry *i___LINE__;
1073         /* Additional hash entries for predefined identifiers */
1074         struct hash_entry *i___func__;
1075         /* Additional hash entries for attributes */
1076         struct hash_entry *i_noinline;
1077         struct hash_entry *i_always_inline;
1078         int scope_depth;
1079         unsigned char if_bytes[(MAX_CPP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1080         int if_depth;
1081         int eat_depth, eat_targ;
1082         int macro_line;
1083         struct file_state *macro_file;
1084         struct triple *functions;
1085         struct triple *main_function;
1086         struct triple *first;
1087         struct triple *global_pool;
1088         struct basic_blocks bb;
1089         int functions_joined;
1090 };
1091
1092 /* visibility global/local */
1093 /* static/auto duration */
1094 /* typedef, register, inline */
1095 #define STOR_SHIFT         0
1096 #define STOR_MASK     0x001f
1097 /* Visibility */
1098 #define STOR_GLOBAL   0x0001
1099 /* Duration */
1100 #define STOR_PERM     0x0002
1101 /* Definition locality */
1102 #define STOR_NONLOCAL 0x0004  /* The definition is not in this translation unit */
1103 /* Storage specifiers */
1104 #define STOR_AUTO     0x0000
1105 #define STOR_STATIC   0x0002
1106 #define STOR_LOCAL    0x0003
1107 #define STOR_EXTERN   0x0007
1108 #define STOR_INLINE   0x0008
1109 #define STOR_REGISTER 0x0010
1110 #define STOR_TYPEDEF  0x0018
1111
1112 #define QUAL_SHIFT         5
1113 #define QUAL_MASK     0x00e0
1114 #define QUAL_NONE     0x0000
1115 #define QUAL_CONST    0x0020
1116 #define QUAL_VOLATILE 0x0040
1117 #define QUAL_RESTRICT 0x0080
1118
1119 #define TYPE_SHIFT         8
1120 #define TYPE_MASK     0x1f00
1121 #define TYPE_INTEGER(TYPE)    ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1122 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1123 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
1124 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
1125 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1126 #define TYPE_RANK(TYPE)       ((TYPE) & ~0xF1FF)
1127 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1128 #define TYPE_DEFAULT  0x0000
1129 #define TYPE_VOID     0x0100
1130 #define TYPE_CHAR     0x0200
1131 #define TYPE_UCHAR    0x0300
1132 #define TYPE_SHORT    0x0400
1133 #define TYPE_USHORT   0x0500
1134 #define TYPE_INT      0x0600
1135 #define TYPE_UINT     0x0700
1136 #define TYPE_LONG     0x0800
1137 #define TYPE_ULONG    0x0900
1138 #define TYPE_LLONG    0x0a00 /* long long */
1139 #define TYPE_ULLONG   0x0b00
1140 #define TYPE_FLOAT    0x0c00
1141 #define TYPE_DOUBLE   0x0d00
1142 #define TYPE_LDOUBLE  0x0e00 /* long double */
1143
1144 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1145 #define TYPE_ENUM     0x1600
1146 #define TYPE_LIST     0x1700
1147 /* TYPE_LIST is a basic building block when defining enumerations
1148  * type->field_ident holds the name of this enumeration entry.
1149  * type->right holds the entry in the list.
1150  */
1151
1152 #define TYPE_STRUCT   0x1000
1153 /* For TYPE_STRUCT
1154  * type->left holds the link list of TYPE_PRODUCT entries that
1155  * make up the structure.
1156  * type->elements hold the length of the linked list
1157  */
1158 #define TYPE_UNION    0x1100
1159 /* For TYPE_UNION
1160  * type->left holds the link list of TYPE_OVERLAP entries that
1161  * make up the union.
1162  * type->elements hold the length of the linked list
1163  */
1164 #define TYPE_POINTER  0x1200 
1165 /* For TYPE_POINTER:
1166  * type->left holds the type pointed to.
1167  */
1168 #define TYPE_FUNCTION 0x1300 
1169 /* For TYPE_FUNCTION:
1170  * type->left holds the return type.
1171  * type->right holds the type of the arguments
1172  * type->elements holds the count of the arguments
1173  */
1174 #define TYPE_PRODUCT  0x1400
1175 /* TYPE_PRODUCT is a basic building block when defining structures
1176  * type->left holds the type that appears first in memory.
1177  * type->right holds the type that appears next in memory.
1178  */
1179 #define TYPE_OVERLAP  0x1500
1180 /* TYPE_OVERLAP is a basic building block when defining unions
1181  * type->left and type->right holds to types that overlap
1182  * each other in memory.
1183  */
1184 #define TYPE_ARRAY    0x1800
1185 /* TYPE_ARRAY is a basic building block when definitng arrays.
1186  * type->left holds the type we are an array of.
1187  * type->elements holds the number of elements.
1188  */
1189 #define TYPE_TUPLE    0x1900
1190 /* TYPE_TUPLE is a basic building block when defining 
1191  * positionally reference type conglomerations. (i.e. closures)
1192  * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1193  * except it has no field names.
1194  * type->left holds the liked list of TYPE_PRODUCT entries that
1195  * make up the closure type.
1196  * type->elements hold the number of elements in the closure.
1197  */
1198 #define TYPE_JOIN     0x1a00
1199 /* TYPE_JOIN is a basic building block when defining 
1200  * positionally reference type conglomerations. (i.e. closures)
1201  * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1202  * except it has no field names.
1203  * type->left holds the liked list of TYPE_OVERLAP entries that
1204  * make up the closure type.
1205  * type->elements hold the number of elements in the closure.
1206  */
1207 #define TYPE_BITFIELD 0x1b00
1208 /* TYPE_BITFIED is the type of a bitfield.
1209  * type->left holds the type basic type TYPE_BITFIELD is derived from.
1210  * type->elements holds the number of bits in the bitfield.
1211  */
1212 #define TYPE_UNKNOWN  0x1c00
1213 /* TYPE_UNKNOWN is the type of an unknown value.
1214  * Used on unknown consts and other places where I don't know the type.
1215  */
1216
1217 #define ATTRIB_SHIFT                 16
1218 #define ATTRIB_MASK          0xffff0000
1219 #define ATTRIB_NOINLINE      0x00010000
1220 #define ATTRIB_ALWAYS_INLINE 0x00020000
1221
1222 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1223
1224 struct type {
1225         unsigned int type;
1226         struct type *left, *right;
1227         ulong_t elements;
1228         struct hash_entry *field_ident;
1229         struct hash_entry *type_ident;
1230 };
1231
1232 #define TEMPLATE_BITS      7
1233 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
1234 #define MAX_REG_EQUIVS     16
1235 #define MAX_REGC           14
1236 #define MAX_REGISTERS      75
1237 #define REGISTER_BITS      7
1238 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1239 #define REG_ERROR          0
1240 #define REG_UNSET          1
1241 #define REG_UNNEEDED       2
1242 #define REG_VIRT0          (MAX_REGISTERS + 0)
1243 #define REG_VIRT1          (MAX_REGISTERS + 1)
1244 #define REG_VIRT2          (MAX_REGISTERS + 2)
1245 #define REG_VIRT3          (MAX_REGISTERS + 3)
1246 #define REG_VIRT4          (MAX_REGISTERS + 4)
1247 #define REG_VIRT5          (MAX_REGISTERS + 5)
1248 #define REG_VIRT6          (MAX_REGISTERS + 6)
1249 #define REG_VIRT7          (MAX_REGISTERS + 7)
1250 #define REG_VIRT8          (MAX_REGISTERS + 8)
1251 #define REG_VIRT9          (MAX_REGISTERS + 9)
1252
1253 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1254 #error "MAX_VIRT_REGISTERS to small"
1255 #endif
1256 #if (MAX_REGC + REGISTER_BITS) >= 26
1257 #error "Too many id bits used"
1258 #endif
1259
1260 /* Provision for 8 register classes */
1261 #define REG_SHIFT  0
1262 #define REGC_SHIFT REGISTER_BITS
1263 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1264 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1265 #define ID_REG(ID)              ((ID) & REG_MASK)
1266 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1267 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
1268 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1269 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1270                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1271
1272 #define ARCH_INPUT_REGS 4
1273 #define ARCH_OUTPUT_REGS 4
1274
1275 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1276 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1277 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1278 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1279 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1280 static void arch_reg_equivs(
1281         struct compile_state *state, unsigned *equiv, int reg);
1282 static int arch_select_free_register(
1283         struct compile_state *state, char *used, int classes);
1284 static unsigned arch_regc_size(struct compile_state *state, int class);
1285 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1286 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1287 static const char *arch_reg_str(int reg);
1288 static struct reg_info arch_reg_constraint(
1289         struct compile_state *state, struct type *type, const char *constraint);
1290 static struct reg_info arch_reg_clobber(
1291         struct compile_state *state, const char *clobber);
1292 static struct reg_info arch_reg_lhs(struct compile_state *state, 
1293         struct triple *ins, int index);
1294 static struct reg_info arch_reg_rhs(struct compile_state *state, 
1295         struct triple *ins, int index);
1296 static int arch_reg_size(int reg);
1297 static struct triple *transform_to_arch_instruction(
1298         struct compile_state *state, struct triple *ins);
1299 static struct triple *flatten(
1300         struct compile_state *state, struct triple *first, struct triple *ptr);
1301
1302
1303
1304
1305 #define DEBUG_ABORT_ON_ERROR    0x00000001
1306 #define DEBUG_BASIC_BLOCKS      0x00000002
1307 #define DEBUG_FDOMINATORS       0x00000004
1308 #define DEBUG_RDOMINATORS       0x00000008
1309 #define DEBUG_TRIPLES           0x00000010
1310 #define DEBUG_INTERFERENCE      0x00000020
1311 #define DEBUG_SCC_TRANSFORM     0x00000040
1312 #define DEBUG_SCC_TRANSFORM2    0x00000080
1313 #define DEBUG_REBUILD_SSA_FORM  0x00000100
1314 #define DEBUG_INLINE            0x00000200
1315 #define DEBUG_RANGE_CONFLICTS   0x00000400
1316 #define DEBUG_RANGE_CONFLICTS2  0x00000800
1317 #define DEBUG_COLOR_GRAPH       0x00001000
1318 #define DEBUG_COLOR_GRAPH2      0x00002000
1319 #define DEBUG_COALESCING        0x00004000
1320 #define DEBUG_COALESCING2       0x00008000
1321 #define DEBUG_VERIFICATION      0x00010000
1322 #define DEBUG_CALLS             0x00020000
1323 #define DEBUG_CALLS2            0x00040000
1324 #define DEBUG_TOKENS            0x80000000
1325
1326 #define DEBUG_DEFAULT ( \
1327         DEBUG_ABORT_ON_ERROR | \
1328         DEBUG_BASIC_BLOCKS | \
1329         DEBUG_FDOMINATORS | \
1330         DEBUG_RDOMINATORS | \
1331         DEBUG_TRIPLES | \
1332         0 )
1333
1334 #define DEBUG_ALL ( \
1335         DEBUG_ABORT_ON_ERROR   | \
1336         DEBUG_BASIC_BLOCKS     | \
1337         DEBUG_FDOMINATORS      | \
1338         DEBUG_RDOMINATORS      | \
1339         DEBUG_TRIPLES          | \
1340         DEBUG_INTERFERENCE     | \
1341         DEBUG_SCC_TRANSFORM    | \
1342         DEBUG_SCC_TRANSFORM2   | \
1343         DEBUG_REBUILD_SSA_FORM | \
1344         DEBUG_INLINE           | \
1345         DEBUG_RANGE_CONFLICTS  | \
1346         DEBUG_RANGE_CONFLICTS2 | \
1347         DEBUG_COLOR_GRAPH      | \
1348         DEBUG_COLOR_GRAPH2     | \
1349         DEBUG_COALESCING       | \
1350         DEBUG_COALESCING2      | \
1351         DEBUG_VERIFICATION     | \
1352         DEBUG_CALLS            | \
1353         DEBUG_CALLS2           | \
1354         DEBUG_TOKENS           | \
1355         0 )
1356
1357 #define COMPILER_INLINE_MASK               0x00000007
1358 #define COMPILER_INLINE_ALWAYS             0x00000000
1359 #define COMPILER_INLINE_NEVER              0x00000001
1360 #define COMPILER_INLINE_DEFAULTON          0x00000002
1361 #define COMPILER_INLINE_DEFAULTOFF         0x00000003
1362 #define COMPILER_INLINE_NOPENALTY          0x00000004
1363 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1364 #define COMPILER_SIMPLIFY                  0x00000010
1365 #define COMPILER_SCC_TRANSFORM             0x00000020
1366 #define COMPILER_SIMPLIFY_OP               0x00000040
1367 #define COMPILER_SIMPLIFY_PHI              0x00000080
1368 #define COMPILER_SIMPLIFY_LABEL            0x00000100
1369 #define COMPILER_SIMPLIFY_BRANCH           0x00000200
1370 #define COMPILER_SIMPLIFY_COPY             0x00000400
1371 #define COMPILER_SIMPLIFY_ARITH            0x00000800
1372 #define COMPILER_SIMPLIFY_SHIFT            0x00001000
1373 #define COMPILER_SIMPLIFY_BITWISE          0x00002000
1374 #define COMPILER_SIMPLIFY_LOGICAL          0x00004000
1375 #define COMPILER_SIMPLIFY_BITFIELD         0x00008000
1376
1377 #define COMPILER_CPP_ONLY                  0x80000000
1378
1379 #define COMPILER_DEFAULT_FLAGS ( \
1380         COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1381         COMPILER_INLINE_DEFAULTON | \
1382         COMPILER_SIMPLIFY_OP | \
1383         COMPILER_SIMPLIFY_PHI | \
1384         COMPILER_SIMPLIFY_LABEL | \
1385         COMPILER_SIMPLIFY_BRANCH | \
1386         COMPILER_SIMPLIFY_COPY | \
1387         COMPILER_SIMPLIFY_ARITH | \
1388         COMPILER_SIMPLIFY_SHIFT | \
1389         COMPILER_SIMPLIFY_BITWISE | \
1390         COMPILER_SIMPLIFY_LOGICAL | \
1391         COMPILER_SIMPLIFY_BITFIELD | \
1392         0 )
1393
1394 #define GLOBAL_SCOPE_DEPTH   1
1395 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1396
1397 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1398
1399
1400
1401 static void init_compiler_state(struct compiler_state *compiler)
1402 {
1403         memset(compiler, 0, sizeof(*compiler));
1404         compiler->label_prefix = "";
1405         compiler->ofilename = "auto.inc";
1406         compiler->flags = COMPILER_DEFAULT_FLAGS;
1407         compiler->debug = 0;
1408         compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1409         compiler->include_path_count = 1;
1410         compiler->include_paths      = xcmalloc(sizeof(char *), "include_paths");
1411         compiler->define_count       = 1;
1412         compiler->defines            = xcmalloc(sizeof(char *), "defines");
1413         compiler->undef_count        = 1;
1414         compiler->undefs             = xcmalloc(sizeof(char *), "undefs");
1415 }
1416
1417 struct compiler_flag {
1418         const char *name;
1419         unsigned long flag;
1420 };
1421
1422 struct compiler_arg {
1423         const char *name;
1424         unsigned long mask;
1425         struct compiler_flag flags[16];
1426 };
1427
1428 static int set_flag(
1429         const struct compiler_flag *ptr, unsigned long *flags,
1430         int act, const char *flag)
1431 {
1432         int result = -1;
1433         for(; ptr->name; ptr++) {
1434                 if (strcmp(ptr->name, flag) == 0) {
1435                         break;
1436                 }
1437         }
1438         if (ptr->name) {
1439                 result = 0;
1440                 *flags &= ~(ptr->flag);
1441                 if (act) {
1442                         *flags |= ptr->flag;
1443                 }
1444         }
1445         return result;
1446 }
1447
1448 static int set_arg(
1449         const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1450 {
1451         const char *val;
1452         int result = -1;
1453         int len;
1454         val = strchr(arg, '=');
1455         if (val) {
1456                 len = val - arg;
1457                 val++;
1458                 for(; ptr->name; ptr++) {
1459                         if (strncmp(ptr->name, arg, len) == 0) {
1460                                 break;
1461                         }
1462                 }
1463                 if (ptr->name) {
1464                         *flags &= ~ptr->mask;
1465                         result = set_flag(&ptr->flags[0], flags, 1, val);
1466                 }
1467         }
1468         return result;
1469 }
1470         
1471
1472 static void flag_usage(FILE *fp, const struct compiler_flag *ptr, 
1473         const char *prefix, const char *invert_prefix)
1474 {
1475         for(;ptr->name; ptr++) {
1476                 fprintf(fp, "%s%s\n", prefix, ptr->name);
1477                 if (invert_prefix) {
1478                         fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1479                 }
1480         }
1481 }
1482
1483 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1484         const char *prefix)
1485 {
1486         for(;ptr->name; ptr++) {
1487                 const struct compiler_flag *flag;
1488                 for(flag = &ptr->flags[0]; flag->name; flag++) {
1489                         fprintf(fp, "%s%s=%s\n", 
1490                                 prefix, ptr->name, flag->name);
1491                 }
1492         }
1493 }
1494
1495 static int append_string(size_t *max, const char ***vec, const char *str,
1496         const char *name)
1497 {
1498         size_t count;
1499         count = ++(*max);
1500         *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1501         (*vec)[count -1] = 0;
1502         (*vec)[count -2] = str; 
1503         return 0;
1504 }
1505
1506 static void arg_error(char *fmt, ...);
1507 static const char *identifier(const char *str, const char *end);
1508
1509 static int append_include_path(struct compiler_state *compiler, const char *str)
1510 {
1511         int result;
1512         if (!exists(str, ".")) {
1513                 arg_error("Nonexistent include path: `%s'\n",
1514                         str);
1515         }
1516         result = append_string(&compiler->include_path_count,
1517                 &compiler->include_paths, str, "include_paths");
1518         return result;
1519 }
1520
1521 static int append_define(struct compiler_state *compiler, const char *str)
1522 {
1523         const char *end, *rest;
1524         int result;
1525
1526         end = strchr(str, '=');
1527         if (!end) {
1528                 end = str + strlen(str);
1529         }
1530         rest = identifier(str, end);
1531         if (rest != end) {
1532                 int len = end - str - 1;
1533                 arg_error("Invalid name cannot define macro: `%*.*s'\n", 
1534                         len, len, str);
1535         }
1536         result = append_string(&compiler->define_count,
1537                 &compiler->defines, str, "defines");
1538         return result;
1539 }
1540
1541 static int append_undef(struct compiler_state *compiler, const char *str)
1542 {
1543         const char *end, *rest;
1544         int result;
1545
1546         end = str + strlen(str);
1547         rest = identifier(str, end);
1548         if (rest != end) {
1549                 int len = end - str - 1;
1550                 arg_error("Invalid name cannot undefine macro: `%*.*s'\n", 
1551                         len, len, str);
1552         }
1553         result = append_string(&compiler->undef_count,
1554                 &compiler->undefs, str, "undefs");
1555         return result;
1556 }
1557
1558 static const struct compiler_flag romcc_flags[] = {
1559         { "cpp-only",                  COMPILER_CPP_ONLY },
1560         { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1561         { "simplify",                  COMPILER_SIMPLIFY },
1562         { "scc-transform",             COMPILER_SCC_TRANSFORM },
1563         { "simplify-op",               COMPILER_SIMPLIFY_OP },
1564         { "simplify-phi",              COMPILER_SIMPLIFY_PHI },
1565         { "simplify-label",            COMPILER_SIMPLIFY_LABEL },
1566         { "simplify-branch",           COMPILER_SIMPLIFY_BRANCH },
1567         { "simplify-copy",             COMPILER_SIMPLIFY_COPY },
1568         { "simplify-arith",            COMPILER_SIMPLIFY_ARITH },
1569         { "simplify-shift",            COMPILER_SIMPLIFY_SHIFT },
1570         { "simplify-bitwise",          COMPILER_SIMPLIFY_BITWISE },
1571         { "simplify-logical",          COMPILER_SIMPLIFY_LOGICAL },
1572         { "simplify-bitfield",         COMPILER_SIMPLIFY_BITFIELD },
1573         { 0, 0 },
1574 };
1575 static const struct compiler_arg romcc_args[] = {
1576         { "inline-policy",             COMPILER_INLINE_MASK,
1577                 {
1578                         { "always",      COMPILER_INLINE_ALWAYS, },
1579                         { "never",       COMPILER_INLINE_NEVER, },
1580                         { "defaulton",   COMPILER_INLINE_DEFAULTON, },
1581                         { "defaultoff",  COMPILER_INLINE_DEFAULTOFF, },
1582                         { "nopenalty",   COMPILER_INLINE_NOPENALTY, },
1583                         { 0, 0 },
1584                 },
1585         },
1586         { 0, 0 },
1587 };
1588 static const struct compiler_flag romcc_opt_flags[] = {
1589         { "-O",  COMPILER_SIMPLIFY },
1590         { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1591         { "-E",  COMPILER_CPP_ONLY },
1592         { 0, 0, },
1593 };
1594 static const struct compiler_flag romcc_debug_flags[] = {
1595         { "all",                   DEBUG_ALL },
1596         { "abort-on-error",        DEBUG_ABORT_ON_ERROR },
1597         { "basic-blocks",          DEBUG_BASIC_BLOCKS },
1598         { "fdominators",           DEBUG_FDOMINATORS },
1599         { "rdominators",           DEBUG_RDOMINATORS },
1600         { "triples",               DEBUG_TRIPLES },
1601         { "interference",          DEBUG_INTERFERENCE },
1602         { "scc-transform",         DEBUG_SCC_TRANSFORM },
1603         { "scc-transform2",        DEBUG_SCC_TRANSFORM2 },
1604         { "rebuild-ssa-form",      DEBUG_REBUILD_SSA_FORM },
1605         { "inline",                DEBUG_INLINE },
1606         { "live-range-conflicts",  DEBUG_RANGE_CONFLICTS },
1607         { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1608         { "color-graph",           DEBUG_COLOR_GRAPH },
1609         { "color-graph2",          DEBUG_COLOR_GRAPH2 },
1610         { "coalescing",            DEBUG_COALESCING },
1611         { "coalescing2",           DEBUG_COALESCING2 },
1612         { "verification",          DEBUG_VERIFICATION },
1613         { "calls",                 DEBUG_CALLS },
1614         { "calls2",                DEBUG_CALLS2 },
1615         { "tokens",                DEBUG_TOKENS },
1616         { 0, 0 },
1617 };
1618
1619 static int compiler_encode_flag(
1620         struct compiler_state *compiler, const char *flag)
1621 {
1622         int act;
1623         int result;
1624
1625         act = 1;
1626         result = -1;
1627         if (strncmp(flag, "no-", 3) == 0) {
1628                 flag += 3;
1629                 act = 0;
1630         }
1631         if (strncmp(flag, "-O", 2) == 0) {
1632                 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1633         }
1634         else if (strncmp(flag, "-E", 2) == 0) {
1635                 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1636         }
1637         else if (strncmp(flag, "-I", 2) == 0) {
1638                 result = append_include_path(compiler, flag + 2);
1639         }
1640         else if (strncmp(flag, "-D", 2) == 0) {
1641                 result = append_define(compiler, flag + 2);
1642         }
1643         else if (strncmp(flag, "-U", 2) == 0) {
1644                 result = append_undef(compiler, flag + 2);
1645         }
1646         else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1647                 result = 0;
1648                 compiler->label_prefix = flag + 13;
1649         }
1650         else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1651                 unsigned long max_passes;
1652                 char *end;
1653                 max_passes = strtoul(flag + 22, &end, 10);
1654                 if (end[0] == '\0') {
1655                         result = 0;
1656                         compiler->max_allocation_passes = max_passes;
1657                 }
1658         }
1659         else if (act && strcmp(flag, "debug") == 0) {
1660                 result = 0;
1661                 compiler->debug |= DEBUG_DEFAULT;
1662         }
1663         else if (strncmp(flag, "debug-", 6) == 0) {
1664                 flag += 6;
1665                 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1666         }
1667         else {
1668                 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1669                 if (result < 0) {
1670                         result = set_arg(romcc_args, &compiler->flags, flag);
1671                 }
1672         }
1673         return result;
1674 }
1675
1676 static void compiler_usage(FILE *fp)
1677 {
1678         flag_usage(fp, romcc_opt_flags, "", 0);
1679         flag_usage(fp, romcc_flags, "-f", "-fno-");
1680         arg_usage(fp,  romcc_args, "-f");
1681         flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1682         fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1683         fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1684         fprintf(fp, "-I<include path>\n");
1685         fprintf(fp, "-D<macro>[=defn]\n");
1686         fprintf(fp, "-U<macro>\n");
1687 }
1688
1689 static void do_cleanup(struct compile_state *state)
1690 {
1691         if (state->output) {
1692                 fclose(state->output);
1693                 unlink(state->compiler->ofilename);
1694                 state->output = 0;
1695         }
1696         if (state->dbgout) {
1697                 fflush(state->dbgout);
1698         }
1699         if (state->errout) {
1700                 fflush(state->errout);
1701         }
1702 }
1703
1704 static struct compile_state *exit_state;
1705 static void exit_cleanup(void)
1706 {
1707         if (exit_state) {
1708                 do_cleanup(exit_state);
1709         }
1710 }
1711
1712 static int get_col(struct file_state *file)
1713 {
1714         int col;
1715         const char *ptr, *end;
1716         ptr = file->line_start;
1717         end = file->pos;
1718         for(col = 0; ptr < end; ptr++) {
1719                 if (*ptr != '\t') {
1720                         col++;
1721                 } 
1722                 else {
1723                         col = (col & ~7) + 8;
1724                 }
1725         }
1726         return col;
1727 }
1728
1729 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1730 {
1731         int col;
1732         if (triple && triple->occurance) {
1733                 struct occurance *spot;
1734                 for(spot = triple->occurance; spot; spot = spot->parent) {
1735                         fprintf(fp, "%s:%d.%d: ", 
1736                                 spot->filename, spot->line, spot->col);
1737                 }
1738                 return;
1739         }
1740         if (!state->file) {
1741                 return;
1742         }
1743         col = get_col(state->file);
1744         fprintf(fp, "%s:%d.%d: ", 
1745                 state->file->report_name, state->file->report_line, col);
1746 }
1747
1748 static void internal_error(struct compile_state *state, struct triple *ptr, 
1749         const char *fmt, ...)
1750 {
1751         FILE *fp = state->errout;
1752         va_list args;
1753         va_start(args, fmt);
1754         loc(fp, state, ptr);
1755         fputc('\n', fp);
1756         if (ptr) {
1757                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1758         }
1759         fprintf(fp, "Internal compiler error: ");
1760         vfprintf(fp, fmt, args);
1761         fprintf(fp, "\n");
1762         va_end(args);
1763         do_cleanup(state);
1764         abort();
1765 }
1766
1767
1768 static void internal_warning(struct compile_state *state, struct triple *ptr, 
1769         const char *fmt, ...)
1770 {
1771         FILE *fp = state->errout;
1772         va_list args;
1773         va_start(args, fmt);
1774         loc(fp, state, ptr);
1775         if (ptr) {
1776                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1777         }
1778         fprintf(fp, "Internal compiler warning: ");
1779         vfprintf(fp, fmt, args);
1780         fprintf(fp, "\n");
1781         va_end(args);
1782 }
1783
1784
1785
1786 static void error(struct compile_state *state, struct triple *ptr, 
1787         const char *fmt, ...)
1788 {
1789         FILE *fp = state->errout;
1790         va_list args;
1791         va_start(args, fmt);
1792         loc(fp, state, ptr);
1793         fputc('\n', fp);
1794         if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1795                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1796         }
1797         vfprintf(fp, fmt, args);
1798         va_end(args);
1799         fprintf(fp, "\n");
1800         do_cleanup(state);
1801         if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1802                 abort();
1803         }
1804         exit(1);
1805 }
1806
1807 static void warning(struct compile_state *state, struct triple *ptr, 
1808         const char *fmt, ...)
1809 {
1810         FILE *fp = state->errout;
1811         va_list args;
1812         va_start(args, fmt);
1813         loc(fp, state, ptr);
1814         fprintf(fp, "warning: "); 
1815         if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1816                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1817         }
1818         vfprintf(fp, fmt, args);
1819         fprintf(fp, "\n");
1820         va_end(args);
1821 }
1822
1823 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1824
1825 static void valid_op(struct compile_state *state, int op)
1826 {
1827         char *fmt = "invalid op: %d";
1828         if (op >= OP_MAX) {
1829                 internal_error(state, 0, fmt, op);
1830         }
1831         if (op < 0) {
1832                 internal_error(state, 0, fmt, op);
1833         }
1834 }
1835
1836 static void valid_ins(struct compile_state *state, struct triple *ptr)
1837 {
1838         valid_op(state, ptr->op);
1839 }
1840
1841 static void valid_param_count(struct compile_state *state, struct triple *ins)
1842 {
1843         int lhs, rhs, misc, targ;
1844         valid_ins(state, ins);
1845         lhs  = table_ops[ins->op].lhs;
1846         rhs  = table_ops[ins->op].rhs;
1847         misc = table_ops[ins->op].misc;
1848         targ = table_ops[ins->op].targ;
1849
1850         if ((lhs >= 0) && (ins->lhs != lhs)) {
1851                 internal_error(state, ins, "Bad lhs count");
1852         }
1853         if ((rhs >= 0) && (ins->rhs != rhs)) {
1854                 internal_error(state, ins, "Bad rhs count");
1855         }
1856         if ((misc >= 0) && (ins->misc != misc)) {
1857                 internal_error(state, ins, "Bad misc count");
1858         }
1859         if ((targ >= 0) && (ins->targ != targ)) {
1860                 internal_error(state, ins, "Bad targ count");
1861         }
1862 }
1863
1864 static void process_trigraphs(struct compile_state *state)
1865 {
1866         char *src, *dest, *end;
1867         struct file_state *file;
1868         file = state->file;
1869         src = dest = file->buf;
1870         end = file->buf + file->size;
1871         while((end - src) >= 3) {
1872                 if ((src[0] == '?') && (src[1] == '?')) {
1873                         int c = -1;
1874                         switch(src[2]) {
1875                         case '=': c = '#'; break;
1876                         case '/': c = '\\'; break;
1877                         case '\'': c = '^'; break;
1878                         case '(': c = '['; break;
1879                         case ')': c = ']'; break;
1880                         case '!': c = '!'; break;
1881                         case '<': c = '{'; break;
1882                         case '>': c = '}'; break;
1883                         case '-': c = '~'; break;
1884                         }
1885                         if (c != -1) {
1886                                 *dest++ = c;
1887                                 src += 3;
1888                         }
1889                         else {
1890                                 *dest++ = *src++;
1891                         }
1892                 }
1893                 else {
1894                         *dest++ = *src++;
1895                 }
1896         }
1897         while(src != end) {
1898                 *dest++ = *src++;
1899         }
1900         file->size = dest - file->buf;
1901 }
1902
1903 static void splice_lines(struct compile_state *state)
1904 {
1905         char *src, *dest, *end;
1906         struct file_state *file;
1907         file = state->file;
1908         src = dest = file->buf;
1909         end = file->buf + file->size;
1910         while((end - src) >= 2) {
1911                 if ((src[0] == '\\') && (src[1] == '\n')) {
1912                         src += 2;
1913                 }
1914                 else {
1915                         *dest++ = *src++;
1916                 }
1917         }
1918         while(src != end) {
1919                 *dest++ = *src++;
1920         }
1921         file->size = dest - file->buf;
1922 }
1923
1924 static struct type void_type;
1925 static struct type unknown_type;
1926 static void use_triple(struct triple *used, struct triple *user)
1927 {
1928         struct triple_set **ptr, *new;
1929         if (!used)
1930                 return;
1931         if (!user)
1932                 return;
1933         ptr = &used->use;
1934         while(*ptr) {
1935                 if ((*ptr)->member == user) {
1936                         return;
1937                 }
1938                 ptr = &(*ptr)->next;
1939         }
1940         /* Append new to the head of the list, 
1941          * copy_func and rename_block_variables
1942          * depends on this.
1943          */
1944         new = xcmalloc(sizeof(*new), "triple_set");
1945         new->member = user;
1946         new->next   = used->use;
1947         used->use   = new;
1948 }
1949
1950 static void unuse_triple(struct triple *used, struct triple *unuser)
1951 {
1952         struct triple_set *use, **ptr;
1953         if (!used) {
1954                 return;
1955         }
1956         ptr = &used->use;
1957         while(*ptr) {
1958                 use = *ptr;
1959                 if (use->member == unuser) {
1960                         *ptr = use->next;
1961                         xfree(use);
1962                 }
1963                 else {
1964                         ptr = &use->next;
1965                 }
1966         }
1967 }
1968
1969 static void put_occurance(struct occurance *occurance)
1970 {
1971         if (occurance) {
1972                 occurance->count -= 1;
1973                 if (occurance->count <= 0) {
1974                         if (occurance->parent) {
1975                                 put_occurance(occurance->parent);
1976                         }
1977                         xfree(occurance);
1978                 }
1979         }
1980 }
1981
1982 static void get_occurance(struct occurance *occurance)
1983 {
1984         if (occurance) {
1985                 occurance->count += 1;
1986         }
1987 }
1988
1989
1990 static struct occurance *new_occurance(struct compile_state *state)
1991 {
1992         struct occurance *result, *last;
1993         const char *filename;
1994         const char *function;
1995         int line, col;
1996
1997         function = "";
1998         filename = 0;
1999         line = 0;
2000         col  = 0;
2001         if (state->file) {
2002                 filename = state->file->report_name;
2003                 line     = state->file->report_line;
2004                 col      = get_col(state->file);
2005         }
2006         if (state->function) {
2007                 function = state->function;
2008         }
2009         last = state->last_occurance;
2010         if (last &&
2011                 (last->col == col) &&
2012                 (last->line == line) &&
2013                 (last->function == function) &&
2014                 ((last->filename == filename) ||
2015                         (strcmp(last->filename, filename) == 0))) 
2016         {
2017                 get_occurance(last);
2018                 return last;
2019         }
2020         if (last) {
2021                 state->last_occurance = 0;
2022                 put_occurance(last);
2023         }
2024         result = xmalloc(sizeof(*result), "occurance");
2025         result->count    = 2;
2026         result->filename = filename;
2027         result->function = function;
2028         result->line     = line;
2029         result->col      = col;
2030         result->parent   = 0;
2031         state->last_occurance = result;
2032         return result;
2033 }
2034
2035 static struct occurance *inline_occurance(struct compile_state *state,
2036         struct occurance *base, struct occurance *top)
2037 {
2038         struct occurance *result, *last;
2039         if (top->parent) {
2040                 internal_error(state, 0, "inlining an already inlined function?");
2041         }
2042         /* If I have a null base treat it that way */
2043         if ((base->parent == 0) &&
2044                 (base->col == 0) &&
2045                 (base->line == 0) &&
2046                 (base->function[0] == '\0') &&
2047                 (base->filename[0] == '\0')) {
2048                 base = 0;
2049         }
2050         /* See if I can reuse the last occurance I had */
2051         last = state->last_occurance;
2052         if (last &&
2053                 (last->parent   == base) &&
2054                 (last->col      == top->col) &&
2055                 (last->line     == top->line) &&
2056                 (last->function == top->function) &&
2057                 (last->filename == top->filename)) {
2058                 get_occurance(last);
2059                 return last;
2060         }
2061         /* I can't reuse the last occurance so free it */
2062         if (last) {
2063                 state->last_occurance = 0;
2064                 put_occurance(last);
2065         }
2066         /* Generate a new occurance structure */
2067         get_occurance(base);
2068         result = xmalloc(sizeof(*result), "occurance");
2069         result->count    = 2;
2070         result->filename = top->filename;
2071         result->function = top->function;
2072         result->line     = top->line;
2073         result->col      = top->col;
2074         result->parent   = base;
2075         state->last_occurance = result;
2076         return result;
2077 }
2078
2079 static struct occurance dummy_occurance = {
2080         .count    = 2,
2081         .filename = __FILE__,
2082         .function = "",
2083         .line     = __LINE__,
2084         .col      = 0,
2085         .parent   = 0,
2086 };
2087
2088 /* The undef triple is used as a place holder when we are removing pointers
2089  * from a triple.  Having allows certain sanity checks to pass even
2090  * when the original triple that was pointed to is gone.
2091  */
2092 static struct triple unknown_triple = {
2093         .next      = &unknown_triple,
2094         .prev      = &unknown_triple,
2095         .use       = 0,
2096         .op        = OP_UNKNOWNVAL,
2097         .lhs       = 0,
2098         .rhs       = 0,
2099         .misc      = 0,
2100         .targ      = 0,
2101         .type      = &unknown_type,
2102         .id        = -1, /* An invalid id */
2103         .u = { .cval = 0, },
2104         .occurance = &dummy_occurance,
2105         .param = { [0] = 0, [1] = 0, },
2106 };
2107
2108
2109 static size_t registers_of(struct compile_state *state, struct type *type);
2110
2111 static struct triple *alloc_triple(struct compile_state *state, 
2112         int op, struct type *type, int lhs_wanted, int rhs_wanted,
2113         struct occurance *occurance)
2114 {
2115         size_t size, extra_count, min_count;
2116         int lhs, rhs, misc, targ;
2117         struct triple *ret, dummy;
2118         dummy.op = op;
2119         dummy.occurance = occurance;
2120         valid_op(state, op);
2121         lhs = table_ops[op].lhs;
2122         rhs = table_ops[op].rhs;
2123         misc = table_ops[op].misc;
2124         targ = table_ops[op].targ;
2125
2126         switch(op) {
2127         case OP_FCALL:
2128                 rhs = rhs_wanted;
2129                 break;
2130         case OP_PHI:
2131                 rhs = rhs_wanted;
2132                 break;
2133         case OP_ADECL:
2134                 lhs = registers_of(state, type);
2135                 break;
2136         case OP_TUPLE:
2137                 lhs = registers_of(state, type);
2138                 break;
2139         case OP_ASM:
2140                 rhs = rhs_wanted;
2141                 lhs = lhs_wanted;
2142                 break;
2143         }
2144         if ((rhs < 0) || (rhs > MAX_RHS)) {
2145                 internal_error(state, &dummy, "bad rhs count %d", rhs);
2146         }
2147         if ((lhs < 0) || (lhs > MAX_LHS)) {
2148                 internal_error(state, &dummy, "bad lhs count %d", lhs);
2149         }
2150         if ((misc < 0) || (misc > MAX_MISC)) {
2151                 internal_error(state, &dummy, "bad misc count %d", misc);
2152         }
2153         if ((targ < 0) || (targ > MAX_TARG)) {
2154                 internal_error(state, &dummy, "bad targs count %d", targ);
2155         }
2156
2157         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2158         extra_count = lhs + rhs + misc + targ;
2159         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2160
2161         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2162         ret = xcmalloc(size, "tripple");
2163         ret->op        = op;
2164         ret->lhs       = lhs;
2165         ret->rhs       = rhs;
2166         ret->misc      = misc;
2167         ret->targ      = targ;
2168         ret->type      = type;
2169         ret->next      = ret;
2170         ret->prev      = ret;
2171         ret->occurance = occurance;
2172         /* A simple sanity check */
2173         if ((ret->op != op) ||
2174                 (ret->lhs != lhs) ||
2175                 (ret->rhs != rhs) ||
2176                 (ret->misc != misc) ||
2177                 (ret->targ != targ) ||
2178                 (ret->type != type) ||
2179                 (ret->next != ret) ||
2180                 (ret->prev != ret) ||
2181                 (ret->occurance != occurance)) {
2182                 internal_error(state, ret, "huh?");
2183         }
2184         return ret;
2185 }
2186
2187 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2188 {
2189         struct triple *dup;
2190         int src_lhs, src_rhs, src_size;
2191         src_lhs = src->lhs;
2192         src_rhs = src->rhs;
2193         src_size = TRIPLE_SIZE(src);
2194         get_occurance(src->occurance);
2195         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2196                 src->occurance);
2197         memcpy(dup, src, sizeof(*src));
2198         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2199         return dup;
2200 }
2201
2202 static struct triple *new_triple(struct compile_state *state, 
2203         int op, struct type *type, int lhs, int rhs)
2204 {
2205         struct triple *ret;
2206         struct occurance *occurance;
2207         occurance = new_occurance(state);
2208         ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2209         return ret;
2210 }
2211
2212 static struct triple *build_triple(struct compile_state *state, 
2213         int op, struct type *type, struct triple *left, struct triple *right,
2214         struct occurance *occurance)
2215 {
2216         struct triple *ret;
2217         size_t count;
2218         ret = alloc_triple(state, op, type, -1, -1, occurance);
2219         count = TRIPLE_SIZE(ret);
2220         if (count > 0) {
2221                 ret->param[0] = left;
2222         }
2223         if (count > 1) {
2224                 ret->param[1] = right;
2225         }
2226         return ret;
2227 }
2228
2229 static struct triple *triple(struct compile_state *state, 
2230         int op, struct type *type, struct triple *left, struct triple *right)
2231 {
2232         struct triple *ret;
2233         size_t count;
2234         ret = new_triple(state, op, type, -1, -1);
2235         count = TRIPLE_SIZE(ret);
2236         if (count >= 1) {
2237                 ret->param[0] = left;
2238         }
2239         if (count >= 2) {
2240                 ret->param[1] = right;
2241         }
2242         return ret;
2243 }
2244
2245 static struct triple *branch(struct compile_state *state, 
2246         struct triple *targ, struct triple *test)
2247 {
2248         struct triple *ret;
2249         if (test) {
2250                 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2251                 RHS(ret, 0) = test;
2252         } else {
2253                 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2254         }
2255         TARG(ret, 0) = targ;
2256         /* record the branch target was used */
2257         if (!targ || (targ->op != OP_LABEL)) {
2258                 internal_error(state, 0, "branch not to label");
2259         }
2260         return ret;
2261 }
2262
2263 static int triple_is_label(struct compile_state *state, struct triple *ins);
2264 static int triple_is_call(struct compile_state *state, struct triple *ins);
2265 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2266 static void insert_triple(struct compile_state *state,
2267         struct triple *first, struct triple *ptr)
2268 {
2269         if (ptr) {
2270                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2271                         internal_error(state, ptr, "expression already used");
2272                 }
2273                 ptr->next       = first;
2274                 ptr->prev       = first->prev;
2275                 ptr->prev->next = ptr;
2276                 ptr->next->prev = ptr;
2277
2278                 if (triple_is_cbranch(state, ptr->prev) ||
2279                         triple_is_call(state, ptr->prev)) {
2280                         unuse_triple(first, ptr->prev);
2281                         use_triple(ptr, ptr->prev);
2282                 }
2283         }
2284 }
2285
2286 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2287 {
2288         /* This function is used to determine if u.block 
2289          * is utilized to store the current block number.
2290          */
2291         int stores_block;
2292         valid_ins(state, ins);
2293         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2294         return stores_block;
2295 }
2296
2297 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2298 static struct block *block_of_triple(struct compile_state *state, 
2299         struct triple *ins)
2300 {
2301         struct triple *first;
2302         if (!ins || ins == &unknown_triple) {
2303                 return 0;
2304         }
2305         first = state->first;
2306         while(ins != first && !triple_is_branch(state, ins->prev) &&
2307                 !triple_stores_block(state, ins)) 
2308         { 
2309                 if (ins == ins->prev) {
2310                         internal_error(state, ins, "ins == ins->prev?");
2311                 }
2312                 ins = ins->prev;
2313         }
2314         return triple_stores_block(state, ins)? ins->u.block: 0;
2315 }
2316
2317 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2318 static struct triple *pre_triple(struct compile_state *state,
2319         struct triple *base,
2320         int op, struct type *type, struct triple *left, struct triple *right)
2321 {
2322         struct block *block;
2323         struct triple *ret;
2324         int i;
2325         /* If I am an OP_PIECE jump to the real instruction */
2326         if (base->op == OP_PIECE) {
2327                 base = MISC(base, 0);
2328         }
2329         block = block_of_triple(state, base);
2330         get_occurance(base->occurance);
2331         ret = build_triple(state, op, type, left, right, base->occurance);
2332         generate_lhs_pieces(state, ret);
2333         if (triple_stores_block(state, ret)) {
2334                 ret->u.block = block;
2335         }
2336         insert_triple(state, base, ret);
2337         for(i = 0; i < ret->lhs; i++) {
2338                 struct triple *piece;
2339                 piece = LHS(ret, i);
2340                 insert_triple(state, base, piece);
2341                 use_triple(ret, piece);
2342                 use_triple(piece, ret);
2343         }
2344         if (block && (block->first == base)) {
2345                 block->first = ret;
2346         }
2347         return ret;
2348 }
2349
2350 static struct triple *post_triple(struct compile_state *state,
2351         struct triple *base,
2352         int op, struct type *type, struct triple *left, struct triple *right)
2353 {
2354         struct block *block;
2355         struct triple *ret, *next;
2356         int zlhs, i;
2357         /* If I am an OP_PIECE jump to the real instruction */
2358         if (base->op == OP_PIECE) {
2359                 base = MISC(base, 0);
2360         }
2361         /* If I have a left hand side skip over it */
2362         zlhs = base->lhs;
2363         if (zlhs) {
2364                 base = LHS(base, zlhs - 1);
2365         }
2366
2367         block = block_of_triple(state, base);
2368         get_occurance(base->occurance);
2369         ret = build_triple(state, op, type, left, right, base->occurance);
2370         generate_lhs_pieces(state, ret);
2371         if (triple_stores_block(state, ret)) {
2372                 ret->u.block = block;
2373         }
2374         next = base->next;
2375         insert_triple(state, next, ret);
2376         zlhs = ret->lhs;
2377         for(i = 0; i < zlhs; i++) {
2378                 struct triple *piece;
2379                 piece = LHS(ret, i);
2380                 insert_triple(state, next, piece);
2381                 use_triple(ret, piece);
2382                 use_triple(piece, ret);
2383         }
2384         if (block && (block->last == base)) {
2385                 block->last = ret;
2386                 if (zlhs) {
2387                         block->last = LHS(ret, zlhs - 1);
2388                 }
2389         }
2390         return ret;
2391 }
2392
2393 static struct type *reg_type(
2394         struct compile_state *state, struct type *type, int reg);
2395
2396 static void generate_lhs_piece(
2397         struct compile_state *state, struct triple *ins, int index)
2398 {
2399         struct type *piece_type;
2400         struct triple *piece;
2401         get_occurance(ins->occurance);
2402         piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2403
2404         if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2405                 piece_type = piece_type->left;
2406         }
2407 #if 0
2408 {
2409         static void name_of(FILE *fp, struct type *type);
2410         FILE * fp = state->errout;
2411         fprintf(fp, "piece_type(%d): ", index);
2412         name_of(fp, piece_type);
2413         fprintf(fp, "\n");
2414 }
2415 #endif
2416         piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2417         piece->u.cval  = index;
2418         LHS(ins, piece->u.cval) = piece;
2419         MISC(piece, 0) = ins;
2420 }
2421
2422 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2423 {
2424         int i, zlhs;
2425         zlhs = ins->lhs;
2426         for(i = 0; i < zlhs; i++) {
2427                 generate_lhs_piece(state, ins, i);
2428         }
2429 }
2430
2431 static struct triple *label(struct compile_state *state)
2432 {
2433         /* Labels don't get a type */
2434         struct triple *result;
2435         result = triple(state, OP_LABEL, &void_type, 0, 0);
2436         return result;
2437 }
2438
2439 static struct triple *mkprog(struct compile_state *state, ...)
2440 {
2441         struct triple *prog, *head, *arg;
2442         va_list args;
2443         int i;
2444
2445         head = label(state);
2446         prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2447         RHS(prog, 0) = head;
2448         va_start(args, state);
2449         i = 0;
2450         while((arg = va_arg(args, struct triple *)) != 0) {
2451                 if (++i >= 100) {
2452                         internal_error(state, 0, "too many arguments to mkprog");
2453                 }
2454                 flatten(state, head, arg);
2455         }
2456         va_end(args);
2457         prog->type = head->prev->type;
2458         return prog;
2459 }
2460 static void name_of(FILE *fp, struct type *type);
2461 static void display_triple(FILE *fp, struct triple *ins)
2462 {
2463         struct occurance *ptr;
2464         const char *reg;
2465         char pre, post, vol;
2466         pre = post = vol = ' ';
2467         if (ins) {
2468                 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2469                         pre = '^';
2470                 }
2471                 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2472                         post = ',';
2473                 }
2474                 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2475                         vol = 'v';
2476                 }
2477                 reg = arch_reg_str(ID_REG(ins->id));
2478         }
2479         if (ins == 0) {
2480                 fprintf(fp, "(%p) <nothing> ", ins);
2481         }
2482         else if (ins->op == OP_INTCONST) {
2483                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx>         ",
2484                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op), 
2485                         (unsigned long)(ins->u.cval));
2486         }
2487         else if (ins->op == OP_ADDRCONST) {
2488                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2489                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op), 
2490                         MISC(ins, 0), (unsigned long)(ins->u.cval));
2491         }
2492         else if (ins->op == OP_INDEX) {
2493                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2494                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op), 
2495                         RHS(ins, 0), (unsigned long)(ins->u.cval));
2496         }
2497         else if (ins->op == OP_PIECE) {
2498                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2499                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op), 
2500                         MISC(ins, 0), (unsigned long)(ins->u.cval));
2501         }
2502         else {
2503                 int i, count;
2504                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s", 
2505                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2506                 if (table_ops[ins->op].flags & BITFIELD) {
2507                         fprintf(fp, " <%2d-%2d:%2d>", 
2508                                 ins->u.bitfield.offset,
2509                                 ins->u.bitfield.offset + ins->u.bitfield.size,
2510                                 ins->u.bitfield.size);
2511                 }
2512                 count = TRIPLE_SIZE(ins);
2513                 for(i = 0; i < count; i++) {
2514                         fprintf(fp, " %-10p", ins->param[i]);
2515                 }
2516                 for(; i < 2; i++) {
2517                         fprintf(fp, "           ");
2518                 }
2519         }
2520         if (ins) {
2521                 struct triple_set *user;
2522 #if DEBUG_DISPLAY_TYPES
2523                 fprintf(fp, " <");
2524                 name_of(fp, ins->type);
2525                 fprintf(fp, "> ");
2526 #endif
2527 #if DEBUG_DISPLAY_USES
2528                 fprintf(fp, " [");
2529                 for(user = ins->use; user; user = user->next) {
2530                         fprintf(fp, " %-10p", user->member);
2531                 }
2532                 fprintf(fp, " ]");
2533 #endif
2534                 fprintf(fp, " @");
2535                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2536                         fprintf(fp, " %s,%s:%d.%d",
2537                                 ptr->function, 
2538                                 ptr->filename,
2539                                 ptr->line, 
2540                                 ptr->col);
2541                 }
2542                 if (ins->op == OP_ASM) {
2543                         fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2544                 }
2545         }
2546         fprintf(fp, "\n");
2547         fflush(fp);
2548 }
2549
2550 static int equiv_types(struct type *left, struct type *right);
2551 static void display_triple_changes(
2552         FILE *fp, const struct triple *new, const struct triple *orig)
2553 {
2554
2555         int new_count, orig_count;
2556         new_count = TRIPLE_SIZE(new);
2557         orig_count = TRIPLE_SIZE(orig);
2558         if ((new->op != orig->op) ||
2559                 (new_count != orig_count) ||
2560                 (memcmp(orig->param, new->param,        
2561                         orig_count * sizeof(orig->param[0])) != 0) ||
2562                 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0)) 
2563         {
2564                 struct occurance *ptr;
2565                 int i, min_count, indent;
2566                 fprintf(fp, "(%p %p)", new, orig);
2567                 if (orig->op == new->op) {
2568                         fprintf(fp, " %-11s", tops(orig->op));
2569                 } else {
2570                         fprintf(fp, " [%-10s %-10s]", 
2571                                 tops(new->op), tops(orig->op));
2572                 }
2573                 min_count = new_count;
2574                 if (min_count > orig_count) {
2575                         min_count = orig_count;
2576                 }
2577                 for(indent = i = 0; i < min_count; i++) {
2578                         if (orig->param[i] == new->param[i]) {
2579                                 fprintf(fp, " %-11p", 
2580                                         orig->param[i]);
2581                                 indent += 12;
2582                         } else {
2583                                 fprintf(fp, " [%-10p %-10p]",
2584                                         new->param[i], 
2585                                         orig->param[i]);
2586                                 indent += 24;
2587                         }
2588                 }
2589                 for(; i < orig_count; i++) {
2590                         fprintf(fp, " [%-9p]", orig->param[i]);
2591                         indent += 12;
2592                 }
2593                 for(; i < new_count; i++) {
2594                         fprintf(fp, " [%-9p]", new->param[i]);
2595                         indent += 12;
2596                 }
2597                 if ((new->op == OP_INTCONST)||
2598                         (new->op == OP_ADDRCONST)) {
2599                         fprintf(fp, " <0x%08lx>", 
2600                                 (unsigned long)(new->u.cval));
2601                         indent += 13;
2602                 }
2603                 for(;indent < 36; indent++) {
2604                         putc(' ', fp);
2605                 }
2606
2607 #if DEBUG_DISPLAY_TYPES
2608                 fprintf(fp, " <");
2609                 name_of(fp, new->type);
2610                 if (!equiv_types(new->type, orig->type)) {
2611                         fprintf(fp, " -- ");
2612                         name_of(fp, orig->type);
2613                 }
2614                 fprintf(fp, "> ");
2615 #endif
2616
2617                 fprintf(fp, " @");
2618                 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2619                         fprintf(fp, " %s,%s:%d.%d",
2620                                 ptr->function, 
2621                                 ptr->filename,
2622                                 ptr->line, 
2623                                 ptr->col);
2624                         
2625                 }
2626                 fprintf(fp, "\n");
2627                 fflush(fp);
2628         }
2629 }
2630
2631 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2632 {
2633         /* Does the triple have no side effects.
2634          * I.e. Rexecuting the triple with the same arguments 
2635          * gives the same value.
2636          */
2637         unsigned pure;
2638         valid_ins(state, ins);
2639         pure = PURE_BITS(table_ops[ins->op].flags);
2640         if ((pure != PURE) && (pure != IMPURE)) {
2641                 internal_error(state, 0, "Purity of %s not known",
2642                         tops(ins->op));
2643         }
2644         return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2645 }
2646
2647 static int triple_is_branch_type(struct compile_state *state, 
2648         struct triple *ins, unsigned type)
2649 {
2650         /* Is this one of the passed branch types? */
2651         valid_ins(state, ins);
2652         return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2653 }
2654
2655 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2656 {
2657         /* Is this triple a branch instruction? */
2658         valid_ins(state, ins);
2659         return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2660 }
2661
2662 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2663 {
2664         /* Is this triple a conditional branch instruction? */
2665         return triple_is_branch_type(state, ins, CBRANCH);
2666 }
2667
2668 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2669 {
2670         /* Is this triple a unconditional branch instruction? */
2671         unsigned type;
2672         valid_ins(state, ins);
2673         type = BRANCH_BITS(table_ops[ins->op].flags);
2674         return (type != 0) && (type != CBRANCH);
2675 }
2676
2677 static int triple_is_call(struct compile_state *state, struct triple *ins)
2678 {
2679         /* Is this triple a call instruction? */
2680         return triple_is_branch_type(state, ins, CALLBRANCH);
2681 }
2682
2683 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2684 {
2685         /* Is this triple a return instruction? */
2686         return triple_is_branch_type(state, ins, RETBRANCH);
2687 }
2688
2689 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2690 {
2691         /* Is this triple an unconditional branch and not a call or a
2692          * return? */
2693         return triple_is_branch_type(state, ins, UBRANCH);
2694 }
2695
2696 static int triple_is_end(struct compile_state *state, struct triple *ins)
2697 {
2698         return triple_is_branch_type(state, ins, ENDBRANCH);
2699 }
2700
2701 static int triple_is_label(struct compile_state *state, struct triple *ins)
2702 {
2703         valid_ins(state, ins);
2704         return (ins->op == OP_LABEL);
2705 }
2706
2707 static struct triple *triple_to_block_start(
2708         struct compile_state *state, struct triple *start)
2709 {
2710         while(!triple_is_branch(state, start->prev) &&
2711                 (!triple_is_label(state, start) || !start->use)) {
2712                 start = start->prev;
2713         }
2714         return start;
2715 }
2716
2717 static int triple_is_def(struct compile_state *state, struct triple *ins)
2718 {
2719         /* This function is used to determine which triples need
2720          * a register.
2721          */
2722         int is_def;
2723         valid_ins(state, ins);
2724         is_def = (table_ops[ins->op].flags & DEF) == DEF;
2725         if (ins->lhs >= 1) {
2726                 is_def = 0;
2727         }
2728         return is_def;
2729 }
2730
2731 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2732 {
2733         int is_structural;
2734         valid_ins(state, ins);
2735         is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2736         return is_structural;
2737 }
2738
2739 static int triple_is_part(struct compile_state *state, struct triple *ins)
2740 {
2741         int is_part;
2742         valid_ins(state, ins);
2743         is_part = (table_ops[ins->op].flags & PART) == PART;
2744         return is_part;
2745 }
2746
2747 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2748 {
2749         return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2750 }
2751
2752 static struct triple **triple_iter(struct compile_state *state,
2753         size_t count, struct triple **vector,
2754         struct triple *ins, struct triple **last)
2755 {
2756         struct triple **ret;
2757         ret = 0;
2758         if (count) {
2759                 if (!last) {
2760                         ret = vector;
2761                 }
2762                 else if ((last >= vector) && (last < (vector + count - 1))) {
2763                         ret = last + 1;
2764                 }
2765         }
2766         return ret;
2767         
2768 }
2769
2770 static struct triple **triple_lhs(struct compile_state *state,
2771         struct triple *ins, struct triple **last)
2772 {
2773         return triple_iter(state, ins->lhs, &LHS(ins,0), 
2774                 ins, last);
2775 }
2776
2777 static struct triple **triple_rhs(struct compile_state *state,
2778         struct triple *ins, struct triple **last)
2779 {
2780         return triple_iter(state, ins->rhs, &RHS(ins,0), 
2781                 ins, last);
2782 }
2783
2784 static struct triple **triple_misc(struct compile_state *state,
2785         struct triple *ins, struct triple **last)
2786 {
2787         return triple_iter(state, ins->misc, &MISC(ins,0), 
2788                 ins, last);
2789 }
2790
2791 static struct triple **do_triple_targ(struct compile_state *state,
2792         struct triple *ins, struct triple **last, int call_edges, int next_edges)
2793 {
2794         size_t count;
2795         struct triple **ret, **vector;
2796         int next_is_targ;
2797         ret = 0;
2798         count = ins->targ;
2799         next_is_targ = 0;
2800         if (triple_is_cbranch(state, ins)) {
2801                 next_is_targ = 1;
2802         }
2803         if (!call_edges && triple_is_call(state, ins)) {
2804                 count = 0;
2805         }
2806         if (next_edges && triple_is_call(state, ins)) {
2807                 next_is_targ = 1;
2808         }
2809         vector = &TARG(ins, 0);
2810         if (!ret && next_is_targ) {
2811                 if (!last) {
2812                         ret = &ins->next;
2813                 } else if (last == &ins->next) {
2814                         last = 0;
2815                 }
2816         }
2817         if (!ret && count) {
2818                 if (!last) {
2819                         ret = vector;
2820                 }
2821                 else if ((last >= vector) && (last < (vector + count - 1))) {
2822                         ret = last + 1;
2823                 }
2824                 else if (last == vector + count - 1) {
2825                         last = 0;
2826                 }
2827         }
2828         if (!ret && triple_is_ret(state, ins) && call_edges) {
2829                 struct triple_set *use;
2830                 for(use = ins->use; use; use = use->next) {
2831                         if (!triple_is_call(state, use->member)) {
2832                                 continue;
2833                         }
2834                         if (!last) {
2835                                 ret = &use->member->next;
2836                                 break;
2837                         }
2838                         else if (last == &use->member->next) {
2839                                 last = 0;
2840                         }
2841                 }
2842         }
2843         return ret;
2844 }
2845
2846 static struct triple **triple_targ(struct compile_state *state,
2847         struct triple *ins, struct triple **last)
2848 {
2849         return do_triple_targ(state, ins, last, 1, 1);
2850 }
2851
2852 static struct triple **triple_edge_targ(struct compile_state *state,
2853         struct triple *ins, struct triple **last)
2854 {
2855         return do_triple_targ(state, ins, last, 
2856                 state->functions_joined, !state->functions_joined);
2857 }
2858
2859 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2860 {
2861         struct triple *next;
2862         int lhs, i;
2863         lhs = ins->lhs;
2864         next = ins->next;
2865         for(i = 0; i < lhs; i++) {
2866                 struct triple *piece;
2867                 piece = LHS(ins, i);
2868                 if (next != piece) {
2869                         internal_error(state, ins, "malformed lhs on %s",
2870                                 tops(ins->op));
2871                 }
2872                 if (next->op != OP_PIECE) {
2873                         internal_error(state, ins, "bad lhs op %s at %d on %s",
2874                                 tops(next->op), i, tops(ins->op));
2875                 }
2876                 if (next->u.cval != i) {
2877                         internal_error(state, ins, "bad u.cval of %d %d expected",
2878                                 next->u.cval, i);
2879                 }
2880                 next = next->next;
2881         }
2882         return next;
2883 }
2884
2885 /* Function piece accessor functions */
2886 static struct triple *do_farg(struct compile_state *state, 
2887         struct triple *func, unsigned index)
2888 {
2889         struct type *ftype;
2890         struct triple *first, *arg;
2891         unsigned i;
2892
2893         ftype = func->type;
2894         if((index < 0) || (index >= (ftype->elements + 2))) {
2895                 internal_error(state, func, "bad argument index: %d", index);
2896         }
2897         first = RHS(func, 0);
2898         arg = first->next;
2899         for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2900                 /* do nothing */
2901         }
2902         if (arg->op != OP_ADECL) {
2903                 internal_error(state, 0, "arg not adecl?");
2904         }
2905         return arg;
2906 }
2907 static struct triple *fresult(struct compile_state *state, struct triple *func)
2908 {
2909         return do_farg(state, func, 0);
2910 }
2911 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2912 {
2913         return do_farg(state, func, 1);
2914 }
2915 static struct triple *farg(struct compile_state *state, 
2916         struct triple *func, unsigned index)
2917 {
2918         return do_farg(state, func, index + 2);
2919 }
2920
2921
2922 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2923 {
2924         struct triple *first, *ins;
2925         fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2926         first = ins = RHS(func, 0);
2927         do {
2928                 if (triple_is_label(state, ins) && ins->use) {
2929                         fprintf(fp, "%p:\n", ins);
2930                 }
2931                 display_triple(fp, ins);
2932
2933                 if (triple_is_branch(state, ins)) {
2934                         fprintf(fp, "\n");
2935                 }
2936                 if (ins->next->prev != ins) {
2937                         internal_error(state, ins->next, "bad prev");
2938                 }
2939                 ins = ins->next;
2940         } while(ins != first);
2941 }
2942
2943 static void verify_use(struct compile_state *state,
2944         struct triple *user, struct triple *used)
2945 {
2946         int size, i;
2947         size = TRIPLE_SIZE(user);
2948         for(i = 0; i < size; i++) {
2949                 if (user->param[i] == used) {
2950                         break;
2951                 }
2952         }
2953         if (triple_is_branch(state, user)) {
2954                 if (user->next == used) {
2955                         i = -1;
2956                 }
2957         }
2958         if (i == size) {
2959                 internal_error(state, user, "%s(%p) does not use %s(%p)",
2960                         tops(user->op), user, tops(used->op), used);
2961         }
2962 }
2963
2964 static int find_rhs_use(struct compile_state *state, 
2965         struct triple *user, struct triple *used)
2966 {
2967         struct triple **param;
2968         int size, i;
2969         verify_use(state, user, used);
2970 #warning "AUDIT ME ->rhs"
2971         size = user->rhs;
2972         param = &RHS(user, 0);
2973         for(i = 0; i < size; i++) {
2974                 if (param[i] == used) {
2975                         return i;
2976                 }
2977         }
2978         return -1;
2979 }
2980
2981 static void free_triple(struct compile_state *state, struct triple *ptr)
2982 {
2983         size_t size;
2984         size = sizeof(*ptr) - sizeof(ptr->param) +
2985                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2986         ptr->prev->next = ptr->next;
2987         ptr->next->prev = ptr->prev;
2988         if (ptr->use) {
2989                 internal_error(state, ptr, "ptr->use != 0");
2990         }
2991         put_occurance(ptr->occurance);
2992         memset(ptr, -1, size);
2993         xfree(ptr);
2994 }
2995
2996 static void release_triple(struct compile_state *state, struct triple *ptr)
2997 {
2998         struct triple_set *set, *next;
2999         struct triple **expr;
3000         struct block *block;
3001         if (ptr == &unknown_triple) {
3002                 return;
3003         }
3004         valid_ins(state, ptr);
3005         /* Make certain the we are not the first or last element of a block */
3006         block = block_of_triple(state, ptr);
3007         if (block) {
3008                 if ((block->last == ptr) && (block->first == ptr)) {
3009                         block->last = block->first = 0;
3010                 }
3011                 else if (block->last == ptr) {
3012                         block->last = ptr->prev;
3013                 }
3014                 else if (block->first == ptr) {
3015                         block->first = ptr->next;
3016                 }
3017         }
3018         /* Remove ptr from use chains where it is the user */
3019         expr = triple_rhs(state, ptr, 0);
3020         for(; expr; expr = triple_rhs(state, ptr, expr)) {
3021                 if (*expr) {
3022                         unuse_triple(*expr, ptr);
3023                 }
3024         }
3025         expr = triple_lhs(state, ptr, 0);
3026         for(; expr; expr = triple_lhs(state, ptr, expr)) {
3027                 if (*expr) {
3028                         unuse_triple(*expr, ptr);
3029                 }
3030         }
3031         expr = triple_misc(state, ptr, 0);
3032         for(; expr; expr = triple_misc(state, ptr, expr)) {
3033                 if (*expr) {
3034                         unuse_triple(*expr, ptr);
3035                 }
3036         }
3037         expr = triple_targ(state, ptr, 0);
3038         for(; expr; expr = triple_targ(state, ptr, expr)) {
3039                 if (*expr){
3040                         unuse_triple(*expr, ptr);
3041                 }
3042         }
3043         /* Reomve ptr from use chains where it is used */
3044         for(set = ptr->use; set; set = next) {
3045                 next = set->next;
3046                 valid_ins(state, set->member);
3047                 expr = triple_rhs(state, set->member, 0);
3048                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3049                         if (*expr == ptr) {
3050                                 *expr = &unknown_triple;
3051                         }
3052                 }
3053                 expr = triple_lhs(state, set->member, 0);
3054                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3055                         if (*expr == ptr) {
3056                                 *expr = &unknown_triple;
3057                         }
3058                 }
3059                 expr = triple_misc(state, set->member, 0);
3060                 for(; expr; expr = triple_misc(state, set->member, expr)) {
3061                         if (*expr == ptr) {
3062                                 *expr = &unknown_triple;
3063                         }
3064                 }
3065                 expr = triple_targ(state, set->member, 0);
3066                 for(; expr; expr = triple_targ(state, set->member, expr)) {
3067                         if (*expr == ptr) {
3068                                 *expr = &unknown_triple;
3069                         }
3070                 }
3071                 unuse_triple(ptr, set->member);
3072         }
3073         free_triple(state, ptr);
3074 }
3075
3076 static void print_triples(struct compile_state *state);
3077 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3078
3079 #define TOK_UNKNOWN     0
3080 #define TOK_SPACE       1
3081 #define TOK_SEMI        2
3082 #define TOK_LBRACE      3
3083 #define TOK_RBRACE      4
3084 #define TOK_COMMA       5
3085 #define TOK_EQ          6
3086 #define TOK_COLON       7
3087 #define TOK_LBRACKET    8
3088 #define TOK_RBRACKET    9
3089 #define TOK_LPAREN      10
3090 #define TOK_RPAREN      11
3091 #define TOK_STAR        12
3092 #define TOK_DOTS        13
3093 #define TOK_MORE        14
3094 #define TOK_LESS        15
3095 #define TOK_TIMESEQ     16
3096 #define TOK_DIVEQ       17
3097 #define TOK_MODEQ       18
3098 #define TOK_PLUSEQ      19
3099 #define TOK_MINUSEQ     20
3100 #define TOK_SLEQ        21
3101 #define TOK_SREQ        22
3102 #define TOK_ANDEQ       23
3103 #define TOK_XOREQ       24
3104 #define TOK_OREQ        25
3105 #define TOK_EQEQ        26
3106 #define TOK_NOTEQ       27
3107 #define TOK_QUEST       28
3108 #define TOK_LOGOR       29
3109 #define TOK_LOGAND      30
3110 #define TOK_OR          31
3111 #define TOK_AND         32
3112 #define TOK_XOR         33
3113 #define TOK_LESSEQ      34
3114 #define TOK_MOREEQ      35
3115 #define TOK_SL          36
3116 #define TOK_SR          37
3117 #define TOK_PLUS        38
3118 #define TOK_MINUS       39
3119 #define TOK_DIV         40
3120 #define TOK_MOD         41
3121 #define TOK_PLUSPLUS    42
3122 #define TOK_MINUSMINUS  43
3123 #define TOK_BANG        44
3124 #define TOK_ARROW       45
3125 #define TOK_DOT         46
3126 #define TOK_TILDE       47
3127 #define TOK_LIT_STRING  48
3128 #define TOK_LIT_CHAR    49
3129 #define TOK_LIT_INT     50
3130 #define TOK_LIT_FLOAT   51
3131 #define TOK_MACRO       52
3132 #define TOK_CONCATENATE 53
3133
3134 #define TOK_IDENT       54
3135 #define TOK_STRUCT_NAME 55
3136 #define TOK_ENUM_CONST  56
3137 #define TOK_TYPE_NAME   57
3138
3139 #define TOK_AUTO        58
3140 #define TOK_BREAK       59
3141 #define TOK_CASE        60
3142 #define TOK_CHAR        61
3143 #define TOK_CONST       62
3144 #define TOK_CONTINUE    63
3145 #define TOK_DEFAULT     64
3146 #define TOK_DO          65
3147 #define TOK_DOUBLE      66
3148 #define TOK_ELSE        67
3149 #define TOK_ENUM        68
3150 #define TOK_EXTERN      69
3151 #define TOK_FLOAT       70
3152 #define TOK_FOR         71
3153 #define TOK_GOTO        72
3154 #define TOK_IF          73
3155 #define TOK_INLINE      74
3156 #define TOK_INT         75
3157 #define TOK_LONG        76
3158 #define TOK_REGISTER    77
3159 #define TOK_RESTRICT    78
3160 #define TOK_RETURN      79
3161 #define TOK_SHORT       80
3162 #define TOK_SIGNED      81
3163 #define TOK_SIZEOF      82
3164 #define TOK_STATIC      83
3165 #define TOK_STRUCT      84
3166 #define TOK_SWITCH      85
3167 #define TOK_TYPEDEF     86
3168 #define TOK_UNION       87
3169 #define TOK_UNSIGNED    88
3170 #define TOK_VOID        89
3171 #define TOK_VOLATILE    90
3172 #define TOK_WHILE       91
3173 #define TOK_ASM         92
3174 #define TOK_ATTRIBUTE   93
3175 #define TOK_ALIGNOF     94
3176 #define TOK_FIRST_KEYWORD TOK_AUTO
3177 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
3178
3179 #define TOK_DEFINE      100
3180 #define TOK_UNDEF       101
3181 #define TOK_INCLUDE     102
3182 #define TOK_LINE        103
3183 #define TOK_ERROR       104
3184 #define TOK_WARNING     105
3185 #define TOK_PRAGMA      106
3186 #define TOK_IFDEF       107
3187 #define TOK_IFNDEF      108
3188 #define TOK_ELIF        109
3189 #define TOK_ENDIF       110
3190
3191 #define TOK_FIRST_MACRO TOK_DEFINE
3192 #define TOK_LAST_MACRO  TOK_ENDIF
3193          
3194 #define TOK_DEFINED     111
3195 #define TOK_EOF         112
3196
3197 static const char *tokens[] = {
3198 [TOK_UNKNOWN     ] = "unknown",
3199 [TOK_SPACE       ] = ":space:",
3200 [TOK_SEMI        ] = ";",
3201 [TOK_LBRACE      ] = "{",
3202 [TOK_RBRACE      ] = "}",
3203 [TOK_COMMA       ] = ",",
3204 [TOK_EQ          ] = "=",
3205 [TOK_COLON       ] = ":",
3206 [TOK_LBRACKET    ] = "[",
3207 [TOK_RBRACKET    ] = "]",
3208 [TOK_LPAREN      ] = "(",
3209 [TOK_RPAREN      ] = ")",
3210 [TOK_STAR        ] = "*",
3211 [TOK_DOTS        ] = "...",
3212 [TOK_MORE        ] = ">",
3213 [TOK_LESS        ] = "<",
3214 [TOK_TIMESEQ     ] = "*=",
3215 [TOK_DIVEQ       ] = "/=",
3216 [TOK_MODEQ       ] = "%=",
3217 [TOK_PLUSEQ      ] = "+=",
3218 [TOK_MINUSEQ     ] = "-=",
3219 [TOK_SLEQ        ] = "<<=",
3220 [TOK_SREQ        ] = ">>=",
3221 [TOK_ANDEQ       ] = "&=",
3222 [TOK_XOREQ       ] = "^=",
3223 [TOK_OREQ        ] = "|=",
3224 [TOK_EQEQ        ] = "==",
3225 [TOK_NOTEQ       ] = "!=",
3226 [TOK_QUEST       ] = "?",
3227 [TOK_LOGOR       ] = "||",
3228 [TOK_LOGAND      ] = "&&",
3229 [TOK_OR          ] = "|",
3230 [TOK_AND         ] = "&",
3231 [TOK_XOR         ] = "^",
3232 [TOK_LESSEQ      ] = "<=",
3233 [TOK_MOREEQ      ] = ">=",
3234 [TOK_SL          ] = "<<",
3235 [TOK_SR          ] = ">>",
3236 [TOK_PLUS        ] = "+",
3237 [TOK_MINUS       ] = "-",
3238 [TOK_DIV         ] = "/",
3239 [TOK_MOD         ] = "%",
3240 [TOK_PLUSPLUS    ] = "++",
3241 [TOK_MINUSMINUS  ] = "--",
3242 [TOK_BANG        ] = "!",
3243 [TOK_ARROW       ] = "->",
3244 [TOK_DOT         ] = ".",
3245 [TOK_TILDE       ] = "~",
3246 [TOK_LIT_STRING  ] = ":string:",
3247 [TOK_IDENT       ] = ":ident:",
3248 [TOK_TYPE_NAME   ] = ":typename:",
3249 [TOK_LIT_CHAR    ] = ":char:",
3250 [TOK_LIT_INT     ] = ":integer:",
3251 [TOK_LIT_FLOAT   ] = ":float:",
3252 [TOK_MACRO       ] = "#",
3253 [TOK_CONCATENATE ] = "##",
3254
3255 [TOK_AUTO        ] = "auto",
3256 [TOK_BREAK       ] = "break",
3257 [TOK_CASE        ] = "case",
3258 [TOK_CHAR        ] = "char",
3259 [TOK_CONST       ] = "const",
3260 [TOK_CONTINUE    ] = "continue",
3261 [TOK_DEFAULT     ] = "default",
3262 [TOK_DO          ] = "do",
3263 [TOK_DOUBLE      ] = "double",
3264 [TOK_ELSE        ] = "else",
3265 [TOK_ENUM        ] = "enum",
3266 [TOK_EXTERN      ] = "extern",
3267 [TOK_FLOAT       ] = "float",
3268 [TOK_FOR         ] = "for",
3269 [TOK_GOTO        ] = "goto",
3270 [TOK_IF          ] = "if",
3271 [TOK_INLINE      ] = "inline",
3272 [TOK_INT         ] = "int",
3273 [TOK_LONG        ] = "long",
3274 [TOK_REGISTER    ] = "register",
3275 [TOK_RESTRICT    ] = "restrict",
3276 [TOK_RETURN      ] = "return",
3277 [TOK_SHORT       ] = "short",
3278 [TOK_SIGNED      ] = "signed",
3279 [TOK_SIZEOF      ] = "sizeof",
3280 [TOK_STATIC      ] = "static",
3281 [TOK_STRUCT      ] = "struct",
3282 [TOK_SWITCH      ] = "switch",
3283 [TOK_TYPEDEF     ] = "typedef",
3284 [TOK_UNION       ] = "union",
3285 [TOK_UNSIGNED    ] = "unsigned",
3286 [TOK_VOID        ] = "void",
3287 [TOK_VOLATILE    ] = "volatile",
3288 [TOK_WHILE       ] = "while",
3289 [TOK_ASM         ] = "asm",
3290 [TOK_ATTRIBUTE   ] = "__attribute__",
3291 [TOK_ALIGNOF     ] = "__alignof__",
3292
3293 [TOK_DEFINE      ] = "define",
3294 [TOK_UNDEF       ] = "undef",
3295 [TOK_INCLUDE     ] = "include",
3296 [TOK_LINE        ] = "line",
3297 [TOK_ERROR       ] = "error",
3298 [TOK_WARNING     ] = "warning",
3299 [TOK_PRAGMA      ] = "pragma",
3300 [TOK_IFDEF       ] = "ifdef",
3301 [TOK_IFNDEF      ] = "ifndef",
3302 [TOK_ELIF        ] = "elif",
3303 [TOK_ENDIF       ] = "endif",
3304
3305 [TOK_DEFINED     ] = "defined",
3306 [TOK_EOF         ] = "EOF",
3307 };
3308
3309 static unsigned int hash(const char *str, int str_len)
3310 {
3311         unsigned int hash;
3312         const char *end;
3313         end = str + str_len;
3314         hash = 0;
3315         for(; str < end; str++) {
3316                 hash = (hash *263) + *str;
3317         }
3318         hash = hash & (HASH_TABLE_SIZE -1);
3319         return hash;
3320 }
3321
3322 static struct hash_entry *lookup(
3323         struct compile_state *state, const char *name, int name_len)
3324 {
3325         struct hash_entry *entry;
3326         unsigned int index;
3327         index = hash(name, name_len);
3328         entry = state->hash_table[index];
3329         while(entry && 
3330                 ((entry->name_len != name_len) ||
3331                         (memcmp(entry->name, name, name_len) != 0))) {
3332                 entry = entry->next;
3333         }
3334         if (!entry) {
3335                 char *new_name;
3336                 /* Get a private copy of the name */
3337                 new_name = xmalloc(name_len + 1, "hash_name");
3338                 memcpy(new_name, name, name_len);
3339                 new_name[name_len] = '\0';
3340
3341                 /* Create a new hash entry */
3342                 entry = xcmalloc(sizeof(*entry), "hash_entry");
3343                 entry->next = state->hash_table[index];
3344                 entry->name = new_name;
3345                 entry->name_len = name_len;
3346
3347                 /* Place the new entry in the hash table */
3348                 state->hash_table[index] = entry;
3349         }
3350         return entry;
3351 }
3352
3353 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3354 {
3355         struct hash_entry *entry;
3356         entry = tk->ident;
3357         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3358                 (entry->tok == TOK_ENUM_CONST) ||
3359                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
3360                         (entry->tok <= TOK_LAST_KEYWORD)))) {
3361                 tk->tok = entry->tok;
3362         }
3363 }
3364
3365 static void ident_to_macro(struct compile_state *state, struct token *tk)
3366 {
3367         struct hash_entry *entry;
3368         entry = tk->ident;
3369         if (entry && 
3370                 (entry->tok >= TOK_FIRST_MACRO) &&
3371                 (entry->tok <= TOK_LAST_MACRO)) {
3372                 tk->tok = entry->tok;
3373         }
3374 }
3375
3376 static void hash_keyword(
3377         struct compile_state *state, const char *keyword, int tok)
3378 {
3379         struct hash_entry *entry;
3380         entry = lookup(state, keyword, strlen(keyword));
3381         if (entry && entry->tok != TOK_UNKNOWN) {
3382                 die("keyword %s already hashed", keyword);
3383         }
3384         entry->tok  = tok;
3385 }
3386
3387 static void romcc_symbol(
3388         struct compile_state *state, struct hash_entry *ident,
3389         struct symbol **chain, struct triple *def, struct type *type, int depth)
3390 {
3391         struct symbol *sym;
3392         if (*chain && ((*chain)->scope_depth >= depth)) {
3393                 error(state, 0, "%s already defined", ident->name);
3394         }
3395         sym = xcmalloc(sizeof(*sym), "symbol");
3396         sym->ident = ident;
3397         sym->def   = def;
3398         sym->type  = type;
3399         sym->scope_depth = depth;
3400         sym->next = *chain;
3401         *chain    = sym;
3402 }
3403
3404 static void symbol(
3405         struct compile_state *state, struct hash_entry *ident,
3406         struct symbol **chain, struct triple *def, struct type *type)
3407 {
3408         romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3409 }
3410
3411 static void var_symbol(struct compile_state *state, 
3412         struct hash_entry *ident, struct triple *def)
3413 {
3414         if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3415                 internal_error(state, 0, "bad var type");
3416         }
3417         symbol(state, ident, &ident->sym_ident, def, def->type);
3418 }
3419
3420 static void label_symbol(struct compile_state *state, 
3421         struct hash_entry *ident, struct triple *label, int depth)
3422 {
3423         romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3424 }
3425
3426 static void start_scope(struct compile_state *state)
3427 {
3428         state->scope_depth++;
3429 }
3430
3431 static void end_scope_syms(struct compile_state *state,
3432         struct symbol **chain, int depth)
3433 {
3434         struct symbol *sym, *next;
3435         sym = *chain;
3436         while(sym && (sym->scope_depth == depth)) {
3437                 next = sym->next;
3438                 xfree(sym);
3439                 sym = next;
3440         }
3441         *chain = sym;
3442 }
3443
3444 static void end_scope(struct compile_state *state)
3445 {
3446         int i;
3447         int depth;
3448         /* Walk through the hash table and remove all symbols
3449          * in the current scope. 
3450          */
3451         depth = state->scope_depth;
3452         for(i = 0; i < HASH_TABLE_SIZE; i++) {
3453                 struct hash_entry *entry;
3454                 entry = state->hash_table[i];
3455                 while(entry) {
3456                         end_scope_syms(state, &entry->sym_label, depth);
3457                         end_scope_syms(state, &entry->sym_tag,   depth);
3458                         end_scope_syms(state, &entry->sym_ident, depth);
3459                         entry = entry->next;
3460                 }
3461         }
3462         state->scope_depth = depth - 1;
3463 }
3464
3465 static void register_keywords(struct compile_state *state)
3466 {
3467         hash_keyword(state, "auto",          TOK_AUTO);
3468         hash_keyword(state, "break",         TOK_BREAK);
3469         hash_keyword(state, "case",          TOK_CASE);
3470         hash_keyword(state, "char",          TOK_CHAR);
3471         hash_keyword(state, "const",         TOK_CONST);
3472         hash_keyword(state, "continue",      TOK_CONTINUE);
3473         hash_keyword(state, "default",       TOK_DEFAULT);
3474         hash_keyword(state, "do",            TOK_DO);
3475         hash_keyword(state, "double",        TOK_DOUBLE);
3476         hash_keyword(state, "else",          TOK_ELSE);
3477         hash_keyword(state, "enum",          TOK_ENUM);
3478         hash_keyword(state, "extern",        TOK_EXTERN);
3479         hash_keyword(state, "float",         TOK_FLOAT);
3480         hash_keyword(state, "for",           TOK_FOR);
3481         hash_keyword(state, "goto",          TOK_GOTO);
3482         hash_keyword(state, "if",            TOK_IF);
3483         hash_keyword(state, "inline",        TOK_INLINE);
3484         hash_keyword(state, "int",           TOK_INT);
3485         hash_keyword(state, "long",          TOK_LONG);
3486         hash_keyword(state, "register",      TOK_REGISTER);
3487         hash_keyword(state, "restrict",      TOK_RESTRICT);
3488         hash_keyword(state, "return",        TOK_RETURN);
3489         hash_keyword(state, "short",         TOK_SHORT);
3490         hash_keyword(state, "signed",        TOK_SIGNED);
3491         hash_keyword(state, "sizeof",        TOK_SIZEOF);
3492         hash_keyword(state, "static",        TOK_STATIC);
3493         hash_keyword(state, "struct",        TOK_STRUCT);
3494         hash_keyword(state, "switch",        TOK_SWITCH);
3495         hash_keyword(state, "typedef",       TOK_TYPEDEF);
3496         hash_keyword(state, "union",         TOK_UNION);
3497         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
3498         hash_keyword(state, "void",          TOK_VOID);
3499         hash_keyword(state, "volatile",      TOK_VOLATILE);
3500         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
3501         hash_keyword(state, "while",         TOK_WHILE);
3502         hash_keyword(state, "asm",           TOK_ASM);
3503         hash_keyword(state, "__asm__",       TOK_ASM);
3504         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3505         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
3506 }
3507
3508 static void register_macro_keywords(struct compile_state *state)
3509 {
3510         hash_keyword(state, "define",        TOK_DEFINE);
3511         hash_keyword(state, "undef",         TOK_UNDEF);
3512         hash_keyword(state, "include",       TOK_INCLUDE);
3513         hash_keyword(state, "line",          TOK_LINE);
3514         hash_keyword(state, "error",         TOK_ERROR);
3515         hash_keyword(state, "warning",       TOK_WARNING);
3516         hash_keyword(state, "pragma",        TOK_PRAGMA);
3517         hash_keyword(state, "ifdef",         TOK_IFDEF);
3518         hash_keyword(state, "ifndef",        TOK_IFNDEF);
3519         hash_keyword(state, "elif",          TOK_ELIF);
3520         hash_keyword(state, "endif",         TOK_ENDIF);
3521 }
3522
3523
3524 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3525 {
3526         if (ident->sym_define != 0) {
3527                 struct macro *macro;
3528                 struct macro_arg *arg, *anext;
3529                 macro = ident->sym_define;
3530                 ident->sym_define = 0;
3531                 
3532                 /* Free the macro arguments... */
3533                 anext = macro->args;
3534                 while(anext) {
3535                         arg = anext;
3536                         anext = arg->next;
3537                         xfree(arg);
3538                 }
3539
3540                 /* Free the macro buffer */
3541                 xfree(macro->buf);
3542
3543                 /* Now free the macro itself */
3544                 xfree(macro);
3545         }
3546 }
3547
3548 static void define_macro(
3549         struct compile_state *state,
3550         struct hash_entry *ident, 
3551         const char *value, int value_len, int value_off, 
3552         struct macro_arg *args)
3553 {
3554         struct macro *macro;
3555         struct macro_arg *arg;
3556         macro = ident->sym_define;
3557         if (macro != 0) {
3558                 /* Explicitly allow identical redefinitions of the same macro */
3559                 if ((macro->buf_len == value_len) &&
3560                         (memcmp(macro->buf, value, value_len) == 0)) {
3561                         return;
3562                 }
3563                 error(state, 0, "macro %s already defined\n", ident->name);
3564         }
3565 #if 0
3566         fprintf(state->errout, "%s: `%*.*s'\n",
3567                 ident->name,
3568                 value_len - value_off,
3569                 value_len - value_off,
3570                 value + value_off);
3571 #endif
3572         macro = xmalloc(sizeof(*macro), "macro");
3573         macro->ident = ident;
3574         macro->buf_len = value_len;
3575         macro->buf_off = value_off;
3576         macro->args    = args;
3577         macro->buf = xmalloc(macro->buf_len + 2, "macro buf");
3578
3579         macro->argc = 0;
3580         for(arg = args; arg; arg = arg->next) {
3581                 macro->argc += 1;
3582         }      
3583
3584         memcpy(macro->buf, value, macro->buf_len);
3585         macro->buf[macro->buf_len] = '\n';
3586         macro->buf[macro->buf_len+1] = '\0';
3587
3588         ident->sym_define = macro;
3589 }
3590
3591 static void register_builtin_macro(struct compile_state *state,
3592         const char *name, const char *value)
3593 {
3594         struct hash_entry *ident;
3595
3596         if (value[0] == '(') {
3597                 internal_error(state, 0, "Builtin macros with arguments not supported");
3598         }
3599         ident = lookup(state, name, strlen(name));
3600         define_macro(state, ident, value, strlen(value), 0, 0);
3601 }
3602
3603 static void register_builtin_macros(struct compile_state *state)
3604 {
3605         char buf[30];
3606         char scratch[30];
3607         time_t now;
3608         struct tm *tm;
3609         now = time(NULL);
3610         tm = localtime(&now);
3611
3612         register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3613         register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3614         register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3615         register_builtin_macro(state, "__LINE__", "54321");
3616
3617         strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3618         sprintf(buf, "\"%s\"", scratch);
3619         register_builtin_macro(state, "__DATE__", buf);
3620
3621         strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3622         sprintf(buf, "\"%s\"", scratch);
3623         register_builtin_macro(state, "__TIME__", buf);
3624
3625         /* I can't be a conforming implementation of C :( */
3626         register_builtin_macro(state, "__STDC__", "0");
3627         /* In particular I don't conform to C99 */
3628         register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3629         
3630 }
3631
3632 static void process_cmdline_macros(struct compile_state *state)
3633 {
3634         const char **macro, *name;
3635         struct hash_entry *ident;
3636         for(macro = state->compiler->defines; (name = *macro); macro++) {
3637                 const char *body;
3638                 size_t name_len;
3639
3640                 name_len = strlen(name);
3641                 body = strchr(name, '=');
3642                 if (!body) {
3643                         body = "\0";
3644                 } else {
3645                         name_len = body - name;
3646                         body++;
3647                 }
3648                 ident = lookup(state, name, name_len);
3649                 define_macro(state, ident, body, strlen(body), 0, 0);
3650         }
3651         for(macro = state->compiler->undefs; (name = *macro); macro++) {
3652                 ident = lookup(state, name, strlen(name));
3653                 undef_macro(state, ident);
3654         }
3655 }
3656
3657 static int spacep(int c)
3658 {
3659         int ret = 0;
3660         switch(c) {
3661         case ' ':
3662         case '\t':
3663         case '\f':
3664         case '\v':
3665         case '\r':
3666         case '\n':
3667                 ret = 1;
3668                 break;
3669         }
3670         return ret;
3671 }
3672
3673 static int digitp(int c)
3674 {
3675         int ret = 0;
3676         switch(c) {
3677         case '0': case '1': case '2': case '3': case '4': 
3678         case '5': case '6': case '7': case '8': case '9':
3679                 ret = 1;
3680                 break;
3681         }
3682         return ret;
3683 }
3684 static int digval(int c)
3685 {
3686         int val = -1;
3687         if ((c >= '0') && (c <= '9')) {
3688                 val = c - '0';
3689         }
3690         return val;
3691 }
3692
3693 static int hexdigitp(int c)
3694 {
3695         int ret = 0;
3696         switch(c) {
3697         case '0': case '1': case '2': case '3': case '4': 
3698         case '5': case '6': case '7': case '8': case '9':
3699         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3700         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3701                 ret = 1;
3702                 break;
3703         }
3704         return ret;
3705 }
3706 static int hexdigval(int c) 
3707 {
3708         int val = -1;
3709         if ((c >= '0') && (c <= '9')) {
3710                 val = c - '0';
3711         }
3712         else if ((c >= 'A') && (c <= 'F')) {
3713                 val = 10 + (c - 'A');
3714         }
3715         else if ((c >= 'a') && (c <= 'f')) {
3716                 val = 10 + (c - 'a');
3717         }
3718         return val;
3719 }
3720
3721 static int octdigitp(int c)
3722 {
3723         int ret = 0;
3724         switch(c) {
3725         case '0': case '1': case '2': case '3': 
3726         case '4': case '5': case '6': case '7':
3727                 ret = 1;
3728                 break;
3729         }
3730         return ret;
3731 }
3732 static int octdigval(int c)
3733 {
3734         int val = -1;
3735         if ((c >= '0') && (c <= '7')) {
3736                 val = c - '0';
3737         }
3738         return val;
3739 }
3740
3741 static int letterp(int c)
3742 {
3743         int ret = 0;
3744         switch(c) {
3745         case 'a': case 'b': case 'c': case 'd': case 'e':
3746         case 'f': case 'g': case 'h': case 'i': case 'j':
3747         case 'k': case 'l': case 'm': case 'n': case 'o':
3748         case 'p': case 'q': case 'r': case 's': case 't':
3749         case 'u': case 'v': case 'w': case 'x': case 'y':
3750         case 'z':
3751         case 'A': case 'B': case 'C': case 'D': case 'E':
3752         case 'F': case 'G': case 'H': case 'I': case 'J':
3753         case 'K': case 'L': case 'M': case 'N': case 'O':
3754         case 'P': case 'Q': case 'R': case 'S': case 'T':
3755         case 'U': case 'V': case 'W': case 'X': case 'Y':
3756         case 'Z':
3757         case '_':
3758                 ret = 1;
3759                 break;
3760         }
3761         return ret;
3762 }
3763
3764 static const char *identifier(const char *str, const char *end)
3765 {
3766         if (letterp(*str)) {
3767                 for(; str < end; str++) {
3768                         int c;
3769                         c = *str;
3770                         if (!letterp(c) && !digitp(c)) {
3771                                 break;
3772                         }
3773                 }
3774         }
3775         return str;
3776 }
3777
3778 static int char_value(struct compile_state *state,
3779         const signed char **strp, const signed char *end)
3780 {
3781         const signed char *str;
3782         int c;
3783         str = *strp;
3784         c = *str++;
3785         if ((c == '\\') && (str < end)) {
3786                 switch(*str) {
3787                 case 'n':  c = '\n'; str++; break;
3788                 case 't':  c = '\t'; str++; break;
3789                 case 'v':  c = '\v'; str++; break;
3790                 case 'b':  c = '\b'; str++; break;
3791                 case 'r':  c = '\r'; str++; break;
3792                 case 'f':  c = '\f'; str++; break;
3793                 case 'a':  c = '\a'; str++; break;
3794                 case '\\': c = '\\'; str++; break;
3795                 case '?':  c = '?';  str++; break;
3796                 case '\'': c = '\''; str++; break;
3797                 case '"':  c = '"';  str++; break;
3798                 case 'x': 
3799                         c = 0;
3800                         str++;
3801                         while((str < end) && hexdigitp(*str)) {
3802                                 c <<= 4;
3803                                 c += hexdigval(*str);
3804                                 str++;
3805                         }
3806                         break;
3807                 case '0': case '1': case '2': case '3': 
3808                 case '4': case '5': case '6': case '7':
3809                         c = 0;
3810                         while((str < end) && octdigitp(*str)) {
3811                                 c <<= 3;
3812                                 c += octdigval(*str);
3813                                 str++;
3814                         }
3815                         break;
3816                 default:
3817                         error(state, 0, "Invalid character constant");
3818                         break;
3819                 }
3820         }
3821         *strp = str;
3822         return c;
3823 }
3824
3825 static const char *after_digits(const char *ptr, const char *end)
3826 {
3827         while((ptr < end) && digitp(*ptr)) {
3828                 ptr++;
3829         }
3830         return ptr;
3831 }
3832
3833 static const char *after_octdigits(const char *ptr, const char *end)
3834 {
3835         while((ptr < end) && octdigitp(*ptr)) {
3836                 ptr++;
3837         }
3838         return ptr;
3839 }
3840
3841 static const char *after_hexdigits(const char *ptr, const char *end)
3842 {
3843         while((ptr < end) && hexdigitp(*ptr)) {
3844                 ptr++;
3845         }
3846         return ptr;
3847 }
3848
3849 static void save_string(struct compile_state *state, 
3850         struct token *tk, const char *start, const char *end, const char *id)
3851 {
3852         char *str;
3853         int str_len;
3854         /* Create a private copy of the string */
3855         str_len = end - start + 1;
3856         str = xmalloc(str_len + 1, id);
3857         memcpy(str, start, str_len);
3858         str[str_len] = '\0';
3859
3860         /* Store the copy in the token */
3861         tk->val.str = str;
3862         tk->str_len = str_len;
3863 }
3864
3865 static int lparen_peek(struct compile_state *state, struct file_state *file)
3866 {
3867         const char *tokp, *end;
3868         /* Is the next token going to be an lparen? 
3869          * Whitespace tokens are significant for seeing if a macro
3870          * should be expanded.
3871          */
3872         tokp = file->pos;
3873         end = file->buf + file->size;
3874         return (tokp < end) && (*tokp == '(');
3875 }
3876
3877 static void raw_next_token(struct compile_state *state, 
3878         struct file_state *file, struct token *tk)
3879 {
3880         const char *token;
3881         int c, c1, c2, c3;
3882         const char *tokp, *end;
3883         int tok;
3884
3885         tk->str_len = 0;
3886         tk->ident = 0;
3887         token = tokp = file->pos;
3888         end = file->buf + file->size;
3889         tok = TOK_UNKNOWN;
3890         c = -1;
3891         if (tokp < end) {
3892                 c = *tokp;
3893         }
3894         c1 = -1;
3895         if ((tokp + 1) < end) {
3896                 c1 = tokp[1];
3897         }
3898         c2 = -1;
3899         if ((tokp + 2) < end) {
3900                 c2 = tokp[2];
3901         }
3902         c3 = -1;
3903         if ((tokp + 3) < end) {
3904                 c3 = tokp[3];
3905         }
3906         if (tokp >= end) {
3907                 tok = TOK_EOF;
3908                 tokp = end;
3909         }
3910         /* Whitespace */
3911         else if (spacep(c)) {
3912                 tok = TOK_SPACE;
3913                 while ((tokp < end) && spacep(c)) {
3914                         if (c == '\n') {
3915                                 file->line++;
3916                                 file->report_line++;
3917                                 file->line_start = tokp + 1;
3918                         }
3919                         c = *(++tokp);
3920                 }
3921                 if (!spacep(c)) {
3922                         tokp--;
3923                 }
3924         }
3925         /* EOL Comments */
3926         else if ((c == '/') && (c1 == '/')) {
3927                 tok = TOK_SPACE;
3928                 for(tokp += 2; tokp < end; tokp++) {
3929                         c = *tokp;
3930                         if (c == '\n') {
3931                                 file->line++;
3932                                 file->report_line++;
3933                                 file->line_start = tokp +1;
3934                                 break;
3935                         }
3936                 }
3937         }
3938         /* Comments */
3939         else if ((c == '/') && (c1 == '*')) {
3940                 int line;
3941                 const char *line_start;
3942                 line = file->line;
3943                 line_start = file->line_start;
3944                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
3945                         c = *tokp;
3946                         if (c == '\n') {
3947                                 line++;
3948                                 line_start = tokp +1;
3949                         }
3950                         else if ((c == '*') && (tokp[1] == '/')) {
3951                                 tok = TOK_SPACE;
3952                                 tokp += 1;
3953                                 break;
3954                         }
3955                 }
3956                 if (tok == TOK_UNKNOWN) {
3957                         error(state, 0, "unterminated comment");
3958                 }
3959                 file->report_line += line - file->line;
3960                 file->line = line;
3961                 file->line_start = line_start;
3962         }
3963         /* string constants */
3964         else if ((c == '"') ||
3965                 ((c == 'L') && (c1 == '"'))) {
3966                 int line;
3967                 const char *line_start;
3968                 int wchar;
3969                 line = file->line;
3970                 line_start = file->line_start;
3971                 wchar = 0;
3972                 if (c == 'L') {
3973                         wchar = 1;
3974                         tokp++;
3975                 }
3976                 for(tokp += 1; tokp < end; tokp++) {
3977                         c = *tokp;
3978                         if (c == '\n') {
3979                                 line++;
3980                                 line_start = tokp + 1;
3981                         }
3982                         else if ((c == '\\') && (tokp +1 < end)) {
3983                                 tokp++;
3984                         }
3985                         else if (c == '"') {
3986                                 tok = TOK_LIT_STRING;
3987                                 break;
3988                         }
3989                 }
3990                 if (tok == TOK_UNKNOWN) {
3991                         error(state, 0, "unterminated string constant");
3992                 }
3993                 if (line != file->line) {
3994                         warning(state, 0, "multiline string constant");
3995                 }
3996                 file->report_line += line - file->line;
3997                 file->line = line;
3998                 file->line_start = line_start;
3999
4000                 /* Save the string value */
4001                 save_string(state, tk, token, tokp, "literal string");
4002         }
4003         /* character constants */
4004         else if ((c == '\'') ||
4005                 ((c == 'L') && (c1 == '\''))) {
4006                 int line;
4007                 const char *line_start;
4008                 int wchar;
4009                 line = file->line;
4010                 line_start = file->line_start;
4011                 wchar = 0;
4012                 if (c == 'L') {
4013                         wchar = 1;
4014                         tokp++;
4015                 }
4016                 for(tokp += 1; tokp < end; tokp++) {
4017                         c = *tokp;
4018                         if (c == '\n') {
4019                                 line++;
4020                                 line_start = tokp + 1;
4021                         }
4022                         else if ((c == '\\') && (tokp +1 < end)) {
4023                                 tokp++;
4024                         }
4025                         else if (c == '\'') {
4026                                 tok = TOK_LIT_CHAR;
4027                                 break;
4028                         }
4029                 }
4030                 if (tok == TOK_UNKNOWN) {
4031                         error(state, 0, "unterminated character constant");
4032                 }
4033                 if (line != file->line) {
4034                         warning(state, 0, "multiline character constant");
4035                 }
4036                 file->report_line += line - file->line;
4037                 file->line = line;
4038                 file->line_start = line_start;
4039
4040                 /* Save the character value */
4041                 save_string(state, tk, token, tokp, "literal character");
4042         }
4043         /* integer and floating constants 
4044          * Integer Constants
4045          * {digits}
4046          * 0[Xx]{hexdigits}
4047          * 0{octdigit}+
4048          * 
4049          * Floating constants
4050          * {digits}.{digits}[Ee][+-]?{digits}
4051          * {digits}.{digits}
4052          * {digits}[Ee][+-]?{digits}
4053          * .{digits}[Ee][+-]?{digits}
4054          * .{digits}
4055          */
4056         
4057         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4058                 const char *next, *new;
4059                 int is_float;
4060                 is_float = 0;
4061                 if (c != '.') {
4062                         next = after_digits(tokp, end);
4063                 }
4064                 else {
4065                         next = tokp;
4066                 }
4067                 if (next[0] == '.') {
4068                         new = after_digits(next, end);
4069                         is_float = (new != next);
4070                         next = new;
4071                 }
4072                 if ((next[0] == 'e') || (next[0] == 'E')) {
4073                         if (((next + 1) < end) && 
4074                                 ((next[1] == '+') || (next[1] == '-'))) {
4075                                 next++;
4076                         }
4077                         new = after_digits(next, end);
4078                         is_float = (new != next);
4079                         next = new;
4080                 }
4081                 if (is_float) {
4082                         tok = TOK_LIT_FLOAT;
4083                         if ((next < end) && (
4084                                 (next[0] == 'f') ||
4085                                 (next[0] == 'F') ||
4086                                 (next[0] == 'l') ||
4087                                 (next[0] == 'L'))
4088                                 ) {
4089                                 next++;
4090                         }
4091                 }
4092                 if (!is_float && digitp(c)) {
4093                         tok = TOK_LIT_INT;
4094                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4095                                 next = after_hexdigits(tokp + 2, end);
4096                         }
4097                         else if (c == '0') {
4098                                 next = after_octdigits(tokp, end);
4099                         }
4100                         else {
4101                                 next = after_digits(tokp, end);
4102                         }
4103                         /* crazy integer suffixes */
4104                         if ((next < end) && 
4105                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
4106                                 next++;
4107                                 if ((next < end) &&
4108                                         ((next[0] == 'l') || (next[0] == 'L'))) {
4109                                         next++;
4110                                 }
4111                         }
4112                         else if ((next < end) &&
4113                                 ((next[0] == 'l') || (next[0] == 'L'))) {
4114                                 next++;
4115                                 if ((next < end) && 
4116                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
4117                                         next++;
4118                                 }
4119                         }
4120                 }
4121                 tokp = next - 1;
4122
4123                 /* Save the integer/floating point value */
4124                 save_string(state, tk, token, tokp, "literal number");
4125         }
4126         /* identifiers */
4127         else if (letterp(c)) {
4128                 tok = TOK_IDENT;
4129                 tokp = identifier(tokp, end);
4130                 tokp -= 1;
4131                 tk->ident = lookup(state, token, tokp +1 - token);
4132                 /* See if this identifier can be macro expanded */
4133                 tk->val.notmacro = 0;
4134                 if ((tokp < end) && (tokp[1] == '$')) {
4135                         tokp++;
4136                         tk->val.notmacro = 1;
4137                 }
4138         }
4139         /* C99 alternate macro characters */
4140         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
4141                 tokp += 3; 
4142                 tok = TOK_CONCATENATE; 
4143         }
4144         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
4145         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
4146         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
4147         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
4148         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
4149         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
4150         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
4151         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
4152         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
4153         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
4154         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
4155         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
4156         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
4157         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
4158         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
4159         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
4160         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
4161         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
4162         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
4163         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
4164         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
4165         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
4166         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
4167         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
4168         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
4169         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
4170         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
4171         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
4172         else if (c == ';') { tok = TOK_SEMI; }
4173         else if (c == '{') { tok = TOK_LBRACE; }
4174         else if (c == '}') { tok = TOK_RBRACE; }
4175         else if (c == ',') { tok = TOK_COMMA; }
4176         else if (c == '=') { tok = TOK_EQ; }
4177         else if (c == ':') { tok = TOK_COLON; }
4178         else if (c == '[') { tok = TOK_LBRACKET; }
4179         else if (c == ']') { tok = TOK_RBRACKET; }
4180         else if (c == '(') { tok = TOK_LPAREN; }
4181         else if (c == ')') { tok = TOK_RPAREN; }
4182         else if (c == '*') { tok = TOK_STAR; }
4183         else if (c == '>') { tok = TOK_MORE; }
4184         else if (c == '<') { tok = TOK_LESS; }
4185         else if (c == '?') { tok = TOK_QUEST; }
4186         else if (c == '|') { tok = TOK_OR; }
4187         else if (c == '&') { tok = TOK_AND; }
4188         else if (c == '^') { tok = TOK_XOR; }
4189         else if (c == '+') { tok = TOK_PLUS; }
4190         else if (c == '-') { tok = TOK_MINUS; }
4191         else if (c == '/') { tok = TOK_DIV; }
4192         else if (c == '%') { tok = TOK_MOD; }
4193         else if (c == '!') { tok = TOK_BANG; }
4194         else if (c == '.') { tok = TOK_DOT; }
4195         else if (c == '~') { tok = TOK_TILDE; }
4196         else if (c == '#') { tok = TOK_MACRO; }
4197
4198         file->pos = tokp + 1;
4199         tk->tok = tok;
4200         if (tok == TOK_IDENT) {
4201                 ident_to_keyword(state, tk);
4202         }
4203 }
4204
4205 static void next_token(struct compile_state *state, struct token *tk)
4206 {
4207         struct file_state *file;
4208         file = state->file;
4209         /* Don't return space tokens. */
4210         do {
4211                 raw_next_token(state, file, tk);
4212                 if (tk->tok == TOK_MACRO) {
4213                         /* Only match preprocessor directives at the start of a line */
4214                         const char *ptr;
4215                         for(ptr = file->line_start; spacep(*ptr); ptr++)
4216                                 ;
4217                         if (ptr != file->pos - 1) {
4218                                 tk->tok = TOK_UNKNOWN;
4219                         }
4220                 }
4221                 if (tk->tok == TOK_UNKNOWN) {
4222                         error(state, 0, "unknown token");
4223                 }
4224         } while(tk->tok == TOK_SPACE);
4225 }
4226
4227 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4228 {
4229         if (tk->tok != tok) {
4230                 const char *name1, *name2;
4231                 name1 = tokens[tk->tok];
4232                 name2 = "";
4233                 if (tk->tok == TOK_IDENT) {
4234                         name2 = tk->ident->name;
4235                 }
4236                 error(state, 0, "\tfound %s %s expected %s",
4237                         name1, name2, tokens[tok]);
4238         }
4239 }
4240
4241 struct macro_arg_value {
4242         struct hash_entry *ident;
4243         unsigned char *value;
4244         size_t len;
4245 };
4246 static struct macro_arg_value *read_macro_args(
4247         struct compile_state *state, struct macro *macro, 
4248         struct file_state *file, struct token *tk)
4249 {
4250         struct macro_arg_value *argv;
4251         struct macro_arg *arg;
4252         int paren_depth;
4253         int i;
4254
4255         if (macro->argc == 0) {
4256                 do {
4257                         raw_next_token(state, file, tk);
4258                 } while(tk->tok == TOK_SPACE);
4259                 return 0;
4260         }
4261         argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4262         for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4263                 argv[i].value = 0;
4264                 argv[i].len   = 0;
4265                 argv[i].ident = arg->ident;
4266         }
4267         paren_depth = 0;
4268         i = 0;
4269         
4270         for(;;) {
4271                 const char *start;
4272                 size_t len;
4273                 start = file->pos;
4274                 raw_next_token(state, file, tk);
4275                 
4276                 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4277                         (argv[i].ident != state->i___VA_ARGS__)) 
4278                 {
4279                         i++;
4280                         if (i >= macro->argc) {
4281                                 error(state, 0, "too many args to %s\n",
4282                                         macro->ident->name);
4283                         }
4284                         continue;
4285                 }
4286                 
4287                 if (tk->tok == TOK_LPAREN) {
4288                         paren_depth++;
4289                 }
4290                 
4291                 if (tk->tok == TOK_RPAREN) {
4292                         if (paren_depth == 0) {
4293                                 break;
4294                         }
4295                         paren_depth--;
4296                 }
4297                 if (tk->tok == TOK_EOF) {
4298                         error(state, 0, "End of file encountered while parsing macro arguments");
4299                 }
4300                 
4301                 len = file->pos - start;
4302                 argv[i].value = xrealloc(
4303                         argv[i].value, argv[i].len + len, "macro args");
4304                 memcpy(argv[i].value + argv[i].len, start, len);
4305                 argv[i].len += len;
4306         }
4307         if (i != macro->argc -1) {
4308                 error(state, 0, "missing %s arg %d\n", 
4309                         macro->ident->name, i +2);
4310         }
4311         return argv;
4312 }
4313
4314
4315 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4316 {
4317         int i;
4318         for(i = 0; i < macro->argc; i++) {
4319                 xfree(argv[i].value);
4320         }
4321         xfree(argv);
4322 }
4323
4324 struct macro_buf {
4325         char *str;
4326         size_t len, pos;
4327 };
4328
4329 static void append_macro_text(struct compile_state *state,
4330         struct macro *macro, struct macro_buf *buf, 
4331         const char *fstart, size_t flen)
4332 {
4333 #if 0
4334         fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4335                 buf->pos, buf->pos, buf->str,
4336                 flen, flen, fstart);
4337 #endif
4338         if ((buf->pos + flen) < buf->len) {
4339                 memcpy(buf->str + buf->pos, fstart, flen);
4340         } else {
4341                 buf->str = xrealloc(buf->str, buf->len + flen, macro->ident->name);
4342                 memcpy(buf->str + buf->pos, fstart, flen);
4343                 buf->len += flen;
4344         }
4345         buf->pos += flen;
4346 }
4347
4348 static int compile_macro(struct compile_state *state, 
4349         struct file_state **filep, struct token *tk);
4350
4351 static void macro_expand_args(struct compile_state *state, 
4352         struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4353 {
4354         size_t i;
4355         
4356         for(i = 0; i < macro->argc; i++) {
4357                 struct file_state fmacro, *file;
4358                 struct macro_buf buf;
4359                 const char *fstart;
4360                 size_t flen;
4361
4362                 fmacro.basename    = argv[i].ident->name;
4363                 fmacro.dirname     = "";
4364                 fmacro.size        = argv[i].len;
4365                 fmacro.buf         = argv[i].value;
4366                 fmacro.pos         = fmacro.buf;
4367                 fmacro.line_start  = fmacro.buf;
4368                 fmacro.line        = 1;
4369                 fmacro.report_line = 1;
4370                 fmacro.report_name = fmacro.basename;
4371                 fmacro.report_dir  = fmacro.dirname;
4372                 fmacro.prev        = 0;
4373
4374                 buf.len = argv[i].len;
4375                 buf.str = xmalloc(buf.len, argv[i].ident->name);
4376                 buf.pos = 0;
4377
4378                 file = &fmacro;
4379                 for(;;) {
4380                         fstart = file->pos;
4381                         raw_next_token(state, file, tk);
4382                         flen = file->pos - fstart;
4383                         
4384                         if (tk->tok == TOK_EOF) {
4385                                 struct file_state *old;
4386                                 old = file;
4387                                 file = file->prev;
4388                                 if (!file) {
4389                                         break;
4390                                 }
4391                                 /* old->basename is used keep it */
4392                                 xfree(old->dirname);
4393                                 xfree(old->buf);
4394                                 xfree(old);
4395                                 continue;
4396                         }
4397                         else if (tk->ident && tk->ident->sym_define) {
4398                                 if (compile_macro(state, &file, tk)) {
4399                                         continue;
4400                                 }
4401                         }
4402
4403                         append_macro_text(state, macro, &buf,
4404                                 fstart, flen);
4405                 }
4406                         
4407                 xfree(argv[i].value);
4408                 argv[i].value = buf.str;
4409                 argv[i].len   = buf.pos;
4410         }
4411         return;
4412 }
4413
4414 static void expand_macro(struct compile_state *state,
4415         struct macro *macro, struct macro_buf *buf,
4416         struct macro_arg_value *argv, struct token *tk)
4417 {
4418         struct file_state fmacro;
4419         const char space[] = " ";
4420         const char *fstart;
4421         size_t flen;
4422         size_t i, j;
4423         fmacro.basename = macro->ident->name;
4424         fmacro.dirname  = "";
4425         fmacro.size = macro->buf_len - macro->buf_off;;
4426         fmacro.buf  = macro->buf + macro->buf_off;
4427         fmacro.pos  = fmacro.buf;
4428         fmacro.line_start = fmacro.buf;
4429         fmacro.line = 1;
4430         fmacro.report_line = 1;
4431         fmacro.report_name = fmacro.basename;
4432         fmacro.report_dir  = fmacro.dirname;
4433         fmacro.prev = 0;
4434         
4435         buf->len = macro->buf_len + 3;
4436         buf->str = xmalloc(buf->len, macro->ident->name);
4437         buf->pos = 0;
4438         
4439         fstart = fmacro.pos;
4440         raw_next_token(state, &fmacro, tk);
4441         while(tk->tok != TOK_EOF) {
4442                 flen = fmacro.pos - fstart;
4443                 switch(tk->tok) {
4444                 case TOK_IDENT:
4445                         for(i = 0; i < macro->argc; i++) {
4446                                 if (argv[i].ident == tk->ident) {
4447                                         break;
4448                                 }
4449                         }
4450                         if (i >= macro->argc) {
4451                                 break;
4452                         }
4453                         /* Substitute macro parameter */
4454                         fstart = argv[i].value;
4455                         flen   = argv[i].len;
4456                         break;
4457                 case TOK_MACRO:
4458                         if (!macro->buf_off) {
4459                                 break;
4460                         }
4461                         do {
4462                                 raw_next_token(state, &fmacro, tk);
4463                         } while(tk->tok == TOK_SPACE);
4464                         check_tok(state, tk, TOK_IDENT);
4465                         for(i = 0; i < macro->argc; i++) {
4466                                 if (argv[i].ident == tk->ident) {
4467                                         break;
4468                                 }
4469                         }
4470                         if (i >= macro->argc) {
4471                                 error(state, 0, "parameter `%s' not found",
4472                                         tk->ident->name);
4473                         }
4474                         /* Stringize token */
4475                         append_macro_text(state, macro, buf, "\"", 1);
4476                         for(j = 0; j < argv[i].len; j++) {
4477                                 char *str = argv[i].value + j;
4478                                 size_t len = 1;
4479                                 if (*str == '\\') {
4480                                         str = "\\";
4481                                         len = 2;
4482                                 } 
4483                                 else if (*str == '"') {
4484                                         str = "\\\"";
4485                                         len = 2;
4486                                 }
4487                                 append_macro_text(state, macro, buf, str, len);
4488                         }
4489                         append_macro_text(state, macro, buf, "\"", 1);
4490                         fstart = 0;
4491                         flen   = 0;
4492                         break;
4493                 case TOK_CONCATENATE:
4494                         /* Concatenate tokens */
4495                         /* Delete the previous whitespace token */
4496                         if (buf->str[buf->pos - 1] == ' ') {
4497                                 buf->pos -= 1;
4498                         }
4499                         /* Skip the next sequence of whitspace tokens */
4500                         do {
4501                                 fstart = fmacro.pos;
4502                                 raw_next_token(state, &fmacro, tk);
4503                         } while(tk->tok == TOK_SPACE);
4504                         /* Restart at the top of the loop.
4505                          * I need to process the non white space token.
4506                          */
4507                         continue;
4508                         break;
4509                 case TOK_SPACE:
4510                         /* Collapse multiple spaces into one */
4511                         if (buf->str[buf->pos - 1] != ' ') {
4512                                 fstart = space;
4513                                 flen   = 1;
4514                         } else {
4515                                 fstart = 0;
4516                                 flen   = 0;
4517                         }
4518                         break;
4519                 default:
4520                         break;
4521                 }
4522
4523                 append_macro_text(state, macro, buf, fstart, flen);
4524                 
4525                 fstart = fmacro.pos;
4526                 raw_next_token(state, &fmacro, tk);
4527         }
4528 }
4529
4530 static void tag_macro_name(struct compile_state *state,
4531         struct macro *macro, struct macro_buf *buf,
4532         struct token *tk)
4533 {
4534         /* Guard all instances of the macro name in the replacement
4535          * text from further macro expansion.
4536          */
4537         struct file_state fmacro;
4538         const char *fstart;
4539         size_t flen;
4540         fmacro.basename = macro->ident->name;
4541         fmacro.dirname  = "";
4542         fmacro.size = buf->pos;
4543         fmacro.buf  = buf->str;
4544         fmacro.pos  = fmacro.buf;
4545         fmacro.line_start = fmacro.buf;
4546         fmacro.line = 1;
4547         fmacro.report_line = 1;
4548         fmacro.report_name = fmacro.basename;
4549         fmacro.report_dir  = fmacro.dirname;
4550         fmacro.prev = 0;
4551         
4552         buf->len = macro->buf_len + 3;
4553         buf->str = xmalloc(buf->len, macro->ident->name);
4554         buf->pos = 0;
4555         
4556         fstart = fmacro.pos;
4557         raw_next_token(state, &fmacro, tk);
4558         while(tk->tok != TOK_EOF) {
4559                 flen = fmacro.pos - fstart;
4560                 if ((tk->tok == TOK_IDENT) &&
4561                         (tk->ident == macro->ident) &&
4562                         (tk->val.notmacro == 0)) {
4563                         append_macro_text(state, macro, buf, fstart, flen);
4564                         fstart = "$";
4565                         flen   = 1;
4566                 }
4567
4568                 append_macro_text(state, macro, buf, fstart, flen);
4569                 
4570                 fstart = fmacro.pos;
4571                 raw_next_token(state, &fmacro, tk);
4572         }
4573         xfree(fmacro.buf);
4574 }
4575         
4576 static int compile_macro(struct compile_state *state, 
4577         struct file_state **filep, struct token *tk)
4578 {
4579         struct file_state *file;
4580         struct hash_entry *ident;
4581         struct macro *macro;
4582         struct macro_arg_value *argv;
4583         struct macro_buf buf;
4584
4585 #if 0
4586         fprintf(state->errout, "macro: %s\n", tk->ident->name);
4587 #endif
4588         ident = tk->ident;
4589         macro = ident->sym_define;
4590
4591         /* If this token comes from a macro expansion ignore it */
4592         if (tk->val.notmacro) {
4593                 return 0;
4594         }
4595         /* If I am a function like macro and the identifier is not followed
4596          * by a left parenthesis, do nothing.
4597          */
4598         if ((macro->buf_off != 0) && !lparen_peek(state, *filep)) {
4599                 return 0;
4600         }
4601
4602         /* Read in the macro arguments */
4603         argv = 0;
4604         if (macro->buf_off) {
4605                 raw_next_token(state, *filep, tk);
4606                 check_tok(state, tk, TOK_LPAREN);
4607
4608                 argv = read_macro_args(state, macro, *filep, tk);
4609
4610                 check_tok(state, tk, TOK_RPAREN);
4611         }
4612         /* Macro expand the macro arguments */
4613         macro_expand_args(state, macro, argv, tk);
4614
4615         buf.str = 0;
4616         buf.len = 0;
4617         buf.pos = 0;
4618         if (ident == state->i___FILE__) {
4619                 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4620                 buf.str = xmalloc(buf.len, ident->name);
4621                 sprintf(buf.str, "\"%s\"", state->file->basename);
4622                 buf.pos = strlen(buf.str);
4623         }
4624         else if (ident == state->i___LINE__) {
4625                 buf.len = 30;
4626                 buf.str = xmalloc(buf.len, ident->name);
4627                 sprintf(buf.str, "%d", state->file->line);
4628                 buf.pos = strlen(buf.str);
4629         }
4630         else {
4631                 expand_macro(state, macro, &buf, argv, tk);
4632         }
4633         /* Tag the macro name with a $ so it will no longer
4634          * be regonized as a canidate for macro expansion.
4635          */
4636         tag_macro_name(state, macro, &buf, tk);
4637         append_macro_text(state, macro, &buf, "\n\0", 2);
4638
4639 #if 0
4640         fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4641                 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4642 #endif
4643
4644         free_macro_args(macro, argv);
4645
4646         file = xmalloc(sizeof(*file), "file_state");
4647         file->basename = xstrdup(ident->name);
4648         file->dirname = xstrdup("");
4649         file->buf = buf.str;
4650         file->size = buf.pos - 2;
4651         file->pos = file->buf;
4652         file->line_start = file->pos;
4653         file->line = 1;
4654         file->report_line = 1;
4655         file->report_name = file->basename;
4656         file->report_dir  = file->dirname;
4657         file->prev = *filep;
4658         *filep = file;
4659         return 1;
4660 }
4661
4662
4663 static int mpeek(struct compile_state *state, int index)
4664 {
4665         struct token *tk;
4666         int rescan;
4667         tk = &state->token[index + 1];
4668         if (tk->tok == -1) {
4669                 do {
4670                         raw_next_token(state, state->file, tk);
4671                 } while(tk->tok == TOK_SPACE);
4672         }
4673         do {
4674                 rescan = 0;
4675                 if ((tk->tok == TOK_EOF) && 
4676                         (state->file != state->macro_file) &&
4677                         (state->file->prev)) {
4678                         struct file_state *file = state->file;
4679                         state->file = file->prev;
4680                         /* file->basename is used keep it */
4681                         if (file->report_dir != file->dirname) {
4682                                 xfree(file->report_dir);
4683                         }
4684                         xfree(file->dirname);
4685                         xfree(file->buf);
4686                         xfree(file);
4687                         next_token(state, tk);
4688                         rescan = 1;
4689                 }
4690                 else if (tk->ident && tk->ident->sym_define) {
4691                         rescan = compile_macro(state, &state->file, tk);
4692                         if (rescan) {
4693                                 next_token(state, tk);
4694                         }
4695                                 
4696                 }
4697         } while(rescan);
4698         /* Don't show the token on the next line */
4699         if (state->macro_line < state->macro_file->line) {
4700                 return TOK_EOF;
4701         }
4702         return tk->tok;
4703 }
4704
4705 static void meat(struct compile_state *state, int index, int tok)
4706 {
4707         int i;
4708         int next_tok;
4709         next_tok = mpeek(state, index);
4710         if (next_tok != tok) {
4711                 check_tok(state, &state->token[index + 1], tok);
4712         }
4713
4714         /* Free the old token value */
4715         if (state->token[index].str_len) {
4716                 memset((void *)(state->token[index].val.str), -1, 
4717                         state->token[index].str_len);
4718                 xfree(state->token[index].val.str);
4719         }
4720         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4721                 state->token[i] = state->token[i + 1];
4722         }
4723         memset(&state->token[i], 0, sizeof(state->token[i]));
4724         state->token[i].tok = -1;
4725 }
4726
4727 static int mpeek_raw(struct compile_state *state, int index)
4728 {
4729         struct token *tk;
4730         int rescan;
4731         tk = &state->token[index + 1];
4732         if (tk->tok == -1) {
4733                 do {
4734                         raw_next_token(state, state->file, tk);
4735                 } while(tk->tok == TOK_SPACE);
4736         }
4737         do {
4738                 rescan = 0;
4739                 if ((tk->tok == TOK_EOF) && 
4740                         (state->file != state->macro_file) &&
4741                         (state->file->prev)) {
4742                         struct file_state *file = state->file;
4743                         state->file = file->prev;
4744                         /* file->basename is used keep it */
4745                         if (file->report_dir != file->dirname) {
4746                                 xfree(file->report_dir);
4747                         }
4748                         xfree(file->dirname);
4749                         xfree(file->buf);
4750                         xfree(file);
4751                         next_token(state, tk);
4752                         rescan = 1;
4753                 }
4754         } while(rescan);
4755         /* Don't show the token on the next line */
4756         if (state->macro_line < state->macro_file->line) {
4757                 return TOK_EOF;
4758         }
4759         return tk->tok;
4760 }
4761
4762 static void meat_raw(struct compile_state *state, int index, int tok)
4763 {
4764         int next_tok;
4765         int i;
4766         next_tok = mpeek_raw(state, index);
4767         if (next_tok != tok) {
4768                 check_tok(state, &state->token[index + 1], tok);
4769         }
4770
4771         /* Free the old token value */
4772         if (state->token[index].str_len) {
4773                 memset((void *)(state->token[index].val.str), -1, 
4774                         state->token[index].str_len);
4775                 xfree(state->token[index].val.str);
4776         }
4777         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4778                 state->token[i] = state->token[i + 1];
4779         }
4780         memset(&state->token[i], 0, sizeof(state->token[i]));
4781         state->token[i].tok = -1;
4782 }
4783
4784 static long_t mcexpr(struct compile_state *state, int index);
4785
4786 static long_t mprimary_expr(struct compile_state *state, int index)
4787 {
4788         long_t val;
4789         int tok;
4790         tok = mpeek(state, index);
4791         switch(tok) {
4792         case TOK_LPAREN:
4793                 meat(state, index, TOK_LPAREN);
4794                 val = mcexpr(state, index);
4795                 meat(state, index, TOK_RPAREN);
4796                 break;
4797         case TOK_LIT_INT:
4798         {
4799                 long lval;
4800                 char *end;
4801                 meat(state, index, TOK_LIT_INT);
4802                 errno = 0;
4803                 lval = strtol(state->token[index].val.str, &end, 0);
4804                 if ((lval > LONG_T_MAX) || (lval < LONG_T_MIN) ||
4805                         (((lval == LONG_MIN) || (lval == LONG_MAX)) &&
4806                                 (errno == ERANGE))) {
4807                         error(state, 0, "Integer constant `%s' to large", state->token[index].val.str);
4808                 }
4809                 val = lval;
4810                 break;
4811         }
4812         default:
4813                 meat(state, index, TOK_LIT_INT);
4814                 val = 0;
4815         }
4816         return val;
4817 }
4818 static long_t munary_expr(struct compile_state *state, int index)
4819 {
4820         long_t val;
4821         int tok;
4822         tok = mpeek(state, index);
4823         if ((tok == TOK_IDENT) && 
4824                 (state->token[index + 1].ident == state->i_defined)) {
4825                 tok = TOK_DEFINED;
4826         }
4827         switch(tok) {
4828         case TOK_PLUS:
4829                 meat(state, index, TOK_PLUS);
4830                 val = munary_expr(state, index);
4831                 val = + val;
4832                 break;
4833         case TOK_MINUS:
4834                 meat(state, index, TOK_MINUS);
4835                 val = munary_expr(state, index);
4836                 val = - val;
4837                 break;
4838         case TOK_TILDE:
4839                 meat(state, index, TOK_BANG);
4840                 val = munary_expr(state, index);
4841                 val = ~ val;
4842                 break;
4843         case TOK_BANG:
4844                 meat(state, index, TOK_BANG);
4845                 val = munary_expr(state, index);
4846                 val = ! val;
4847                 break;
4848         case TOK_DEFINED:
4849         {
4850                 struct hash_entry *ident;
4851                 int parens;
4852                 meat(state, index, TOK_IDENT);
4853                 parens = 0;
4854                 if (mpeek_raw(state, index) == TOK_LPAREN) {
4855                         meat(state, index, TOK_LPAREN);
4856                         parens = 1;
4857                 }
4858                 meat_raw(state, index, TOK_IDENT);
4859                 ident = state->token[index].ident;
4860                 val = ident->sym_define != 0;
4861                 if (parens) {
4862                         meat(state, index, TOK_RPAREN);
4863                 }
4864                 break;
4865         }
4866         default:
4867                 val = mprimary_expr(state, index);
4868                 break;
4869         }
4870         return val;
4871         
4872 }
4873 static long_t mmul_expr(struct compile_state *state, int index)
4874 {
4875         long_t val;
4876         int done;
4877         val = munary_expr(state, index);
4878         do {
4879                 long_t right;
4880                 done = 0;
4881                 switch(mpeek(state, index)) {
4882                 case TOK_STAR:
4883                         meat(state, index, TOK_STAR);
4884                         right = munary_expr(state, index);
4885                         val = val * right;
4886                         break;
4887                 case TOK_DIV:
4888                         meat(state, index, TOK_DIV);
4889                         right = munary_expr(state, index);
4890                         val = val / right;
4891                         break;
4892                 case TOK_MOD:
4893                         meat(state, index, TOK_MOD);
4894                         right = munary_expr(state, index);
4895                         val = val % right;
4896                         break;
4897                 default:
4898                         done = 1;
4899                         break;
4900                 }
4901         } while(!done);
4902
4903         return val;
4904 }
4905
4906 static long_t madd_expr(struct compile_state *state, int index)
4907 {
4908         long_t val;
4909         int done;
4910         val = mmul_expr(state, index);
4911         do {
4912                 long_t right;
4913                 done = 0;
4914                 switch(mpeek(state, index)) {
4915                 case TOK_PLUS:
4916                         meat(state, index, TOK_PLUS);
4917                         right = mmul_expr(state, index);
4918                         val = val + right;
4919                         break;
4920                 case TOK_MINUS:
4921                         meat(state, index, TOK_MINUS);
4922                         right = mmul_expr(state, index);
4923                         val = val - right;
4924                         break;
4925                 default:
4926                         done = 1;
4927                         break;
4928                 }
4929         } while(!done);
4930
4931         return val;
4932 }
4933
4934 static long_t mshift_expr(struct compile_state *state, int index)
4935 {
4936         long_t val;
4937         int done;
4938         val = madd_expr(state, index);
4939         do {
4940                 long_t right;
4941                 done = 0;
4942                 switch(mpeek(state, index)) {
4943                 case TOK_SL:
4944                         meat(state, index, TOK_SL);
4945                         right = madd_expr(state, index);
4946                         val = val << right;
4947                         break;
4948                 case TOK_SR:
4949                         meat(state, index, TOK_SR);
4950                         right = madd_expr(state, index);
4951                         val = val >> right;
4952                         break;
4953                 default:
4954                         done = 1;
4955                         break;
4956                 }
4957         } while(!done);
4958
4959         return val;
4960 }
4961
4962 static long_t mrel_expr(struct compile_state *state, int index)
4963 {
4964         long_t val;
4965         int done;
4966         val = mshift_expr(state, index);
4967         do {
4968                 long_t right;
4969                 done = 0;
4970                 switch(mpeek(state, index)) {
4971                 case TOK_LESS:
4972                         meat(state, index, TOK_LESS);
4973                         right = mshift_expr(state, index);
4974                         val = val < right;
4975                         break;
4976                 case TOK_MORE:
4977                         meat(state, index, TOK_MORE);
4978                         right = mshift_expr(state, index);
4979                         val = val > right;
4980                         break;
4981                 case TOK_LESSEQ:
4982                         meat(state, index, TOK_LESSEQ);
4983                         right = mshift_expr(state, index);
4984                         val = val <= right;
4985                         break;
4986                 case TOK_MOREEQ:
4987                         meat(state, index, TOK_MOREEQ);
4988                         right = mshift_expr(state, index);
4989                         val = val >= right;
4990                         break;
4991                 default:
4992                         done = 1;
4993                         break;
4994                 }
4995         } while(!done);
4996         return val;
4997 }
4998
4999 static long_t meq_expr(struct compile_state *state, int index)
5000 {
5001         long_t val;
5002         int done;
5003         val = mrel_expr(state, index);
5004         do {
5005                 long_t right;
5006                 done = 0;
5007                 switch(mpeek(state, index)) {
5008                 case TOK_EQEQ:
5009                         meat(state, index, TOK_EQEQ);
5010                         right = mrel_expr(state, index);
5011                         val = val == right;
5012                         break;
5013                 case TOK_NOTEQ:
5014                         meat(state, index, TOK_NOTEQ);
5015                         right = mrel_expr(state, index);
5016                         val = val != right;
5017                         break;
5018                 default:
5019                         done = 1;
5020                         break;
5021                 }
5022         } while(!done);
5023         return val;
5024 }
5025
5026 static long_t mand_expr(struct compile_state *state, int index)
5027 {
5028         long_t val;
5029         val = meq_expr(state, index);
5030         while (mpeek(state, index) == TOK_AND) {
5031                 long_t right;
5032                 meat(state, index, TOK_AND);
5033                 right = meq_expr(state, index);
5034                 val = val & right;
5035         }
5036         return val;
5037 }
5038
5039 static long_t mxor_expr(struct compile_state *state, int index)
5040 {
5041         long_t val;
5042         val = mand_expr(state, index);
5043         while (mpeek(state, index) == TOK_XOR) {
5044                 long_t right;
5045                 meat(state, index, TOK_XOR);
5046                 right = mand_expr(state, index);
5047                 val = val ^ right;
5048         }
5049         return val;
5050 }
5051
5052 static long_t mor_expr(struct compile_state *state, int index)
5053 {
5054         long_t val;
5055         val = mxor_expr(state, index);
5056         while (mpeek(state, index) == TOK_OR) {
5057                 long_t right;
5058                 meat(state, index, TOK_OR);
5059                 right = mxor_expr(state, index);
5060                 val = val | right;
5061         }
5062         return val;
5063 }
5064
5065 static long_t mland_expr(struct compile_state *state, int index)
5066 {
5067         long_t val;
5068         val = mor_expr(state, index);
5069         while (mpeek(state, index) == TOK_LOGAND) {
5070                 long_t right;
5071                 meat(state, index, TOK_LOGAND);
5072                 right = mor_expr(state, index);
5073                 val = val && right;
5074         }
5075         return val;
5076 }
5077 static long_t mlor_expr(struct compile_state *state, int index)
5078 {
5079         long_t val;
5080         val = mland_expr(state, index);
5081         while (mpeek(state, index) == TOK_LOGOR) {
5082                 long_t right;
5083                 meat(state, index, TOK_LOGOR);
5084                 right = mland_expr(state, index);
5085                 val = val || right;
5086         }
5087         return val;
5088 }
5089
5090 static long_t mcexpr(struct compile_state *state, int index)
5091 {
5092         return mlor_expr(state, index);
5093 }
5094
5095 static void eat_tokens(struct compile_state *state, int targ_tok)
5096 {
5097         if (state->eat_depth > 0) {
5098                 internal_error(state, 0, "Already eating...");
5099         }
5100         state->eat_depth = state->if_depth;
5101         state->eat_targ = targ_tok;
5102 }
5103 static int if_eat(struct compile_state *state)
5104 {
5105         return state->eat_depth > 0;
5106 }
5107 static int if_value(struct compile_state *state)
5108 {
5109         int index, offset;
5110         index = state->if_depth / CHAR_BIT;
5111         offset = state->if_depth % CHAR_BIT;
5112         return !!(state->if_bytes[index] & (1 << (offset)));
5113 }
5114 static void set_if_value(struct compile_state *state, int value) 
5115 {
5116         int index, offset;
5117         index = state->if_depth / CHAR_BIT;
5118         offset = state->if_depth % CHAR_BIT;
5119
5120         state->if_bytes[index] &= ~(1 << offset);
5121         if (value) {
5122                 state->if_bytes[index] |= (1 << offset);
5123         }
5124 }
5125 static void in_if(struct compile_state *state, const char *name)
5126 {
5127         if (state->if_depth <= 0) {
5128                 error(state, 0, "%s without #if", name);
5129         }
5130 }
5131 static void enter_if(struct compile_state *state)
5132 {
5133         state->if_depth += 1;
5134         if (state->if_depth > MAX_CPP_IF_DEPTH) {
5135                 error(state, 0, "#if depth too great");
5136         }
5137 }
5138 static void reenter_if(struct compile_state *state, const char *name)
5139 {
5140         in_if(state, name);
5141         if ((state->eat_depth == state->if_depth) &&
5142                 (state->eat_targ == TOK_ELSE)) {
5143                 state->eat_depth = 0;
5144                 state->eat_targ = 0;
5145         }
5146 }
5147 static void enter_else(struct compile_state *state, const char *name)
5148 {
5149         in_if(state, name);
5150         if ((state->eat_depth == state->if_depth) &&
5151                 (state->eat_targ == TOK_ELSE)) {
5152                 state->eat_depth = 0;
5153                 state->eat_targ = 0;
5154         }
5155 }
5156 static void exit_if(struct compile_state *state, const char *name)
5157 {
5158         in_if(state, name);
5159         if (state->eat_depth == state->if_depth) {
5160                 state->eat_depth = 0;
5161                 state->eat_targ = 0;
5162         }
5163         state->if_depth -= 1;
5164 }
5165
5166 static void preprocess(struct compile_state *state, int index)
5167 {
5168         /* Doing much more with the preprocessor would require
5169          * a parser and a major restructuring.
5170          * Postpone that for later.
5171          */
5172         struct file_state *file;
5173         struct token *tk;
5174         int line;
5175         int tok;
5176         
5177         file = state->file;
5178         tk = &state->token[index];
5179         state->macro_line = line = file->line;
5180         state->macro_file = file;
5181
5182         next_token(state, tk);
5183         ident_to_macro(state, tk);
5184         if (tk->tok == TOK_IDENT) {
5185                 error(state, 0, "undefined preprocessing directive `%s'",
5186                         tk->ident->name);
5187         }
5188         switch(tk->tok) {
5189         case TOK_LIT_INT:
5190         {
5191                 int override_line;
5192                 override_line = strtoul(tk->val.str, 0, 10);
5193                 next_token(state, tk);
5194                 /* I have a cpp line marker parse it */
5195                 if (tk->tok == TOK_LIT_STRING) {
5196                         const char *token, *base;
5197                         char *name, *dir;
5198                         int name_len, dir_len;
5199                         name = xmalloc(tk->str_len, "report_name");
5200                         token = tk->val.str + 1;
5201                         base = strrchr(token, '/');
5202                         name_len = tk->str_len -2;
5203                         if (base != 0) {
5204                                 dir_len = base - token;
5205                                 base++;
5206                                 name_len -= base - token;
5207                         } else {
5208                                 dir_len = 0;
5209                                 base = token;
5210                         }
5211                         memcpy(name, base, name_len);
5212                         name[name_len] = '\0';
5213                         dir = xmalloc(dir_len + 1, "report_dir");
5214                         memcpy(dir, token, dir_len);
5215                         dir[dir_len] = '\0';
5216                         file->report_line = override_line - 1;
5217                         file->report_name = name;
5218                         file->report_dir = dir;
5219                 }
5220                 break;
5221         }
5222         case TOK_LINE:
5223                 meat(state, index, TOK_LIT_INT);
5224                 file->report_line = strtoul(tk->val.str, 0, 10) -1;
5225                 if (mpeek(state, index) == TOK_LIT_STRING) {
5226                         const char *token, *base;
5227                         char *name, *dir;
5228                         int name_len, dir_len;
5229                         meat(state, index, TOK_LIT_STRING);
5230                         name = xmalloc(tk->str_len, "report_name");
5231                         token = tk->val.str + 1;
5232                         base = strrchr(token, '/');
5233                         name_len = tk->str_len - 2;
5234                         if (base != 0) {
5235                                 dir_len = base - token;
5236                                 base++;
5237                                 name_len -= base - token;
5238                         } else {
5239                                 dir_len = 0;
5240                                 base = token;
5241                         }
5242                         memcpy(name, base, name_len);
5243                         name[name_len] = '\0';
5244                         dir = xmalloc(dir_len + 1, "report_dir");
5245                         memcpy(dir, token, dir_len);
5246                         dir[dir_len] = '\0';
5247                         file->report_name = name;
5248                         file->report_dir = dir;
5249                 }
5250                 break;
5251         case TOK_UNDEF:
5252         {
5253                 struct hash_entry *ident;
5254                 if (if_eat(state))  /* quit early when #if'd out */
5255                         break;
5256
5257                 meat_raw(state, index, TOK_IDENT);
5258                 ident = tk->ident;
5259
5260                 undef_macro(state, ident);
5261                 break;
5262         }
5263         case TOK_PRAGMA:
5264                 if (if_eat(state))  /* quit early when #if'd out */
5265                         break;
5266                 warning(state, 0, "Ignoring preprocessor directive: %s", 
5267                         tk->ident->name);
5268                 break;
5269         case TOK_ELIF:
5270                 reenter_if(state, "#elif");
5271                 if (if_eat(state))   /* quit early when #if'd out */
5272                         break;
5273                 /* If the #if was taken the #elif just disables the following code */
5274                 if (if_value(state)) {
5275                         eat_tokens(state, TOK_ENDIF);
5276                 }
5277                 /* If the previous #if was not taken see if the #elif enables the 
5278                  * trailing code.
5279                  */
5280                 else {
5281                         set_if_value(state, mcexpr(state, index) != 0);
5282                         if (!if_value(state)) {
5283                                 eat_tokens(state, TOK_ELSE);
5284                         }
5285                 }
5286                 break;
5287         case TOK_IF:
5288                 enter_if(state);
5289                 if (if_eat(state))  /* quit early when #if'd out */
5290                         break;
5291                 set_if_value(state, mcexpr(state, index) != 0);
5292                 if (!if_value(state)) {
5293                         eat_tokens(state, TOK_ELSE);
5294                 }
5295                 break;
5296         case TOK_IFNDEF:
5297                 enter_if(state);
5298                 if (if_eat(state))  /* quit early when #if'd out */
5299                         break;
5300                 next_token(state, tk);
5301                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
5302                         error(state, 0, "Invalid macro name");
5303                 }
5304                 set_if_value(state, tk->ident->sym_define == 0);
5305                 if (!if_value(state)) {
5306                         eat_tokens(state, TOK_ELSE);
5307                 }
5308                 break;
5309         case TOK_IFDEF:
5310                 enter_if(state);
5311                 if (if_eat(state))  /* quit early when #if'd out */
5312                         break;
5313                 next_token(state, tk);
5314                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
5315                         error(state, 0, "Invalid macro name");
5316                 }
5317                 set_if_value(state, tk->ident->sym_define != 0);
5318                 if (!if_value(state)) {
5319                         eat_tokens(state, TOK_ELSE);
5320                 }
5321                 break;
5322         case TOK_ELSE:
5323                 enter_else(state, "#else");
5324                 if (!if_eat(state) && if_value(state)) {
5325                         eat_tokens(state, TOK_ENDIF);
5326                 }
5327                 break;
5328         case TOK_ENDIF:
5329                 exit_if(state, "#endif");
5330                 break;
5331         case TOK_DEFINE:
5332         {
5333                 struct hash_entry *ident;
5334                 struct macro_arg *args, **larg;
5335                 const char *start, *mstart, *ptr;
5336
5337                 if (if_eat(state))  /* quit early when #if'd out */
5338                         break;
5339
5340                 meat_raw(state, index, TOK_IDENT);
5341                 ident = tk->ident;
5342                 args = 0;
5343                 larg = &args;
5344
5345                 /* Remember the start of the macro */
5346                 start = file->pos;
5347
5348                 /* Find the end of the line. */
5349                 for(ptr = start; *ptr != '\n'; ptr++)  
5350                         ;
5351
5352                 /* remove the trailing whitespace */
5353                 while(spacep(*ptr)) {
5354                         ptr--;
5355                 }
5356
5357                 /* Remove leading whitespace */
5358                 while(spacep(*start) && (start < ptr)) {
5359                         start++;
5360                 }
5361                 /* Remember where the macro starts */
5362                 mstart = start;
5363
5364                 /* Parse macro parameters */
5365                 if (lparen_peek(state, state->file)) {
5366                         meat_raw(state, index, TOK_LPAREN);
5367                         
5368                         for(;;) {
5369                                 struct macro_arg *narg, *arg;
5370                                 struct hash_entry *aident;
5371                                 int tok;
5372
5373                                 tok = mpeek_raw(state, index);
5374                                 if (!args && (tok == TOK_RPAREN)) {
5375                                         break;
5376                                 }
5377                                 else if (tok == TOK_DOTS) {
5378                                         meat_raw(state, index, TOK_DOTS);
5379                                         aident = state->i___VA_ARGS__;
5380                                 } 
5381                                 else {
5382                                         meat_raw(state, index, TOK_IDENT);
5383                                         aident = tk->ident;
5384                                 }
5385                                 
5386                                 narg = xcmalloc(sizeof(*arg), "macro arg");
5387                                 narg->ident = aident;
5388
5389                                 /* Verify I don't have a duplicate identifier */
5390                                 for(arg = args; arg; arg = arg->next) {
5391                                         if (arg->ident == narg->ident) {
5392                                                 error(state, 0, "Duplicate macro arg `%s'",
5393                                                         narg->ident->name);
5394                                         }
5395                                 }
5396                                 /* Add the new argument to the end of the list */
5397                                 *larg = narg;
5398                                 larg = &narg->next;
5399
5400                                 if ((aident == state->i___VA_ARGS__) ||
5401                                         (mpeek(state, index) != TOK_COMMA)) {
5402                                         break;
5403                                 }
5404                                 meat_raw(state, index, TOK_COMMA);
5405                         }
5406                         meat_raw(state, index, TOK_RPAREN);
5407
5408                         /* Get the start of the macro body */
5409                         mstart = file->pos;
5410
5411                         /* Remove leading whitespace */
5412                         while(spacep(*mstart) && (mstart < ptr)) {
5413                                 mstart++;
5414                         }
5415                 }
5416                 define_macro(state, ident, start, ptr - start + 1, 
5417                         mstart - start, args);
5418                 break;
5419         }
5420         case TOK_ERROR:
5421         {
5422                 const char *end;
5423                 int len;
5424                 
5425                 /* Find the end of the line */
5426                 for(end = file->pos; *end != '\n'; end++)
5427                         ;
5428                 len = (end - file->pos);
5429                 if (!if_eat(state)) {
5430                         error(state, 0, "%*.*s", len, len, file->pos);
5431                 }
5432                 file->pos = end;
5433                 break;
5434         }
5435         case TOK_WARNING:
5436         {
5437                 const char *end;
5438                 int len;
5439                 
5440                 /* Find the end of the line */
5441                 for(end = file->pos; *end != '\n'; end++)
5442                         ;
5443                 len = (end - file->pos);
5444                 if (!if_eat(state)) {
5445                         warning(state, 0, "%*.*s", len, len, file->pos);
5446                 }
5447                 file->pos = end;
5448                 break;
5449         }
5450         case TOK_INCLUDE:
5451         {
5452                 char *name;
5453                 const char *ptr;
5454                 int local;
5455                 local = 0;
5456                 name = 0;
5457                 next_token(state, tk);
5458                 if (tk->tok == TOK_LIT_STRING) {
5459                         const char *token;
5460                         int name_len;
5461                         name = xmalloc(tk->str_len, "include");
5462                         token = tk->val.str +1;
5463                         name_len = tk->str_len -2;
5464                         if (*token == '"') {
5465                                 token++;
5466                                 name_len--;
5467                         }
5468                         memcpy(name, token, name_len);
5469                         name[name_len] = '\0';
5470                         local = 1;
5471                 }
5472                 else if (tk->tok == TOK_LESS) {
5473                         const char *start, *end;
5474                         start = file->pos;
5475                         for(end = start; *end != '\n'; end++) {
5476                                 if (*end == '>') {
5477                                         break;
5478                                 }
5479                         }
5480                         if (*end == '\n') {
5481                                 error(state, 0, "Unterminated included directive");
5482                         }
5483                         name = xmalloc(end - start + 1, "include");
5484                         memcpy(name, start, end - start);
5485                         name[end - start] = '\0';
5486                         file->pos = end +1;
5487                         local = 0;
5488                 }
5489                 else {
5490                         error(state, 0, "Invalid include directive");
5491                 }
5492                 /* Error if there are any characters after the include */
5493                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
5494                         switch(*ptr) {
5495                         case ' ':
5496                         case '\t':
5497                         case '\v':
5498                                 break;
5499                         default:
5500                                 error(state, 0, "garbage after include directive");
5501                         }
5502                 }
5503                 if (!if_eat(state)) {
5504                         compile_file(state, name, local);
5505                 }
5506                 xfree(name);
5507                 next_token(state, tk);
5508                 return;
5509         }
5510         default:
5511                 /* Ignore # without a following ident */
5512                 if (tk->tok == TOK_IDENT) {
5513                         error(state, 0, "Invalid preprocessor directive: %s", 
5514                                 tk->ident->name);
5515                 }
5516                 break;
5517         }
5518         /* Consume the rest of the macro line */
5519         do {
5520                 tok = mpeek_raw(state, index);
5521                 meat_raw(state, index, tok);
5522         } while(tok != TOK_EOF);
5523         return;
5524 }
5525
5526 static void token(struct compile_state *state, int index)
5527 {
5528         struct file_state *file;
5529         struct token *tk;
5530         int rescan;
5531
5532         tk = &state->token[index];
5533         next_token(state, tk);
5534         do {
5535                 rescan = 0;
5536                 file = state->file;
5537                 if (tk->tok == TOK_EOF && file->prev) {
5538                         state->file = file->prev;
5539                         /* file->basename is used keep it */
5540                         xfree(file->dirname);
5541                         xfree(file->buf);
5542                         xfree(file);
5543                         next_token(state, tk);
5544                         rescan = 1;
5545                 }
5546                 else if (tk->tok == TOK_MACRO) {
5547                         preprocess(state, index);
5548                         rescan = 1;
5549                 }
5550                 else if (tk->ident && tk->ident->sym_define) {
5551                         rescan = compile_macro(state, &state->file, tk);
5552                         if (rescan) {
5553                                 next_token(state, tk);
5554                         }
5555                 }
5556                 else if (if_eat(state)) {
5557                         next_token(state, tk);
5558                         rescan = 1;
5559                 }
5560         } while(rescan);
5561 }
5562
5563 static int peek(struct compile_state *state)
5564 {
5565         if (state->token[1].tok == -1) {
5566                 token(state, 1);
5567         }
5568         return state->token[1].tok;
5569 }
5570
5571 static int peek2(struct compile_state *state)
5572 {
5573         if (state->token[1].tok == -1) {
5574                 token(state, 1);
5575         }
5576         if (state->token[2].tok == -1) {
5577                 token(state, 2);
5578         }
5579         return state->token[2].tok;
5580 }
5581
5582 static void eat(struct compile_state *state, int tok)
5583 {
5584         int i;
5585         peek(state);
5586         check_tok(state, &state->token[1], tok);
5587
5588         /* Free the old token value */
5589         if (state->token[0].str_len) {
5590                 xfree((void *)(state->token[0].val.str));
5591         }
5592         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
5593                 state->token[i] = state->token[i + 1];
5594         }
5595         memset(&state->token[i], 0, sizeof(state->token[i]));
5596         state->token[i].tok = -1;
5597 }
5598
5599 static void compile_file(struct compile_state *state, const char *filename, int local)
5600 {
5601         char cwd[MAX_CWD_SIZE];
5602         const char *subdir, *base;
5603         int subdir_len;
5604         struct file_state *file;
5605         char *basename;
5606         file = xmalloc(sizeof(*file), "file_state");
5607
5608         base = strrchr(filename, '/');
5609         subdir = filename;
5610         if (base != 0) {
5611                 subdir_len = base - filename;
5612                 base++;
5613         }
5614         else {
5615                 base = filename;
5616                 subdir_len = 0;
5617         }
5618         basename = xmalloc(strlen(base) +1, "basename");
5619         strcpy(basename, base);
5620         file->basename = basename;
5621
5622         if (getcwd(cwd, sizeof(cwd)) == 0) {
5623                 die("cwd buffer to small");
5624         }
5625         if (subdir[0] == '/') {
5626                 file->dirname = xmalloc(subdir_len + 1, "dirname");
5627                 memcpy(file->dirname, subdir, subdir_len);
5628                 file->dirname[subdir_len] = '\0';
5629         }
5630         else {
5631                 const char *dir;
5632                 int dirlen;
5633                 const char **path;
5634                 /* Find the appropriate directory... */
5635                 dir = 0;
5636                 if (!state->file && exists(cwd, filename)) {
5637                         dir = cwd;
5638                 }
5639                 if (local && state->file && exists(state->file->dirname, filename)) {
5640                         dir = state->file->dirname;
5641                 }
5642                 for(path = state->compiler->include_paths; !dir && *path; path++) {
5643                         if (exists(*path, filename)) {
5644                                 dir = *path;
5645                         }
5646                 }
5647                 if (!dir) {
5648                         error(state, 0, "Cannot find `%s'\n", filename);
5649                 }
5650                 dirlen = strlen(dir);
5651                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5652                 memcpy(file->dirname, dir, dirlen);
5653                 file->dirname[dirlen] = '/';
5654                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5655                 file->dirname[dirlen + 1 + subdir_len] = '\0';
5656         }
5657         file->buf = slurp_file(file->dirname, file->basename, &file->size);
5658
5659         file->pos = file->buf;
5660         file->line_start = file->pos;
5661         file->line = 1;
5662
5663         file->report_line = 1;
5664         file->report_name = file->basename;
5665         file->report_dir  = file->dirname;
5666
5667         file->prev = state->file;
5668         state->file = file;
5669         
5670         process_trigraphs(state);
5671         splice_lines(state);
5672 }
5673
5674 /* Type helper functions */
5675
5676 static struct type *new_type(
5677         unsigned int type, struct type *left, struct type *right)
5678 {
5679         struct type *result;
5680         result = xmalloc(sizeof(*result), "type");
5681         result->type = type;
5682         result->left = left;
5683         result->right = right;
5684         result->field_ident = 0;
5685         result->type_ident = 0;
5686         result->elements = 0;
5687         return result;
5688 }
5689
5690 static struct type *clone_type(unsigned int specifiers, struct type *old)
5691 {
5692         struct type *result;
5693         result = xmalloc(sizeof(*result), "type");
5694         memcpy(result, old, sizeof(*result));
5695         result->type &= TYPE_MASK;
5696         result->type |= specifiers;
5697         return result;
5698 }
5699
5700 static struct type *dup_type(struct compile_state *state, struct type *orig)
5701 {
5702         struct type *new;
5703         new = xcmalloc(sizeof(*new), "type");
5704         new->type = orig->type;
5705         new->field_ident = orig->field_ident;
5706         new->type_ident  = orig->type_ident;
5707         new->elements    = orig->elements;
5708         if (orig->left) {
5709                 new->left = dup_type(state, orig->left);
5710         }
5711         if (orig->right) {
5712                 new->right = dup_type(state, orig->right);
5713         }
5714         return new;
5715 }
5716
5717
5718 static struct type *invalid_type(struct compile_state *state, struct type *type)
5719 {
5720         struct type *invalid, *member;
5721         invalid = 0;
5722         if (!type) {
5723                 internal_error(state, 0, "type missing?");
5724         }
5725         switch(type->type & TYPE_MASK) {
5726         case TYPE_VOID:
5727         case TYPE_CHAR:         case TYPE_UCHAR:
5728         case TYPE_SHORT:        case TYPE_USHORT:
5729         case TYPE_INT:          case TYPE_UINT:
5730         case TYPE_LONG:         case TYPE_ULONG:
5731         case TYPE_LLONG:        case TYPE_ULLONG:
5732         case TYPE_POINTER:
5733         case TYPE_ENUM:
5734                 break;
5735         case TYPE_BITFIELD:
5736                 invalid = invalid_type(state, type->left);
5737                 break;
5738         case TYPE_ARRAY:
5739                 invalid = invalid_type(state, type->left);
5740                 break;
5741         case TYPE_STRUCT:
5742         case TYPE_TUPLE:
5743                 member = type->left;
5744                 while(member && (invalid == 0) && 
5745                         ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5746                         invalid = invalid_type(state, member->left);
5747                         member = member->right;
5748                 }
5749                 if (!invalid) {
5750                         invalid = invalid_type(state, member);
5751                 }
5752                 break;
5753         case TYPE_UNION:
5754         case TYPE_JOIN:
5755                 member = type->left;
5756                 while(member && (invalid == 0) &&
5757                         ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5758                         invalid = invalid_type(state, member->left);
5759                         member = member->right;
5760                 }
5761                 if (!invalid) {
5762                         invalid = invalid_type(state, member);
5763                 }
5764                 break;
5765         default:
5766                 invalid = type;
5767                 break;
5768         }
5769         return invalid;
5770         
5771 }
5772
5773 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
5774 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5775 static inline ulong_t mask_uint(ulong_t x)
5776 {
5777         if (SIZEOF_INT < SIZEOF_LONG) {
5778                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT))) -1;
5779                 x &= mask;
5780         }
5781         return x;
5782 }
5783 #define MASK_UINT(X)      (mask_uint(X))
5784 #define MASK_ULONG(X)    (X)
5785
5786 static struct type void_type    = { .type  = TYPE_VOID };
5787 static struct type char_type    = { .type  = TYPE_CHAR };
5788 static struct type uchar_type   = { .type  = TYPE_UCHAR };
5789 static struct type short_type   = { .type  = TYPE_SHORT };
5790 static struct type ushort_type  = { .type  = TYPE_USHORT };
5791 static struct type int_type     = { .type  = TYPE_INT };
5792 static struct type uint_type    = { .type  = TYPE_UINT };
5793 static struct type long_type    = { .type  = TYPE_LONG };
5794 static struct type ulong_type   = { .type  = TYPE_ULONG };
5795 static struct type unknown_type = { .type  = TYPE_UNKNOWN };
5796
5797 static struct type void_ptr_type  = {
5798         .type = TYPE_POINTER,
5799         .left = &void_type,
5800 };
5801
5802 static struct type void_func_type = { 
5803         .type  = TYPE_FUNCTION,
5804         .left  = &void_type,
5805         .right = &void_type,
5806 };
5807
5808 static size_t bits_to_bytes(size_t size)
5809 {
5810         return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5811 }
5812
5813 static struct triple *variable(struct compile_state *state, struct type *type)
5814 {
5815         struct triple *result;
5816         if ((type->type & STOR_MASK) != STOR_PERM) {
5817                 result = triple(state, OP_ADECL, type, 0, 0);
5818                 generate_lhs_pieces(state, result);
5819         }
5820         else {
5821                 result = triple(state, OP_SDECL, type, 0, 0);
5822         }
5823         return result;
5824 }
5825
5826 static void stor_of(FILE *fp, struct type *type)
5827 {
5828         switch(type->type & STOR_MASK) {
5829         case STOR_AUTO:
5830                 fprintf(fp, "auto ");
5831                 break;
5832         case STOR_STATIC:
5833                 fprintf(fp, "static ");
5834                 break;
5835         case STOR_LOCAL:
5836                 fprintf(fp, "local ");
5837                 break;
5838         case STOR_EXTERN:
5839                 fprintf(fp, "extern ");
5840                 break;
5841         case STOR_REGISTER:
5842                 fprintf(fp, "register ");
5843                 break;
5844         case STOR_TYPEDEF:
5845                 fprintf(fp, "typedef ");
5846                 break;
5847         case STOR_INLINE | STOR_LOCAL:
5848                 fprintf(fp, "inline ");
5849                 break;
5850         case STOR_INLINE | STOR_STATIC:
5851                 fprintf(fp, "static inline");
5852                 break;
5853         case STOR_INLINE | STOR_EXTERN:
5854                 fprintf(fp, "extern inline");
5855                 break;
5856         default:
5857                 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5858                 break;
5859         }
5860 }
5861 static void qual_of(FILE *fp, struct type *type)
5862 {
5863         if (type->type & QUAL_CONST) {
5864                 fprintf(fp, " const");
5865         }
5866         if (type->type & QUAL_VOLATILE) {
5867                 fprintf(fp, " volatile");
5868         }
5869         if (type->type & QUAL_RESTRICT) {
5870                 fprintf(fp, " restrict");
5871         }
5872 }
5873
5874 static void name_of(FILE *fp, struct type *type)
5875 {
5876         unsigned int base_type;
5877         base_type = type->type & TYPE_MASK;
5878         if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5879                 stor_of(fp, type);
5880         }
5881         switch(base_type) {
5882         case TYPE_VOID:
5883                 fprintf(fp, "void");
5884                 qual_of(fp, type);
5885                 break;
5886         case TYPE_CHAR:
5887                 fprintf(fp, "signed char");
5888                 qual_of(fp, type);
5889                 break;
5890         case TYPE_UCHAR:
5891                 fprintf(fp, "unsigned char");
5892                 qual_of(fp, type);
5893                 break;
5894         case TYPE_SHORT:
5895                 fprintf(fp, "signed short");
5896                 qual_of(fp, type);
5897                 break;
5898         case TYPE_USHORT:
5899                 fprintf(fp, "unsigned short");
5900                 qual_of(fp, type);
5901                 break;
5902         case TYPE_INT:
5903                 fprintf(fp, "signed int");
5904                 qual_of(fp, type);
5905                 break;
5906         case TYPE_UINT:
5907                 fprintf(fp, "unsigned int");
5908                 qual_of(fp, type);
5909                 break;
5910         case TYPE_LONG:
5911                 fprintf(fp, "signed long");
5912                 qual_of(fp, type);
5913                 break;
5914         case TYPE_ULONG:
5915                 fprintf(fp, "unsigned long");
5916                 qual_of(fp, type);
5917                 break;
5918         case TYPE_POINTER:
5919                 name_of(fp, type->left);
5920                 fprintf(fp, " * ");
5921                 qual_of(fp, type);
5922                 break;
5923         case TYPE_PRODUCT:
5924                 name_of(fp, type->left);
5925                 fprintf(fp, ", ");
5926                 name_of(fp, type->right);
5927                 break;
5928         case TYPE_OVERLAP:
5929                 name_of(fp, type->left);
5930                 fprintf(fp, ",| ");
5931                 name_of(fp, type->right);
5932                 break;
5933         case TYPE_ENUM:
5934                 fprintf(fp, "enum %s", 
5935                         (type->type_ident)? type->type_ident->name : "");
5936                 qual_of(fp, type);
5937                 break;
5938         case TYPE_STRUCT:
5939                 fprintf(fp, "struct %s { ", 
5940                         (type->type_ident)? type->type_ident->name : "");
5941                 name_of(fp, type->left);
5942                 fprintf(fp, " } ");
5943                 qual_of(fp, type);
5944                 break;
5945         case TYPE_UNION:
5946                 fprintf(fp, "union %s { ", 
5947                         (type->type_ident)? type->type_ident->name : "");
5948                 name_of(fp, type->left);
5949                 fprintf(fp, " } ");
5950                 qual_of(fp, type);
5951                 break;
5952         case TYPE_FUNCTION:
5953                 name_of(fp, type->left);
5954                 fprintf(fp, " (*)(");
5955                 name_of(fp, type->right);
5956                 fprintf(fp, ")");
5957                 break;
5958         case TYPE_ARRAY:
5959                 name_of(fp, type->left);
5960                 fprintf(fp, " [%ld]", (long)(type->elements));
5961                 break;
5962         case TYPE_TUPLE:
5963                 fprintf(fp, "tuple { "); 
5964                 name_of(fp, type->left);
5965                 fprintf(fp, " } ");
5966                 qual_of(fp, type);
5967                 break;
5968         case TYPE_JOIN:
5969                 fprintf(fp, "join { ");
5970                 name_of(fp, type->left);
5971                 fprintf(fp, " } ");
5972                 qual_of(fp, type);
5973                 break;
5974         case TYPE_BITFIELD:
5975                 name_of(fp, type->left);
5976                 fprintf(fp, " : %d ", type->elements);
5977                 qual_of(fp, type);
5978                 break;
5979         case TYPE_UNKNOWN:
5980                 fprintf(fp, "unknown_t");
5981                 break;
5982         default:
5983                 fprintf(fp, "????: %x", base_type);
5984                 break;
5985         }
5986         if (type->field_ident && type->field_ident->name) {
5987                 fprintf(fp, " .%s", type->field_ident->name);
5988         }
5989 }
5990
5991 static size_t align_of(struct compile_state *state, struct type *type)
5992 {
5993         size_t align;
5994         align = 0;
5995         switch(type->type & TYPE_MASK) {
5996         case TYPE_VOID:
5997                 align = 1;
5998                 break;
5999         case TYPE_BITFIELD:
6000                 align = 1;
6001                 break;
6002         case TYPE_CHAR:
6003         case TYPE_UCHAR:
6004                 align = ALIGNOF_CHAR;
6005                 break;
6006         case TYPE_SHORT:
6007         case TYPE_USHORT:
6008                 align = ALIGNOF_SHORT;
6009                 break;
6010         case TYPE_INT:
6011         case TYPE_UINT:
6012         case TYPE_ENUM:
6013                 align = ALIGNOF_INT;
6014                 break;
6015         case TYPE_LONG:
6016         case TYPE_ULONG:
6017                 align = ALIGNOF_LONG;
6018                 break;
6019         case TYPE_POINTER:
6020                 align = ALIGNOF_POINTER;
6021                 break;
6022         case TYPE_PRODUCT:
6023         case TYPE_OVERLAP:
6024         {
6025                 size_t left_align, right_align;
6026                 left_align  = align_of(state, type->left);
6027                 right_align = align_of(state, type->right);
6028                 align = (left_align >= right_align) ? left_align : right_align;
6029                 break;
6030         }
6031         case TYPE_ARRAY:
6032                 align = align_of(state, type->left);
6033                 break;
6034         case TYPE_STRUCT:
6035         case TYPE_TUPLE:
6036         case TYPE_UNION:
6037         case TYPE_JOIN:
6038                 align = align_of(state, type->left);
6039                 break;
6040         default:
6041                 error(state, 0, "alignof not yet defined for type\n");
6042                 break;
6043         }
6044         return align;
6045 }
6046
6047 static size_t reg_align_of(struct compile_state *state, struct type *type)
6048 {
6049         size_t align;
6050         align = 0;
6051         switch(type->type & TYPE_MASK) {
6052         case TYPE_VOID:
6053                 align = 1;
6054                 break;
6055         case TYPE_BITFIELD:
6056                 align = 1;
6057                 break;
6058         case TYPE_CHAR:
6059         case TYPE_UCHAR:
6060                 align = REG_ALIGNOF_CHAR;
6061                 break;
6062         case TYPE_SHORT:
6063         case TYPE_USHORT:
6064                 align = REG_ALIGNOF_SHORT;
6065                 break;
6066         case TYPE_INT:
6067         case TYPE_UINT:
6068         case TYPE_ENUM:
6069                 align = REG_ALIGNOF_INT;
6070                 break;
6071         case TYPE_LONG:
6072         case TYPE_ULONG:
6073                 align = REG_ALIGNOF_LONG;
6074                 break;
6075         case TYPE_POINTER:
6076                 align = REG_ALIGNOF_POINTER;
6077                 break;
6078         case TYPE_PRODUCT:
6079         case TYPE_OVERLAP:
6080         {
6081                 size_t left_align, right_align;
6082                 left_align  = reg_align_of(state, type->left);
6083                 right_align = reg_align_of(state, type->right);
6084                 align = (left_align >= right_align) ? left_align : right_align;
6085                 break;
6086         }
6087         case TYPE_ARRAY:
6088                 align = reg_align_of(state, type->left);
6089                 break;
6090         case TYPE_STRUCT:
6091         case TYPE_UNION:
6092         case TYPE_TUPLE:
6093         case TYPE_JOIN:
6094                 align = reg_align_of(state, type->left);
6095                 break;
6096         default:
6097                 error(state, 0, "alignof not yet defined for type\n");
6098                 break;
6099         }
6100         return align;
6101 }
6102
6103 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
6104 {
6105         return bits_to_bytes(align_of(state, type));
6106 }
6107 static size_t size_of(struct compile_state *state, struct type *type);
6108 static size_t reg_size_of(struct compile_state *state, struct type *type);
6109
6110 static size_t needed_padding(struct compile_state *state, 
6111         struct type *type, size_t offset)
6112 {
6113         size_t padding, align;
6114         align = align_of(state, type);
6115         /* Align to the next machine word if the bitfield does completely
6116          * fit into the current word.
6117          */
6118         if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
6119                 size_t size;
6120                 size = size_of(state, type);
6121                 if ((offset + type->elements)/size != offset/size) {
6122                         align = size;
6123                 }
6124         }
6125         padding = 0;
6126         if (offset % align) {
6127                 padding = align - (offset % align);
6128         }
6129         return padding;
6130 }
6131
6132 static size_t reg_needed_padding(struct compile_state *state, 
6133         struct type *type, size_t offset)
6134 {
6135         size_t padding, align;
6136         align = reg_align_of(state, type);
6137         /* Align to the next register word if the bitfield does completely
6138          * fit into the current register.
6139          */
6140         if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
6141                 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG))) 
6142         {
6143                 align = REG_SIZEOF_REG;
6144         }
6145         padding = 0;
6146         if (offset % align) {
6147                 padding = align - (offset % align);
6148         }
6149         return padding;
6150 }
6151
6152 static size_t size_of(struct compile_state *state, struct type *type)
6153 {
6154         size_t size;
6155         size = 0;
6156         switch(type->type & TYPE_MASK) {
6157         case TYPE_VOID:
6158                 size = 0;
6159                 break;
6160         case TYPE_BITFIELD:
6161                 size = type->elements;
6162                 break;
6163         case TYPE_CHAR:
6164         case TYPE_UCHAR:
6165                 size = SIZEOF_CHAR;
6166                 break;
6167         case TYPE_SHORT:
6168         case TYPE_USHORT:
6169                 size = SIZEOF_SHORT;
6170                 break;
6171         case TYPE_INT:
6172         case TYPE_UINT:
6173         case TYPE_ENUM:
6174                 size = SIZEOF_INT;
6175                 break;
6176         case TYPE_LONG:
6177         case TYPE_ULONG:
6178                 size = SIZEOF_LONG;
6179                 break;
6180         case TYPE_POINTER:
6181                 size = SIZEOF_POINTER;
6182                 break;
6183         case TYPE_PRODUCT:
6184         {
6185                 size_t pad;
6186                 size = 0;
6187                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6188                         pad = needed_padding(state, type->left, size);
6189                         size = size + pad + size_of(state, type->left);
6190                         type = type->right;
6191                 }
6192                 pad = needed_padding(state, type, size);
6193                 size = size + pad + size_of(state, type);
6194                 break;
6195         }
6196         case TYPE_OVERLAP:
6197         {
6198                 size_t size_left, size_right;
6199                 size_left = size_of(state, type->left);
6200                 size_right = size_of(state, type->right);
6201                 size = (size_left >= size_right)? size_left : size_right;
6202                 break;
6203         }
6204         case TYPE_ARRAY:
6205                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6206                         internal_error(state, 0, "Invalid array type");
6207                 } else {
6208                         size = size_of(state, type->left) * type->elements;
6209                 }
6210                 break;
6211         case TYPE_STRUCT:
6212         case TYPE_TUPLE:
6213         {
6214                 size_t pad;
6215                 size = size_of(state, type->left);
6216                 /* Pad structures so their size is a multiples of their alignment */
6217                 pad = needed_padding(state, type, size);
6218                 size = size + pad;
6219                 break;
6220         }
6221         case TYPE_UNION:
6222         case TYPE_JOIN:
6223         {
6224                 size_t pad;
6225                 size = size_of(state, type->left);
6226                 /* Pad unions so their size is a multiple of their alignment */
6227                 pad = needed_padding(state, type, size);
6228                 size = size + pad;
6229                 break;
6230         }
6231         default:
6232                 internal_error(state, 0, "sizeof not yet defined for type");
6233                 break;
6234         }
6235         return size;
6236 }
6237
6238 static size_t reg_size_of(struct compile_state *state, struct type *type)
6239 {
6240         size_t size;
6241         size = 0;
6242         switch(type->type & TYPE_MASK) {
6243         case TYPE_VOID:
6244                 size = 0;
6245                 break;
6246         case TYPE_BITFIELD:
6247                 size = type->elements;
6248                 break;
6249         case TYPE_CHAR:
6250         case TYPE_UCHAR:
6251                 size = REG_SIZEOF_CHAR;
6252                 break;
6253         case TYPE_SHORT:
6254         case TYPE_USHORT:
6255                 size = REG_SIZEOF_SHORT;
6256                 break;
6257         case TYPE_INT:
6258         case TYPE_UINT:
6259         case TYPE_ENUM:
6260                 size = REG_SIZEOF_INT;
6261                 break;
6262         case TYPE_LONG:
6263         case TYPE_ULONG:
6264                 size = REG_SIZEOF_LONG;
6265                 break;
6266         case TYPE_POINTER:
6267                 size = REG_SIZEOF_POINTER;
6268                 break;
6269         case TYPE_PRODUCT:
6270         {
6271                 size_t pad;
6272                 size = 0;
6273                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6274                         pad = reg_needed_padding(state, type->left, size);
6275                         size = size + pad + reg_size_of(state, type->left);
6276                         type = type->right;
6277                 }
6278                 pad = reg_needed_padding(state, type, size);
6279                 size = size + pad + reg_size_of(state, type);
6280                 break;
6281         }
6282         case TYPE_OVERLAP:
6283         {
6284                 size_t size_left, size_right;
6285                 size_left  = reg_size_of(state, type->left);
6286                 size_right = reg_size_of(state, type->right);
6287                 size = (size_left >= size_right)? size_left : size_right;
6288                 break;
6289         }
6290         case TYPE_ARRAY:
6291                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6292                         internal_error(state, 0, "Invalid array type");
6293                 } else {
6294                         size = reg_size_of(state, type->left) * type->elements;
6295                 }
6296                 break;
6297         case TYPE_STRUCT:
6298         case TYPE_TUPLE:
6299         {
6300                 size_t pad;
6301                 size = reg_size_of(state, type->left);
6302                 /* Pad structures so their size is a multiples of their alignment */
6303                 pad = reg_needed_padding(state, type, size);
6304                 size = size + pad;
6305                 break;
6306         }
6307         case TYPE_UNION:
6308         case TYPE_JOIN:
6309         {
6310                 size_t pad;
6311                 size = reg_size_of(state, type->left);
6312                 /* Pad unions so their size is a multiple of their alignment */
6313                 pad = reg_needed_padding(state, type, size);
6314                 size = size + pad;
6315                 break;
6316         }
6317         default:
6318                 internal_error(state, 0, "sizeof not yet defined for type");
6319                 break;
6320         }
6321         return size;
6322 }
6323
6324 static size_t registers_of(struct compile_state *state, struct type *type)
6325 {
6326         size_t registers;
6327         registers = reg_size_of(state, type);
6328         registers += REG_SIZEOF_REG - 1;
6329         registers /= REG_SIZEOF_REG;
6330         return registers;
6331 }
6332
6333 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6334 {
6335         return bits_to_bytes(size_of(state, type));
6336 }
6337
6338 static size_t field_offset(struct compile_state *state, 
6339         struct type *type, struct hash_entry *field)
6340 {
6341         struct type *member;
6342         size_t size;
6343
6344         size = 0;
6345         member = 0;
6346         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6347                 member = type->left;
6348                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6349                         size += needed_padding(state, member->left, size);
6350                         if (member->left->field_ident == field) {
6351                                 member = member->left;
6352                                 break;
6353                         }
6354                         size += size_of(state, member->left);
6355                         member = member->right;
6356                 }
6357                 size += needed_padding(state, member, size);
6358         }
6359         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6360                 member = type->left;
6361                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6362                         if (member->left->field_ident == field) {
6363                                 member = member->left;
6364                                 break;
6365                         }
6366                         member = member->right;
6367                 }
6368         }
6369         else {
6370                 internal_error(state, 0, "field_offset only works on structures and unions");
6371         }
6372
6373         if (!member || (member->field_ident != field)) {
6374                 error(state, 0, "member %s not present", field->name);
6375         }
6376         return size;
6377 }
6378
6379 static size_t field_reg_offset(struct compile_state *state, 
6380         struct type *type, struct hash_entry *field)
6381 {
6382         struct type *member;
6383         size_t size;
6384
6385         size = 0;
6386         member = 0;
6387         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6388                 member = type->left;
6389                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6390                         size += reg_needed_padding(state, member->left, size);
6391                         if (member->left->field_ident == field) {
6392                                 member = member->left;
6393                                 break;
6394                         }
6395                         size += reg_size_of(state, member->left);
6396                         member = member->right;
6397                 }
6398         }
6399         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6400                 member = type->left;
6401                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6402                         if (member->left->field_ident == field) {
6403                                 member = member->left;
6404                                 break;
6405                         }
6406                         member = member->right;
6407                 }
6408         }
6409         else {
6410                 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6411         }
6412
6413         size += reg_needed_padding(state, member, size);
6414         if (!member || (member->field_ident != field)) {
6415                 error(state, 0, "member %s not present", field->name);
6416         }
6417         return size;
6418 }
6419
6420 static struct type *field_type(struct compile_state *state, 
6421         struct type *type, struct hash_entry *field)
6422 {
6423         struct type *member;
6424
6425         member = 0;
6426         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6427                 member = type->left;
6428                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6429                         if (member->left->field_ident == field) {
6430                                 member = member->left;
6431                                 break;
6432                         }
6433                         member = member->right;
6434                 }
6435         }
6436         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6437                 member = type->left;
6438                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6439                         if (member->left->field_ident == field) {
6440                                 member = member->left;
6441                                 break;
6442                         }
6443                         member = member->right;
6444                 }
6445         }
6446         else {
6447                 internal_error(state, 0, "field_type only works on structures and unions");
6448         }
6449         
6450         if (!member || (member->field_ident != field)) {
6451                 error(state, 0, "member %s not present", field->name);
6452         }
6453         return member;
6454 }
6455
6456 static size_t index_offset(struct compile_state *state, 
6457         struct type *type, ulong_t index)
6458 {
6459         struct type *member;
6460         size_t size;
6461         size = 0;
6462         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6463                 size = size_of(state, type->left) * index;
6464         }
6465         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6466                 ulong_t i;
6467                 member = type->left;
6468                 i = 0;
6469                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6470                         size += needed_padding(state, member->left, size);
6471                         if (i == index) {
6472                                 member = member->left;
6473                                 break;
6474                         }
6475                         size += size_of(state, member->left);
6476                         i++;
6477                         member = member->right;
6478                 }
6479                 size += needed_padding(state, member, size);
6480                 if (i != index) {
6481                         internal_error(state, 0, "Missing member index: %u", index);
6482                 }
6483         }
6484         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6485                 ulong_t i;
6486                 size = 0;
6487                 member = type->left;
6488                 i = 0;
6489                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6490                         if (i == index) {
6491                                 member = member->left;
6492                                 break;
6493                         }
6494                         i++;
6495                         member = member->right;
6496                 }
6497                 if (i != index) {
6498                         internal_error(state, 0, "Missing member index: %u", index);
6499                 }
6500         }
6501         else {
6502                 internal_error(state, 0, 
6503                         "request for index %u in something not an array, tuple or join",
6504                         index);
6505         }
6506         return size;
6507 }
6508
6509 static size_t index_reg_offset(struct compile_state *state, 
6510         struct type *type, ulong_t index)
6511 {
6512         struct type *member;
6513         size_t size;
6514         size = 0;
6515         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6516                 size = reg_size_of(state, type->left) * index;
6517         }
6518         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6519                 ulong_t i;
6520                 member = type->left;
6521                 i = 0;
6522                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6523                         size += reg_needed_padding(state, member->left, size);
6524                         if (i == index) {
6525                                 member = member->left;
6526                                 break;
6527                         }
6528                         size += reg_size_of(state, member->left);
6529                         i++;
6530                         member = member->right;
6531                 }
6532                 size += reg_needed_padding(state, member, size);
6533                 if (i != index) {
6534                         internal_error(state, 0, "Missing member index: %u", index);
6535                 }
6536                 
6537         }
6538         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6539                 ulong_t i;
6540                 size = 0;
6541                 member = type->left;
6542                 i = 0;
6543                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6544                         if (i == index) {
6545                                 member = member->left;
6546                                 break;
6547                         }
6548                         i++;
6549                         member = member->right;
6550                 }
6551                 if (i != index) {
6552                         internal_error(state, 0, "Missing member index: %u", index);
6553                 }
6554         }
6555         else {
6556                 internal_error(state, 0, 
6557                         "request for index %u in something not an array, tuple or join",
6558                         index);
6559         }
6560         return size;
6561 }
6562
6563 static struct type *index_type(struct compile_state *state,
6564         struct type *type, ulong_t index)
6565 {
6566         struct type *member;
6567         if (index >= type->elements) {
6568                 internal_error(state, 0, "Invalid element %u requested", index);
6569         }
6570         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6571                 member = type->left;
6572         }
6573         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6574                 ulong_t i;
6575                 member = type->left;
6576                 i = 0;
6577                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6578                         if (i == index) {
6579                                 member = member->left;
6580                                 break;
6581                         }
6582                         i++;
6583                         member = member->right;
6584                 }
6585                 if (i != index) {
6586                         internal_error(state, 0, "Missing member index: %u", index);
6587                 }
6588         }
6589         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6590                 ulong_t i;
6591                 member = type->left;
6592                 i = 0;
6593                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6594                         if (i == index) {
6595                                 member = member->left;
6596                                 break;
6597                         }
6598                         i++;
6599                         member = member->right;
6600                 }
6601                 if (i != index) {
6602                         internal_error(state, 0, "Missing member index: %u", index);
6603                 }
6604         }
6605         else {
6606                 member = 0;
6607                 internal_error(state, 0, 
6608                         "request for index %u in something not an array, tuple or join",
6609                         index);
6610         }
6611         return member;
6612 }
6613
6614 static struct type *unpack_type(struct compile_state *state, struct type *type)
6615 {
6616         /* If I have a single register compound type not a bit-field
6617          * find the real type.
6618          */
6619         struct type *start_type;
6620         size_t size;
6621         /* Get out early if I need multiple registers for this type */
6622         size = reg_size_of(state, type);
6623         if (size > REG_SIZEOF_REG) {
6624                 return type;
6625         }
6626         /* Get out early if I don't need any registers for this type */
6627         if (size == 0) {
6628                 return &void_type;
6629         }
6630         /* Loop until I have no more layers I can remove */
6631         do {
6632                 start_type = type;
6633                 switch(type->type & TYPE_MASK) {
6634                 case TYPE_ARRAY:
6635                         /* If I have a single element the unpacked type
6636                          * is that element.
6637                          */
6638                         if (type->elements == 1) {
6639                                 type = type->left;
6640                         }
6641                         break;
6642                 case TYPE_STRUCT:
6643                 case TYPE_TUPLE:
6644                         /* If I have a single element the unpacked type
6645                          * is that element.
6646                          */
6647                         if (type->elements == 1) {
6648                                 type = type->left;
6649                         }
6650                         /* If I have multiple elements the unpacked
6651                          * type is the non-void element.
6652                          */
6653                         else {
6654                                 struct type *next, *member;
6655                                 struct type *sub_type;
6656                                 sub_type = 0;
6657                                 next = type->left;
6658                                 while(next) {
6659                                         member = next;
6660                                         next = 0;
6661                                         if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6662                                                 next = member->right;
6663                                                 member = member->left;
6664                                         }
6665                                         if (reg_size_of(state, member) > 0) {
6666                                                 if (sub_type) {
6667                                                         internal_error(state, 0, "true compound type in a register");
6668                                                 }
6669                                                 sub_type = member;
6670                                         }
6671                                 }
6672                                 if (sub_type) {
6673                                         type = sub_type;
6674                                 }
6675                         }
6676                         break;
6677
6678                 case TYPE_UNION:
6679                 case TYPE_JOIN:
6680                         /* If I have a single element the unpacked type
6681                          * is that element.
6682                          */
6683                         if (type->elements == 1) {
6684                                 type = type->left;
6685                         }
6686                         /* I can't in general unpack union types */
6687                         break;
6688                 default:
6689                         /* If I'm not a compound type I can't unpack it */
6690                         break;
6691                 }
6692         } while(start_type != type);
6693         switch(type->type & TYPE_MASK) {
6694         case TYPE_STRUCT:
6695         case TYPE_ARRAY:
6696         case TYPE_TUPLE:
6697                 internal_error(state, 0, "irredicible type?");
6698                 break;
6699         }
6700         return type;
6701 }
6702
6703 static int equiv_types(struct type *left, struct type *right);
6704 static int is_compound_type(struct type *type);
6705
6706 static struct type *reg_type(
6707         struct compile_state *state, struct type *type, int reg_offset)
6708 {
6709         struct type *member;
6710         size_t size;
6711 #if 1
6712         struct type *invalid;
6713         invalid = invalid_type(state, type);
6714         if (invalid) {
6715                 fprintf(state->errout, "type: ");
6716                 name_of(state->errout, type);
6717                 fprintf(state->errout, "\n");
6718                 fprintf(state->errout, "invalid: ");
6719                 name_of(state->errout, invalid);
6720                 fprintf(state->errout, "\n");
6721                 internal_error(state, 0, "bad input type?");
6722         }
6723 #endif
6724
6725         size = reg_size_of(state, type);
6726         if (reg_offset > size) {
6727                 member = 0;
6728                 fprintf(state->errout, "type: ");
6729                 name_of(state->errout, type);
6730                 fprintf(state->errout, "\n");
6731                 internal_error(state, 0, "offset outside of type");
6732         }
6733         else {
6734                 switch(type->type & TYPE_MASK) {
6735                         /* Don't do anything with the basic types */
6736                 case TYPE_VOID:
6737                 case TYPE_CHAR:         case TYPE_UCHAR:
6738                 case TYPE_SHORT:        case TYPE_USHORT:
6739                 case TYPE_INT:          case TYPE_UINT:
6740                 case TYPE_LONG:         case TYPE_ULONG:
6741                 case TYPE_LLONG:        case TYPE_ULLONG:
6742                 case TYPE_FLOAT:        case TYPE_DOUBLE:
6743                 case TYPE_LDOUBLE:
6744                 case TYPE_POINTER:
6745                 case TYPE_ENUM:
6746                 case TYPE_BITFIELD:
6747                         member = type;
6748                         break;
6749                 case TYPE_ARRAY:
6750                         member = type->left;
6751                         size = reg_size_of(state, member);
6752                         if (size > REG_SIZEOF_REG) {
6753                                 member = reg_type(state, member, reg_offset % size);
6754                         }
6755                         break;
6756                 case TYPE_STRUCT:
6757                 case TYPE_TUPLE:
6758                 {
6759                         size_t offset;
6760                         offset = 0;
6761                         member = type->left;
6762                         while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6763                                 size = reg_size_of(state, member->left);
6764                                 offset += reg_needed_padding(state, member->left, offset);
6765                                 if ((offset + size) > reg_offset) {
6766                                         member = member->left;
6767                                         break;
6768                                 }
6769                                 offset += size;
6770                                 member = member->right;
6771                         }
6772                         offset += reg_needed_padding(state, member, offset);
6773                         member = reg_type(state, member, reg_offset - offset);
6774                         break;
6775                 }
6776                 case TYPE_UNION:
6777                 case TYPE_JOIN:
6778                 {
6779                         struct type *join, **jnext, *mnext;
6780                         join = new_type(TYPE_JOIN, 0, 0);
6781                         jnext = &join->left;
6782                         mnext = type->left;
6783                         while(mnext) {
6784                                 size_t size;
6785                                 member = mnext;
6786                                 mnext = 0;
6787                                 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6788                                         mnext = member->right;
6789                                         member = member->left;
6790                                 }
6791                                 size = reg_size_of(state, member);
6792                                 if (size > reg_offset) {
6793                                         struct type *part, *hunt;
6794                                         part = reg_type(state, member, reg_offset);
6795                                         /* See if this type is already in the union */
6796                                         hunt = join->left;
6797                                         while(hunt) {
6798                                                 struct type *test = hunt;
6799                                                 hunt = 0;
6800                                                 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6801                                                         hunt = test->right;
6802                                                         test = test->left;
6803                                                 }
6804                                                 if (equiv_types(part, test)) {
6805                                                         goto next;
6806                                                 }
6807                                         }
6808                                         /* Nope add it */
6809                                         if (!*jnext) {
6810                                                 *jnext = part;
6811                                         } else {
6812                                                 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6813                                                 jnext = &(*jnext)->right;
6814                                         }
6815                                         join->elements++;
6816                                 }
6817                         next:
6818                                 ;
6819                         }
6820                         if (join->elements == 0) {
6821                                 internal_error(state, 0, "No elements?");
6822                         }
6823                         member = join;
6824                         break;
6825                 }
6826                 default:
6827                         member = 0;
6828                         fprintf(state->errout, "type: ");
6829                         name_of(state->errout, type);
6830                         fprintf(state->errout, "\n");
6831                         internal_error(state, 0, "reg_type not yet defined for type");
6832                         
6833                 }
6834         }
6835         /* If I have a single register compound type not a bit-field
6836          * find the real type.
6837          */
6838         member = unpack_type(state, member);
6839                 ;
6840         size  = reg_size_of(state, member);
6841         if (size > REG_SIZEOF_REG) {
6842                 internal_error(state, 0, "Cannot find type of single register");
6843         }
6844 #if 1
6845         invalid = invalid_type(state, member);
6846         if (invalid) {
6847                 fprintf(state->errout, "type: ");
6848                 name_of(state->errout, member);
6849                 fprintf(state->errout, "\n");
6850                 fprintf(state->errout, "invalid: ");
6851                 name_of(state->errout, invalid);
6852                 fprintf(state->errout, "\n");
6853                 internal_error(state, 0, "returning bad type?");
6854         }
6855 #endif
6856         return member;
6857 }
6858
6859 static struct type *next_field(struct compile_state *state,
6860         struct type *type, struct type *prev_member) 
6861 {
6862         struct type *member;
6863         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6864                 internal_error(state, 0, "next_field only works on structures");
6865         }
6866         member = type->left;
6867         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6868                 if (!prev_member) {
6869                         member = member->left;
6870                         break;
6871                 }
6872                 if (member->left == prev_member) {
6873                         prev_member = 0;
6874                 }
6875                 member = member->right;
6876         }
6877         if (member == prev_member) {
6878                 prev_member = 0;
6879         }
6880         if (prev_member) {
6881                 internal_error(state, 0, "prev_member %s not present", 
6882                         prev_member->field_ident->name);
6883         }
6884         return member;
6885 }
6886
6887 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type, 
6888         size_t ret_offset, size_t mem_offset, void *arg);
6889
6890 static void walk_type_fields(struct compile_state *state,
6891         struct type *type, size_t reg_offset, size_t mem_offset,
6892         walk_type_fields_cb_t cb, void *arg);
6893
6894 static void walk_struct_fields(struct compile_state *state,
6895         struct type *type, size_t reg_offset, size_t mem_offset,
6896         walk_type_fields_cb_t cb, void *arg)
6897 {
6898         struct type *tptr;
6899         ulong_t i;
6900         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6901                 internal_error(state, 0, "walk_struct_fields only works on structures");
6902         }
6903         tptr = type->left;
6904         for(i = 0; i < type->elements; i++) {
6905                 struct type *mtype;
6906                 mtype = tptr;
6907                 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6908                         mtype = mtype->left;
6909                 }
6910                 walk_type_fields(state, mtype, 
6911                         reg_offset + 
6912                         field_reg_offset(state, type, mtype->field_ident),
6913                         mem_offset + 
6914                         field_offset(state, type, mtype->field_ident),
6915                         cb, arg);
6916                 tptr = tptr->right;
6917         }
6918         
6919 }
6920
6921 static void walk_type_fields(struct compile_state *state,
6922         struct type *type, size_t reg_offset, size_t mem_offset,
6923         walk_type_fields_cb_t cb, void *arg)
6924 {
6925         switch(type->type & TYPE_MASK) {
6926         case TYPE_STRUCT:
6927                 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6928                 break;
6929         case TYPE_CHAR:
6930         case TYPE_UCHAR:
6931         case TYPE_SHORT:
6932         case TYPE_USHORT:
6933         case TYPE_INT:
6934         case TYPE_UINT:
6935         case TYPE_LONG:
6936         case TYPE_ULONG:
6937                 cb(state, type, reg_offset, mem_offset, arg);
6938                 break;
6939         case TYPE_VOID:
6940                 break;
6941         default:
6942                 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6943         }
6944 }
6945
6946 static void arrays_complete(struct compile_state *state, struct type *type)
6947 {
6948         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6949                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6950                         error(state, 0, "array size not specified");
6951                 }
6952                 arrays_complete(state, type->left);
6953         }
6954 }
6955
6956 static unsigned int get_basic_type(struct type *type)
6957 {
6958         unsigned int basic;
6959         basic = type->type & TYPE_MASK;
6960         /* Convert enums to ints */
6961         if (basic == TYPE_ENUM) {
6962                 basic = TYPE_INT;
6963         }
6964         /* Convert bitfields to standard types */
6965         else if (basic == TYPE_BITFIELD) {
6966                 if (type->elements <= SIZEOF_CHAR) {
6967                         basic = TYPE_CHAR;
6968                 }
6969                 else if (type->elements <= SIZEOF_SHORT) {
6970                         basic = TYPE_SHORT;
6971                 }
6972                 else if (type->elements <= SIZEOF_INT) {
6973                         basic = TYPE_INT;
6974                 }
6975                 else if (type->elements <= SIZEOF_LONG) {
6976                         basic = TYPE_LONG;
6977                 }
6978                 if (!TYPE_SIGNED(type->left->type)) {
6979                         basic += 1;
6980                 }
6981         }
6982         return basic;
6983 }
6984
6985 static unsigned int do_integral_promotion(unsigned int type)
6986 {
6987         if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6988                 type = TYPE_INT;
6989         }
6990         return type;
6991 }
6992
6993 static unsigned int do_arithmetic_conversion(
6994         unsigned int left, unsigned int right)
6995 {
6996         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6997                 return TYPE_LDOUBLE;
6998         }
6999         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
7000                 return TYPE_DOUBLE;
7001         }
7002         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
7003                 return TYPE_FLOAT;
7004         }
7005         left = do_integral_promotion(left);
7006         right = do_integral_promotion(right);
7007         /* If both operands have the same size done */
7008         if (left == right) {
7009                 return left;
7010         }
7011         /* If both operands have the same signedness pick the larger */
7012         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
7013                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
7014         }
7015         /* If the signed type can hold everything use it */
7016         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
7017                 return left;
7018         }
7019         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
7020                 return right;
7021         }
7022         /* Convert to the unsigned type with the same rank as the signed type */
7023         else if (TYPE_SIGNED(left)) {
7024                 return TYPE_MKUNSIGNED(left);
7025         }
7026         else {
7027                 return TYPE_MKUNSIGNED(right);
7028         }
7029 }
7030
7031 /* see if two types are the same except for qualifiers */
7032 static int equiv_types(struct type *left, struct type *right)
7033 {
7034         unsigned int type;
7035         /* Error if the basic types do not match */
7036         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
7037                 return 0;
7038         }
7039         type = left->type & TYPE_MASK;
7040         /* If the basic types match and it is a void type we are done */
7041         if (type == TYPE_VOID) {
7042                 return 1;
7043         }
7044         /* For bitfields we need to compare the sizes */
7045         else if (type == TYPE_BITFIELD) {
7046                 return (left->elements == right->elements) &&
7047                         (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
7048         }
7049         /* if the basic types match and it is an arithmetic type we are done */
7050         else if (TYPE_ARITHMETIC(type)) {
7051                 return 1;
7052         }
7053         /* If it is a pointer type recurse and keep testing */
7054         else if (type == TYPE_POINTER) {
7055                 return equiv_types(left->left, right->left);
7056         }
7057         else if (type == TYPE_ARRAY) {
7058                 return (left->elements == right->elements) &&
7059                         equiv_types(left->left, right->left);
7060         }
7061         /* test for struct equality */
7062         else if (type == TYPE_STRUCT) {
7063                 return left->type_ident == right->type_ident;
7064         }
7065         /* test for union equality */
7066         else if (type == TYPE_UNION) {
7067                 return left->type_ident == right->type_ident;
7068         }
7069         /* Test for equivalent functions */
7070         else if (type == TYPE_FUNCTION) {
7071                 return equiv_types(left->left, right->left) &&
7072                         equiv_types(left->right, right->right);
7073         }
7074         /* We only see TYPE_PRODUCT as part of function equivalence matching */
7075         /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
7076         else if (type == TYPE_PRODUCT) {
7077                 return equiv_types(left->left, right->left) &&
7078                         equiv_types(left->right, right->right);
7079         }
7080         /* We should see TYPE_OVERLAP when comparing joins */
7081         else if (type == TYPE_OVERLAP) {
7082                 return equiv_types(left->left, right->left) &&
7083                         equiv_types(left->right, right->right);
7084         }
7085         /* Test for equivalence of tuples */
7086         else if (type == TYPE_TUPLE) {
7087                 return (left->elements == right->elements) &&
7088                         equiv_types(left->left, right->left);
7089         }
7090         /* Test for equivalence of joins */
7091         else if (type == TYPE_JOIN) {
7092                 return (left->elements == right->elements) &&
7093                         equiv_types(left->left, right->left);
7094         }
7095         else {
7096                 return 0;
7097         }
7098 }
7099
7100 static int equiv_ptrs(struct type *left, struct type *right)
7101 {
7102         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7103                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7104                 return 0;
7105         }
7106         return equiv_types(left->left, right->left);
7107 }
7108
7109 static struct type *compatible_types(struct type *left, struct type *right)
7110 {
7111         struct type *result;
7112         unsigned int type, qual_type;
7113         /* Error if the basic types do not match */
7114         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
7115                 return 0;
7116         }
7117         type = left->type & TYPE_MASK;
7118         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7119         result = 0;
7120         /* if the basic types match and it is an arithmetic type we are done */
7121         if (TYPE_ARITHMETIC(type)) {
7122                 result = new_type(qual_type, 0, 0);
7123         }
7124         /* If it is a pointer type recurse and keep testing */
7125         else if (type == TYPE_POINTER) {
7126                 result = compatible_types(left->left, right->left);
7127                 if (result) {
7128                         result = new_type(qual_type, result, 0);
7129                 }
7130         }
7131         /* test for struct equality */
7132         else if (type == TYPE_STRUCT) {
7133                 if (left->type_ident == right->type_ident) {
7134                         result = left;
7135                 }
7136         }
7137         /* test for union equality */
7138         else if (type == TYPE_UNION) {
7139                 if (left->type_ident == right->type_ident) {
7140                         result = left;
7141                 }
7142         }
7143         /* Test for equivalent functions */
7144         else if (type == TYPE_FUNCTION) {
7145                 struct type *lf, *rf;
7146                 lf = compatible_types(left->left, right->left);
7147                 rf = compatible_types(left->right, right->right);
7148                 if (lf && rf) {
7149                         result = new_type(qual_type, lf, rf);
7150                 }
7151         }
7152         /* We only see TYPE_PRODUCT as part of function equivalence matching */
7153         else if (type == TYPE_PRODUCT) {
7154                 struct type *lf, *rf;
7155                 lf = compatible_types(left->left, right->left);
7156                 rf = compatible_types(left->right, right->right);
7157                 if (lf && rf) {
7158                         result = new_type(qual_type, lf, rf);
7159                 }
7160         }
7161         else {
7162                 /* Nothing else is compatible */
7163         }
7164         return result;
7165 }
7166
7167 /* See if left is a equivalent to right or right is a union member of left */
7168 static int is_subset_type(struct type *left, struct type *right)
7169 {
7170         if (equiv_types(left, right)) {
7171                 return 1;
7172         }
7173         if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7174                 struct type *member, *mnext;
7175                 mnext = left->left;
7176                 while(mnext) {
7177                         member = mnext;
7178                         mnext = 0;
7179                         if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7180                                 mnext = member->right;
7181                                 member = member->left;
7182                         }
7183                         if (is_subset_type( member, right)) {
7184                                 return 1;
7185                         }
7186                 }
7187         }
7188         return 0;
7189 }
7190
7191 static struct type *compatible_ptrs(struct type *left, struct type *right)
7192 {
7193         struct type *result;
7194         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7195                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7196                 return 0;
7197         }
7198         result = compatible_types(left->left, right->left);
7199         if (result) {
7200                 unsigned int qual_type;
7201                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7202                 result = new_type(qual_type, result, 0);
7203         }
7204         return result;
7205         
7206 }
7207 static struct triple *integral_promotion(
7208         struct compile_state *state, struct triple *def)
7209 {
7210         struct type *type;
7211         type = def->type;
7212         /* As all operations are carried out in registers
7213          * the values are converted on load I just convert
7214          * logical type of the operand.
7215          */
7216         if (TYPE_INTEGER(type->type)) {
7217                 unsigned int int_type;
7218                 int_type = type->type & ~TYPE_MASK;
7219                 int_type |= do_integral_promotion(get_basic_type(type));
7220                 if (int_type != type->type) {
7221                         if (def->op != OP_LOAD) {
7222                                 def->type = new_type(int_type, 0, 0);
7223                         }
7224                         else {
7225                                 def = triple(state, OP_CONVERT, 
7226                                         new_type(int_type, 0, 0), def, 0);
7227                         }
7228                 }
7229         }
7230         return def;
7231 }
7232
7233
7234 static void arithmetic(struct compile_state *state, struct triple *def)
7235 {
7236         if (!TYPE_ARITHMETIC(def->type->type)) {
7237                 error(state, 0, "arithmetic type expexted");
7238         }
7239 }
7240
7241 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7242 {
7243         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7244                 error(state, def, "pointer or arithmetic type expected");
7245         }
7246 }
7247
7248 static int is_integral(struct triple *ins)
7249 {
7250         return TYPE_INTEGER(ins->type->type);
7251 }
7252
7253 static void integral(struct compile_state *state, struct triple *def)
7254 {
7255         if (!is_integral(def)) {
7256                 error(state, 0, "integral type expected");
7257         }
7258 }
7259
7260
7261 static void bool(struct compile_state *state, struct triple *def)
7262 {
7263         if (!TYPE_ARITHMETIC(def->type->type) &&
7264                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7265                 error(state, 0, "arithmetic or pointer type expected");
7266         }
7267 }
7268
7269 static int is_signed(struct type *type)
7270 {
7271         if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7272                 type = type->left;
7273         }
7274         return !!TYPE_SIGNED(type->type);
7275 }
7276 static int is_compound_type(struct type *type)
7277 {
7278         int is_compound;
7279         switch((type->type & TYPE_MASK)) {
7280         case TYPE_ARRAY:
7281         case TYPE_STRUCT:
7282         case TYPE_TUPLE:
7283         case TYPE_UNION:
7284         case TYPE_JOIN: 
7285                 is_compound = 1;
7286                 break;
7287         default:
7288                 is_compound = 0;
7289                 break;
7290         }
7291         return is_compound;
7292 }
7293
7294 /* Is this value located in a register otherwise it must be in memory */
7295 static int is_in_reg(struct compile_state *state, struct triple *def)
7296 {
7297         int in_reg;
7298         if (def->op == OP_ADECL) {
7299                 in_reg = 1;
7300         }
7301         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7302                 in_reg = 0;
7303         }
7304         else if (triple_is_part(state, def)) {
7305                 in_reg = is_in_reg(state, MISC(def, 0));
7306         }
7307         else {
7308                 internal_error(state, def, "unknown expr storage location");
7309                 in_reg = -1;
7310         }
7311         return in_reg;
7312 }
7313
7314 /* Is this an auto or static variable location? Something that can
7315  * be assigned to.  Otherwise it must must be a pure value, a temporary.
7316  */
7317 static int is_lvalue(struct compile_state *state, struct triple *def)
7318 {
7319         int ret;
7320         ret = 0;
7321         if (!def) {
7322                 return 0;
7323         }
7324         if ((def->op == OP_ADECL) || 
7325                 (def->op == OP_SDECL) || 
7326                 (def->op == OP_DEREF) ||
7327                 (def->op == OP_BLOBCONST) ||
7328                 (def->op == OP_LIST)) {
7329                 ret = 1;
7330         }
7331         else if (triple_is_part(state, def)) {
7332                 ret = is_lvalue(state, MISC(def, 0));
7333         }
7334         return ret;
7335 }
7336
7337 static void clvalue(struct compile_state *state, struct triple *def)
7338 {
7339         if (!def) {
7340                 internal_error(state, def, "nothing where lvalue expected?");
7341         }
7342         if (!is_lvalue(state, def)) { 
7343                 error(state, def, "lvalue expected");
7344         }
7345 }
7346 static void lvalue(struct compile_state *state, struct triple *def)
7347 {
7348         clvalue(state, def);
7349         if (def->type->type & QUAL_CONST) {
7350                 error(state, def, "modifable lvalue expected");
7351         }
7352 }
7353
7354 static int is_pointer(struct triple *def)
7355 {
7356         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7357 }
7358
7359 static void pointer(struct compile_state *state, struct triple *def)
7360 {
7361         if (!is_pointer(def)) {
7362                 error(state, def, "pointer expected");
7363         }
7364 }
7365
7366 static struct triple *int_const(
7367         struct compile_state *state, struct type *type, ulong_t value)
7368 {
7369         struct triple *result;
7370         switch(type->type & TYPE_MASK) {
7371         case TYPE_CHAR:
7372         case TYPE_INT:   case TYPE_UINT:
7373         case TYPE_LONG:  case TYPE_ULONG:
7374                 break;
7375         default:
7376                 internal_error(state, 0, "constant for unknown type");
7377         }
7378         result = triple(state, OP_INTCONST, type, 0, 0);
7379         result->u.cval = value;
7380         return result;
7381 }
7382
7383
7384 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7385
7386 static struct triple *do_mk_addr_expr(struct compile_state *state, 
7387         struct triple *expr, struct type *type, ulong_t offset)
7388 {
7389         struct triple *result;
7390         struct type *ptr_type;
7391         clvalue(state, expr);
7392
7393         ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7394
7395         
7396         result = 0;
7397         if (expr->op == OP_ADECL) {
7398                 error(state, expr, "address of auto variables not supported");
7399         }
7400         else if (expr->op == OP_SDECL) {
7401                 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7402                 MISC(result, 0) = expr;
7403                 result->u.cval = offset;
7404         }
7405         else if (expr->op == OP_DEREF) {
7406                 result = triple(state, OP_ADD, ptr_type,
7407                         RHS(expr, 0),
7408                         int_const(state, &ulong_type, offset));
7409         }
7410         else if (expr->op == OP_BLOBCONST) {
7411                 FINISHME();
7412                 internal_error(state, expr, "not yet implemented");
7413         }
7414         else if (expr->op == OP_LIST) {
7415                 error(state, 0, "Function addresses not supported");
7416         }
7417         else if (triple_is_part(state, expr)) {
7418                 struct triple *part;
7419                 part = expr;
7420                 expr = MISC(expr, 0);
7421                 if (part->op == OP_DOT) {
7422                         offset += bits_to_bytes(
7423                                 field_offset(state, expr->type, part->u.field));
7424                 }
7425                 else if (part->op == OP_INDEX) {
7426                         offset += bits_to_bytes(
7427                                 index_offset(state, expr->type, part->u.cval));
7428                 }
7429                 else {
7430                         internal_error(state, part, "unhandled part type");
7431                 }
7432                 result = do_mk_addr_expr(state, expr, type, offset);
7433         }
7434         if (!result) {
7435                 internal_error(state, expr, "cannot take address of expression");
7436         }
7437         return result;
7438 }
7439
7440 static struct triple *mk_addr_expr(
7441         struct compile_state *state, struct triple *expr, ulong_t offset)
7442 {
7443         return do_mk_addr_expr(state, expr, expr->type, offset);
7444 }
7445
7446 static struct triple *mk_deref_expr(
7447         struct compile_state *state, struct triple *expr)
7448 {
7449         struct type *base_type;
7450         pointer(state, expr);
7451         base_type = expr->type->left;
7452         return triple(state, OP_DEREF, base_type, expr, 0);
7453 }
7454
7455 /* lvalue conversions always apply except when certain operators
7456  * are applied.  So I apply apply it when I know no more
7457  * operators will be applied.
7458  */
7459 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7460 {
7461         /* Tranform an array to a pointer to the first element */
7462         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7463                 struct type *type;
7464                 type = new_type(
7465                         TYPE_POINTER | (def->type->type & QUAL_MASK),
7466                         def->type->left, 0);
7467                 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7468                         struct triple *addrconst;
7469                         if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7470                                 internal_error(state, def, "bad array constant");
7471                         }
7472                         addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7473                         MISC(addrconst, 0) = def;
7474                         def = addrconst;
7475                 }
7476                 else {
7477                         def = triple(state, OP_CONVERT, type, def, 0);
7478                 }
7479         }
7480         /* Transform a function to a pointer to it */
7481         else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7482                 def = mk_addr_expr(state, def, 0);
7483         }
7484         return def;
7485 }
7486
7487 static struct triple *deref_field(
7488         struct compile_state *state, struct triple *expr, struct hash_entry *field)
7489 {
7490         struct triple *result;
7491         struct type *type, *member;
7492         ulong_t offset;
7493         if (!field) {
7494                 internal_error(state, 0, "No field passed to deref_field");
7495         }
7496         result = 0;
7497         type = expr->type;
7498         if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7499                 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7500                 error(state, 0, "request for member %s in something not a struct or union",
7501                         field->name);
7502         }
7503         member = field_type(state, type, field);
7504         if ((type->type & STOR_MASK) == STOR_PERM) {
7505                 /* Do the pointer arithmetic to get a deref the field */
7506                 offset = bits_to_bytes(field_offset(state, type, field));
7507                 result = do_mk_addr_expr(state, expr, member, offset);
7508                 result = mk_deref_expr(state, result);
7509         }
7510         else {
7511                 /* Find the variable for the field I want. */
7512                 result = triple(state, OP_DOT, member, expr, 0);
7513                 result->u.field = field;
7514         }
7515         return result;
7516 }
7517
7518 static struct triple *deref_index(
7519         struct compile_state *state, struct triple *expr, size_t index)
7520 {
7521         struct triple *result;
7522         struct type *type, *member;
7523         ulong_t offset;
7524
7525         result = 0;
7526         type = expr->type;
7527         member = index_type(state, type, index);
7528
7529         if ((type->type & STOR_MASK) == STOR_PERM) {
7530                 offset = bits_to_bytes(index_offset(state, type, index));
7531                 result = do_mk_addr_expr(state, expr, member, offset);
7532                 result = mk_deref_expr(state, result);
7533         }
7534         else {
7535                 result = triple(state, OP_INDEX, member, expr, 0);
7536                 result->u.cval = index;
7537         }
7538         return result;
7539 }
7540
7541 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7542 {
7543         int op;
7544         if  (!def) {
7545                 return 0;
7546         }
7547 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7548         /* Transform lvalues into something we can read */
7549         def = lvalue_conversion(state, def);
7550         if (!is_lvalue(state, def)) {
7551                 return def;
7552         }
7553         if (is_in_reg(state, def)) {
7554                 op = OP_READ;
7555         } else {
7556                 if (def->op == OP_SDECL) {
7557                         def = mk_addr_expr(state, def, 0);
7558                         def = mk_deref_expr(state, def);
7559                 }
7560                 op = OP_LOAD;
7561         }
7562         def = triple(state, op, def->type, def, 0);
7563         if (def->type->type & QUAL_VOLATILE) {
7564                 def->id |= TRIPLE_FLAG_VOLATILE;
7565         }
7566         return def;
7567 }
7568
7569 int is_write_compatible(struct compile_state *state, 
7570         struct type *dest, struct type *rval)
7571 {
7572         int compatible = 0;
7573         /* Both operands have arithmetic type */
7574         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7575                 compatible = 1;
7576         }
7577         /* One operand is a pointer and the other is a pointer to void */
7578         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7579                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7580                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7581                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7582                 compatible = 1;
7583         }
7584         /* If both types are the same without qualifiers we are good */
7585         else if (equiv_ptrs(dest, rval)) {
7586                 compatible = 1;
7587         }
7588         /* test for struct/union equality  */
7589         else if (equiv_types(dest, rval)) {
7590                 compatible = 1;
7591         }
7592         return compatible;
7593 }
7594
7595 static void write_compatible(struct compile_state *state,
7596         struct type *dest, struct type *rval)
7597 {
7598         if (!is_write_compatible(state, dest, rval)) {
7599                 FILE *fp = state->errout;
7600                 fprintf(fp, "dest: ");
7601                 name_of(fp, dest);
7602                 fprintf(fp,"\nrval: ");
7603                 name_of(fp, rval);
7604                 fprintf(fp, "\n");
7605                 error(state, 0, "Incompatible types in assignment");
7606         }
7607 }
7608
7609 static int is_init_compatible(struct compile_state *state,
7610         struct type *dest, struct type *rval)
7611 {
7612         int compatible = 0;
7613         if (is_write_compatible(state, dest, rval)) {
7614                 compatible = 1;
7615         }
7616         else if (equiv_types(dest, rval)) {
7617                 compatible = 1;
7618         }
7619         return compatible;
7620 }
7621
7622 static struct triple *write_expr(
7623         struct compile_state *state, struct triple *dest, struct triple *rval)
7624 {
7625         struct triple *def;
7626         int op;
7627
7628         def = 0;
7629         if (!rval) {
7630                 internal_error(state, 0, "missing rval");
7631         }
7632
7633         if (rval->op == OP_LIST) {
7634                 internal_error(state, 0, "expression of type OP_LIST?");
7635         }
7636         if (!is_lvalue(state, dest)) {
7637                 internal_error(state, 0, "writing to a non lvalue?");
7638         }
7639         if (dest->type->type & QUAL_CONST) {
7640                 internal_error(state, 0, "modifable lvalue expexted");
7641         }
7642
7643         write_compatible(state, dest->type, rval->type);
7644         if (!equiv_types(dest->type, rval->type)) {
7645                 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7646         }
7647
7648         /* Now figure out which assignment operator to use */
7649         op = -1;
7650         if (is_in_reg(state, dest)) {
7651                 def = triple(state, OP_WRITE, dest->type, rval, dest);
7652                 if (MISC(def, 0) != dest) {
7653                         internal_error(state, def, "huh?");
7654                 }
7655                 if (RHS(def, 0) != rval) {
7656                         internal_error(state, def, "huh?");
7657                 }
7658         } else {
7659                 def = triple(state, OP_STORE, dest->type, dest, rval);
7660         }
7661         if (def->type->type & QUAL_VOLATILE) {
7662                 def->id |= TRIPLE_FLAG_VOLATILE;
7663         }
7664         return def;
7665 }
7666
7667 static struct triple *init_expr(
7668         struct compile_state *state, struct triple *dest, struct triple *rval)
7669 {
7670         struct triple *def;
7671
7672         def = 0;
7673         if (!rval) {
7674                 internal_error(state, 0, "missing rval");
7675         }
7676         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
7677                 rval = read_expr(state, rval);
7678                 def = write_expr(state, dest, rval);
7679         }
7680         else {
7681                 /* Fill in the array size if necessary */
7682                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
7683                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
7684                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
7685                                 dest->type->elements = rval->type->elements;
7686                         }
7687                 }
7688                 if (!equiv_types(dest->type, rval->type)) {
7689                         error(state, 0, "Incompatible types in inializer");
7690                 }
7691                 MISC(dest, 0) = rval;
7692                 insert_triple(state, dest, rval);
7693                 rval->id |= TRIPLE_FLAG_FLATTENED;
7694                 use_triple(MISC(dest, 0), dest);
7695         }
7696         return def;
7697 }
7698
7699 struct type *arithmetic_result(
7700         struct compile_state *state, struct triple *left, struct triple *right)
7701 {
7702         struct type *type;
7703         /* Sanity checks to ensure I am working with arithmetic types */
7704         arithmetic(state, left);
7705         arithmetic(state, right);
7706         type = new_type(
7707                 do_arithmetic_conversion(
7708                         get_basic_type(left->type),
7709                         get_basic_type(right->type)),
7710                 0, 0);
7711         return type;
7712 }
7713
7714 struct type *ptr_arithmetic_result(
7715         struct compile_state *state, struct triple *left, struct triple *right)
7716 {
7717         struct type *type;
7718         /* Sanity checks to ensure I am working with the proper types */
7719         ptr_arithmetic(state, left);
7720         arithmetic(state, right);
7721         if (TYPE_ARITHMETIC(left->type->type) && 
7722                 TYPE_ARITHMETIC(right->type->type)) {
7723                 type = arithmetic_result(state, left, right);
7724         }
7725         else if (TYPE_PTR(left->type->type)) {
7726                 type = left->type;
7727         }
7728         else {
7729                 internal_error(state, 0, "huh?");
7730                 type = 0;
7731         }
7732         return type;
7733 }
7734
7735 /* boolean helper function */
7736
7737 static struct triple *ltrue_expr(struct compile_state *state, 
7738         struct triple *expr)
7739 {
7740         switch(expr->op) {
7741         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
7742         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
7743         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
7744                 /* If the expression is already boolean do nothing */
7745                 break;
7746         default:
7747                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
7748                 break;
7749         }
7750         return expr;
7751 }
7752
7753 static struct triple *lfalse_expr(struct compile_state *state, 
7754         struct triple *expr)
7755 {
7756         return triple(state, OP_LFALSE, &int_type, expr, 0);
7757 }
7758
7759 static struct triple *mkland_expr(
7760         struct compile_state *state,
7761         struct triple *left, struct triple *right)
7762 {
7763         struct triple *def, *val, *var, *jmp, *mid, *end;
7764
7765         /* Generate some intermediate triples */
7766         end = label(state);
7767         var = variable(state, &int_type);
7768         
7769         /* Store the left hand side value */
7770         left = write_expr(state, var, left);
7771
7772         /* Jump if the value is false */
7773         jmp =  branch(state, end, 
7774                 lfalse_expr(state, read_expr(state, var)));
7775         mid = label(state);
7776         
7777         /* Store the right hand side value */
7778         right = write_expr(state, var, right);
7779
7780         /* An expression for the computed value */
7781         val = read_expr(state, var);
7782
7783         /* Generate the prog for a logical and */
7784         def = mkprog(state, var, left, jmp, mid, right, end, val, 0);
7785         
7786         return def;
7787 }
7788
7789 static struct triple *mklor_expr(
7790         struct compile_state *state,
7791         struct triple *left, struct triple *right)
7792 {
7793         struct triple *def, *val, *var, *jmp, *mid, *end;
7794
7795         /* Generate some intermediate triples */
7796         end = label(state);
7797         var = variable(state, &int_type);
7798         
7799         /* Store the left hand side value */
7800         left = write_expr(state, var, left);
7801         
7802         /* Jump if the value is true */
7803         jmp = branch(state, end, read_expr(state, var));
7804         mid = label(state);
7805         
7806         /* Store the right hand side value */
7807         right = write_expr(state, var, right);
7808                 
7809         /* An expression for the computed value*/
7810         val = read_expr(state, var);
7811
7812         /* Generate the prog for a logical or */
7813         def = mkprog(state, var, left, jmp, mid, right, end, val, 0);
7814
7815         return def;
7816 }
7817
7818 static struct triple *mkcond_expr(
7819         struct compile_state *state, 
7820         struct triple *test, struct triple *left, struct triple *right)
7821 {
7822         struct triple *def, *val, *var, *jmp1, *jmp2, *top, *mid, *end;
7823         struct type *result_type;
7824         unsigned int left_type, right_type;
7825         bool(state, test);
7826         left_type = left->type->type;
7827         right_type = right->type->type;
7828         result_type = 0;
7829         /* Both operands have arithmetic type */
7830         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
7831                 result_type = arithmetic_result(state, left, right);
7832         }
7833         /* Both operands have void type */
7834         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
7835                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
7836                 result_type = &void_type;
7837         }
7838         /* pointers to the same type... */
7839         else if ((result_type = compatible_ptrs(left->type, right->type))) {
7840                 ;
7841         }
7842         /* Both operands are pointers and left is a pointer to void */
7843         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7844                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7845                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7846                 result_type = right->type;
7847         }
7848         /* Both operands are pointers and right is a pointer to void */
7849         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7850                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7851                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7852                 result_type = left->type;
7853         }
7854         if (!result_type) {
7855                 error(state, 0, "Incompatible types in conditional expression");
7856         }
7857         /* Generate some intermediate triples */
7858         mid = label(state);
7859         end = label(state);
7860         var = variable(state, result_type);
7861
7862         /* Branch if the test is false */
7863         jmp1 = branch(state, mid, lfalse_expr(state, read_expr(state, test)));
7864         top = label(state);
7865
7866         /* Store the left hand side value */
7867         left = write_expr(state, var, left);
7868
7869         /* Branch to the end */
7870         jmp2 = branch(state, end, 0);
7871
7872         /* Store the right hand side value */
7873         right = write_expr(state, var, right);
7874         
7875         /* An expression for the computed value */
7876         val = read_expr(state, var);
7877
7878         /* Generate the prog for a conditional expression */
7879         def = mkprog(state, var, jmp1, top, left, jmp2, mid, right, end, val, 0);
7880
7881         return def;
7882 }
7883
7884
7885 static int expr_depth(struct compile_state *state, struct triple *ins)
7886 {
7887 #warning "FIXME move optimal ordering of subexpressions into the optimizer"
7888         int count;
7889         count = 0;
7890         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
7891                 count = 0;
7892         }
7893         else if (ins->op == OP_DEREF) {
7894                 count = expr_depth(state, RHS(ins, 0)) - 1;
7895         }
7896         else if (ins->op == OP_VAL) {
7897                 count = expr_depth(state, RHS(ins, 0)) - 1;
7898         }
7899         else if (ins->op == OP_FCALL) {
7900                 /* Don't figure the depth of a call just guess it is huge */
7901                 count = 1000;
7902         }
7903         else {
7904                 struct triple **expr;
7905                 expr = triple_rhs(state, ins, 0);
7906                 for(;expr; expr = triple_rhs(state, ins, expr)) {
7907                         if (*expr) {
7908                                 int depth;
7909                                 depth = expr_depth(state, *expr);
7910                                 if (depth > count) {
7911                                         count = depth;
7912                                 }
7913                         }
7914                 }
7915         }
7916         return count + 1;
7917 }
7918
7919 static struct triple *flatten_generic(
7920         struct compile_state *state, struct triple *first, struct triple *ptr,
7921         int ignored)
7922 {
7923         struct rhs_vector {
7924                 int depth;
7925                 struct triple **ins;
7926         } vector[MAX_RHS];
7927         int i, rhs, lhs;
7928         /* Only operations with just a rhs and a lhs should come here */
7929         rhs = ptr->rhs;
7930         lhs = ptr->lhs;
7931         if (TRIPLE_SIZE(ptr) != lhs + rhs + ignored) {
7932                 internal_error(state, ptr, "unexpected args for: %d %s",
7933                         ptr->op, tops(ptr->op));
7934         }
7935         /* Find the depth of the rhs elements */
7936         for(i = 0; i < rhs; i++) {
7937                 vector[i].ins = &RHS(ptr, i);
7938                 vector[i].depth = expr_depth(state, *vector[i].ins);
7939         }
7940         /* Selection sort the rhs */
7941         for(i = 0; i < rhs; i++) {
7942                 int j, max = i;
7943                 for(j = i + 1; j < rhs; j++ ) {
7944                         if (vector[j].depth > vector[max].depth) {
7945                                 max = j;
7946                         }
7947                 }
7948                 if (max != i) {
7949                         struct rhs_vector tmp;
7950                         tmp = vector[i];
7951                         vector[i] = vector[max];
7952                         vector[max] = tmp;
7953                 }
7954         }
7955         /* Now flatten the rhs elements */
7956         for(i = 0; i < rhs; i++) {
7957                 *vector[i].ins = flatten(state, first, *vector[i].ins);
7958                 use_triple(*vector[i].ins, ptr);
7959         }
7960         if (lhs) {
7961                 insert_triple(state, first, ptr);
7962                 ptr->id |= TRIPLE_FLAG_FLATTENED;
7963                 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7964                 
7965                 /* Now flatten the lhs elements */
7966                 for(i = 0; i < lhs; i++) {
7967                         struct triple **ins = &LHS(ptr, i);
7968                         *ins = flatten(state, first, *ins);
7969                         use_triple(*ins, ptr);
7970                 }
7971         }
7972         return ptr;
7973 }
7974
7975 static struct triple *flatten_prog(
7976         struct compile_state *state, struct triple *first, struct triple *ptr)
7977 {
7978         struct triple *head, *body, *val;
7979         head = RHS(ptr, 0);
7980         RHS(ptr, 0) = 0;
7981         val  = head->prev;
7982         body = head->next;
7983         release_triple(state, head);
7984         release_triple(state, ptr);
7985         val->next        = first;
7986         body->prev       = first->prev;
7987         body->prev->next = body;
7988         val->next->prev  = val;
7989
7990         if (triple_is_cbranch(state, body->prev) ||
7991                 triple_is_call(state, body->prev)) {
7992                 unuse_triple(first, body->prev);
7993                 use_triple(body, body->prev);
7994         }
7995         
7996         if (!(val->id & TRIPLE_FLAG_FLATTENED)) {
7997                 internal_error(state, val, "val not flattened?");
7998         }
7999
8000         return val;
8001 }
8002
8003
8004 static struct triple *flatten_part(
8005         struct compile_state *state, struct triple *first, struct triple *ptr)
8006 {
8007         if (!triple_is_part(state, ptr)) {
8008                 internal_error(state, ptr,  "not a part");
8009         }
8010         if (ptr->rhs || ptr->lhs || ptr->targ || (ptr->misc != 1)) {
8011                 internal_error(state, ptr, "unexpected args for: %d %s",
8012                         ptr->op, tops(ptr->op));
8013         }
8014         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8015         use_triple(MISC(ptr, 0), ptr);
8016         return flatten_generic(state, first, ptr, 1);
8017 }
8018
8019 static struct triple *flatten(
8020         struct compile_state *state, struct triple *first, struct triple *ptr)
8021 {
8022         struct triple *orig_ptr;
8023         if (!ptr)
8024                 return 0;
8025         do {
8026                 orig_ptr = ptr;
8027                 /* Only flatten triples once */
8028                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
8029                         return ptr;
8030                 }
8031                 switch(ptr->op) {
8032                 case OP_VAL:
8033                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
8034                         return MISC(ptr, 0);
8035                         break;
8036                 case OP_PROG:
8037                         ptr = flatten_prog(state, first, ptr);
8038                         break;
8039                 case OP_FCALL:
8040                         ptr = flatten_generic(state, first, ptr, 1);
8041                         insert_triple(state, first, ptr);
8042                         ptr->id |= TRIPLE_FLAG_FLATTENED;
8043                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
8044                         if (ptr->next != ptr) {
8045                                 use_triple(ptr->next, ptr);
8046                         }
8047                         break;
8048                 case OP_READ:
8049                 case OP_LOAD:
8050                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
8051                         use_triple(RHS(ptr, 0), ptr);
8052                         break;
8053                 case OP_WRITE:
8054                         ptr = flatten_generic(state, first, ptr, 1);
8055                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8056                         use_triple(MISC(ptr, 0), ptr);
8057                         break;
8058                 case OP_BRANCH:
8059                         use_triple(TARG(ptr, 0), ptr);
8060                         break;
8061                 case OP_CBRANCH:
8062                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
8063                         use_triple(RHS(ptr, 0), ptr);
8064                         use_triple(TARG(ptr, 0), ptr);
8065                         insert_triple(state, first, ptr);
8066                         ptr->id |= TRIPLE_FLAG_FLATTENED;
8067                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
8068                         if (ptr->next != ptr) {
8069                                 use_triple(ptr->next, ptr);
8070                         }
8071                         break;
8072                 case OP_CALL:
8073                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8074                         use_triple(MISC(ptr, 0), ptr);
8075                         use_triple(TARG(ptr, 0), ptr);
8076                         insert_triple(state, first, ptr);
8077                         ptr->id |= TRIPLE_FLAG_FLATTENED;
8078                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
8079                         if (ptr->next != ptr) {
8080                                 use_triple(ptr->next, ptr);
8081                         }
8082                         break;
8083                 case OP_RET:
8084                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
8085                         use_triple(RHS(ptr, 0), ptr);
8086                         break;
8087                 case OP_BLOBCONST:
8088                         insert_triple(state, state->global_pool, ptr);
8089                         ptr->id |= TRIPLE_FLAG_FLATTENED;
8090                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
8091                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
8092                         use_triple(MISC(ptr, 0), ptr);
8093                         break;
8094                 case OP_DEREF:
8095                         /* Since OP_DEREF is just a marker delete it when I flatten it */
8096                         ptr = RHS(ptr, 0);
8097                         RHS(orig_ptr, 0) = 0;
8098                         free_triple(state, orig_ptr);
8099                         break;
8100                 case OP_DOT:
8101                         if (RHS(ptr, 0)->op == OP_DEREF) {
8102                                 struct triple *base, *left;
8103                                 ulong_t offset;
8104                                 base = MISC(ptr, 0);
8105                                 offset = bits_to_bytes(field_offset(state, base->type, ptr->u.field));
8106                                 left = RHS(base, 0);
8107                                 ptr = triple(state, OP_ADD, left->type, 
8108                                         read_expr(state, left),
8109                                         int_const(state, &ulong_type, offset));
8110                                 free_triple(state, base);
8111                         }
8112                         else {
8113                                 ptr = flatten_part(state, first, ptr);
8114                         }
8115                         break;
8116                 case OP_INDEX:
8117                         if (RHS(ptr, 0)->op == OP_DEREF) {
8118                                 struct triple *base, *left;
8119                                 ulong_t offset;
8120                                 base = MISC(ptr, 0);
8121                                 offset = bits_to_bytes(index_offset(state, base->type, ptr->u.cval));
8122                                 left = RHS(base, 0);
8123                                 ptr = triple(state, OP_ADD, left->type,
8124                                         read_expr(state, left),
8125                                         int_const(state, &long_type, offset));
8126                                 free_triple(state, base);
8127                         }
8128                         else {
8129                                 ptr = flatten_part(state, first, ptr);
8130                         }
8131                         break;
8132                 case OP_PIECE:
8133                         ptr = flatten_part(state, first, ptr);
8134                         use_triple(ptr, MISC(ptr, 0));
8135                         break;
8136                 case OP_ADDRCONST:
8137                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8138                         use_triple(MISC(ptr, 0), ptr);
8139                         break;
8140                 case OP_SDECL:
8141                         first = state->global_pool;
8142                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8143                         use_triple(MISC(ptr, 0), ptr);
8144                         insert_triple(state, first, ptr);
8145                         ptr->id |= TRIPLE_FLAG_FLATTENED;
8146                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
8147                         return ptr;
8148                 case OP_ADECL:
8149                         ptr = flatten_generic(state, first, ptr, 0);
8150                         break;
8151                 default:
8152                         /* Flatten the easy cases we don't override */
8153                         ptr = flatten_generic(state, first, ptr, 0);
8154                         break;
8155                 }
8156         } while(ptr && (ptr != orig_ptr));
8157         if (ptr && !(ptr->id & TRIPLE_FLAG_FLATTENED)) {
8158                 insert_triple(state, first, ptr);
8159                 ptr->id |= TRIPLE_FLAG_FLATTENED;
8160                 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8161         }
8162         return ptr;
8163 }
8164
8165 static void release_expr(struct compile_state *state, struct triple *expr)
8166 {
8167         struct triple *head;
8168         head = label(state);
8169         flatten(state, head, expr);
8170         while(head->next != head) {
8171                 release_triple(state, head->next);
8172         }
8173         free_triple(state, head);
8174 }
8175
8176 static int replace_rhs_use(struct compile_state *state,
8177         struct triple *orig, struct triple *new, struct triple *use)
8178 {
8179         struct triple **expr;
8180         int found;
8181         found = 0;
8182         expr = triple_rhs(state, use, 0);
8183         for(;expr; expr = triple_rhs(state, use, expr)) {
8184                 if (*expr == orig) {
8185                         *expr = new;
8186                         found = 1;
8187                 }
8188         }
8189         if (found) {
8190                 unuse_triple(orig, use);
8191                 use_triple(new, use);
8192         }
8193         return found;
8194 }
8195
8196 static int replace_lhs_use(struct compile_state *state,
8197         struct triple *orig, struct triple *new, struct triple *use)
8198 {
8199         struct triple **expr;
8200         int found;
8201         found = 0;
8202         expr = triple_lhs(state, use, 0);
8203         for(;expr; expr = triple_lhs(state, use, expr)) {
8204                 if (*expr == orig) {
8205                         *expr = new;
8206                         found = 1;
8207                 }
8208         }
8209         if (found) {
8210                 unuse_triple(orig, use);
8211                 use_triple(new, use);
8212         }
8213         return found;
8214 }
8215
8216 static int replace_misc_use(struct compile_state *state,
8217         struct triple *orig, struct triple *new, struct triple *use)
8218 {
8219         struct triple **expr;
8220         int found;
8221         found = 0;
8222         expr = triple_misc(state, use, 0);
8223         for(;expr; expr = triple_misc(state, use, expr)) {
8224                 if (*expr == orig) {
8225                         *expr = new;
8226                         found = 1;
8227                 }
8228         }
8229         if (found) {
8230                 unuse_triple(orig, use);
8231                 use_triple(new, use);
8232         }
8233         return found;
8234 }
8235
8236 static int replace_targ_use(struct compile_state *state,
8237         struct triple *orig, struct triple *new, struct triple *use)
8238 {
8239         struct triple **expr;
8240         int found;
8241         found = 0;
8242         expr = triple_targ(state, use, 0);
8243         for(;expr; expr = triple_targ(state, use, expr)) {
8244                 if (*expr == orig) {
8245                         *expr = new;
8246                         found = 1;
8247                 }
8248         }
8249         if (found) {
8250                 unuse_triple(orig, use);
8251                 use_triple(new, use);
8252         }
8253         return found;
8254 }
8255
8256 static void replace_use(struct compile_state *state,
8257         struct triple *orig, struct triple *new, struct triple *use)
8258 {
8259         int found;
8260         found = 0;
8261         found |= replace_rhs_use(state, orig, new, use);
8262         found |= replace_lhs_use(state, orig, new, use);
8263         found |= replace_misc_use(state, orig, new, use);
8264         found |= replace_targ_use(state, orig, new, use);
8265         if (!found) {
8266                 internal_error(state, use, "use without use");
8267         }
8268 }
8269
8270 static void propogate_use(struct compile_state *state,
8271         struct triple *orig, struct triple *new)
8272 {
8273         struct triple_set *user, *next;
8274         for(user = orig->use; user; user = next) {
8275                 /* Careful replace_use modifies the use chain and
8276                  * removes use.  So we must get a copy of the next
8277                  * entry early.
8278                  */
8279                 next = user->next;
8280                 replace_use(state, orig, new, user->member);
8281         }
8282         if (orig->use) {
8283                 internal_error(state, orig, "used after propogate_use");
8284         }
8285 }
8286
8287 /*
8288  * Code generators
8289  * ===========================
8290  */
8291
8292 static struct triple *mk_cast_expr(
8293         struct compile_state *state, struct type *type, struct triple *expr)
8294 {
8295         struct triple *def;
8296         def = read_expr(state, expr);
8297         def = triple(state, OP_CONVERT, type, def, 0);
8298         return def;
8299 }
8300
8301 static struct triple *mk_add_expr(
8302         struct compile_state *state, struct triple *left, struct triple *right)
8303 {
8304         struct type *result_type;
8305         /* Put pointer operands on the left */
8306         if (is_pointer(right)) {
8307                 struct triple *tmp;
8308                 tmp = left;
8309                 left = right;
8310                 right = tmp;
8311         }
8312         left  = read_expr(state, left);
8313         right = read_expr(state, right);
8314         result_type = ptr_arithmetic_result(state, left, right);
8315         if (is_pointer(left)) {
8316                 struct type *ptr_math;
8317                 int op;
8318                 if (is_signed(right->type)) {
8319                         ptr_math = &long_type;
8320                         op = OP_SMUL;
8321                 } else {
8322                         ptr_math = &ulong_type;
8323                         op = OP_UMUL;
8324                 }
8325                 if (!equiv_types(right->type, ptr_math)) {
8326                         right = mk_cast_expr(state, ptr_math, right);
8327                 }
8328                 right = triple(state, op, ptr_math, right, 
8329                         int_const(state, ptr_math, 
8330                                 size_of_in_bytes(state, left->type->left)));
8331         }
8332         return triple(state, OP_ADD, result_type, left, right);
8333 }
8334
8335 static struct triple *mk_sub_expr(
8336         struct compile_state *state, struct triple *left, struct triple *right)
8337 {
8338         struct type *result_type;
8339         result_type = ptr_arithmetic_result(state, left, right);
8340         left  = read_expr(state, left);
8341         right = read_expr(state, right);
8342         if (is_pointer(left)) {
8343                 struct type *ptr_math;
8344                 int op;
8345                 if (is_signed(right->type)) {
8346                         ptr_math = &long_type;
8347                         op = OP_SMUL;
8348                 } else {
8349                         ptr_math = &ulong_type;
8350                         op = OP_UMUL;
8351                 }
8352                 if (!equiv_types(right->type, ptr_math)) {
8353                         right = mk_cast_expr(state, ptr_math, right);
8354                 }
8355                 right = triple(state, op, ptr_math, right, 
8356                         int_const(state, ptr_math, 
8357                                 size_of_in_bytes(state, left->type->left)));
8358         }
8359         return triple(state, OP_SUB, result_type, left, right);
8360 }
8361
8362 static struct triple *mk_pre_inc_expr(
8363         struct compile_state *state, struct triple *def)
8364 {
8365         struct triple *val;
8366         lvalue(state, def);
8367         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
8368         return triple(state, OP_VAL, def->type,
8369                 write_expr(state, def, val),
8370                 val);
8371 }
8372
8373 static struct triple *mk_pre_dec_expr(
8374         struct compile_state *state, struct triple *def)
8375 {
8376         struct triple *val;
8377         lvalue(state, def);
8378         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
8379         return triple(state, OP_VAL, def->type,
8380                 write_expr(state, def, val),
8381                 val);
8382 }
8383
8384 static struct triple *mk_post_inc_expr(
8385         struct compile_state *state, struct triple *def)
8386 {
8387         struct triple *val;
8388         lvalue(state, def);
8389         val = read_expr(state, def);
8390         return triple(state, OP_VAL, def->type,
8391                 write_expr(state, def,
8392                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
8393                 , val);
8394 }
8395
8396 static struct triple *mk_post_dec_expr(
8397         struct compile_state *state, struct triple *def)
8398 {
8399         struct triple *val;
8400         lvalue(state, def);
8401         val = read_expr(state, def);
8402         return triple(state, OP_VAL, def->type, 
8403                 write_expr(state, def,
8404                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
8405                 , val);
8406 }
8407
8408 static struct triple *mk_subscript_expr(
8409         struct compile_state *state, struct triple *left, struct triple *right)
8410 {
8411         left  = read_expr(state, left);
8412         right = read_expr(state, right);
8413         if (!is_pointer(left) && !is_pointer(right)) {
8414                 error(state, left, "subscripted value is not a pointer");
8415         }
8416         return mk_deref_expr(state, mk_add_expr(state, left, right));
8417 }
8418
8419
8420 /*
8421  * Compile time evaluation
8422  * ===========================
8423  */
8424 static int is_const(struct triple *ins)
8425 {
8426         return IS_CONST_OP(ins->op);
8427 }
8428
8429 static int is_simple_const(struct triple *ins)
8430 {
8431         /* Is this a constant that u.cval has the value.
8432          * Or equivalently is this a constant that read_const
8433          * works on.
8434          * So far only OP_INTCONST qualifies.  
8435          */
8436         return (ins->op == OP_INTCONST);
8437 }
8438
8439 static int constants_equal(struct compile_state *state, 
8440         struct triple *left, struct triple *right)
8441 {
8442         int equal;
8443         if ((left->op == OP_UNKNOWNVAL) || (right->op == OP_UNKNOWNVAL)) {
8444                 equal = 0;
8445         }
8446         else if (!is_const(left) || !is_const(right)) {
8447                 equal = 0;
8448         }
8449         else if (left->op != right->op) {
8450                 equal = 0;
8451         }
8452         else if (!equiv_types(left->type, right->type)) {
8453                 equal = 0;
8454         }
8455         else {
8456                 equal = 0;
8457                 switch(left->op) {
8458                 case OP_INTCONST:
8459                         if (left->u.cval == right->u.cval) {
8460                                 equal = 1;
8461                         }
8462                         break;
8463                 case OP_BLOBCONST:
8464                 {
8465                         size_t lsize, rsize, bytes;
8466                         lsize = size_of(state, left->type);
8467                         rsize = size_of(state, right->type);
8468                         if (lsize != rsize) {
8469                                 break;
8470                         }
8471                         bytes = bits_to_bytes(lsize);
8472                         if (memcmp(left->u.blob, right->u.blob, bytes) == 0) {
8473                                 equal = 1;
8474                         }
8475                         break;
8476                 }
8477                 case OP_ADDRCONST:
8478                         if ((MISC(left, 0) == MISC(right, 0)) &&
8479                                 (left->u.cval == right->u.cval)) {
8480                                 equal = 1;
8481                         }
8482                         break;
8483                 default:
8484                         internal_error(state, left, "uknown constant type");
8485                         break;
8486                 }
8487         }
8488         return equal;
8489 }
8490
8491 static int is_zero(struct triple *ins)
8492 {
8493         return is_simple_const(ins) && (ins->u.cval == 0);
8494 }
8495
8496 static int is_one(struct triple *ins)
8497 {
8498         return is_simple_const(ins) && (ins->u.cval == 1);
8499 }
8500
8501 static long_t bit_count(ulong_t value)
8502 {
8503         int count;
8504         int i;
8505         count = 0;
8506         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8507                 ulong_t mask;
8508                 mask = 1;
8509                 mask <<= i;
8510                 if (value & mask) {
8511                         count++;
8512                 }
8513         }
8514         return count;
8515         
8516 }
8517 static long_t bsr(ulong_t value)
8518 {
8519         int i;
8520         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8521                 ulong_t mask;
8522                 mask = 1;
8523                 mask <<= i;
8524                 if (value & mask) {
8525                         return i;
8526                 }
8527         }
8528         return -1;
8529 }
8530
8531 static long_t bsf(ulong_t value)
8532 {
8533         int i;
8534         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
8535                 ulong_t mask;
8536                 mask = 1;
8537                 mask <<= 1;
8538                 if (value & mask) {
8539                         return i;
8540                 }
8541         }
8542         return -1;
8543 }
8544
8545 static long_t log2(ulong_t value)
8546 {
8547         return bsr(value);
8548 }
8549
8550 static long_t tlog2(struct triple *ins)
8551 {
8552         return log2(ins->u.cval);
8553 }
8554
8555 static int is_pow2(struct triple *ins)
8556 {
8557         ulong_t value, mask;
8558         long_t log;
8559         if (!is_const(ins)) {
8560                 return 0;
8561         }
8562         value = ins->u.cval;
8563         log = log2(value);
8564         if (log == -1) {
8565                 return 0;
8566         }
8567         mask = 1;
8568         mask <<= log;
8569         return  ((value & mask) == value);
8570 }
8571
8572 static ulong_t read_const(struct compile_state *state,
8573         struct triple *ins, struct triple *rhs)
8574 {
8575         switch(rhs->type->type &TYPE_MASK) {
8576         case TYPE_CHAR:   
8577         case TYPE_SHORT:
8578         case TYPE_INT:
8579         case TYPE_LONG:
8580         case TYPE_UCHAR:   
8581         case TYPE_USHORT:  
8582         case TYPE_UINT:
8583         case TYPE_ULONG:
8584         case TYPE_POINTER:
8585         case TYPE_BITFIELD:
8586                 break;
8587         default:
8588                 fprintf(state->errout, "type: ");
8589                 name_of(state->errout, rhs->type);
8590                 fprintf(state->errout, "\n");
8591                 internal_warning(state, rhs, "bad type to read_const");
8592                 break;
8593         }
8594         if (!is_simple_const(rhs)) {
8595                 internal_error(state, rhs, "bad op to read_const");
8596         }
8597         return rhs->u.cval;
8598 }
8599
8600 static long_t read_sconst(struct compile_state *state,
8601         struct triple *ins, struct triple *rhs)
8602 {
8603         return (long_t)(rhs->u.cval);
8604 }
8605
8606 int const_ltrue(struct compile_state *state, struct triple *ins, struct triple *rhs)
8607 {
8608         if (!is_const(rhs)) {
8609                 internal_error(state, 0, "non const passed to const_true");
8610         }
8611         return !is_zero(rhs);
8612 }
8613
8614 int const_eq(struct compile_state *state, struct triple *ins,
8615         struct triple *left, struct triple *right)
8616 {
8617         int result;
8618         if (!is_const(left) || !is_const(right)) {
8619                 internal_warning(state, ins, "non const passed to const_eq");
8620                 result = -1;
8621         }
8622         else if (left == right) {
8623                 result = 1;
8624         }
8625         else if (is_simple_const(left) && is_simple_const(right)) {
8626                 ulong_t lval, rval;
8627                 lval = read_const(state, ins, left);
8628                 rval = read_const(state, ins, right);
8629                 result = (lval == rval);
8630         }
8631         else if ((left->op == OP_ADDRCONST) && 
8632                 (right->op == OP_ADDRCONST)) {
8633                 result = (MISC(left, 0) == MISC(right, 0)) &&
8634                         (left->u.cval == right->u.cval);
8635         }
8636         else {
8637                 internal_warning(state, ins, "incomparable constants passed to const_eq");
8638                 result = -1;
8639         }
8640         return result;
8641         
8642 }
8643
8644 int const_ucmp(struct compile_state *state, struct triple *ins,
8645         struct triple *left, struct triple *right)
8646 {
8647         int result;
8648         if (!is_const(left) || !is_const(right)) {
8649                 internal_warning(state, ins, "non const past to const_ucmp");
8650                 result = -2;
8651         }
8652         else if (left == right) {
8653                 result = 0;
8654         }
8655         else if (is_simple_const(left) && is_simple_const(right)) {
8656                 ulong_t lval, rval;
8657                 lval = read_const(state, ins, left);
8658                 rval = read_const(state, ins, right);
8659                 result = 0;
8660                 if (lval > rval) {
8661                         result = 1;
8662                 } else if (rval > lval) {
8663                         result = -1;
8664                 }
8665         }
8666         else if ((left->op == OP_ADDRCONST) && 
8667                 (right->op == OP_ADDRCONST) &&
8668                 (MISC(left, 0) == MISC(right, 0))) {
8669                 result = 0;
8670                 if (left->u.cval > right->u.cval) {
8671                         result = 1;
8672                 } else if (left->u.cval < right->u.cval) {
8673                         result = -1;
8674                 }
8675         }
8676         else {
8677                 internal_warning(state, ins, "incomparable constants passed to const_ucmp");
8678                 result = -2;
8679         }
8680         return result;
8681 }
8682
8683 int const_scmp(struct compile_state *state, struct triple *ins,
8684         struct triple *left, struct triple *right)
8685 {
8686         int result;
8687         if (!is_const(left) || !is_const(right)) {
8688                 internal_warning(state, ins, "non const past to ucmp_const");
8689                 result = -2;
8690         }
8691         else if (left == right) {
8692                 result = 0;
8693         }
8694         else if (is_simple_const(left) && is_simple_const(right)) {
8695                 long_t lval, rval;
8696                 lval = read_sconst(state, ins, left);
8697                 rval = read_sconst(state, ins, right);
8698                 result = 0;
8699                 if (lval > rval) {
8700                         result = 1;
8701                 } else if (rval > lval) {
8702                         result = -1;
8703                 }
8704         }
8705         else {
8706                 internal_warning(state, ins, "incomparable constants passed to const_scmp");
8707                 result = -2;
8708         }
8709         return result;
8710 }
8711
8712 static void unuse_rhs(struct compile_state *state, struct triple *ins)
8713 {
8714         struct triple **expr;
8715         expr = triple_rhs(state, ins, 0);
8716         for(;expr;expr = triple_rhs(state, ins, expr)) {
8717                 if (*expr) {
8718                         unuse_triple(*expr, ins);
8719                         *expr = 0;
8720                 }
8721         }
8722 }
8723
8724 static void unuse_lhs(struct compile_state *state, struct triple *ins)
8725 {
8726         struct triple **expr;
8727         expr = triple_lhs(state, ins, 0);
8728         for(;expr;expr = triple_lhs(state, ins, expr)) {
8729                 unuse_triple(*expr, ins);
8730                 *expr = 0;
8731         }
8732 }
8733
8734 static void unuse_misc(struct compile_state *state, struct triple *ins)
8735 {
8736         struct triple **expr;
8737         expr = triple_misc(state, ins, 0);
8738         for(;expr;expr = triple_misc(state, ins, expr)) {
8739                 unuse_triple(*expr, ins);
8740                 *expr = 0;
8741         }
8742 }
8743
8744 static void unuse_targ(struct compile_state *state, struct triple *ins)
8745 {
8746         int i;
8747         struct triple **slot;
8748         slot = &TARG(ins, 0);
8749         for(i = 0; i < ins->targ; i++) {
8750                 unuse_triple(slot[i], ins);
8751                 slot[i] = 0;
8752         }
8753 }
8754
8755 static void check_lhs(struct compile_state *state, struct triple *ins)
8756 {
8757         struct triple **expr;
8758         expr = triple_lhs(state, ins, 0);
8759         for(;expr;expr = triple_lhs(state, ins, expr)) {
8760                 internal_error(state, ins, "unexpected lhs");
8761         }
8762         
8763 }
8764
8765 static void check_misc(struct compile_state *state, struct triple *ins)
8766 {
8767         struct triple **expr;
8768         expr = triple_misc(state, ins, 0);
8769         for(;expr;expr = triple_misc(state, ins, expr)) {
8770                 if (*expr) {
8771                         internal_error(state, ins, "unexpected misc");
8772                 }
8773         }
8774 }
8775
8776 static void check_targ(struct compile_state *state, struct triple *ins)
8777 {
8778         struct triple **expr;
8779         expr = triple_targ(state, ins, 0);
8780         for(;expr;expr = triple_targ(state, ins, expr)) {
8781                 internal_error(state, ins, "unexpected targ");
8782         }
8783 }
8784
8785 static void wipe_ins(struct compile_state *state, struct triple *ins)
8786 {
8787         /* Becareful which instructions you replace the wiped
8788          * instruction with, as there are not enough slots
8789          * in all instructions to hold all others.
8790          */
8791         check_targ(state, ins);
8792         check_misc(state, ins);
8793         unuse_rhs(state, ins);
8794         unuse_lhs(state, ins);
8795         ins->lhs  = 0;
8796         ins->rhs  = 0;
8797         ins->misc = 0;
8798         ins->targ = 0;
8799 }
8800
8801 static void wipe_branch(struct compile_state *state, struct triple *ins)
8802 {
8803         /* Becareful which instructions you replace the wiped
8804          * instruction with, as there are not enough slots
8805          * in all instructions to hold all others.
8806          */
8807         unuse_rhs(state, ins);
8808         unuse_lhs(state, ins);
8809         unuse_misc(state, ins);
8810         unuse_targ(state, ins);
8811         ins->lhs  = 0;
8812         ins->rhs  = 0;
8813         ins->misc = 0;
8814         ins->targ = 0;
8815 }
8816
8817 static void mkcopy(struct compile_state *state, 
8818         struct triple *ins, struct triple *rhs)
8819 {
8820         struct block *block;
8821         if (!equiv_types(ins->type, rhs->type)) {
8822                 FILE *fp = state->errout;
8823                 fprintf(fp, "src type: ");
8824                 name_of(fp, rhs->type);
8825                 fprintf(fp, "\ndst type: ");
8826                 name_of(fp, ins->type);
8827                 fprintf(fp, "\n");
8828                 internal_error(state, ins, "mkcopy type mismatch");
8829         }
8830         block = block_of_triple(state, ins);
8831         wipe_ins(state, ins);
8832         ins->op = OP_COPY;
8833         ins->rhs  = 1;
8834         ins->u.block = block;
8835         RHS(ins, 0) = rhs;
8836         use_triple(RHS(ins, 0), ins);
8837 }
8838
8839 static void mkconst(struct compile_state *state, 
8840         struct triple *ins, ulong_t value)
8841 {
8842         if (!is_integral(ins) && !is_pointer(ins)) {
8843                 fprintf(state->errout, "type: ");
8844                 name_of(state->errout, ins->type);
8845                 fprintf(state->errout, "\n");
8846                 internal_error(state, ins, "unknown type to make constant value: %ld",
8847                         value);
8848         }
8849         wipe_ins(state, ins);
8850         ins->op = OP_INTCONST;
8851         ins->u.cval = value;
8852 }
8853
8854 static void mkaddr_const(struct compile_state *state,
8855         struct triple *ins, struct triple *sdecl, ulong_t value)
8856 {
8857         if ((sdecl->op != OP_SDECL) && (sdecl->op != OP_LABEL)) {
8858                 internal_error(state, ins, "bad base for addrconst");
8859         }
8860         wipe_ins(state, ins);
8861         ins->op = OP_ADDRCONST;
8862         ins->misc = 1;
8863         MISC(ins, 0) = sdecl;
8864         ins->u.cval = value;
8865         use_triple(sdecl, ins);
8866 }
8867
8868 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8869 static void print_tuple(struct compile_state *state, 
8870         struct triple *ins, struct triple *tuple)
8871 {
8872         FILE *fp = state->dbgout;
8873         fprintf(fp, "%5s %p tuple: %p ", tops(ins->op), ins, tuple);
8874         name_of(fp, tuple->type);
8875         if (tuple->lhs > 0) {
8876                 fprintf(fp, " lhs: ");
8877                 name_of(fp, LHS(tuple, 0)->type);
8878         }
8879         fprintf(fp, "\n");
8880         
8881 }
8882 #endif
8883
8884 static struct triple *decompose_with_tuple(struct compile_state *state, 
8885         struct triple *ins, struct triple *tuple)
8886 {
8887         struct triple *next;
8888         next = ins->next;
8889         flatten(state, next, tuple);
8890 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8891         print_tuple(state, ins, tuple);
8892 #endif
8893
8894         if (!is_compound_type(tuple->type) && (tuple->lhs > 0)) {
8895                 struct triple *tmp;
8896                 if (tuple->lhs != 1) {
8897                         internal_error(state, tuple, "plain type in multiple registers?");
8898                 }
8899                 tmp = LHS(tuple, 0);
8900                 release_triple(state, tuple);
8901                 tuple = tmp;
8902         }
8903
8904         propogate_use(state, ins, tuple);
8905         release_triple(state, ins);
8906         
8907         return next;
8908 }
8909
8910 static struct triple *decompose_unknownval(struct compile_state *state,
8911         struct triple *ins)
8912 {
8913         struct triple *tuple;
8914         ulong_t i;
8915
8916 #if DEBUG_DECOMPOSE_HIRES
8917         FILE *fp = state->dbgout;
8918         fprintf(fp, "unknown type: ");
8919         name_of(fp, ins->type);
8920         fprintf(fp, "\n");
8921 #endif
8922
8923         get_occurance(ins->occurance);
8924         tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1, 
8925                 ins->occurance);
8926
8927         for(i = 0; i < tuple->lhs; i++) {
8928                 struct type *piece_type;
8929                 struct triple *unknown;
8930
8931                 piece_type = reg_type(state, ins->type, i * REG_SIZEOF_REG);
8932                 get_occurance(tuple->occurance);
8933                 unknown = alloc_triple(state, OP_UNKNOWNVAL, piece_type, 0, 0,
8934                         tuple->occurance);
8935                 LHS(tuple, i) = unknown;
8936         }
8937         return decompose_with_tuple(state, ins, tuple);
8938 }
8939
8940
8941 static struct triple *decompose_read(struct compile_state *state, 
8942         struct triple *ins)
8943 {
8944         struct triple *tuple, *lval;
8945         ulong_t i;
8946
8947         lval = RHS(ins, 0);
8948
8949         if (lval->op == OP_PIECE) {
8950                 return ins->next;
8951         }
8952         get_occurance(ins->occurance);
8953         tuple = alloc_triple(state, OP_TUPLE, lval->type, -1, -1,
8954                 ins->occurance);
8955
8956         if ((tuple->lhs != lval->lhs) &&
8957                 (!triple_is_def(state, lval) || (tuple->lhs != 1))) 
8958         {
8959                 internal_error(state, ins, "lhs size inconsistency?");
8960         }
8961         for(i = 0; i < tuple->lhs; i++) {
8962                 struct triple *piece, *read, *bitref;
8963                 if ((i != 0) || !triple_is_def(state, lval)) {
8964                         piece = LHS(lval, i);
8965                 } else {
8966                         piece = lval;
8967                 }
8968
8969                 /* See if the piece is really a bitref */
8970                 bitref = 0;
8971                 if (piece->op == OP_BITREF) {
8972                         bitref = piece;
8973                         piece = RHS(bitref, 0);
8974                 }
8975
8976                 get_occurance(tuple->occurance);
8977                 read = alloc_triple(state, OP_READ, piece->type, -1, -1, 
8978                         tuple->occurance);
8979                 RHS(read, 0) = piece;
8980
8981                 if (bitref) {
8982                         struct triple *extract;
8983                         int op;
8984                         if (is_signed(bitref->type->left)) {
8985                                 op = OP_SEXTRACT;
8986                         } else {
8987                                 op = OP_UEXTRACT;
8988                         }
8989                         get_occurance(tuple->occurance);
8990                         extract = alloc_triple(state, op, bitref->type, -1, -1,
8991                                 tuple->occurance);
8992                         RHS(extract, 0) = read;
8993                         extract->u.bitfield.size   = bitref->u.bitfield.size;
8994                         extract->u.bitfield.offset = bitref->u.bitfield.offset;
8995
8996                         read = extract;
8997                 }
8998
8999                 LHS(tuple, i) = read;
9000         }
9001         return decompose_with_tuple(state, ins, tuple);
9002 }
9003
9004 static struct triple *decompose_write(struct compile_state *state, 
9005         struct triple *ins)
9006 {
9007         struct triple *tuple, *lval, *val;
9008         ulong_t i;
9009         
9010         lval = MISC(ins, 0);
9011         val = RHS(ins, 0);
9012         get_occurance(ins->occurance);
9013         tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9014                 ins->occurance);
9015
9016         if ((tuple->lhs != lval->lhs) &&
9017                 (!triple_is_def(state, lval) || tuple->lhs != 1)) 
9018         {
9019                 internal_error(state, ins, "lhs size inconsistency?");
9020         }
9021         for(i = 0; i < tuple->lhs; i++) {
9022                 struct triple *piece, *write, *pval, *bitref;
9023                 if ((i != 0) || !triple_is_def(state, lval)) {
9024                         piece = LHS(lval, i);
9025                 } else {
9026                         piece = lval;
9027                 }
9028                 if ((i == 0) && (tuple->lhs == 1) && (val->lhs == 0)) {
9029                         pval = val;
9030                 }
9031                 else {
9032                         if (i > val->lhs) {
9033                                 internal_error(state, ins, "lhs size inconsistency?");
9034                         }
9035                         pval = LHS(val, i);
9036                 }
9037                 
9038                 /* See if the piece is really a bitref */
9039                 bitref = 0;
9040                 if (piece->op == OP_BITREF) {
9041                         struct triple *read, *deposit;
9042                         bitref = piece;
9043                         piece = RHS(bitref, 0);
9044
9045                         /* Read the destination register */
9046                         get_occurance(tuple->occurance);
9047                         read = alloc_triple(state, OP_READ, piece->type, -1, -1,
9048                                 tuple->occurance);
9049                         RHS(read, 0) = piece;
9050
9051                         /* Deposit the new bitfield value */
9052                         get_occurance(tuple->occurance);
9053                         deposit = alloc_triple(state, OP_DEPOSIT, piece->type, -1, -1,
9054                                 tuple->occurance);
9055                         RHS(deposit, 0) = read;
9056                         RHS(deposit, 1) = pval;
9057                         deposit->u.bitfield.size   = bitref->u.bitfield.size;
9058                         deposit->u.bitfield.offset = bitref->u.bitfield.offset;
9059
9060                         /* Now write the newly generated value */
9061                         pval = deposit;
9062                 }
9063
9064                 get_occurance(tuple->occurance);
9065                 write = alloc_triple(state, OP_WRITE, piece->type, -1, -1, 
9066                         tuple->occurance);
9067                 MISC(write, 0) = piece;
9068                 RHS(write, 0) = pval;
9069                 LHS(tuple, i) = write;
9070         }
9071         return decompose_with_tuple(state, ins, tuple);
9072 }
9073
9074 struct decompose_load_info {
9075         struct occurance *occurance;
9076         struct triple *lval;
9077         struct triple *tuple;
9078 };
9079 static void decompose_load_cb(struct compile_state *state,
9080         struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9081 {
9082         struct decompose_load_info *info = arg;
9083         struct triple *load;
9084         
9085         if (reg_offset > info->tuple->lhs) {
9086                 internal_error(state, info->tuple, "lhs to small?");
9087         }
9088         get_occurance(info->occurance);
9089         load = alloc_triple(state, OP_LOAD, type, -1, -1, info->occurance);
9090         RHS(load, 0) = mk_addr_expr(state, info->lval, mem_offset);
9091         LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = load;
9092 }
9093
9094 static struct triple *decompose_load(struct compile_state *state, 
9095         struct triple *ins)
9096 {
9097         struct triple *tuple;
9098         struct decompose_load_info info;
9099
9100         if (!is_compound_type(ins->type)) {
9101                 return ins->next;
9102         }
9103         get_occurance(ins->occurance);
9104         tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9105                 ins->occurance);
9106
9107         info.occurance = ins->occurance;
9108         info.lval      = RHS(ins, 0);
9109         info.tuple     = tuple;
9110         walk_type_fields(state, ins->type, 0, 0, decompose_load_cb, &info);
9111
9112         return decompose_with_tuple(state, ins, tuple);
9113 }
9114
9115
9116 struct decompose_store_info {
9117         struct occurance *occurance;
9118         struct triple *lval;
9119         struct triple *val;
9120         struct triple *tuple;
9121 };
9122 static void decompose_store_cb(struct compile_state *state,
9123         struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9124 {
9125         struct decompose_store_info *info = arg;
9126         struct triple *store;
9127         
9128         if (reg_offset > info->tuple->lhs) {
9129                 internal_error(state, info->tuple, "lhs to small?");
9130         }
9131         get_occurance(info->occurance);
9132         store = alloc_triple(state, OP_STORE, type, -1, -1, info->occurance);
9133         RHS(store, 0) = mk_addr_expr(state, info->lval, mem_offset);
9134         RHS(store, 1) = LHS(info->val, reg_offset);
9135         LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = store;
9136 }
9137
9138 static struct triple *decompose_store(struct compile_state *state, 
9139         struct triple *ins)
9140 {
9141         struct triple *tuple;
9142         struct decompose_store_info info;
9143
9144         if (!is_compound_type(ins->type)) {
9145                 return ins->next;
9146         }
9147         get_occurance(ins->occurance);
9148         tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9149                 ins->occurance);
9150
9151         info.occurance = ins->occurance;
9152         info.lval      = RHS(ins, 0);
9153         info.val       = RHS(ins, 1);
9154         info.tuple     = tuple;
9155         walk_type_fields(state, ins->type, 0, 0, decompose_store_cb, &info);
9156
9157         return decompose_with_tuple(state, ins, tuple);
9158 }
9159
9160 static struct triple *decompose_dot(struct compile_state *state, 
9161         struct triple *ins)
9162 {
9163         struct triple *tuple, *lval;
9164         struct type *type;
9165         size_t reg_offset;
9166         int i, idx;
9167
9168         lval = MISC(ins, 0);
9169         reg_offset = field_reg_offset(state, lval->type, ins->u.field);
9170         idx  = reg_offset/REG_SIZEOF_REG;
9171         type = field_type(state, lval->type, ins->u.field);
9172 #if DEBUG_DECOMPOSE_HIRES
9173         {
9174                 FILE *fp = state->dbgout;
9175                 fprintf(fp, "field type: ");
9176                 name_of(fp, type);
9177                 fprintf(fp, "\n");
9178         }
9179 #endif
9180
9181         get_occurance(ins->occurance);
9182         tuple = alloc_triple(state, OP_TUPLE, type, -1, -1, 
9183                 ins->occurance);
9184
9185         if (((ins->type->type & TYPE_MASK) == TYPE_BITFIELD) &&
9186                 (tuple->lhs != 1))
9187         {
9188                 internal_error(state, ins, "multi register bitfield?");
9189         }
9190
9191         for(i = 0; i < tuple->lhs; i++, idx++) {
9192                 struct triple *piece;
9193                 if (!triple_is_def(state, lval)) {
9194                         if (idx > lval->lhs) {
9195                                 internal_error(state, ins, "inconsistent lhs count");
9196                         }
9197                         piece = LHS(lval, idx);
9198                 } else {
9199                         if (idx != 0) {
9200                                 internal_error(state, ins, "bad reg_offset into def");
9201                         }
9202                         if (i != 0) {
9203                                 internal_error(state, ins, "bad reg count from def");
9204                         }
9205                         piece = lval;
9206                 }
9207
9208                 /* Remember the offset of the bitfield */
9209                 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
9210                         get_occurance(ins->occurance);
9211                         piece = build_triple(state, OP_BITREF, type, piece, 0,
9212                                 ins->occurance);
9213                         piece->u.bitfield.size   = size_of(state, type);
9214                         piece->u.bitfield.offset = reg_offset % REG_SIZEOF_REG;
9215                 }
9216                 else if ((reg_offset % REG_SIZEOF_REG) != 0) {
9217                         internal_error(state, ins, 
9218                                 "request for a nonbitfield sub register?");
9219                 }
9220
9221                 LHS(tuple, i) = piece;
9222         }
9223
9224         return decompose_with_tuple(state, ins, tuple);
9225 }
9226
9227 static struct triple *decompose_index(struct compile_state *state, 
9228         struct triple *ins)
9229 {
9230         struct triple *tuple, *lval;
9231         struct type *type;
9232         int i, idx;
9233
9234         lval = MISC(ins, 0);
9235         idx = index_reg_offset(state, lval->type, ins->u.cval)/REG_SIZEOF_REG;
9236         type = index_type(state, lval->type, ins->u.cval);
9237 #if DEBUG_DECOMPOSE_HIRES
9238 {
9239         FILE *fp = state->dbgout;
9240         fprintf(fp, "index type: ");
9241         name_of(fp, type);
9242         fprintf(fp, "\n");
9243 }
9244 #endif
9245
9246         get_occurance(ins->occurance);
9247         tuple = alloc_triple(state, OP_TUPLE, type, -1, -1, 
9248                 ins->occurance);
9249
9250         for(i = 0; i < tuple->lhs; i++, idx++) {
9251                 struct triple *piece;
9252                 if (!triple_is_def(state, lval)) {
9253                         if (idx > lval->lhs) {
9254                                 internal_error(state, ins, "inconsistent lhs count");
9255                         }
9256                         piece = LHS(lval, idx);
9257                 } else {
9258                         if (idx != 0) {
9259                                 internal_error(state, ins, "bad reg_offset into def");
9260                         }
9261                         if (i != 0) {
9262                                 internal_error(state, ins, "bad reg count from def");
9263                         }
9264                         piece = lval;
9265                 }
9266                 LHS(tuple, i) = piece;
9267         }
9268
9269         return decompose_with_tuple(state, ins, tuple);
9270 }
9271
9272 static void decompose_compound_types(struct compile_state *state)
9273 {
9274         struct triple *ins, *next, *first;
9275         FILE *fp;
9276         fp = state->dbgout;
9277         first = state->first;
9278         ins = first;
9279
9280         /* Pass one expand compound values into pseudo registers.
9281          */
9282         next = first;
9283         do {
9284                 ins = next;
9285                 next = ins->next;
9286                 switch(ins->op) {
9287                 case OP_UNKNOWNVAL:
9288                         next = decompose_unknownval(state, ins);
9289                         break;
9290
9291                 case OP_READ:
9292                         next = decompose_read(state, ins);
9293                         break;
9294
9295                 case OP_WRITE:
9296                         next = decompose_write(state, ins);
9297                         break;
9298
9299
9300                 /* Be very careful with the load/store logic. These
9301                  * operations must convert from the in register layout
9302                  * to the in memory layout, which is nontrivial.
9303                  */
9304                 case OP_LOAD:
9305                         next = decompose_load(state, ins);
9306                         break;
9307                 case OP_STORE:
9308                         next = decompose_store(state, ins);
9309                         break;
9310
9311                 case OP_DOT:
9312                         next = decompose_dot(state, ins);
9313                         break;
9314                 case OP_INDEX:
9315                         next = decompose_index(state, ins);
9316                         break;
9317                         
9318                 }
9319 #if DEBUG_DECOMPOSE_HIRES
9320                 fprintf(fp, "decompose next: %p \n", next);
9321                 fflush(fp);
9322                 fprintf(fp, "next->op: %d %s\n",
9323                         next->op, tops(next->op));
9324                 /* High resolution debugging mode */
9325                 print_triples(state);
9326 #endif
9327         } while (next != first);
9328
9329         /* Pass two remove the tuples.
9330          */
9331         ins = first;
9332         do {
9333                 next = ins->next;
9334                 if (ins->op == OP_TUPLE) {
9335                         if (ins->use) {
9336                                 internal_error(state, ins, "tuple used");
9337                         }
9338                         else {
9339                                 release_triple(state, ins);
9340                         }
9341                 } 
9342                 ins = next;
9343         } while(ins != first);
9344         ins = first;
9345         do {
9346                 next = ins->next;
9347                 if (ins->op == OP_BITREF) {
9348                         if (ins->use) {
9349                                 internal_error(state, ins, "bitref used");
9350                         } 
9351                         else {
9352                                 release_triple(state, ins);
9353                         }
9354                 }
9355                 ins = next;
9356         } while(ins != first);
9357
9358         /* Pass three verify the state and set ->id to 0.
9359          */
9360         next = first;
9361         do {
9362                 ins = next;
9363                 next = ins->next;
9364                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9365                 if (triple_stores_block(state, ins)) {
9366                         ins->u.block = 0;
9367                 }
9368                 if (triple_is_def(state, ins)) {
9369                         if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9370                                 internal_error(state, ins, "multi register value remains?");
9371                         }
9372                 }
9373                 if (ins->op == OP_DOT) {
9374                         internal_error(state, ins, "OP_DOT remains?");
9375                 }
9376                 if (ins->op == OP_INDEX) {
9377                         internal_error(state, ins, "OP_INDEX remains?");
9378                 }
9379                 if (ins->op == OP_BITREF) {
9380                         internal_error(state, ins, "OP_BITREF remains?");
9381                 }
9382                 if (ins->op == OP_TUPLE) {
9383                         internal_error(state, ins, "OP_TUPLE remains?");
9384                 }
9385         } while(next != first);
9386 }
9387
9388 /* For those operations that cannot be simplified */
9389 static void simplify_noop(struct compile_state *state, struct triple *ins)
9390 {
9391         return;
9392 }
9393
9394 static void simplify_smul(struct compile_state *state, struct triple *ins)
9395 {
9396         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9397                 struct triple *tmp;
9398                 tmp = RHS(ins, 0);
9399                 RHS(ins, 0) = RHS(ins, 1);
9400                 RHS(ins, 1) = tmp;
9401         }
9402         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9403                 long_t left, right;
9404                 left  = read_sconst(state, ins, RHS(ins, 0));
9405                 right = read_sconst(state, ins, RHS(ins, 1));
9406                 mkconst(state, ins, left * right);
9407         }
9408         else if (is_zero(RHS(ins, 1))) {
9409                 mkconst(state, ins, 0);
9410         }
9411         else if (is_one(RHS(ins, 1))) {
9412                 mkcopy(state, ins, RHS(ins, 0));
9413         }
9414         else if (is_pow2(RHS(ins, 1))) {
9415                 struct triple *val;
9416                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9417                 ins->op = OP_SL;
9418                 insert_triple(state, state->global_pool, val);
9419                 unuse_triple(RHS(ins, 1), ins);
9420                 use_triple(val, ins);
9421                 RHS(ins, 1) = val;
9422         }
9423 }
9424
9425 static void simplify_umul(struct compile_state *state, struct triple *ins)
9426 {
9427         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9428                 struct triple *tmp;
9429                 tmp = RHS(ins, 0);
9430                 RHS(ins, 0) = RHS(ins, 1);
9431                 RHS(ins, 1) = tmp;
9432         }
9433         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9434                 ulong_t left, right;
9435                 left  = read_const(state, ins, RHS(ins, 0));
9436                 right = read_const(state, ins, RHS(ins, 1));
9437                 mkconst(state, ins, left * right);
9438         }
9439         else if (is_zero(RHS(ins, 1))) {
9440                 mkconst(state, ins, 0);
9441         }
9442         else if (is_one(RHS(ins, 1))) {
9443                 mkcopy(state, ins, RHS(ins, 0));
9444         }
9445         else if (is_pow2(RHS(ins, 1))) {
9446                 struct triple *val;
9447                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9448                 ins->op = OP_SL;
9449                 insert_triple(state, state->global_pool, val);
9450                 unuse_triple(RHS(ins, 1), ins);
9451                 use_triple(val, ins);
9452                 RHS(ins, 1) = val;
9453         }
9454 }
9455
9456 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9457 {
9458         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9459                 long_t left, right;
9460                 left  = read_sconst(state, ins, RHS(ins, 0));
9461                 right = read_sconst(state, ins, RHS(ins, 1));
9462                 mkconst(state, ins, left / right);
9463         }
9464         else if (is_zero(RHS(ins, 0))) {
9465                 mkconst(state, ins, 0);
9466         }
9467         else if (is_zero(RHS(ins, 1))) {
9468                 error(state, ins, "division by zero");
9469         }
9470         else if (is_one(RHS(ins, 1))) {
9471                 mkcopy(state, ins, RHS(ins, 0));
9472         }
9473         else if (is_pow2(RHS(ins, 1))) {
9474                 struct triple *val;
9475                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9476                 ins->op = OP_SSR;
9477                 insert_triple(state, state->global_pool, val);
9478                 unuse_triple(RHS(ins, 1), ins);
9479                 use_triple(val, ins);
9480                 RHS(ins, 1) = val;
9481         }
9482 }
9483
9484 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9485 {
9486         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9487                 ulong_t left, right;
9488                 left  = read_const(state, ins, RHS(ins, 0));
9489                 right = read_const(state, ins, RHS(ins, 1));
9490                 mkconst(state, ins, left / right);
9491         }
9492         else if (is_zero(RHS(ins, 0))) {
9493                 mkconst(state, ins, 0);
9494         }
9495         else if (is_zero(RHS(ins, 1))) {
9496                 error(state, ins, "division by zero");
9497         }
9498         else if (is_one(RHS(ins, 1))) {
9499                 mkcopy(state, ins, RHS(ins, 0));
9500         }
9501         else if (is_pow2(RHS(ins, 1))) {
9502                 struct triple *val;
9503                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9504                 ins->op = OP_USR;
9505                 insert_triple(state, state->global_pool, val);
9506                 unuse_triple(RHS(ins, 1), ins);
9507                 use_triple(val, ins);
9508                 RHS(ins, 1) = val;
9509         }
9510 }
9511
9512 static void simplify_smod(struct compile_state *state, struct triple *ins)
9513 {
9514         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9515                 long_t left, right;
9516                 left  = read_const(state, ins, RHS(ins, 0));
9517                 right = read_const(state, ins, RHS(ins, 1));
9518                 mkconst(state, ins, left % right);
9519         }
9520         else if (is_zero(RHS(ins, 0))) {
9521                 mkconst(state, ins, 0);
9522         }
9523         else if (is_zero(RHS(ins, 1))) {
9524                 error(state, ins, "division by zero");
9525         }
9526         else if (is_one(RHS(ins, 1))) {
9527                 mkconst(state, ins, 0);
9528         }
9529         else if (is_pow2(RHS(ins, 1))) {
9530                 struct triple *val;
9531                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9532                 ins->op = OP_AND;
9533                 insert_triple(state, state->global_pool, val);
9534                 unuse_triple(RHS(ins, 1), ins);
9535                 use_triple(val, ins);
9536                 RHS(ins, 1) = val;
9537         }
9538 }
9539
9540 static void simplify_umod(struct compile_state *state, struct triple *ins)
9541 {
9542         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9543                 ulong_t left, right;
9544                 left  = read_const(state, ins, RHS(ins, 0));
9545                 right = read_const(state, ins, RHS(ins, 1));
9546                 mkconst(state, ins, left % right);
9547         }
9548         else if (is_zero(RHS(ins, 0))) {
9549                 mkconst(state, ins, 0);
9550         }
9551         else if (is_zero(RHS(ins, 1))) {
9552                 error(state, ins, "division by zero");
9553         }
9554         else if (is_one(RHS(ins, 1))) {
9555                 mkconst(state, ins, 0);
9556         }
9557         else if (is_pow2(RHS(ins, 1))) {
9558                 struct triple *val;
9559                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9560                 ins->op = OP_AND;
9561                 insert_triple(state, state->global_pool, val);
9562                 unuse_triple(RHS(ins, 1), ins);
9563                 use_triple(val, ins);
9564                 RHS(ins, 1) = val;
9565         }
9566 }
9567
9568 static void simplify_add(struct compile_state *state, struct triple *ins)
9569 {
9570         /* start with the pointer on the left */
9571         if (is_pointer(RHS(ins, 1))) {
9572                 struct triple *tmp;
9573                 tmp = RHS(ins, 0);
9574                 RHS(ins, 0) = RHS(ins, 1);
9575                 RHS(ins, 1) = tmp;
9576         }
9577         if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9578                 if (RHS(ins, 0)->op == OP_INTCONST) {
9579                         ulong_t left, right;
9580                         left  = read_const(state, ins, RHS(ins, 0));
9581                         right = read_const(state, ins, RHS(ins, 1));
9582                         mkconst(state, ins, left + right);
9583                 }
9584                 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9585                         struct triple *sdecl;
9586                         ulong_t left, right;
9587                         sdecl = MISC(RHS(ins, 0), 0);
9588                         left  = RHS(ins, 0)->u.cval;
9589                         right = RHS(ins, 1)->u.cval;
9590                         mkaddr_const(state, ins, sdecl, left + right);
9591                 }
9592                 else {
9593                         internal_warning(state, ins, "Optimize me!");
9594                 }
9595         }
9596         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9597                 struct triple *tmp;
9598                 tmp = RHS(ins, 1);
9599                 RHS(ins, 1) = RHS(ins, 0);
9600                 RHS(ins, 0) = tmp;
9601         }
9602 }
9603
9604 static void simplify_sub(struct compile_state *state, struct triple *ins)
9605 {
9606         if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9607                 if (RHS(ins, 0)->op == OP_INTCONST) {
9608                         ulong_t left, right;
9609                         left  = read_const(state, ins, RHS(ins, 0));
9610                         right = read_const(state, ins, RHS(ins, 1));
9611                         mkconst(state, ins, left - right);
9612                 }
9613                 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9614                         struct triple *sdecl;
9615                         ulong_t left, right;
9616                         sdecl = MISC(RHS(ins, 0), 0);
9617                         left  = RHS(ins, 0)->u.cval;
9618                         right = RHS(ins, 1)->u.cval;
9619                         mkaddr_const(state, ins, sdecl, left - right);
9620                 }
9621                 else {
9622                         internal_warning(state, ins, "Optimize me!");
9623                 }
9624         }
9625 }
9626
9627 static void simplify_sl(struct compile_state *state, struct triple *ins)
9628 {
9629         if (is_simple_const(RHS(ins, 1))) {
9630                 ulong_t right;
9631                 right = read_const(state, ins, RHS(ins, 1));
9632                 if (right >= (size_of(state, ins->type))) {
9633                         warning(state, ins, "left shift count >= width of type");
9634                 }
9635         }
9636         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9637                 ulong_t left, right;
9638                 left  = read_const(state, ins, RHS(ins, 0));
9639                 right = read_const(state, ins, RHS(ins, 1));
9640                 mkconst(state, ins,  left << right);
9641         }
9642 }
9643
9644 static void simplify_usr(struct compile_state *state, struct triple *ins)
9645 {
9646         if (is_simple_const(RHS(ins, 1))) {
9647                 ulong_t right;
9648                 right = read_const(state, ins, RHS(ins, 1));
9649                 if (right >= (size_of(state, ins->type))) {
9650                         warning(state, ins, "right shift count >= width of type");
9651                 }
9652         }
9653         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9654                 ulong_t left, right;
9655                 left  = read_const(state, ins, RHS(ins, 0));
9656                 right = read_const(state, ins, RHS(ins, 1));
9657                 mkconst(state, ins, left >> right);
9658         }
9659 }
9660
9661 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9662 {
9663         if (is_simple_const(RHS(ins, 1))) {
9664                 ulong_t right;
9665                 right = read_const(state, ins, RHS(ins, 1));
9666                 if (right >= (size_of(state, ins->type))) {
9667                         warning(state, ins, "right shift count >= width of type");
9668                 }
9669         }
9670         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9671                 long_t left, right;
9672                 left  = read_sconst(state, ins, RHS(ins, 0));
9673                 right = read_sconst(state, ins, RHS(ins, 1));
9674                 mkconst(state, ins, left >> right);
9675         }
9676 }
9677
9678 static void simplify_and(struct compile_state *state, struct triple *ins)
9679 {
9680         struct triple *left, *right;
9681         left = RHS(ins, 0);
9682         right = RHS(ins, 1);
9683
9684         if (is_simple_const(left) && is_simple_const(right)) {
9685                 ulong_t lval, rval;
9686                 lval = read_const(state, ins, left);
9687                 rval = read_const(state, ins, right);
9688                 mkconst(state, ins, lval & rval);
9689         }
9690         else if (is_zero(right) || is_zero(left)) {
9691                 mkconst(state, ins, 0);
9692         }
9693 }
9694
9695 static void simplify_or(struct compile_state *state, struct triple *ins)
9696 {
9697         struct triple *left, *right;
9698         left = RHS(ins, 0);
9699         right = RHS(ins, 1);
9700
9701         if (is_simple_const(left) && is_simple_const(right)) {
9702                 ulong_t lval, rval;
9703                 lval = read_const(state, ins, left);
9704                 rval = read_const(state, ins, right);
9705                 mkconst(state, ins, lval | rval);
9706         }
9707 #if 0 /* I need to handle type mismatches here... */
9708         else if (is_zero(right)) {
9709                 mkcopy(state, ins, left);
9710         }
9711         else if (is_zero(left)) {
9712                 mkcopy(state, ins, right);
9713         }
9714 #endif
9715 }
9716
9717 static void simplify_xor(struct compile_state *state, struct triple *ins)
9718 {
9719         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9720                 ulong_t left, right;
9721                 left  = read_const(state, ins, RHS(ins, 0));
9722                 right = read_const(state, ins, RHS(ins, 1));
9723                 mkconst(state, ins, left ^ right);
9724         }
9725 }
9726
9727 static void simplify_pos(struct compile_state *state, struct triple *ins)
9728 {
9729         if (is_const(RHS(ins, 0))) {
9730                 mkconst(state, ins, RHS(ins, 0)->u.cval);
9731         }
9732         else {
9733                 mkcopy(state, ins, RHS(ins, 0));
9734         }
9735 }
9736
9737 static void simplify_neg(struct compile_state *state, struct triple *ins)
9738 {
9739         if (is_simple_const(RHS(ins, 0))) {
9740                 ulong_t left;
9741                 left = read_const(state, ins, RHS(ins, 0));
9742                 mkconst(state, ins, -left);
9743         }
9744         else if (RHS(ins, 0)->op == OP_NEG) {
9745                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9746         }
9747 }
9748
9749 static void simplify_invert(struct compile_state *state, struct triple *ins)
9750 {
9751         if (is_simple_const(RHS(ins, 0))) {
9752                 ulong_t left;
9753                 left = read_const(state, ins, RHS(ins, 0));
9754                 mkconst(state, ins, ~left);
9755         }
9756 }
9757
9758 static void simplify_eq(struct compile_state *state, struct triple *ins)
9759 {
9760         struct triple *left, *right;
9761         left = RHS(ins, 0);
9762         right = RHS(ins, 1);
9763
9764         if (is_const(left) && is_const(right)) {
9765                 int val;
9766                 val = const_eq(state, ins, left, right);
9767                 if (val >= 0) {
9768                         mkconst(state, ins, val == 1);
9769                 }
9770         }
9771         else if (left == right) {
9772                 mkconst(state, ins, 1);
9773         }
9774 }
9775
9776 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9777 {
9778         struct triple *left, *right;
9779         left = RHS(ins, 0);
9780         right = RHS(ins, 1);
9781
9782         if (is_const(left) && is_const(right)) {
9783                 int val;
9784                 val = const_eq(state, ins, left, right);
9785                 if (val >= 0) {
9786                         mkconst(state, ins, val != 1);
9787                 }
9788         }
9789         if (left == right) {
9790                 mkconst(state, ins, 0);
9791         }
9792 }
9793
9794 static void simplify_sless(struct compile_state *state, struct triple *ins)
9795 {
9796         struct triple *left, *right;
9797         left = RHS(ins, 0);
9798         right = RHS(ins, 1);
9799
9800         if (is_const(left) && is_const(right)) {
9801                 int val;
9802                 val = const_scmp(state, ins, left, right);
9803                 if ((val >= -1) && (val <= 1)) {
9804                         mkconst(state, ins, val < 0);
9805                 }
9806         }
9807         else if (left == right) {
9808                 mkconst(state, ins, 0);
9809         }
9810 }
9811
9812 static void simplify_uless(struct compile_state *state, struct triple *ins)
9813 {
9814         struct triple *left, *right;
9815         left = RHS(ins, 0);
9816         right = RHS(ins, 1);
9817
9818         if (is_const(left) && is_const(right)) {
9819                 int val;
9820                 val = const_ucmp(state, ins, left, right);
9821                 if ((val >= -1) && (val <= 1)) {
9822                         mkconst(state, ins, val < 0);
9823                 }
9824         }
9825         else if (is_zero(right)) {
9826                 mkconst(state, ins, 0);
9827         }
9828         else if (left == right) {
9829                 mkconst(state, ins, 0);
9830         }
9831 }
9832
9833 static void simplify_smore(struct compile_state *state, struct triple *ins)
9834 {
9835         struct triple *left, *right;
9836         left = RHS(ins, 0);
9837         right = RHS(ins, 1);
9838
9839         if (is_const(left) && is_const(right)) {
9840                 int val;
9841                 val = const_scmp(state, ins, left, right);
9842                 if ((val >= -1) && (val <= 1)) {
9843                         mkconst(state, ins, val > 0);
9844                 }
9845         }
9846         else if (left == right) {
9847                 mkconst(state, ins, 0);
9848         }
9849 }
9850
9851 static void simplify_umore(struct compile_state *state, struct triple *ins)
9852 {
9853         struct triple *left, *right;
9854         left = RHS(ins, 0);
9855         right = RHS(ins, 1);
9856
9857         if (is_const(left) && is_const(right)) {
9858                 int val;
9859                 val = const_ucmp(state, ins, left, right);
9860                 if ((val >= -1) && (val <= 1)) {
9861                         mkconst(state, ins, val > 0);
9862                 }
9863         }
9864         else if (is_zero(left)) {
9865                 mkconst(state, ins, 0);
9866         }
9867         else if (left == right) {
9868                 mkconst(state, ins, 0);
9869         }
9870 }
9871
9872
9873 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9874 {
9875         struct triple *left, *right;
9876         left = RHS(ins, 0);
9877         right = RHS(ins, 1);
9878
9879         if (is_const(left) && is_const(right)) {
9880                 int val;
9881                 val = const_scmp(state, ins, left, right);
9882                 if ((val >= -1) && (val <= 1)) {
9883                         mkconst(state, ins, val <= 0);
9884                 }
9885         }
9886         else if (left == right) {
9887                 mkconst(state, ins, 1);
9888         }
9889 }
9890
9891 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9892 {
9893         struct triple *left, *right;
9894         left = RHS(ins, 0);
9895         right = RHS(ins, 1);
9896
9897         if (is_const(left) && is_const(right)) {
9898                 int val;
9899                 val = const_ucmp(state, ins, left, right);
9900                 if ((val >= -1) && (val <= 1)) {
9901                         mkconst(state, ins, val <= 0);
9902                 }
9903         }
9904         else if (is_zero(left)) {
9905                 mkconst(state, ins, 1);
9906         }
9907         else if (left == right) {
9908                 mkconst(state, ins, 1);
9909         }
9910 }
9911
9912 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9913 {
9914         struct triple *left, *right;
9915         left = RHS(ins, 0);
9916         right = RHS(ins, 1);
9917
9918         if (is_const(left) && is_const(right)) {
9919                 int val;
9920                 val = const_scmp(state, ins, left, right);
9921                 if ((val >= -1) && (val <= 1)) {
9922                         mkconst(state, ins, val >= 0);
9923                 }
9924         }
9925         else if (left == right) {
9926                 mkconst(state, ins, 1);
9927         }
9928 }
9929
9930 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9931 {
9932         struct triple *left, *right;
9933         left = RHS(ins, 0);
9934         right = RHS(ins, 1);
9935
9936         if (is_const(left) && is_const(right)) {
9937                 int val;
9938                 val = const_ucmp(state, ins, left, right);
9939                 if ((val >= -1) && (val <= 1)) {
9940                         mkconst(state, ins, val >= 0);
9941                 }
9942         }
9943         else if (is_zero(right)) {
9944                 mkconst(state, ins, 1);
9945         }
9946         else if (left == right) {
9947                 mkconst(state, ins, 1);
9948         }
9949 }
9950
9951 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9952 {
9953         struct triple *rhs;
9954         rhs = RHS(ins, 0);
9955
9956         if (is_const(rhs)) {
9957                 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9958         }
9959         /* Otherwise if I am the only user... */
9960         else if ((rhs->use) &&
9961                 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9962                 int need_copy = 1;
9963                 /* Invert a boolean operation */
9964                 switch(rhs->op) {
9965                 case OP_LTRUE:   rhs->op = OP_LFALSE;  break;
9966                 case OP_LFALSE:  rhs->op = OP_LTRUE;   break;
9967                 case OP_EQ:      rhs->op = OP_NOTEQ;   break;
9968                 case OP_NOTEQ:   rhs->op = OP_EQ;      break;
9969                 case OP_SLESS:   rhs->op = OP_SMOREEQ; break;
9970                 case OP_ULESS:   rhs->op = OP_UMOREEQ; break;
9971                 case OP_SMORE:   rhs->op = OP_SLESSEQ; break;
9972                 case OP_UMORE:   rhs->op = OP_ULESSEQ; break;
9973                 case OP_SLESSEQ: rhs->op = OP_SMORE;   break;
9974                 case OP_ULESSEQ: rhs->op = OP_UMORE;   break;
9975                 case OP_SMOREEQ: rhs->op = OP_SLESS;   break;
9976                 case OP_UMOREEQ: rhs->op = OP_ULESS;   break;
9977                 default:
9978                         need_copy = 0;
9979                         break;
9980                 }
9981                 if (need_copy) {
9982                         mkcopy(state, ins, rhs);
9983                 }
9984         }
9985 }
9986
9987 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9988 {
9989         struct triple *rhs;
9990         rhs = RHS(ins, 0);
9991
9992         if (is_const(rhs)) {
9993                 mkconst(state, ins, const_ltrue(state, ins, rhs));
9994         }
9995         else switch(rhs->op) {
9996         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
9997         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
9998         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9999                 mkcopy(state, ins, rhs);
10000         }
10001
10002 }
10003
10004 static void simplify_load(struct compile_state *state, struct triple *ins)
10005 {
10006         struct triple *addr, *sdecl, *blob;
10007
10008         /* If I am doing a load with a constant pointer from a constant
10009          * table get the value.
10010          */
10011         addr = RHS(ins, 0);
10012         if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
10013                 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
10014                 (blob->op == OP_BLOBCONST)) {
10015                 unsigned char buffer[SIZEOF_WORD];
10016                 size_t reg_size, mem_size;
10017                 const char *src, *end;
10018                 ulong_t val;
10019                 reg_size = reg_size_of(state, ins->type);
10020                 if (reg_size > REG_SIZEOF_REG) {
10021                         internal_error(state, ins, "load size greater than register");
10022                 }
10023                 mem_size = size_of(state, ins->type);
10024                 end = blob->u.blob;
10025                 end += bits_to_bytes(size_of(state, sdecl->type));
10026                 src = blob->u.blob;
10027                 src += addr->u.cval;
10028
10029                 if (src > end) {
10030                         error(state, ins, "Load address out of bounds");
10031                 }
10032
10033                 memset(buffer, 0, sizeof(buffer));
10034                 memcpy(buffer, src, bits_to_bytes(mem_size));
10035
10036                 switch(mem_size) {
10037                 case SIZEOF_I8:  val = *((uint8_t *) buffer); break;
10038                 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
10039                 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
10040                 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
10041                 default:
10042                         internal_error(state, ins, "mem_size: %d not handled",
10043                                 mem_size);
10044                         val = 0;
10045                         break;
10046                 }
10047                 mkconst(state, ins, val);
10048         }
10049 }
10050
10051 static void simplify_uextract(struct compile_state *state, struct triple *ins)
10052 {
10053         if (is_simple_const(RHS(ins, 0))) {
10054                 ulong_t val;
10055                 ulong_t mask;
10056                 val = read_const(state, ins, RHS(ins, 0));
10057                 mask = 1;
10058                 mask <<= ins->u.bitfield.size;
10059                 mask -= 1;
10060                 val >>= ins->u.bitfield.offset;
10061                 val &= mask;
10062                 mkconst(state, ins, val);
10063         }
10064 }
10065
10066 static void simplify_sextract(struct compile_state *state, struct triple *ins)
10067 {
10068         if (is_simple_const(RHS(ins, 0))) {
10069                 ulong_t val;
10070                 ulong_t mask;
10071                 long_t sval;
10072                 val = read_const(state, ins, RHS(ins, 0));
10073                 mask = 1;
10074                 mask <<= ins->u.bitfield.size;
10075                 mask -= 1;
10076                 val >>= ins->u.bitfield.offset;
10077                 val &= mask;
10078                 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
10079                 sval = val;
10080                 sval >>= (SIZEOF_LONG - ins->u.bitfield.size); 
10081                 mkconst(state, ins, sval);
10082         }
10083 }
10084
10085 static void simplify_deposit(struct compile_state *state, struct triple *ins)
10086 {
10087         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
10088                 ulong_t targ, val;
10089                 ulong_t mask;
10090                 targ = read_const(state, ins, RHS(ins, 0));
10091                 val  = read_const(state, ins, RHS(ins, 1));
10092                 mask = 1;
10093                 mask <<= ins->u.bitfield.size;
10094                 mask -= 1;
10095                 mask <<= ins->u.bitfield.offset;
10096                 targ &= ~mask;
10097                 val <<= ins->u.bitfield.offset;
10098                 val &= mask;
10099                 targ |= val;
10100                 mkconst(state, ins, targ);
10101         }
10102 }
10103
10104 static void simplify_copy(struct compile_state *state, struct triple *ins)
10105 {
10106         struct triple *right;
10107         right = RHS(ins, 0);
10108         if (is_subset_type(ins->type, right->type)) {
10109                 ins->type = right->type;
10110         }
10111         if (equiv_types(ins->type, right->type)) {
10112                 ins->op = OP_COPY;/* I don't need to convert if the types match */
10113         } else {
10114                 if (ins->op == OP_COPY) {
10115                         internal_error(state, ins, "type mismatch on copy");
10116                 }
10117         }
10118         if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
10119                 struct triple *sdecl;
10120                 ulong_t offset;
10121                 sdecl  = MISC(right, 0);
10122                 offset = right->u.cval;
10123                 mkaddr_const(state, ins, sdecl, offset);
10124         }
10125         else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
10126                 switch(right->op) {
10127                 case OP_INTCONST:
10128                 {
10129                         ulong_t left;
10130                         left = read_const(state, ins, right);
10131                         /* Ensure I have not overflowed the destination. */
10132                         if (size_of(state, right->type) > size_of(state, ins->type)) {
10133                                 ulong_t mask;
10134                                 mask = 1;
10135                                 mask <<= size_of(state, ins->type);
10136                                 mask -= 1;
10137                                 left &= mask;
10138                         }
10139                         /* Ensure I am properly sign extended */
10140                         if (size_of(state, right->type) < size_of(state, ins->type) &&
10141                                 is_signed(right->type)) {
10142                                 long_t val;
10143                                 int shift;
10144                                 shift = SIZEOF_LONG - size_of(state, right->type);
10145                                 val = left;
10146                                 val <<= shift;
10147                                 val >>= shift;
10148                                 left = val;
10149                         }
10150                         mkconst(state, ins, left);
10151                         break;
10152                 }
10153                 default:
10154                         internal_error(state, ins, "uknown constant");
10155                         break;
10156                 }
10157         }
10158 }
10159
10160 static int phi_present(struct block *block)
10161 {
10162         struct triple *ptr;
10163         if (!block) {
10164                 return 0;
10165         }
10166         ptr = block->first;
10167         do {
10168                 if (ptr->op == OP_PHI) {
10169                         return 1;
10170                 }
10171                 ptr = ptr->next;
10172         } while(ptr != block->last);
10173         return 0;
10174 }
10175
10176 static int phi_dependency(struct block *block)
10177 {
10178         /* A block has a phi dependency if a phi function
10179          * depends on that block to exist, and makes a block
10180          * that is otherwise useless unsafe to remove.
10181          */
10182         if (block) {
10183                 struct block_set *edge;
10184                 for(edge = block->edges; edge; edge = edge->next) {
10185                         if (phi_present(edge->member)) {
10186                                 return 1;
10187                         }
10188                 }
10189         }
10190         return 0;
10191 }
10192
10193 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10194 {
10195         struct triple *targ;
10196         targ = TARG(ins, 0);
10197         /* During scc_transform temporary triples are allocated that
10198          * loop back onto themselves. If I see one don't advance the
10199          * target.
10200          */
10201         while(triple_is_structural(state, targ) && 
10202                 (targ->next != targ) && (targ->next != state->first)) {
10203                 targ = targ->next;
10204         }
10205         return targ;
10206 }
10207
10208
10209 static void simplify_branch(struct compile_state *state, struct triple *ins)
10210 {
10211         int simplified, loops;
10212         if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10213                 internal_error(state, ins, "not branch");
10214         }
10215         if (ins->use != 0) {
10216                 internal_error(state, ins, "branch use");
10217         }
10218         /* The challenge here with simplify branch is that I need to 
10219          * make modifications to the control flow graph as well
10220          * as to the branch instruction itself.  That is handled
10221          * by rebuilding the basic blocks after simplify all is called.
10222          */
10223
10224         /* If we have a branch to an unconditional branch update
10225          * our target.  But watch out for dependencies from phi
10226          * functions.
10227          * Also only do this a limited number of times so
10228          * we don't get into an infinite loop.
10229          */
10230         loops = 0;
10231         do {
10232                 struct triple *targ;
10233                 simplified = 0;
10234                 targ = branch_target(state, ins);
10235                 if ((targ != ins) && (targ->op == OP_BRANCH) && 
10236                         !phi_dependency(targ->u.block))
10237                 {
10238                         unuse_triple(TARG(ins, 0), ins);
10239                         TARG(ins, 0) = TARG(targ, 0);
10240                         use_triple(TARG(ins, 0), ins);
10241                         simplified = 1;
10242                 }
10243         } while(simplified && (++loops < 20));
10244
10245         /* If we have a conditional branch with a constant condition
10246          * make it an unconditional branch.
10247          */
10248         if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10249                 struct triple *targ;
10250                 ulong_t value;
10251                 value = read_const(state, ins, RHS(ins, 0));
10252                 unuse_triple(RHS(ins, 0), ins);
10253                 targ = TARG(ins, 0);
10254                 ins->rhs  = 0;
10255                 ins->targ = 1;
10256                 ins->op = OP_BRANCH;
10257                 if (value) {
10258                         unuse_triple(ins->next, ins);
10259                         TARG(ins, 0) = targ;
10260                 }
10261                 else {
10262                         unuse_triple(targ, ins);
10263                         TARG(ins, 0) = ins->next;
10264                 }
10265         }
10266
10267         /* If we have a branch to the next instruction,
10268          * make it a noop.
10269          */
10270         if (TARG(ins, 0) == ins->next) {
10271                 unuse_triple(TARG(ins, 0), ins);
10272                 if (ins->op == OP_CBRANCH) {
10273                         unuse_triple(RHS(ins, 0), ins);
10274                         unuse_triple(ins->next, ins);
10275                 }
10276                 ins->lhs = 0;
10277                 ins->rhs = 0;
10278                 ins->misc = 0;
10279                 ins->targ = 0;
10280                 ins->op = OP_NOOP;
10281                 if (ins->use) {
10282                         internal_error(state, ins, "noop use != 0");
10283                 }
10284         }
10285 }
10286
10287 static void simplify_label(struct compile_state *state, struct triple *ins)
10288 {
10289         /* Ignore volatile labels */
10290         if (!triple_is_pure(state, ins, ins->id)) {
10291                 return;
10292         }
10293         if (ins->use == 0) {
10294                 ins->op = OP_NOOP;
10295         }
10296         else if (ins->prev->op == OP_LABEL) {
10297                 /* In general it is not safe to merge one label that
10298                  * imediately follows another.  The problem is that the empty
10299                  * looking block may have phi functions that depend on it.
10300                  */
10301                 if (!phi_dependency(ins->prev->u.block)) {
10302                         struct triple_set *user, *next;
10303                         ins->op = OP_NOOP;
10304                         for(user = ins->use; user; user = next) {
10305                                 struct triple *use, **expr;
10306                                 next = user->next;
10307                                 use = user->member;
10308                                 expr = triple_targ(state, use, 0);
10309                                 for(;expr; expr = triple_targ(state, use, expr)) {
10310                                         if (*expr == ins) {
10311                                                 *expr = ins->prev;
10312                                                 unuse_triple(ins, use);
10313                                                 use_triple(ins->prev, use);
10314                                         }
10315                                         
10316                                 }
10317                         }
10318                         if (ins->use) {
10319                                 internal_error(state, ins, "noop use != 0");
10320                         }
10321                 }
10322         }
10323 }
10324
10325 static void simplify_phi(struct compile_state *state, struct triple *ins)
10326 {
10327         struct triple **slot;
10328         struct triple *value;
10329         int zrhs, i;
10330         ulong_t cvalue;
10331         slot = &RHS(ins, 0);
10332         zrhs = ins->rhs;
10333         if (zrhs == 0) {
10334                 return;
10335         }
10336         /* See if all of the rhs members of a phi have the same value */
10337         if (slot[0] && is_simple_const(slot[0])) {
10338                 cvalue = read_const(state, ins, slot[0]);
10339                 for(i = 1; i < zrhs; i++) {
10340                         if (    !slot[i] ||
10341                                 !is_simple_const(slot[i]) ||
10342                                 !equiv_types(slot[0]->type, slot[i]->type) ||
10343                                 (cvalue != read_const(state, ins, slot[i]))) {
10344                                 break;
10345                         }
10346                 }
10347                 if (i == zrhs) {
10348                         mkconst(state, ins, cvalue);
10349                         return;
10350                 }
10351         }
10352         
10353         /* See if all of rhs members of a phi are the same */
10354         value = slot[0];
10355         for(i = 1; i < zrhs; i++) {
10356                 if (slot[i] != value) {
10357                         break;
10358                 }
10359         }
10360         if (i == zrhs) {
10361                 /* If the phi has a single value just copy it */
10362                 if (!is_subset_type(ins->type, value->type)) {
10363                         internal_error(state, ins, "bad input type to phi");
10364                 }
10365                 /* Make the types match */
10366                 if (!equiv_types(ins->type, value->type)) {
10367                         ins->type = value->type;
10368                 }
10369                 /* Now make the actual copy */
10370                 mkcopy(state, ins, value);
10371                 return;
10372         }
10373 }
10374
10375
10376 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10377 {
10378         if (is_simple_const(RHS(ins, 0))) {
10379                 ulong_t left;
10380                 left = read_const(state, ins, RHS(ins, 0));
10381                 mkconst(state, ins, bsf(left));
10382         }
10383 }
10384
10385 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10386 {
10387         if (is_simple_const(RHS(ins, 0))) {
10388                 ulong_t left;
10389                 left = read_const(state, ins, RHS(ins, 0));
10390                 mkconst(state, ins, bsr(left));
10391         }
10392 }
10393
10394
10395 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10396 static const struct simplify_table {
10397         simplify_t func;
10398         unsigned long flag;
10399 } table_simplify[] = {
10400 #define simplify_sdivt    simplify_noop
10401 #define simplify_udivt    simplify_noop
10402 #define simplify_piece    simplify_noop
10403
10404 [OP_SDIVT      ] = { simplify_sdivt,    COMPILER_SIMPLIFY_ARITH },
10405 [OP_UDIVT      ] = { simplify_udivt,    COMPILER_SIMPLIFY_ARITH },
10406 [OP_SMUL       ] = { simplify_smul,     COMPILER_SIMPLIFY_ARITH },
10407 [OP_UMUL       ] = { simplify_umul,     COMPILER_SIMPLIFY_ARITH },
10408 [OP_SDIV       ] = { simplify_sdiv,     COMPILER_SIMPLIFY_ARITH },
10409 [OP_UDIV       ] = { simplify_udiv,     COMPILER_SIMPLIFY_ARITH },
10410 [OP_SMOD       ] = { simplify_smod,     COMPILER_SIMPLIFY_ARITH },
10411 [OP_UMOD       ] = { simplify_umod,     COMPILER_SIMPLIFY_ARITH },
10412 [OP_ADD        ] = { simplify_add,      COMPILER_SIMPLIFY_ARITH },
10413 [OP_SUB        ] = { simplify_sub,      COMPILER_SIMPLIFY_ARITH },
10414 [OP_SL         ] = { simplify_sl,       COMPILER_SIMPLIFY_SHIFT },
10415 [OP_USR        ] = { simplify_usr,      COMPILER_SIMPLIFY_SHIFT },
10416 [OP_SSR        ] = { simplify_ssr,      COMPILER_SIMPLIFY_SHIFT },
10417 [OP_AND        ] = { simplify_and,      COMPILER_SIMPLIFY_BITWISE },
10418 [OP_XOR        ] = { simplify_xor,      COMPILER_SIMPLIFY_BITWISE },
10419 [OP_OR         ] = { simplify_or,       COMPILER_SIMPLIFY_BITWISE },
10420 [OP_POS        ] = { simplify_pos,      COMPILER_SIMPLIFY_ARITH },
10421 [OP_NEG        ] = { simplify_neg,      COMPILER_SIMPLIFY_ARITH },
10422 [OP_INVERT     ] = { simplify_invert,   COMPILER_SIMPLIFY_BITWISE },
10423
10424 [OP_EQ         ] = { simplify_eq,       COMPILER_SIMPLIFY_LOGICAL },
10425 [OP_NOTEQ      ] = { simplify_noteq,    COMPILER_SIMPLIFY_LOGICAL },
10426 [OP_SLESS      ] = { simplify_sless,    COMPILER_SIMPLIFY_LOGICAL },
10427 [OP_ULESS      ] = { simplify_uless,    COMPILER_SIMPLIFY_LOGICAL },
10428 [OP_SMORE      ] = { simplify_smore,    COMPILER_SIMPLIFY_LOGICAL },
10429 [OP_UMORE      ] = { simplify_umore,    COMPILER_SIMPLIFY_LOGICAL },
10430 [OP_SLESSEQ    ] = { simplify_slesseq,  COMPILER_SIMPLIFY_LOGICAL },
10431 [OP_ULESSEQ    ] = { simplify_ulesseq,  COMPILER_SIMPLIFY_LOGICAL },
10432 [OP_SMOREEQ    ] = { simplify_smoreeq,  COMPILER_SIMPLIFY_LOGICAL },
10433 [OP_UMOREEQ    ] = { simplify_umoreeq,  COMPILER_SIMPLIFY_LOGICAL },
10434 [OP_LFALSE     ] = { simplify_lfalse,   COMPILER_SIMPLIFY_LOGICAL },
10435 [OP_LTRUE      ] = { simplify_ltrue,    COMPILER_SIMPLIFY_LOGICAL },
10436
10437 [OP_LOAD       ] = { simplify_load,     COMPILER_SIMPLIFY_OP },
10438 [OP_STORE      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10439
10440 [OP_UEXTRACT   ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10441 [OP_SEXTRACT   ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10442 [OP_DEPOSIT    ] = { simplify_deposit,  COMPILER_SIMPLIFY_BITFIELD },
10443
10444 [OP_NOOP       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10445
10446 [OP_INTCONST   ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10447 [OP_BLOBCONST  ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10448 [OP_ADDRCONST  ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10449 [OP_UNKNOWNVAL ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10450
10451 [OP_WRITE      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10452 [OP_READ       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10453 [OP_COPY       ] = { simplify_copy,     COMPILER_SIMPLIFY_COPY },
10454 [OP_CONVERT    ] = { simplify_copy,     COMPILER_SIMPLIFY_COPY },
10455 [OP_PIECE      ] = { simplify_piece,    COMPILER_SIMPLIFY_OP },
10456 [OP_ASM        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10457
10458 [OP_DOT        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10459 [OP_INDEX      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10460
10461 [OP_LIST       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10462 [OP_BRANCH     ] = { simplify_branch,   COMPILER_SIMPLIFY_BRANCH },
10463 [OP_CBRANCH    ] = { simplify_branch,   COMPILER_SIMPLIFY_BRANCH },
10464 [OP_CALL       ] = { simplify_noop,     COMPILER_SIMPLIFY_BRANCH },
10465 [OP_RET        ] = { simplify_noop,     COMPILER_SIMPLIFY_BRANCH },
10466 [OP_LABEL      ] = { simplify_label,    COMPILER_SIMPLIFY_LABEL },
10467 [OP_ADECL      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10468 [OP_SDECL      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10469 [OP_PHI        ] = { simplify_phi,      COMPILER_SIMPLIFY_PHI },
10470
10471 [OP_INB        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10472 [OP_INW        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10473 [OP_INL        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10474 [OP_OUTB       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10475 [OP_OUTW       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10476 [OP_OUTL       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10477 [OP_BSF        ] = { simplify_bsf,      COMPILER_SIMPLIFY_OP },
10478 [OP_BSR        ] = { simplify_bsr,      COMPILER_SIMPLIFY_OP },
10479 [OP_RDMSR      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10480 [OP_WRMSR      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },               
10481 [OP_HLT        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10482 };
10483
10484 static inline void debug_simplify(struct compile_state *state, 
10485         simplify_t do_simplify, struct triple *ins)
10486 {
10487 #if DEBUG_SIMPLIFY_HIRES
10488                 if (state->functions_joined && (do_simplify != simplify_noop)) {
10489                         /* High resolution debugging mode */
10490                         fprintf(state->dbgout, "simplifing: ");
10491                         display_triple(state->dbgout, ins);
10492                 }
10493 #endif
10494                 do_simplify(state, ins);
10495 #if DEBUG_SIMPLIFY_HIRES
10496                 if (state->functions_joined && (do_simplify != simplify_noop)) {
10497                         /* High resolution debugging mode */
10498                         fprintf(state->dbgout, "simplified: ");
10499                         display_triple(state->dbgout, ins);
10500                 }
10501 #endif
10502 }
10503 static void simplify(struct compile_state *state, struct triple *ins)
10504 {
10505         int op;
10506         simplify_t do_simplify;
10507         if (ins == &unknown_triple) {
10508                 internal_error(state, ins, "simplifying the unknown triple?");
10509         }
10510         do {
10511                 op = ins->op;
10512                 do_simplify = 0;
10513                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10514                         do_simplify = 0;
10515                 }
10516                 else {
10517                         do_simplify = table_simplify[op].func;
10518                 }
10519                 if (do_simplify && 
10520                         !(state->compiler->flags & table_simplify[op].flag)) {
10521                         do_simplify = simplify_noop;
10522                 }
10523                 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10524                         do_simplify = simplify_noop;
10525                 }
10526         
10527                 if (!do_simplify) {
10528                         internal_error(state, ins, "cannot simplify op: %d %s",
10529                                 op, tops(op));
10530                         return;
10531                 }
10532                 debug_simplify(state, do_simplify, ins);
10533         } while(ins->op != op);
10534 }
10535
10536 static void rebuild_ssa_form(struct compile_state *state);
10537
10538 static void simplify_all(struct compile_state *state)
10539 {
10540         struct triple *ins, *first;
10541         if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10542                 return;
10543         }
10544         first = state->first;
10545         ins = first->prev;
10546         do {
10547                 simplify(state, ins);
10548                 ins = ins->prev;
10549         } while(ins != first->prev);
10550         ins = first;
10551         do {
10552                 simplify(state, ins);
10553                 ins = ins->next;
10554         }while(ins != first);
10555         rebuild_ssa_form(state);
10556
10557         print_blocks(state, __func__, state->dbgout);
10558 }
10559
10560 /*
10561  * Builtins....
10562  * ============================
10563  */
10564
10565 static void register_builtin_function(struct compile_state *state,
10566         const char *name, int op, struct type *rtype, ...)
10567 {
10568         struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10569         struct triple *def, *arg, *result, *work, *last, *first, *retvar, *ret;
10570         struct hash_entry *ident;
10571         struct file_state file;
10572         int parameters;
10573         int name_len;
10574         va_list args;
10575         int i;
10576
10577         /* Dummy file state to get debug handling right */
10578         memset(&file, 0, sizeof(file));
10579         file.basename = "<built-in>";
10580         file.line = 1;
10581         file.report_line = 1;
10582         file.report_name = file.basename;
10583         file.prev = state->file;
10584         state->file = &file;
10585         state->function = name;
10586
10587         /* Find the Parameter count */
10588         valid_op(state, op);
10589         parameters = table_ops[op].rhs;
10590         if (parameters < 0 ) {
10591                 internal_error(state, 0, "Invalid builtin parameter count");
10592         }
10593
10594         /* Find the function type */
10595         ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10596         ftype->elements = parameters;
10597         next = &ftype->right;
10598         va_start(args, rtype);
10599         for(i = 0; i < parameters; i++) {
10600                 atype = va_arg(args, struct type *);
10601                 if (!*next) {
10602                         *next = atype;
10603                 } else {
10604                         *next = new_type(TYPE_PRODUCT, *next, atype);
10605                         next = &((*next)->right);
10606                 }
10607         }
10608         if (!*next) {
10609                 *next = &void_type;
10610         }
10611         va_end(args);
10612
10613         /* Get the initial closure type */
10614         ctype = new_type(TYPE_JOIN, &void_type, 0);
10615         ctype->elements = 1;
10616
10617         /* Get the return type */
10618         crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10619         crtype->elements = 2;
10620
10621         /* Generate the needed triples */
10622         def = triple(state, OP_LIST, ftype, 0, 0);
10623         first = label(state);
10624         RHS(def, 0) = first;
10625         result = flatten(state, first, variable(state, crtype));
10626         retvar = flatten(state, first, variable(state, &void_ptr_type));
10627         ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10628
10629         /* Now string them together */
10630         param = ftype->right;
10631         for(i = 0; i < parameters; i++) {
10632                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10633                         atype = param->left;
10634                 } else {
10635                         atype = param;
10636                 }
10637                 arg = flatten(state, first, variable(state, atype));
10638                 param = param->right;
10639         }
10640         work = new_triple(state, op, rtype, -1, parameters);
10641         generate_lhs_pieces(state, work);
10642         for(i = 0; i < parameters; i++) {
10643                 RHS(work, i) = read_expr(state, farg(state, def, i));
10644         }
10645         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10646                 work = write_expr(state, deref_index(state, result, 1), work);
10647         }
10648         work = flatten(state, first, work);
10649         last = flatten(state, first, label(state));
10650         ret  = flatten(state, first, ret);
10651         name_len = strlen(name);
10652         ident = lookup(state, name, name_len);
10653         ftype->type_ident = ident;
10654         symbol(state, ident, &ident->sym_ident, def, ftype);
10655         
10656         state->file = file.prev;
10657         state->function = 0;
10658         state->main_function = 0;
10659
10660         if (!state->functions) {
10661                 state->functions = def;
10662         } else {
10663                 insert_triple(state, state->functions, def);
10664         }
10665         if (state->compiler->debug & DEBUG_INLINE) {
10666                 FILE *fp = state->dbgout;
10667                 fprintf(fp, "\n");
10668                 loc(fp, state, 0);
10669                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10670                 display_func(state, fp, def);
10671                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10672         }
10673 }
10674
10675 static struct type *partial_struct(struct compile_state *state,
10676         const char *field_name, struct type *type, struct type *rest)
10677 {
10678         struct hash_entry *field_ident;
10679         struct type *result;
10680         int field_name_len;
10681
10682         field_name_len = strlen(field_name);
10683         field_ident = lookup(state, field_name, field_name_len);
10684
10685         result = clone_type(0, type);
10686         result->field_ident = field_ident;
10687
10688         if (rest) {
10689                 result = new_type(TYPE_PRODUCT, result, rest);
10690         }
10691         return result;
10692 }
10693
10694 static struct type *register_builtin_type(struct compile_state *state,
10695         const char *name, struct type *type)
10696 {
10697         struct hash_entry *ident;
10698         int name_len;
10699
10700         name_len = strlen(name);
10701         ident = lookup(state, name, name_len);
10702         
10703         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10704                 ulong_t elements = 0;
10705                 struct type *field;
10706                 type = new_type(TYPE_STRUCT, type, 0);
10707                 field = type->left;
10708                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10709                         elements++;
10710                         field = field->right;
10711                 }
10712                 elements++;
10713                 symbol(state, ident, &ident->sym_tag, 0, type);
10714                 type->type_ident = ident;
10715                 type->elements = elements;
10716         }
10717         symbol(state, ident, &ident->sym_ident, 0, type);
10718         ident->tok = TOK_TYPE_NAME;
10719         return type;
10720 }
10721
10722
10723 static void register_builtins(struct compile_state *state)
10724 {
10725         struct type *div_type, *ldiv_type;
10726         struct type *udiv_type, *uldiv_type;
10727         struct type *msr_type;
10728
10729         div_type = register_builtin_type(state, "__builtin_div_t",
10730                 partial_struct(state, "quot", &int_type,
10731                 partial_struct(state, "rem",  &int_type, 0)));
10732         ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10733                 partial_struct(state, "quot", &long_type,
10734                 partial_struct(state, "rem",  &long_type, 0)));
10735         udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10736                 partial_struct(state, "quot", &uint_type,
10737                 partial_struct(state, "rem",  &uint_type, 0)));
10738         uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10739                 partial_struct(state, "quot", &ulong_type,
10740                 partial_struct(state, "rem",  &ulong_type, 0)));
10741
10742         register_builtin_function(state, "__builtin_div",   OP_SDIVT, div_type,
10743                 &int_type, &int_type);
10744         register_builtin_function(state, "__builtin_ldiv",  OP_SDIVT, ldiv_type,
10745                 &long_type, &long_type);
10746         register_builtin_function(state, "__builtin_udiv",  OP_UDIVT, udiv_type,
10747                 &uint_type, &uint_type);
10748         register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10749                 &ulong_type, &ulong_type);
10750
10751         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
10752                 &ushort_type);
10753         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10754                 &ushort_type);
10755         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
10756                 &ushort_type);
10757
10758         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
10759                 &uchar_type, &ushort_type);
10760         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
10761                 &ushort_type, &ushort_type);
10762         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
10763                 &uint_type, &ushort_type);
10764         
10765         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
10766                 &int_type);
10767         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
10768                 &int_type);
10769
10770         msr_type = register_builtin_type(state, "__builtin_msr_t",
10771                 partial_struct(state, "lo", &ulong_type,
10772                 partial_struct(state, "hi", &ulong_type, 0)));
10773
10774         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10775                 &ulong_type);
10776         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10777                 &ulong_type, &ulong_type, &ulong_type);
10778         
10779         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
10780                 &void_type);
10781 }
10782
10783 static struct type *declarator(
10784         struct compile_state *state, struct type *type, 
10785         struct hash_entry **ident, int need_ident);
10786 static void decl(struct compile_state *state, struct triple *first);
10787 static struct type *specifier_qualifier_list(struct compile_state *state);
10788 static int isdecl_specifier(int tok);
10789 static struct type *decl_specifiers(struct compile_state *state);
10790 static int istype(int tok);
10791 static struct triple *expr(struct compile_state *state);
10792 static struct triple *assignment_expr(struct compile_state *state);
10793 static struct type *type_name(struct compile_state *state);
10794 static void statement(struct compile_state *state, struct triple *first);
10795
10796 static struct triple *call_expr(
10797         struct compile_state *state, struct triple *func)
10798 {
10799         struct triple *def;
10800         struct type *param, *type;
10801         ulong_t pvals, index;
10802
10803         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10804                 error(state, 0, "Called object is not a function");
10805         }
10806         if (func->op != OP_LIST) {
10807                 internal_error(state, 0, "improper function");
10808         }
10809         eat(state, TOK_LPAREN);
10810         /* Find the return type without any specifiers */
10811         type = clone_type(0, func->type->left);
10812         /* Count the number of rhs entries for OP_FCALL */
10813         param = func->type->right;
10814         pvals = 0;
10815         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10816                 pvals++;
10817                 param = param->right;
10818         }
10819         if ((param->type & TYPE_MASK) != TYPE_VOID) {
10820                 pvals++;
10821         }
10822         def = new_triple(state, OP_FCALL, type, -1, pvals);
10823         MISC(def, 0) = func;
10824
10825         param = func->type->right;
10826         for(index = 0; index < pvals; index++) {
10827                 struct triple *val;
10828                 struct type *arg_type;
10829                 val = read_expr(state, assignment_expr(state));
10830                 arg_type = param;
10831                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10832                         arg_type = param->left;
10833                 }
10834                 write_compatible(state, arg_type, val->type);
10835                 RHS(def, index) = val;
10836                 if (index != (pvals - 1)) {
10837                         eat(state, TOK_COMMA);
10838                         param = param->right;
10839                 }
10840         }
10841         eat(state, TOK_RPAREN);
10842         return def;
10843 }
10844
10845
10846 static struct triple *character_constant(struct compile_state *state)
10847 {
10848         struct triple *def;
10849         struct token *tk;
10850         const signed char *str, *end;
10851         int c;
10852         int str_len;
10853         eat(state, TOK_LIT_CHAR);
10854         tk = &state->token[0];
10855         str = tk->val.str + 1;
10856         str_len = tk->str_len - 2;
10857         if (str_len <= 0) {
10858                 error(state, 0, "empty character constant");
10859         }
10860         end = str + str_len;
10861         c = char_value(state, &str, end);
10862         if (str != end) {
10863                 error(state, 0, "multibyte character constant not supported");
10864         }
10865         def = int_const(state, &char_type, (ulong_t)((long_t)c));
10866         return def;
10867 }
10868
10869 static struct triple *string_constant(struct compile_state *state)
10870 {
10871         struct triple *def;
10872         struct token *tk;
10873         struct type *type;
10874         const signed char *str, *end;
10875         signed char *buf, *ptr;
10876         int str_len;
10877
10878         buf = 0;
10879         type = new_type(TYPE_ARRAY, &char_type, 0);
10880         type->elements = 0;
10881         /* The while loop handles string concatenation */
10882         do {
10883                 eat(state, TOK_LIT_STRING);
10884                 tk = &state->token[0];
10885                 str = tk->val.str + 1;
10886                 str_len = tk->str_len - 2;
10887                 if (str_len < 0) {
10888                         error(state, 0, "negative string constant length");
10889                 }
10890                 end = str + str_len;
10891                 ptr = buf;
10892                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10893                 memcpy(buf, ptr, type->elements);
10894                 ptr = buf + type->elements;
10895                 do {
10896                         *ptr++ = char_value(state, &str, end);
10897                 } while(str < end);
10898                 type->elements = ptr - buf;
10899         } while(peek(state) == TOK_LIT_STRING);
10900         *ptr = '\0';
10901         type->elements += 1;
10902         def = triple(state, OP_BLOBCONST, type, 0, 0);
10903         def->u.blob = buf;
10904
10905         return def;
10906 }
10907
10908
10909 static struct triple *integer_constant(struct compile_state *state)
10910 {
10911         struct triple *def;
10912         unsigned long val;
10913         struct token *tk;
10914         char *end;
10915         int u, l, decimal;
10916         struct type *type;
10917
10918         eat(state, TOK_LIT_INT);
10919         tk = &state->token[0];
10920         errno = 0;
10921         decimal = (tk->val.str[0] != '0');
10922         val = strtoul(tk->val.str, &end, 0);
10923         if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10924                 error(state, 0, "Integer constant to large");
10925         }
10926         u = l = 0;
10927         if ((*end == 'u') || (*end == 'U')) {
10928                 u = 1;
10929                         end++;
10930         }
10931         if ((*end == 'l') || (*end == 'L')) {
10932                 l = 1;
10933                 end++;
10934         }
10935         if ((*end == 'u') || (*end == 'U')) {
10936                 u = 1;
10937                 end++;
10938         }
10939         if (*end) {
10940                 error(state, 0, "Junk at end of integer constant");
10941         }
10942         if (u && l)  {
10943                 type = &ulong_type;
10944         }
10945         else if (l) {
10946                 type = &long_type;
10947                 if (!decimal && (val > LONG_T_MAX)) {
10948                         type = &ulong_type;
10949                 }
10950         }
10951         else if (u) {
10952                 type = &uint_type;
10953                 if (val > UINT_T_MAX) {
10954                         type = &ulong_type;
10955                 }
10956         }
10957         else {
10958                 type = &int_type;
10959                 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10960                         type = &uint_type;
10961                 }
10962                 else if (!decimal && (val > LONG_T_MAX)) {
10963                         type = &ulong_type;
10964                 }
10965                 else if (val > INT_T_MAX) {
10966                         type = &long_type;
10967                 }
10968         }
10969         def = int_const(state, type, val);
10970         return def;
10971 }
10972
10973 static struct triple *primary_expr(struct compile_state *state)
10974 {
10975         struct triple *def;
10976         int tok;
10977         tok = peek(state);
10978         switch(tok) {
10979         case TOK_IDENT:
10980         {
10981                 struct hash_entry *ident;
10982                 /* Here ident is either:
10983                  * a varable name
10984                  * a function name
10985                  */
10986                 eat(state, TOK_IDENT);
10987                 ident = state->token[0].ident;
10988                 if (!ident->sym_ident) {
10989                         error(state, 0, "%s undeclared", ident->name);
10990                 }
10991                 def = ident->sym_ident->def;
10992                 break;
10993         }
10994         case TOK_ENUM_CONST:
10995         {
10996                 struct hash_entry *ident;
10997                 /* Here ident is an enumeration constant */
10998                 eat(state, TOK_ENUM_CONST);
10999                 ident = state->token[0].ident;
11000                 if (!ident->sym_ident) {
11001                         error(state, 0, "%s undeclared", ident->name);
11002                 }
11003                 def = ident->sym_ident->def;
11004                 break;
11005         }
11006         case TOK_LPAREN:
11007                 eat(state, TOK_LPAREN);
11008                 def = expr(state);
11009                 eat(state, TOK_RPAREN);
11010                 break;
11011         case TOK_LIT_INT:
11012                 def = integer_constant(state);
11013                 break;
11014         case TOK_LIT_FLOAT:
11015                 eat(state, TOK_LIT_FLOAT);
11016                 error(state, 0, "Floating point constants not supported");
11017                 def = 0;
11018                 FINISHME();
11019                 break;
11020         case TOK_LIT_CHAR:
11021                 def = character_constant(state);
11022                 break;
11023         case TOK_LIT_STRING:
11024                 def = string_constant(state);
11025                 break;
11026         default:
11027                 def = 0;
11028                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
11029         }
11030         return def;
11031 }
11032
11033 static struct triple *postfix_expr(struct compile_state *state)
11034 {
11035         struct triple *def;
11036         int postfix;
11037         def = primary_expr(state);
11038         do {
11039                 struct triple *left;
11040                 int tok;
11041                 postfix = 1;
11042                 left = def;
11043                 switch((tok = peek(state))) {
11044                 case TOK_LBRACKET:
11045                         eat(state, TOK_LBRACKET);
11046                         def = mk_subscript_expr(state, left, expr(state));
11047                         eat(state, TOK_RBRACKET);
11048                         break;
11049                 case TOK_LPAREN:
11050                         def = call_expr(state, def);
11051                         break;
11052                 case TOK_DOT:
11053                 {
11054                         struct hash_entry *field;
11055                         eat(state, TOK_DOT);
11056                         eat(state, TOK_IDENT);
11057                         field = state->token[0].ident;
11058                         def = deref_field(state, def, field);
11059                         break;
11060                 }
11061                 case TOK_ARROW:
11062                 {
11063                         struct hash_entry *field;
11064                         eat(state, TOK_ARROW);
11065                         eat(state, TOK_IDENT);
11066                         field = state->token[0].ident;
11067                         def = mk_deref_expr(state, read_expr(state, def));
11068                         def = deref_field(state, def, field);
11069                         break;
11070                 }
11071                 case TOK_PLUSPLUS:
11072                         eat(state, TOK_PLUSPLUS);
11073                         def = mk_post_inc_expr(state, left);
11074                         break;
11075                 case TOK_MINUSMINUS:
11076                         eat(state, TOK_MINUSMINUS);
11077                         def = mk_post_dec_expr(state, left);
11078                         break;
11079                 default:
11080                         postfix = 0;
11081                         break;
11082                 }
11083         } while(postfix);
11084         return def;
11085 }
11086
11087 static struct triple *cast_expr(struct compile_state *state);
11088
11089 static struct triple *unary_expr(struct compile_state *state)
11090 {
11091         struct triple *def, *right;
11092         int tok;
11093         switch((tok = peek(state))) {
11094         case TOK_PLUSPLUS:
11095                 eat(state, TOK_PLUSPLUS);
11096                 def = mk_pre_inc_expr(state, unary_expr(state));
11097                 break;
11098         case TOK_MINUSMINUS:
11099                 eat(state, TOK_MINUSMINUS);
11100                 def = mk_pre_dec_expr(state, unary_expr(state));
11101                 break;
11102         case TOK_AND:
11103                 eat(state, TOK_AND);
11104                 def = mk_addr_expr(state, cast_expr(state), 0);
11105                 break;
11106         case TOK_STAR:
11107                 eat(state, TOK_STAR);
11108                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
11109                 break;
11110         case TOK_PLUS:
11111                 eat(state, TOK_PLUS);
11112                 right = read_expr(state, cast_expr(state));
11113                 arithmetic(state, right);
11114                 def = integral_promotion(state, right);
11115                 break;
11116         case TOK_MINUS:
11117                 eat(state, TOK_MINUS);
11118                 right = read_expr(state, cast_expr(state));
11119                 arithmetic(state, right);
11120                 def = integral_promotion(state, right);
11121                 def = triple(state, OP_NEG, def->type, def, 0);
11122                 break;
11123         case TOK_TILDE:
11124                 eat(state, TOK_TILDE);
11125                 right = read_expr(state, cast_expr(state));
11126                 integral(state, right);
11127                 def = integral_promotion(state, right);
11128                 def = triple(state, OP_INVERT, def->type, def, 0);
11129                 break;
11130         case TOK_BANG:
11131                 eat(state, TOK_BANG);
11132                 right = read_expr(state, cast_expr(state));
11133                 bool(state, right);
11134                 def = lfalse_expr(state, right);
11135                 break;
11136         case TOK_SIZEOF:
11137         {
11138                 struct type *type;
11139                 int tok1, tok2;
11140                 eat(state, TOK_SIZEOF);
11141                 tok1 = peek(state);
11142                 tok2 = peek2(state);
11143                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11144                         eat(state, TOK_LPAREN);
11145                         type = type_name(state);
11146                         eat(state, TOK_RPAREN);
11147                 }
11148                 else {
11149                         struct triple *expr;
11150                         expr = unary_expr(state);
11151                         type = expr->type;
11152                         release_expr(state, expr);
11153                 }
11154                 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11155                 break;
11156         }
11157         case TOK_ALIGNOF:
11158         {
11159                 struct type *type;
11160                 int tok1, tok2;
11161                 eat(state, TOK_ALIGNOF);
11162                 tok1 = peek(state);
11163                 tok2 = peek2(state);
11164                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11165                         eat(state, TOK_LPAREN);
11166                         type = type_name(state);
11167                         eat(state, TOK_RPAREN);
11168                 }
11169                 else {
11170                         struct triple *expr;
11171                         expr = unary_expr(state);
11172                         type = expr->type;
11173                         release_expr(state, expr);
11174                 }
11175                 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11176                 break;
11177         }
11178         default:
11179                 def = postfix_expr(state);
11180                 break;
11181         }
11182         return def;
11183 }
11184
11185 static struct triple *cast_expr(struct compile_state *state)
11186 {
11187         struct triple *def;
11188         int tok1, tok2;
11189         tok1 = peek(state);
11190         tok2 = peek2(state);
11191         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11192                 struct type *type;
11193                 eat(state, TOK_LPAREN);
11194                 type = type_name(state);
11195                 eat(state, TOK_RPAREN);
11196                 def = mk_cast_expr(state, type, cast_expr(state));
11197         }
11198         else {
11199                 def = unary_expr(state);
11200         }
11201         return def;
11202 }
11203
11204 static struct triple *mult_expr(struct compile_state *state)
11205 {
11206         struct triple *def;
11207         int done;
11208         def = cast_expr(state);
11209         do {
11210                 struct triple *left, *right;
11211                 struct type *result_type;
11212                 int tok, op, sign;
11213                 done = 0;
11214                 switch(tok = (peek(state))) {
11215                 case TOK_STAR:
11216                 case TOK_DIV:
11217                 case TOK_MOD:
11218                         left = read_expr(state, def);
11219                         arithmetic(state, left);
11220
11221                         eat(state, tok);
11222
11223                         right = read_expr(state, cast_expr(state));
11224                         arithmetic(state, right);
11225
11226                         result_type = arithmetic_result(state, left, right);
11227                         sign = is_signed(result_type);
11228                         op = -1;
11229                         switch(tok) {
11230                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11231                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
11232                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
11233                         }
11234                         def = triple(state, op, result_type, left, right);
11235                         break;
11236                 default:
11237                         done = 1;
11238                         break;
11239                 }
11240         } while(!done);
11241         return def;
11242 }
11243
11244 static struct triple *add_expr(struct compile_state *state)
11245 {
11246         struct triple *def;
11247         int done;
11248         def = mult_expr(state);
11249         do {
11250                 done = 0;
11251                 switch( peek(state)) {
11252                 case TOK_PLUS:
11253                         eat(state, TOK_PLUS);
11254                         def = mk_add_expr(state, def, mult_expr(state));
11255                         break;
11256                 case TOK_MINUS:
11257                         eat(state, TOK_MINUS);
11258                         def = mk_sub_expr(state, def, mult_expr(state));
11259                         break;
11260                 default:
11261                         done = 1;
11262                         break;
11263                 }
11264         } while(!done);
11265         return def;
11266 }
11267
11268 static struct triple *shift_expr(struct compile_state *state)
11269 {
11270         struct triple *def;
11271         int done;
11272         def = add_expr(state);
11273         do {
11274                 struct triple *left, *right;
11275                 int tok, op;
11276                 done = 0;
11277                 switch((tok = peek(state))) {
11278                 case TOK_SL:
11279                 case TOK_SR:
11280                         left = read_expr(state, def);
11281                         integral(state, left);
11282                         left = integral_promotion(state, left);
11283
11284                         eat(state, tok);
11285
11286                         right = read_expr(state, add_expr(state));
11287                         integral(state, right);
11288                         right = integral_promotion(state, right);
11289                         
11290                         op = (tok == TOK_SL)? OP_SL : 
11291                                 is_signed(left->type)? OP_SSR: OP_USR;
11292
11293                         def = triple(state, op, left->type, left, right);
11294                         break;
11295                 default:
11296                         done = 1;
11297                         break;
11298                 }
11299         } while(!done);
11300         return def;
11301 }
11302
11303 static struct triple *relational_expr(struct compile_state *state)
11304 {
11305 #warning "Extend relational exprs to work on more than arithmetic types"
11306         struct triple *def;
11307         int done;
11308         def = shift_expr(state);
11309         do {
11310                 struct triple *left, *right;
11311                 struct type *arg_type;
11312                 int tok, op, sign;
11313                 done = 0;
11314                 switch((tok = peek(state))) {
11315                 case TOK_LESS:
11316                 case TOK_MORE:
11317                 case TOK_LESSEQ:
11318                 case TOK_MOREEQ:
11319                         left = read_expr(state, def);
11320                         arithmetic(state, left);
11321
11322                         eat(state, tok);
11323
11324                         right = read_expr(state, shift_expr(state));
11325                         arithmetic(state, right);
11326
11327                         arg_type = arithmetic_result(state, left, right);
11328                         sign = is_signed(arg_type);
11329                         op = -1;
11330                         switch(tok) {
11331                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
11332                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
11333                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11334                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11335                         }
11336                         def = triple(state, op, &int_type, left, right);
11337                         break;
11338                 default:
11339                         done = 1;
11340                         break;
11341                 }
11342         } while(!done);
11343         return def;
11344 }
11345
11346 static struct triple *equality_expr(struct compile_state *state)
11347 {
11348 #warning "Extend equality exprs to work on more than arithmetic types"
11349         struct triple *def;
11350         int done;
11351         def = relational_expr(state);
11352         do {
11353                 struct triple *left, *right;
11354                 int tok, op;
11355                 done = 0;
11356                 switch((tok = peek(state))) {
11357                 case TOK_EQEQ:
11358                 case TOK_NOTEQ:
11359                         left = read_expr(state, def);
11360                         arithmetic(state, left);
11361                         eat(state, tok);
11362                         right = read_expr(state, relational_expr(state));
11363                         arithmetic(state, right);
11364                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11365                         def = triple(state, op, &int_type, left, right);
11366                         break;
11367                 default:
11368                         done = 1;
11369                         break;
11370                 }
11371         } while(!done);
11372         return def;
11373 }
11374
11375 static struct triple *and_expr(struct compile_state *state)
11376 {
11377         struct triple *def;
11378         def = equality_expr(state);
11379         while(peek(state) == TOK_AND) {
11380                 struct triple *left, *right;
11381                 struct type *result_type;
11382                 left = read_expr(state, def);
11383                 integral(state, left);
11384                 eat(state, TOK_AND);
11385                 right = read_expr(state, equality_expr(state));
11386                 integral(state, right);
11387                 result_type = arithmetic_result(state, left, right);
11388                 def = triple(state, OP_AND, result_type, left, right);
11389         }
11390         return def;
11391 }
11392
11393 static struct triple *xor_expr(struct compile_state *state)
11394 {
11395         struct triple *def;
11396         def = and_expr(state);
11397         while(peek(state) == TOK_XOR) {
11398                 struct triple *left, *right;
11399                 struct type *result_type;
11400                 left = read_expr(state, def);
11401                 integral(state, left);
11402                 eat(state, TOK_XOR);
11403                 right = read_expr(state, and_expr(state));
11404                 integral(state, right);
11405                 result_type = arithmetic_result(state, left, right);
11406                 def = triple(state, OP_XOR, result_type, left, right);
11407         }
11408         return def;
11409 }
11410
11411 static struct triple *or_expr(struct compile_state *state)
11412 {
11413         struct triple *def;
11414         def = xor_expr(state);
11415         while(peek(state) == TOK_OR) {
11416                 struct triple *left, *right;
11417                 struct type *result_type;
11418                 left = read_expr(state, def);
11419                 integral(state, left);
11420                 eat(state, TOK_OR);
11421                 right = read_expr(state, xor_expr(state));
11422                 integral(state, right);
11423                 result_type = arithmetic_result(state, left, right);
11424                 def = triple(state, OP_OR, result_type, left, right);
11425         }
11426         return def;
11427 }
11428
11429 static struct triple *land_expr(struct compile_state *state)
11430 {
11431         struct triple *def;
11432         def = or_expr(state);
11433         while(peek(state) == TOK_LOGAND) {
11434                 struct triple *left, *right;
11435                 left = read_expr(state, def);
11436                 bool(state, left);
11437                 eat(state, TOK_LOGAND);
11438                 right = read_expr(state, or_expr(state));
11439                 bool(state, right);
11440
11441                 def = mkland_expr(state,
11442                         ltrue_expr(state, left),
11443                         ltrue_expr(state, right));
11444         }
11445         return def;
11446 }
11447
11448 static struct triple *lor_expr(struct compile_state *state)
11449 {
11450         struct triple *def;
11451         def = land_expr(state);
11452         while(peek(state) == TOK_LOGOR) {
11453                 struct triple *left, *right;
11454                 left = read_expr(state, def);
11455                 bool(state, left);
11456                 eat(state, TOK_LOGOR);
11457                 right = read_expr(state, land_expr(state));
11458                 bool(state, right);
11459
11460                 def = mklor_expr(state, 
11461                         ltrue_expr(state, left),
11462                         ltrue_expr(state, right));
11463         }
11464         return def;
11465 }
11466
11467 static struct triple *conditional_expr(struct compile_state *state)
11468 {
11469         struct triple *def;
11470         def = lor_expr(state);
11471         if (peek(state) == TOK_QUEST) {
11472                 struct triple *test, *left, *right;
11473                 bool(state, def);
11474                 test = ltrue_expr(state, read_expr(state, def));
11475                 eat(state, TOK_QUEST);
11476                 left = read_expr(state, expr(state));
11477                 eat(state, TOK_COLON);
11478                 right = read_expr(state, conditional_expr(state));
11479
11480                 def = mkcond_expr(state, test, left, right);
11481         }
11482         return def;
11483 }
11484
11485 static struct triple *eval_const_expr(
11486         struct compile_state *state, struct triple *expr)
11487 {
11488         struct triple *def;
11489         if (is_const(expr)) {
11490                 def = expr;
11491         } 
11492         else {
11493                 /* If we don't start out as a constant simplify into one */
11494                 struct triple *head, *ptr;
11495                 head = label(state); /* dummy initial triple */
11496                 flatten(state, head, expr);
11497                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11498                         simplify(state, ptr);
11499                 }
11500                 /* Remove the constant value the tail of the list */
11501                 def = head->prev;
11502                 def->prev->next = def->next;
11503                 def->next->prev = def->prev;
11504                 def->next = def->prev = def;
11505                 if (!is_const(def)) {
11506                         error(state, 0, "Not a constant expression");
11507                 }
11508                 /* Free the intermediate expressions */
11509                 while(head->next != head) {
11510                         release_triple(state, head->next);
11511                 }
11512                 free_triple(state, head);
11513         }
11514         return def;
11515 }
11516
11517 static struct triple *constant_expr(struct compile_state *state)
11518 {
11519         return eval_const_expr(state, conditional_expr(state));
11520 }
11521
11522 static struct triple *assignment_expr(struct compile_state *state)
11523 {
11524         struct triple *def, *left, *right;
11525         int tok, op, sign;
11526         /* The C grammer in K&R shows assignment expressions
11527          * only taking unary expressions as input on their
11528          * left hand side.  But specifies the precedence of
11529          * assignemnt as the lowest operator except for comma.
11530          *
11531          * Allowing conditional expressions on the left hand side
11532          * of an assignement results in a grammar that accepts
11533          * a larger set of statements than standard C.   As long
11534          * as the subset of the grammar that is standard C behaves
11535          * correctly this should cause no problems.
11536          * 
11537          * For the extra token strings accepted by the grammar
11538          * none of them should produce a valid lvalue, so they
11539          * should not produce functioning programs.
11540          *
11541          * GCC has this bug as well, so surprises should be minimal.
11542          */
11543         def = conditional_expr(state);
11544         left = def;
11545         switch((tok = peek(state))) {
11546         case TOK_EQ:
11547                 lvalue(state, left);
11548                 eat(state, TOK_EQ);
11549                 def = write_expr(state, left, 
11550                         read_expr(state, assignment_expr(state)));
11551                 break;
11552         case TOK_TIMESEQ:
11553         case TOK_DIVEQ:
11554         case TOK_MODEQ:
11555                 lvalue(state, left);
11556                 arithmetic(state, left);
11557                 eat(state, tok);
11558                 right = read_expr(state, assignment_expr(state));
11559                 arithmetic(state, right);
11560
11561                 sign = is_signed(left->type);
11562                 op = -1;
11563                 switch(tok) {
11564                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11565                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
11566                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
11567                 }
11568                 def = write_expr(state, left,
11569                         triple(state, op, left->type, 
11570                                 read_expr(state, left), right));
11571                 break;
11572         case TOK_PLUSEQ:
11573                 lvalue(state, left);
11574                 eat(state, TOK_PLUSEQ);
11575                 def = write_expr(state, left,
11576                         mk_add_expr(state, left, assignment_expr(state)));
11577                 break;
11578         case TOK_MINUSEQ:
11579                 lvalue(state, left);
11580                 eat(state, TOK_MINUSEQ);
11581                 def = write_expr(state, left,
11582                         mk_sub_expr(state, left, assignment_expr(state)));
11583                 break;
11584         case TOK_SLEQ:
11585         case TOK_SREQ:
11586         case TOK_ANDEQ:
11587         case TOK_XOREQ:
11588         case TOK_OREQ:
11589                 lvalue(state, left);
11590                 integral(state, left);
11591                 eat(state, tok);
11592                 right = read_expr(state, assignment_expr(state));
11593                 integral(state, right);
11594                 right = integral_promotion(state, right);
11595                 sign = is_signed(left->type);
11596                 op = -1;
11597                 switch(tok) {
11598                 case TOK_SLEQ:  op = OP_SL; break;
11599                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
11600                 case TOK_ANDEQ: op = OP_AND; break;
11601                 case TOK_XOREQ: op = OP_XOR; break;
11602                 case TOK_OREQ:  op = OP_OR; break;
11603                 }
11604                 def = write_expr(state, left,
11605                         triple(state, op, left->type, 
11606                                 read_expr(state, left), right));
11607                 break;
11608         }
11609         return def;
11610 }
11611
11612 static struct triple *expr(struct compile_state *state)
11613 {
11614         struct triple *def;
11615         def = assignment_expr(state);
11616         while(peek(state) == TOK_COMMA) {
11617                 eat(state, TOK_COMMA);
11618                 def = mkprog(state, def, assignment_expr(state), 0);
11619         }
11620         return def;
11621 }
11622
11623 static void expr_statement(struct compile_state *state, struct triple *first)
11624 {
11625         if (peek(state) != TOK_SEMI) {
11626                 /* lvalue conversions always apply except when certian operators
11627                  * are applied.  I apply the lvalue conversions here
11628                  * as I know no more operators will be applied.
11629                  */
11630                 flatten(state, first, lvalue_conversion(state, expr(state)));
11631         }
11632         eat(state, TOK_SEMI);
11633 }
11634
11635 static void if_statement(struct compile_state *state, struct triple *first)
11636 {
11637         struct triple *test, *jmp1, *jmp2, *middle, *end;
11638
11639         jmp1 = jmp2 = middle = 0;
11640         eat(state, TOK_IF);
11641         eat(state, TOK_LPAREN);
11642         test = expr(state);
11643         bool(state, test);
11644         /* Cleanup and invert the test */
11645         test = lfalse_expr(state, read_expr(state, test));
11646         eat(state, TOK_RPAREN);
11647         /* Generate the needed pieces */
11648         middle = label(state);
11649         jmp1 = branch(state, middle, test);
11650         /* Thread the pieces together */
11651         flatten(state, first, test);
11652         flatten(state, first, jmp1);
11653         flatten(state, first, label(state));
11654         statement(state, first);
11655         if (peek(state) == TOK_ELSE) {
11656                 eat(state, TOK_ELSE);
11657                 /* Generate the rest of the pieces */
11658                 end = label(state);
11659                 jmp2 = branch(state, end, 0);
11660                 /* Thread them together */
11661                 flatten(state, first, jmp2);
11662                 flatten(state, first, middle);
11663                 statement(state, first);
11664                 flatten(state, first, end);
11665         }
11666         else {
11667                 flatten(state, first, middle);
11668         }
11669 }
11670
11671 static void for_statement(struct compile_state *state, struct triple *first)
11672 {
11673         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11674         struct triple *label1, *label2, *label3;
11675         struct hash_entry *ident;
11676
11677         eat(state, TOK_FOR);
11678         eat(state, TOK_LPAREN);
11679         head = test = tail = jmp1 = jmp2 = 0;
11680         if (peek(state) != TOK_SEMI) {
11681                 head = expr(state);
11682         } 
11683         eat(state, TOK_SEMI);
11684         if (peek(state) != TOK_SEMI) {
11685                 test = expr(state);
11686                 bool(state, test);
11687                 test = ltrue_expr(state, read_expr(state, test));
11688         }
11689         eat(state, TOK_SEMI);
11690         if (peek(state) != TOK_RPAREN) {
11691                 tail = expr(state);
11692         }
11693         eat(state, TOK_RPAREN);
11694         /* Generate the needed pieces */
11695         label1 = label(state);
11696         label2 = label(state);
11697         label3 = label(state);
11698         if (test) {
11699                 jmp1 = branch(state, label3, 0);
11700                 jmp2 = branch(state, label1, test);
11701         }
11702         else {
11703                 jmp2 = branch(state, label1, 0);
11704         }
11705         end = label(state);
11706         /* Remember where break and continue go */
11707         start_scope(state);
11708         ident = state->i_break;
11709         symbol(state, ident, &ident->sym_ident, end, end->type);
11710         ident = state->i_continue;
11711         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11712         /* Now include the body */
11713         flatten(state, first, head);
11714         flatten(state, first, jmp1);
11715         flatten(state, first, label1);
11716         statement(state, first);
11717         flatten(state, first, label2);
11718         flatten(state, first, tail);
11719         flatten(state, first, label3);
11720         flatten(state, first, test);
11721         flatten(state, first, jmp2);
11722         flatten(state, first, end);
11723         /* Cleanup the break/continue scope */
11724         end_scope(state);
11725 }
11726
11727 static void while_statement(struct compile_state *state, struct triple *first)
11728 {
11729         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11730         struct hash_entry *ident;
11731         eat(state, TOK_WHILE);
11732         eat(state, TOK_LPAREN);
11733         test = expr(state);
11734         bool(state, test);
11735         test = ltrue_expr(state, read_expr(state, test));
11736         eat(state, TOK_RPAREN);
11737         /* Generate the needed pieces */
11738         label1 = label(state);
11739         label2 = label(state);
11740         jmp1 = branch(state, label2, 0);
11741         jmp2 = branch(state, label1, test);
11742         end = label(state);
11743         /* Remember where break and continue go */
11744         start_scope(state);
11745         ident = state->i_break;
11746         symbol(state, ident, &ident->sym_ident, end, end->type);
11747         ident = state->i_continue;
11748         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11749         /* Thread them together */
11750         flatten(state, first, jmp1);
11751         flatten(state, first, label1);
11752         statement(state, first);
11753         flatten(state, first, label2);
11754         flatten(state, first, test);
11755         flatten(state, first, jmp2);
11756         flatten(state, first, end);
11757         /* Cleanup the break/continue scope */
11758         end_scope(state);
11759 }
11760
11761 static void do_statement(struct compile_state *state, struct triple *first)
11762 {
11763         struct triple *label1, *label2, *test, *end;
11764         struct hash_entry *ident;
11765         eat(state, TOK_DO);
11766         /* Generate the needed pieces */
11767         label1 = label(state);
11768         label2 = label(state);
11769         end = label(state);
11770         /* Remember where break and continue go */
11771         start_scope(state);
11772         ident = state->i_break;
11773         symbol(state, ident, &ident->sym_ident, end, end->type);
11774         ident = state->i_continue;
11775         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11776         /* Now include the body */
11777         flatten(state, first, label1);
11778         statement(state, first);
11779         /* Cleanup the break/continue scope */
11780         end_scope(state);
11781         /* Eat the rest of the loop */
11782         eat(state, TOK_WHILE);
11783         eat(state, TOK_LPAREN);
11784         test = read_expr(state, expr(state));
11785         bool(state, test);
11786         eat(state, TOK_RPAREN);
11787         eat(state, TOK_SEMI);
11788         /* Thread the pieces together */
11789         test = ltrue_expr(state, test);
11790         flatten(state, first, label2);
11791         flatten(state, first, test);
11792         flatten(state, first, branch(state, label1, test));
11793         flatten(state, first, end);
11794 }
11795
11796
11797 static void return_statement(struct compile_state *state, struct triple *first)
11798 {
11799         struct triple *jmp, *mv, *dest, *var, *val;
11800         int last;
11801         eat(state, TOK_RETURN);
11802
11803 #warning "FIXME implement a more general excess branch elimination"
11804         val = 0;
11805         /* If we have a return value do some more work */
11806         if (peek(state) != TOK_SEMI) {
11807                 val = read_expr(state, expr(state));
11808         }
11809         eat(state, TOK_SEMI);
11810
11811         /* See if this last statement in a function */
11812         last = ((peek(state) == TOK_RBRACE) && 
11813                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11814
11815         /* Find the return variable */
11816         var = fresult(state, state->main_function);
11817
11818         /* Find the return destination */
11819         dest = state->i_return->sym_ident->def;
11820         mv = jmp = 0;
11821         /* If needed generate a jump instruction */
11822         if (!last) {
11823                 jmp = branch(state, dest, 0);
11824         }
11825         /* If needed generate an assignment instruction */
11826         if (val) {
11827                 mv = write_expr(state, deref_index(state, var, 1), val);
11828         }
11829         /* Now put the code together */
11830         if (mv) {
11831                 flatten(state, first, mv);
11832                 flatten(state, first, jmp);
11833         }
11834         else if (jmp) {
11835                 flatten(state, first, jmp);
11836         }
11837 }
11838
11839 static void break_statement(struct compile_state *state, struct triple *first)
11840 {
11841         struct triple *dest;
11842         eat(state, TOK_BREAK);
11843         eat(state, TOK_SEMI);
11844         if (!state->i_break->sym_ident) {
11845                 error(state, 0, "break statement not within loop or switch");
11846         }
11847         dest = state->i_break->sym_ident->def;
11848         flatten(state, first, branch(state, dest, 0));
11849 }
11850
11851 static void continue_statement(struct compile_state *state, struct triple *first)
11852 {
11853         struct triple *dest;
11854         eat(state, TOK_CONTINUE);
11855         eat(state, TOK_SEMI);
11856         if (!state->i_continue->sym_ident) {
11857                 error(state, 0, "continue statement outside of a loop");
11858         }
11859         dest = state->i_continue->sym_ident->def;
11860         flatten(state, first, branch(state, dest, 0));
11861 }
11862
11863 static void goto_statement(struct compile_state *state, struct triple *first)
11864 {
11865         struct hash_entry *ident;
11866         eat(state, TOK_GOTO);
11867         eat(state, TOK_IDENT);
11868         ident = state->token[0].ident;
11869         if (!ident->sym_label) {
11870                 /* If this is a forward branch allocate the label now,
11871                  * it will be flattend in the appropriate location later.
11872                  */
11873                 struct triple *ins;
11874                 ins = label(state);
11875                 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11876         }
11877         eat(state, TOK_SEMI);
11878
11879         flatten(state, first, branch(state, ident->sym_label->def, 0));
11880 }
11881
11882 static void labeled_statement(struct compile_state *state, struct triple *first)
11883 {
11884         struct triple *ins;
11885         struct hash_entry *ident;
11886         eat(state, TOK_IDENT);
11887
11888         ident = state->token[0].ident;
11889         if (ident->sym_label && ident->sym_label->def) {
11890                 ins = ident->sym_label->def;
11891                 put_occurance(ins->occurance);
11892                 ins->occurance = new_occurance(state);
11893         }
11894         else {
11895                 ins = label(state);
11896                 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11897         }
11898         if (ins->id & TRIPLE_FLAG_FLATTENED) {
11899                 error(state, 0, "label %s already defined", ident->name);
11900         }
11901         flatten(state, first, ins);
11902
11903         eat(state, TOK_COLON);
11904         statement(state, first);
11905 }
11906
11907 static void switch_statement(struct compile_state *state, struct triple *first)
11908 {
11909         struct triple *value, *top, *end, *dbranch;
11910         struct hash_entry *ident;
11911
11912         /* See if we have a valid switch statement */
11913         eat(state, TOK_SWITCH);
11914         eat(state, TOK_LPAREN);
11915         value = expr(state);
11916         integral(state, value);
11917         value = read_expr(state, value);
11918         eat(state, TOK_RPAREN);
11919         /* Generate the needed pieces */
11920         top = label(state);
11921         end = label(state);
11922         dbranch = branch(state, end, 0);
11923         /* Remember where case branches and break goes */
11924         start_scope(state);
11925         ident = state->i_switch;
11926         symbol(state, ident, &ident->sym_ident, value, value->type);
11927         ident = state->i_case;
11928         symbol(state, ident, &ident->sym_ident, top, top->type);
11929         ident = state->i_break;
11930         symbol(state, ident, &ident->sym_ident, end, end->type);
11931         ident = state->i_default;
11932         symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11933         /* Thread them together */
11934         flatten(state, first, value);
11935         flatten(state, first, top);
11936         flatten(state, first, dbranch);
11937         statement(state, first);
11938         flatten(state, first, end);
11939         /* Cleanup the switch scope */
11940         end_scope(state);
11941 }
11942
11943 static void case_statement(struct compile_state *state, struct triple *first)
11944 {
11945         struct triple *cvalue, *dest, *test, *jmp;
11946         struct triple *ptr, *value, *top, *dbranch;
11947
11948         /* See if w have a valid case statement */
11949         eat(state, TOK_CASE);
11950         cvalue = constant_expr(state);
11951         integral(state, cvalue);
11952         if (cvalue->op != OP_INTCONST) {
11953                 error(state, 0, "integer constant expected");
11954         }
11955         eat(state, TOK_COLON);
11956         if (!state->i_case->sym_ident) {
11957                 error(state, 0, "case statement not within a switch");
11958         }
11959
11960         /* Lookup the interesting pieces */
11961         top = state->i_case->sym_ident->def;
11962         value = state->i_switch->sym_ident->def;
11963         dbranch = state->i_default->sym_ident->def;
11964
11965         /* See if this case label has already been used */
11966         for(ptr = top; ptr != dbranch; ptr = ptr->next) {
11967                 if (ptr->op != OP_EQ) {
11968                         continue;
11969                 }
11970                 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
11971                         error(state, 0, "duplicate case %d statement",
11972                                 cvalue->u.cval);
11973                 }
11974         }
11975         /* Generate the needed pieces */
11976         dest = label(state);
11977         test = triple(state, OP_EQ, &int_type, value, cvalue);
11978         jmp = branch(state, dest, test);
11979         /* Thread the pieces together */
11980         flatten(state, dbranch, test);
11981         flatten(state, dbranch, jmp);
11982         flatten(state, dbranch, label(state));
11983         flatten(state, first, dest);
11984         statement(state, first);
11985 }
11986
11987 static void default_statement(struct compile_state *state, struct triple *first)
11988 {
11989         struct triple *dest;
11990         struct triple *dbranch, *end;
11991
11992         /* See if we have a valid default statement */
11993         eat(state, TOK_DEFAULT);
11994         eat(state, TOK_COLON);
11995
11996         if (!state->i_case->sym_ident) {
11997                 error(state, 0, "default statement not within a switch");
11998         }
11999
12000         /* Lookup the interesting pieces */
12001         dbranch = state->i_default->sym_ident->def;
12002         end = state->i_break->sym_ident->def;
12003
12004         /* See if a default statement has already happened */
12005         if (TARG(dbranch, 0) != end) {
12006                 error(state, 0, "duplicate default statement");
12007         }
12008
12009         /* Generate the needed pieces */
12010         dest = label(state);
12011
12012         /* Blame the branch on the default statement */
12013         put_occurance(dbranch->occurance);
12014         dbranch->occurance = new_occurance(state);
12015
12016         /* Thread the pieces together */
12017         TARG(dbranch, 0) = dest;
12018         use_triple(dest, dbranch);
12019         flatten(state, first, dest);
12020         statement(state, first);
12021 }
12022
12023 static void asm_statement(struct compile_state *state, struct triple *first)
12024 {
12025         struct asm_info *info;
12026         struct {
12027                 struct triple *constraint;
12028                 struct triple *expr;
12029         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12030         struct triple *def, *asm_str;
12031         int out, in, clobbers, more, colons, i;
12032         int flags;
12033
12034         flags = 0;
12035         eat(state, TOK_ASM);
12036         /* For now ignore the qualifiers */
12037         switch(peek(state)) {
12038         case TOK_CONST:
12039                 eat(state, TOK_CONST);
12040                 break;
12041         case TOK_VOLATILE:
12042                 eat(state, TOK_VOLATILE);
12043                 flags |= TRIPLE_FLAG_VOLATILE;
12044                 break;
12045         }
12046         eat(state, TOK_LPAREN);
12047         asm_str = string_constant(state);
12048
12049         colons = 0;
12050         out = in = clobbers = 0;
12051         /* Outputs */
12052         if ((colons == 0) && (peek(state) == TOK_COLON)) {
12053                 eat(state, TOK_COLON);
12054                 colons++;
12055                 more = (peek(state) == TOK_LIT_STRING);
12056                 while(more) {
12057                         struct triple *var;
12058                         struct triple *constraint;
12059                         char *str;
12060                         more = 0;
12061                         if (out > MAX_LHS) {
12062                                 error(state, 0, "Maximum output count exceeded.");
12063                         }
12064                         constraint = string_constant(state);
12065                         str = constraint->u.blob;
12066                         if (str[0] != '=') {
12067                                 error(state, 0, "Output constraint does not start with =");
12068                         }
12069                         constraint->u.blob = str + 1;
12070                         eat(state, TOK_LPAREN);
12071                         var = conditional_expr(state);
12072                         eat(state, TOK_RPAREN);
12073
12074                         lvalue(state, var);
12075                         out_param[out].constraint = constraint;
12076                         out_param[out].expr       = var;
12077                         if (peek(state) == TOK_COMMA) {
12078                                 eat(state, TOK_COMMA);
12079                                 more = 1;
12080                         }
12081                         out++;
12082                 }
12083         }
12084         /* Inputs */
12085         if ((colons == 1) && (peek(state) == TOK_COLON)) {
12086                 eat(state, TOK_COLON);
12087                 colons++;
12088                 more = (peek(state) == TOK_LIT_STRING);
12089                 while(more) {
12090                         struct triple *val;
12091                         struct triple *constraint;
12092                         char *str;
12093                         more = 0;
12094                         if (in > MAX_RHS) {
12095                                 error(state, 0, "Maximum input count exceeded.");
12096                         }
12097                         constraint = string_constant(state);
12098                         str = constraint->u.blob;
12099                         if (digitp(str[0] && str[1] == '\0')) {
12100                                 int val;
12101                                 val = digval(str[0]);
12102                                 if ((val < 0) || (val >= out)) {
12103                                         error(state, 0, "Invalid input constraint %d", val);
12104                                 }
12105                         }
12106                         eat(state, TOK_LPAREN);
12107                         val = conditional_expr(state);
12108                         eat(state, TOK_RPAREN);
12109
12110                         in_param[in].constraint = constraint;
12111                         in_param[in].expr       = val;
12112                         if (peek(state) == TOK_COMMA) {
12113                                 eat(state, TOK_COMMA);
12114                                 more = 1;
12115                         }
12116                         in++;
12117                 }
12118         }
12119
12120         /* Clobber */
12121         if ((colons == 2) && (peek(state) == TOK_COLON)) {
12122                 eat(state, TOK_COLON);
12123                 colons++;
12124                 more = (peek(state) == TOK_LIT_STRING);
12125                 while(more) {
12126                         struct triple *clobber;
12127                         more = 0;
12128                         if ((clobbers + out) > MAX_LHS) {
12129                                 error(state, 0, "Maximum clobber limit exceeded.");
12130                         }
12131                         clobber = string_constant(state);
12132
12133                         clob_param[clobbers].constraint = clobber;
12134                         if (peek(state) == TOK_COMMA) {
12135                                 eat(state, TOK_COMMA);
12136                                 more = 1;
12137                         }
12138                         clobbers++;
12139                 }
12140         }
12141         eat(state, TOK_RPAREN);
12142         eat(state, TOK_SEMI);
12143
12144
12145         info = xcmalloc(sizeof(*info), "asm_info");
12146         info->str = asm_str->u.blob;
12147         free_triple(state, asm_str);
12148
12149         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12150         def->u.ainfo = info;
12151         def->id |= flags;
12152
12153         /* Find the register constraints */
12154         for(i = 0; i < out; i++) {
12155                 struct triple *constraint;
12156                 constraint = out_param[i].constraint;
12157                 info->tmpl.lhs[i] = arch_reg_constraint(state, 
12158                         out_param[i].expr->type, constraint->u.blob);
12159                 free_triple(state, constraint);
12160         }
12161         for(; i - out < clobbers; i++) {
12162                 struct triple *constraint;
12163                 constraint = clob_param[i - out].constraint;
12164                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12165                 free_triple(state, constraint);
12166         }
12167         for(i = 0; i < in; i++) {
12168                 struct triple *constraint;
12169                 const char *str;
12170                 constraint = in_param[i].constraint;
12171                 str = constraint->u.blob;
12172                 if (digitp(str[0]) && str[1] == '\0') {
12173                         struct reg_info cinfo;
12174                         int val;
12175                         val = digval(str[0]);
12176                         cinfo.reg = info->tmpl.lhs[val].reg;
12177                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12178                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
12179                         if (cinfo.reg == REG_UNSET) {
12180                                 cinfo.reg = REG_VIRT0 + val;
12181                         }
12182                         if (cinfo.regcm == 0) {
12183                                 error(state, 0, "No registers for %d", val);
12184                         }
12185                         info->tmpl.lhs[val] = cinfo;
12186                         info->tmpl.rhs[i]   = cinfo;
12187                                 
12188                 } else {
12189                         info->tmpl.rhs[i] = arch_reg_constraint(state, 
12190                                 in_param[i].expr->type, str);
12191                 }
12192                 free_triple(state, constraint);
12193         }
12194
12195         /* Now build the helper expressions */
12196         for(i = 0; i < in; i++) {
12197                 RHS(def, i) = read_expr(state, in_param[i].expr);
12198         }
12199         flatten(state, first, def);
12200         for(i = 0; i < (out + clobbers); i++) {
12201                 struct type *type;
12202                 struct triple *piece;
12203                 if (i < out) {
12204                         type = out_param[i].expr->type;
12205                 } else {
12206                         size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12207                         if (size >= SIZEOF_LONG) {
12208                                 type = &ulong_type;
12209                         } 
12210                         else if (size >= SIZEOF_INT) {
12211                                 type = &uint_type;
12212                         }
12213                         else if (size >= SIZEOF_SHORT) {
12214                                 type = &ushort_type;
12215                         }
12216                         else {
12217                                 type = &uchar_type;
12218                         }
12219                 }
12220                 piece = triple(state, OP_PIECE, type, def, 0);
12221                 piece->u.cval = i;
12222                 LHS(def, i) = piece;
12223                 flatten(state, first, piece);
12224         }
12225         /* And write the helpers to their destinations */
12226         for(i = 0; i < out; i++) {
12227                 struct triple *piece;
12228                 piece = LHS(def, i);
12229                 flatten(state, first,
12230                         write_expr(state, out_param[i].expr, piece));
12231         }
12232 }
12233
12234
12235 static int isdecl(int tok)
12236 {
12237         switch(tok) {
12238         case TOK_AUTO:
12239         case TOK_REGISTER:
12240         case TOK_STATIC:
12241         case TOK_EXTERN:
12242         case TOK_TYPEDEF:
12243         case TOK_CONST:
12244         case TOK_RESTRICT:
12245         case TOK_VOLATILE:
12246         case TOK_VOID:
12247         case TOK_CHAR:
12248         case TOK_SHORT:
12249         case TOK_INT:
12250         case TOK_LONG:
12251         case TOK_FLOAT:
12252         case TOK_DOUBLE:
12253         case TOK_SIGNED:
12254         case TOK_UNSIGNED:
12255         case TOK_STRUCT:
12256         case TOK_UNION:
12257         case TOK_ENUM:
12258         case TOK_TYPE_NAME: /* typedef name */
12259                 return 1;
12260         default:
12261                 return 0;
12262         }
12263 }
12264
12265 static void compound_statement(struct compile_state *state, struct triple *first)
12266 {
12267         eat(state, TOK_LBRACE);
12268         start_scope(state);
12269
12270         /* statement-list opt */
12271         while (peek(state) != TOK_RBRACE) {
12272                 statement(state, first);
12273         }
12274         end_scope(state);
12275         eat(state, TOK_RBRACE);
12276 }
12277
12278 static void statement(struct compile_state *state, struct triple *first)
12279 {
12280         int tok;
12281         tok = peek(state);
12282         if (tok == TOK_LBRACE) {
12283                 compound_statement(state, first);
12284         }
12285         else if (tok == TOK_IF) {
12286                 if_statement(state, first); 
12287         }
12288         else if (tok == TOK_FOR) {
12289                 for_statement(state, first);
12290         }
12291         else if (tok == TOK_WHILE) {
12292                 while_statement(state, first);
12293         }
12294         else if (tok == TOK_DO) {
12295                 do_statement(state, first);
12296         }
12297         else if (tok == TOK_RETURN) {
12298                 return_statement(state, first);
12299         }
12300         else if (tok == TOK_BREAK) {
12301                 break_statement(state, first);
12302         }
12303         else if (tok == TOK_CONTINUE) {
12304                 continue_statement(state, first);
12305         }
12306         else if (tok == TOK_GOTO) {
12307                 goto_statement(state, first);
12308         }
12309         else if (tok == TOK_SWITCH) {
12310                 switch_statement(state, first);
12311         }
12312         else if (tok == TOK_ASM) {
12313                 asm_statement(state, first);
12314         }
12315         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12316                 labeled_statement(state, first); 
12317         }
12318         else if (tok == TOK_CASE) {
12319                 case_statement(state, first);
12320         }
12321         else if (tok == TOK_DEFAULT) {
12322                 default_statement(state, first);
12323         }
12324         else if (isdecl(tok)) {
12325                 /* This handles C99 intermixing of statements and decls */
12326                 decl(state, first);
12327         }
12328         else {
12329                 expr_statement(state, first);
12330         }
12331 }
12332
12333 static struct type *param_decl(struct compile_state *state)
12334 {
12335         struct type *type;
12336         struct hash_entry *ident;
12337         /* Cheat so the declarator will know we are not global */
12338         start_scope(state); 
12339         ident = 0;
12340         type = decl_specifiers(state);
12341         type = declarator(state, type, &ident, 0);
12342         type->field_ident = ident;
12343         end_scope(state);
12344         return type;
12345 }
12346
12347 static struct type *param_type_list(struct compile_state *state, struct type *type)
12348 {
12349         struct type *ftype, **next;
12350         ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12351         next = &ftype->right;
12352         ftype->elements = 1;
12353         while(peek(state) == TOK_COMMA) {
12354                 eat(state, TOK_COMMA);
12355                 if (peek(state) == TOK_DOTS) {
12356                         eat(state, TOK_DOTS);
12357                         error(state, 0, "variadic functions not supported");
12358                 }
12359                 else {
12360                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12361                         next = &((*next)->right);
12362                         ftype->elements++;
12363                 }
12364         }
12365         return ftype;
12366 }
12367
12368 static struct type *type_name(struct compile_state *state)
12369 {
12370         struct type *type;
12371         type = specifier_qualifier_list(state);
12372         /* abstract-declarator (may consume no tokens) */
12373         type = declarator(state, type, 0, 0);
12374         return type;
12375 }
12376
12377 static struct type *direct_declarator(
12378         struct compile_state *state, struct type *type, 
12379         struct hash_entry **ident, int need_ident)
12380 {
12381         struct type *outer;
12382         int op;
12383         outer = 0;
12384         arrays_complete(state, type);
12385         switch(peek(state)) {
12386         case TOK_IDENT:
12387                 eat(state, TOK_IDENT);
12388                 if (!ident) {
12389                         error(state, 0, "Unexpected identifier found");
12390                 }
12391                 /* The name of what we are declaring */
12392                 *ident = state->token[0].ident;
12393                 break;
12394         case TOK_LPAREN:
12395                 eat(state, TOK_LPAREN);
12396                 outer = declarator(state, type, ident, need_ident);
12397                 eat(state, TOK_RPAREN);
12398                 break;
12399         default:
12400                 if (need_ident) {
12401                         error(state, 0, "Identifier expected");
12402                 }
12403                 break;
12404         }
12405         do {
12406                 op = 1;
12407                 arrays_complete(state, type);
12408                 switch(peek(state)) {
12409                 case TOK_LPAREN:
12410                         eat(state, TOK_LPAREN);
12411                         type = param_type_list(state, type);
12412                         eat(state, TOK_RPAREN);
12413                         break;
12414                 case TOK_LBRACKET:
12415                 {
12416                         unsigned int qualifiers;
12417                         struct triple *value;
12418                         value = 0;
12419                         eat(state, TOK_LBRACKET);
12420                         if (peek(state) != TOK_RBRACKET) {
12421                                 value = constant_expr(state);
12422                                 integral(state, value);
12423                         }
12424                         eat(state, TOK_RBRACKET);
12425
12426                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12427                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12428                         if (value) {
12429                                 type->elements = value->u.cval;
12430                                 free_triple(state, value);
12431                         } else {
12432                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12433                                 op = 0;
12434                         }
12435                 }
12436                         break;
12437                 default:
12438                         op = 0;
12439                         break;
12440                 }
12441         } while(op);
12442         if (outer) {
12443                 struct type *inner;
12444                 arrays_complete(state, type);
12445                 FINISHME();
12446                 for(inner = outer; inner->left; inner = inner->left)
12447                         ;
12448                 inner->left = type;
12449                 type = outer;
12450         }
12451         return type;
12452 }
12453
12454 static struct type *declarator(
12455         struct compile_state *state, struct type *type, 
12456         struct hash_entry **ident, int need_ident)
12457 {
12458         while(peek(state) == TOK_STAR) {
12459                 eat(state, TOK_STAR);
12460                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12461         }
12462         type = direct_declarator(state, type, ident, need_ident);
12463         return type;
12464 }
12465
12466 static struct type *typedef_name(
12467         struct compile_state *state, unsigned int specifiers)
12468 {
12469         struct hash_entry *ident;
12470         struct type *type;
12471         eat(state, TOK_TYPE_NAME);
12472         ident = state->token[0].ident;
12473         type = ident->sym_ident->type;
12474         specifiers |= type->type & QUAL_MASK;
12475         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
12476                 (type->type & (STOR_MASK | QUAL_MASK))) {
12477                 type = clone_type(specifiers, type);
12478         }
12479         return type;
12480 }
12481
12482 static struct type *enum_specifier(
12483         struct compile_state *state, unsigned int spec)
12484 {
12485         struct hash_entry *ident;
12486         ulong_t base;
12487         int tok;
12488         struct type *enum_type;
12489         enum_type = 0;
12490         ident = 0;
12491         eat(state, TOK_ENUM);
12492         tok = peek(state);
12493         if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12494                 eat(state, tok);
12495                 ident = state->token[0].ident;
12496                 
12497         }
12498         base = 0;
12499         if (!ident || (peek(state) == TOK_LBRACE)) {
12500                 struct type **next;
12501                 eat(state, TOK_LBRACE);
12502                 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12503                 enum_type->type_ident = ident;
12504                 next = &enum_type->right;
12505                 do {
12506                         struct hash_entry *eident;
12507                         struct triple *value;
12508                         struct type *entry;
12509                         eat(state, TOK_IDENT);
12510                         eident = state->token[0].ident;
12511                         if (eident->sym_ident) {
12512                                 error(state, 0, "%s already declared", 
12513                                         eident->name);
12514                         }
12515                         eident->tok = TOK_ENUM_CONST;
12516                         if (peek(state) == TOK_EQ) {
12517                                 struct triple *val;
12518                                 eat(state, TOK_EQ);
12519                                 val = constant_expr(state);
12520                                 integral(state, val);
12521                                 base = val->u.cval;
12522                         }
12523                         value = int_const(state, &int_type, base);
12524                         symbol(state, eident, &eident->sym_ident, value, &int_type);
12525                         entry = new_type(TYPE_LIST, 0, 0);
12526                         entry->field_ident = eident;
12527                         *next = entry;
12528                         next = &entry->right;
12529                         base += 1;
12530                         if (peek(state) == TOK_COMMA) {
12531                                 eat(state, TOK_COMMA);
12532                         }
12533                 } while(peek(state) != TOK_RBRACE);
12534                 eat(state, TOK_RBRACE);
12535                 if (ident) {
12536                         symbol(state, ident, &ident->sym_tag, 0, enum_type);
12537                 }
12538         }
12539         if (ident && ident->sym_tag &&
12540                 ident->sym_tag->type &&
12541                 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12542                 enum_type = clone_type(spec, ident->sym_tag->type);
12543         }
12544         else if (ident && !enum_type) {
12545                 error(state, 0, "enum %s undeclared", ident->name);
12546         }
12547         return enum_type;
12548 }
12549
12550 static struct type *struct_declarator(
12551         struct compile_state *state, struct type *type, struct hash_entry **ident)
12552 {
12553         if (peek(state) != TOK_COLON) {
12554                 type = declarator(state, type, ident, 1);
12555         }
12556         if (peek(state) == TOK_COLON) {
12557                 struct triple *value;
12558                 eat(state, TOK_COLON);
12559                 value = constant_expr(state);
12560                 if (value->op != OP_INTCONST) {
12561                         error(state, 0, "Invalid constant expression");
12562                 }
12563                 if (value->u.cval > size_of(state, type)) {
12564                         error(state, 0, "bitfield larger than base type");
12565                 }
12566                 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12567                         error(state, 0, "bitfield base not an integer type");
12568                 }
12569                 type = new_type(TYPE_BITFIELD, type, 0);
12570                 type->elements = value->u.cval;
12571         }
12572         return type;
12573 }
12574
12575 static struct type *struct_or_union_specifier(
12576         struct compile_state *state, unsigned int spec)
12577 {
12578         struct type *struct_type;
12579         struct hash_entry *ident;
12580         unsigned int type_main;
12581         unsigned int type_join;
12582         int tok;
12583         struct_type = 0;
12584         ident = 0;
12585         switch(peek(state)) {
12586         case TOK_STRUCT:
12587                 eat(state, TOK_STRUCT);
12588                 type_main = TYPE_STRUCT;
12589                 type_join = TYPE_PRODUCT;
12590                 break;
12591         case TOK_UNION:
12592                 eat(state, TOK_UNION);
12593                 type_main = TYPE_UNION;
12594                 type_join = TYPE_OVERLAP;
12595                 break;
12596         default:
12597                 eat(state, TOK_STRUCT);
12598                 type_main = TYPE_STRUCT;
12599                 type_join = TYPE_PRODUCT;
12600                 break;
12601         }
12602         tok = peek(state);
12603         if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12604                 eat(state, tok);
12605                 ident = state->token[0].ident;
12606         }
12607         if (!ident || (peek(state) == TOK_LBRACE)) {
12608                 ulong_t elements;
12609                 struct type **next;
12610                 elements = 0;
12611                 eat(state, TOK_LBRACE);
12612                 next = &struct_type;
12613                 do {
12614                         struct type *base_type;
12615                         int done;
12616                         base_type = specifier_qualifier_list(state);
12617                         do {
12618                                 struct type *type;
12619                                 struct hash_entry *fident;
12620                                 done = 1;
12621                                 type = struct_declarator(state, base_type, &fident);
12622                                 elements++;
12623                                 if (peek(state) == TOK_COMMA) {
12624                                         done = 0;
12625                                         eat(state, TOK_COMMA);
12626                                 }
12627                                 type = clone_type(0, type);
12628                                 type->field_ident = fident;
12629                                 if (*next) {
12630                                         *next = new_type(type_join, *next, type);
12631                                         next = &((*next)->right);
12632                                 } else {
12633                                         *next = type;
12634                                 }
12635                         } while(!done);
12636                         eat(state, TOK_SEMI);
12637                 } while(peek(state) != TOK_RBRACE);
12638                 eat(state, TOK_RBRACE);
12639                 struct_type = new_type(type_main | spec, struct_type, 0);
12640                 struct_type->type_ident = ident;
12641                 struct_type->elements = elements;
12642                 if (ident) {
12643                         symbol(state, ident, &ident->sym_tag, 0, struct_type);
12644                 }
12645         }
12646         if (ident && ident->sym_tag && 
12647                 ident->sym_tag->type && 
12648                 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12649                 struct_type = clone_type(spec, ident->sym_tag->type);
12650         }
12651         else if (ident && !struct_type) {
12652                 error(state, 0, "%s %s undeclared", 
12653                         (type_main == TYPE_STRUCT)?"struct" : "union",
12654                         ident->name);
12655         }
12656         return struct_type;
12657 }
12658
12659 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12660 {
12661         unsigned int specifiers;
12662         switch(peek(state)) {
12663         case TOK_AUTO:
12664                 eat(state, TOK_AUTO);
12665                 specifiers = STOR_AUTO;
12666                 break;
12667         case TOK_REGISTER:
12668                 eat(state, TOK_REGISTER);
12669                 specifiers = STOR_REGISTER;
12670                 break;
12671         case TOK_STATIC:
12672                 eat(state, TOK_STATIC);
12673                 specifiers = STOR_STATIC;
12674                 break;
12675         case TOK_EXTERN:
12676                 eat(state, TOK_EXTERN);
12677                 specifiers = STOR_EXTERN;
12678                 break;
12679         case TOK_TYPEDEF:
12680                 eat(state, TOK_TYPEDEF);
12681                 specifiers = STOR_TYPEDEF;
12682                 break;
12683         default:
12684                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12685                         specifiers = STOR_LOCAL;
12686                 }
12687                 else {
12688                         specifiers = STOR_AUTO;
12689                 }
12690         }
12691         return specifiers;
12692 }
12693
12694 static unsigned int function_specifier_opt(struct compile_state *state)
12695 {
12696         /* Ignore the inline keyword */
12697         unsigned int specifiers;
12698         specifiers = 0;
12699         switch(peek(state)) {
12700         case TOK_INLINE:
12701                 eat(state, TOK_INLINE);
12702                 specifiers = STOR_INLINE;
12703         }
12704         return specifiers;
12705 }
12706
12707 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12708 {
12709         int tok = peek(state);
12710         switch(tok) {
12711         case TOK_COMMA:
12712         case TOK_LPAREN:
12713                 /* The empty attribute ignore it */
12714                 break;
12715         case TOK_IDENT:
12716         case TOK_ENUM_CONST:
12717         case TOK_TYPE_NAME:
12718         {
12719                 struct hash_entry *ident;
12720                 eat(state, TOK_IDENT);
12721                 ident = state->token[0].ident;
12722
12723                 if (ident == state->i_noinline) {
12724                         if (attributes & ATTRIB_ALWAYS_INLINE) {
12725                                 error(state, 0, "both always_inline and noinline attribtes");
12726                         }
12727                         attributes |= ATTRIB_NOINLINE;
12728                 }
12729                 else if (ident == state->i_always_inline) {
12730                         if (attributes & ATTRIB_NOINLINE) {
12731                                 error(state, 0, "both noinline and always_inline attribtes");
12732                         }
12733                         attributes |= ATTRIB_ALWAYS_INLINE;
12734                 }
12735                 else {
12736                         error(state, 0, "Unknown attribute:%s", ident->name);
12737                 }
12738                 break;
12739         }
12740         default:
12741                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12742                 break;
12743         }
12744         return attributes;
12745 }
12746
12747 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12748 {
12749         type = attrib(state, type);
12750         while(peek(state) == TOK_COMMA) {
12751                 eat(state, TOK_COMMA);
12752                 type = attrib(state, type);
12753         }
12754         return type;
12755 }
12756
12757 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12758 {
12759         if (peek(state) == TOK_ATTRIBUTE) {
12760                 eat(state, TOK_ATTRIBUTE);
12761                 eat(state, TOK_LPAREN);
12762                 eat(state, TOK_LPAREN);
12763                 type = attribute_list(state, type);
12764                 eat(state, TOK_RPAREN);
12765                 eat(state, TOK_RPAREN);
12766         }
12767         return type;
12768 }
12769
12770 static unsigned int type_qualifiers(struct compile_state *state)
12771 {
12772         unsigned int specifiers;
12773         int done;
12774         done = 0;
12775         specifiers = QUAL_NONE;
12776         do {
12777                 switch(peek(state)) {
12778                 case TOK_CONST:
12779                         eat(state, TOK_CONST);
12780                         specifiers |= QUAL_CONST;
12781                         break;
12782                 case TOK_VOLATILE:
12783                         eat(state, TOK_VOLATILE);
12784                         specifiers |= QUAL_VOLATILE;
12785                         break;
12786                 case TOK_RESTRICT:
12787                         eat(state, TOK_RESTRICT);
12788                         specifiers |= QUAL_RESTRICT;
12789                         break;
12790                 default:
12791                         done = 1;
12792                         break;
12793                 }
12794         } while(!done);
12795         return specifiers;
12796 }
12797
12798 static struct type *type_specifier(
12799         struct compile_state *state, unsigned int spec)
12800 {
12801         struct type *type;
12802         type = 0;
12803         switch(peek(state)) {
12804         case TOK_VOID:
12805                 eat(state, TOK_VOID);
12806                 type = new_type(TYPE_VOID | spec, 0, 0);
12807                 break;
12808         case TOK_CHAR:
12809                 eat(state, TOK_CHAR);
12810                 type = new_type(TYPE_CHAR | spec, 0, 0);
12811                 break;
12812         case TOK_SHORT:
12813                 eat(state, TOK_SHORT);
12814                 if (peek(state) == TOK_INT) {
12815                         eat(state, TOK_INT);
12816                 }
12817                 type = new_type(TYPE_SHORT | spec, 0, 0);
12818                 break;
12819         case TOK_INT:
12820                 eat(state, TOK_INT);
12821                 type = new_type(TYPE_INT | spec, 0, 0);
12822                 break;
12823         case TOK_LONG:
12824                 eat(state, TOK_LONG);
12825                 switch(peek(state)) {
12826                 case TOK_LONG:
12827                         eat(state, TOK_LONG);
12828                         error(state, 0, "long long not supported");
12829                         break;
12830                 case TOK_DOUBLE:
12831                         eat(state, TOK_DOUBLE);
12832                         error(state, 0, "long double not supported");
12833                         break;
12834                 case TOK_INT:
12835                         eat(state, TOK_INT);
12836                         type = new_type(TYPE_LONG | spec, 0, 0);
12837                         break;
12838                 default:
12839                         type = new_type(TYPE_LONG | spec, 0, 0);
12840                         break;
12841                 }
12842                 break;
12843         case TOK_FLOAT:
12844                 eat(state, TOK_FLOAT);
12845                 error(state, 0, "type float not supported");
12846                 break;
12847         case TOK_DOUBLE:
12848                 eat(state, TOK_DOUBLE);
12849                 error(state, 0, "type double not supported");
12850                 break;
12851         case TOK_SIGNED:
12852                 eat(state, TOK_SIGNED);
12853                 switch(peek(state)) {
12854                 case TOK_LONG:
12855                         eat(state, TOK_LONG);
12856                         switch(peek(state)) {
12857                         case TOK_LONG:
12858                                 eat(state, TOK_LONG);
12859                                 error(state, 0, "type long long not supported");
12860                                 break;
12861                         case TOK_INT:
12862                                 eat(state, TOK_INT);
12863                                 type = new_type(TYPE_LONG | spec, 0, 0);
12864                                 break;
12865                         default:
12866                                 type = new_type(TYPE_LONG | spec, 0, 0);
12867                                 break;
12868                         }
12869                         break;
12870                 case TOK_INT:
12871                         eat(state, TOK_INT);
12872                         type = new_type(TYPE_INT | spec, 0, 0);
12873                         break;
12874                 case TOK_SHORT:
12875                         eat(state, TOK_SHORT);
12876                         type = new_type(TYPE_SHORT | spec, 0, 0);
12877                         break;
12878                 case TOK_CHAR:
12879                         eat(state, TOK_CHAR);
12880                         type = new_type(TYPE_CHAR | spec, 0, 0);
12881                         break;
12882                 default:
12883                         type = new_type(TYPE_INT | spec, 0, 0);
12884                         break;
12885                 }
12886                 break;
12887         case TOK_UNSIGNED:
12888                 eat(state, TOK_UNSIGNED);
12889                 switch(peek(state)) {
12890                 case TOK_LONG:
12891                         eat(state, TOK_LONG);
12892                         switch(peek(state)) {
12893                         case TOK_LONG:
12894                                 eat(state, TOK_LONG);
12895                                 error(state, 0, "unsigned long long not supported");
12896                                 break;
12897                         case TOK_INT:
12898                                 eat(state, TOK_INT);
12899                                 type = new_type(TYPE_ULONG | spec, 0, 0);
12900                                 break;
12901                         default:
12902                                 type = new_type(TYPE_ULONG | spec, 0, 0);
12903                                 break;
12904                         }
12905                         break;
12906                 case TOK_INT:
12907                         eat(state, TOK_INT);
12908                         type = new_type(TYPE_UINT | spec, 0, 0);
12909                         break;
12910                 case TOK_SHORT:
12911                         eat(state, TOK_SHORT);
12912                         type = new_type(TYPE_USHORT | spec, 0, 0);
12913                         break;
12914                 case TOK_CHAR:
12915                         eat(state, TOK_CHAR);
12916                         type = new_type(TYPE_UCHAR | spec, 0, 0);
12917                         break;
12918                 default:
12919                         type = new_type(TYPE_UINT | spec, 0, 0);
12920                         break;
12921                 }
12922                 break;
12923                 /* struct or union specifier */
12924         case TOK_STRUCT:
12925         case TOK_UNION:
12926                 type = struct_or_union_specifier(state, spec);
12927                 break;
12928                 /* enum-spefifier */
12929         case TOK_ENUM:
12930                 type = enum_specifier(state, spec);
12931                 break;
12932                 /* typedef name */
12933         case TOK_TYPE_NAME:
12934                 type = typedef_name(state, spec);
12935                 break;
12936         default:
12937                 error(state, 0, "bad type specifier %s", 
12938                         tokens[peek(state)]);
12939                 break;
12940         }
12941         return type;
12942 }
12943
12944 static int istype(int tok)
12945 {
12946         switch(tok) {
12947         case TOK_CONST:
12948         case TOK_RESTRICT:
12949         case TOK_VOLATILE:
12950         case TOK_VOID:
12951         case TOK_CHAR:
12952         case TOK_SHORT:
12953         case TOK_INT:
12954         case TOK_LONG:
12955         case TOK_FLOAT:
12956         case TOK_DOUBLE:
12957         case TOK_SIGNED:
12958         case TOK_UNSIGNED:
12959         case TOK_STRUCT:
12960         case TOK_UNION:
12961         case TOK_ENUM:
12962         case TOK_TYPE_NAME:
12963                 return 1;
12964         default:
12965                 return 0;
12966         }
12967 }
12968
12969
12970 static struct type *specifier_qualifier_list(struct compile_state *state)
12971 {
12972         struct type *type;
12973         unsigned int specifiers = 0;
12974
12975         /* type qualifiers */
12976         specifiers |= type_qualifiers(state);
12977
12978         /* type specifier */
12979         type = type_specifier(state, specifiers);
12980
12981         return type;
12982 }
12983
12984 static int isdecl_specifier(int tok)
12985 {
12986         switch(tok) {
12987                 /* storage class specifier */
12988         case TOK_AUTO:
12989         case TOK_REGISTER:
12990         case TOK_STATIC:
12991         case TOK_EXTERN:
12992         case TOK_TYPEDEF:
12993                 /* type qualifier */
12994         case TOK_CONST:
12995         case TOK_RESTRICT:
12996         case TOK_VOLATILE:
12997                 /* type specifiers */
12998         case TOK_VOID:
12999         case TOK_CHAR:
13000         case TOK_SHORT:
13001         case TOK_INT:
13002         case TOK_LONG:
13003         case TOK_FLOAT:
13004         case TOK_DOUBLE:
13005         case TOK_SIGNED:
13006         case TOK_UNSIGNED:
13007                 /* struct or union specifier */
13008         case TOK_STRUCT:
13009         case TOK_UNION:
13010                 /* enum-spefifier */
13011         case TOK_ENUM:
13012                 /* typedef name */
13013         case TOK_TYPE_NAME:
13014                 /* function specifiers */
13015         case TOK_INLINE:
13016                 return 1;
13017         default:
13018                 return 0;
13019         }
13020 }
13021
13022 static struct type *decl_specifiers(struct compile_state *state)
13023 {
13024         struct type *type;
13025         unsigned int specifiers;
13026         /* I am overly restrictive in the arragement of specifiers supported.
13027          * C is overly flexible in this department it makes interpreting
13028          * the parse tree difficult.
13029          */
13030         specifiers = 0;
13031
13032         /* storage class specifier */
13033         specifiers |= storage_class_specifier_opt(state);
13034
13035         /* function-specifier */
13036         specifiers |= function_specifier_opt(state);
13037
13038         /* attributes */
13039         specifiers |= attributes_opt(state, 0);
13040
13041         /* type qualifier */
13042         specifiers |= type_qualifiers(state);
13043
13044         /* type specifier */
13045         type = type_specifier(state, specifiers);
13046         return type;
13047 }
13048
13049 struct field_info {
13050         struct type *type;
13051         size_t offset;
13052 };
13053
13054 static struct field_info designator(struct compile_state *state, struct type *type)
13055 {
13056         int tok;
13057         struct field_info info;
13058         info.offset = ~0U;
13059         info.type = 0;
13060         do {
13061                 switch(peek(state)) {
13062                 case TOK_LBRACKET:
13063                 {
13064                         struct triple *value;
13065                         if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13066                                 error(state, 0, "Array designator not in array initializer");
13067                         }
13068                         eat(state, TOK_LBRACKET);
13069                         value = constant_expr(state);
13070                         eat(state, TOK_RBRACKET);
13071
13072                         info.type = type->left;
13073                         info.offset = value->u.cval * size_of(state, info.type);
13074                         break;
13075                 }
13076                 case TOK_DOT:
13077                 {
13078                         struct hash_entry *field;
13079                         if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13080                                 ((type->type & TYPE_MASK) != TYPE_UNION))
13081                         {
13082                                 error(state, 0, "Struct designator not in struct initializer");
13083                         }
13084                         eat(state, TOK_DOT);
13085                         eat(state, TOK_IDENT);
13086                         field = state->token[0].ident;
13087                         info.offset = field_offset(state, type, field);
13088                         info.type   = field_type(state, type, field);
13089                         break;
13090                 }
13091                 default:
13092                         error(state, 0, "Invalid designator");
13093                 }
13094                 tok = peek(state);
13095         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13096         eat(state, TOK_EQ);
13097         return info;
13098 }
13099
13100 static struct triple *initializer(
13101         struct compile_state *state, struct type *type)
13102 {
13103         struct triple *result;
13104 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13105         if (peek(state) != TOK_LBRACE) {
13106                 result = assignment_expr(state);
13107                 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13108                         (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13109                         ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13110                         (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13111                         (equiv_types(type->left, result->type->left))) {
13112                         type->elements = result->type->elements;
13113                 }
13114                 if (is_lvalue(state, result) && 
13115                         ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13116                         (type->type & TYPE_MASK) != TYPE_ARRAY)
13117                 {
13118                         result = lvalue_conversion(state, result);
13119                 }
13120                 if (!is_init_compatible(state, type, result->type)) {
13121                         error(state, 0, "Incompatible types in initializer");
13122                 }
13123                 if (!equiv_types(type, result->type)) {
13124                         result = mk_cast_expr(state, type, result);
13125                 }
13126         }
13127         else {
13128                 int comma;
13129                 size_t max_offset;
13130                 struct field_info info;
13131                 void *buf;
13132                 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13133                         ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13134                         internal_error(state, 0, "unknown initializer type");
13135                 }
13136                 info.offset = 0;
13137                 info.type = type->left;
13138                 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13139                         info.type = next_field(state, type, 0);
13140                 }
13141                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13142                         max_offset = 0;
13143                 } else {
13144                         max_offset = size_of(state, type);
13145                 }
13146                 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13147                 eat(state, TOK_LBRACE);
13148                 do {
13149                         struct triple *value;
13150                         struct type *value_type;
13151                         size_t value_size;
13152                         void *dest;
13153                         int tok;
13154                         comma = 0;
13155                         tok = peek(state);
13156                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13157                                 info = designator(state, type);
13158                         }
13159                         if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13160                                 (info.offset >= max_offset)) {
13161                                 error(state, 0, "element beyond bounds");
13162                         }
13163                         value_type = info.type;
13164                         value = eval_const_expr(state, initializer(state, value_type));
13165                         value_size = size_of(state, value_type);
13166                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13167                                 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13168                                 (max_offset <= info.offset)) {
13169                                 void *old_buf;
13170                                 size_t old_size;
13171                                 old_buf = buf;
13172                                 old_size = max_offset;
13173                                 max_offset = info.offset + value_size;
13174                                 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13175                                 memcpy(buf, old_buf, bits_to_bytes(old_size));
13176                                 xfree(old_buf);
13177                         }
13178                         dest = ((char *)buf) + bits_to_bytes(info.offset);
13179 #if DEBUG_INITIALIZER
13180                         fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n", 
13181                                 dest - buf,
13182                                 bits_to_bytes(max_offset),
13183                                 bits_to_bytes(value_size),
13184                                 value->op);
13185 #endif
13186                         if (value->op == OP_BLOBCONST) {
13187                                 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13188                         }
13189                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13190 #if DEBUG_INITIALIZER
13191                                 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13192 #endif
13193                                 *((uint8_t *)dest) = value->u.cval & 0xff;
13194                         }
13195                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13196                                 *((uint16_t *)dest) = value->u.cval & 0xffff;
13197                         }
13198                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13199                                 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13200                         }
13201                         else {
13202                                 internal_error(state, 0, "unhandled constant initializer");
13203                         }
13204                         free_triple(state, value);
13205                         if (peek(state) == TOK_COMMA) {
13206                                 eat(state, TOK_COMMA);
13207                                 comma = 1;
13208                         }
13209                         info.offset += value_size;
13210                         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13211                                 info.type = next_field(state, type, info.type);
13212                                 info.offset = field_offset(state, type, 
13213                                         info.type->field_ident);
13214                         }
13215                 } while(comma && (peek(state) != TOK_RBRACE));
13216                 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13217                         ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13218                         type->elements = max_offset / size_of(state, type->left);
13219                 }
13220                 eat(state, TOK_RBRACE);
13221                 result = triple(state, OP_BLOBCONST, type, 0, 0);
13222                 result->u.blob = buf;
13223         }
13224         return result;
13225 }
13226
13227 static void resolve_branches(struct compile_state *state, struct triple *first)
13228 {
13229         /* Make a second pass and finish anything outstanding
13230          * with respect to branches.  The only outstanding item
13231          * is to see if there are goto to labels that have not
13232          * been defined and to error about them.
13233          */
13234         int i;
13235         struct triple *ins;
13236         /* Also error on branches that do not use their targets */
13237         ins = first;
13238         do {
13239                 if (!triple_is_ret(state, ins)) {
13240                         struct triple **expr ;
13241                         struct triple_set *set;
13242                         expr = triple_targ(state, ins, 0);
13243                         for(; expr; expr = triple_targ(state, ins, expr)) {
13244                                 struct triple *targ;
13245                                 targ = *expr;
13246                                 for(set = targ?targ->use:0; set; set = set->next) {
13247                                         if (set->member == ins) {
13248                                                 break;
13249                                         }
13250                                 }
13251                                 if (!set) {
13252                                         internal_error(state, ins, "targ not used");
13253                                 }
13254                         }
13255                 }
13256                 ins = ins->next;
13257         } while(ins != first);
13258         /* See if there are goto to labels that have not been defined */
13259         for(i = 0; i < HASH_TABLE_SIZE; i++) {
13260                 struct hash_entry *entry;
13261                 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13262                         struct triple *ins;
13263                         if (!entry->sym_label) {
13264                                 continue;
13265                         }
13266                         ins = entry->sym_label->def;
13267                         if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13268                                 error(state, ins, "label `%s' used but not defined",
13269                                         entry->name);
13270                         }
13271                 }
13272         }
13273 }
13274
13275 static struct triple *function_definition(
13276         struct compile_state *state, struct type *type)
13277 {
13278         struct triple *def, *tmp, *first, *end, *retvar, *result, *ret;
13279         struct triple *fname;
13280         struct type *fname_type;
13281         struct hash_entry *ident;
13282         struct type *param, *crtype, *ctype;
13283         int i;
13284         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13285                 error(state, 0, "Invalid function header");
13286         }
13287
13288         /* Verify the function type */
13289         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
13290                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13291                 (type->right->field_ident == 0)) {
13292                 error(state, 0, "Invalid function parameters");
13293         }
13294         param = type->right;
13295         i = 0;
13296         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13297                 i++;
13298                 if (!param->left->field_ident) {
13299                         error(state, 0, "No identifier for parameter %d\n", i);
13300                 }
13301                 param = param->right;
13302         }
13303         i++;
13304         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13305                 error(state, 0, "No identifier for paramter %d\n", i);
13306         }
13307         
13308         /* Get a list of statements for this function. */
13309         def = triple(state, OP_LIST, type, 0, 0);
13310
13311         /* Start a new scope for the passed parameters */
13312         start_scope(state);
13313
13314         /* Put a label at the very start of a function */
13315         first = label(state);
13316         RHS(def, 0) = first;
13317
13318         /* Put a label at the very end of a function */
13319         end = label(state);
13320         flatten(state, first, end);
13321         /* Remember where return goes */
13322         ident = state->i_return;
13323         symbol(state, ident, &ident->sym_ident, end, end->type);
13324
13325         /* Get the initial closure type */
13326         ctype = new_type(TYPE_JOIN, &void_type, 0);
13327         ctype->elements = 1;
13328
13329         /* Add a variable for the return value */
13330         crtype = new_type(TYPE_TUPLE, 
13331                 /* Remove all type qualifiers from the return type */
13332                 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13333         crtype->elements = 2;
13334         result = flatten(state, end, variable(state, crtype));
13335
13336         /* Allocate a variable for the return address */
13337         retvar = flatten(state, end, variable(state, &void_ptr_type));
13338
13339         /* Add in the return instruction */
13340         ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13341         ret = flatten(state, first, ret);
13342
13343         /* Walk through the parameters and create symbol table entries
13344          * for them.
13345          */
13346         param = type->right;
13347         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13348                 ident = param->left->field_ident;
13349                 tmp = variable(state, param->left);
13350                 var_symbol(state, ident, tmp);
13351                 flatten(state, end, tmp);
13352                 param = param->right;
13353         }
13354         if ((param->type & TYPE_MASK) != TYPE_VOID) {
13355                 /* And don't forget the last parameter */
13356                 ident = param->field_ident;
13357                 tmp = variable(state, param);
13358                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13359                 flatten(state, end, tmp);
13360         }
13361
13362         /* Add the declaration static const char __func__ [] = "func-name"  */
13363         fname_type = new_type(TYPE_ARRAY, 
13364                 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13365         fname_type->type |= QUAL_CONST | STOR_STATIC;
13366         fname_type->elements = strlen(state->function) + 1;
13367
13368         fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13369         fname->u.blob = (void *)state->function;
13370         fname = flatten(state, end, fname);
13371
13372         ident = state->i___func__;
13373         symbol(state, ident, &ident->sym_ident, fname, fname_type);
13374
13375         /* Remember which function I am compiling.
13376          * Also assume the last defined function is the main function.
13377          */
13378         state->main_function = def;
13379
13380         /* Now get the actual function definition */
13381         compound_statement(state, end);
13382
13383         /* Finish anything unfinished with branches */
13384         resolve_branches(state, first);
13385
13386         /* Remove the parameter scope */
13387         end_scope(state);
13388
13389
13390         /* Remember I have defined a function */
13391         if (!state->functions) {
13392                 state->functions = def;
13393         } else {
13394                 insert_triple(state, state->functions, def);
13395         }
13396         if (state->compiler->debug & DEBUG_INLINE) {
13397                 FILE *fp = state->dbgout;
13398                 fprintf(fp, "\n");
13399                 loc(fp, state, 0);
13400                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13401                 display_func(state, fp, def);
13402                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13403         }
13404
13405         return def;
13406 }
13407
13408 static struct triple *do_decl(struct compile_state *state, 
13409         struct type *type, struct hash_entry *ident)
13410 {
13411         struct triple *def;
13412         def = 0;
13413         /* Clean up the storage types used */
13414         switch (type->type & STOR_MASK) {
13415         case STOR_AUTO:
13416         case STOR_STATIC:
13417                 /* These are the good types I am aiming for */
13418                 break;
13419         case STOR_REGISTER:
13420                 type->type &= ~STOR_MASK;
13421                 type->type |= STOR_AUTO;
13422                 break;
13423         case STOR_LOCAL:
13424         case STOR_EXTERN:
13425                 type->type &= ~STOR_MASK;
13426                 type->type |= STOR_STATIC;
13427                 break;
13428         case STOR_TYPEDEF:
13429                 if (!ident) {
13430                         error(state, 0, "typedef without name");
13431                 }
13432                 symbol(state, ident, &ident->sym_ident, 0, type);
13433                 ident->tok = TOK_TYPE_NAME;
13434                 return 0;
13435                 break;
13436         default:
13437                 internal_error(state, 0, "Undefined storage class");
13438         }
13439         if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13440                 error(state, 0, "Function prototypes not supported");
13441         }
13442         if (ident && 
13443                 ((type->type & STOR_MASK) == STOR_STATIC) &&
13444                 ((type->type & QUAL_CONST) == 0)) {
13445                 error(state, 0, "non const static variables not supported");
13446         }
13447         if (ident) {
13448                 def = variable(state, type);
13449                 var_symbol(state, ident, def);
13450         }
13451         return def;
13452 }
13453
13454 static void decl(struct compile_state *state, struct triple *first)
13455 {
13456         struct type *base_type, *type;
13457         struct hash_entry *ident;
13458         struct triple *def;
13459         int global;
13460         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13461         base_type = decl_specifiers(state);
13462         ident = 0;
13463         type = declarator(state, base_type, &ident, 0);
13464         type->type = attributes_opt(state, type->type);
13465         if (global && ident && (peek(state) == TOK_LBRACE)) {
13466                 /* function */
13467                 type->type_ident = ident;
13468                 state->function = ident->name;
13469                 def = function_definition(state, type);
13470                 symbol(state, ident, &ident->sym_ident, def, type);
13471                 state->function = 0;
13472         }
13473         else {
13474                 int done;
13475                 flatten(state, first, do_decl(state, type, ident));
13476                 /* type or variable definition */
13477                 do {
13478                         done = 1;
13479                         if (peek(state) == TOK_EQ) {
13480                                 if (!ident) {
13481                                         error(state, 0, "cannot assign to a type");
13482                                 }
13483                                 eat(state, TOK_EQ);
13484                                 flatten(state, first,
13485                                         init_expr(state, 
13486                                                 ident->sym_ident->def, 
13487                                                 initializer(state, type)));
13488                         }
13489                         arrays_complete(state, type);
13490                         if (peek(state) == TOK_COMMA) {
13491                                 eat(state, TOK_COMMA);
13492                                 ident = 0;
13493                                 type = declarator(state, base_type, &ident, 0);
13494                                 flatten(state, first, do_decl(state, type, ident));
13495                                 done = 0;
13496                         }
13497                 } while(!done);
13498                 eat(state, TOK_SEMI);
13499         }
13500 }
13501
13502 static void decls(struct compile_state *state)
13503 {
13504         struct triple *list;
13505         int tok;
13506         list = label(state);
13507         while(1) {
13508                 tok = peek(state);
13509                 if (tok == TOK_EOF) {
13510                         return;
13511                 }
13512                 if (tok == TOK_SPACE) {
13513                         eat(state, TOK_SPACE);
13514                 }
13515                 decl(state, list);
13516                 if (list->next != list) {
13517                         error(state, 0, "global variables not supported");
13518                 }
13519         }
13520 }
13521
13522 /* 
13523  * Function inlining
13524  */
13525 struct triple_reg_set {
13526         struct triple_reg_set *next;
13527         struct triple *member;
13528         struct triple *new;
13529 };
13530 struct reg_block {
13531         struct block *block;
13532         struct triple_reg_set *in;
13533         struct triple_reg_set *out;
13534         int vertex;
13535 };
13536 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13537 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13538 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13539 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13540 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13541         void (*cb)(struct compile_state *state, struct block *block, void *arg),
13542         void *arg);
13543 static void print_block(
13544         struct compile_state *state, struct block *block, void *arg);
13545 static int do_triple_set(struct triple_reg_set **head, 
13546         struct triple *member, struct triple *new_member);
13547 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13548 static struct reg_block *compute_variable_lifetimes(
13549         struct compile_state *state, struct basic_blocks *bb);
13550 static void free_variable_lifetimes(struct compile_state *state, 
13551         struct basic_blocks *bb, struct reg_block *blocks);
13552 static void print_live_variables(struct compile_state *state, 
13553         struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13554
13555
13556 static struct triple *call(struct compile_state *state,
13557         struct triple *retvar, struct triple *ret_addr, 
13558         struct triple *targ, struct triple *ret)
13559 {
13560         struct triple *call;
13561
13562         if (!retvar || !is_lvalue(state, retvar)) {
13563                 internal_error(state, 0, "writing to a non lvalue?");
13564         }
13565         write_compatible(state, retvar->type, &void_ptr_type);
13566
13567         call = new_triple(state, OP_CALL, &void_type, 1, 0);
13568         TARG(call, 0) = targ;
13569         MISC(call, 0) = ret;
13570         if (!targ || (targ->op != OP_LABEL)) {
13571                 internal_error(state, 0, "call not to a label");
13572         }
13573         if (!ret || (ret->op != OP_RET)) {
13574                 internal_error(state, 0, "call not matched with return");
13575         }
13576         return call;
13577 }
13578
13579 static void walk_functions(struct compile_state *state,
13580         void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13581         void *arg)
13582 {
13583         struct triple *func, *first;
13584         func = first = state->functions;
13585         do {
13586                 cb(state, func, arg);
13587                 func = func->next;
13588         } while(func != first);
13589 }
13590
13591 static void reverse_walk_functions(struct compile_state *state,
13592         void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13593         void *arg)
13594 {
13595         struct triple *func, *first;
13596         func = first = state->functions;
13597         do {
13598                 func = func->prev;
13599                 cb(state, func, arg);
13600         } while(func != first);
13601 }
13602
13603
13604 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13605 {
13606         struct triple *ptr, *first;
13607         if (func->u.cval == 0) {
13608                 return;
13609         }
13610         ptr = first = RHS(func, 0);
13611         do {
13612                 if (ptr->op == OP_FCALL) {
13613                         struct triple *called_func;
13614                         called_func = MISC(ptr, 0);
13615                         /* Mark the called function as used */
13616                         if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13617                                 called_func->u.cval++;
13618                         }
13619                         /* Remove the called function from the list */
13620                         called_func->prev->next = called_func->next;
13621                         called_func->next->prev = called_func->prev;
13622
13623                         /* Place the called function before me on the list */
13624                         called_func->next       = func;
13625                         called_func->prev       = func->prev;
13626                         called_func->prev->next = called_func;
13627                         called_func->next->prev = called_func;
13628                 }
13629                 ptr = ptr->next;
13630         } while(ptr != first);
13631         func->id |= TRIPLE_FLAG_FLATTENED;
13632 }
13633
13634 static void mark_live_functions(struct compile_state *state)
13635 {
13636         /* Ensure state->main_function is the last function in 
13637          * the list of functions.
13638          */
13639         if ((state->main_function->next != state->functions) ||
13640                 (state->functions->prev != state->main_function)) {
13641                 internal_error(state, 0, 
13642                         "state->main_function is not at the end of the function list ");
13643         }
13644         state->main_function->u.cval = 1;
13645         reverse_walk_functions(state, mark_live, 0);
13646 }
13647
13648 static int local_triple(struct compile_state *state, 
13649         struct triple *func, struct triple *ins)
13650 {
13651         int local = (ins->id & TRIPLE_FLAG_LOCAL);
13652 #if 0
13653         if (!local) {
13654                 FILE *fp = state->errout;
13655                 fprintf(fp, "global: ");
13656                 display_triple(fp, ins);
13657         }
13658 #endif
13659         return local;
13660 }
13661
13662 struct triple *copy_func(struct compile_state *state, struct triple *ofunc, 
13663         struct occurance *base_occurance)
13664 {
13665         struct triple *nfunc;
13666         struct triple *nfirst, *ofirst;
13667         struct triple *new, *old;
13668
13669         if (state->compiler->debug & DEBUG_INLINE) {
13670                 FILE *fp = state->dbgout;
13671                 fprintf(fp, "\n");
13672                 loc(fp, state, 0);
13673                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13674                 display_func(state, fp, ofunc);
13675                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13676         }
13677
13678         /* Make a new copy of the old function */
13679         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13680         nfirst = 0;
13681         ofirst = old = RHS(ofunc, 0);
13682         do {
13683                 struct triple *new;
13684                 struct occurance *occurance;
13685                 int old_lhs, old_rhs;
13686                 old_lhs = old->lhs;
13687                 old_rhs = old->rhs;
13688                 occurance = inline_occurance(state, base_occurance, old->occurance);
13689                 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13690                         MISC(old, 0)->u.cval += 1;
13691                 }
13692                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13693                         occurance);
13694                 if (!triple_stores_block(state, new)) {
13695                         memcpy(&new->u, &old->u, sizeof(new->u));
13696                 }
13697                 if (!nfirst) {
13698                         RHS(nfunc, 0) = nfirst = new;
13699                 }
13700                 else {
13701                         insert_triple(state, nfirst, new);
13702                 }
13703                 new->id |= TRIPLE_FLAG_FLATTENED;
13704                 new->id |= old->id & TRIPLE_FLAG_COPY;
13705                 
13706                 /* During the copy remember new as user of old */
13707                 use_triple(old, new);
13708
13709                 /* Remember which instructions are local */
13710                 old->id |= TRIPLE_FLAG_LOCAL;
13711                 old = old->next;
13712         } while(old != ofirst);
13713
13714         /* Make a second pass to fix up any unresolved references */
13715         old = ofirst;
13716         new = nfirst;
13717         do {
13718                 struct triple **oexpr, **nexpr;
13719                 int count, i;
13720                 /* Lookup where the copy is, to join pointers */
13721                 count = TRIPLE_SIZE(old);
13722                 for(i = 0; i < count; i++) {
13723                         oexpr = &old->param[i];
13724                         nexpr = &new->param[i];
13725                         if (*oexpr && !*nexpr) {
13726                                 if (!local_triple(state, ofunc, *oexpr)) {
13727                                         *nexpr = *oexpr;
13728                                 }
13729                                 else if ((*oexpr)->use) {
13730                                         *nexpr = (*oexpr)->use->member;
13731                                 }
13732                                 if (*nexpr == old) {
13733                                         internal_error(state, 0, "new == old?");
13734                                 }
13735                                 use_triple(*nexpr, new);
13736                         }
13737                         if (!*nexpr && *oexpr) {
13738                                 internal_error(state, 0, "Could not copy %d", i);
13739                         }
13740                 }
13741                 old = old->next;
13742                 new = new->next;
13743         } while((old != ofirst) && (new != nfirst));
13744         
13745         /* Make a third pass to cleanup the extra useses */
13746         old = ofirst;
13747         new = nfirst;
13748         do {
13749                 unuse_triple(old, new);
13750                 /* Forget which instructions are local */
13751                 old->id &= ~TRIPLE_FLAG_LOCAL;
13752                 old = old->next;
13753                 new = new->next;
13754         } while ((old != ofirst) && (new != nfirst));
13755         return nfunc;
13756 }
13757
13758 static void expand_inline_call(
13759         struct compile_state *state, struct triple *me, struct triple *fcall)
13760 {
13761         /* Inline the function call */
13762         struct type *ptype;
13763         struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13764         struct triple *end, *nend;
13765         int pvals, i;
13766
13767         /* Find the triples */
13768         ofunc = MISC(fcall, 0);
13769         if (ofunc->op != OP_LIST) {
13770                 internal_error(state, 0, "improper function");
13771         }
13772         nfunc = copy_func(state, ofunc, fcall->occurance);
13773         /* Prepend the parameter reading into the new function list */
13774         ptype = nfunc->type->right;
13775         pvals = fcall->rhs;
13776         for(i = 0; i < pvals; i++) {
13777                 struct type *atype;
13778                 struct triple *arg, *param;
13779                 atype = ptype;
13780                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13781                         atype = ptype->left;
13782                 }
13783                 param = farg(state, nfunc, i);
13784                 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13785                         internal_error(state, fcall, "param %d type mismatch", i);
13786                 }
13787                 arg = RHS(fcall, i);
13788                 flatten(state, fcall, write_expr(state, param, arg));
13789                 ptype = ptype->right;
13790         }
13791         result = 0;
13792         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13793                 result = read_expr(state, 
13794                         deref_index(state, fresult(state, nfunc), 1));
13795         }
13796         if (state->compiler->debug & DEBUG_INLINE) {
13797                 FILE *fp = state->dbgout;
13798                 fprintf(fp, "\n");
13799                 loc(fp, state, 0);
13800                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13801                 display_func(state, fp, nfunc);
13802                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13803         }
13804
13805         /* 
13806          * Get rid of the extra triples 
13807          */
13808         /* Remove the read of the return address */
13809         ins = RHS(nfunc, 0)->prev->prev;
13810         if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13811                 internal_error(state, ins, "Not return addres read?");
13812         }
13813         release_triple(state, ins);
13814         /* Remove the return instruction */
13815         ins = RHS(nfunc, 0)->prev;
13816         if (ins->op != OP_RET) {
13817                 internal_error(state, ins, "Not return?");
13818         }
13819         release_triple(state, ins);
13820         /* Remove the retaddres variable */
13821         retvar = fretaddr(state, nfunc);
13822         if ((retvar->lhs != 1) || 
13823                 (retvar->op != OP_ADECL) ||
13824                 (retvar->next->op != OP_PIECE) ||
13825                 (MISC(retvar->next, 0) != retvar)) {
13826                 internal_error(state, retvar, "Not the return address?");
13827         }
13828         release_triple(state, retvar->next);
13829         release_triple(state, retvar);
13830
13831         /* Remove the label at the start of the function */
13832         ins = RHS(nfunc, 0);
13833         if (ins->op != OP_LABEL) {
13834                 internal_error(state, ins, "Not label?");
13835         }
13836         nfirst = ins->next;
13837         free_triple(state, ins);
13838         /* Release the new function header */
13839         RHS(nfunc, 0) = 0;
13840         free_triple(state, nfunc);
13841
13842         /* Append the new function list onto the return list */
13843         end = fcall->prev;
13844         nend = nfirst->prev;
13845         end->next    = nfirst;
13846         nfirst->prev = end;
13847         nend->next   = fcall;
13848         fcall->prev  = nend;
13849
13850         /* Now the result reading code */
13851         if (result) {
13852                 result = flatten(state, fcall, result);
13853                 propogate_use(state, fcall, result);
13854         }
13855
13856         /* Release the original fcall instruction */
13857         release_triple(state, fcall);
13858
13859         return;
13860 }
13861
13862 /*
13863  *
13864  * Type of the result variable.
13865  * 
13866  *                                     result
13867  *                                        |
13868  *                             +----------+------------+
13869  *                             |                       |
13870  *                     union of closures         result_type
13871  *                             |
13872  *          +------------------+---------------+
13873  *          |                                  |
13874  *       closure1                    ...   closuerN
13875  *          |                                  | 
13876  *  +----+--+-+--------+-----+       +----+----+---+-----+
13877  *  |    |    |        |     |       |    |        |     |
13878  * var1 var2 var3 ... varN result   var1 var2 ... varN result
13879  *                           |
13880  *                  +--------+---------+
13881  *                  |                  |
13882  *          union of closures     result_type
13883  *                  |
13884  *            +-----+-------------------+
13885  *            |                         |
13886  *         closure1            ...  closureN
13887  *            |                         |
13888  *  +-----+---+----+----+      +----+---+----+-----+
13889  *  |     |        |    |      |    |        |     |
13890  * var1 var2 ... varN result  var1 var2 ... varN result
13891  */
13892
13893 static int add_closure_type(struct compile_state *state, 
13894         struct triple *func, struct type *closure_type)
13895 {
13896         struct type *type, *ctype, **next;
13897         struct triple *var, *new_var;
13898         int i;
13899
13900 #if 0
13901         FILE *fp = state->errout;
13902         fprintf(fp, "original_type: ");
13903         name_of(fp, fresult(state, func)->type);
13904         fprintf(fp, "\n");
13905 #endif
13906         /* find the original type */
13907         var = fresult(state, func);
13908         type = var->type;
13909         if (type->elements != 2) {
13910                 internal_error(state, var, "bad return type");
13911         }
13912
13913         /* Find the complete closure type and update it */
13914         ctype = type->left->left;
13915         next = &ctype->left;
13916         while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13917                 next = &(*next)->right;
13918         }
13919         *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13920         ctype->elements += 1;
13921
13922 #if 0
13923         fprintf(fp, "new_type: ");
13924         name_of(fp, type);
13925         fprintf(fp, "\n");
13926         fprintf(fp, "ctype: %p %d bits: %d ", 
13927                 ctype, ctype->elements, reg_size_of(state, ctype));
13928         name_of(fp, ctype);
13929         fprintf(fp, "\n");
13930 #endif
13931         
13932         /* Regenerate the variable with the new type definition */
13933         new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13934         new_var->id |= TRIPLE_FLAG_FLATTENED;
13935         for(i = 0; i < new_var->lhs; i++) {
13936                 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13937         }
13938         
13939         /* Point everyone at the new variable */
13940         propogate_use(state, var, new_var);
13941
13942         /* Release the original variable */
13943         for(i = 0; i < var->lhs; i++) {
13944                 release_triple(state, LHS(var, i));
13945         }
13946         release_triple(state, var);
13947         
13948         /* Return the index of the added closure type */
13949         return ctype->elements - 1;
13950 }
13951
13952 static struct triple *closure_expr(struct compile_state *state,
13953         struct triple *func, int closure_idx, int var_idx)
13954 {
13955         return deref_index(state,
13956                 deref_index(state,
13957                         deref_index(state, fresult(state, func), 0),
13958                         closure_idx),
13959                 var_idx);
13960 }
13961
13962
13963 static void insert_triple_set(
13964         struct triple_reg_set **head, struct triple *member)
13965 {
13966         struct triple_reg_set *new;
13967         new = xcmalloc(sizeof(*new), "triple_set");
13968         new->member = member;
13969         new->new    = 0;
13970         new->next   = *head;
13971         *head       = new;
13972 }
13973
13974 static int ordered_triple_set(
13975         struct triple_reg_set **head, struct triple *member)
13976 {
13977         struct triple_reg_set **ptr;
13978         if (!member)
13979                 return 0;
13980         ptr = head;
13981         while(*ptr) {
13982                 if (member == (*ptr)->member) {
13983                         return 0;
13984                 }
13985                 /* keep the list ordered */
13986                 if (member->id < (*ptr)->member->id) {
13987                         break;
13988                 }
13989                 ptr = &(*ptr)->next;
13990         }
13991         insert_triple_set(ptr, member);
13992         return 1;
13993 }
13994
13995
13996 static void free_closure_variables(struct compile_state *state,
13997         struct triple_reg_set **enclose)
13998 {
13999         struct triple_reg_set *entry, *next;
14000         for(entry = *enclose; entry; entry = next) {
14001                 next = entry->next;
14002                 do_triple_unset(enclose, entry->member);
14003         }
14004 }
14005
14006 static int lookup_closure_index(struct compile_state *state,
14007         struct triple *me, struct triple *val)
14008 {
14009         struct triple *first, *ins, *next;
14010         first = RHS(me, 0);
14011         ins = next = first;
14012         do {
14013                 struct triple *result;
14014                 struct triple *index0, *index1, *index2, *read, *write;
14015                 ins = next;
14016                 next = ins->next;
14017                 if (ins->op != OP_CALL) {
14018                         continue;
14019                 }
14020                 /* I am at a previous call point examine it closely */
14021                 if (ins->next->op != OP_LABEL) {
14022                         internal_error(state, ins, "call not followed by label");
14023                 }
14024                 /* Does this call does not enclose any variables? */
14025                 if ((ins->next->next->op != OP_INDEX) ||
14026                         (ins->next->next->u.cval != 0) ||
14027                         (result = MISC(ins->next->next, 0)) ||
14028                         (result->id & TRIPLE_FLAG_LOCAL)) {
14029                         continue;
14030                 }
14031                 index0 = ins->next->next;
14032                 /* The pattern is:
14033                  * 0 index result < 0 >
14034                  * 1 index 0 < ? >
14035                  * 2 index 1 < ? >
14036                  * 3 read  2
14037                  * 4 write 3 var
14038                  */
14039                 for(index0 = ins->next->next;
14040                         (index0->op == OP_INDEX) &&
14041                                 (MISC(index0, 0) == result) &&
14042                                 (index0->u.cval == 0) ; 
14043                         index0 = write->next)
14044                 {
14045                         index1 = index0->next;
14046                         index2 = index1->next;
14047                         read   = index2->next;
14048                         write  = read->next;
14049                         if ((index0->op != OP_INDEX) ||
14050                                 (index1->op != OP_INDEX) ||
14051                                 (index2->op != OP_INDEX) ||
14052                                 (read->op != OP_READ) ||
14053                                 (write->op != OP_WRITE) ||
14054                                 (MISC(index1, 0) != index0) ||
14055                                 (MISC(index2, 0) != index1) ||
14056                                 (RHS(read, 0) != index2) ||
14057                                 (RHS(write, 0) != read)) {
14058                                 internal_error(state, index0, "bad var read");
14059                         }
14060                         if (MISC(write, 0) == val) {
14061                                 return index2->u.cval;
14062                         }
14063                 }
14064         } while(next != first);
14065         return -1;
14066 }
14067
14068 static inline int enclose_triple(struct triple *ins)
14069 {
14070         return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14071 }
14072
14073 static void compute_closure_variables(struct compile_state *state,
14074         struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14075 {
14076         struct triple_reg_set *set, *vars, **last_var;
14077         struct basic_blocks bb;
14078         struct reg_block *rb;
14079         struct block *block;
14080         struct triple *old_result, *first, *ins;
14081         size_t count, idx;
14082         unsigned long used_indicies;
14083         int i, max_index;
14084 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14085 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14086         struct { 
14087                 unsigned id;
14088                 int index;
14089         } *info;
14090
14091         
14092         /* Find the basic blocks of this function */
14093         bb.func = me;
14094         bb.first = RHS(me, 0);
14095         old_result = 0;
14096         if (!triple_is_ret(state, bb.first->prev)) {
14097                 bb.func = 0;
14098         } else {
14099                 old_result = fresult(state, me);
14100         }
14101         analyze_basic_blocks(state, &bb);
14102
14103         /* Find which variables are currently alive in a given block */
14104         rb = compute_variable_lifetimes(state, &bb);
14105
14106         /* Find the variables that are currently alive */
14107         block = block_of_triple(state, fcall);
14108         if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14109                 internal_error(state, fcall, "No reg block? block: %p", block);
14110         }
14111
14112 #if DEBUG_EXPLICIT_CLOSURES
14113         print_live_variables(state, &bb, rb, state->dbgout);
14114         fflush(state->dbgout);
14115 #endif
14116
14117         /* Count the number of triples in the function */
14118         first = RHS(me, 0);
14119         ins = first;
14120         count = 0;
14121         do {
14122                 count++;
14123                 ins = ins->next;
14124         } while(ins != first);
14125
14126         /* Allocate some memory to temorary hold the id info */
14127         info = xcmalloc(sizeof(*info) * (count +1), "info");
14128
14129         /* Mark the local function */
14130         first = RHS(me, 0);
14131         ins = first;
14132         idx = 1;
14133         do {
14134                 info[idx].id = ins->id;
14135                 ins->id = TRIPLE_FLAG_LOCAL | idx;
14136                 idx++;
14137                 ins = ins->next;
14138         } while(ins != first);
14139
14140         /* 
14141          * Build the list of variables to enclose.
14142          *
14143          * A target it to put the same variable in the
14144          * same slot for ever call of a given function.
14145          * After coloring this removes all of the variable
14146          * manipulation code.
14147          *
14148          * The list of variables to enclose is built ordered
14149          * program order because except in corner cases this
14150          * gives me the stability of assignment I need.
14151          *
14152          * To gurantee that stability I lookup the variables
14153          * to see where they have been used before and
14154          * I build my final list with the assigned indicies.
14155          */
14156         vars = 0;
14157         if (enclose_triple(old_result)) {
14158                 ordered_triple_set(&vars, old_result);
14159         }
14160         for(set = rb[block->vertex].out; set; set = set->next) {
14161                 if (!enclose_triple(set->member)) {
14162                         continue;
14163                 }
14164                 if ((set->member == fcall) || (set->member == old_result)) {
14165                         continue;
14166                 }
14167                 if (!local_triple(state, me, set->member)) {
14168                         internal_error(state, set->member, "not local?");
14169                 }
14170                 ordered_triple_set(&vars, set->member);
14171         }
14172
14173         /* Lookup the current indicies of the live varialbe */
14174         used_indicies = 0;
14175         max_index = -1;
14176         for(set = vars; set ; set = set->next) {
14177                 struct triple *ins;
14178                 int index;
14179                 ins = set->member;
14180                 index  = lookup_closure_index(state, me, ins);
14181                 info[ID_BITS(ins->id)].index = index;
14182                 if (index < 0) {
14183                         continue;
14184                 }
14185                 if (index >= MAX_INDICIES) {
14186                         internal_error(state, ins, "index unexpectedly large");
14187                 }
14188                 if (used_indicies & (1 << index)) {
14189                         internal_error(state, ins, "index previously used?");
14190                 }
14191                 /* Remember which indicies have been used */
14192                 used_indicies |= (1 << index);
14193                 if (index > max_index) {
14194                         max_index = index;
14195                 }
14196         }
14197
14198         /* Walk through the live variables and make certain
14199          * everything is assigned an index.
14200          */
14201         for(set = vars; set; set = set->next) {
14202                 struct triple *ins;
14203                 int index;
14204                 ins = set->member;
14205                 index = info[ID_BITS(ins->id)].index;
14206                 if (index >= 0) {
14207                         continue;
14208                 }
14209                 /* Find the lowest unused index value */
14210                 for(index = 0; index < MAX_INDICIES; index++) {
14211                         if (!(used_indicies & (1 << index))) {
14212                                 break;
14213                         }
14214                 }
14215                 if (index == MAX_INDICIES) {
14216                         internal_error(state, ins, "no free indicies?");
14217                 }
14218                 info[ID_BITS(ins->id)].index = index;
14219                 /* Remember which indicies have been used */
14220                 used_indicies |= (1 << index);
14221                 if (index > max_index) {
14222                         max_index = index;
14223                 }
14224         }
14225
14226         /* Build the return list of variables with positions matching
14227          * their indicies.
14228          */
14229         *enclose = 0;
14230         last_var = enclose;
14231         for(i = 0; i <= max_index; i++) {
14232                 struct triple *var;
14233                 var = 0;
14234                 if (used_indicies & (1 << i)) {
14235                         for(set = vars; set; set = set->next) {
14236                                 int index;
14237                                 index = info[ID_BITS(set->member->id)].index;
14238                                 if (index == i) {
14239                                         var = set->member;
14240                                         break;
14241                                 }
14242                         }
14243                         if (!var) {
14244                                 internal_error(state, me, "missing variable");
14245                         }
14246                 }
14247                 insert_triple_set(last_var, var);
14248                 last_var = &(*last_var)->next;
14249         }
14250
14251 #if DEBUG_EXPLICIT_CLOSURES
14252         /* Print out the variables to be enclosed */
14253         loc(state->dbgout, state, fcall);
14254         fprintf(state->dbgout, "Alive: \n");
14255         for(set = *enclose; set; set = set->next) {
14256                 display_triple(state->dbgout, set->member);
14257         }
14258         fflush(state->dbgout);
14259 #endif
14260
14261         /* Clear the marks */
14262         ins = first;
14263         do {
14264                 ins->id = info[ID_BITS(ins->id)].id;
14265                 ins = ins->next;
14266         } while(ins != first);
14267
14268         /* Release the ordered list of live variables */
14269         free_closure_variables(state, &vars);
14270
14271         /* Release the storage of the old ids */
14272         xfree(info);
14273
14274         /* Release the variable lifetime information */
14275         free_variable_lifetimes(state, &bb, rb);
14276
14277         /* Release the basic blocks of this function */
14278         free_basic_blocks(state, &bb);
14279 }
14280
14281 static void expand_function_call(
14282         struct compile_state *state, struct triple *me, struct triple *fcall)
14283 {
14284         /* Generate an ordinary function call */
14285         struct type *closure_type, **closure_next;
14286         struct triple *func, *func_first, *func_last, *retvar;
14287         struct triple *first;
14288         struct type *ptype, *rtype;
14289         struct triple *jmp;
14290         struct triple *ret_addr, *ret_loc, *ret_set;
14291         struct triple_reg_set *enclose, *set;
14292         int closure_idx, pvals, i;
14293
14294 #if DEBUG_EXPLICIT_CLOSURES
14295         FILE *fp = state->dbgout;
14296         fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14297         display_func(state, fp, MISC(fcall, 0));
14298         display_func(state, fp, me);
14299         fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14300 #endif
14301
14302         /* Find the triples */
14303         func = MISC(fcall, 0);
14304         func_first = RHS(func, 0);
14305         retvar = fretaddr(state, func);
14306         func_last  = func_first->prev;
14307         first = fcall->next;
14308
14309         /* Find what I need to enclose */
14310         compute_closure_variables(state, me, fcall, &enclose);
14311
14312         /* Compute the closure type */
14313         closure_type = new_type(TYPE_TUPLE, 0, 0);
14314         closure_type->elements = 0;
14315         closure_next = &closure_type->left;
14316         for(set = enclose; set ; set = set->next) {
14317                 struct type *type;
14318                 type = &void_type;
14319                 if (set->member) {
14320                         type = set->member->type;
14321                 }
14322                 if (!*closure_next) {
14323                         *closure_next = type;
14324                 } else {
14325                         *closure_next = new_type(TYPE_PRODUCT, *closure_next, 
14326                                 type);
14327                         closure_next = &(*closure_next)->right;
14328                 }
14329                 closure_type->elements += 1;
14330         }
14331         if (closure_type->elements == 0) {
14332                 closure_type->type = TYPE_VOID;
14333         }
14334
14335
14336 #if DEBUG_EXPLICIT_CLOSURES
14337         fprintf(state->dbgout, "closure type: ");
14338         name_of(state->dbgout, closure_type);
14339         fprintf(state->dbgout, "\n");
14340 #endif
14341
14342         /* Update the called functions closure variable */
14343         closure_idx = add_closure_type(state, func, closure_type);
14344
14345         /* Generate some needed triples */
14346         ret_loc = label(state);
14347         ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14348
14349         /* Pass the parameters to the new function */
14350         ptype = func->type->right;
14351         pvals = fcall->rhs;
14352         for(i = 0; i < pvals; i++) {
14353                 struct type *atype;
14354                 struct triple *arg, *param;
14355                 atype = ptype;
14356                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14357                         atype = ptype->left;
14358                 }
14359                 param = farg(state, func, i);
14360                 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14361                         internal_error(state, fcall, "param type mismatch");
14362                 }
14363                 arg = RHS(fcall, i);
14364                 flatten(state, first, write_expr(state, param, arg));
14365                 ptype = ptype->right;
14366         }
14367         rtype = func->type->left;
14368
14369         /* Thread the triples together */
14370         ret_loc       = flatten(state, first, ret_loc);
14371
14372         /* Save the active variables in the result variable */
14373         for(i = 0, set = enclose; set ; set = set->next, i++) {
14374                 if (!set->member) {
14375                         continue;
14376                 }
14377                 flatten(state, ret_loc,
14378                         write_expr(state,
14379                                 closure_expr(state, func, closure_idx, i),
14380                                 read_expr(state, set->member)));
14381         }
14382
14383         /* Initialize the return value */
14384         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14385                 flatten(state, ret_loc, 
14386                         write_expr(state, 
14387                                 deref_index(state, fresult(state, func), 1),
14388                                 new_triple(state, OP_UNKNOWNVAL, rtype,  0, 0)));
14389         }
14390
14391         ret_addr      = flatten(state, ret_loc, ret_addr);
14392         ret_set       = flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14393         jmp           = flatten(state, ret_loc, 
14394                 call(state, retvar, ret_addr, func_first, func_last));
14395
14396         /* Find the result */
14397         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14398                 struct triple * result;
14399                 result = flatten(state, first, 
14400                         read_expr(state, 
14401                                 deref_index(state, fresult(state, func), 1)));
14402
14403                 propogate_use(state, fcall, result);
14404         }
14405
14406         /* Release the original fcall instruction */
14407         release_triple(state, fcall);
14408
14409         /* Restore the active variables from the result variable */
14410         for(i = 0, set = enclose; set ; set = set->next, i++) {
14411                 struct triple_set *use, *next;
14412                 struct triple *new;
14413                 struct basic_blocks bb;
14414                 if (!set->member || (set->member == fcall)) {
14415                         continue;
14416                 }
14417                 /* Generate an expression for the value */
14418                 new = flatten(state, first,
14419                         read_expr(state, 
14420                                 closure_expr(state, func, closure_idx, i)));
14421
14422
14423                 /* If the original is an lvalue restore the preserved value */
14424                 if (is_lvalue(state, set->member)) {
14425                         flatten(state, first,
14426                                 write_expr(state, set->member, new));
14427                         continue;
14428                 }
14429                 /*
14430                  * If the original is a value update the dominated uses.
14431                  */
14432                 
14433                 /* Analyze the basic blocks so I can see who dominates whom */
14434                 bb.func = me;
14435                 bb.first = RHS(me, 0);
14436                 if (!triple_is_ret(state, bb.first->prev)) {
14437                         bb.func = 0;
14438                 }
14439                 analyze_basic_blocks(state, &bb);
14440                 
14441
14442 #if DEBUG_EXPLICIT_CLOSURES
14443                 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14444                         set->member, new);
14445 #endif
14446                 /* If fcall dominates the use update the expression */
14447                 for(use = set->member->use; use; use = next) {
14448                         /* Replace use modifies the use chain and 
14449                          * removes use, so I must take a copy of the
14450                          * next entry early.
14451                          */
14452                         next = use->next;
14453                         if (!tdominates(state, fcall, use->member)) {
14454                                 continue;
14455                         }
14456                         replace_use(state, set->member, new, use->member);
14457                 }
14458
14459                 /* Release the basic blocks, the instructions will be
14460                  * different next time, and flatten/insert_triple does
14461                  * not update the block values so I can't cache the analysis.
14462                  */
14463                 free_basic_blocks(state, &bb);
14464         }
14465
14466         /* Release the closure variable list */
14467         free_closure_variables(state, &enclose);
14468
14469         if (state->compiler->debug & DEBUG_INLINE) {
14470                 FILE *fp = state->dbgout;
14471                 fprintf(fp, "\n");
14472                 loc(fp, state, 0);
14473                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14474                 display_func(state, fp, func);
14475                 display_func(state, fp, me);
14476                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14477         }
14478
14479         return;
14480 }
14481
14482 static int do_inline(struct compile_state *state, struct triple *func)
14483 {
14484         int do_inline;
14485         int policy;
14486
14487         policy = state->compiler->flags & COMPILER_INLINE_MASK;
14488         switch(policy) {
14489         case COMPILER_INLINE_ALWAYS:
14490                 do_inline = 1;
14491                 if (func->type->type & ATTRIB_NOINLINE) {
14492                         error(state, func, "noinline with always_inline compiler option");
14493                 }
14494                 break;
14495         case COMPILER_INLINE_NEVER:
14496                 do_inline = 0;
14497                 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14498                         error(state, func, "always_inline with noinline compiler option");
14499                 }
14500                 break;
14501         case COMPILER_INLINE_DEFAULTON:
14502                 switch(func->type->type & STOR_MASK) {
14503                 case STOR_STATIC | STOR_INLINE:
14504                 case STOR_LOCAL  | STOR_INLINE:
14505                 case STOR_EXTERN | STOR_INLINE:
14506                         do_inline = 1;
14507                         break;
14508                 default:
14509                         do_inline = 1;
14510                         break;
14511                 }
14512                 break;
14513         case COMPILER_INLINE_DEFAULTOFF:
14514                 switch(func->type->type & STOR_MASK) {
14515                 case STOR_STATIC | STOR_INLINE:
14516                 case STOR_LOCAL  | STOR_INLINE:
14517                 case STOR_EXTERN | STOR_INLINE:
14518                         do_inline = 1;
14519                         break;
14520                 default:
14521                         do_inline = 0;
14522                         break;
14523                 }
14524                 break;
14525         case COMPILER_INLINE_NOPENALTY:
14526                 switch(func->type->type & STOR_MASK) {
14527                 case STOR_STATIC | STOR_INLINE:
14528                 case STOR_LOCAL  | STOR_INLINE:
14529                 case STOR_EXTERN | STOR_INLINE:
14530                         do_inline = 1;
14531                         break;
14532                 default:
14533                         do_inline = (func->u.cval == 1);
14534                         break;
14535                 }
14536                 break;
14537         default:
14538                 do_inline = 0;
14539                 internal_error(state, 0, "Unimplemented inline policy");
14540                 break;
14541         }
14542         /* Force inlining */
14543         if (func->type->type & ATTRIB_NOINLINE) {
14544                 do_inline = 0;
14545         }
14546         if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14547                 do_inline = 1;
14548         }
14549         return do_inline;
14550 }
14551
14552 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14553 {
14554         struct triple *first, *ptr, *next;
14555         /* If the function is not used don't bother */
14556         if (me->u.cval <= 0) {
14557                 return;
14558         }
14559         if (state->compiler->debug & DEBUG_CALLS2) {
14560                 FILE *fp = state->dbgout;
14561                 fprintf(fp, "in: %s\n",
14562                         me->type->type_ident->name);
14563         }
14564
14565         first = RHS(me, 0);
14566         ptr = next = first;
14567         do {
14568                 struct triple *func, *prev;
14569                 ptr = next;
14570                 prev = ptr->prev;
14571                 next = ptr->next;
14572                 if (ptr->op != OP_FCALL) {
14573                         continue;
14574                 }
14575                 func = MISC(ptr, 0);
14576                 /* See if the function should be inlined */
14577                 if (!do_inline(state, func)) {
14578                         /* Put a label after the fcall */
14579                         post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14580                         continue;
14581                 }
14582                 if (state->compiler->debug & DEBUG_CALLS) {
14583                         FILE *fp = state->dbgout;
14584                         if (state->compiler->debug & DEBUG_CALLS2) {
14585                                 loc(fp, state, ptr);
14586                         }
14587                         fprintf(fp, "inlining %s\n",
14588                                 func->type->type_ident->name);
14589                         fflush(fp);
14590                 }
14591
14592                 /* Update the function use counts */
14593                 func->u.cval -= 1;
14594
14595                 /* Replace the fcall with the called function */
14596                 expand_inline_call(state, me, ptr);
14597
14598                 next = prev->next;
14599         } while (next != first);
14600
14601         ptr = next = first;
14602         do {
14603                 struct triple *prev, *func;
14604                 ptr = next;
14605                 prev = ptr->prev;
14606                 next = ptr->next;
14607                 if (ptr->op != OP_FCALL) {
14608                         continue;
14609                 }
14610                 func = MISC(ptr, 0);
14611                 if (state->compiler->debug & DEBUG_CALLS) {
14612                         FILE *fp = state->dbgout;
14613                         if (state->compiler->debug & DEBUG_CALLS2) {
14614                                 loc(fp, state, ptr);
14615                         }
14616                         fprintf(fp, "calling %s\n",
14617                                 func->type->type_ident->name);
14618                         fflush(fp);
14619                 }
14620                 /* Replace the fcall with the instruction sequence
14621                  * needed to make the call.
14622                  */
14623                 expand_function_call(state, me, ptr);
14624                 next = prev->next;
14625         } while(next != first);
14626 }
14627
14628 static void inline_functions(struct compile_state *state, struct triple *func)
14629 {
14630         inline_function(state, func, 0);
14631         reverse_walk_functions(state, inline_function, 0);
14632 }
14633
14634 static void insert_function(struct compile_state *state,
14635         struct triple *func, void *arg)
14636 {
14637         struct triple *first, *end, *ffirst, *fend;
14638
14639         if (state->compiler->debug & DEBUG_INLINE) {
14640                 FILE *fp = state->errout;
14641                 fprintf(fp, "%s func count: %d\n", 
14642                         func->type->type_ident->name, func->u.cval);
14643         }
14644         if (func->u.cval == 0) {
14645                 return;
14646         }
14647
14648         /* Find the end points of the lists */
14649         first  = arg;
14650         end    = first->prev;
14651         ffirst = RHS(func, 0);
14652         fend   = ffirst->prev;
14653
14654         /* splice the lists together */
14655         end->next    = ffirst;
14656         ffirst->prev = end;
14657         fend->next   = first;
14658         first->prev  = fend;
14659 }
14660
14661 struct triple *input_asm(struct compile_state *state)
14662 {
14663         struct asm_info *info;
14664         struct triple *def;
14665         int i, out;
14666         
14667         info = xcmalloc(sizeof(*info), "asm_info");
14668         info->str = "";
14669
14670         out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14671         memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14672
14673         def = new_triple(state, OP_ASM, &void_type, out, 0);
14674         def->u.ainfo = info;
14675         def->id |= TRIPLE_FLAG_VOLATILE;
14676         
14677         for(i = 0; i < out; i++) {
14678                 struct triple *piece;
14679                 piece = triple(state, OP_PIECE, &int_type, def, 0);
14680                 piece->u.cval = i;
14681                 LHS(def, i) = piece;
14682         }
14683
14684         return def;
14685 }
14686
14687 struct triple *output_asm(struct compile_state *state)
14688 {
14689         struct asm_info *info;
14690         struct triple *def;
14691         int in;
14692         
14693         info = xcmalloc(sizeof(*info), "asm_info");
14694         info->str = "";
14695
14696         in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14697         memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14698
14699         def = new_triple(state, OP_ASM, &void_type, 0, in);
14700         def->u.ainfo = info;
14701         def->id |= TRIPLE_FLAG_VOLATILE;
14702         
14703         return def;
14704 }
14705
14706 static void join_functions(struct compile_state *state)
14707 {
14708         struct triple *jmp, *start, *end, *call, *in, *out, *func;
14709         struct file_state file;
14710         struct type *pnext, *param;
14711         struct type *result_type, *args_type;
14712         int idx;
14713
14714         /* Be clear the functions have not been joined yet */
14715         state->functions_joined = 0;
14716
14717         /* Dummy file state to get debug handing right */
14718         memset(&file, 0, sizeof(file));
14719         file.basename = "";
14720         file.line = 0;
14721         file.report_line = 0;
14722         file.report_name = file.basename;
14723         file.prev = state->file;
14724         state->file = &file;
14725         state->function = "";
14726
14727         /* The type of arguments */
14728         args_type   = state->main_function->type->right;
14729         /* The return type without any specifiers */
14730         result_type = clone_type(0, state->main_function->type->left);
14731
14732
14733         /* Verify the external arguments */
14734         if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14735                 error(state, state->main_function, 
14736                         "Too many external input arguments");
14737         }
14738         if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14739                 error(state, state->main_function, 
14740                         "Too many external output arguments");
14741         }
14742
14743         /* Lay down the basic program structure */
14744         end           = label(state);
14745         start         = label(state);
14746         start         = flatten(state, state->first, start);
14747         end           = flatten(state, state->first, end);
14748         in            = input_asm(state);
14749         out           = output_asm(state);
14750         call          = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14751         MISC(call, 0) = state->main_function;
14752         in            = flatten(state, state->first, in);
14753         call          = flatten(state, state->first, call);
14754         out           = flatten(state, state->first, out);
14755
14756
14757         /* Read the external input arguments */
14758         pnext = args_type;
14759         idx = 0;
14760         while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14761                 struct triple *expr;
14762                 param = pnext;
14763                 pnext = 0;
14764                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14765                         pnext = param->right;
14766                         param = param->left;
14767                 }
14768                 if (registers_of(state, param) != 1) {
14769                         error(state, state->main_function, 
14770                                 "Arg: %d %s requires multiple registers", 
14771                                 idx + 1, param->field_ident->name);
14772                 }
14773                 expr = read_expr(state, LHS(in, idx));
14774                 RHS(call, idx) = expr;
14775                 expr = flatten(state, call, expr);
14776                 use_triple(expr, call);
14777
14778                 idx++;  
14779         }
14780
14781
14782         /* Write the external output arguments */
14783         pnext = result_type;
14784         if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14785                 pnext = result_type->left;
14786         }
14787         for(idx = 0; idx < out->rhs; idx++) {
14788                 struct triple *expr;
14789                 param = pnext;
14790                 pnext = 0;
14791                 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14792                         pnext = param->right;
14793                         param = param->left;
14794                 }
14795                 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14796                         param = 0;
14797                 }
14798                 if (param) {
14799                         if (registers_of(state, param) != 1) {
14800                                 error(state, state->main_function,
14801                                         "Result: %d %s requires multiple registers",
14802                                         idx, param->field_ident->name);
14803                         }
14804                         expr = read_expr(state, call);
14805                         if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14806                                 expr = deref_field(state, expr, param->field_ident);
14807                         }
14808                 } else {
14809                         expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14810                 }
14811                 flatten(state, out, expr);
14812                 RHS(out, idx) = expr;
14813                 use_triple(expr, out);
14814         }
14815
14816         /* Allocate a dummy containing function */
14817         func = triple(state, OP_LIST, 
14818                 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14819         func->type->type_ident = lookup(state, "", 0);
14820         RHS(func, 0) = state->first;
14821         func->u.cval = 1;
14822
14823         /* See which functions are called, and how often */
14824         mark_live_functions(state);
14825         inline_functions(state, func);
14826         walk_functions(state, insert_function, end);
14827
14828         if (start->next != end) {
14829                 jmp = flatten(state, start, branch(state, end, 0));
14830         }
14831
14832         /* OK now the functions have been joined. */
14833         state->functions_joined = 1;
14834
14835         /* Done now cleanup */
14836         state->file = file.prev;
14837         state->function = 0;
14838 }
14839
14840 /*
14841  * Data structurs for optimation.
14842  */
14843
14844
14845 static int do_use_block(
14846         struct block *used, struct block_set **head, struct block *user, 
14847         int front)
14848 {
14849         struct block_set **ptr, *new;
14850         if (!used)
14851                 return 0;
14852         if (!user)
14853                 return 0;
14854         ptr = head;
14855         while(*ptr) {
14856                 if ((*ptr)->member == user) {
14857                         return 0;
14858                 }
14859                 ptr = &(*ptr)->next;
14860         }
14861         new = xcmalloc(sizeof(*new), "block_set");
14862         new->member = user;
14863         if (front) {
14864                 new->next = *head;
14865                 *head = new;
14866         }
14867         else {
14868                 new->next = 0;
14869                 *ptr = new;
14870         }
14871         return 1;
14872 }
14873 static int do_unuse_block(
14874         struct block *used, struct block_set **head, struct block *unuser)
14875 {
14876         struct block_set *use, **ptr;
14877         int count;
14878         count = 0;
14879         ptr = head;
14880         while(*ptr) {
14881                 use = *ptr;
14882                 if (use->member == unuser) {
14883                         *ptr = use->next;
14884                         memset(use, -1, sizeof(*use));
14885                         xfree(use);
14886                         count += 1;
14887                 }
14888                 else {
14889                         ptr = &use->next;
14890                 }
14891         }
14892         return count;
14893 }
14894
14895 static void use_block(struct block *used, struct block *user)
14896 {
14897         int count;
14898         /* Append new to the head of the list, print_block
14899          * depends on this.
14900          */
14901         count = do_use_block(used, &used->use, user, 1); 
14902         used->users += count;
14903 }
14904 static void unuse_block(struct block *used, struct block *unuser)
14905 {
14906         int count;
14907         count = do_unuse_block(used, &used->use, unuser); 
14908         used->users -= count;
14909 }
14910
14911 static void add_block_edge(struct block *block, struct block *edge, int front)
14912 {
14913         int count;
14914         count = do_use_block(block, &block->edges, edge, front);
14915         block->edge_count += count;
14916 }
14917
14918 static void remove_block_edge(struct block *block, struct block *edge)
14919 {
14920         int count;
14921         count = do_unuse_block(block, &block->edges, edge);
14922         block->edge_count -= count;
14923 }
14924
14925 static void idom_block(struct block *idom, struct block *user)
14926 {
14927         do_use_block(idom, &idom->idominates, user, 0);
14928 }
14929
14930 static void unidom_block(struct block *idom, struct block *unuser)
14931 {
14932         do_unuse_block(idom, &idom->idominates, unuser);
14933 }
14934
14935 static void domf_block(struct block *block, struct block *domf)
14936 {
14937         do_use_block(block, &block->domfrontier, domf, 0);
14938 }
14939
14940 static void undomf_block(struct block *block, struct block *undomf)
14941 {
14942         do_unuse_block(block, &block->domfrontier, undomf);
14943 }
14944
14945 static void ipdom_block(struct block *ipdom, struct block *user)
14946 {
14947         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14948 }
14949
14950 static void unipdom_block(struct block *ipdom, struct block *unuser)
14951 {
14952         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14953 }
14954
14955 static void ipdomf_block(struct block *block, struct block *ipdomf)
14956 {
14957         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
14958 }
14959
14960 static void unipdomf_block(struct block *block, struct block *unipdomf)
14961 {
14962         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
14963 }
14964
14965 static int walk_triples(
14966         struct compile_state *state, 
14967         int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
14968         void *arg)
14969 {
14970         struct triple *ptr;
14971         int result;
14972         ptr = state->first;
14973         do {
14974                 result = cb(state, ptr, arg);
14975                 if (ptr->next->prev != ptr) {
14976                         internal_error(state, ptr->next, "bad prev");
14977                 }
14978                 ptr = ptr->next;
14979         } while((result == 0) && (ptr != state->first));
14980         return result;
14981 }
14982
14983 #define PRINT_LIST 1
14984 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
14985 {
14986         FILE *fp = arg;
14987         int op;
14988         op = ins->op;
14989         if (op == OP_LIST) {
14990 #if !PRINT_LIST
14991                 return 0;
14992 #endif
14993         }
14994         if ((op == OP_LABEL) && (ins->use)) {
14995                 fprintf(fp, "\n%p:\n", ins);
14996         }
14997         display_triple(fp, ins);
14998
14999         if (triple_is_branch(state, ins) && ins->use && 
15000                 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
15001                 internal_error(state, ins, "branch used?");
15002         }
15003         if (triple_is_branch(state, ins)) {
15004                 fprintf(fp, "\n");
15005         }
15006         return 0;
15007 }
15008
15009 static void print_triples(struct compile_state *state)
15010 {
15011         if (state->compiler->debug & DEBUG_TRIPLES) {
15012                 FILE *fp = state->dbgout;
15013                 fprintf(fp, "--------------- triples ---------------\n");
15014                 walk_triples(state, do_print_triple, fp);
15015                 fprintf(fp, "\n");
15016         }
15017 }
15018
15019 struct cf_block {
15020         struct block *block;
15021 };
15022 static void find_cf_blocks(struct cf_block *cf, struct block *block)
15023 {
15024         struct block_set *edge;
15025         if (!block || (cf[block->vertex].block == block)) {
15026                 return;
15027         }
15028         cf[block->vertex].block = block;
15029         for(edge = block->edges; edge; edge = edge->next) {
15030                 find_cf_blocks(cf, edge->member);
15031         }
15032 }
15033
15034 static void print_control_flow(struct compile_state *state,
15035         FILE *fp, struct basic_blocks *bb)
15036 {
15037         struct cf_block *cf;
15038         int i;
15039         fprintf(fp, "\ncontrol flow\n");
15040         cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15041         find_cf_blocks(cf, bb->first_block);
15042
15043         for(i = 1; i <= bb->last_vertex; i++) {
15044                 struct block *block;
15045                 struct block_set *edge;
15046                 block = cf[i].block;
15047                 if (!block)
15048                         continue;
15049                 fprintf(fp, "(%p) %d:", block, block->vertex);
15050                 for(edge = block->edges; edge; edge = edge->next) {
15051                         fprintf(fp, " %d", edge->member->vertex);
15052                 }
15053                 fprintf(fp, "\n");
15054         }
15055
15056         xfree(cf);
15057 }
15058
15059 static void free_basic_block(struct compile_state *state, struct block *block)
15060 {
15061         struct block_set *edge, *entry;
15062         struct block *child;
15063         if (!block) {
15064                 return;
15065         }
15066         if (block->vertex == -1) {
15067                 return;
15068         }
15069         block->vertex = -1;
15070         for(edge = block->edges; edge; edge = edge->next) {
15071                 if (edge->member) {
15072                         unuse_block(edge->member, block);
15073                 }
15074         }
15075         if (block->idom) {
15076                 unidom_block(block->idom, block);
15077         }
15078         block->idom = 0;
15079         if (block->ipdom) {
15080                 unipdom_block(block->ipdom, block);
15081         }
15082         block->ipdom = 0;
15083         while((entry = block->use)) {
15084                 child = entry->member;
15085                 unuse_block(block, child);
15086                 if (child && (child->vertex != -1)) {
15087                         for(edge = child->edges; edge; edge = edge->next) {
15088                                 edge->member = 0;
15089                         }
15090                 }
15091         }
15092         while((entry = block->idominates)) {
15093                 child = entry->member;
15094                 unidom_block(block, child);
15095                 if (child && (child->vertex != -1)) {
15096                         child->idom = 0;
15097                 }
15098         }
15099         while((entry = block->domfrontier)) {
15100                 child = entry->member;
15101                 undomf_block(block, child);
15102         }
15103         while((entry = block->ipdominates)) {
15104                 child = entry->member;
15105                 unipdom_block(block, child);
15106                 if (child && (child->vertex != -1)) {
15107                         child->ipdom = 0;
15108                 }
15109         }
15110         while((entry = block->ipdomfrontier)) {
15111                 child = entry->member;
15112                 unipdomf_block(block, child);
15113         }
15114         if (block->users != 0) {
15115                 internal_error(state, 0, "block still has users");
15116         }
15117         while((edge = block->edges)) {
15118                 child = edge->member;
15119                 remove_block_edge(block, child);
15120                 
15121                 if (child && (child->vertex != -1)) {
15122                         free_basic_block(state, child);
15123                 }
15124         }
15125         memset(block, -1, sizeof(*block));
15126         xfree(block);
15127 }
15128
15129 static void free_basic_blocks(struct compile_state *state, 
15130         struct basic_blocks *bb)
15131 {
15132         struct triple *first, *ins;
15133         free_basic_block(state, bb->first_block);
15134         bb->last_vertex = 0;
15135         bb->first_block = bb->last_block = 0;
15136         first = bb->first;
15137         ins = first;
15138         do {
15139                 if (triple_stores_block(state, ins)) {
15140                         ins->u.block = 0;
15141                 }
15142                 ins = ins->next;
15143         } while(ins != first);
15144         
15145 }
15146
15147 static struct block *basic_block(struct compile_state *state, 
15148         struct basic_blocks *bb, struct triple *first)
15149 {
15150         struct block *block;
15151         struct triple *ptr;
15152         if (!triple_is_label(state, first)) {
15153                 internal_error(state, first, "block does not start with a label");
15154         }
15155         /* See if this basic block has already been setup */
15156         if (first->u.block != 0) {
15157                 return first->u.block;
15158         }
15159         /* Allocate another basic block structure */
15160         bb->last_vertex += 1;
15161         block = xcmalloc(sizeof(*block), "block");
15162         block->first = block->last = first;
15163         block->vertex = bb->last_vertex;
15164         ptr = first;
15165         do {
15166                 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) { 
15167                         break;
15168                 }
15169                 block->last = ptr;
15170                 /* If ptr->u is not used remember where the baic block is */
15171                 if (triple_stores_block(state, ptr)) {
15172                         ptr->u.block = block;
15173                 }
15174                 if (triple_is_branch(state, ptr)) {
15175                         break;
15176                 }
15177                 ptr = ptr->next;
15178         } while (ptr != bb->first);
15179         if ((ptr == bb->first) ||
15180                 ((ptr->next == bb->first) && (
15181                         triple_is_end(state, ptr) || 
15182                         triple_is_ret(state, ptr))))
15183         {
15184                 /* The block has no outflowing edges */
15185         }
15186         else if (triple_is_label(state, ptr)) {
15187                 struct block *next;
15188                 next = basic_block(state, bb, ptr);
15189                 add_block_edge(block, next, 0);
15190                 use_block(next, block);
15191         }
15192         else if (triple_is_branch(state, ptr)) {
15193                 struct triple **expr, *first;
15194                 struct block *child;
15195                 /* Find the branch targets.
15196                  * I special case the first branch as that magically
15197                  * avoids some difficult cases for the register allocator.
15198                  */
15199                 expr = triple_edge_targ(state, ptr, 0);
15200                 if (!expr) {
15201                         internal_error(state, ptr, "branch without targets");
15202                 }
15203                 first = *expr;
15204                 expr = triple_edge_targ(state, ptr, expr);
15205                 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15206                         if (!*expr) continue;
15207                         child = basic_block(state, bb, *expr);
15208                         use_block(child, block);
15209                         add_block_edge(block, child, 0);
15210                 }
15211                 if (first) {
15212                         child = basic_block(state, bb, first);
15213                         use_block(child, block);
15214                         add_block_edge(block, child, 1);
15215
15216                         /* Be certain the return block of a call is
15217                          * in a basic block.  When it is not find
15218                          * start of the block, insert a label if
15219                          * necessary and build the basic block.
15220                          * Then add a fake edge from the start block
15221                          * to the return block of the function.
15222                          */
15223                         if (state->functions_joined && triple_is_call(state, ptr)
15224                                 && !block_of_triple(state, MISC(ptr, 0))) {
15225                                 struct block *tail;
15226                                 struct triple *start;
15227                                 start = triple_to_block_start(state, MISC(ptr, 0));
15228                                 if (!triple_is_label(state, start)) {
15229                                         start = pre_triple(state,
15230                                                 start, OP_LABEL, &void_type, 0, 0);
15231                                 }
15232                                 tail = basic_block(state, bb, start);
15233                                 add_block_edge(child, tail, 0);
15234                                 use_block(tail, child);
15235                         }
15236                 }
15237         }
15238         else {
15239                 internal_error(state, 0, "Bad basic block split");
15240         }
15241 #if 0
15242 {
15243         struct block_set *edge;
15244         FILE *fp = state->errout;
15245         fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15246                 block, block->vertex, 
15247                 block->first, block->last);
15248         for(edge = block->edges; edge; edge = edge->next) {
15249                 fprintf(fp, " %10p [%2d]",
15250                         edge->member ? edge->member->first : 0,
15251                         edge->member ? edge->member->vertex : -1);
15252         }
15253         fprintf(fp, "\n");
15254 }
15255 #endif
15256         return block;
15257 }
15258
15259
15260 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15261         void (*cb)(struct compile_state *state, struct block *block, void *arg),
15262         void *arg)
15263 {
15264         struct triple *ptr, *first;
15265         struct block *last_block;
15266         last_block = 0;
15267         first = bb->first;
15268         ptr = first;
15269         do {
15270                 if (triple_stores_block(state, ptr)) {
15271                         struct block *block;
15272                         block = ptr->u.block;
15273                         if (block && (block != last_block)) {
15274                                 cb(state, block, arg);
15275                         }
15276                         last_block = block;
15277                 }
15278                 ptr = ptr->next;
15279         } while(ptr != first);
15280 }
15281
15282 static void print_block(
15283         struct compile_state *state, struct block *block, void *arg)
15284 {
15285         struct block_set *user, *edge;
15286         struct triple *ptr;
15287         FILE *fp = arg;
15288
15289         fprintf(fp, "\nblock: %p (%d) ",
15290                 block, 
15291                 block->vertex);
15292
15293         for(edge = block->edges; edge; edge = edge->next) {
15294                 fprintf(fp, " %p<-%p",
15295                         edge->member,
15296                         (edge->member && edge->member->use)?
15297                         edge->member->use->member : 0);
15298         }
15299         fprintf(fp, "\n");
15300         if (block->first->op == OP_LABEL) {
15301                 fprintf(fp, "%p:\n", block->first);
15302         }
15303         for(ptr = block->first; ; ) {
15304                 display_triple(fp, ptr);
15305                 if (ptr == block->last)
15306                         break;
15307                 ptr = ptr->next;
15308                 if (ptr == block->first) {
15309                         internal_error(state, 0, "missing block last?");
15310                 }
15311         }
15312         fprintf(fp, "users %d: ", block->users);
15313         for(user = block->use; user; user = user->next) {
15314                 fprintf(fp, "%p (%d) ", 
15315                         user->member,
15316                         user->member->vertex);
15317         }
15318         fprintf(fp,"\n\n");
15319 }
15320
15321
15322 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15323 {
15324         fprintf(fp, "--------------- blocks ---------------\n");
15325         walk_blocks(state, &state->bb, print_block, fp);
15326 }
15327 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15328 {
15329         static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb);
15330         static void print_dominance_frontiers(struct compile_state *state, FILE *fp, struct basic_blocks *bb);
15331         if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15332                 fprintf(fp, "After %s\n", func);
15333                 romcc_print_blocks(state, fp);
15334                 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15335                         print_dominators(state, fp, &state->bb);
15336                         print_dominance_frontiers(state, fp, &state->bb);
15337                 }
15338                 print_control_flow(state, fp, &state->bb);
15339         }
15340 }
15341
15342 static void prune_nonblock_triples(struct compile_state *state, 
15343         struct basic_blocks *bb)
15344 {
15345         struct block *block;
15346         struct triple *first, *ins, *next;
15347         /* Delete the triples not in a basic block */
15348         block = 0;
15349         first = bb->first;
15350         ins = first;
15351         do {
15352                 next = ins->next;
15353                 if (ins->op == OP_LABEL) {
15354                         block = ins->u.block;
15355                 }
15356                 if (!block) {
15357                         struct triple_set *use;
15358                         for(use = ins->use; use; use = use->next) {
15359                                 struct block *block;
15360                                 block = block_of_triple(state, use->member);
15361                                 if (block != 0) {
15362                                         internal_error(state, ins, "pruning used ins?");
15363                                 }
15364                         }
15365                         release_triple(state, ins);
15366                 }
15367                 if (block && block->last == ins) {
15368                         block = 0;
15369                 }
15370                 ins = next;
15371         } while(ins != first);
15372 }
15373
15374 static void setup_basic_blocks(struct compile_state *state, 
15375         struct basic_blocks *bb)
15376 {
15377         if (!triple_stores_block(state, bb->first)) {
15378                 internal_error(state, 0, "ins will not store block?");
15379         }
15380         /* Initialize the state */
15381         bb->first_block = bb->last_block = 0;
15382         bb->last_vertex = 0;
15383         free_basic_blocks(state, bb);
15384
15385         /* Find the basic blocks */
15386         bb->first_block = basic_block(state, bb, bb->first);
15387
15388         /* Be certain the last instruction of a function, or the
15389          * entire program is in a basic block.  When it is not find 
15390          * the start of the block, insert a label if necessary and build 
15391          * basic block.  Then add a fake edge from the start block
15392          * to the final block.
15393          */
15394         if (!block_of_triple(state, bb->first->prev)) {
15395                 struct triple *start;
15396                 struct block *tail;
15397                 start = triple_to_block_start(state, bb->first->prev);
15398                 if (!triple_is_label(state, start)) {
15399                         start = pre_triple(state,
15400                                 start, OP_LABEL, &void_type, 0, 0);
15401                 }
15402                 tail = basic_block(state, bb, start);
15403                 add_block_edge(bb->first_block, tail, 0);
15404                 use_block(tail, bb->first_block);
15405         }
15406         
15407         /* Find the last basic block.
15408          */
15409         bb->last_block = block_of_triple(state, bb->first->prev);
15410
15411         /* Delete the triples not in a basic block */
15412         prune_nonblock_triples(state, bb);
15413
15414 #if 0
15415         /* If we are debugging print what I have just done */
15416         if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15417                 print_blocks(state, state->dbgout);
15418                 print_control_flow(state, bb);
15419         }
15420 #endif
15421 }
15422
15423
15424 struct sdom_block {
15425         struct block *block;
15426         struct sdom_block *sdominates;
15427         struct sdom_block *sdom_next;
15428         struct sdom_block *sdom;
15429         struct sdom_block *label;
15430         struct sdom_block *parent;
15431         struct sdom_block *ancestor;
15432         int vertex;
15433 };
15434
15435
15436 static void unsdom_block(struct sdom_block *block)
15437 {
15438         struct sdom_block **ptr;
15439         if (!block->sdom_next) {
15440                 return;
15441         }
15442         ptr = &block->sdom->sdominates;
15443         while(*ptr) {
15444                 if ((*ptr) == block) {
15445                         *ptr = block->sdom_next;
15446                         return;
15447                 }
15448                 ptr = &(*ptr)->sdom_next;
15449         }
15450 }
15451
15452 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15453 {
15454         unsdom_block(block);
15455         block->sdom = sdom;
15456         block->sdom_next = sdom->sdominates;
15457         sdom->sdominates = block;
15458 }
15459
15460
15461
15462 static int initialize_sdblock(struct sdom_block *sd,
15463         struct block *parent, struct block *block, int vertex)
15464 {
15465         struct block_set *edge;
15466         if (!block || (sd[block->vertex].block == block)) {
15467                 return vertex;
15468         }
15469         vertex += 1;
15470         /* Renumber the blocks in a convinient fashion */
15471         block->vertex = vertex;
15472         sd[vertex].block    = block;
15473         sd[vertex].sdom     = &sd[vertex];
15474         sd[vertex].label    = &sd[vertex];
15475         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
15476         sd[vertex].ancestor = 0;
15477         sd[vertex].vertex   = vertex;
15478         for(edge = block->edges; edge; edge = edge->next) {
15479                 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15480         }
15481         return vertex;
15482 }
15483
15484 static int initialize_spdblock(
15485         struct compile_state *state, struct sdom_block *sd,
15486         struct block *parent, struct block *block, int vertex)
15487 {
15488         struct block_set *user;
15489         if (!block || (sd[block->vertex].block == block)) {
15490                 return vertex;
15491         }
15492         vertex += 1;
15493         /* Renumber the blocks in a convinient fashion */
15494         block->vertex = vertex;
15495         sd[vertex].block    = block;
15496         sd[vertex].sdom     = &sd[vertex];
15497         sd[vertex].label    = &sd[vertex];
15498         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
15499         sd[vertex].ancestor = 0;
15500         sd[vertex].vertex   = vertex;
15501         for(user = block->use; user; user = user->next) {
15502                 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15503         }
15504         return vertex;
15505 }
15506
15507 static int setup_spdblocks(struct compile_state *state, 
15508         struct basic_blocks *bb, struct sdom_block *sd)
15509 {
15510         struct block *block;
15511         int vertex;
15512         /* Setup as many sdpblocks as possible without using fake edges */
15513         vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15514
15515         /* Walk through the graph and find unconnected blocks.  Add a
15516          * fake edge from the unconnected blocks to the end of the
15517          * graph. 
15518          */
15519         block = bb->first_block->last->next->u.block;
15520         for(; block && block != bb->first_block; block = block->last->next->u.block) {
15521                 if (sd[block->vertex].block == block) {
15522                         continue;
15523                 }
15524 #if DEBUG_SDP_BLOCKS
15525                 {
15526                         FILE *fp = state->errout;
15527                         fprintf(fp, "Adding %d\n", vertex +1);
15528                 }
15529 #endif
15530                 add_block_edge(block, bb->last_block, 0);
15531                 use_block(bb->last_block, block);
15532
15533                 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15534         }
15535         return vertex;
15536 }
15537
15538 static void compress_ancestors(struct sdom_block *v)
15539 {
15540         /* This procedure assumes ancestor(v) != 0 */
15541         /* if (ancestor(ancestor(v)) != 0) {
15542          *      compress(ancestor(ancestor(v)));
15543          *      if (semi(label(ancestor(v))) < semi(label(v))) {
15544          *              label(v) = label(ancestor(v));
15545          *      }
15546          *      ancestor(v) = ancestor(ancestor(v));
15547          * }
15548          */
15549         if (!v->ancestor) {
15550                 return;
15551         }
15552         if (v->ancestor->ancestor) {
15553                 compress_ancestors(v->ancestor->ancestor);
15554                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15555                         v->label = v->ancestor->label;
15556                 }
15557                 v->ancestor = v->ancestor->ancestor;
15558         }
15559 }
15560
15561 static void compute_sdom(struct compile_state *state, 
15562         struct basic_blocks *bb, struct sdom_block *sd)
15563 {
15564         int i;
15565         /* // step 2 
15566          *  for each v <= pred(w) {
15567          *      u = EVAL(v);
15568          *      if (semi[u] < semi[w] { 
15569          *              semi[w] = semi[u]; 
15570          *      } 
15571          * }
15572          * add w to bucket(vertex(semi[w]));
15573          * LINK(parent(w), w);
15574          *
15575          * // step 3
15576          * for each v <= bucket(parent(w)) {
15577          *      delete v from bucket(parent(w));
15578          *      u = EVAL(v);
15579          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15580          * }
15581          */
15582         for(i = bb->last_vertex; i >= 2; i--) {
15583                 struct sdom_block *v, *parent, *next;
15584                 struct block_set *user;
15585                 struct block *block;
15586                 block = sd[i].block;
15587                 parent = sd[i].parent;
15588                 /* Step 2 */
15589                 for(user = block->use; user; user = user->next) {
15590                         struct sdom_block *v, *u;
15591                         v = &sd[user->member->vertex];
15592                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15593                         if (u->sdom->vertex < sd[i].sdom->vertex) {
15594                                 sd[i].sdom = u->sdom;
15595                         }
15596                 }
15597                 sdom_block(sd[i].sdom, &sd[i]);
15598                 sd[i].ancestor = parent;
15599                 /* Step 3 */
15600                 for(v = parent->sdominates; v; v = next) {
15601                         struct sdom_block *u;
15602                         next = v->sdom_next;
15603                         unsdom_block(v);
15604                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15605                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
15606                                 u->block : parent->block;
15607                 }
15608         }
15609 }
15610
15611 static void compute_spdom(struct compile_state *state, 
15612         struct basic_blocks *bb, struct sdom_block *sd)
15613 {
15614         int i;
15615         /* // step 2 
15616          *  for each v <= pred(w) {
15617          *      u = EVAL(v);
15618          *      if (semi[u] < semi[w] { 
15619          *              semi[w] = semi[u]; 
15620          *      } 
15621          * }
15622          * add w to bucket(vertex(semi[w]));
15623          * LINK(parent(w), w);
15624          *
15625          * // step 3
15626          * for each v <= bucket(parent(w)) {
15627          *      delete v from bucket(parent(w));
15628          *      u = EVAL(v);
15629          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15630          * }
15631          */
15632         for(i = bb->last_vertex; i >= 2; i--) {
15633                 struct sdom_block *u, *v, *parent, *next;
15634                 struct block_set *edge;
15635                 struct block *block;
15636                 block = sd[i].block;
15637                 parent = sd[i].parent;
15638                 /* Step 2 */
15639                 for(edge = block->edges; edge; edge = edge->next) {
15640                         v = &sd[edge->member->vertex];
15641                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15642                         if (u->sdom->vertex < sd[i].sdom->vertex) {
15643                                 sd[i].sdom = u->sdom;
15644                         }
15645                 }
15646                 sdom_block(sd[i].sdom, &sd[i]);
15647                 sd[i].ancestor = parent;
15648                 /* Step 3 */
15649                 for(v = parent->sdominates; v; v = next) {
15650                         struct sdom_block *u;
15651                         next = v->sdom_next;
15652                         unsdom_block(v);
15653                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15654                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
15655                                 u->block : parent->block;
15656                 }
15657         }
15658 }
15659
15660 static void compute_idom(struct compile_state *state, 
15661         struct basic_blocks *bb, struct sdom_block *sd)
15662 {
15663         int i;
15664         for(i = 2; i <= bb->last_vertex; i++) {
15665                 struct block *block;
15666                 block = sd[i].block;
15667                 if (block->idom->vertex != sd[i].sdom->vertex) {
15668                         block->idom = block->idom->idom;
15669                 }
15670                 idom_block(block->idom, block);
15671         }
15672         sd[1].block->idom = 0;
15673 }
15674
15675 static void compute_ipdom(struct compile_state *state, 
15676         struct basic_blocks *bb, struct sdom_block *sd)
15677 {
15678         int i;
15679         for(i = 2; i <= bb->last_vertex; i++) {
15680                 struct block *block;
15681                 block = sd[i].block;
15682                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15683                         block->ipdom = block->ipdom->ipdom;
15684                 }
15685                 ipdom_block(block->ipdom, block);
15686         }
15687         sd[1].block->ipdom = 0;
15688 }
15689
15690         /* Theorem 1:
15691          *   Every vertex of a flowgraph G = (V, E, r) except r has
15692          *   a unique immediate dominator.  
15693          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15694          *   rooted at r, called the dominator tree of G, such that 
15695          *   v dominates w if and only if v is a proper ancestor of w in
15696          *   the dominator tree.
15697          */
15698         /* Lemma 1:  
15699          *   If v and w are vertices of G such that v <= w,
15700          *   than any path from v to w must contain a common ancestor
15701          *   of v and w in T.
15702          */
15703         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
15704         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
15705         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
15706         /* Theorem 2:
15707          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
15708          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
15709          */
15710         /* Theorem 3:
15711          *   Let w != r and let u be a vertex for which sdom(u) is 
15712          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
15713          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15714          */
15715         /* Lemma 5:  Let vertices v,w satisfy v -> w.
15716          *           Then v -> idom(w) or idom(w) -> idom(v)
15717          */
15718
15719 static void find_immediate_dominators(struct compile_state *state,
15720         struct basic_blocks *bb)
15721 {
15722         struct sdom_block *sd;
15723         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15724          *           vi > w for (1 <= i <= k - 1}
15725          */
15726         /* Theorem 4:
15727          *   For any vertex w != r.
15728          *   sdom(w) = min(
15729          *                 {v|(v,w) <= E  and v < w } U 
15730          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15731          */
15732         /* Corollary 1:
15733          *   Let w != r and let u be a vertex for which sdom(u) is 
15734          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
15735          *   Then:
15736          *                   { sdom(w) if sdom(w) = sdom(u),
15737          *        idom(w) = {
15738          *                   { idom(u) otherwise
15739          */
15740         /* The algorithm consists of the following 4 steps.
15741          * Step 1.  Carry out a depth-first search of the problem graph.  
15742          *    Number the vertices from 1 to N as they are reached during
15743          *    the search.  Initialize the variables used in succeeding steps.
15744          * Step 2.  Compute the semidominators of all vertices by applying
15745          *    theorem 4.   Carry out the computation vertex by vertex in
15746          *    decreasing order by number.
15747          * Step 3.  Implicitly define the immediate dominator of each vertex
15748          *    by applying Corollary 1.
15749          * Step 4.  Explicitly define the immediate dominator of each vertex,
15750          *    carrying out the computation vertex by vertex in increasing order
15751          *    by number.
15752          */
15753         /* Step 1 initialize the basic block information */
15754         sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15755         initialize_sdblock(sd, 0, bb->first_block, 0);
15756 #if 0
15757         sd[1].size  = 0;
15758         sd[1].label = 0;
15759         sd[1].sdom  = 0;
15760 #endif
15761         /* Step 2 compute the semidominators */
15762         /* Step 3 implicitly define the immediate dominator of each vertex */
15763         compute_sdom(state, bb, sd);
15764         /* Step 4 explicitly define the immediate dominator of each vertex */
15765         compute_idom(state, bb, sd);
15766         xfree(sd);
15767 }
15768
15769 static void find_post_dominators(struct compile_state *state,
15770         struct basic_blocks *bb)
15771 {
15772         struct sdom_block *sd;
15773         int vertex;
15774         /* Step 1 initialize the basic block information */
15775         sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15776
15777         vertex = setup_spdblocks(state, bb, sd);
15778         if (vertex != bb->last_vertex) {
15779                 internal_error(state, 0, "missing %d blocks",
15780                         bb->last_vertex - vertex);
15781         }
15782
15783         /* Step 2 compute the semidominators */
15784         /* Step 3 implicitly define the immediate dominator of each vertex */
15785         compute_spdom(state, bb, sd);
15786         /* Step 4 explicitly define the immediate dominator of each vertex */
15787         compute_ipdom(state, bb, sd);
15788         xfree(sd);
15789 }
15790
15791
15792
15793 static void find_block_domf(struct compile_state *state, struct block *block)
15794 {
15795         struct block *child;
15796         struct block_set *user, *edge;
15797         if (block->domfrontier != 0) {
15798                 internal_error(state, block->first, "domfrontier present?");
15799         }
15800         for(user = block->idominates; user; user = user->next) {
15801                 child = user->member;
15802                 if (child->idom != block) {
15803                         internal_error(state, block->first, "bad idom");
15804                 }
15805                 find_block_domf(state, child);
15806         }
15807         for(edge = block->edges; edge; edge = edge->next) {
15808                 if (edge->member->idom != block) {
15809                         domf_block(block, edge->member);
15810                 }
15811         }
15812         for(user = block->idominates; user; user = user->next) {
15813                 struct block_set *frontier;
15814                 child = user->member;
15815                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15816                         if (frontier->member->idom != block) {
15817                                 domf_block(block, frontier->member);
15818                         }
15819                 }
15820         }
15821 }
15822
15823 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15824 {
15825         struct block *child;
15826         struct block_set *user;
15827         if (block->ipdomfrontier != 0) {
15828                 internal_error(state, block->first, "ipdomfrontier present?");
15829         }
15830         for(user = block->ipdominates; user; user = user->next) {
15831                 child = user->member;
15832                 if (child->ipdom != block) {
15833                         internal_error(state, block->first, "bad ipdom");
15834                 }
15835                 find_block_ipdomf(state, child);
15836         }
15837         for(user = block->use; user; user = user->next) {
15838                 if (user->member->ipdom != block) {
15839                         ipdomf_block(block, user->member);
15840                 }
15841         }
15842         for(user = block->ipdominates; user; user = user->next) {
15843                 struct block_set *frontier;
15844                 child = user->member;
15845                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15846                         if (frontier->member->ipdom != block) {
15847                                 ipdomf_block(block, frontier->member);
15848                         }
15849                 }
15850         }
15851 }
15852
15853 static void print_dominated(
15854         struct compile_state *state, struct block *block, void *arg)
15855 {
15856         struct block_set *user;
15857         FILE *fp = arg;
15858
15859         fprintf(fp, "%d:", block->vertex);
15860         for(user = block->idominates; user; user = user->next) {
15861                 fprintf(fp, " %d", user->member->vertex);
15862                 if (user->member->idom != block) {
15863                         internal_error(state, user->member->first, "bad idom");
15864                 }
15865         }
15866         fprintf(fp,"\n");
15867 }
15868
15869 static void print_dominated2(
15870         struct compile_state *state, FILE *fp, int depth, struct block *block)
15871 {
15872         struct block_set *user;
15873         struct triple *ins;
15874         struct occurance *ptr, *ptr2;
15875         const char *filename1, *filename2;
15876         int equal_filenames;
15877         int i;
15878         for(i = 0; i < depth; i++) {
15879                 fprintf(fp, "   ");
15880         }
15881         fprintf(fp, "%3d: %p (%p - %p) @", 
15882                 block->vertex, block, block->first, block->last);
15883         ins = block->first;
15884         while(ins != block->last && (ins->occurance->line == 0)) {
15885                 ins = ins->next;
15886         }
15887         ptr = ins->occurance;
15888         ptr2 = block->last->occurance;
15889         filename1 = ptr->filename? ptr->filename : "";
15890         filename2 = ptr2->filename? ptr2->filename : "";
15891         equal_filenames = (strcmp(filename1, filename2) == 0);
15892         if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15893                 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15894         } else if (equal_filenames) {
15895                 fprintf(fp, " %s:(%d - %d)",
15896                         ptr->filename, ptr->line, ptr2->line);
15897         } else {
15898                 fprintf(fp, " (%s:%d - %s:%d)",
15899                         ptr->filename, ptr->line,
15900                         ptr2->filename, ptr2->line);
15901         }
15902         fprintf(fp, "\n");
15903         for(user = block->idominates; user; user = user->next) {
15904                 print_dominated2(state, fp, depth + 1, user->member);
15905         }
15906 }
15907
15908 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15909 {
15910         fprintf(fp, "\ndominates\n");
15911         walk_blocks(state, bb, print_dominated, fp);
15912         fprintf(fp, "dominates\n");
15913         print_dominated2(state, fp, 0, bb->first_block);
15914 }
15915
15916
15917 static int print_frontiers(
15918         struct compile_state *state, FILE *fp, struct block *block, int vertex)
15919 {
15920         struct block_set *user, *edge;
15921
15922         if (!block || (block->vertex != vertex + 1)) {
15923                 return vertex;
15924         }
15925         vertex += 1;
15926
15927         fprintf(fp, "%d:", block->vertex);
15928         for(user = block->domfrontier; user; user = user->next) {
15929                 fprintf(fp, " %d", user->member->vertex);
15930         }
15931         fprintf(fp, "\n");
15932         
15933         for(edge = block->edges; edge; edge = edge->next) {
15934                 vertex = print_frontiers(state, fp, edge->member, vertex);
15935         }
15936         return vertex;
15937 }
15938 static void print_dominance_frontiers(struct compile_state *state,
15939         FILE *fp, struct basic_blocks *bb)
15940 {
15941         fprintf(fp, "\ndominance frontiers\n");
15942         print_frontiers(state, fp, bb->first_block, 0);
15943         
15944 }
15945
15946 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15947 {
15948         /* Find the immediate dominators */
15949         find_immediate_dominators(state, bb);
15950         /* Find the dominance frontiers */
15951         find_block_domf(state, bb->first_block);
15952         /* If debuging print the print what I have just found */
15953         if (state->compiler->debug & DEBUG_FDOMINATORS) {
15954                 print_dominators(state, state->dbgout, bb);
15955                 print_dominance_frontiers(state, state->dbgout, bb);
15956                 print_control_flow(state, state->dbgout, bb);
15957         }
15958 }
15959
15960
15961 static void print_ipdominated(
15962         struct compile_state *state, struct block *block, void *arg)
15963 {
15964         struct block_set *user;
15965         FILE *fp = arg;
15966
15967         fprintf(fp, "%d:", block->vertex);
15968         for(user = block->ipdominates; user; user = user->next) {
15969                 fprintf(fp, " %d", user->member->vertex);
15970                 if (user->member->ipdom != block) {
15971                         internal_error(state, user->member->first, "bad ipdom");
15972                 }
15973         }
15974         fprintf(fp, "\n");
15975 }
15976
15977 static void print_ipdominators(struct compile_state *state, FILE *fp,
15978         struct basic_blocks *bb)
15979 {
15980         fprintf(fp, "\nipdominates\n");
15981         walk_blocks(state, bb, print_ipdominated, fp);
15982 }
15983
15984 static int print_pfrontiers(
15985         struct compile_state *state, FILE *fp, struct block *block, int vertex)
15986 {
15987         struct block_set *user;
15988
15989         if (!block || (block->vertex != vertex + 1)) {
15990                 return vertex;
15991         }
15992         vertex += 1;
15993
15994         fprintf(fp, "%d:", block->vertex);
15995         for(user = block->ipdomfrontier; user; user = user->next) {
15996                 fprintf(fp, " %d", user->member->vertex);
15997         }
15998         fprintf(fp, "\n");
15999         for(user = block->use; user; user = user->next) {
16000                 vertex = print_pfrontiers(state, fp, user->member, vertex);
16001         }
16002         return vertex;
16003 }
16004 static void print_ipdominance_frontiers(struct compile_state *state,
16005         FILE *fp, struct basic_blocks *bb)
16006 {
16007         fprintf(fp, "\nipdominance frontiers\n");
16008         print_pfrontiers(state, fp, bb->last_block, 0);
16009         
16010 }
16011
16012 static void analyze_ipdominators(struct compile_state *state,
16013         struct basic_blocks *bb)
16014 {
16015         /* Find the post dominators */
16016         find_post_dominators(state, bb);
16017         /* Find the control dependencies (post dominance frontiers) */
16018         find_block_ipdomf(state, bb->last_block);
16019         /* If debuging print the print what I have just found */
16020         if (state->compiler->debug & DEBUG_RDOMINATORS) {
16021                 print_ipdominators(state, state->dbgout, bb);
16022                 print_ipdominance_frontiers(state, state->dbgout, bb);
16023                 print_control_flow(state, state->dbgout, bb);
16024         }
16025 }
16026
16027 static int bdominates(struct compile_state *state,
16028         struct block *dom, struct block *sub)
16029 {
16030         while(sub && (sub != dom)) {
16031                 sub = sub->idom;
16032         }
16033         return sub == dom;
16034 }
16035
16036 static int tdominates(struct compile_state *state,
16037         struct triple *dom, struct triple *sub)
16038 {
16039         struct block *bdom, *bsub;
16040         int result;
16041         bdom = block_of_triple(state, dom);
16042         bsub = block_of_triple(state, sub);
16043         if (bdom != bsub) {
16044                 result = bdominates(state, bdom, bsub);
16045         } 
16046         else {
16047                 struct triple *ins;
16048                 if (!bdom || !bsub) {
16049                         internal_error(state, dom, "huh?");
16050                 }
16051                 ins = sub;
16052                 while((ins != bsub->first) && (ins != dom)) {
16053                         ins = ins->prev;
16054                 }
16055                 result = (ins == dom);
16056         }
16057         return result;
16058 }
16059
16060 static void analyze_basic_blocks(
16061         struct compile_state *state, struct basic_blocks *bb)
16062 {
16063         setup_basic_blocks(state, bb);
16064         analyze_idominators(state, bb);
16065         analyze_ipdominators(state, bb);
16066 }
16067
16068 static void insert_phi_operations(struct compile_state *state)
16069 {
16070         size_t size;
16071         struct triple *first;
16072         int *has_already, *work;
16073         struct block *work_list, **work_list_tail;
16074         int iter;
16075         struct triple *var, *vnext;
16076
16077         size = sizeof(int) * (state->bb.last_vertex + 1);
16078         has_already = xcmalloc(size, "has_already");
16079         work =        xcmalloc(size, "work");
16080         iter = 0;
16081
16082         first = state->first;
16083         for(var = first->next; var != first ; var = vnext) {
16084                 struct block *block;
16085                 struct triple_set *user, *unext;
16086                 vnext = var->next;
16087
16088                 if (!triple_is_auto_var(state, var) || !var->use) {
16089                         continue;
16090                 }
16091                         
16092                 iter += 1;
16093                 work_list = 0;
16094                 work_list_tail = &work_list;
16095                 for(user = var->use; user; user = unext) {
16096                         unext = user->next;
16097                         if (MISC(var, 0) == user->member) {
16098                                 continue;
16099                         }
16100                         if (user->member->op == OP_READ) {
16101                                 continue;
16102                         }
16103                         if (user->member->op != OP_WRITE) {
16104                                 internal_error(state, user->member, 
16105                                         "bad variable access");
16106                         }
16107                         block = user->member->u.block;
16108                         if (!block) {
16109                                 warning(state, user->member, "dead code");
16110                                 release_triple(state, user->member);
16111                                 continue;
16112                         }
16113                         if (work[block->vertex] >= iter) {
16114                                 continue;
16115                         }
16116                         work[block->vertex] = iter;
16117                         *work_list_tail = block;
16118                         block->work_next = 0;
16119                         work_list_tail = &block->work_next;
16120                 }
16121                 for(block = work_list; block; block = block->work_next) {
16122                         struct block_set *df;
16123                         for(df = block->domfrontier; df; df = df->next) {
16124                                 struct triple *phi;
16125                                 struct block *front;
16126                                 int in_edges;
16127                                 front = df->member;
16128
16129                                 if (has_already[front->vertex] >= iter) {
16130                                         continue;
16131                                 }
16132                                 /* Count how many edges flow into this block */
16133                                 in_edges = front->users;
16134                                 /* Insert a phi function for this variable */
16135                                 get_occurance(var->occurance);
16136                                 phi = alloc_triple(
16137                                         state, OP_PHI, var->type, -1, in_edges, 
16138                                         var->occurance);
16139                                 phi->u.block = front;
16140                                 MISC(phi, 0) = var;
16141                                 use_triple(var, phi);
16142 #if 1
16143                                 if (phi->rhs != in_edges) {
16144                                         internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16145                                                 phi->rhs, in_edges);
16146                                 }
16147 #endif
16148                                 /* Insert the phi functions immediately after the label */
16149                                 insert_triple(state, front->first->next, phi);
16150                                 if (front->first == front->last) {
16151                                         front->last = front->first->next;
16152                                 }
16153                                 has_already[front->vertex] = iter;
16154                                 transform_to_arch_instruction(state, phi);
16155
16156                                 /* If necessary plan to visit the basic block */
16157                                 if (work[front->vertex] >= iter) {
16158                                         continue;
16159                                 }
16160                                 work[front->vertex] = iter;
16161                                 *work_list_tail = front;
16162                                 front->work_next = 0;
16163                                 work_list_tail = &front->work_next;
16164                         }
16165                 }
16166         }
16167         xfree(has_already);
16168         xfree(work);
16169 }
16170
16171
16172 struct stack {
16173         struct triple_set *top;
16174         unsigned orig_id;
16175 };
16176
16177 static int count_auto_vars(struct compile_state *state)
16178 {
16179         struct triple *first, *ins;
16180         int auto_vars = 0;
16181         first = state->first;
16182         ins = first;
16183         do {
16184                 if (triple_is_auto_var(state, ins)) {
16185                         auto_vars += 1;
16186                 }
16187                 ins = ins->next;
16188         } while(ins != first);
16189         return auto_vars;
16190 }
16191
16192 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16193 {
16194         struct triple *first, *ins;
16195         int auto_vars = 0;
16196         first = state->first;
16197         ins = first;
16198         do {
16199                 if (triple_is_auto_var(state, ins)) {
16200                         auto_vars += 1;
16201                         stacks[auto_vars].orig_id = ins->id;
16202                         ins->id = auto_vars;
16203                 }
16204                 ins = ins->next;
16205         } while(ins != first);
16206 }
16207
16208 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16209 {
16210         struct triple *first, *ins;
16211         first = state->first;
16212         ins = first;
16213         do {
16214                 if (triple_is_auto_var(state, ins)) {
16215                         ins->id = stacks[ins->id].orig_id;
16216                 }
16217                 ins = ins->next;
16218         } while(ins != first);
16219 }
16220
16221 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16222 {
16223         struct triple_set *head;
16224         struct triple *top_val;
16225         top_val = 0;
16226         head = stacks[var->id].top;
16227         if (head) {
16228                 top_val = head->member;
16229         }
16230         return top_val;
16231 }
16232
16233 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16234 {
16235         struct triple_set *new;
16236         /* Append new to the head of the list,
16237          * it's the only sensible behavoir for a stack.
16238          */
16239         new = xcmalloc(sizeof(*new), "triple_set");
16240         new->member = val;
16241         new->next   = stacks[var->id].top;
16242         stacks[var->id].top = new;
16243 }
16244
16245 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16246 {
16247         struct triple_set *set, **ptr;
16248         ptr = &stacks[var->id].top;
16249         while(*ptr) {
16250                 set = *ptr;
16251                 if (set->member == oldval) {
16252                         *ptr = set->next;
16253                         xfree(set);
16254                         /* Only free one occurance from the stack */
16255                         return;
16256                 }
16257                 else {
16258                         ptr = &set->next;
16259                 }
16260         }
16261 }
16262
16263 /*
16264  * C(V)
16265  * S(V)
16266  */
16267 static void fixup_block_phi_variables(
16268         struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16269 {
16270         struct block_set *set;
16271         struct triple *ptr;
16272         int edge;
16273         if (!parent || !block)
16274                 return;
16275         /* Find the edge I am coming in on */
16276         edge = 0;
16277         for(set = block->use; set; set = set->next, edge++) {
16278                 if (set->member == parent) {
16279                         break;
16280                 }
16281         }
16282         if (!set) {
16283                 internal_error(state, 0, "phi input is not on a control predecessor");
16284         }
16285         for(ptr = block->first; ; ptr = ptr->next) {
16286                 if (ptr->op == OP_PHI) {
16287                         struct triple *var, *val, **slot;
16288                         var = MISC(ptr, 0);
16289                         if (!var) {
16290                                 internal_error(state, ptr, "no var???");
16291                         }
16292                         /* Find the current value of the variable */
16293                         val = peek_triple(stacks, var);
16294                         if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16295                                 internal_error(state, val, "bad value in phi");
16296                         }
16297                         if (edge >= ptr->rhs) {
16298                                 internal_error(state, ptr, "edges > phi rhs");
16299                         }
16300                         slot = &RHS(ptr, edge);
16301                         if ((*slot != 0) && (*slot != val)) {
16302                                 internal_error(state, ptr, "phi already bound on this edge");
16303                         }
16304                         *slot = val;
16305                         use_triple(val, ptr);
16306                 }
16307                 if (ptr == block->last) {
16308                         break;
16309                 }
16310         }
16311 }
16312
16313
16314 static void rename_block_variables(
16315         struct compile_state *state, struct stack *stacks, struct block *block)
16316 {
16317         struct block_set *user, *edge;
16318         struct triple *ptr, *next, *last;
16319         int done;
16320         if (!block)
16321                 return;
16322         last = block->first;
16323         done = 0;
16324         for(ptr = block->first; !done; ptr = next) {
16325                 next = ptr->next;
16326                 if (ptr == block->last) {
16327                         done = 1;
16328                 }
16329                 /* RHS(A) */
16330                 if (ptr->op == OP_READ) {
16331                         struct triple *var, *val;
16332                         var = RHS(ptr, 0);
16333                         if (!triple_is_auto_var(state, var)) {
16334                                 internal_error(state, ptr, "read of non auto var!");
16335                         }
16336                         unuse_triple(var, ptr);
16337                         /* Find the current value of the variable */
16338                         val = peek_triple(stacks, var);
16339                         if (!val) {
16340                                 /* Let the optimizer at variables that are not initially
16341                                  * set.  But give it a bogus value so things seem to
16342                                  * work by accident.  This is useful for bitfields because
16343                                  * setting them always involves a read-modify-write.
16344                                  */
16345                                 if (TYPE_ARITHMETIC(ptr->type->type)) {
16346                                         val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16347                                         val->u.cval = 0xdeadbeaf;
16348                                 } else {
16349                                         val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16350                                 }
16351                         }
16352                         if (!val) {
16353                                 error(state, ptr, "variable used without being set");
16354                         }
16355                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16356                                 internal_error(state, val, "bad value in read");
16357                         }
16358                         propogate_use(state, ptr, val);
16359                         release_triple(state, ptr);
16360                         continue;
16361                 }
16362                 /* LHS(A) */
16363                 if (ptr->op == OP_WRITE) {
16364                         struct triple *var, *val, *tval;
16365                         var = MISC(ptr, 0);
16366                         if (!triple_is_auto_var(state, var)) {
16367                                 internal_error(state, ptr, "write to non auto var!");
16368                         }
16369                         tval = val = RHS(ptr, 0);
16370                         if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16371                                 triple_is_auto_var(state, val)) {
16372                                 internal_error(state, ptr, "bad value in write");
16373                         }
16374                         /* Insert a cast if the types differ */
16375                         if (!is_subset_type(ptr->type, val->type)) {
16376                                 if (val->op == OP_INTCONST) {
16377                                         tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16378                                         tval->u.cval = val->u.cval;
16379                                 }
16380                                 else {
16381                                         tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16382                                         use_triple(val, tval);
16383                                 }
16384                                 transform_to_arch_instruction(state, tval);
16385                                 unuse_triple(val, ptr);
16386                                 RHS(ptr, 0) = tval;
16387                                 use_triple(tval, ptr);
16388                         }
16389                         propogate_use(state, ptr, tval);
16390                         unuse_triple(var, ptr);
16391                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
16392                         push_triple(stacks, var, tval);
16393                 }
16394                 if (ptr->op == OP_PHI) {
16395                         struct triple *var;
16396                         var = MISC(ptr, 0);
16397                         if (!triple_is_auto_var(state, var)) {
16398                                 internal_error(state, ptr, "phi references non auto var!");
16399                         }
16400                         /* Push OP_PHI onto a stack of variable uses */
16401                         push_triple(stacks, var, ptr);
16402                 }
16403                 last = ptr;
16404         }
16405         block->last = last;
16406
16407         /* Fixup PHI functions in the cf successors */
16408         for(edge = block->edges; edge; edge = edge->next) {
16409                 fixup_block_phi_variables(state, stacks, block, edge->member);
16410         }
16411         /* rename variables in the dominated nodes */
16412         for(user = block->idominates; user; user = user->next) {
16413                 rename_block_variables(state, stacks, user->member);
16414         }
16415         /* pop the renamed variable stack */
16416         last = block->first;
16417         done = 0;
16418         for(ptr = block->first; !done ; ptr = next) {
16419                 next = ptr->next;
16420                 if (ptr == block->last) {
16421                         done = 1;
16422                 }
16423                 if (ptr->op == OP_WRITE) {
16424                         struct triple *var;
16425                         var = MISC(ptr, 0);
16426                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
16427                         pop_triple(stacks, var, RHS(ptr, 0));
16428                         release_triple(state, ptr);
16429                         continue;
16430                 }
16431                 if (ptr->op == OP_PHI) {
16432                         struct triple *var;
16433                         var = MISC(ptr, 0);
16434                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
16435                         pop_triple(stacks, var, ptr);
16436                 }
16437                 last = ptr;
16438         }
16439         block->last = last;
16440 }
16441
16442 static void rename_variables(struct compile_state *state)
16443 {
16444         struct stack *stacks;
16445         int auto_vars;
16446
16447         /* Allocate stacks for the Variables */
16448         auto_vars = count_auto_vars(state);
16449         stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16450
16451         /* Give each auto_var a stack */
16452         number_auto_vars(state, stacks);
16453
16454         /* Rename the variables */
16455         rename_block_variables(state, stacks, state->bb.first_block);
16456
16457         /* Remove the stacks from the auto_vars */
16458         restore_auto_vars(state, stacks);
16459         xfree(stacks);
16460 }
16461
16462 static void prune_block_variables(struct compile_state *state,
16463         struct block *block)
16464 {
16465         struct block_set *user;
16466         struct triple *next, *ptr;
16467         int done;
16468
16469         done = 0;
16470         for(ptr = block->first; !done; ptr = next) {
16471                 /* Be extremely careful I am deleting the list
16472                  * as I walk trhough it.
16473                  */
16474                 next = ptr->next;
16475                 if (ptr == block->last) {
16476                         done = 1;
16477                 }
16478                 if (triple_is_auto_var(state, ptr)) {
16479                         struct triple_set *user, *next;
16480                         for(user = ptr->use; user; user = next) {
16481                                 struct triple *use;
16482                                 next = user->next;
16483                                 use = user->member;
16484                                 if (MISC(ptr, 0) == user->member) {
16485                                         continue;
16486                                 }
16487                                 if (use->op != OP_PHI) {
16488                                         internal_error(state, use, "decl still used");
16489                                 }
16490                                 if (MISC(use, 0) != ptr) {
16491                                         internal_error(state, use, "bad phi use of decl");
16492                                 }
16493                                 unuse_triple(ptr, use);
16494                                 MISC(use, 0) = 0;
16495                         }
16496                         if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16497                                 /* Delete the adecl */
16498                                 release_triple(state, MISC(ptr, 0));
16499                                 /* And the piece */
16500                                 release_triple(state, ptr);
16501                         }
16502                         continue;
16503                 }
16504         }
16505         for(user = block->idominates; user; user = user->next) {
16506                 prune_block_variables(state, user->member);
16507         }
16508 }
16509
16510 struct phi_triple {
16511         struct triple *phi;
16512         unsigned orig_id;
16513         int alive;
16514 };
16515
16516 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16517 {
16518         struct triple **slot;
16519         int zrhs, i;
16520         if (live[phi->id].alive) {
16521                 return;
16522         }
16523         live[phi->id].alive = 1;
16524         zrhs = phi->rhs;
16525         slot = &RHS(phi, 0);
16526         for(i = 0; i < zrhs; i++) {
16527                 struct triple *used;
16528                 used = slot[i];
16529                 if (used && (used->op == OP_PHI)) {
16530                         keep_phi(state, live, used);
16531                 }
16532         }
16533 }
16534
16535 static void prune_unused_phis(struct compile_state *state)
16536 {
16537         struct triple *first, *phi;
16538         struct phi_triple *live;
16539         int phis, i;
16540         
16541         /* Find the first instruction */
16542         first = state->first;
16543
16544         /* Count how many phi functions I need to process */
16545         phis = 0;
16546         for(phi = first->next; phi != first; phi = phi->next) {
16547                 if (phi->op == OP_PHI) {
16548                         phis += 1;
16549                 }
16550         }
16551         
16552         /* Mark them all dead */
16553         live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16554         phis = 0;
16555         for(phi = first->next; phi != first; phi = phi->next) {
16556                 if (phi->op != OP_PHI) {
16557                         continue;
16558                 }
16559                 live[phis].alive   = 0;
16560                 live[phis].orig_id = phi->id;
16561                 live[phis].phi     = phi;
16562                 phi->id = phis;
16563                 phis += 1;
16564         }
16565         
16566         /* Mark phis alive that are used by non phis */
16567         for(i = 0; i < phis; i++) {
16568                 struct triple_set *set;
16569                 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16570                         if (set->member->op != OP_PHI) {
16571                                 keep_phi(state, live, live[i].phi);
16572                                 break;
16573                         }
16574                 }
16575         }
16576
16577         /* Delete the extraneous phis */
16578         for(i = 0; i < phis; i++) {
16579                 struct triple **slot;
16580                 int zrhs, j;
16581                 if (!live[i].alive) {
16582                         release_triple(state, live[i].phi);
16583                         continue;
16584                 }
16585                 phi = live[i].phi;
16586                 slot = &RHS(phi, 0);
16587                 zrhs = phi->rhs;
16588                 for(j = 0; j < zrhs; j++) {
16589                         if(!slot[j]) {
16590                                 struct triple *unknown;
16591                                 get_occurance(phi->occurance);
16592                                 unknown = flatten(state, state->global_pool,
16593                                         alloc_triple(state, OP_UNKNOWNVAL,
16594                                                 phi->type, 0, 0, phi->occurance));
16595                                 slot[j] = unknown;
16596                                 use_triple(unknown, phi);
16597                                 transform_to_arch_instruction(state, unknown);
16598 #if 0                           
16599                                 warning(state, phi, "variable not set at index %d on all paths to use", j);
16600 #endif
16601                         }
16602                 }
16603         }
16604         xfree(live);
16605 }
16606
16607 static void transform_to_ssa_form(struct compile_state *state)
16608 {
16609         insert_phi_operations(state);
16610         rename_variables(state);
16611
16612         prune_block_variables(state, state->bb.first_block);
16613         prune_unused_phis(state);
16614
16615         print_blocks(state, __func__, state->dbgout);
16616 }
16617
16618
16619 static void clear_vertex(
16620         struct compile_state *state, struct block *block, void *arg)
16621 {
16622         /* Clear the current blocks vertex and the vertex of all
16623          * of the current blocks neighbors in case there are malformed
16624          * blocks with now instructions at this point.
16625          */
16626         struct block_set *user, *edge;
16627         block->vertex = 0;
16628         for(edge = block->edges; edge; edge = edge->next) {
16629                 edge->member->vertex = 0;
16630         }
16631         for(user = block->use; user; user = user->next) {
16632                 user->member->vertex = 0;
16633         }
16634 }
16635
16636 static void mark_live_block(
16637         struct compile_state *state, struct block *block, int *next_vertex)
16638 {
16639         /* See if this is a block that has not been marked */
16640         if (block->vertex != 0) {
16641                 return;
16642         }
16643         block->vertex = *next_vertex;
16644         *next_vertex += 1;
16645         if (triple_is_branch(state, block->last)) {
16646                 struct triple **targ;
16647                 targ = triple_edge_targ(state, block->last, 0);
16648                 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16649                         if (!*targ) {
16650                                 continue;
16651                         }
16652                         if (!triple_stores_block(state, *targ)) {
16653                                 internal_error(state, 0, "bad targ");
16654                         }
16655                         mark_live_block(state, (*targ)->u.block, next_vertex);
16656                 }
16657                 /* Ensure the last block of a function remains alive */
16658                 if (triple_is_call(state, block->last)) {
16659                         mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16660                 }
16661         }
16662         else if (block->last->next != state->first) {
16663                 struct triple *ins;
16664                 ins = block->last->next;
16665                 if (!triple_stores_block(state, ins)) {
16666                         internal_error(state, 0, "bad block start");
16667                 }
16668                 mark_live_block(state, ins->u.block, next_vertex);
16669         }
16670 }
16671
16672 static void transform_from_ssa_form(struct compile_state *state)
16673 {
16674         /* To get out of ssa form we insert moves on the incoming
16675          * edges to blocks containting phi functions.
16676          */
16677         struct triple *first;
16678         struct triple *phi, *var, *next;
16679         int next_vertex;
16680
16681         /* Walk the control flow to see which blocks remain alive */
16682         walk_blocks(state, &state->bb, clear_vertex, 0);
16683         next_vertex = 1;
16684         mark_live_block(state, state->bb.first_block, &next_vertex);
16685
16686         /* Walk all of the operations to find the phi functions */
16687         first = state->first;
16688         for(phi = first->next; phi != first ; phi = next) {
16689                 struct block_set *set;
16690                 struct block *block;
16691                 struct triple **slot;
16692                 struct triple *var;
16693                 struct triple_set *use, *use_next;
16694                 int edge, writers, readers;
16695                 next = phi->next;
16696                 if (phi->op != OP_PHI) {
16697                         continue;
16698                 }
16699
16700                 block = phi->u.block;
16701                 slot  = &RHS(phi, 0);
16702
16703                 /* If this phi is in a dead block just forget it */
16704                 if (block->vertex == 0) {
16705                         release_triple(state, phi);
16706                         continue;
16707                 }
16708
16709                 /* Forget uses from code in dead blocks */
16710                 for(use = phi->use; use; use = use_next) {
16711                         struct block *ublock;
16712                         struct triple **expr;
16713                         use_next = use->next;
16714                         ublock = block_of_triple(state, use->member);
16715                         if ((use->member == phi) || (ublock->vertex != 0)) {
16716                                 continue;
16717                         }
16718                         expr = triple_rhs(state, use->member, 0);
16719                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
16720                                 if (*expr == phi) {
16721                                         *expr = 0;
16722                                 }
16723                         }
16724                         unuse_triple(phi, use->member);
16725                 }
16726                 /* A variable to replace the phi function */
16727                 if (registers_of(state, phi->type) != 1) {
16728                         internal_error(state, phi, "phi->type does not fit in a single register!");
16729                 }
16730                 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16731                 var = var->next; /* point at the var */
16732                         
16733                 /* Replaces use of phi with var */
16734                 propogate_use(state, phi, var);
16735
16736                 /* Count the readers */
16737                 readers = 0;
16738                 for(use = var->use; use; use = use->next) {
16739                         if (use->member != MISC(var, 0)) {
16740                                 readers++;
16741                         }
16742                 }
16743
16744                 /* Walk all of the incoming edges/blocks and insert moves.
16745                  */
16746                 writers = 0;
16747                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16748                         struct block *eblock, *vblock;
16749                         struct triple *move;
16750                         struct triple *val, *base;
16751                         eblock = set->member;
16752                         val = slot[edge];
16753                         slot[edge] = 0;
16754                         unuse_triple(val, phi);
16755                         vblock = block_of_triple(state, val);
16756
16757                         /* If we don't have a value that belongs in an OP_WRITE
16758                          * continue on.
16759                          */
16760                         if (!val || (val == &unknown_triple) || (val == phi)
16761                                 || (vblock && (vblock->vertex == 0))) {
16762                                 continue;
16763                         }
16764                         /* If the value should never occur error */
16765                         if (!vblock) {
16766                                 internal_error(state, val, "no vblock?");
16767                                 continue;
16768                         }
16769
16770                         /* If the value occurs in a dead block see if a replacement
16771                          * block can be found.
16772                          */
16773                         while(eblock && (eblock->vertex == 0)) {
16774                                 eblock = eblock->idom;
16775                         }
16776                         /* If not continue on with the next value. */
16777                         if (!eblock || (eblock->vertex == 0)) {
16778                                 continue;
16779                         }
16780
16781                         /* If we have an empty incoming block ignore it. */
16782                         if (!eblock->first) {
16783                                 internal_error(state, 0, "empty block?");
16784                         }
16785                         
16786                         /* Make certain the write is placed in the edge block... */
16787                         /* Walk through the edge block backwards to find an
16788                          * appropriate location for the OP_WRITE.
16789                          */
16790                         for(base = eblock->last; base != eblock->first; base = base->prev) {
16791                                 struct triple **expr;
16792                                 if (base->op == OP_PIECE) {
16793                                         base = MISC(base, 0);
16794                                 }
16795                                 if ((base == var) || (base == val)) {
16796                                         goto out;
16797                                 }
16798                                 expr = triple_lhs(state, base, 0);
16799                                 for(; expr; expr = triple_lhs(state, base, expr)) {
16800                                         if ((*expr) == val) {
16801                                                 goto out;
16802                                         }
16803                                 }
16804                                 expr = triple_rhs(state, base, 0);
16805                                 for(; expr; expr = triple_rhs(state, base, expr)) {
16806                                         if ((*expr) == var) {
16807                                                 goto out;
16808                                         }
16809                                 }
16810                         }
16811                 out:
16812                         if (triple_is_branch(state, base)) {
16813                                 internal_error(state, base,
16814                                         "Could not insert write to phi");
16815                         }
16816                         move = post_triple(state, base, OP_WRITE, var->type, val, var);
16817                         use_triple(val, move);
16818                         use_triple(var, move);
16819                         writers++;
16820                 }
16821                 if (!writers && readers) {
16822                         internal_error(state, var, "no value written to in use phi?");
16823                 }
16824                 /* If var is not used free it */
16825                 if (!writers) {
16826                         release_triple(state, MISC(var, 0));
16827                         release_triple(state, var);
16828                 }
16829                 /* Release the phi function */
16830                 release_triple(state, phi);
16831         }
16832         
16833         /* Walk all of the operations to find the adecls */
16834         for(var = first->next; var != first ; var = var->next) {
16835                 struct triple_set *use, *use_next;
16836                 if (!triple_is_auto_var(state, var)) {
16837                         continue;
16838                 }
16839
16840                 /* Walk through all of the rhs uses of var and
16841                  * replace them with read of var.
16842                  */
16843                 for(use = var->use; use; use = use_next) {
16844                         struct triple *read, *user;
16845                         struct triple **slot;
16846                         int zrhs, i, used;
16847                         use_next = use->next;
16848                         user = use->member;
16849                         
16850                         /* Generate a read of var */
16851                         read = pre_triple(state, user, OP_READ, var->type, var, 0);
16852                         use_triple(var, read);
16853
16854                         /* Find the rhs uses and see if they need to be replaced */
16855                         used = 0;
16856                         zrhs = user->rhs;
16857                         slot = &RHS(user, 0);
16858                         for(i = 0; i < zrhs; i++) {
16859                                 if (slot[i] == var) {
16860                                         slot[i] = read;
16861                                         used = 1;
16862                                 }
16863                         }
16864                         /* If we did use it cleanup the uses */
16865                         if (used) {
16866                                 unuse_triple(var, user);
16867                                 use_triple(read, user);
16868                         } 
16869                         /* If we didn't use it release the extra triple */
16870                         else {
16871                                 release_triple(state, read);
16872                         }
16873                 }
16874         }
16875 }
16876
16877 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16878         FILE *fp = state->dbgout; \
16879         fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16880         } 
16881
16882 static void rebuild_ssa_form(struct compile_state *state)
16883 {
16884 HI();
16885         transform_from_ssa_form(state);
16886 HI();
16887         state->bb.first = state->first;
16888         free_basic_blocks(state, &state->bb);
16889         analyze_basic_blocks(state, &state->bb);
16890 HI();
16891         insert_phi_operations(state);
16892 HI();
16893         rename_variables(state);
16894 HI();
16895         
16896         prune_block_variables(state, state->bb.first_block);
16897 HI();
16898         prune_unused_phis(state);
16899 HI();
16900 }
16901 #undef HI
16902
16903 /* 
16904  * Register conflict resolution
16905  * =========================================================
16906  */
16907
16908 static struct reg_info find_def_color(
16909         struct compile_state *state, struct triple *def)
16910 {
16911         struct triple_set *set;
16912         struct reg_info info;
16913         info.reg = REG_UNSET;
16914         info.regcm = 0;
16915         if (!triple_is_def(state, def)) {
16916                 return info;
16917         }
16918         info = arch_reg_lhs(state, def, 0);
16919         if (info.reg >= MAX_REGISTERS) {
16920                 info.reg = REG_UNSET;
16921         }
16922         for(set = def->use; set; set = set->next) {
16923                 struct reg_info tinfo;
16924                 int i;
16925                 i = find_rhs_use(state, set->member, def);
16926                 if (i < 0) {
16927                         continue;
16928                 }
16929                 tinfo = arch_reg_rhs(state, set->member, i);
16930                 if (tinfo.reg >= MAX_REGISTERS) {
16931                         tinfo.reg = REG_UNSET;
16932                 }
16933                 if ((tinfo.reg != REG_UNSET) && 
16934                         (info.reg != REG_UNSET) &&
16935                         (tinfo.reg != info.reg)) {
16936                         internal_error(state, def, "register conflict");
16937                 }
16938                 if ((info.regcm & tinfo.regcm) == 0) {
16939                         internal_error(state, def, "regcm conflict %x & %x == 0",
16940                                 info.regcm, tinfo.regcm);
16941                 }
16942                 if (info.reg == REG_UNSET) {
16943                         info.reg = tinfo.reg;
16944                 }
16945                 info.regcm &= tinfo.regcm;
16946         }
16947         if (info.reg >= MAX_REGISTERS) {
16948                 internal_error(state, def, "register out of range");
16949         }
16950         return info;
16951 }
16952
16953 static struct reg_info find_lhs_pre_color(
16954         struct compile_state *state, struct triple *ins, int index)
16955 {
16956         struct reg_info info;
16957         int zlhs, zrhs, i;
16958         zrhs = ins->rhs;
16959         zlhs = ins->lhs;
16960         if (!zlhs && triple_is_def(state, ins)) {
16961                 zlhs = 1;
16962         }
16963         if (index >= zlhs) {
16964                 internal_error(state, ins, "Bad lhs %d", index);
16965         }
16966         info = arch_reg_lhs(state, ins, index);
16967         for(i = 0; i < zrhs; i++) {
16968                 struct reg_info rinfo;
16969                 rinfo = arch_reg_rhs(state, ins, i);
16970                 if ((info.reg == rinfo.reg) &&
16971                         (rinfo.reg >= MAX_REGISTERS)) {
16972                         struct reg_info tinfo;
16973                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
16974                         info.reg = tinfo.reg;
16975                         info.regcm &= tinfo.regcm;
16976                         break;
16977                 }
16978         }
16979         if (info.reg >= MAX_REGISTERS) {
16980                 info.reg = REG_UNSET;
16981         }
16982         return info;
16983 }
16984
16985 static struct reg_info find_rhs_post_color(
16986         struct compile_state *state, struct triple *ins, int index);
16987
16988 static struct reg_info find_lhs_post_color(
16989         struct compile_state *state, struct triple *ins, int index)
16990 {
16991         struct triple_set *set;
16992         struct reg_info info;
16993         struct triple *lhs;
16994 #if DEBUG_TRIPLE_COLOR
16995         fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
16996                 ins, index);
16997 #endif
16998         if ((index == 0) && triple_is_def(state, ins)) {
16999                 lhs = ins;
17000         }
17001         else if (index < ins->lhs) {
17002                 lhs = LHS(ins, index);
17003         }
17004         else {
17005                 internal_error(state, ins, "Bad lhs %d", index);
17006                 lhs = 0;
17007         }
17008         info = arch_reg_lhs(state, ins, index);
17009         if (info.reg >= MAX_REGISTERS) {
17010                 info.reg = REG_UNSET;
17011         }
17012         for(set = lhs->use; set; set = set->next) {
17013                 struct reg_info rinfo;
17014                 struct triple *user;
17015                 int zrhs, i;
17016                 user = set->member;
17017                 zrhs = user->rhs;
17018                 for(i = 0; i < zrhs; i++) {
17019                         if (RHS(user, i) != lhs) {
17020                                 continue;
17021                         }
17022                         rinfo = find_rhs_post_color(state, user, i);
17023                         if ((info.reg != REG_UNSET) &&
17024                                 (rinfo.reg != REG_UNSET) &&
17025                                 (info.reg != rinfo.reg)) {
17026                                 internal_error(state, ins, "register conflict");
17027                         }
17028                         if ((info.regcm & rinfo.regcm) == 0) {
17029                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
17030                                         info.regcm, rinfo.regcm);
17031                         }
17032                         if (info.reg == REG_UNSET) {
17033                                 info.reg = rinfo.reg;
17034                         }
17035                         info.regcm &= rinfo.regcm;
17036                 }
17037         }
17038 #if DEBUG_TRIPLE_COLOR
17039         fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17040                 ins, index, info.reg, info.regcm);
17041 #endif
17042         return info;
17043 }
17044
17045 static struct reg_info find_rhs_post_color(
17046         struct compile_state *state, struct triple *ins, int index)
17047 {
17048         struct reg_info info, rinfo;
17049         int zlhs, i;
17050 #if DEBUG_TRIPLE_COLOR
17051         fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17052                 ins, index);
17053 #endif
17054         rinfo = arch_reg_rhs(state, ins, index);
17055         zlhs = ins->lhs;
17056         if (!zlhs && triple_is_def(state, ins)) {
17057                 zlhs = 1;
17058         }
17059         info = rinfo;
17060         if (info.reg >= MAX_REGISTERS) {
17061                 info.reg = REG_UNSET;
17062         }
17063         for(i = 0; i < zlhs; i++) {
17064                 struct reg_info linfo;
17065                 linfo = arch_reg_lhs(state, ins, i);
17066                 if ((linfo.reg == rinfo.reg) &&
17067                         (linfo.reg >= MAX_REGISTERS)) {
17068                         struct reg_info tinfo;
17069                         tinfo = find_lhs_post_color(state, ins, i);
17070                         if (tinfo.reg >= MAX_REGISTERS) {
17071                                 tinfo.reg = REG_UNSET;
17072                         }
17073                         info.regcm &= linfo.regcm;
17074                         info.regcm &= tinfo.regcm;
17075                         if (info.reg != REG_UNSET) {
17076                                 internal_error(state, ins, "register conflict");
17077                         }
17078                         if (info.regcm == 0) {
17079                                 internal_error(state, ins, "regcm conflict");
17080                         }
17081                         info.reg = tinfo.reg;
17082                 }
17083         }
17084 #if DEBUG_TRIPLE_COLOR
17085         fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17086                 ins, index, info.reg, info.regcm);
17087 #endif
17088         return info;
17089 }
17090
17091 static struct reg_info find_lhs_color(
17092         struct compile_state *state, struct triple *ins, int index)
17093 {
17094         struct reg_info pre, post, info;
17095 #if DEBUG_TRIPLE_COLOR
17096         fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17097                 ins, index);
17098 #endif
17099         pre = find_lhs_pre_color(state, ins, index);
17100         post = find_lhs_post_color(state, ins, index);
17101         if ((pre.reg != post.reg) &&
17102                 (pre.reg != REG_UNSET) &&
17103                 (post.reg != REG_UNSET)) {
17104                 internal_error(state, ins, "register conflict");
17105         }
17106         info.regcm = pre.regcm & post.regcm;
17107         info.reg = pre.reg;
17108         if (info.reg == REG_UNSET) {
17109                 info.reg = post.reg;
17110         }
17111 #if DEBUG_TRIPLE_COLOR
17112         fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17113                 ins, index, info.reg, info.regcm,
17114                 pre.reg, pre.regcm, post.reg, post.regcm);
17115 #endif
17116         return info;
17117 }
17118
17119 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17120 {
17121         struct triple_set *entry, *next;
17122         struct triple *out;
17123         struct reg_info info, rinfo;
17124
17125         info = arch_reg_lhs(state, ins, 0);
17126         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17127         use_triple(RHS(out, 0), out);
17128         /* Get the users of ins to use out instead */
17129         for(entry = ins->use; entry; entry = next) {
17130                 int i;
17131                 next = entry->next;
17132                 if (entry->member == out) {
17133                         continue;
17134                 }
17135                 i = find_rhs_use(state, entry->member, ins);
17136                 if (i < 0) {
17137                         continue;
17138                 }
17139                 rinfo = arch_reg_rhs(state, entry->member, i);
17140                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17141                         continue;
17142                 }
17143                 replace_rhs_use(state, ins, out, entry->member);
17144         }
17145         transform_to_arch_instruction(state, out);
17146         return out;
17147 }
17148
17149 static struct triple *typed_pre_copy(
17150         struct compile_state *state, struct type *type, struct triple *ins, int index)
17151 {
17152         /* Carefully insert enough operations so that I can
17153          * enter any operation with a GPR32.
17154          */
17155         struct triple *in;
17156         struct triple **expr;
17157         unsigned classes;
17158         struct reg_info info;
17159         int op;
17160         if (ins->op == OP_PHI) {
17161                 internal_error(state, ins, "pre_copy on a phi?");
17162         }
17163         classes = arch_type_to_regcm(state, type);
17164         info = arch_reg_rhs(state, ins, index);
17165         expr = &RHS(ins, index);
17166         if ((info.regcm & classes) == 0) {
17167                 FILE *fp = state->errout;
17168                 fprintf(fp, "src_type: ");
17169                 name_of(fp, ins->type);
17170                 fprintf(fp, "\ndst_type: ");
17171                 name_of(fp, type);
17172                 fprintf(fp, "\n");
17173                 internal_error(state, ins, "pre_copy with no register classes");
17174         }
17175         op = OP_COPY;
17176         if (!equiv_types(type, (*expr)->type)) {
17177                 op = OP_CONVERT;
17178         }
17179         in = pre_triple(state, ins, op, type, *expr, 0);
17180         unuse_triple(*expr, ins);
17181         *expr = in;
17182         use_triple(RHS(in, 0), in);
17183         use_triple(in, ins);
17184         transform_to_arch_instruction(state, in);
17185         return in;
17186         
17187 }
17188 static struct triple *pre_copy(
17189         struct compile_state *state, struct triple *ins, int index)
17190 {
17191         return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17192 }
17193
17194
17195 static void insert_copies_to_phi(struct compile_state *state)
17196 {
17197         /* To get out of ssa form we insert moves on the incoming
17198          * edges to blocks containting phi functions.
17199          */
17200         struct triple *first;
17201         struct triple *phi;
17202
17203         /* Walk all of the operations to find the phi functions */
17204         first = state->first;
17205         for(phi = first->next; phi != first ; phi = phi->next) {
17206                 struct block_set *set;
17207                 struct block *block;
17208                 struct triple **slot, *copy;
17209                 int edge;
17210                 if (phi->op != OP_PHI) {
17211                         continue;
17212                 }
17213                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17214                 block = phi->u.block;
17215                 slot  = &RHS(phi, 0);
17216                 /* Phi's that feed into mandatory live range joins
17217                  * cause nasty complications.  Insert a copy of
17218                  * the phi value so I never have to deal with
17219                  * that in the rest of the code.
17220                  */
17221                 copy = post_copy(state, phi);
17222                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17223                 /* Walk all of the incoming edges/blocks and insert moves.
17224                  */
17225                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17226                         struct block *eblock;
17227                         struct triple *move;
17228                         struct triple *val;
17229                         struct triple *ptr;
17230                         eblock = set->member;
17231                         val = slot[edge];
17232
17233                         if (val == phi) {
17234                                 continue;
17235                         }
17236
17237                         get_occurance(val->occurance);
17238                         move = build_triple(state, OP_COPY, val->type, val, 0,
17239                                 val->occurance);
17240                         move->u.block = eblock;
17241                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
17242                         use_triple(val, move);
17243                         
17244                         slot[edge] = move;
17245                         unuse_triple(val, phi);
17246                         use_triple(move, phi);
17247
17248                         /* Walk up the dominator tree until I have found the appropriate block */
17249                         while(eblock && !tdominates(state, val, eblock->last)) {
17250                                 eblock = eblock->idom;
17251                         }
17252                         if (!eblock) {
17253                                 internal_error(state, phi, "Cannot find block dominated by %p",
17254                                         val);
17255                         }
17256
17257                         /* Walk through the block backwards to find
17258                          * an appropriate location for the OP_COPY.
17259                          */
17260                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17261                                 struct triple **expr;
17262                                 if (ptr->op == OP_PIECE) {
17263                                         ptr = MISC(ptr, 0);
17264                                 }
17265                                 if ((ptr == phi) || (ptr == val)) {
17266                                         goto out;
17267                                 }
17268                                 expr = triple_lhs(state, ptr, 0);
17269                                 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17270                                         if ((*expr) == val) {
17271                                                 goto out;
17272                                         }
17273                                 }
17274                                 expr = triple_rhs(state, ptr, 0);
17275                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17276                                         if ((*expr) == phi) {
17277                                                 goto out;
17278                                         }
17279                                 }
17280                         }
17281                 out:
17282                         if (triple_is_branch(state, ptr)) {
17283                                 internal_error(state, ptr,
17284                                         "Could not insert write to phi");
17285                         }
17286                         insert_triple(state, after_lhs(state, ptr), move);
17287                         if (eblock->last == after_lhs(state, ptr)->prev) {
17288                                 eblock->last = move;
17289                         }
17290                         transform_to_arch_instruction(state, move);
17291                 }
17292         }
17293         print_blocks(state, __func__, state->dbgout);
17294 }
17295
17296 struct triple_reg_set;
17297 struct reg_block;
17298
17299
17300 static int do_triple_set(struct triple_reg_set **head, 
17301         struct triple *member, struct triple *new_member)
17302 {
17303         struct triple_reg_set **ptr, *new;
17304         if (!member)
17305                 return 0;
17306         ptr = head;
17307         while(*ptr) {
17308                 if ((*ptr)->member == member) {
17309                         return 0;
17310                 }
17311                 ptr = &(*ptr)->next;
17312         }
17313         new = xcmalloc(sizeof(*new), "triple_set");
17314         new->member = member;
17315         new->new    = new_member;
17316         new->next   = *head;
17317         *head       = new;
17318         return 1;
17319 }
17320
17321 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17322 {
17323         struct triple_reg_set *entry, **ptr;
17324         ptr = head;
17325         while(*ptr) {
17326                 entry = *ptr;
17327                 if (entry->member == member) {
17328                         *ptr = entry->next;
17329                         xfree(entry);
17330                         return;
17331                 }
17332                 else {
17333                         ptr = &entry->next;
17334                 }
17335         }
17336 }
17337
17338 static int in_triple(struct reg_block *rb, struct triple *in)
17339 {
17340         return do_triple_set(&rb->in, in, 0);
17341 }
17342 static void unin_triple(struct reg_block *rb, struct triple *unin)
17343 {
17344         do_triple_unset(&rb->in, unin);
17345 }
17346
17347 static int out_triple(struct reg_block *rb, struct triple *out)
17348 {
17349         return do_triple_set(&rb->out, out, 0);
17350 }
17351 static void unout_triple(struct reg_block *rb, struct triple *unout)
17352 {
17353         do_triple_unset(&rb->out, unout);
17354 }
17355
17356 static int initialize_regblock(struct reg_block *blocks,
17357         struct block *block, int vertex)
17358 {
17359         struct block_set *user;
17360         if (!block || (blocks[block->vertex].block == block)) {
17361                 return vertex;
17362         }
17363         vertex += 1;
17364         /* Renumber the blocks in a convinient fashion */
17365         block->vertex = vertex;
17366         blocks[vertex].block    = block;
17367         blocks[vertex].vertex   = vertex;
17368         for(user = block->use; user; user = user->next) {
17369                 vertex = initialize_regblock(blocks, user->member, vertex);
17370         }
17371         return vertex;
17372 }
17373
17374 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17375 {
17376 /* Part to piece is a best attempt and it cannot be correct all by
17377  * itself.  If various values are read as different sizes in different
17378  * parts of the code this function cannot work.  Or rather it cannot
17379  * work in conjunction with compute_variable_liftimes.  As the
17380  * analysis will get confused.
17381  */
17382         struct triple *base;
17383         unsigned reg;
17384         if (!is_lvalue(state, ins)) {
17385                 return ins;
17386         }
17387         base = 0;
17388         reg = 0;
17389         while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17390                 base = MISC(ins, 0);
17391                 switch(ins->op) {
17392                 case OP_INDEX:
17393                         reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17394                         break;
17395                 case OP_DOT:
17396                         reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17397                         break;
17398                 default:
17399                         internal_error(state, ins, "unhandled part");
17400                         break;
17401                 }
17402                 ins = base;
17403         }
17404         if (base) {
17405                 if (reg > base->lhs) {
17406                         internal_error(state, base, "part out of range?");
17407                 }
17408                 ins = LHS(base, reg);
17409         }
17410         return ins;
17411 }
17412
17413 static int this_def(struct compile_state *state, 
17414         struct triple *ins, struct triple *other)
17415 {
17416         if (ins == other) {
17417                 return 1;
17418         }
17419         if (ins->op == OP_WRITE) {
17420                 ins = part_to_piece(state, MISC(ins, 0));
17421         }
17422         return ins == other;
17423 }
17424
17425 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17426         struct reg_block *rb, struct block *suc)
17427 {
17428         /* Read the conditional input set of a successor block
17429          * (i.e. the input to the phi nodes) and place it in the
17430          * current blocks output set.
17431          */
17432         struct block_set *set;
17433         struct triple *ptr;
17434         int edge;
17435         int done, change;
17436         change = 0;
17437         /* Find the edge I am coming in on */
17438         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17439                 if (set->member == rb->block) {
17440                         break;
17441                 }
17442         }
17443         if (!set) {
17444                 internal_error(state, 0, "Not coming on a control edge?");
17445         }
17446         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17447                 struct triple **slot, *expr, *ptr2;
17448                 int out_change, done2;
17449                 done = (ptr == suc->last);
17450                 if (ptr->op != OP_PHI) {
17451                         continue;
17452                 }
17453                 slot = &RHS(ptr, 0);
17454                 expr = slot[edge];
17455                 out_change = out_triple(rb, expr);
17456                 if (!out_change) {
17457                         continue;
17458                 }
17459                 /* If we don't define the variable also plast it
17460                  * in the current blocks input set.
17461                  */
17462                 ptr2 = rb->block->first;
17463                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17464                         if (this_def(state, ptr2, expr)) {
17465                                 break;
17466                         }
17467                         done2 = (ptr2 == rb->block->last);
17468                 }
17469                 if (!done2) {
17470                         continue;
17471                 }
17472                 change |= in_triple(rb, expr);
17473         }
17474         return change;
17475 }
17476
17477 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17478         struct reg_block *rb, struct block *suc)
17479 {
17480         struct triple_reg_set *in_set;
17481         int change;
17482         change = 0;
17483         /* Read the input set of a successor block
17484          * and place it in the current blocks output set.
17485          */
17486         in_set = blocks[suc->vertex].in;
17487         for(; in_set; in_set = in_set->next) {
17488                 int out_change, done;
17489                 struct triple *first, *last, *ptr;
17490                 out_change = out_triple(rb, in_set->member);
17491                 if (!out_change) {
17492                         continue;
17493                 }
17494                 /* If we don't define the variable also place it
17495                  * in the current blocks input set.
17496                  */
17497                 first = rb->block->first;
17498                 last = rb->block->last;
17499                 done = 0;
17500                 for(ptr = first; !done; ptr = ptr->next) {
17501                         if (this_def(state, ptr, in_set->member)) {
17502                                 break;
17503                         }
17504                         done = (ptr == last);
17505                 }
17506                 if (!done) {
17507                         continue;
17508                 }
17509                 change |= in_triple(rb, in_set->member);
17510         }
17511         change |= phi_in(state, blocks, rb, suc);
17512         return change;
17513 }
17514
17515 static int use_in(struct compile_state *state, struct reg_block *rb)
17516 {
17517         /* Find the variables we use but don't define and add
17518          * it to the current blocks input set.
17519          */
17520 #warning "FIXME is this O(N^2) algorithm bad?"
17521         struct block *block;
17522         struct triple *ptr;
17523         int done;
17524         int change;
17525         block = rb->block;
17526         change = 0;
17527         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17528                 struct triple **expr;
17529                 done = (ptr == block->first);
17530                 /* The variable a phi function uses depends on the
17531                  * control flow, and is handled in phi_in, not
17532                  * here.
17533                  */
17534                 if (ptr->op == OP_PHI) {
17535                         continue;
17536                 }
17537                 expr = triple_rhs(state, ptr, 0);
17538                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17539                         struct triple *rhs, *test;
17540                         int tdone;
17541                         rhs = part_to_piece(state, *expr);
17542                         if (!rhs) {
17543                                 continue;
17544                         }
17545
17546                         /* See if rhs is defined in this block.
17547                          * A write counts as a definition.
17548                          */
17549                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17550                                 tdone = (test == block->first);
17551                                 if (this_def(state, test, rhs)) {
17552                                         rhs = 0;
17553                                         break;
17554                                 }
17555                         }
17556                         /* If I still have a valid rhs add it to in */
17557                         change |= in_triple(rb, rhs);
17558                 }
17559         }
17560         return change;
17561 }
17562
17563 static struct reg_block *compute_variable_lifetimes(
17564         struct compile_state *state, struct basic_blocks *bb)
17565 {
17566         struct reg_block *blocks;
17567         int change;
17568         blocks = xcmalloc(
17569                 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17570         initialize_regblock(blocks, bb->last_block, 0);
17571         do {
17572                 int i;
17573                 change = 0;
17574                 for(i = 1; i <= bb->last_vertex; i++) {
17575                         struct block_set *edge;
17576                         struct reg_block *rb;
17577                         rb = &blocks[i];
17578                         /* Add the all successor's input set to in */
17579                         for(edge = rb->block->edges; edge; edge = edge->next) {
17580                                 change |= reg_in(state, blocks, rb, edge->member);
17581                         }
17582                         /* Add use to in... */
17583                         change |= use_in(state, rb);
17584                 }
17585         } while(change);
17586         return blocks;
17587 }
17588
17589 static void free_variable_lifetimes(struct compile_state *state, 
17590         struct basic_blocks *bb, struct reg_block *blocks)
17591 {
17592         int i;
17593         /* free in_set && out_set on each block */
17594         for(i = 1; i <= bb->last_vertex; i++) {
17595                 struct triple_reg_set *entry, *next;
17596                 struct reg_block *rb;
17597                 rb = &blocks[i];
17598                 for(entry = rb->in; entry ; entry = next) {
17599                         next = entry->next;
17600                         do_triple_unset(&rb->in, entry->member);
17601                 }
17602                 for(entry = rb->out; entry; entry = next) {
17603                         next = entry->next;
17604                         do_triple_unset(&rb->out, entry->member);
17605                 }
17606         }
17607         xfree(blocks);
17608
17609 }
17610
17611 typedef void (*wvl_cb_t)(
17612         struct compile_state *state, 
17613         struct reg_block *blocks, struct triple_reg_set *live, 
17614         struct reg_block *rb, struct triple *ins, void *arg);
17615
17616 static void walk_variable_lifetimes(struct compile_state *state,
17617         struct basic_blocks *bb, struct reg_block *blocks, 
17618         wvl_cb_t cb, void *arg)
17619 {
17620         int i;
17621         
17622         for(i = 1; i <= state->bb.last_vertex; i++) {
17623                 struct triple_reg_set *live;
17624                 struct triple_reg_set *entry, *next;
17625                 struct triple *ptr, *prev;
17626                 struct reg_block *rb;
17627                 struct block *block;
17628                 int done;
17629
17630                 /* Get the blocks */
17631                 rb = &blocks[i];
17632                 block = rb->block;
17633
17634                 /* Copy out into live */
17635                 live = 0;
17636                 for(entry = rb->out; entry; entry = next) {
17637                         next = entry->next;
17638                         do_triple_set(&live, entry->member, entry->new);
17639                 }
17640                 /* Walk through the basic block calculating live */
17641                 for(done = 0, ptr = block->last; !done; ptr = prev) {
17642                         struct triple **expr;
17643
17644                         prev = ptr->prev;
17645                         done = (ptr == block->first);
17646
17647                         /* Ensure the current definition is in live */
17648                         if (triple_is_def(state, ptr)) {
17649                                 do_triple_set(&live, ptr, 0);
17650                         }
17651
17652                         /* Inform the callback function of what is
17653                          * going on.
17654                          */
17655                          cb(state, blocks, live, rb, ptr, arg);
17656                         
17657                         /* Remove the current definition from live */
17658                         do_triple_unset(&live, ptr);
17659
17660                         /* Add the current uses to live.
17661                          *
17662                          * It is safe to skip phi functions because they do
17663                          * not have any block local uses, and the block
17664                          * output sets already properly account for what
17665                          * control flow depedent uses phi functions do have.
17666                          */
17667                         if (ptr->op == OP_PHI) {
17668                                 continue;
17669                         }
17670                         expr = triple_rhs(state, ptr, 0);
17671                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
17672                                 /* If the triple is not a definition skip it. */
17673                                 if (!*expr || !triple_is_def(state, *expr)) {
17674                                         continue;
17675                                 }
17676                                 do_triple_set(&live, *expr, 0);
17677                         }
17678                 }
17679                 /* Free live */
17680                 for(entry = live; entry; entry = next) {
17681                         next = entry->next;
17682                         do_triple_unset(&live, entry->member);
17683                 }
17684         }
17685 }
17686
17687 struct print_live_variable_info {
17688         struct reg_block *rb;
17689         FILE *fp;
17690 };
17691 static void print_live_variables_block(
17692         struct compile_state *state, struct block *block, void *arg)
17693
17694 {
17695         struct print_live_variable_info *info = arg;
17696         struct block_set *edge;
17697         FILE *fp = info->fp;
17698         struct reg_block *rb;
17699         struct triple *ptr;
17700         int phi_present;
17701         int done;
17702         rb = &info->rb[block->vertex];
17703
17704         fprintf(fp, "\nblock: %p (%d),",
17705                 block,  block->vertex);
17706         for(edge = block->edges; edge; edge = edge->next) {
17707                 fprintf(fp, " %p<-%p",
17708                         edge->member, 
17709                         edge->member && edge->member->use?edge->member->use->member : 0);
17710         }
17711         fprintf(fp, "\n");
17712         if (rb->in) {
17713                 struct triple_reg_set *in_set;
17714                 fprintf(fp, "        in:");
17715                 for(in_set = rb->in; in_set; in_set = in_set->next) {
17716                         fprintf(fp, " %-10p", in_set->member);
17717                 }
17718                 fprintf(fp, "\n");
17719         }
17720         phi_present = 0;
17721         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17722                 done = (ptr == block->last);
17723                 if (ptr->op == OP_PHI) {
17724                         phi_present = 1;
17725                         break;
17726                 }
17727         }
17728         if (phi_present) {
17729                 int edge;
17730                 for(edge = 0; edge < block->users; edge++) {
17731                         fprintf(fp, "     in(%d):", edge);
17732                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17733                                 struct triple **slot;
17734                                 done = (ptr == block->last);
17735                                 if (ptr->op != OP_PHI) {
17736                                         continue;
17737                                 }
17738                                 slot = &RHS(ptr, 0);
17739                                 fprintf(fp, " %-10p", slot[edge]);
17740                         }
17741                         fprintf(fp, "\n");
17742                 }
17743         }
17744         if (block->first->op == OP_LABEL) {
17745                 fprintf(fp, "%p:\n", block->first);
17746         }
17747         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17748                 done = (ptr == block->last);
17749                 display_triple(fp, ptr);
17750         }
17751         if (rb->out) {
17752                 struct triple_reg_set *out_set;
17753                 fprintf(fp, "       out:");
17754                 for(out_set = rb->out; out_set; out_set = out_set->next) {
17755                         fprintf(fp, " %-10p", out_set->member);
17756                 }
17757                 fprintf(fp, "\n");
17758         }
17759         fprintf(fp, "\n");
17760 }
17761
17762 static void print_live_variables(struct compile_state *state, 
17763         struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17764 {
17765         struct print_live_variable_info info;
17766         info.rb = rb;
17767         info.fp = fp;
17768         fprintf(fp, "\nlive variables by block\n");
17769         walk_blocks(state, bb, print_live_variables_block, &info);
17770
17771 }
17772
17773
17774 static int count_triples(struct compile_state *state)
17775 {
17776         struct triple *first, *ins;
17777         int triples = 0;
17778         first = state->first;
17779         ins = first;
17780         do {
17781                 triples++;
17782                 ins = ins->next;
17783         } while (ins != first);
17784         return triples;
17785 }
17786
17787
17788 struct dead_triple {
17789         struct triple *triple;
17790         struct dead_triple *work_next;
17791         struct block *block;
17792         int old_id;
17793         int flags;
17794 #define TRIPLE_FLAG_ALIVE 1
17795 #define TRIPLE_FLAG_FREE  1
17796 };
17797
17798 static void print_dead_triples(struct compile_state *state, 
17799         struct dead_triple *dtriple)
17800 {
17801         struct triple *first, *ins;
17802         struct dead_triple *dt;
17803         FILE *fp;
17804         if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17805                 return;
17806         }
17807         fp = state->dbgout;
17808         fprintf(fp, "--------------- dtriples ---------------\n");
17809         first = state->first;
17810         ins = first;
17811         do {
17812                 dt = &dtriple[ins->id];
17813                 if ((ins->op == OP_LABEL) && (ins->use)) {
17814                         fprintf(fp, "\n%p:\n", ins);
17815                 }
17816                 fprintf(fp, "%c", 
17817                         (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17818                 display_triple(fp, ins);
17819                 if (triple_is_branch(state, ins)) {
17820                         fprintf(fp, "\n");
17821                 }
17822                 ins = ins->next;
17823         } while(ins != first);
17824         fprintf(fp, "\n");
17825 }
17826
17827
17828 static void awaken(
17829         struct compile_state *state,
17830         struct dead_triple *dtriple, struct triple **expr,
17831         struct dead_triple ***work_list_tail)
17832 {
17833         struct triple *triple;
17834         struct dead_triple *dt;
17835         if (!expr) {
17836                 return;
17837         }
17838         triple = *expr;
17839         if (!triple) {
17840                 return;
17841         }
17842         if (triple->id <= 0)  {
17843                 internal_error(state, triple, "bad triple id: %d",
17844                         triple->id);
17845         }
17846         if (triple->op == OP_NOOP) {
17847                 internal_error(state, triple, "awakening noop?");
17848                 return;
17849         }
17850         dt = &dtriple[triple->id];
17851         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17852                 dt->flags |= TRIPLE_FLAG_ALIVE;
17853                 if (!dt->work_next) {
17854                         **work_list_tail = dt;
17855                         *work_list_tail = &dt->work_next;
17856                 }
17857         }
17858 }
17859
17860 static void eliminate_inefectual_code(struct compile_state *state)
17861 {
17862         struct block *block;
17863         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17864         int triples, i;
17865         struct triple *first, *final, *ins;
17866
17867         if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17868                 return;
17869         }
17870
17871         /* Setup the work list */
17872         work_list = 0;
17873         work_list_tail = &work_list;
17874
17875         first = state->first;
17876         final = state->first->prev;
17877
17878         /* Count how many triples I have */
17879         triples = count_triples(state);
17880
17881         /* Now put then in an array and mark all of the triples dead */
17882         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17883         
17884         ins = first;
17885         i = 1;
17886         block = 0;
17887         do {
17888                 dtriple[i].triple = ins;
17889                 dtriple[i].block  = block_of_triple(state, ins);
17890                 dtriple[i].flags  = 0;
17891                 dtriple[i].old_id = ins->id;
17892                 ins->id = i;
17893                 /* See if it is an operation we always keep */
17894                 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17895                         awaken(state, dtriple, &ins, &work_list_tail);
17896                 }
17897                 i++;
17898                 ins = ins->next;
17899         } while(ins != first);
17900         while(work_list) {
17901                 struct block *block;
17902                 struct dead_triple *dt;
17903                 struct block_set *user;
17904                 struct triple **expr;
17905                 dt = work_list;
17906                 work_list = dt->work_next;
17907                 if (!work_list) {
17908                         work_list_tail = &work_list;
17909                 }
17910                 /* Make certain the block the current instruction is in lives */
17911                 block = block_of_triple(state, dt->triple);
17912                 awaken(state, dtriple, &block->first, &work_list_tail);
17913                 if (triple_is_branch(state, block->last)) {
17914                         awaken(state, dtriple, &block->last, &work_list_tail);
17915                 } else {
17916                         awaken(state, dtriple, &block->last->next, &work_list_tail);
17917                 }
17918
17919                 /* Wake up the data depencencies of this triple */
17920                 expr = 0;
17921                 do {
17922                         expr = triple_rhs(state, dt->triple, expr);
17923                         awaken(state, dtriple, expr, &work_list_tail);
17924                 } while(expr);
17925                 do {
17926                         expr = triple_lhs(state, dt->triple, expr);
17927                         awaken(state, dtriple, expr, &work_list_tail);
17928                 } while(expr);
17929                 do {
17930                         expr = triple_misc(state, dt->triple, expr);
17931                         awaken(state, dtriple, expr, &work_list_tail);
17932                 } while(expr);
17933                 /* Wake up the forward control dependencies */
17934                 do {
17935                         expr = triple_targ(state, dt->triple, expr);
17936                         awaken(state, dtriple, expr, &work_list_tail);
17937                 } while(expr);
17938                 /* Wake up the reverse control dependencies of this triple */
17939                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17940                         struct triple *last;
17941                         last = user->member->last;
17942                         while((last->op == OP_NOOP) && (last != user->member->first)) {
17943                                 internal_warning(state, last, "awakening noop?");
17944                                 last = last->prev;
17945                         }
17946                         awaken(state, dtriple, &last, &work_list_tail);
17947                 }
17948         }
17949         print_dead_triples(state, dtriple);
17950         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
17951                 if ((dt->triple->op == OP_NOOP) && 
17952                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
17953                         internal_error(state, dt->triple, "noop effective?");
17954                 }
17955                 dt->triple->id = dt->old_id;    /* Restore the color */
17956                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17957                         release_triple(state, dt->triple);
17958                 }
17959         }
17960         xfree(dtriple);
17961
17962         rebuild_ssa_form(state);
17963
17964         print_blocks(state, __func__, state->dbgout);
17965 }
17966
17967
17968 static void insert_mandatory_copies(struct compile_state *state)
17969 {
17970         struct triple *ins, *first;
17971
17972         /* The object is with a minimum of inserted copies,
17973          * to resolve in fundamental register conflicts between
17974          * register value producers and consumers.
17975          * Theoretically we may be greater than minimal when we
17976          * are inserting copies before instructions but that
17977          * case should be rare.
17978          */
17979         first = state->first;
17980         ins = first;
17981         do {
17982                 struct triple_set *entry, *next;
17983                 struct triple *tmp;
17984                 struct reg_info info;
17985                 unsigned reg, regcm;
17986                 int do_post_copy, do_pre_copy;
17987                 tmp = 0;
17988                 if (!triple_is_def(state, ins)) {
17989                         goto next;
17990                 }
17991                 /* Find the architecture specific color information */
17992                 info = find_lhs_pre_color(state, ins, 0);
17993                 if (info.reg >= MAX_REGISTERS) {
17994                         info.reg = REG_UNSET;
17995                 }
17996
17997                 reg = REG_UNSET;
17998                 regcm = arch_type_to_regcm(state, ins->type);
17999                 do_post_copy = do_pre_copy = 0;
18000
18001                 /* Walk through the uses of ins and check for conflicts */
18002                 for(entry = ins->use; entry; entry = next) {
18003                         struct reg_info rinfo;
18004                         int i;
18005                         next = entry->next;
18006                         i = find_rhs_use(state, entry->member, ins);
18007                         if (i < 0) {
18008                                 continue;
18009                         }
18010                         
18011                         /* Find the users color requirements */
18012                         rinfo = arch_reg_rhs(state, entry->member, i);
18013                         if (rinfo.reg >= MAX_REGISTERS) {
18014                                 rinfo.reg = REG_UNSET;
18015                         }
18016                         
18017                         /* See if I need a pre_copy */
18018                         if (rinfo.reg != REG_UNSET) {
18019                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
18020                                         do_pre_copy = 1;
18021                                 }
18022                                 reg = rinfo.reg;
18023                         }
18024                         regcm &= rinfo.regcm;
18025                         regcm = arch_regcm_normalize(state, regcm);
18026                         if (regcm == 0) {
18027                                 do_pre_copy = 1;
18028                         }
18029                         /* Always use pre_copies for constants.
18030                          * They do not take up any registers until a
18031                          * copy places them in one.
18032                          */
18033                         if ((info.reg == REG_UNNEEDED) && 
18034                                 (rinfo.reg != REG_UNNEEDED)) {
18035                                 do_pre_copy = 1;
18036                         }
18037                 }
18038                 do_post_copy =
18039                         !do_pre_copy &&
18040                         (((info.reg != REG_UNSET) && 
18041                                 (reg != REG_UNSET) &&
18042                                 (info.reg != reg)) ||
18043                         ((info.regcm & regcm) == 0));
18044
18045                 reg = info.reg;
18046                 regcm = info.regcm;
18047                 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18048                 for(entry = ins->use; entry; entry = next) {
18049                         struct reg_info rinfo;
18050                         int i;
18051                         next = entry->next;
18052                         i = find_rhs_use(state, entry->member, ins);
18053                         if (i < 0) {
18054                                 continue;
18055                         }
18056                         
18057                         /* Find the users color requirements */
18058                         rinfo = arch_reg_rhs(state, entry->member, i);
18059                         if (rinfo.reg >= MAX_REGISTERS) {
18060                                 rinfo.reg = REG_UNSET;
18061                         }
18062
18063                         /* Now see if it is time to do the pre_copy */
18064                         if (rinfo.reg != REG_UNSET) {
18065                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18066                                         ((regcm & rinfo.regcm) == 0) ||
18067                                         /* Don't let a mandatory coalesce sneak
18068                                          * into a operation that is marked to prevent
18069                                          * coalescing.
18070                                          */
18071                                         ((reg != REG_UNNEEDED) &&
18072                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18073                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18074                                         ) {
18075                                         if (do_pre_copy) {
18076                                                 struct triple *user;
18077                                                 user = entry->member;
18078                                                 if (RHS(user, i) != ins) {
18079                                                         internal_error(state, user, "bad rhs");
18080                                                 }
18081                                                 tmp = pre_copy(state, user, i);
18082                                                 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18083                                                 continue;
18084                                         } else {
18085                                                 do_post_copy = 1;
18086                                         }
18087                                 }
18088                                 reg = rinfo.reg;
18089                         }
18090                         if ((regcm & rinfo.regcm) == 0) {
18091                                 if (do_pre_copy) {
18092                                         struct triple *user;
18093                                         user = entry->member;
18094                                         if (RHS(user, i) != ins) {
18095                                                 internal_error(state, user, "bad rhs");
18096                                         }
18097                                         tmp = pre_copy(state, user, i);
18098                                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18099                                         continue;
18100                                 } else {
18101                                         do_post_copy = 1;
18102                                 }
18103                         }
18104                         regcm &= rinfo.regcm;
18105                         
18106                 }
18107                 if (do_post_copy) {
18108                         struct reg_info pre, post;
18109                         tmp = post_copy(state, ins);
18110                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18111                         pre = arch_reg_lhs(state, ins, 0);
18112                         post = arch_reg_lhs(state, tmp, 0);
18113                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18114                                 internal_error(state, tmp, "useless copy");
18115                         }
18116                 }
18117         next:
18118                 ins = ins->next;
18119         } while(ins != first);
18120
18121         print_blocks(state, __func__, state->dbgout);
18122 }
18123
18124
18125 struct live_range_edge;
18126 struct live_range_def;
18127 struct live_range {
18128         struct live_range_edge *edges;
18129         struct live_range_def *defs;
18130 /* Note. The list pointed to by defs is kept in order.
18131  * That is baring splits in the flow control
18132  * defs dominates defs->next wich dominates defs->next->next
18133  * etc.
18134  */
18135         unsigned color;
18136         unsigned classes;
18137         unsigned degree;
18138         unsigned length;
18139         struct live_range *group_next, **group_prev;
18140 };
18141
18142 struct live_range_edge {
18143         struct live_range_edge *next;
18144         struct live_range *node;
18145 };
18146
18147 struct live_range_def {
18148         struct live_range_def *next;
18149         struct live_range_def *prev;
18150         struct live_range *lr;
18151         struct triple *def;
18152         unsigned orig_id;
18153 };
18154
18155 #define LRE_HASH_SIZE 2048
18156 struct lre_hash {
18157         struct lre_hash *next;
18158         struct live_range *left;
18159         struct live_range *right;
18160 };
18161
18162
18163 struct reg_state {
18164         struct lre_hash *hash[LRE_HASH_SIZE];
18165         struct reg_block *blocks;
18166         struct live_range_def *lrd;
18167         struct live_range *lr;
18168         struct live_range *low, **low_tail;
18169         struct live_range *high, **high_tail;
18170         unsigned defs;
18171         unsigned ranges;
18172         int passes, max_passes;
18173 };
18174
18175
18176 struct print_interference_block_info {
18177         struct reg_state *rstate;
18178         FILE *fp;
18179         int need_edges;
18180 };
18181 static void print_interference_block(
18182         struct compile_state *state, struct block *block, void *arg)
18183
18184 {
18185         struct print_interference_block_info *info = arg;
18186         struct reg_state *rstate = info->rstate;
18187         struct block_set *edge;
18188         FILE *fp = info->fp;
18189         struct reg_block *rb;
18190         struct triple *ptr;
18191         int phi_present;
18192         int done;
18193         rb = &rstate->blocks[block->vertex];
18194
18195         fprintf(fp, "\nblock: %p (%d),",
18196                 block,  block->vertex);
18197         for(edge = block->edges; edge; edge = edge->next) {
18198                 fprintf(fp, " %p<-%p",
18199                         edge->member, 
18200                         edge->member && edge->member->use?edge->member->use->member : 0);
18201         }
18202         fprintf(fp, "\n");
18203         if (rb->in) {
18204                 struct triple_reg_set *in_set;
18205                 fprintf(fp, "        in:");
18206                 for(in_set = rb->in; in_set; in_set = in_set->next) {
18207                         fprintf(fp, " %-10p", in_set->member);
18208                 }
18209                 fprintf(fp, "\n");
18210         }
18211         phi_present = 0;
18212         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18213                 done = (ptr == block->last);
18214                 if (ptr->op == OP_PHI) {
18215                         phi_present = 1;
18216                         break;
18217                 }
18218         }
18219         if (phi_present) {
18220                 int edge;
18221                 for(edge = 0; edge < block->users; edge++) {
18222                         fprintf(fp, "     in(%d):", edge);
18223                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18224                                 struct triple **slot;
18225                                 done = (ptr == block->last);
18226                                 if (ptr->op != OP_PHI) {
18227                                         continue;
18228                                 }
18229                                 slot = &RHS(ptr, 0);
18230                                 fprintf(fp, " %-10p", slot[edge]);
18231                         }
18232                         fprintf(fp, "\n");
18233                 }
18234         }
18235         if (block->first->op == OP_LABEL) {
18236                 fprintf(fp, "%p:\n", block->first);
18237         }
18238         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18239                 struct live_range *lr;
18240                 unsigned id;
18241                 int op;
18242                 op = ptr->op;
18243                 done = (ptr == block->last);
18244                 lr = rstate->lrd[ptr->id].lr;
18245                 
18246                 id = ptr->id;
18247                 ptr->id = rstate->lrd[id].orig_id;
18248                 SET_REG(ptr->id, lr->color);
18249                 display_triple(fp, ptr);
18250                 ptr->id = id;
18251
18252                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18253                         internal_error(state, ptr, "lr has no defs!");
18254                 }
18255                 if (info->need_edges) {
18256                         if (lr->defs) {
18257                                 struct live_range_def *lrd;
18258                                 fprintf(fp, "       range:");
18259                                 lrd = lr->defs;
18260                                 do {
18261                                         fprintf(fp, " %-10p", lrd->def);
18262                                         lrd = lrd->next;
18263                                 } while(lrd != lr->defs);
18264                                 fprintf(fp, "\n");
18265                         }
18266                         if (lr->edges > 0) {
18267                                 struct live_range_edge *edge;
18268                                 fprintf(fp, "       edges:");
18269                                 for(edge = lr->edges; edge; edge = edge->next) {
18270                                         struct live_range_def *lrd;
18271                                         lrd = edge->node->defs;
18272                                         do {
18273                                                 fprintf(fp, " %-10p", lrd->def);
18274                                                 lrd = lrd->next;
18275                                         } while(lrd != edge->node->defs);
18276                                         fprintf(fp, "|");
18277                                 }
18278                                 fprintf(fp, "\n");
18279                         }
18280                 }
18281                 /* Do a bunch of sanity checks */
18282                 valid_ins(state, ptr);
18283                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18284                         internal_error(state, ptr, "Invalid triple id: %d",
18285                                 ptr->id);
18286                 }
18287         }
18288         if (rb->out) {
18289                 struct triple_reg_set *out_set;
18290                 fprintf(fp, "       out:");
18291                 for(out_set = rb->out; out_set; out_set = out_set->next) {
18292                         fprintf(fp, " %-10p", out_set->member);
18293                 }
18294                 fprintf(fp, "\n");
18295         }
18296         fprintf(fp, "\n");
18297 }
18298
18299 static void print_interference_blocks(
18300         struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18301 {
18302         struct print_interference_block_info info;
18303         info.rstate = rstate;
18304         info.fp = fp;
18305         info.need_edges = need_edges;
18306         fprintf(fp, "\nlive variables by block\n");
18307         walk_blocks(state, &state->bb, print_interference_block, &info);
18308
18309 }
18310
18311 static unsigned regc_max_size(struct compile_state *state, int classes)
18312 {
18313         unsigned max_size;
18314         int i;
18315         max_size = 0;
18316         for(i = 0; i < MAX_REGC; i++) {
18317                 if (classes & (1 << i)) {
18318                         unsigned size;
18319                         size = arch_regc_size(state, i);
18320                         if (size > max_size) {
18321                                 max_size = size;
18322                         }
18323                 }
18324         }
18325         return max_size;
18326 }
18327
18328 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18329 {
18330         unsigned equivs[MAX_REG_EQUIVS];
18331         int i;
18332         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18333                 internal_error(state, 0, "invalid register");
18334         }
18335         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18336                 internal_error(state, 0, "invalid register");
18337         }
18338         arch_reg_equivs(state, equivs, reg1);
18339         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18340                 if (equivs[i] == reg2) {
18341                         return 1;
18342                 }
18343         }
18344         return 0;
18345 }
18346
18347 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18348 {
18349         unsigned equivs[MAX_REG_EQUIVS];
18350         int i;
18351         if (reg == REG_UNNEEDED) {
18352                 return;
18353         }
18354         arch_reg_equivs(state, equivs, reg);
18355         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18356                 used[equivs[i]] = 1;
18357         }
18358         return;
18359 }
18360
18361 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18362 {
18363         unsigned equivs[MAX_REG_EQUIVS];
18364         int i;
18365         if (reg == REG_UNNEEDED) {
18366                 return;
18367         }
18368         arch_reg_equivs(state, equivs, reg);
18369         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18370                 used[equivs[i]] += 1;
18371         }
18372         return;
18373 }
18374
18375 static unsigned int hash_live_edge(
18376         struct live_range *left, struct live_range *right)
18377 {
18378         unsigned int hash, val;
18379         unsigned long lval, rval;
18380         lval = ((unsigned long)left)/sizeof(struct live_range);
18381         rval = ((unsigned long)right)/sizeof(struct live_range);
18382         hash = 0;
18383         while(lval) {
18384                 val = lval & 0xff;
18385                 lval >>= 8;
18386                 hash = (hash *263) + val;
18387         }
18388         while(rval) {
18389                 val = rval & 0xff;
18390                 rval >>= 8;
18391                 hash = (hash *263) + val;
18392         }
18393         hash = hash & (LRE_HASH_SIZE - 1);
18394         return hash;
18395 }
18396
18397 static struct lre_hash **lre_probe(struct reg_state *rstate,
18398         struct live_range *left, struct live_range *right)
18399 {
18400         struct lre_hash **ptr;
18401         unsigned int index;
18402         /* Ensure left <= right */
18403         if (left > right) {
18404                 struct live_range *tmp;
18405                 tmp = left;
18406                 left = right;
18407                 right = tmp;
18408         }
18409         index = hash_live_edge(left, right);
18410         
18411         ptr = &rstate->hash[index];
18412         while(*ptr) {
18413                 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18414                         break;
18415                 }
18416                 ptr = &(*ptr)->next;
18417         }
18418         return ptr;
18419 }
18420
18421 static int interfere(struct reg_state *rstate,
18422         struct live_range *left, struct live_range *right)
18423 {
18424         struct lre_hash **ptr;
18425         ptr = lre_probe(rstate, left, right);
18426         return ptr && *ptr;
18427 }
18428
18429 static void add_live_edge(struct reg_state *rstate, 
18430         struct live_range *left, struct live_range *right)
18431 {
18432         /* FIXME the memory allocation overhead is noticeable here... */
18433         struct lre_hash **ptr, *new_hash;
18434         struct live_range_edge *edge;
18435
18436         if (left == right) {
18437                 return;
18438         }
18439         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18440                 return;
18441         }
18442         /* Ensure left <= right */
18443         if (left > right) {
18444                 struct live_range *tmp;
18445                 tmp = left;
18446                 left = right;
18447                 right = tmp;
18448         }
18449         ptr = lre_probe(rstate, left, right);
18450         if (*ptr) {
18451                 return;
18452         }
18453 #if 0
18454         fprintf(state->errout, "new_live_edge(%p, %p)\n",
18455                 left, right);
18456 #endif
18457         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18458         new_hash->next  = *ptr;
18459         new_hash->left  = left;
18460         new_hash->right = right;
18461         *ptr = new_hash;
18462
18463         edge = xmalloc(sizeof(*edge), "live_range_edge");
18464         edge->next   = left->edges;
18465         edge->node   = right;
18466         left->edges  = edge;
18467         left->degree += 1;
18468         
18469         edge = xmalloc(sizeof(*edge), "live_range_edge");
18470         edge->next    = right->edges;
18471         edge->node    = left;
18472         right->edges  = edge;
18473         right->degree += 1;
18474 }
18475
18476 static void remove_live_edge(struct reg_state *rstate,
18477         struct live_range *left, struct live_range *right)
18478 {
18479         struct live_range_edge *edge, **ptr;
18480         struct lre_hash **hptr, *entry;
18481         hptr = lre_probe(rstate, left, right);
18482         if (!hptr || !*hptr) {
18483                 return;
18484         }
18485         entry = *hptr;
18486         *hptr = entry->next;
18487         xfree(entry);
18488
18489         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18490                 edge = *ptr;
18491                 if (edge->node == right) {
18492                         *ptr = edge->next;
18493                         memset(edge, 0, sizeof(*edge));
18494                         xfree(edge);
18495                         right->degree--;
18496                         break;
18497                 }
18498         }
18499         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18500                 edge = *ptr;
18501                 if (edge->node == left) {
18502                         *ptr = edge->next;
18503                         memset(edge, 0, sizeof(*edge));
18504                         xfree(edge);
18505                         left->degree--;
18506                         break;
18507                 }
18508         }
18509 }
18510
18511 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18512 {
18513         struct live_range_edge *edge, *next;
18514         for(edge = range->edges; edge; edge = next) {
18515                 next = edge->next;
18516                 remove_live_edge(rstate, range, edge->node);
18517         }
18518 }
18519
18520 static void transfer_live_edges(struct reg_state *rstate, 
18521         struct live_range *dest, struct live_range *src)
18522 {
18523         struct live_range_edge *edge, *next;
18524         for(edge = src->edges; edge; edge = next) {
18525                 struct live_range *other;
18526                 next = edge->next;
18527                 other = edge->node;
18528                 remove_live_edge(rstate, src, other);
18529                 add_live_edge(rstate, dest, other);
18530         }
18531 }
18532
18533
18534 /* Interference graph...
18535  * 
18536  * new(n) --- Return a graph with n nodes but no edges.
18537  * add(g,x,y) --- Return a graph including g with an between x and y
18538  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18539  *                x and y in the graph g
18540  * degree(g, x) --- Return the degree of the node x in the graph g
18541  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18542  *
18543  * Implement with a hash table && a set of adjcency vectors.
18544  * The hash table supports constant time implementations of add and interfere.
18545  * The adjacency vectors support an efficient implementation of neighbors.
18546  */
18547
18548 /* 
18549  *     +---------------------------------------------------+
18550  *     |         +--------------+                          |
18551  *     v         v              |                          |
18552  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
18553  *
18554  * -- In simplify implment optimistic coloring... (No backtracking)
18555  * -- Implement Rematerialization it is the only form of spilling we can perform
18556  *    Essentially this means dropping a constant from a register because
18557  *    we can regenerate it later.
18558  *
18559  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18560  *     coalesce at phi points...
18561  * --- Bias coloring if at all possible do the coalesing a compile time.
18562  *
18563  *
18564  */
18565
18566 static void different_colored(
18567         struct compile_state *state, struct reg_state *rstate, 
18568         struct triple *parent, struct triple *ins)
18569 {
18570         struct live_range *lr;
18571         struct triple **expr;
18572         lr = rstate->lrd[ins->id].lr;
18573         expr = triple_rhs(state, ins, 0);
18574         for(;expr; expr = triple_rhs(state, ins, expr)) {
18575                 struct live_range *lr2;
18576                 if (!*expr || (*expr == parent) || (*expr == ins)) {
18577                         continue;
18578                 }
18579                 lr2 = rstate->lrd[(*expr)->id].lr;
18580                 if (lr->color == lr2->color) {
18581                         internal_error(state, ins, "live range too big");
18582                 }
18583         }
18584 }
18585
18586
18587 static struct live_range *coalesce_ranges(
18588         struct compile_state *state, struct reg_state *rstate,
18589         struct live_range *lr1, struct live_range *lr2)
18590 {
18591         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18592         unsigned color;
18593         unsigned classes;
18594         if (lr1 == lr2) {
18595                 return lr1;
18596         }
18597         if (!lr1->defs || !lr2->defs) {
18598                 internal_error(state, 0,
18599                         "cannot coalese dead live ranges");
18600         }
18601         if ((lr1->color == REG_UNNEEDED) ||
18602                 (lr2->color == REG_UNNEEDED)) {
18603                 internal_error(state, 0, 
18604                         "cannot coalesce live ranges without a possible color");
18605         }
18606         if ((lr1->color != lr2->color) &&
18607                 (lr1->color != REG_UNSET) &&
18608                 (lr2->color != REG_UNSET)) {
18609                 internal_error(state, lr1->defs->def, 
18610                         "cannot coalesce live ranges of different colors");
18611         }
18612         color = lr1->color;
18613         if (color == REG_UNSET) {
18614                 color = lr2->color;
18615         }
18616         classes = lr1->classes & lr2->classes;
18617         if (!classes) {
18618                 internal_error(state, lr1->defs->def,
18619                         "cannot coalesce live ranges with dissimilar register classes");
18620         }
18621         if (state->compiler->debug & DEBUG_COALESCING) {
18622                 FILE *fp = state->errout;
18623                 fprintf(fp, "coalescing:");
18624                 lrd = lr1->defs;
18625                 do {
18626                         fprintf(fp, " %p", lrd->def);
18627                         lrd = lrd->next;
18628                 } while(lrd != lr1->defs);
18629                 fprintf(fp, " |");
18630                 lrd = lr2->defs;
18631                 do {
18632                         fprintf(fp, " %p", lrd->def);
18633                         lrd = lrd->next;
18634                 } while(lrd != lr2->defs);
18635                 fprintf(fp, "\n");
18636         }
18637         /* If there is a clear dominate live range put it in lr1,
18638          * For purposes of this test phi functions are
18639          * considered dominated by the definitions that feed into
18640          * them. 
18641          */
18642         if ((lr1->defs->prev->def->op == OP_PHI) ||
18643                 ((lr2->defs->prev->def->op != OP_PHI) &&
18644                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18645                 struct live_range *tmp;
18646                 tmp = lr1;
18647                 lr1 = lr2;
18648                 lr2 = tmp;
18649         }
18650 #if 0
18651         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
18652                 fprintf(state->errout, "lr1 post\n");
18653         }
18654         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18655                 fprintf(state->errout, "lr1 pre\n");
18656         }
18657         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
18658                 fprintf(state->errout, "lr2 post\n");
18659         }
18660         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18661                 fprintf(state->errout, "lr2 pre\n");
18662         }
18663 #endif
18664 #if 0
18665         fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18666                 lr1->defs->def,
18667                 lr1->color,
18668                 lr2->defs->def,
18669                 lr2->color);
18670 #endif
18671         
18672         /* Append lr2 onto lr1 */
18673 #warning "FIXME should this be a merge instead of a splice?"
18674         /* This FIXME item applies to the correctness of live_range_end 
18675          * and to the necessity of making multiple passes of coalesce_live_ranges.
18676          * A failure to find some coalesce opportunities in coaleace_live_ranges
18677          * does not impact the correct of the compiler just the efficiency with
18678          * which registers are allocated.
18679          */
18680         head = lr1->defs;
18681         mid1 = lr1->defs->prev;
18682         mid2 = lr2->defs;
18683         end  = lr2->defs->prev;
18684         
18685         head->prev = end;
18686         end->next  = head;
18687
18688         mid1->next = mid2;
18689         mid2->prev = mid1;
18690
18691         /* Fixup the live range in the added live range defs */
18692         lrd = head;
18693         do {
18694                 lrd->lr = lr1;
18695                 lrd = lrd->next;
18696         } while(lrd != head);
18697
18698         /* Mark lr2 as free. */
18699         lr2->defs = 0;
18700         lr2->color = REG_UNNEEDED;
18701         lr2->classes = 0;
18702
18703         if (!lr1->defs) {
18704                 internal_error(state, 0, "lr1->defs == 0 ?");
18705         }
18706
18707         lr1->color   = color;
18708         lr1->classes = classes;
18709
18710         /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18711         transfer_live_edges(rstate, lr1, lr2);
18712
18713         return lr1;
18714 }
18715
18716 static struct live_range_def *live_range_head(
18717         struct compile_state *state, struct live_range *lr,
18718         struct live_range_def *last)
18719 {
18720         struct live_range_def *result;
18721         result = 0;
18722         if (last == 0) {
18723                 result = lr->defs;
18724         }
18725         else if (!tdominates(state, lr->defs->def, last->next->def)) {
18726                 result = last->next;
18727         }
18728         return result;
18729 }
18730
18731 static struct live_range_def *live_range_end(
18732         struct compile_state *state, struct live_range *lr,
18733         struct live_range_def *last)
18734 {
18735         struct live_range_def *result;
18736         result = 0;
18737         if (last == 0) {
18738                 result = lr->defs->prev;
18739         }
18740         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18741                 result = last->prev;
18742         }
18743         return result;
18744 }
18745
18746
18747 static void initialize_live_ranges(
18748         struct compile_state *state, struct reg_state *rstate)
18749 {
18750         struct triple *ins, *first;
18751         size_t count, size;
18752         int i, j;
18753
18754         first = state->first;
18755         /* First count how many instructions I have.
18756          */
18757         count = count_triples(state);
18758         /* Potentially I need one live range definitions for each
18759          * instruction.
18760          */
18761         rstate->defs = count;
18762         /* Potentially I need one live range for each instruction
18763          * plus an extra for the dummy live range.
18764          */
18765         rstate->ranges = count + 1;
18766         size = sizeof(rstate->lrd[0]) * rstate->defs;
18767         rstate->lrd = xcmalloc(size, "live_range_def");
18768         size = sizeof(rstate->lr[0]) * rstate->ranges;
18769         rstate->lr  = xcmalloc(size, "live_range");
18770
18771         /* Setup the dummy live range */
18772         rstate->lr[0].classes = 0;
18773         rstate->lr[0].color = REG_UNSET;
18774         rstate->lr[0].defs = 0;
18775         i = j = 0;
18776         ins = first;
18777         do {
18778                 /* If the triple is a variable give it a live range */
18779                 if (triple_is_def(state, ins)) {
18780                         struct reg_info info;
18781                         /* Find the architecture specific color information */
18782                         info = find_def_color(state, ins);
18783                         i++;
18784                         rstate->lr[i].defs    = &rstate->lrd[j];
18785                         rstate->lr[i].color   = info.reg;
18786                         rstate->lr[i].classes = info.regcm;
18787                         rstate->lr[i].degree  = 0;
18788                         rstate->lrd[j].lr = &rstate->lr[i];
18789                 } 
18790                 /* Otherwise give the triple the dummy live range. */
18791                 else {
18792                         rstate->lrd[j].lr = &rstate->lr[0];
18793                 }
18794
18795                 /* Initalize the live_range_def */
18796                 rstate->lrd[j].next    = &rstate->lrd[j];
18797                 rstate->lrd[j].prev    = &rstate->lrd[j];
18798                 rstate->lrd[j].def     = ins;
18799                 rstate->lrd[j].orig_id = ins->id;
18800                 ins->id = j;
18801
18802                 j++;
18803                 ins = ins->next;
18804         } while(ins != first);
18805         rstate->ranges = i;
18806
18807         /* Make a second pass to handle achitecture specific register
18808          * constraints.
18809          */
18810         ins = first;
18811         do {
18812                 int zlhs, zrhs, i, j;
18813                 if (ins->id > rstate->defs) {
18814                         internal_error(state, ins, "bad id");
18815                 }
18816                 
18817                 /* Walk through the template of ins and coalesce live ranges */
18818                 zlhs = ins->lhs;
18819                 if ((zlhs == 0) && triple_is_def(state, ins)) {
18820                         zlhs = 1;
18821                 }
18822                 zrhs = ins->rhs;
18823
18824                 if (state->compiler->debug & DEBUG_COALESCING2) {
18825                         fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18826                                 ins, zlhs, zrhs);
18827                 }
18828
18829                 for(i = 0; i < zlhs; i++) {
18830                         struct reg_info linfo;
18831                         struct live_range_def *lhs;
18832                         linfo = arch_reg_lhs(state, ins, i);
18833                         if (linfo.reg < MAX_REGISTERS) {
18834                                 continue;
18835                         }
18836                         if (triple_is_def(state, ins)) {
18837                                 lhs = &rstate->lrd[ins->id];
18838                         } else {
18839                                 lhs = &rstate->lrd[LHS(ins, i)->id];
18840                         }
18841
18842                         if (state->compiler->debug & DEBUG_COALESCING2) {
18843                                 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18844                                         i, lhs, linfo.reg);
18845                         }
18846
18847                         for(j = 0; j < zrhs; j++) {
18848                                 struct reg_info rinfo;
18849                                 struct live_range_def *rhs;
18850                                 rinfo = arch_reg_rhs(state, ins, j);
18851                                 if (rinfo.reg < MAX_REGISTERS) {
18852                                         continue;
18853                                 }
18854                                 rhs = &rstate->lrd[RHS(ins, j)->id];
18855
18856                                 if (state->compiler->debug & DEBUG_COALESCING2) {
18857                                         fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18858                                                 j, rhs, rinfo.reg);
18859                                 }
18860
18861                                 if (rinfo.reg == linfo.reg) {
18862                                         coalesce_ranges(state, rstate, 
18863                                                 lhs->lr, rhs->lr);
18864                                 }
18865                         }
18866                 }
18867                 ins = ins->next;
18868         } while(ins != first);
18869 }
18870
18871 static void graph_ins(
18872         struct compile_state *state, 
18873         struct reg_block *blocks, struct triple_reg_set *live, 
18874         struct reg_block *rb, struct triple *ins, void *arg)
18875 {
18876         struct reg_state *rstate = arg;
18877         struct live_range *def;
18878         struct triple_reg_set *entry;
18879
18880         /* If the triple is not a definition
18881          * we do not have a definition to add to
18882          * the interference graph.
18883          */
18884         if (!triple_is_def(state, ins)) {
18885                 return;
18886         }
18887         def = rstate->lrd[ins->id].lr;
18888         
18889         /* Create an edge between ins and everything that is
18890          * alive, unless the live_range cannot share
18891          * a physical register with ins.
18892          */
18893         for(entry = live; entry; entry = entry->next) {
18894                 struct live_range *lr;
18895                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18896                         internal_error(state, 0, "bad entry?");
18897                 }
18898                 lr = rstate->lrd[entry->member->id].lr;
18899                 if (def == lr) {
18900                         continue;
18901                 }
18902                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18903                         continue;
18904                 }
18905                 add_live_edge(rstate, def, lr);
18906         }
18907         return;
18908 }
18909
18910 static struct live_range *get_verify_live_range(
18911         struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18912 {
18913         struct live_range *lr;
18914         struct live_range_def *lrd;
18915         int ins_found;
18916         if ((ins->id < 0) || (ins->id > rstate->defs)) {
18917                 internal_error(state, ins, "bad ins?");
18918         }
18919         lr = rstate->lrd[ins->id].lr;
18920         ins_found = 0;
18921         lrd = lr->defs;
18922         do {
18923                 if (lrd->def == ins) {
18924                         ins_found = 1;
18925                 }
18926                 lrd = lrd->next;
18927         } while(lrd != lr->defs);
18928         if (!ins_found) {
18929                 internal_error(state, ins, "ins not in live range");
18930         }
18931         return lr;
18932 }
18933
18934 static void verify_graph_ins(
18935         struct compile_state *state, 
18936         struct reg_block *blocks, struct triple_reg_set *live, 
18937         struct reg_block *rb, struct triple *ins, void *arg)
18938 {
18939         struct reg_state *rstate = arg;
18940         struct triple_reg_set *entry1, *entry2;
18941
18942
18943         /* Compare live against edges and make certain the code is working */
18944         for(entry1 = live; entry1; entry1 = entry1->next) {
18945                 struct live_range *lr1;
18946                 lr1 = get_verify_live_range(state, rstate, entry1->member);
18947                 for(entry2 = live; entry2; entry2 = entry2->next) {
18948                         struct live_range *lr2;
18949                         struct live_range_edge *edge2;
18950                         int lr1_found;
18951                         int lr2_degree;
18952                         if (entry2 == entry1) {
18953                                 continue;
18954                         }
18955                         lr2 = get_verify_live_range(state, rstate, entry2->member);
18956                         if (lr1 == lr2) {
18957                                 internal_error(state, entry2->member, 
18958                                         "live range with 2 values simultaneously alive");
18959                         }
18960                         if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
18961                                 continue;
18962                         }
18963                         if (!interfere(rstate, lr1, lr2)) {
18964                                 internal_error(state, entry2->member, 
18965                                         "edges don't interfere?");
18966                         }
18967                                 
18968                         lr1_found = 0;
18969                         lr2_degree = 0;
18970                         for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
18971                                 lr2_degree++;
18972                                 if (edge2->node == lr1) {
18973                                         lr1_found = 1;
18974                                 }
18975                         }
18976                         if (lr2_degree != lr2->degree) {
18977                                 internal_error(state, entry2->member,
18978                                         "computed degree: %d does not match reported degree: %d\n",
18979                                         lr2_degree, lr2->degree);
18980                         }
18981                         if (!lr1_found) {
18982                                 internal_error(state, entry2->member, "missing edge");
18983                         }
18984                 }
18985         }
18986         return;
18987 }
18988
18989
18990 static void print_interference_ins(
18991         struct compile_state *state, 
18992         struct reg_block *blocks, struct triple_reg_set *live, 
18993         struct reg_block *rb, struct triple *ins, void *arg)
18994 {
18995         struct reg_state *rstate = arg;
18996         struct live_range *lr;
18997         unsigned id;
18998         FILE *fp = state->dbgout;
18999
19000         lr = rstate->lrd[ins->id].lr;
19001         id = ins->id;
19002         ins->id = rstate->lrd[id].orig_id;
19003         SET_REG(ins->id, lr->color);
19004         display_triple(state->dbgout, ins);
19005         ins->id = id;
19006
19007         if (lr->defs) {
19008                 struct live_range_def *lrd;
19009                 fprintf(fp, "       range:");
19010                 lrd = lr->defs;
19011                 do {
19012                         fprintf(fp, " %-10p", lrd->def);
19013                         lrd = lrd->next;
19014                 } while(lrd != lr->defs);
19015                 fprintf(fp, "\n");
19016         }
19017         if (live) {
19018                 struct triple_reg_set *entry;
19019                 fprintf(fp, "        live:");
19020                 for(entry = live; entry; entry = entry->next) {
19021                         fprintf(fp, " %-10p", entry->member);
19022                 }
19023                 fprintf(fp, "\n");
19024         }
19025         if (lr->edges) {
19026                 struct live_range_edge *entry;
19027                 fprintf(fp, "       edges:");
19028                 for(entry = lr->edges; entry; entry = entry->next) {
19029                         struct live_range_def *lrd;
19030                         lrd = entry->node->defs;
19031                         do {
19032                                 fprintf(fp, " %-10p", lrd->def);
19033                                 lrd = lrd->next;
19034                         } while(lrd != entry->node->defs);
19035                         fprintf(fp, "|");
19036                 }
19037                 fprintf(fp, "\n");
19038         }
19039         if (triple_is_branch(state, ins)) {
19040                 fprintf(fp, "\n");
19041         }
19042         return;
19043 }
19044
19045 static int coalesce_live_ranges(
19046         struct compile_state *state, struct reg_state *rstate)
19047 {
19048         /* At the point where a value is moved from one
19049          * register to another that value requires two
19050          * registers, thus increasing register pressure.
19051          * Live range coaleescing reduces the register
19052          * pressure by keeping a value in one register
19053          * longer.
19054          *
19055          * In the case of a phi function all paths leading
19056          * into it must be allocated to the same register
19057          * otherwise the phi function may not be removed.
19058          *
19059          * Forcing a value to stay in a single register
19060          * for an extended period of time does have
19061          * limitations when applied to non homogenous
19062          * register pool.  
19063          *
19064          * The two cases I have identified are:
19065          * 1) Two forced register assignments may
19066          *    collide.
19067          * 2) Registers may go unused because they
19068          *    are only good for storing the value
19069          *    and not manipulating it.
19070          *
19071          * Because of this I need to split live ranges,
19072          * even outside of the context of coalesced live
19073          * ranges.  The need to split live ranges does
19074          * impose some constraints on live range coalescing.
19075          *
19076          * - Live ranges may not be coalesced across phi
19077          *   functions.  This creates a 2 headed live
19078          *   range that cannot be sanely split.
19079          *
19080          * - phi functions (coalesced in initialize_live_ranges) 
19081          *   are handled as pre split live ranges so we will
19082          *   never attempt to split them.
19083          */
19084         int coalesced;
19085         int i;
19086
19087         coalesced = 0;
19088         for(i = 0; i <= rstate->ranges; i++) {
19089                 struct live_range *lr1;
19090                 struct live_range_def *lrd1;
19091                 lr1 = &rstate->lr[i];
19092                 if (!lr1->defs) {
19093                         continue;
19094                 }
19095                 lrd1 = live_range_end(state, lr1, 0);
19096                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19097                         struct triple_set *set;
19098                         if (lrd1->def->op != OP_COPY) {
19099                                 continue;
19100                         }
19101                         /* Skip copies that are the result of a live range split. */
19102                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19103                                 continue;
19104                         }
19105                         for(set = lrd1->def->use; set; set = set->next) {
19106                                 struct live_range_def *lrd2;
19107                                 struct live_range *lr2, *res;
19108
19109                                 lrd2 = &rstate->lrd[set->member->id];
19110
19111                                 /* Don't coalesce with instructions
19112                                  * that are the result of a live range
19113                                  * split.
19114                                  */
19115                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19116                                         continue;
19117                                 }
19118                                 lr2 = rstate->lrd[set->member->id].lr;
19119                                 if (lr1 == lr2) {
19120                                         continue;
19121                                 }
19122                                 if ((lr1->color != lr2->color) &&
19123                                         (lr1->color != REG_UNSET) &&
19124                                         (lr2->color != REG_UNSET)) {
19125                                         continue;
19126                                 }
19127                                 if ((lr1->classes & lr2->classes) == 0) {
19128                                         continue;
19129                                 }
19130                                 
19131                                 if (interfere(rstate, lr1, lr2)) {
19132                                         continue;
19133                                 }
19134
19135                                 res = coalesce_ranges(state, rstate, lr1, lr2);
19136                                 coalesced += 1;
19137                                 if (res != lr1) {
19138                                         goto next;
19139                                 }
19140                         }
19141                 }
19142         next:
19143                 ;
19144         }
19145         return coalesced;
19146 }
19147
19148
19149 static void fix_coalesce_conflicts(struct compile_state *state,
19150         struct reg_block *blocks, struct triple_reg_set *live,
19151         struct reg_block *rb, struct triple *ins, void *arg)
19152 {
19153         int *conflicts = arg;
19154         int zlhs, zrhs, i, j;
19155
19156         /* See if we have a mandatory coalesce operation between
19157          * a lhs and a rhs value.  If so and the rhs value is also
19158          * alive then this triple needs to be pre copied.  Otherwise
19159          * we would have two definitions in the same live range simultaneously
19160          * alive.
19161          */
19162         zlhs = ins->lhs;
19163         if ((zlhs == 0) && triple_is_def(state, ins)) {
19164                 zlhs = 1;
19165         }
19166         zrhs = ins->rhs;
19167         for(i = 0; i < zlhs; i++) {
19168                 struct reg_info linfo;
19169                 linfo = arch_reg_lhs(state, ins, i);
19170                 if (linfo.reg < MAX_REGISTERS) {
19171                         continue;
19172                 }
19173                 for(j = 0; j < zrhs; j++) {
19174                         struct reg_info rinfo;
19175                         struct triple *rhs;
19176                         struct triple_reg_set *set;
19177                         int found;
19178                         found = 0;
19179                         rinfo = arch_reg_rhs(state, ins, j);
19180                         if (rinfo.reg != linfo.reg) {
19181                                 continue;
19182                         }
19183                         rhs = RHS(ins, j);
19184                         for(set = live; set && !found; set = set->next) {
19185                                 if (set->member == rhs) {
19186                                         found = 1;
19187                                 }
19188                         }
19189                         if (found) {
19190                                 struct triple *copy;
19191                                 copy = pre_copy(state, ins, j);
19192                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19193                                 (*conflicts)++;
19194                         }
19195                 }
19196         }
19197         return;
19198 }
19199
19200 static int correct_coalesce_conflicts(
19201         struct compile_state *state, struct reg_block *blocks)
19202 {
19203         int conflicts;
19204         conflicts = 0;
19205         walk_variable_lifetimes(state, &state->bb, blocks, 
19206                 fix_coalesce_conflicts, &conflicts);
19207         return conflicts;
19208 }
19209
19210 static void replace_set_use(struct compile_state *state,
19211         struct triple_reg_set *head, struct triple *orig, struct triple *new)
19212 {
19213         struct triple_reg_set *set;
19214         for(set = head; set; set = set->next) {
19215                 if (set->member == orig) {
19216                         set->member = new;
19217                 }
19218         }
19219 }
19220
19221 static void replace_block_use(struct compile_state *state, 
19222         struct reg_block *blocks, struct triple *orig, struct triple *new)
19223 {
19224         int i;
19225 #warning "WISHLIST visit just those blocks that need it *"
19226         for(i = 1; i <= state->bb.last_vertex; i++) {
19227                 struct reg_block *rb;
19228                 rb = &blocks[i];
19229                 replace_set_use(state, rb->in, orig, new);
19230                 replace_set_use(state, rb->out, orig, new);
19231         }
19232 }
19233
19234 static void color_instructions(struct compile_state *state)
19235 {
19236         struct triple *ins, *first;
19237         first = state->first;
19238         ins = first;
19239         do {
19240                 if (triple_is_def(state, ins)) {
19241                         struct reg_info info;
19242                         info = find_lhs_color(state, ins, 0);
19243                         if (info.reg >= MAX_REGISTERS) {
19244                                 info.reg = REG_UNSET;
19245                         }
19246                         SET_INFO(ins->id, info);
19247                 }
19248                 ins = ins->next;
19249         } while(ins != first);
19250 }
19251
19252 static struct reg_info read_lhs_color(
19253         struct compile_state *state, struct triple *ins, int index)
19254 {
19255         struct reg_info info;
19256         if ((index == 0) && triple_is_def(state, ins)) {
19257                 info.reg   = ID_REG(ins->id);
19258                 info.regcm = ID_REGCM(ins->id);
19259         }
19260         else if (index < ins->lhs) {
19261                 info = read_lhs_color(state, LHS(ins, index), 0);
19262         }
19263         else {
19264                 internal_error(state, ins, "Bad lhs %d", index);
19265                 info.reg = REG_UNSET;
19266                 info.regcm = 0;
19267         }
19268         return info;
19269 }
19270
19271 static struct triple *resolve_tangle(
19272         struct compile_state *state, struct triple *tangle)
19273 {
19274         struct reg_info info, uinfo;
19275         struct triple_set *set, *next;
19276         struct triple *copy;
19277
19278 #warning "WISHLIST recalculate all affected instructions colors"
19279         info = find_lhs_color(state, tangle, 0);
19280         for(set = tangle->use; set; set = next) {
19281                 struct triple *user;
19282                 int i, zrhs;
19283                 next = set->next;
19284                 user = set->member;
19285                 zrhs = user->rhs;
19286                 for(i = 0; i < zrhs; i++) {
19287                         if (RHS(user, i) != tangle) {
19288                                 continue;
19289                         }
19290                         uinfo = find_rhs_post_color(state, user, i);
19291                         if (uinfo.reg == info.reg) {
19292                                 copy = pre_copy(state, user, i);
19293                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19294                                 SET_INFO(copy->id, uinfo);
19295                         }
19296                 }
19297         }
19298         copy = 0;
19299         uinfo = find_lhs_pre_color(state, tangle, 0);
19300         if (uinfo.reg == info.reg) {
19301                 struct reg_info linfo;
19302                 copy = post_copy(state, tangle);
19303                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19304                 linfo = find_lhs_color(state, copy, 0);
19305                 SET_INFO(copy->id, linfo);
19306         }
19307         info = find_lhs_color(state, tangle, 0);
19308         SET_INFO(tangle->id, info);
19309         
19310         return copy;
19311 }
19312
19313
19314 static void fix_tangles(struct compile_state *state,
19315         struct reg_block *blocks, struct triple_reg_set *live,
19316         struct reg_block *rb, struct triple *ins, void *arg)
19317 {
19318         int *tangles = arg;
19319         struct triple *tangle;
19320         do {
19321                 char used[MAX_REGISTERS];
19322                 struct triple_reg_set *set;
19323                 tangle = 0;
19324
19325                 /* Find out which registers have multiple uses at this point */
19326                 memset(used, 0, sizeof(used));
19327                 for(set = live; set; set = set->next) {
19328                         struct reg_info info;
19329                         info = read_lhs_color(state, set->member, 0);
19330                         if (info.reg == REG_UNSET) {
19331                                 continue;
19332                         }
19333                         reg_inc_used(state, used, info.reg);
19334                 }
19335                 
19336                 /* Now find the least dominated definition of a register in
19337                  * conflict I have seen so far.
19338                  */
19339                 for(set = live; set; set = set->next) {
19340                         struct reg_info info;
19341                         info = read_lhs_color(state, set->member, 0);
19342                         if (used[info.reg] < 2) {
19343                                 continue;
19344                         }
19345                         /* Changing copies that feed into phi functions
19346                          * is incorrect.
19347                          */
19348                         if (set->member->use && 
19349                                 (set->member->use->member->op == OP_PHI)) {
19350                                 continue;
19351                         }
19352                         if (!tangle || tdominates(state, set->member, tangle)) {
19353                                 tangle = set->member;
19354                         }
19355                 }
19356                 /* If I have found a tangle resolve it */
19357                 if (tangle) {
19358                         struct triple *post_copy;
19359                         (*tangles)++;
19360                         post_copy = resolve_tangle(state, tangle);
19361                         if (post_copy) {
19362                                 replace_block_use(state, blocks, tangle, post_copy);
19363                         }
19364                         if (post_copy && (tangle != ins)) {
19365                                 replace_set_use(state, live, tangle, post_copy);
19366                         }
19367                 }
19368         } while(tangle);
19369         return;
19370 }
19371
19372 static int correct_tangles(
19373         struct compile_state *state, struct reg_block *blocks)
19374 {
19375         int tangles;
19376         tangles = 0;
19377         color_instructions(state);
19378         walk_variable_lifetimes(state, &state->bb, blocks, 
19379                 fix_tangles, &tangles);
19380         return tangles;
19381 }
19382
19383
19384 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19385 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19386
19387 struct triple *find_constrained_def(
19388         struct compile_state *state, struct live_range *range, struct triple *constrained)
19389 {
19390         struct live_range_def *lrd, *lrd_next;
19391         lrd_next = range->defs;
19392         do {
19393                 struct reg_info info;
19394                 unsigned regcm;
19395
19396                 lrd = lrd_next;
19397                 lrd_next = lrd->next;
19398
19399                 regcm = arch_type_to_regcm(state, lrd->def->type);
19400                 info = find_lhs_color(state, lrd->def, 0);
19401                 regcm      = arch_regcm_reg_normalize(state, regcm);
19402                 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19403                 /* If the 2 register class masks are equal then
19404                  * the current register class is not constrained.
19405                  */
19406                 if (regcm == info.regcm) {
19407                         continue;
19408                 }
19409                 
19410                 /* If there is just one use.
19411                  * That use cannot accept a larger register class.
19412                  * There are no intervening definitions except
19413                  * definitions that feed into that use.
19414                  * Then a triple is not constrained.
19415                  * FIXME handle this case!
19416                  */
19417 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19418                 
19419
19420                 /* Of the constrained live ranges deal with the
19421                  * least dominated one first.
19422                  */
19423                 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19424                         fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19425                                 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19426                 }
19427                 if (!constrained || 
19428                         tdominates(state, lrd->def, constrained))
19429                 {
19430                         constrained = lrd->def;
19431                 }
19432         } while(lrd_next != range->defs);
19433         return constrained;
19434 }
19435
19436 static int split_constrained_ranges(
19437         struct compile_state *state, struct reg_state *rstate, 
19438         struct live_range *range)
19439 {
19440         /* Walk through the edges in conflict and our current live
19441          * range, and find definitions that are more severly constrained
19442          * than they type of data they contain require.
19443          * 
19444          * Then pick one of those ranges and relax the constraints.
19445          */
19446         struct live_range_edge *edge;
19447         struct triple *constrained;
19448
19449         constrained = 0;
19450         for(edge = range->edges; edge; edge = edge->next) {
19451                 constrained = find_constrained_def(state, edge->node, constrained);
19452         }
19453 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19454         if (!constrained) {
19455                 constrained = find_constrained_def(state, range, constrained);
19456         }
19457
19458         if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19459                 fprintf(state->errout, "constrained: ");
19460                 display_triple(state->errout, constrained);
19461         }
19462         if (constrained) {
19463                 ids_from_rstate(state, rstate);
19464                 cleanup_rstate(state, rstate);
19465                 resolve_tangle(state, constrained);
19466         }
19467         return !!constrained;
19468 }
19469         
19470 static int split_ranges(
19471         struct compile_state *state, struct reg_state *rstate,
19472         char *used, struct live_range *range)
19473 {
19474         int split;
19475         if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19476                 fprintf(state->errout, "split_ranges %d %s %p\n", 
19477                         rstate->passes, tops(range->defs->def->op), range->defs->def);
19478         }
19479         if ((range->color == REG_UNNEEDED) ||
19480                 (rstate->passes >= rstate->max_passes)) {
19481                 return 0;
19482         }
19483         split = split_constrained_ranges(state, rstate, range);
19484
19485         /* Ideally I would split the live range that will not be used
19486          * for the longest period of time in hopes that this will 
19487          * (a) allow me to spill a register or
19488          * (b) allow me to place a value in another register.
19489          *
19490          * So far I don't have a test case for this, the resolving
19491          * of mandatory constraints has solved all of my
19492          * know issues.  So I have choosen not to write any
19493          * code until I cat get a better feel for cases where
19494          * it would be useful to have.
19495          *
19496          */
19497 #warning "WISHLIST implement live range splitting..."
19498         
19499         if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19500                 FILE *fp = state->errout;
19501                 print_interference_blocks(state, rstate, fp, 0);
19502                 print_dominators(state, fp, &state->bb);
19503         }
19504         return split;
19505 }
19506
19507 static FILE *cgdebug_fp(struct compile_state *state)
19508 {
19509         FILE *fp;
19510         fp = 0;
19511         if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19512                 fp = state->errout;
19513         }
19514         if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19515                 fp = state->dbgout;
19516         }
19517         return fp;
19518 }
19519
19520 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19521 {
19522         FILE *fp;
19523         fp = cgdebug_fp(state);
19524         if (fp) {
19525                 va_list args;
19526                 va_start(args, fmt);
19527                 vfprintf(fp, fmt, args);
19528                 va_end(args);
19529         }
19530 }
19531
19532 static void cgdebug_flush(struct compile_state *state)
19533 {
19534         FILE *fp;
19535         fp = cgdebug_fp(state);
19536         if (fp) {
19537                 fflush(fp);
19538         }
19539 }
19540
19541 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19542 {
19543         FILE *fp;
19544         fp = cgdebug_fp(state);
19545         if (fp) {
19546                 loc(fp, state, ins);
19547         }
19548 }
19549
19550 static int select_free_color(struct compile_state *state, 
19551         struct reg_state *rstate, struct live_range *range)
19552 {
19553         struct triple_set *entry;
19554         struct live_range_def *lrd;
19555         struct live_range_def *phi;
19556         struct live_range_edge *edge;
19557         char used[MAX_REGISTERS];
19558         struct triple **expr;
19559
19560         /* Instead of doing just the trivial color select here I try
19561          * a few extra things because a good color selection will help reduce
19562          * copies.
19563          */
19564
19565         /* Find the registers currently in use */
19566         memset(used, 0, sizeof(used));
19567         for(edge = range->edges; edge; edge = edge->next) {
19568                 if (edge->node->color == REG_UNSET) {
19569                         continue;
19570                 }
19571                 reg_fill_used(state, used, edge->node->color);
19572         }
19573
19574         if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19575                 int i;
19576                 i = 0;
19577                 for(edge = range->edges; edge; edge = edge->next) {
19578                         i++;
19579                 }
19580                 cgdebug_printf(state, "\n%s edges: %d", 
19581                         tops(range->defs->def->op), i);
19582                 cgdebug_loc(state, range->defs->def);
19583                 cgdebug_printf(state, "\n");
19584                 for(i = 0; i < MAX_REGISTERS; i++) {
19585                         if (used[i]) {
19586                                 cgdebug_printf(state, "used: %s\n",
19587                                         arch_reg_str(i));
19588                         }
19589                 }
19590         }       
19591
19592         /* If a color is already assigned see if it will work */
19593         if (range->color != REG_UNSET) {
19594                 struct live_range_def *lrd;
19595                 if (!used[range->color]) {
19596                         return 1;
19597                 }
19598                 for(edge = range->edges; edge; edge = edge->next) {
19599                         if (edge->node->color != range->color) {
19600                                 continue;
19601                         }
19602                         warning(state, edge->node->defs->def, "edge: ");
19603                         lrd = edge->node->defs;
19604                         do {
19605                                 warning(state, lrd->def, " %p %s",
19606                                         lrd->def, tops(lrd->def->op));
19607                                 lrd = lrd->next;
19608                         } while(lrd != edge->node->defs);
19609                 }
19610                 lrd = range->defs;
19611                 warning(state, range->defs->def, "def: ");
19612                 do {
19613                         warning(state, lrd->def, " %p %s",
19614                                 lrd->def, tops(lrd->def->op));
19615                         lrd = lrd->next;
19616                 } while(lrd != range->defs);
19617                 internal_error(state, range->defs->def,
19618                         "live range with already used color %s",
19619                         arch_reg_str(range->color));
19620         }
19621
19622         /* If I feed into an expression reuse it's color.
19623          * This should help remove copies in the case of 2 register instructions
19624          * and phi functions.
19625          */
19626         phi = 0;
19627         lrd = live_range_end(state, range, 0);
19628         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19629                 entry = lrd->def->use;
19630                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19631                         struct live_range_def *insd;
19632                         unsigned regcm;
19633                         insd = &rstate->lrd[entry->member->id];
19634                         if (insd->lr->defs == 0) {
19635                                 continue;
19636                         }
19637                         if (!phi && (insd->def->op == OP_PHI) &&
19638                                 !interfere(rstate, range, insd->lr)) {
19639                                 phi = insd;
19640                         }
19641                         if (insd->lr->color == REG_UNSET) {
19642                                 continue;
19643                         }
19644                         regcm = insd->lr->classes;
19645                         if (((regcm & range->classes) == 0) ||
19646                                 (used[insd->lr->color])) {
19647                                 continue;
19648                         }
19649                         if (interfere(rstate, range, insd->lr)) {
19650                                 continue;
19651                         }
19652                         range->color = insd->lr->color;
19653                 }
19654         }
19655         /* If I feed into a phi function reuse it's color or the color
19656          * of something else that feeds into the phi function.
19657          */
19658         if (phi) {
19659                 if (phi->lr->color != REG_UNSET) {
19660                         if (used[phi->lr->color]) {
19661                                 range->color = phi->lr->color;
19662                         }
19663                 }
19664                 else {
19665                         expr = triple_rhs(state, phi->def, 0);
19666                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19667                                 struct live_range *lr;
19668                                 unsigned regcm;
19669                                 if (!*expr) {
19670                                         continue;
19671                                 }
19672                                 lr = rstate->lrd[(*expr)->id].lr;
19673                                 if (lr->color == REG_UNSET) {
19674                                         continue;
19675                                 }
19676                                 regcm = lr->classes;
19677                                 if (((regcm & range->classes) == 0) ||
19678                                         (used[lr->color])) {
19679                                         continue;
19680                                 }
19681                                 if (interfere(rstate, range, lr)) {
19682                                         continue;
19683                                 }
19684                                 range->color = lr->color;
19685                         }
19686                 }
19687         }
19688         /* If I don't interfere with a rhs node reuse it's color */
19689         lrd = live_range_head(state, range, 0);
19690         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19691                 expr = triple_rhs(state, lrd->def, 0);
19692                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19693                         struct live_range *lr;
19694                         unsigned regcm;
19695                         if (!*expr) {
19696                                 continue;
19697                         }
19698                         lr = rstate->lrd[(*expr)->id].lr;
19699                         if (lr->color == REG_UNSET) {
19700                                 continue;
19701                         }
19702                         regcm = lr->classes;
19703                         if (((regcm & range->classes) == 0) ||
19704                                 (used[lr->color])) {
19705                                 continue;
19706                         }
19707                         if (interfere(rstate, range, lr)) {
19708                                 continue;
19709                         }
19710                         range->color = lr->color;
19711                         break;
19712                 }
19713         }
19714         /* If I have not opportunitically picked a useful color
19715          * pick the first color that is free.
19716          */
19717         if (range->color == REG_UNSET) {
19718                 range->color = 
19719                         arch_select_free_register(state, used, range->classes);
19720         }
19721         if (range->color == REG_UNSET) {
19722                 struct live_range_def *lrd;
19723                 int i;
19724                 if (split_ranges(state, rstate, used, range)) {
19725                         return 0;
19726                 }
19727                 for(edge = range->edges; edge; edge = edge->next) {
19728                         warning(state, edge->node->defs->def, "edge reg %s",
19729                                 arch_reg_str(edge->node->color));
19730                         lrd = edge->node->defs;
19731                         do {
19732                                 warning(state, lrd->def, " %s %p",
19733                                         tops(lrd->def->op), lrd->def);
19734                                 lrd = lrd->next;
19735                         } while(lrd != edge->node->defs);
19736                 }
19737                 warning(state, range->defs->def, "range: ");
19738                 lrd = range->defs;
19739                 do {
19740                         warning(state, lrd->def, " %s %p",
19741                                 tops(lrd->def->op), lrd->def);
19742                         lrd = lrd->next;
19743                 } while(lrd != range->defs);
19744                         
19745                 warning(state, range->defs->def, "classes: %x",
19746                         range->classes);
19747                 for(i = 0; i < MAX_REGISTERS; i++) {
19748                         if (used[i]) {
19749                                 warning(state, range->defs->def, "used: %s",
19750                                         arch_reg_str(i));
19751                         }
19752                 }
19753                 error(state, range->defs->def, "too few registers");
19754         }
19755         range->classes &= arch_reg_regcm(state, range->color);
19756         if ((range->color == REG_UNSET) || (range->classes == 0)) {
19757                 internal_error(state, range->defs->def, "select_free_color did not?");
19758         }
19759         return 1;
19760 }
19761
19762 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19763 {
19764         int colored;
19765         struct live_range_edge *edge;
19766         struct live_range *range;
19767         if (rstate->low) {
19768                 cgdebug_printf(state, "Lo: ");
19769                 range = rstate->low;
19770                 if (*range->group_prev != range) {
19771                         internal_error(state, 0, "lo: *prev != range?");
19772                 }
19773                 *range->group_prev = range->group_next;
19774                 if (range->group_next) {
19775                         range->group_next->group_prev = range->group_prev;
19776                 }
19777                 if (&range->group_next == rstate->low_tail) {
19778                         rstate->low_tail = range->group_prev;
19779                 }
19780                 if (rstate->low == range) {
19781                         internal_error(state, 0, "low: next != prev?");
19782                 }
19783         }
19784         else if (rstate->high) {
19785                 cgdebug_printf(state, "Hi: ");
19786                 range = rstate->high;
19787                 if (*range->group_prev != range) {
19788                         internal_error(state, 0, "hi: *prev != range?");
19789                 }
19790                 *range->group_prev = range->group_next;
19791                 if (range->group_next) {
19792                         range->group_next->group_prev = range->group_prev;
19793                 }
19794                 if (&range->group_next == rstate->high_tail) {
19795                         rstate->high_tail = range->group_prev;
19796                 }
19797                 if (rstate->high == range) {
19798                         internal_error(state, 0, "high: next != prev?");
19799                 }
19800         }
19801         else {
19802                 return 1;
19803         }
19804         cgdebug_printf(state, " %d\n", range - rstate->lr);
19805         range->group_prev = 0;
19806         for(edge = range->edges; edge; edge = edge->next) {
19807                 struct live_range *node;
19808                 node = edge->node;
19809                 /* Move nodes from the high to the low list */
19810                 if (node->group_prev && (node->color == REG_UNSET) &&
19811                         (node->degree == regc_max_size(state, node->classes))) {
19812                         if (*node->group_prev != node) {
19813                                 internal_error(state, 0, "move: *prev != node?");
19814                         }
19815                         *node->group_prev = node->group_next;
19816                         if (node->group_next) {
19817                                 node->group_next->group_prev = node->group_prev;
19818                         }
19819                         if (&node->group_next == rstate->high_tail) {
19820                                 rstate->high_tail = node->group_prev;
19821                         }
19822                         cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19823                         node->group_prev  = rstate->low_tail;
19824                         node->group_next  = 0;
19825                         *rstate->low_tail = node;
19826                         rstate->low_tail  = &node->group_next;
19827                         if (*node->group_prev != node) {
19828                                 internal_error(state, 0, "move2: *prev != node?");
19829                         }
19830                 }
19831                 node->degree -= 1;
19832         }
19833         colored = color_graph(state, rstate);
19834         if (colored) {
19835                 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19836                 cgdebug_loc(state, range->defs->def);
19837                 cgdebug_flush(state);
19838                 colored = select_free_color(state, rstate, range);
19839                 if (colored) {
19840                         cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19841                 }
19842         }
19843         return colored;
19844 }
19845
19846 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19847 {
19848         struct live_range *lr;
19849         struct live_range_edge *edge;
19850         struct triple *ins, *first;
19851         char used[MAX_REGISTERS];
19852         first = state->first;
19853         ins = first;
19854         do {
19855                 if (triple_is_def(state, ins)) {
19856                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
19857                                 internal_error(state, ins, 
19858                                         "triple without a live range def");
19859                         }
19860                         lr = rstate->lrd[ins->id].lr;
19861                         if (lr->color == REG_UNSET) {
19862                                 internal_error(state, ins,
19863                                         "triple without a color");
19864                         }
19865                         /* Find the registers used by the edges */
19866                         memset(used, 0, sizeof(used));
19867                         for(edge = lr->edges; edge; edge = edge->next) {
19868                                 if (edge->node->color == REG_UNSET) {
19869                                         internal_error(state, 0,
19870                                                 "live range without a color");
19871                         }
19872                                 reg_fill_used(state, used, edge->node->color);
19873                         }
19874                         if (used[lr->color]) {
19875                                 internal_error(state, ins,
19876                                         "triple with already used color");
19877                         }
19878                 }
19879                 ins = ins->next;
19880         } while(ins != first);
19881 }
19882
19883 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19884 {
19885         struct live_range_def *lrd;
19886         struct live_range *lr;
19887         struct triple *first, *ins;
19888         first = state->first;
19889         ins = first;
19890         do {
19891                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19892                         internal_error(state, ins, 
19893                                 "triple without a live range");
19894                 }
19895                 lrd = &rstate->lrd[ins->id];
19896                 lr = lrd->lr;
19897                 ins->id = lrd->orig_id;
19898                 SET_REG(ins->id, lr->color);
19899                 ins = ins->next;
19900         } while (ins != first);
19901 }
19902
19903 static struct live_range *merge_sort_lr(
19904         struct live_range *first, struct live_range *last)
19905 {
19906         struct live_range *mid, *join, **join_tail, *pick;
19907         size_t size;
19908         size = (last - first) + 1;
19909         if (size >= 2) {
19910                 mid = first + size/2;
19911                 first = merge_sort_lr(first, mid -1);
19912                 mid   = merge_sort_lr(mid, last);
19913                 
19914                 join = 0;
19915                 join_tail = &join;
19916                 /* merge the two lists */
19917                 while(first && mid) {
19918                         if ((first->degree < mid->degree) ||
19919                                 ((first->degree == mid->degree) &&
19920                                         (first->length < mid->length))) {
19921                                 pick = first;
19922                                 first = first->group_next;
19923                                 if (first) {
19924                                         first->group_prev = 0;
19925                                 }
19926                         }
19927                         else {
19928                                 pick = mid;
19929                                 mid = mid->group_next;
19930                                 if (mid) {
19931                                         mid->group_prev = 0;
19932                                 }
19933                         }
19934                         pick->group_next = 0;
19935                         pick->group_prev = join_tail;
19936                         *join_tail = pick;
19937                         join_tail = &pick->group_next;
19938                 }
19939                 /* Splice the remaining list */
19940                 pick = (first)? first : mid;
19941                 *join_tail = pick;
19942                 if (pick) { 
19943                         pick->group_prev = join_tail;
19944                 }
19945         }
19946         else {
19947                 if (!first->defs) {
19948                         first = 0;
19949                 }
19950                 join = first;
19951         }
19952         return join;
19953 }
19954
19955 static void ids_from_rstate(struct compile_state *state, 
19956         struct reg_state *rstate)
19957 {
19958         struct triple *ins, *first;
19959         if (!rstate->defs) {
19960                 return;
19961         }
19962         /* Display the graph if desired */
19963         if (state->compiler->debug & DEBUG_INTERFERENCE) {
19964                 FILE *fp = state->dbgout;
19965                 print_interference_blocks(state, rstate, fp, 0);
19966                 print_control_flow(state, fp, &state->bb);
19967                 fflush(fp);
19968         }
19969         first = state->first;
19970         ins = first;
19971         do {
19972                 if (ins->id) {
19973                         struct live_range_def *lrd;
19974                         lrd = &rstate->lrd[ins->id];
19975                         ins->id = lrd->orig_id;
19976                 }
19977                 ins = ins->next;
19978         } while(ins != first);
19979 }
19980
19981 static void cleanup_live_edges(struct reg_state *rstate)
19982 {
19983         int i;
19984         /* Free the edges on each node */
19985         for(i = 1; i <= rstate->ranges; i++) {
19986                 remove_live_edges(rstate, &rstate->lr[i]);
19987         }
19988 }
19989
19990 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
19991 {
19992         cleanup_live_edges(rstate);
19993         xfree(rstate->lrd);
19994         xfree(rstate->lr);
19995
19996         /* Free the variable lifetime information */
19997         if (rstate->blocks) {
19998                 free_variable_lifetimes(state, &state->bb, rstate->blocks);
19999         }
20000         rstate->defs = 0;
20001         rstate->ranges = 0;
20002         rstate->lrd = 0;
20003         rstate->lr = 0;
20004         rstate->blocks = 0;
20005 }
20006
20007 static void verify_consistency(struct compile_state *state);
20008 static void allocate_registers(struct compile_state *state)
20009 {
20010         struct reg_state rstate;
20011         int colored;
20012
20013         /* Clear out the reg_state */
20014         memset(&rstate, 0, sizeof(rstate));
20015         rstate.max_passes = state->compiler->max_allocation_passes;
20016
20017         do {
20018                 struct live_range **point, **next;
20019                 int conflicts;
20020                 int tangles;
20021                 int coalesced;
20022
20023                 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
20024                         FILE *fp = state->errout;
20025                         fprintf(fp, "pass: %d\n", rstate.passes);
20026                         fflush(fp);
20027                 }
20028
20029                 /* Restore ids */
20030                 ids_from_rstate(state, &rstate);
20031
20032                 /* Cleanup the temporary data structures */
20033                 cleanup_rstate(state, &rstate);
20034
20035                 /* Compute the variable lifetimes */
20036                 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20037
20038                 /* Fix invalid mandatory live range coalesce conflicts */
20039                 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
20040
20041                 /* Fix two simultaneous uses of the same register.
20042                  * In a few pathlogical cases a partial untangle moves
20043                  * the tangle to a part of the graph we won't revisit.
20044                  * So we keep looping until we have no more tangle fixes
20045                  * to apply.
20046                  */
20047                 do {
20048                         tangles = correct_tangles(state, rstate.blocks);
20049                 } while(tangles);
20050
20051                 
20052                 print_blocks(state, "resolve_tangles", state->dbgout);
20053                 verify_consistency(state);
20054                 
20055                 /* Allocate and initialize the live ranges */
20056                 initialize_live_ranges(state, &rstate);
20057
20058                 /* Note currently doing coalescing in a loop appears to 
20059                  * buys me nothing.  The code is left this way in case
20060                  * there is some value in it.  Or if a future bugfix
20061                  * yields some benefit.
20062                  */
20063                 do {
20064                         if (state->compiler->debug & DEBUG_COALESCING) {
20065                                 fprintf(state->errout, "coalescing\n");
20066                         }
20067
20068                         /* Remove any previous live edge calculations */
20069                         cleanup_live_edges(&rstate);
20070
20071                         /* Compute the interference graph */
20072                         walk_variable_lifetimes(
20073                                 state, &state->bb, rstate.blocks, 
20074                                 graph_ins, &rstate);
20075                         
20076                         /* Display the interference graph if desired */
20077                         if (state->compiler->debug & DEBUG_INTERFERENCE) {
20078                                 print_interference_blocks(state, &rstate, state->dbgout, 1);
20079                                 fprintf(state->dbgout, "\nlive variables by instruction\n");
20080                                 walk_variable_lifetimes(
20081                                         state, &state->bb, rstate.blocks, 
20082                                         print_interference_ins, &rstate);
20083                         }
20084                         
20085                         coalesced = coalesce_live_ranges(state, &rstate);
20086
20087                         if (state->compiler->debug & DEBUG_COALESCING) {
20088                                 fprintf(state->errout, "coalesced: %d\n", coalesced);
20089                         }
20090                 } while(coalesced);
20091
20092 #if DEBUG_CONSISTENCY > 1
20093 # if 0
20094                 fprintf(state->errout, "verify_graph_ins...\n");
20095 # endif
20096                 /* Verify the interference graph */
20097                 walk_variable_lifetimes(
20098                         state, &state->bb, rstate.blocks, 
20099                         verify_graph_ins, &rstate);
20100 # if 0
20101                 fprintf(state->errout, "verify_graph_ins done\n");
20102 #endif
20103 #endif
20104                         
20105                 /* Build the groups low and high.  But with the nodes
20106                  * first sorted by degree order.
20107                  */
20108                 rstate.low_tail  = &rstate.low;
20109                 rstate.high_tail = &rstate.high;
20110                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20111                 if (rstate.high) {
20112                         rstate.high->group_prev = &rstate.high;
20113                 }
20114                 for(point = &rstate.high; *point; point = &(*point)->group_next)
20115                         ;
20116                 rstate.high_tail = point;
20117                 /* Walk through the high list and move everything that needs
20118                  * to be onto low.
20119                  */
20120                 for(point = &rstate.high; *point; point = next) {
20121                         struct live_range *range;
20122                         next = &(*point)->group_next;
20123                         range = *point;
20124                         
20125                         /* If it has a low degree or it already has a color
20126                          * place the node in low.
20127                          */
20128                         if ((range->degree < regc_max_size(state, range->classes)) ||
20129                                 (range->color != REG_UNSET)) {
20130                                 cgdebug_printf(state, "Lo: %5d degree %5d%s\n", 
20131                                         range - rstate.lr, range->degree,
20132                                         (range->color != REG_UNSET) ? " (colored)": "");
20133                                 *range->group_prev = range->group_next;
20134                                 if (range->group_next) {
20135                                         range->group_next->group_prev = range->group_prev;
20136                                 }
20137                                 if (&range->group_next == rstate.high_tail) {
20138                                         rstate.high_tail = range->group_prev;
20139                                 }
20140                                 range->group_prev  = rstate.low_tail;
20141                                 range->group_next  = 0;
20142                                 *rstate.low_tail   = range;
20143                                 rstate.low_tail    = &range->group_next;
20144                                 next = point;
20145                         }
20146                         else {
20147                                 cgdebug_printf(state, "hi: %5d degree %5d%s\n", 
20148                                         range - rstate.lr, range->degree,
20149                                         (range->color != REG_UNSET) ? " (colored)": "");
20150                         }
20151                 }
20152                 /* Color the live_ranges */
20153                 colored = color_graph(state, &rstate);
20154                 rstate.passes++;
20155         } while (!colored);
20156
20157         /* Verify the graph was properly colored */
20158         verify_colors(state, &rstate);
20159
20160         /* Move the colors from the graph to the triples */
20161         color_triples(state, &rstate);
20162
20163         /* Cleanup the temporary data structures */
20164         cleanup_rstate(state, &rstate);
20165
20166         /* Display the new graph */
20167         print_blocks(state, __func__, state->dbgout);
20168 }
20169
20170 /* Sparce Conditional Constant Propogation
20171  * =========================================
20172  */
20173 struct ssa_edge;
20174 struct flow_block;
20175 struct lattice_node {
20176         unsigned old_id;
20177         struct triple *def;
20178         struct ssa_edge *out;
20179         struct flow_block *fblock;
20180         struct triple *val;
20181         /* lattice high   val == def
20182          * lattice const  is_const(val)
20183          * lattice low    other
20184          */
20185 };
20186 struct ssa_edge {
20187         struct lattice_node *src;
20188         struct lattice_node *dst;
20189         struct ssa_edge *work_next;
20190         struct ssa_edge *work_prev;
20191         struct ssa_edge *out_next;
20192 };
20193 struct flow_edge {
20194         struct flow_block *src;
20195         struct flow_block *dst;
20196         struct flow_edge *work_next;
20197         struct flow_edge *work_prev;
20198         struct flow_edge *in_next;
20199         struct flow_edge *out_next;
20200         int executable;
20201 };
20202 #define MAX_FLOW_BLOCK_EDGES 3
20203 struct flow_block {
20204         struct block *block;
20205         struct flow_edge *in;
20206         struct flow_edge *out;
20207         struct flow_edge *edges;
20208 };
20209
20210 struct scc_state {
20211         int ins_count;
20212         struct lattice_node *lattice;
20213         struct ssa_edge     *ssa_edges;
20214         struct flow_block   *flow_blocks;
20215         struct flow_edge    *flow_work_list;
20216         struct ssa_edge     *ssa_work_list;
20217 };
20218
20219
20220 static int is_scc_const(struct compile_state *state, struct triple *ins)
20221 {
20222         return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20223 }
20224
20225 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20226 {
20227         return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20228 }
20229
20230 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20231 {
20232         return is_scc_const(state, lnode->val);
20233 }
20234
20235 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20236 {
20237         return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20238 }
20239
20240
20241
20242
20243 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
20244         struct flow_edge *fedge)
20245 {
20246         if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20247                 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20248                         fedge,
20249                         fedge->src->block?fedge->src->block->last->id: 0,
20250                         fedge->dst->block?fedge->dst->block->first->id: 0);
20251         }
20252         if ((fedge == scc->flow_work_list) ||
20253                 (fedge->work_next != fedge) ||
20254                 (fedge->work_prev != fedge)) {
20255
20256                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20257                         fprintf(state->errout, "dupped fedge: %p\n",
20258                                 fedge);
20259                 }
20260                 return;
20261         }
20262         if (!scc->flow_work_list) {
20263                 scc->flow_work_list = fedge;
20264                 fedge->work_next = fedge->work_prev = fedge;
20265         }
20266         else {
20267                 struct flow_edge *ftail;
20268                 ftail = scc->flow_work_list->work_prev;
20269                 fedge->work_next = ftail->work_next;
20270                 fedge->work_prev = ftail;
20271                 fedge->work_next->work_prev = fedge;
20272                 fedge->work_prev->work_next = fedge;
20273         }
20274 }
20275
20276 static struct flow_edge *scc_next_fedge(
20277         struct compile_state *state, struct scc_state *scc)
20278 {
20279         struct flow_edge *fedge;
20280         fedge = scc->flow_work_list;
20281         if (fedge) {
20282                 fedge->work_next->work_prev = fedge->work_prev;
20283                 fedge->work_prev->work_next = fedge->work_next;
20284                 if (fedge->work_next != fedge) {
20285                         scc->flow_work_list = fedge->work_next;
20286                 } else {
20287                         scc->flow_work_list = 0;
20288                 }
20289                 fedge->work_next = fedge->work_prev = fedge;
20290         }
20291         return fedge;
20292 }
20293
20294 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20295         struct ssa_edge *sedge)
20296 {
20297         if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20298                 fprintf(state->errout, "adding sedge: %5d (%4d -> %5d)\n",
20299                         sedge - scc->ssa_edges,
20300                         sedge->src->def->id,
20301                         sedge->dst->def->id);
20302         }
20303         if ((sedge == scc->ssa_work_list) ||
20304                 (sedge->work_next != sedge) ||
20305                 (sedge->work_prev != sedge)) {
20306
20307                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20308                         fprintf(state->errout, "dupped sedge: %5d\n",
20309                                 sedge - scc->ssa_edges);
20310                 }
20311                 return;
20312         }
20313         if (!scc->ssa_work_list) {
20314                 scc->ssa_work_list = sedge;
20315                 sedge->work_next = sedge->work_prev = sedge;
20316         }
20317         else {
20318                 struct ssa_edge *stail;
20319                 stail = scc->ssa_work_list->work_prev;
20320                 sedge->work_next = stail->work_next;
20321                 sedge->work_prev = stail;
20322                 sedge->work_next->work_prev = sedge;
20323                 sedge->work_prev->work_next = sedge;
20324         }
20325 }
20326
20327 static struct ssa_edge *scc_next_sedge(
20328         struct compile_state *state, struct scc_state *scc)
20329 {
20330         struct ssa_edge *sedge;
20331         sedge = scc->ssa_work_list;
20332         if (sedge) {
20333                 sedge->work_next->work_prev = sedge->work_prev;
20334                 sedge->work_prev->work_next = sedge->work_next;
20335                 if (sedge->work_next != sedge) {
20336                         scc->ssa_work_list = sedge->work_next;
20337                 } else {
20338                         scc->ssa_work_list = 0;
20339                 }
20340                 sedge->work_next = sedge->work_prev = sedge;
20341         }
20342         return sedge;
20343 }
20344
20345
20346 static void initialize_scc_state(
20347         struct compile_state *state, struct scc_state *scc)
20348 {
20349         int ins_count, ssa_edge_count;
20350         int ins_index, ssa_edge_index, fblock_index;
20351         struct triple *first, *ins;
20352         struct block *block;
20353         struct flow_block *fblock;
20354
20355         memset(scc, 0, sizeof(*scc));
20356
20357         /* Inialize pass zero find out how much memory we need */
20358         first = state->first;
20359         ins = first;
20360         ins_count = ssa_edge_count = 0;
20361         do {
20362                 struct triple_set *edge;
20363                 ins_count += 1;
20364                 for(edge = ins->use; edge; edge = edge->next) {
20365                         ssa_edge_count++;
20366                 }
20367                 ins = ins->next;
20368         } while(ins != first);
20369         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20370                 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20371                         ins_count, ssa_edge_count, state->bb.last_vertex);
20372         }
20373         scc->ins_count   = ins_count;
20374         scc->lattice     = 
20375                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20376         scc->ssa_edges   = 
20377                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20378         scc->flow_blocks = 
20379                 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1), 
20380                         "flow_blocks");
20381
20382         /* Initialize pass one collect up the nodes */
20383         fblock = 0;
20384         block = 0;
20385         ins_index = ssa_edge_index = fblock_index = 0;
20386         ins = first;
20387         do {
20388                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20389                         block = ins->u.block;
20390                         if (!block) {
20391                                 internal_error(state, ins, "label without block");
20392                         }
20393                         fblock_index += 1;
20394                         block->vertex = fblock_index;
20395                         fblock = &scc->flow_blocks[fblock_index];
20396                         fblock->block = block;
20397                         fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20398                                 "flow_edges");
20399                 }
20400                 {
20401                         struct lattice_node *lnode;
20402                         ins_index += 1;
20403                         lnode = &scc->lattice[ins_index];
20404                         lnode->def = ins;
20405                         lnode->out = 0;
20406                         lnode->fblock = fblock;
20407                         lnode->val = ins; /* LATTICE HIGH */
20408                         if (lnode->val->op == OP_UNKNOWNVAL) {
20409                                 lnode->val = 0; /* LATTICE LOW by definition */
20410                         }
20411                         lnode->old_id = ins->id;
20412                         ins->id = ins_index;
20413                 }
20414                 ins = ins->next;
20415         } while(ins != first);
20416         /* Initialize pass two collect up the edges */
20417         block = 0;
20418         fblock = 0;
20419         ins = first;
20420         do {
20421                 {
20422                         struct triple_set *edge;
20423                         struct ssa_edge **stail;
20424                         struct lattice_node *lnode;
20425                         lnode = &scc->lattice[ins->id];
20426                         lnode->out = 0;
20427                         stail = &lnode->out;
20428                         for(edge = ins->use; edge; edge = edge->next) {
20429                                 struct ssa_edge *sedge;
20430                                 ssa_edge_index += 1;
20431                                 sedge = &scc->ssa_edges[ssa_edge_index];
20432                                 *stail = sedge;
20433                                 stail = &sedge->out_next;
20434                                 sedge->src = lnode;
20435                                 sedge->dst = &scc->lattice[edge->member->id];
20436                                 sedge->work_next = sedge->work_prev = sedge;
20437                                 sedge->out_next = 0;
20438                         }
20439                 }
20440                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20441                         struct flow_edge *fedge, **ftail;
20442                         struct block_set *bedge;
20443                         block = ins->u.block;
20444                         fblock = &scc->flow_blocks[block->vertex];
20445                         fblock->in = 0;
20446                         fblock->out = 0;
20447                         ftail = &fblock->out;
20448
20449                         fedge = fblock->edges;
20450                         bedge = block->edges;
20451                         for(; bedge; bedge = bedge->next, fedge++) {
20452                                 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20453                                 if (fedge->dst->block != bedge->member) {
20454                                         internal_error(state, 0, "block mismatch");
20455                                 }
20456                                 *ftail = fedge;
20457                                 ftail = &fedge->out_next;
20458                                 fedge->out_next = 0;
20459                         }
20460                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20461                                 fedge->src = fblock;
20462                                 fedge->work_next = fedge->work_prev = fedge;
20463                                 fedge->executable = 0;
20464                         }
20465                 }
20466                 ins = ins->next;
20467         } while (ins != first);
20468         block = 0;
20469         fblock = 0;
20470         ins = first;
20471         do {
20472                 if ((ins->op  == OP_LABEL) && (block != ins->u.block)) {
20473                         struct flow_edge **ftail;
20474                         struct block_set *bedge;
20475                         block = ins->u.block;
20476                         fblock = &scc->flow_blocks[block->vertex];
20477                         ftail = &fblock->in;
20478                         for(bedge = block->use; bedge; bedge = bedge->next) {
20479                                 struct block *src_block;
20480                                 struct flow_block *sfblock;
20481                                 struct flow_edge *sfedge;
20482                                 src_block = bedge->member;
20483                                 sfblock = &scc->flow_blocks[src_block->vertex];
20484                                 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20485                                         if (sfedge->dst == fblock) {
20486                                                 break;
20487                                         }
20488                                 }
20489                                 if (!sfedge) {
20490                                         internal_error(state, 0, "edge mismatch");
20491                                 }
20492                                 *ftail = sfedge;
20493                                 ftail = &sfedge->in_next;
20494                                 sfedge->in_next = 0;
20495                         }
20496                 }
20497                 ins = ins->next;
20498         } while(ins != first);
20499         /* Setup a dummy block 0 as a node above the start node */
20500         {
20501                 struct flow_block *fblock, *dst;
20502                 struct flow_edge *fedge;
20503                 fblock = &scc->flow_blocks[0];
20504                 fblock->block = 0;
20505                 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20506                 fblock->in = 0;
20507                 fblock->out = fblock->edges;
20508                 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20509                 fedge = fblock->edges;
20510                 fedge->src        = fblock;
20511                 fedge->dst        = dst;
20512                 fedge->work_next  = fedge;
20513                 fedge->work_prev  = fedge;
20514                 fedge->in_next    = fedge->dst->in;
20515                 fedge->out_next   = 0;
20516                 fedge->executable = 0;
20517                 fedge->dst->in = fedge;
20518                 
20519                 /* Initialize the work lists */
20520                 scc->flow_work_list = 0;
20521                 scc->ssa_work_list  = 0;
20522                 scc_add_fedge(state, scc, fedge);
20523         }
20524         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20525                 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20526                         ins_index, ssa_edge_index, fblock_index);
20527         }
20528 }
20529
20530         
20531 static void free_scc_state(
20532         struct compile_state *state, struct scc_state *scc)
20533 {
20534         int i;
20535         for(i = 0; i < state->bb.last_vertex + 1; i++) {
20536                 struct flow_block *fblock;
20537                 fblock = &scc->flow_blocks[i];
20538                 if (fblock->edges) {
20539                         xfree(fblock->edges);
20540                         fblock->edges = 0;
20541                 }
20542         }
20543         xfree(scc->flow_blocks);
20544         xfree(scc->ssa_edges);
20545         xfree(scc->lattice);
20546         
20547 }
20548
20549 static struct lattice_node *triple_to_lattice(
20550         struct compile_state *state, struct scc_state *scc, struct triple *ins)
20551 {
20552         if (ins->id <= 0) {
20553                 internal_error(state, ins, "bad id");
20554         }
20555         return &scc->lattice[ins->id];
20556 }
20557
20558 static struct triple *preserve_lval(
20559         struct compile_state *state, struct lattice_node *lnode)
20560 {
20561         struct triple *old;
20562         /* Preserve the original value */
20563         if (lnode->val) {
20564                 old = dup_triple(state, lnode->val);
20565                 if (lnode->val != lnode->def) {
20566                         xfree(lnode->val);
20567                 }
20568                 lnode->val = 0;
20569         } else {
20570                 old = 0;
20571         }
20572         return old;
20573 }
20574
20575 static int lval_changed(struct compile_state *state, 
20576         struct triple *old, struct lattice_node *lnode)
20577 {
20578         int changed;
20579         /* See if the lattice value has changed */
20580         changed = 1;
20581         if (!old && !lnode->val) {
20582                 changed = 0;
20583         }
20584         if (changed &&
20585                 lnode->val && old &&
20586                 (memcmp(lnode->val->param, old->param,
20587                         TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20588                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20589                 changed = 0;
20590         }
20591         if (old) {
20592                 xfree(old);
20593         }
20594         return changed;
20595
20596 }
20597
20598 static void scc_debug_lnode(
20599         struct compile_state *state, struct scc_state *scc,
20600         struct lattice_node *lnode, int changed)
20601 {
20602         if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20603                 display_triple_changes(state->errout, lnode->val, lnode->def);
20604         }
20605         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20606                 FILE *fp = state->errout;
20607                 struct triple *val, **expr;
20608                 val = lnode->val? lnode->val : lnode->def;
20609                 fprintf(fp, "%p %s %3d %10s (",
20610                         lnode->def, 
20611                         ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20612                         lnode->def->id,
20613                         tops(lnode->def->op));
20614                 expr = triple_rhs(state, lnode->def, 0);
20615                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20616                         if (*expr) {
20617                                 fprintf(fp, " %d", (*expr)->id);
20618                         }
20619                 }
20620                 if (val->op == OP_INTCONST) {
20621                         fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20622                 }
20623                 fprintf(fp, " ) -> %s %s\n",
20624                         (is_lattice_hi(state, lnode)? "hi":
20625                                 is_lattice_const(state, lnode)? "const" : "lo"),
20626                         changed? "changed" : ""
20627                         );
20628         }
20629 }
20630
20631 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20632         struct lattice_node *lnode)
20633 {
20634         int changed;
20635         struct triple *old, *scratch;
20636         struct triple **dexpr, **vexpr;
20637         int count, i;
20638         
20639         /* Store the original value */
20640         old = preserve_lval(state, lnode);
20641
20642         /* Reinitialize the value */
20643         lnode->val = scratch = dup_triple(state, lnode->def);
20644         scratch->id = lnode->old_id;
20645         scratch->next     = scratch;
20646         scratch->prev     = scratch;
20647         scratch->use      = 0;
20648
20649         count = TRIPLE_SIZE(scratch);
20650         for(i = 0; i < count; i++) {
20651                 dexpr = &lnode->def->param[i];
20652                 vexpr = &scratch->param[i];
20653                 *vexpr = *dexpr;
20654                 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20655                         (i >= TRIPLE_TARG_OFF(scratch))) &&
20656                         *dexpr) {
20657                         struct lattice_node *tmp;
20658                         tmp = triple_to_lattice(state, scc, *dexpr);
20659                         *vexpr = (tmp->val)? tmp->val : tmp->def;
20660                 }
20661         }
20662         if (triple_is_branch(state, scratch)) {
20663                 scratch->next = lnode->def->next;
20664         }
20665         /* Recompute the value */
20666 #warning "FIXME see if simplify does anything bad"
20667         /* So far it looks like only the strength reduction
20668          * optimization are things I need to worry about.
20669          */
20670         simplify(state, scratch);
20671         /* Cleanup my value */
20672         if (scratch->use) {
20673                 internal_error(state, lnode->def, "scratch used?");
20674         }
20675         if ((scratch->prev != scratch) ||
20676                 ((scratch->next != scratch) &&
20677                         (!triple_is_branch(state, lnode->def) ||
20678                                 (scratch->next != lnode->def->next)))) {
20679                 internal_error(state, lnode->def, "scratch in list?");
20680         }
20681         /* undo any uses... */
20682         count = TRIPLE_SIZE(scratch);
20683         for(i = 0; i < count; i++) {
20684                 vexpr = &scratch->param[i];
20685                 if (*vexpr) {
20686                         unuse_triple(*vexpr, scratch);
20687                 }
20688         }
20689         if (lnode->val->op == OP_UNKNOWNVAL) {
20690                 lnode->val = 0; /* Lattice low by definition */
20691         }
20692         /* Find the case when I am lattice high */
20693         if (lnode->val && 
20694                 (lnode->val->op == lnode->def->op) &&
20695                 (memcmp(lnode->val->param, lnode->def->param, 
20696                         count * sizeof(lnode->val->param[0])) == 0) &&
20697                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20698                 lnode->val = lnode->def;
20699         }
20700         /* Only allow lattice high when all of my inputs
20701          * are also lattice high.  Occassionally I can
20702          * have constants with a lattice low input, so
20703          * I do not need to check that case.
20704          */
20705         if (is_lattice_hi(state, lnode)) {
20706                 struct lattice_node *tmp;
20707                 int rhs;
20708                 rhs = lnode->val->rhs;
20709                 for(i = 0; i < rhs; i++) {
20710                         tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20711                         if (!is_lattice_hi(state, tmp)) {
20712                                 lnode->val = 0;
20713                                 break;
20714                         }
20715                 }
20716         }
20717         /* Find the cases that are always lattice lo */
20718         if (lnode->val && 
20719                 triple_is_def(state, lnode->val) &&
20720                 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20721                 lnode->val = 0;
20722         }
20723         /* See if the lattice value has changed */
20724         changed = lval_changed(state, old, lnode);
20725         /* See if this value should not change */
20726         if ((lnode->val != lnode->def) && 
20727                 ((      !triple_is_def(state, lnode->def)  &&
20728                         !triple_is_cbranch(state, lnode->def)) ||
20729                         (lnode->def->op == OP_PIECE))) {
20730 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20731                 if (changed) {
20732                         internal_warning(state, lnode->def, "non def changes value?");
20733                 }
20734                 lnode->val = 0;
20735         }
20736
20737         /* See if we need to free the scratch value */
20738         if (lnode->val != scratch) {
20739                 xfree(scratch);
20740         }
20741         
20742         return changed;
20743 }
20744
20745
20746 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20747         struct lattice_node *lnode)
20748 {
20749         struct lattice_node *cond;
20750         struct flow_edge *left, *right;
20751         int changed;
20752
20753         /* Update the branch value */
20754         changed = compute_lnode_val(state, scc, lnode);
20755         scc_debug_lnode(state, scc, lnode, changed);
20756
20757         /* This only applies to conditional branches */
20758         if (!triple_is_cbranch(state, lnode->def)) {
20759                 internal_error(state, lnode->def, "not a conditional branch");
20760         }
20761
20762         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20763                 struct flow_edge *fedge;
20764                 FILE *fp = state->errout;
20765                 fprintf(fp, "%s: %d (",
20766                         tops(lnode->def->op),
20767                         lnode->def->id);
20768                 
20769                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20770                         fprintf(fp, " %d", fedge->dst->block->vertex);
20771                 }
20772                 fprintf(fp, " )");
20773                 if (lnode->def->rhs > 0) {
20774                         fprintf(fp, " <- %d",
20775                                 RHS(lnode->def, 0)->id);
20776                 }
20777                 fprintf(fp, "\n");
20778         }
20779         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20780         for(left = cond->fblock->out; left; left = left->out_next) {
20781                 if (left->dst->block->first == lnode->def->next) {
20782                         break;
20783                 }
20784         }
20785         if (!left) {
20786                 internal_error(state, lnode->def, "Cannot find left branch edge");
20787         }
20788         for(right = cond->fblock->out; right; right = right->out_next) {
20789                 if (right->dst->block->first == TARG(lnode->def, 0)) {
20790                         break;
20791                 }
20792         }
20793         if (!right) {
20794                 internal_error(state, lnode->def, "Cannot find right branch edge");
20795         }
20796         /* I should only come here if the controlling expressions value
20797          * has changed, which means it must be either a constant or lo.
20798          */
20799         if (is_lattice_hi(state, cond)) {
20800                 internal_error(state, cond->def, "condition high?");
20801                 return;
20802         }
20803         if (is_lattice_lo(state, cond)) {
20804                 scc_add_fedge(state, scc, left);
20805                 scc_add_fedge(state, scc, right);
20806         }
20807         else if (cond->val->u.cval) {
20808                 scc_add_fedge(state, scc, right);
20809         } else {
20810                 scc_add_fedge(state, scc, left);
20811         }
20812
20813 }
20814
20815
20816 static void scc_add_sedge_dst(struct compile_state *state, 
20817         struct scc_state *scc, struct ssa_edge *sedge)
20818 {
20819         if (triple_is_cbranch(state, sedge->dst->def)) {
20820                 scc_visit_cbranch(state, scc, sedge->dst);
20821         }
20822         else if (triple_is_def(state, sedge->dst->def)) {
20823                 scc_add_sedge(state, scc, sedge);
20824         }
20825 }
20826
20827 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
20828         struct lattice_node *lnode)
20829 {
20830         struct lattice_node *tmp;
20831         struct triple **slot, *old;
20832         struct flow_edge *fedge;
20833         int changed;
20834         int index;
20835         if (lnode->def->op != OP_PHI) {
20836                 internal_error(state, lnode->def, "not phi");
20837         }
20838         /* Store the original value */
20839         old = preserve_lval(state, lnode);
20840
20841         /* default to lattice high */
20842         lnode->val = lnode->def;
20843         slot = &RHS(lnode->def, 0);
20844         index = 0;
20845         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20846                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20847                         fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n", 
20848                                 index,
20849                                 fedge->dst->block->vertex,
20850                                 fedge->executable
20851                                 );
20852                 }
20853                 if (!fedge->executable) {
20854                         continue;
20855                 }
20856                 if (!slot[index]) {
20857                         internal_error(state, lnode->def, "no phi value");
20858                 }
20859                 tmp = triple_to_lattice(state, scc, slot[index]);
20860                 /* meet(X, lattice low) = lattice low */
20861                 if (is_lattice_lo(state, tmp)) {
20862                         lnode->val = 0;
20863                 }
20864                 /* meet(X, lattice high) = X */
20865                 else if (is_lattice_hi(state, tmp)) {
20866                         lnode->val = lnode->val;
20867                 }
20868                 /* meet(lattice high, X) = X */
20869                 else if (is_lattice_hi(state, lnode)) {
20870                         lnode->val = dup_triple(state, tmp->val);
20871                         /* Only change the type if necessary */
20872                         if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20873                                 lnode->val->type = lnode->def->type;
20874                         }
20875                 }
20876                 /* meet(const, const) = const or lattice low */
20877                 else if (!constants_equal(state, lnode->val, tmp->val)) {
20878                         lnode->val = 0;
20879                 }
20880
20881                 /* meet(lattice low, X) = lattice low */
20882                 if (is_lattice_lo(state, lnode)) {
20883                         lnode->val = 0;
20884                         break;
20885                 }
20886         }
20887         changed = lval_changed(state, old, lnode);
20888         scc_debug_lnode(state, scc, lnode, changed);
20889
20890         /* If the lattice value has changed update the work lists. */
20891         if (changed) {
20892                 struct ssa_edge *sedge;
20893                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20894                         scc_add_sedge_dst(state, scc, sedge);
20895                 }
20896         }
20897 }
20898
20899
20900 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20901         struct lattice_node *lnode)
20902 {
20903         int changed;
20904
20905         if (!triple_is_def(state, lnode->def)) {
20906                 internal_warning(state, lnode->def, "not visiting an expression?");
20907         }
20908         changed = compute_lnode_val(state, scc, lnode);
20909         scc_debug_lnode(state, scc, lnode, changed);
20910
20911         if (changed) {
20912                 struct ssa_edge *sedge;
20913                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20914                         scc_add_sedge_dst(state, scc, sedge);
20915                 }
20916         }
20917 }
20918
20919 static void scc_writeback_values(
20920         struct compile_state *state, struct scc_state *scc)
20921 {
20922         struct triple *first, *ins;
20923         first = state->first;
20924         ins = first;
20925         do {
20926                 struct lattice_node *lnode;
20927                 lnode = triple_to_lattice(state, scc, ins);
20928                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20929                         if (is_lattice_hi(state, lnode) &&
20930                                 (lnode->val->op != OP_NOOP))
20931                         {
20932                                 struct flow_edge *fedge;
20933                                 int executable;
20934                                 executable = 0;
20935                                 for(fedge = lnode->fblock->in; 
20936                                     !executable && fedge; fedge = fedge->in_next) {
20937                                         executable |= fedge->executable;
20938                                 }
20939                                 if (executable) {
20940                                         internal_warning(state, lnode->def,
20941                                                 "lattice node %d %s->%s still high?",
20942                                                 ins->id, 
20943                                                 tops(lnode->def->op),
20944                                                 tops(lnode->val->op));
20945                                 }
20946                         }
20947                 }
20948
20949                 /* Restore id */
20950                 ins->id = lnode->old_id;
20951                 if (lnode->val && (lnode->val != ins)) {
20952                         /* See if it something I know how to write back */
20953                         switch(lnode->val->op) {
20954                         case OP_INTCONST:
20955                                 mkconst(state, ins, lnode->val->u.cval);
20956                                 break;
20957                         case OP_ADDRCONST:
20958                                 mkaddr_const(state, ins, 
20959                                         MISC(lnode->val, 0), lnode->val->u.cval);
20960                                 break;
20961                         default:
20962                                 /* By default don't copy the changes,
20963                                  * recompute them in place instead.
20964                                  */
20965                                 simplify(state, ins);
20966                                 break;
20967                         }
20968                         if (is_const(lnode->val) &&
20969                                 !constants_equal(state, lnode->val, ins)) {
20970                                 internal_error(state, 0, "constants not equal");
20971                         }
20972                         /* Free the lattice nodes */
20973                         xfree(lnode->val);
20974                         lnode->val = 0;
20975                 }
20976                 ins = ins->next;
20977         } while(ins != first);
20978 }
20979
20980 static void scc_transform(struct compile_state *state)
20981 {
20982         struct scc_state scc;
20983         if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
20984                 return;
20985         }
20986
20987         initialize_scc_state(state, &scc);
20988
20989         while(scc.flow_work_list || scc.ssa_work_list) {
20990                 struct flow_edge *fedge;
20991                 struct ssa_edge *sedge;
20992                 struct flow_edge *fptr;
20993                 while((fedge = scc_next_fedge(state, &scc))) {
20994                         struct block *block;
20995                         struct triple *ptr;
20996                         struct flow_block *fblock;
20997                         int reps;
20998                         int done;
20999                         if (fedge->executable) {
21000                                 continue;
21001                         }
21002                         if (!fedge->dst) {
21003                                 internal_error(state, 0, "fedge without dst");
21004                         }
21005                         if (!fedge->src) {
21006                                 internal_error(state, 0, "fedge without src");
21007                         }
21008                         fedge->executable = 1;
21009                         fblock = fedge->dst;
21010                         block = fblock->block;
21011                         reps = 0;
21012                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21013                                 if (fptr->executable) {
21014                                         reps++;
21015                                 }
21016                         }
21017                         
21018                         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21019                                 fprintf(state->errout, "vertex: %d reps: %d\n", 
21020                                         block->vertex, reps);
21021                         }
21022
21023                         done = 0;
21024                         for(ptr = block->first; !done; ptr = ptr->next) {
21025                                 struct lattice_node *lnode;
21026                                 done = (ptr == block->last);
21027                                 lnode = &scc.lattice[ptr->id];
21028                                 if (ptr->op == OP_PHI) {
21029                                         scc_visit_phi(state, &scc, lnode);
21030                                 }
21031                                 else if ((reps == 1) && triple_is_def(state, ptr))
21032                                 {
21033                                         scc_visit_expr(state, &scc, lnode);
21034                                 }
21035                         }
21036                         /* Add unconditional branch edges */
21037                         if (!triple_is_cbranch(state, fblock->block->last)) {
21038                                 struct flow_edge *out;
21039                                 for(out = fblock->out; out; out = out->out_next) {
21040                                         scc_add_fedge(state, &scc, out);
21041                                 }
21042                         }
21043                 }
21044                 while((sedge = scc_next_sedge(state, &scc))) {
21045                         struct lattice_node *lnode;
21046                         struct flow_block *fblock;
21047                         lnode = sedge->dst;
21048                         fblock = lnode->fblock;
21049
21050                         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21051                                 fprintf(state->errout, "sedge: %5d (%5d -> %5d)\n",
21052                                         sedge - scc.ssa_edges,
21053                                         sedge->src->def->id,
21054                                         sedge->dst->def->id);
21055                         }
21056
21057                         if (lnode->def->op == OP_PHI) {
21058                                 scc_visit_phi(state, &scc, lnode);
21059                         }
21060                         else {
21061                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21062                                         if (fptr->executable) {
21063                                                 break;
21064                                         }
21065                                 }
21066                                 if (fptr) {
21067                                         scc_visit_expr(state, &scc, lnode);
21068                                 }
21069                         }
21070                 }
21071         }
21072         
21073         scc_writeback_values(state, &scc);
21074         free_scc_state(state, &scc);
21075         rebuild_ssa_form(state);
21076         
21077         print_blocks(state, __func__, state->dbgout);
21078 }
21079
21080
21081 static void transform_to_arch_instructions(struct compile_state *state)
21082 {
21083         struct triple *ins, *first;
21084         first = state->first;
21085         ins = first;
21086         do {
21087                 ins = transform_to_arch_instruction(state, ins);
21088         } while(ins != first);
21089         
21090         print_blocks(state, __func__, state->dbgout);
21091 }
21092
21093 #if DEBUG_CONSISTENCY
21094 static void verify_uses(struct compile_state *state)
21095 {
21096         struct triple *first, *ins;
21097         struct triple_set *set;
21098         first = state->first;
21099         ins = first;
21100         do {
21101                 struct triple **expr;
21102                 expr = triple_rhs(state, ins, 0);
21103                 for(; expr; expr = triple_rhs(state, ins, expr)) {
21104                         struct triple *rhs;
21105                         rhs = *expr;
21106                         for(set = rhs?rhs->use:0; set; set = set->next) {
21107                                 if (set->member == ins) {
21108                                         break;
21109                                 }
21110                         }
21111                         if (!set) {
21112                                 internal_error(state, ins, "rhs not used");
21113                         }
21114                 }
21115                 expr = triple_lhs(state, ins, 0);
21116                 for(; expr; expr = triple_lhs(state, ins, expr)) {
21117                         struct triple *lhs;
21118                         lhs = *expr;
21119                         for(set =  lhs?lhs->use:0; set; set = set->next) {
21120                                 if (set->member == ins) {
21121                                         break;
21122                                 }
21123                         }
21124                         if (!set) {
21125                                 internal_error(state, ins, "lhs not used");
21126                         }
21127                 }
21128                 expr = triple_misc(state, ins, 0);
21129                 if (ins->op != OP_PHI) {
21130                         for(; expr; expr = triple_targ(state, ins, expr)) {
21131                                 struct triple *misc;
21132                                 misc = *expr;
21133                                 for(set = misc?misc->use:0; set; set = set->next) {
21134                                         if (set->member == ins) {
21135                                                 break;
21136                                         }
21137                                 }
21138                                 if (!set) {
21139                                         internal_error(state, ins, "misc not used");
21140                                 }
21141                         }
21142                 }
21143                 if (!triple_is_ret(state, ins)) {
21144                         expr = triple_targ(state, ins, 0);
21145                         for(; expr; expr = triple_targ(state, ins, expr)) {
21146                                 struct triple *targ;
21147                                 targ = *expr;
21148                                 for(set = targ?targ->use:0; set; set = set->next) {
21149                                         if (set->member == ins) {
21150                                                 break;
21151                                         }
21152                                 }
21153                                 if (!set) {
21154                                         internal_error(state, ins, "targ not used");
21155                                 }
21156                         }
21157                 }
21158                 ins = ins->next;
21159         } while(ins != first);
21160         
21161 }
21162 static void verify_blocks_present(struct compile_state *state)
21163 {
21164         struct triple *first, *ins;
21165         if (!state->bb.first_block) {
21166                 return;
21167         }
21168         first = state->first;
21169         ins = first;
21170         do {
21171                 valid_ins(state, ins);
21172                 if (triple_stores_block(state, ins)) {
21173                         if (!ins->u.block) {
21174                                 internal_error(state, ins, 
21175                                         "%p not in a block?", ins);
21176                         }
21177                 }
21178                 ins = ins->next;
21179         } while(ins != first);
21180         
21181         
21182 }
21183
21184 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21185 {
21186         struct block_set *bedge;
21187         struct block *targ;
21188         targ = block_of_triple(state, edge);
21189         for(bedge = block->edges; bedge; bedge = bedge->next) {
21190                 if (bedge->member == targ) {
21191                         return 1;
21192                 }
21193         }
21194         return 0;
21195 }
21196
21197 static void verify_blocks(struct compile_state *state)
21198 {
21199         struct triple *ins;
21200         struct block *block;
21201         int blocks;
21202         block = state->bb.first_block;
21203         if (!block) {
21204                 return;
21205         }
21206         blocks = 0;
21207         do {
21208                 int users;
21209                 struct block_set *user, *edge;
21210                 blocks++;
21211                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21212                         if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21213                                 internal_error(state, ins, "inconsitent block specified");
21214                         }
21215                         valid_ins(state, ins);
21216                 }
21217                 users = 0;
21218                 for(user = block->use; user; user = user->next) {
21219                         users++;
21220                         if (!user->member->first) {
21221                                 internal_error(state, block->first, "user is empty");
21222                         }
21223                         if ((block == state->bb.last_block) &&
21224                                 (user->member == state->bb.first_block)) {
21225                                 continue;
21226                         }
21227                         for(edge = user->member->edges; edge; edge = edge->next) {
21228                                 if (edge->member == block) {
21229                                         break;
21230                                 }
21231                         }
21232                         if (!edge) {
21233                                 internal_error(state, user->member->first,
21234                                         "user does not use block");
21235                         }
21236                 }
21237                 if (triple_is_branch(state, block->last)) {
21238                         struct triple **expr;
21239                         expr = triple_edge_targ(state, block->last, 0);
21240                         for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21241                                 if (*expr && !edge_present(state, block, *expr)) {
21242                                         internal_error(state, block->last, "no edge to targ");
21243                                 }
21244                         }
21245                 }
21246                 if (!triple_is_ubranch(state, block->last) &&
21247                         (block != state->bb.last_block) &&
21248                         !edge_present(state, block, block->last->next)) {
21249                         internal_error(state, block->last, "no edge to block->last->next");
21250                 }
21251                 for(edge = block->edges; edge; edge = edge->next) {
21252                         for(user = edge->member->use; user; user = user->next) {
21253                                 if (user->member == block) {
21254                                         break;
21255                                 }
21256                         }
21257                         if (!user || user->member != block) {
21258                                 internal_error(state, block->first,
21259                                         "block does not use edge");
21260                         }
21261                         if (!edge->member->first) {
21262                                 internal_error(state, block->first, "edge block is empty");
21263                         }
21264                 }
21265                 if (block->users != users) {
21266                         internal_error(state, block->first, 
21267                                 "computed users %d != stored users %d",
21268                                 users, block->users);
21269                 }
21270                 if (!triple_stores_block(state, block->last->next)) {
21271                         internal_error(state, block->last->next, 
21272                                 "cannot find next block");
21273                 }
21274                 block = block->last->next->u.block;
21275                 if (!block) {
21276                         internal_error(state, block->last->next,
21277                                 "bad next block");
21278                 }
21279         } while(block != state->bb.first_block);
21280         if (blocks != state->bb.last_vertex) {
21281                 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21282                         blocks, state->bb.last_vertex);
21283         }
21284 }
21285
21286 static void verify_domination(struct compile_state *state)
21287 {
21288         struct triple *first, *ins;
21289         struct triple_set *set;
21290         if (!state->bb.first_block) {
21291                 return;
21292         }
21293         
21294         first = state->first;
21295         ins = first;
21296         do {
21297                 for(set = ins->use; set; set = set->next) {
21298                         struct triple **slot;
21299                         struct triple *use_point;
21300                         int i, zrhs;
21301                         use_point = 0;
21302                         zrhs = set->member->rhs;
21303                         slot = &RHS(set->member, 0);
21304                         /* See if the use is on the right hand side */
21305                         for(i = 0; i < zrhs; i++) {
21306                                 if (slot[i] == ins) {
21307                                         break;
21308                                 }
21309                         }
21310                         if (i < zrhs) {
21311                                 use_point = set->member;
21312                                 if (set->member->op == OP_PHI) {
21313                                         struct block_set *bset;
21314                                         int edge;
21315                                         bset = set->member->u.block->use;
21316                                         for(edge = 0; bset && (edge < i); edge++) {
21317                                                 bset = bset->next;
21318                                         }
21319                                         if (!bset) {
21320                                                 internal_error(state, set->member, 
21321                                                         "no edge for phi rhs %d", i);
21322                                         }
21323                                         use_point = bset->member->last;
21324                                 }
21325                         }
21326                         if (use_point &&
21327                                 !tdominates(state, ins, use_point)) {
21328                                 if (is_const(ins)) {
21329                                         internal_warning(state, ins, 
21330                                         "non dominated rhs use point %p?", use_point);
21331                                 }
21332                                 else {
21333                                         internal_error(state, ins, 
21334                                                 "non dominated rhs use point %p?", use_point);
21335                                 }
21336                         }
21337                 }
21338                 ins = ins->next;
21339         } while(ins != first);
21340 }
21341
21342 static void verify_rhs(struct compile_state *state)
21343 {
21344         struct triple *first, *ins;
21345         first = state->first;
21346         ins = first;
21347         do {
21348                 struct triple **slot;
21349                 int zrhs, i;
21350                 zrhs = ins->rhs;
21351                 slot = &RHS(ins, 0);
21352                 for(i = 0; i < zrhs; i++) {
21353                         if (slot[i] == 0) {
21354                                 internal_error(state, ins,
21355                                         "missing rhs %d on %s",
21356                                         i, tops(ins->op));
21357                         }
21358                         if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21359                                 internal_error(state, ins,
21360                                         "ins == rhs[%d] on %s",
21361                                         i, tops(ins->op));
21362                         }
21363                 }
21364                 ins = ins->next;
21365         } while(ins != first);
21366 }
21367
21368 static void verify_piece(struct compile_state *state)
21369 {
21370         struct triple *first, *ins;
21371         first = state->first;
21372         ins = first;
21373         do {
21374                 struct triple *ptr;
21375                 int lhs, i;
21376                 lhs = ins->lhs;
21377                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21378                         if (ptr != LHS(ins, i)) {
21379                                 internal_error(state, ins, "malformed lhs on %s",
21380                                         tops(ins->op));
21381                         }
21382                         if (ptr->op != OP_PIECE) {
21383                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
21384                                         tops(ptr->op), i, tops(ins->op));
21385                         }
21386                         if (ptr->u.cval != i) {
21387                                 internal_error(state, ins, "bad u.cval of %d %d expected",
21388                                         ptr->u.cval, i);
21389                         }
21390                 }
21391                 ins = ins->next;
21392         } while(ins != first);
21393 }
21394
21395 static void verify_ins_colors(struct compile_state *state)
21396 {
21397         struct triple *first, *ins;
21398         
21399         first = state->first;
21400         ins = first;
21401         do {
21402                 ins = ins->next;
21403         } while(ins != first);
21404 }
21405
21406 static void verify_unknown(struct compile_state *state)
21407 {
21408         struct triple *first, *ins;
21409         if (    (unknown_triple.next != &unknown_triple) ||
21410                 (unknown_triple.prev != &unknown_triple) ||
21411 #if 0
21412                 (unknown_triple.use != 0) ||
21413 #endif
21414                 (unknown_triple.op != OP_UNKNOWNVAL) ||
21415                 (unknown_triple.lhs != 0) ||
21416                 (unknown_triple.rhs != 0) ||
21417                 (unknown_triple.misc != 0) ||
21418                 (unknown_triple.targ != 0) ||
21419                 (unknown_triple.template_id != 0) ||
21420                 (unknown_triple.id != -1) ||
21421                 (unknown_triple.type != &unknown_type) ||
21422                 (unknown_triple.occurance != &dummy_occurance) ||
21423                 (unknown_triple.param[0] != 0) ||
21424                 (unknown_triple.param[1] != 0)) {
21425                 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21426         }
21427         if (    (dummy_occurance.count != 2) ||
21428                 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21429                 (strcmp(dummy_occurance.function, "") != 0) ||
21430                 (dummy_occurance.col != 0) ||
21431                 (dummy_occurance.parent != 0)) {
21432                 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21433         }
21434         if (    (unknown_type.type != TYPE_UNKNOWN)) {
21435                 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21436         }
21437         first = state->first;
21438         ins = first;
21439         do {
21440                 int params, i;
21441                 if (ins == &unknown_triple) {
21442                         internal_error(state, ins, "unknown triple in list");
21443                 }
21444                 params = TRIPLE_SIZE(ins);
21445                 for(i = 0; i < params; i++) {
21446                         if (ins->param[i] == &unknown_triple) {
21447                                 internal_error(state, ins, "unknown triple used!");
21448                         }
21449                 }
21450                 ins = ins->next;
21451         } while(ins != first);
21452 }
21453
21454 static void verify_types(struct compile_state *state)
21455 {
21456         struct triple *first, *ins;
21457         first = state->first;
21458         ins = first;
21459         do {
21460                 struct type *invalid;
21461                 invalid = invalid_type(state, ins->type);
21462                 if (invalid) {
21463                         FILE *fp = state->errout;
21464                         fprintf(fp, "type: ");
21465                         name_of(fp, ins->type);
21466                         fprintf(fp, "\n");
21467                         fprintf(fp, "invalid type: ");
21468                         name_of(fp, invalid);
21469                         fprintf(fp, "\n");
21470                         internal_error(state, ins, "invalid ins type");
21471                 }
21472         } while(ins != first);
21473 }
21474
21475 static void verify_copy(struct compile_state *state)
21476 {
21477         struct triple *first, *ins, *next;
21478         first = state->first;
21479         next = ins = first;
21480         do {
21481                 ins = next;
21482                 next = ins->next;
21483                 if (ins->op != OP_COPY) {
21484                         continue;
21485                 }
21486                 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21487                         FILE *fp = state->errout;
21488                         fprintf(fp, "src type: ");
21489                         name_of(fp, RHS(ins, 0)->type);
21490                         fprintf(fp, "\n");
21491                         fprintf(fp, "dst type: ");
21492                         name_of(fp, ins->type);
21493                         fprintf(fp, "\n");
21494                         internal_error(state, ins, "type mismatch in copy");
21495                 }
21496         } while(next != first);
21497 }
21498
21499 static void verify_consistency(struct compile_state *state)
21500 {
21501         verify_unknown(state);
21502         verify_uses(state);
21503         verify_blocks_present(state);
21504         verify_blocks(state);
21505         verify_domination(state);
21506         verify_rhs(state);
21507         verify_piece(state);
21508         verify_ins_colors(state);
21509         verify_types(state);
21510         verify_copy(state);
21511         if (state->compiler->debug & DEBUG_VERIFICATION) {
21512                 fprintf(state->dbgout, "consistency verified\n");
21513         }
21514 }
21515 #else 
21516 static void verify_consistency(struct compile_state *state) {}
21517 #endif /* DEBUG_CONSISTENCY */
21518
21519 static void optimize(struct compile_state *state)
21520 {
21521         /* Join all of the functions into one giant function */
21522         join_functions(state);
21523
21524         /* Dump what the instruction graph intially looks like */
21525         print_triples(state);
21526
21527         /* Replace structures with simpler data types */
21528         decompose_compound_types(state);
21529         print_triples(state);
21530
21531         verify_consistency(state);
21532         /* Analize the intermediate code */
21533         state->bb.first = state->first;
21534         analyze_basic_blocks(state, &state->bb);
21535
21536         /* Transform the code to ssa form. */
21537         /*
21538          * The transformation to ssa form puts a phi function
21539          * on each of edge of a dominance frontier where that
21540          * phi function might be needed.  At -O2 if we don't
21541          * eleminate the excess phi functions we can get an
21542          * exponential code size growth.  So I kill the extra
21543          * phi functions early and I kill them often.
21544          */
21545         transform_to_ssa_form(state);
21546         verify_consistency(state);
21547
21548         /* Remove dead code */
21549         eliminate_inefectual_code(state);
21550         verify_consistency(state);
21551
21552         /* Do strength reduction and simple constant optimizations */
21553         simplify_all(state);
21554         verify_consistency(state);
21555         /* Propogate constants throughout the code */
21556         scc_transform(state);
21557         verify_consistency(state);
21558 #warning "WISHLIST implement single use constants (least possible register pressure)"
21559 #warning "WISHLIST implement induction variable elimination"
21560         /* Select architecture instructions and an initial partial
21561          * coloring based on architecture constraints.
21562          */
21563         transform_to_arch_instructions(state);
21564         verify_consistency(state);
21565
21566         /* Remove dead code */
21567         eliminate_inefectual_code(state);
21568         verify_consistency(state);
21569
21570         /* Color all of the variables to see if they will fit in registers */
21571         insert_copies_to_phi(state);
21572         verify_consistency(state);
21573
21574         insert_mandatory_copies(state);
21575         verify_consistency(state);
21576
21577         allocate_registers(state);
21578         verify_consistency(state);
21579
21580         /* Remove the optimization information.
21581          * This is more to check for memory consistency than to free memory.
21582          */
21583         free_basic_blocks(state, &state->bb);
21584 }
21585
21586 static void print_op_asm(struct compile_state *state,
21587         struct triple *ins, FILE *fp)
21588 {
21589         struct asm_info *info;
21590         const char *ptr;
21591         unsigned lhs, rhs, i;
21592         info = ins->u.ainfo;
21593         lhs = ins->lhs;
21594         rhs = ins->rhs;
21595         /* Don't count the clobbers in lhs */
21596         for(i = 0; i < lhs; i++) {
21597                 if (LHS(ins, i)->type == &void_type) {
21598                         break;
21599                 }
21600         }
21601         lhs = i;
21602         fprintf(fp, "#ASM\n");
21603         fputc('\t', fp);
21604         for(ptr = info->str; *ptr; ptr++) {
21605                 char *next;
21606                 unsigned long param;
21607                 struct triple *piece;
21608                 if (*ptr != '%') {
21609                         fputc(*ptr, fp);
21610                         continue;
21611                 }
21612                 ptr++;
21613                 if (*ptr == '%') {
21614                         fputc('%', fp);
21615                         continue;
21616                 }
21617                 param = strtoul(ptr, &next, 10);
21618                 if (ptr == next) {
21619                         error(state, ins, "Invalid asm template");
21620                 }
21621                 if (param >= (lhs + rhs)) {
21622                         error(state, ins, "Invalid param %%%u in asm template",
21623                                 param);
21624                 }
21625                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21626                 fprintf(fp, "%s", 
21627                         arch_reg_str(ID_REG(piece->id)));
21628                 ptr = next -1;
21629         }
21630         fprintf(fp, "\n#NOT ASM\n");
21631 }
21632
21633
21634 /* Only use the low x86 byte registers.  This allows me
21635  * allocate the entire register when a byte register is used.
21636  */
21637 #define X86_4_8BIT_GPRS 1
21638
21639 /* x86 featrues */
21640 #define X86_MMX_REGS  (1<<0)
21641 #define X86_XMM_REGS  (1<<1)
21642 #define X86_NOOP_COPY (1<<2)
21643
21644 /* The x86 register classes */
21645 #define REGC_FLAGS       0
21646 #define REGC_GPR8        1
21647 #define REGC_GPR16       2
21648 #define REGC_GPR32       3
21649 #define REGC_DIVIDEND64  4
21650 #define REGC_DIVIDEND32  5
21651 #define REGC_MMX         6
21652 #define REGC_XMM         7
21653 #define REGC_GPR32_8     8
21654 #define REGC_GPR16_8     9
21655 #define REGC_GPR8_LO    10
21656 #define REGC_IMM32      11
21657 #define REGC_IMM16      12
21658 #define REGC_IMM8       13
21659 #define LAST_REGC  REGC_IMM8
21660 #if LAST_REGC >= MAX_REGC
21661 #error "MAX_REGC is to low"
21662 #endif
21663
21664 /* Register class masks */
21665 #define REGCM_FLAGS      (1 << REGC_FLAGS)
21666 #define REGCM_GPR8       (1 << REGC_GPR8)
21667 #define REGCM_GPR16      (1 << REGC_GPR16)
21668 #define REGCM_GPR32      (1 << REGC_GPR32)
21669 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21670 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21671 #define REGCM_MMX        (1 << REGC_MMX)
21672 #define REGCM_XMM        (1 << REGC_XMM)
21673 #define REGCM_GPR32_8    (1 << REGC_GPR32_8)
21674 #define REGCM_GPR16_8    (1 << REGC_GPR16_8)
21675 #define REGCM_GPR8_LO    (1 << REGC_GPR8_LO)
21676 #define REGCM_IMM32      (1 << REGC_IMM32)
21677 #define REGCM_IMM16      (1 << REGC_IMM16)
21678 #define REGCM_IMM8       (1 << REGC_IMM8)
21679 #define REGCM_ALL        ((1 << (LAST_REGC + 1)) - 1)
21680 #define REGCM_IMMALL    (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21681
21682 /* The x86 registers */
21683 #define REG_EFLAGS  2
21684 #define REGC_FLAGS_FIRST REG_EFLAGS
21685 #define REGC_FLAGS_LAST  REG_EFLAGS
21686 #define REG_AL      3
21687 #define REG_BL      4
21688 #define REG_CL      5
21689 #define REG_DL      6
21690 #define REG_AH      7
21691 #define REG_BH      8
21692 #define REG_CH      9
21693 #define REG_DH      10
21694 #define REGC_GPR8_LO_FIRST REG_AL
21695 #define REGC_GPR8_LO_LAST  REG_DL
21696 #define REGC_GPR8_FIRST  REG_AL
21697 #define REGC_GPR8_LAST   REG_DH
21698 #define REG_AX     11
21699 #define REG_BX     12
21700 #define REG_CX     13
21701 #define REG_DX     14
21702 #define REG_SI     15
21703 #define REG_DI     16
21704 #define REG_BP     17
21705 #define REG_SP     18
21706 #define REGC_GPR16_FIRST REG_AX
21707 #define REGC_GPR16_LAST  REG_SP
21708 #define REG_EAX    19
21709 #define REG_EBX    20
21710 #define REG_ECX    21
21711 #define REG_EDX    22
21712 #define REG_ESI    23
21713 #define REG_EDI    24
21714 #define REG_EBP    25
21715 #define REG_ESP    26
21716 #define REGC_GPR32_FIRST REG_EAX
21717 #define REGC_GPR32_LAST  REG_ESP
21718 #define REG_EDXEAX 27
21719 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21720 #define REGC_DIVIDEND64_LAST  REG_EDXEAX
21721 #define REG_DXAX   28
21722 #define REGC_DIVIDEND32_FIRST REG_DXAX
21723 #define REGC_DIVIDEND32_LAST  REG_DXAX
21724 #define REG_MMX0   29
21725 #define REG_MMX1   30
21726 #define REG_MMX2   31
21727 #define REG_MMX3   32
21728 #define REG_MMX4   33
21729 #define REG_MMX5   34
21730 #define REG_MMX6   35
21731 #define REG_MMX7   36
21732 #define REGC_MMX_FIRST REG_MMX0
21733 #define REGC_MMX_LAST  REG_MMX7
21734 #define REG_XMM0   37
21735 #define REG_XMM1   38
21736 #define REG_XMM2   39
21737 #define REG_XMM3   40
21738 #define REG_XMM4   41
21739 #define REG_XMM5   42
21740 #define REG_XMM6   43
21741 #define REG_XMM7   44
21742 #define REGC_XMM_FIRST REG_XMM0
21743 #define REGC_XMM_LAST  REG_XMM7
21744 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21745 #define LAST_REG   REG_XMM7
21746
21747 #define REGC_GPR32_8_FIRST REG_EAX
21748 #define REGC_GPR32_8_LAST  REG_EDX
21749 #define REGC_GPR16_8_FIRST REG_AX
21750 #define REGC_GPR16_8_LAST  REG_DX
21751
21752 #define REGC_IMM8_FIRST    -1
21753 #define REGC_IMM8_LAST     -1
21754 #define REGC_IMM16_FIRST   -2
21755 #define REGC_IMM16_LAST    -1
21756 #define REGC_IMM32_FIRST   -4
21757 #define REGC_IMM32_LAST    -1
21758
21759 #if LAST_REG >= MAX_REGISTERS
21760 #error "MAX_REGISTERS to low"
21761 #endif
21762
21763
21764 static unsigned regc_size[LAST_REGC +1] = {
21765         [REGC_FLAGS]      = REGC_FLAGS_LAST      - REGC_FLAGS_FIRST + 1,
21766         [REGC_GPR8]       = REGC_GPR8_LAST       - REGC_GPR8_FIRST + 1,
21767         [REGC_GPR16]      = REGC_GPR16_LAST      - REGC_GPR16_FIRST + 1,
21768         [REGC_GPR32]      = REGC_GPR32_LAST      - REGC_GPR32_FIRST + 1,
21769         [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21770         [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21771         [REGC_MMX]        = REGC_MMX_LAST        - REGC_MMX_FIRST + 1,
21772         [REGC_XMM]        = REGC_XMM_LAST        - REGC_XMM_FIRST + 1,
21773         [REGC_GPR32_8]    = REGC_GPR32_8_LAST    - REGC_GPR32_8_FIRST + 1,
21774         [REGC_GPR16_8]    = REGC_GPR16_8_LAST    - REGC_GPR16_8_FIRST + 1,
21775         [REGC_GPR8_LO]    = REGC_GPR8_LO_LAST    - REGC_GPR8_LO_FIRST + 1,
21776         [REGC_IMM32]      = 0,
21777         [REGC_IMM16]      = 0,
21778         [REGC_IMM8]       = 0,
21779 };
21780
21781 static const struct {
21782         int first, last;
21783 } regcm_bound[LAST_REGC + 1] = {
21784         [REGC_FLAGS]      = { REGC_FLAGS_FIRST,      REGC_FLAGS_LAST },
21785         [REGC_GPR8]       = { REGC_GPR8_FIRST,       REGC_GPR8_LAST },
21786         [REGC_GPR16]      = { REGC_GPR16_FIRST,      REGC_GPR16_LAST },
21787         [REGC_GPR32]      = { REGC_GPR32_FIRST,      REGC_GPR32_LAST },
21788         [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21789         [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21790         [REGC_MMX]        = { REGC_MMX_FIRST,        REGC_MMX_LAST },
21791         [REGC_XMM]        = { REGC_XMM_FIRST,        REGC_XMM_LAST },
21792         [REGC_GPR32_8]    = { REGC_GPR32_8_FIRST,    REGC_GPR32_8_LAST },
21793         [REGC_GPR16_8]    = { REGC_GPR16_8_FIRST,    REGC_GPR16_8_LAST },
21794         [REGC_GPR8_LO]    = { REGC_GPR8_LO_FIRST,    REGC_GPR8_LO_LAST },
21795         [REGC_IMM32]      = { REGC_IMM32_FIRST,      REGC_IMM32_LAST },
21796         [REGC_IMM16]      = { REGC_IMM16_FIRST,      REGC_IMM16_LAST },
21797         [REGC_IMM8]       = { REGC_IMM8_FIRST,       REGC_IMM8_LAST },
21798 };
21799
21800 #if ARCH_INPUT_REGS != 4
21801 #error ARCH_INPUT_REGS size mismatch
21802 #endif
21803 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21804         { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21805         { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21806         { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21807         { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21808 };
21809
21810 #if ARCH_OUTPUT_REGS != 4
21811 #error ARCH_INPUT_REGS size mismatch
21812 #endif
21813 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21814         { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21815         { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21816         { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21817         { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21818 };
21819
21820 static void init_arch_state(struct arch_state *arch)
21821 {
21822         memset(arch, 0, sizeof(*arch));
21823         arch->features = 0;
21824 }
21825
21826 static const struct compiler_flag arch_flags[] = {
21827         { "mmx",       X86_MMX_REGS },
21828         { "sse",       X86_XMM_REGS },
21829         { "noop-copy", X86_NOOP_COPY },
21830         { 0,     0 },
21831 };
21832 static const struct compiler_flag arch_cpus[] = {
21833         { "i386", 0 },
21834         { "p2",   X86_MMX_REGS },
21835         { "p3",   X86_MMX_REGS | X86_XMM_REGS },
21836         { "p4",   X86_MMX_REGS | X86_XMM_REGS },
21837         { "k7",   X86_MMX_REGS },
21838         { "k8",   X86_MMX_REGS | X86_XMM_REGS },
21839         { "c3",   X86_MMX_REGS },
21840         { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21841         {  0,     0 }
21842 };
21843 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21844 {
21845         int result;
21846         int act;
21847
21848         act = 1;
21849         result = -1;
21850         if (strncmp(flag, "no-", 3) == 0) {
21851                 flag += 3;
21852                 act = 0;
21853         }
21854         if (act && strncmp(flag, "cpu=", 4) == 0) {
21855                 flag += 4;
21856                 result = set_flag(arch_cpus, &arch->features, 1, flag);
21857         }
21858         else {
21859                 result = set_flag(arch_flags, &arch->features, act, flag);
21860         }
21861         return result;
21862 }
21863
21864 static void arch_usage(FILE *fp)
21865 {
21866         flag_usage(fp, arch_flags, "-m", "-mno-");
21867         flag_usage(fp, arch_cpus, "-mcpu=", 0);
21868 }
21869
21870 static unsigned arch_regc_size(struct compile_state *state, int class)
21871 {
21872         if ((class < 0) || (class > LAST_REGC)) {
21873                 return 0;
21874         }
21875         return regc_size[class];
21876 }
21877
21878 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21879 {
21880         /* See if two register classes may have overlapping registers */
21881         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21882                 REGCM_GPR32_8 | REGCM_GPR32 | 
21883                 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21884
21885         /* Special case for the immediates */
21886         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21887                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21888                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21889                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
21890                 return 0;
21891         }
21892         return (regcm1 & regcm2) ||
21893                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21894 }
21895
21896 static void arch_reg_equivs(
21897         struct compile_state *state, unsigned *equiv, int reg)
21898 {
21899         if ((reg < 0) || (reg > LAST_REG)) {
21900                 internal_error(state, 0, "invalid register");
21901         }
21902         *equiv++ = reg;
21903         switch(reg) {
21904         case REG_AL:
21905 #if X86_4_8BIT_GPRS
21906                 *equiv++ = REG_AH;
21907 #endif
21908                 *equiv++ = REG_AX;
21909                 *equiv++ = REG_EAX;
21910                 *equiv++ = REG_DXAX;
21911                 *equiv++ = REG_EDXEAX;
21912                 break;
21913         case REG_AH:
21914 #if X86_4_8BIT_GPRS
21915                 *equiv++ = REG_AL;
21916 #endif
21917                 *equiv++ = REG_AX;
21918                 *equiv++ = REG_EAX;
21919                 *equiv++ = REG_DXAX;
21920                 *equiv++ = REG_EDXEAX;
21921                 break;
21922         case REG_BL:  
21923 #if X86_4_8BIT_GPRS
21924                 *equiv++ = REG_BH;
21925 #endif
21926                 *equiv++ = REG_BX;
21927                 *equiv++ = REG_EBX;
21928                 break;
21929
21930         case REG_BH:
21931 #if X86_4_8BIT_GPRS
21932                 *equiv++ = REG_BL;
21933 #endif
21934                 *equiv++ = REG_BX;
21935                 *equiv++ = REG_EBX;
21936                 break;
21937         case REG_CL:
21938 #if X86_4_8BIT_GPRS
21939                 *equiv++ = REG_CH;
21940 #endif
21941                 *equiv++ = REG_CX;
21942                 *equiv++ = REG_ECX;
21943                 break;
21944
21945         case REG_CH:
21946 #if X86_4_8BIT_GPRS
21947                 *equiv++ = REG_CL;
21948 #endif
21949                 *equiv++ = REG_CX;
21950                 *equiv++ = REG_ECX;
21951                 break;
21952         case REG_DL:
21953 #if X86_4_8BIT_GPRS
21954                 *equiv++ = REG_DH;
21955 #endif
21956                 *equiv++ = REG_DX;
21957                 *equiv++ = REG_EDX;
21958                 *equiv++ = REG_DXAX;
21959                 *equiv++ = REG_EDXEAX;
21960                 break;
21961         case REG_DH:
21962 #if X86_4_8BIT_GPRS
21963                 *equiv++ = REG_DL;
21964 #endif
21965                 *equiv++ = REG_DX;
21966                 *equiv++ = REG_EDX;
21967                 *equiv++ = REG_DXAX;
21968                 *equiv++ = REG_EDXEAX;
21969                 break;
21970         case REG_AX:
21971                 *equiv++ = REG_AL;
21972                 *equiv++ = REG_AH;
21973                 *equiv++ = REG_EAX;
21974                 *equiv++ = REG_DXAX;
21975                 *equiv++ = REG_EDXEAX;
21976                 break;
21977         case REG_BX:
21978                 *equiv++ = REG_BL;
21979                 *equiv++ = REG_BH;
21980                 *equiv++ = REG_EBX;
21981                 break;
21982         case REG_CX:  
21983                 *equiv++ = REG_CL;
21984                 *equiv++ = REG_CH;
21985                 *equiv++ = REG_ECX;
21986                 break;
21987         case REG_DX:  
21988                 *equiv++ = REG_DL;
21989                 *equiv++ = REG_DH;
21990                 *equiv++ = REG_EDX;
21991                 *equiv++ = REG_DXAX;
21992                 *equiv++ = REG_EDXEAX;
21993                 break;
21994         case REG_SI:  
21995                 *equiv++ = REG_ESI;
21996                 break;
21997         case REG_DI:
21998                 *equiv++ = REG_EDI;
21999                 break;
22000         case REG_BP:
22001                 *equiv++ = REG_EBP;
22002                 break;
22003         case REG_SP:
22004                 *equiv++ = REG_ESP;
22005                 break;
22006         case REG_EAX:
22007                 *equiv++ = REG_AL;
22008                 *equiv++ = REG_AH;
22009                 *equiv++ = REG_AX;
22010                 *equiv++ = REG_DXAX;
22011                 *equiv++ = REG_EDXEAX;
22012                 break;
22013         case REG_EBX:
22014                 *equiv++ = REG_BL;
22015                 *equiv++ = REG_BH;
22016                 *equiv++ = REG_BX;
22017                 break;
22018         case REG_ECX:
22019                 *equiv++ = REG_CL;
22020                 *equiv++ = REG_CH;
22021                 *equiv++ = REG_CX;
22022                 break;
22023         case REG_EDX:
22024                 *equiv++ = REG_DL;
22025                 *equiv++ = REG_DH;
22026                 *equiv++ = REG_DX;
22027                 *equiv++ = REG_DXAX;
22028                 *equiv++ = REG_EDXEAX;
22029                 break;
22030         case REG_ESI: 
22031                 *equiv++ = REG_SI;
22032                 break;
22033         case REG_EDI: 
22034                 *equiv++ = REG_DI;
22035                 break;
22036         case REG_EBP: 
22037                 *equiv++ = REG_BP;
22038                 break;
22039         case REG_ESP: 
22040                 *equiv++ = REG_SP;
22041                 break;
22042         case REG_DXAX: 
22043                 *equiv++ = REG_AL;
22044                 *equiv++ = REG_AH;
22045                 *equiv++ = REG_DL;
22046                 *equiv++ = REG_DH;
22047                 *equiv++ = REG_AX;
22048                 *equiv++ = REG_DX;
22049                 *equiv++ = REG_EAX;
22050                 *equiv++ = REG_EDX;
22051                 *equiv++ = REG_EDXEAX;
22052                 break;
22053         case REG_EDXEAX: 
22054                 *equiv++ = REG_AL;
22055                 *equiv++ = REG_AH;
22056                 *equiv++ = REG_DL;
22057                 *equiv++ = REG_DH;
22058                 *equiv++ = REG_AX;
22059                 *equiv++ = REG_DX;
22060                 *equiv++ = REG_EAX;
22061                 *equiv++ = REG_EDX;
22062                 *equiv++ = REG_DXAX;
22063                 break;
22064         }
22065         *equiv++ = REG_UNSET; 
22066 }
22067
22068 static unsigned arch_avail_mask(struct compile_state *state)
22069 {
22070         unsigned avail_mask;
22071         /* REGCM_GPR8 is not available */
22072         avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 | 
22073                 REGCM_GPR32 | REGCM_GPR32_8 | 
22074                 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22075                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22076         if (state->arch->features & X86_MMX_REGS) {
22077                 avail_mask |= REGCM_MMX;
22078         }
22079         if (state->arch->features & X86_XMM_REGS) {
22080                 avail_mask |= REGCM_XMM;
22081         }
22082         return avail_mask;
22083 }
22084
22085 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22086 {
22087         unsigned mask, result;
22088         int class, class2;
22089         result = regcm;
22090
22091         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22092                 if ((result & mask) == 0) {
22093                         continue;
22094                 }
22095                 if (class > LAST_REGC) {
22096                         result &= ~mask;
22097                 }
22098                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22099                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22100                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22101                                 result |= (1 << class2);
22102                         }
22103                 }
22104         }
22105         result &= arch_avail_mask(state);
22106         return result;
22107 }
22108
22109 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22110 {
22111         /* Like arch_regcm_normalize except immediate register classes are excluded */
22112         regcm = arch_regcm_normalize(state, regcm);
22113         /* Remove the immediate register classes */
22114         regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22115         return regcm;
22116         
22117 }
22118
22119 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22120 {
22121         unsigned mask;
22122         int class;
22123         mask = 0;
22124         for(class = 0; class <= LAST_REGC; class++) {
22125                 if ((reg >= regcm_bound[class].first) &&
22126                         (reg <= regcm_bound[class].last)) {
22127                         mask |= (1 << class);
22128                 }
22129         }
22130         if (!mask) {
22131                 internal_error(state, 0, "reg %d not in any class", reg);
22132         }
22133         return mask;
22134 }
22135
22136 static struct reg_info arch_reg_constraint(
22137         struct compile_state *state, struct type *type, const char *constraint)
22138 {
22139         static const struct {
22140                 char class;
22141                 unsigned int mask;
22142                 unsigned int reg;
22143         } constraints[] = {
22144                 { 'r', REGCM_GPR32,   REG_UNSET },
22145                 { 'g', REGCM_GPR32,   REG_UNSET },
22146                 { 'p', REGCM_GPR32,   REG_UNSET },
22147                 { 'q', REGCM_GPR8_LO, REG_UNSET },
22148                 { 'Q', REGCM_GPR32_8, REG_UNSET },
22149                 { 'x', REGCM_XMM,     REG_UNSET },
22150                 { 'y', REGCM_MMX,     REG_UNSET },
22151                 { 'a', REGCM_GPR32,   REG_EAX },
22152                 { 'b', REGCM_GPR32,   REG_EBX },
22153                 { 'c', REGCM_GPR32,   REG_ECX },
22154                 { 'd', REGCM_GPR32,   REG_EDX },
22155                 { 'D', REGCM_GPR32,   REG_EDI },
22156                 { 'S', REGCM_GPR32,   REG_ESI },
22157                 { '\0', 0, REG_UNSET },
22158         };
22159         unsigned int regcm;
22160         unsigned int mask, reg;
22161         struct reg_info result;
22162         const char *ptr;
22163         regcm = arch_type_to_regcm(state, type);
22164         reg = REG_UNSET;
22165         mask = 0;
22166         for(ptr = constraint; *ptr; ptr++) {
22167                 int i;
22168                 if (*ptr ==  ' ') {
22169                         continue;
22170                 }
22171                 for(i = 0; constraints[i].class != '\0'; i++) {
22172                         if (constraints[i].class == *ptr) {
22173                                 break;
22174                         }
22175                 }
22176                 if (constraints[i].class == '\0') {
22177                         error(state, 0, "invalid register constraint ``%c''", *ptr);
22178                         break;
22179                 }
22180                 if ((constraints[i].mask & regcm) == 0) {
22181                         error(state, 0, "invalid register class %c specified",
22182                                 *ptr);
22183                 }
22184                 mask |= constraints[i].mask;
22185                 if (constraints[i].reg != REG_UNSET) {
22186                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22187                                 error(state, 0, "Only one register may be specified");
22188                         }
22189                         reg = constraints[i].reg;
22190                 }
22191         }
22192         result.reg = reg;
22193         result.regcm = mask;
22194         return result;
22195 }
22196
22197 static struct reg_info arch_reg_clobber(
22198         struct compile_state *state, const char *clobber)
22199 {
22200         struct reg_info result;
22201         if (strcmp(clobber, "memory") == 0) {
22202                 result.reg = REG_UNSET;
22203                 result.regcm = 0;
22204         }
22205         else if (strcmp(clobber, "eax") == 0) {
22206                 result.reg = REG_EAX;
22207                 result.regcm = REGCM_GPR32;
22208         }
22209         else if (strcmp(clobber, "ebx") == 0) {
22210                 result.reg = REG_EBX;
22211                 result.regcm = REGCM_GPR32;
22212         }
22213         else if (strcmp(clobber, "ecx") == 0) {
22214                 result.reg = REG_ECX;
22215                 result.regcm = REGCM_GPR32;
22216         }
22217         else if (strcmp(clobber, "edx") == 0) {
22218                 result.reg = REG_EDX;
22219                 result.regcm = REGCM_GPR32;
22220         }
22221         else if (strcmp(clobber, "esi") == 0) {
22222                 result.reg = REG_ESI;
22223                 result.regcm = REGCM_GPR32;
22224         }
22225         else if (strcmp(clobber, "edi") == 0) {
22226                 result.reg = REG_EDI;
22227                 result.regcm = REGCM_GPR32;
22228         }
22229         else if (strcmp(clobber, "ebp") == 0) {
22230                 result.reg = REG_EBP;
22231                 result.regcm = REGCM_GPR32;
22232         }
22233         else if (strcmp(clobber, "esp") == 0) {
22234                 result.reg = REG_ESP;
22235                 result.regcm = REGCM_GPR32;
22236         }
22237         else if (strcmp(clobber, "cc") == 0) {
22238                 result.reg = REG_EFLAGS;
22239                 result.regcm = REGCM_FLAGS;
22240         }
22241         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
22242                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22243                 result.reg = REG_XMM0 + octdigval(clobber[3]);
22244                 result.regcm = REGCM_XMM;
22245         }
22246         else if ((strncmp(clobber, "mm", 2) == 0) &&
22247                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22248                 result.reg = REG_MMX0 + octdigval(clobber[3]);
22249                 result.regcm = REGCM_MMX;
22250         }
22251         else {
22252                 error(state, 0, "unknown register name `%s' in asm",
22253                         clobber);
22254                 result.reg = REG_UNSET;
22255                 result.regcm = 0;
22256         }
22257         return result;
22258 }
22259
22260 static int do_select_reg(struct compile_state *state, 
22261         char *used, int reg, unsigned classes)
22262 {
22263         unsigned mask;
22264         if (used[reg]) {
22265                 return REG_UNSET;
22266         }
22267         mask = arch_reg_regcm(state, reg);
22268         return (classes & mask) ? reg : REG_UNSET;
22269 }
22270
22271 static int arch_select_free_register(
22272         struct compile_state *state, char *used, int classes)
22273 {
22274         /* Live ranges with the most neighbors are colored first.
22275          *
22276          * Generally it does not matter which colors are given
22277          * as the register allocator attempts to color live ranges
22278          * in an order where you are guaranteed not to run out of colors.
22279          *
22280          * Occasionally the register allocator cannot find an order
22281          * of register selection that will find a free color.  To
22282          * increase the odds the register allocator will work when
22283          * it guesses first give out registers from register classes
22284          * least likely to run out of registers.
22285          * 
22286          */
22287         int i, reg;
22288         reg = REG_UNSET;
22289         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22290                 reg = do_select_reg(state, used, i, classes);
22291         }
22292         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22293                 reg = do_select_reg(state, used, i, classes);
22294         }
22295         for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22296                 reg = do_select_reg(state, used, i, classes);
22297         }
22298         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22299                 reg = do_select_reg(state, used, i, classes);
22300         }
22301         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22302                 reg = do_select_reg(state, used, i, classes);
22303         }
22304         for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22305                 reg = do_select_reg(state, used, i, classes);
22306         }
22307         for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22308                 reg = do_select_reg(state, used, i, classes);
22309         }
22310         for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22311                 reg = do_select_reg(state, used, i, classes);
22312         }
22313         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22314                 reg = do_select_reg(state, used, i, classes);
22315         }
22316         return reg;
22317 }
22318
22319
22320 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
22321 {
22322 #warning "FIXME force types smaller (if legal) before I get here"
22323         unsigned mask;
22324         mask = 0;
22325         switch(type->type & TYPE_MASK) {
22326         case TYPE_ARRAY:
22327         case TYPE_VOID: 
22328                 mask = 0; 
22329                 break;
22330         case TYPE_CHAR:
22331         case TYPE_UCHAR:
22332                 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22333                         REGCM_GPR16 | REGCM_GPR16_8 | 
22334                         REGCM_GPR32 | REGCM_GPR32_8 |
22335                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22336                         REGCM_MMX | REGCM_XMM |
22337                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22338                 break;
22339         case TYPE_SHORT:
22340         case TYPE_USHORT:
22341                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
22342                         REGCM_GPR32 | REGCM_GPR32_8 |
22343                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22344                         REGCM_MMX | REGCM_XMM |
22345                         REGCM_IMM32 | REGCM_IMM16;
22346                 break;
22347         case TYPE_ENUM:
22348         case TYPE_INT:
22349         case TYPE_UINT:
22350         case TYPE_LONG:
22351         case TYPE_ULONG:
22352         case TYPE_POINTER:
22353                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
22354                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22355                         REGCM_MMX | REGCM_XMM |
22356                         REGCM_IMM32;
22357                 break;
22358         case TYPE_JOIN:
22359         case TYPE_UNION:
22360                 mask = arch_type_to_regcm(state, type->left);
22361                 break;
22362         case TYPE_OVERLAP:
22363                 mask = arch_type_to_regcm(state, type->left) &
22364                         arch_type_to_regcm(state, type->right);
22365                 break;
22366         case TYPE_BITFIELD:
22367                 mask = arch_type_to_regcm(state, type->left);
22368                 break;
22369         default:
22370                 fprintf(state->errout, "type: ");
22371                 name_of(state->errout, type);
22372                 fprintf(state->errout, "\n");
22373                 internal_error(state, 0, "no register class for type");
22374                 break;
22375         }
22376         mask = arch_regcm_normalize(state, mask);
22377         return mask;
22378 }
22379
22380 static int is_imm32(struct triple *imm)
22381 {
22382         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
22383                 (imm->op == OP_ADDRCONST);
22384         
22385 }
22386 static int is_imm16(struct triple *imm)
22387 {
22388         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22389 }
22390 static int is_imm8(struct triple *imm)
22391 {
22392         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22393 }
22394
22395 static int get_imm32(struct triple *ins, struct triple **expr)
22396 {
22397         struct triple *imm;
22398         imm = *expr;
22399         while(imm->op == OP_COPY) {
22400                 imm = RHS(imm, 0);
22401         }
22402         if (!is_imm32(imm)) {
22403                 return 0;
22404         }
22405         unuse_triple(*expr, ins);
22406         use_triple(imm, ins);
22407         *expr = imm;
22408         return 1;
22409 }
22410
22411 static int get_imm8(struct triple *ins, struct triple **expr)
22412 {
22413         struct triple *imm;
22414         imm = *expr;
22415         while(imm->op == OP_COPY) {
22416                 imm = RHS(imm, 0);
22417         }
22418         if (!is_imm8(imm)) {
22419                 return 0;
22420         }
22421         unuse_triple(*expr, ins);
22422         use_triple(imm, ins);
22423         *expr = imm;
22424         return 1;
22425 }
22426
22427 #define TEMPLATE_NOP           0
22428 #define TEMPLATE_INTCONST8     1
22429 #define TEMPLATE_INTCONST32    2
22430 #define TEMPLATE_UNKNOWNVAL    3
22431 #define TEMPLATE_COPY8_REG     5
22432 #define TEMPLATE_COPY16_REG    6
22433 #define TEMPLATE_COPY32_REG    7
22434 #define TEMPLATE_COPY_IMM8     8
22435 #define TEMPLATE_COPY_IMM16    9
22436 #define TEMPLATE_COPY_IMM32   10
22437 #define TEMPLATE_PHI8         11
22438 #define TEMPLATE_PHI16        12
22439 #define TEMPLATE_PHI32        13
22440 #define TEMPLATE_STORE8       14
22441 #define TEMPLATE_STORE16      15
22442 #define TEMPLATE_STORE32      16
22443 #define TEMPLATE_LOAD8        17
22444 #define TEMPLATE_LOAD16       18
22445 #define TEMPLATE_LOAD32       19
22446 #define TEMPLATE_BINARY8_REG  20
22447 #define TEMPLATE_BINARY16_REG 21
22448 #define TEMPLATE_BINARY32_REG 22
22449 #define TEMPLATE_BINARY8_IMM  23
22450 #define TEMPLATE_BINARY16_IMM 24
22451 #define TEMPLATE_BINARY32_IMM 25
22452 #define TEMPLATE_SL8_CL       26
22453 #define TEMPLATE_SL16_CL      27
22454 #define TEMPLATE_SL32_CL      28
22455 #define TEMPLATE_SL8_IMM      29
22456 #define TEMPLATE_SL16_IMM     30
22457 #define TEMPLATE_SL32_IMM     31
22458 #define TEMPLATE_UNARY8       32
22459 #define TEMPLATE_UNARY16      33
22460 #define TEMPLATE_UNARY32      34
22461 #define TEMPLATE_CMP8_REG     35
22462 #define TEMPLATE_CMP16_REG    36
22463 #define TEMPLATE_CMP32_REG    37
22464 #define TEMPLATE_CMP8_IMM     38
22465 #define TEMPLATE_CMP16_IMM    39
22466 #define TEMPLATE_CMP32_IMM    40
22467 #define TEMPLATE_TEST8        41
22468 #define TEMPLATE_TEST16       42
22469 #define TEMPLATE_TEST32       43
22470 #define TEMPLATE_SET          44
22471 #define TEMPLATE_JMP          45
22472 #define TEMPLATE_RET          46
22473 #define TEMPLATE_INB_DX       47
22474 #define TEMPLATE_INB_IMM      48
22475 #define TEMPLATE_INW_DX       49
22476 #define TEMPLATE_INW_IMM      50
22477 #define TEMPLATE_INL_DX       51
22478 #define TEMPLATE_INL_IMM      52
22479 #define TEMPLATE_OUTB_DX      53
22480 #define TEMPLATE_OUTB_IMM     54
22481 #define TEMPLATE_OUTW_DX      55
22482 #define TEMPLATE_OUTW_IMM     56
22483 #define TEMPLATE_OUTL_DX      57
22484 #define TEMPLATE_OUTL_IMM     58
22485 #define TEMPLATE_BSF          59
22486 #define TEMPLATE_RDMSR        60
22487 #define TEMPLATE_WRMSR        61
22488 #define TEMPLATE_UMUL8        62
22489 #define TEMPLATE_UMUL16       63
22490 #define TEMPLATE_UMUL32       64
22491 #define TEMPLATE_DIV8         65
22492 #define TEMPLATE_DIV16        66
22493 #define TEMPLATE_DIV32        67
22494 #define LAST_TEMPLATE       TEMPLATE_DIV32
22495 #if LAST_TEMPLATE >= MAX_TEMPLATES
22496 #error "MAX_TEMPLATES to low"
22497 #endif
22498
22499 #define COPY8_REGCM     (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22500 #define COPY16_REGCM    (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)  
22501 #define COPY32_REGCM    (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22502
22503
22504 static struct ins_template templates[] = {
22505         [TEMPLATE_NOP]      = {
22506                 .lhs = { 
22507                         [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22508                         [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22509                         [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22510                         [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22511                         [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22512                         [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22513                         [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22514                         [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22515                         [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22516                         [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22517                         [10] = { REG_UNNEEDED, REGCM_IMMALL },
22518                         [11] = { REG_UNNEEDED, REGCM_IMMALL },
22519                         [12] = { REG_UNNEEDED, REGCM_IMMALL },
22520                         [13] = { REG_UNNEEDED, REGCM_IMMALL },
22521                         [14] = { REG_UNNEEDED, REGCM_IMMALL },
22522                         [15] = { REG_UNNEEDED, REGCM_IMMALL },
22523                         [16] = { REG_UNNEEDED, REGCM_IMMALL },
22524                         [17] = { REG_UNNEEDED, REGCM_IMMALL },
22525                         [18] = { REG_UNNEEDED, REGCM_IMMALL },
22526                         [19] = { REG_UNNEEDED, REGCM_IMMALL },
22527                         [20] = { REG_UNNEEDED, REGCM_IMMALL },
22528                         [21] = { REG_UNNEEDED, REGCM_IMMALL },
22529                         [22] = { REG_UNNEEDED, REGCM_IMMALL },
22530                         [23] = { REG_UNNEEDED, REGCM_IMMALL },
22531                         [24] = { REG_UNNEEDED, REGCM_IMMALL },
22532                         [25] = { REG_UNNEEDED, REGCM_IMMALL },
22533                         [26] = { REG_UNNEEDED, REGCM_IMMALL },
22534                         [27] = { REG_UNNEEDED, REGCM_IMMALL },
22535                         [28] = { REG_UNNEEDED, REGCM_IMMALL },
22536                         [29] = { REG_UNNEEDED, REGCM_IMMALL },
22537                         [30] = { REG_UNNEEDED, REGCM_IMMALL },
22538                         [31] = { REG_UNNEEDED, REGCM_IMMALL },
22539                         [32] = { REG_UNNEEDED, REGCM_IMMALL },
22540                         [33] = { REG_UNNEEDED, REGCM_IMMALL },
22541                         [34] = { REG_UNNEEDED, REGCM_IMMALL },
22542                         [35] = { REG_UNNEEDED, REGCM_IMMALL },
22543                         [36] = { REG_UNNEEDED, REGCM_IMMALL },
22544                         [37] = { REG_UNNEEDED, REGCM_IMMALL },
22545                         [38] = { REG_UNNEEDED, REGCM_IMMALL },
22546                         [39] = { REG_UNNEEDED, REGCM_IMMALL },
22547                         [40] = { REG_UNNEEDED, REGCM_IMMALL },
22548                         [41] = { REG_UNNEEDED, REGCM_IMMALL },
22549                         [42] = { REG_UNNEEDED, REGCM_IMMALL },
22550                         [43] = { REG_UNNEEDED, REGCM_IMMALL },
22551                         [44] = { REG_UNNEEDED, REGCM_IMMALL },
22552                         [45] = { REG_UNNEEDED, REGCM_IMMALL },
22553                         [46] = { REG_UNNEEDED, REGCM_IMMALL },
22554                         [47] = { REG_UNNEEDED, REGCM_IMMALL },
22555                         [48] = { REG_UNNEEDED, REGCM_IMMALL },
22556                         [49] = { REG_UNNEEDED, REGCM_IMMALL },
22557                         [50] = { REG_UNNEEDED, REGCM_IMMALL },
22558                         [51] = { REG_UNNEEDED, REGCM_IMMALL },
22559                         [52] = { REG_UNNEEDED, REGCM_IMMALL },
22560                         [53] = { REG_UNNEEDED, REGCM_IMMALL },
22561                         [54] = { REG_UNNEEDED, REGCM_IMMALL },
22562                         [55] = { REG_UNNEEDED, REGCM_IMMALL },
22563                         [56] = { REG_UNNEEDED, REGCM_IMMALL },
22564                         [57] = { REG_UNNEEDED, REGCM_IMMALL },
22565                         [58] = { REG_UNNEEDED, REGCM_IMMALL },
22566                         [59] = { REG_UNNEEDED, REGCM_IMMALL },
22567                         [60] = { REG_UNNEEDED, REGCM_IMMALL },
22568                         [61] = { REG_UNNEEDED, REGCM_IMMALL },
22569                         [62] = { REG_UNNEEDED, REGCM_IMMALL },
22570                         [63] = { REG_UNNEEDED, REGCM_IMMALL },
22571                 },
22572         },
22573         [TEMPLATE_INTCONST8] = { 
22574                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22575         },
22576         [TEMPLATE_INTCONST32] = { 
22577                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22578         },
22579         [TEMPLATE_UNKNOWNVAL] = {
22580                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22581         },
22582         [TEMPLATE_COPY8_REG] = {
22583                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22584                 .rhs = { [0] = { REG_UNSET, COPY8_REGCM }  },
22585         },
22586         [TEMPLATE_COPY16_REG] = {
22587                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22588                 .rhs = { [0] = { REG_UNSET, COPY16_REGCM }  },
22589         },
22590         [TEMPLATE_COPY32_REG] = {
22591                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22592                 .rhs = { [0] = { REG_UNSET, COPY32_REGCM }  },
22593         },
22594         [TEMPLATE_COPY_IMM8] = {
22595                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22596                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22597         },
22598         [TEMPLATE_COPY_IMM16] = {
22599                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22600                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22601         },
22602         [TEMPLATE_COPY_IMM32] = {
22603                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22604                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22605         },
22606         [TEMPLATE_PHI8] = { 
22607                 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22608                 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22609         },
22610         [TEMPLATE_PHI16] = { 
22611                 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22612                 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } }, 
22613         },
22614         [TEMPLATE_PHI32] = { 
22615                 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22616                 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } }, 
22617         },
22618         [TEMPLATE_STORE8] = {
22619                 .rhs = { 
22620                         [0] = { REG_UNSET, REGCM_GPR32 },
22621                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22622                 },
22623         },
22624         [TEMPLATE_STORE16] = {
22625                 .rhs = { 
22626                         [0] = { REG_UNSET, REGCM_GPR32 },
22627                         [1] = { REG_UNSET, REGCM_GPR16 },
22628                 },
22629         },
22630         [TEMPLATE_STORE32] = {
22631                 .rhs = { 
22632                         [0] = { REG_UNSET, REGCM_GPR32 },
22633                         [1] = { REG_UNSET, REGCM_GPR32 },
22634                 },
22635         },
22636         [TEMPLATE_LOAD8] = {
22637                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22638                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22639         },
22640         [TEMPLATE_LOAD16] = {
22641                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22642                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22643         },
22644         [TEMPLATE_LOAD32] = {
22645                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22646                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22647         },
22648         [TEMPLATE_BINARY8_REG] = {
22649                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22650                 .rhs = { 
22651                         [0] = { REG_VIRT0, REGCM_GPR8_LO },
22652                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22653                 },
22654         },
22655         [TEMPLATE_BINARY16_REG] = {
22656                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22657                 .rhs = { 
22658                         [0] = { REG_VIRT0, REGCM_GPR16 },
22659                         [1] = { REG_UNSET, REGCM_GPR16 },
22660                 },
22661         },
22662         [TEMPLATE_BINARY32_REG] = {
22663                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22664                 .rhs = { 
22665                         [0] = { REG_VIRT0, REGCM_GPR32 },
22666                         [1] = { REG_UNSET, REGCM_GPR32 },
22667                 },
22668         },
22669         [TEMPLATE_BINARY8_IMM] = {
22670                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22671                 .rhs = { 
22672                         [0] = { REG_VIRT0,    REGCM_GPR8_LO },
22673                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22674                 },
22675         },
22676         [TEMPLATE_BINARY16_IMM] = {
22677                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22678                 .rhs = { 
22679                         [0] = { REG_VIRT0,    REGCM_GPR16 },
22680                         [1] = { REG_UNNEEDED, REGCM_IMM16 },
22681                 },
22682         },
22683         [TEMPLATE_BINARY32_IMM] = {
22684                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22685                 .rhs = { 
22686                         [0] = { REG_VIRT0,    REGCM_GPR32 },
22687                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
22688                 },
22689         },
22690         [TEMPLATE_SL8_CL] = {
22691                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22692                 .rhs = { 
22693                         [0] = { REG_VIRT0, REGCM_GPR8_LO },
22694                         [1] = { REG_CL, REGCM_GPR8_LO },
22695                 },
22696         },
22697         [TEMPLATE_SL16_CL] = {
22698                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22699                 .rhs = { 
22700                         [0] = { REG_VIRT0, REGCM_GPR16 },
22701                         [1] = { REG_CL, REGCM_GPR8_LO },
22702                 },
22703         },
22704         [TEMPLATE_SL32_CL] = {
22705                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22706                 .rhs = { 
22707                         [0] = { REG_VIRT0, REGCM_GPR32 },
22708                         [1] = { REG_CL, REGCM_GPR8_LO },
22709                 },
22710         },
22711         [TEMPLATE_SL8_IMM] = {
22712                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22713                 .rhs = { 
22714                         [0] = { REG_VIRT0,    REGCM_GPR8_LO },
22715                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22716                 },
22717         },
22718         [TEMPLATE_SL16_IMM] = {
22719                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22720                 .rhs = { 
22721                         [0] = { REG_VIRT0,    REGCM_GPR16 },
22722                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22723                 },
22724         },
22725         [TEMPLATE_SL32_IMM] = {
22726                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22727                 .rhs = { 
22728                         [0] = { REG_VIRT0,    REGCM_GPR32 },
22729                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22730                 },
22731         },
22732         [TEMPLATE_UNARY8] = {
22733                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22734                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22735         },
22736         [TEMPLATE_UNARY16] = {
22737                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22738                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22739         },
22740         [TEMPLATE_UNARY32] = {
22741                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22742                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22743         },
22744         [TEMPLATE_CMP8_REG] = {
22745                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22746                 .rhs = {
22747                         [0] = { REG_UNSET, REGCM_GPR8_LO },
22748                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22749                 },
22750         },
22751         [TEMPLATE_CMP16_REG] = {
22752                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22753                 .rhs = {
22754                         [0] = { REG_UNSET, REGCM_GPR16 },
22755                         [1] = { REG_UNSET, REGCM_GPR16 },
22756                 },
22757         },
22758         [TEMPLATE_CMP32_REG] = {
22759                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22760                 .rhs = {
22761                         [0] = { REG_UNSET, REGCM_GPR32 },
22762                         [1] = { REG_UNSET, REGCM_GPR32 },
22763                 },
22764         },
22765         [TEMPLATE_CMP8_IMM] = {
22766                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22767                 .rhs = {
22768                         [0] = { REG_UNSET, REGCM_GPR8_LO },
22769                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22770                 },
22771         },
22772         [TEMPLATE_CMP16_IMM] = {
22773                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22774                 .rhs = {
22775                         [0] = { REG_UNSET, REGCM_GPR16 },
22776                         [1] = { REG_UNNEEDED, REGCM_IMM16 },
22777                 },
22778         },
22779         [TEMPLATE_CMP32_IMM] = {
22780                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22781                 .rhs = {
22782                         [0] = { REG_UNSET, REGCM_GPR32 },
22783                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
22784                 },
22785         },
22786         [TEMPLATE_TEST8] = {
22787                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22788                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22789         },
22790         [TEMPLATE_TEST16] = {
22791                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22792                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22793         },
22794         [TEMPLATE_TEST32] = {
22795                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22796                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22797         },
22798         [TEMPLATE_SET] = {
22799                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22800                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22801         },
22802         [TEMPLATE_JMP] = {
22803                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22804         },
22805         [TEMPLATE_RET] = {
22806                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22807         },
22808         [TEMPLATE_INB_DX] = {
22809                 .lhs = { [0] = { REG_AL,  REGCM_GPR8_LO } },  
22810                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22811         },
22812         [TEMPLATE_INB_IMM] = {
22813                 .lhs = { [0] = { REG_AL,  REGCM_GPR8_LO } },  
22814                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22815         },
22816         [TEMPLATE_INW_DX]  = { 
22817                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
22818                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22819         },
22820         [TEMPLATE_INW_IMM] = { 
22821                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
22822                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22823         },
22824         [TEMPLATE_INL_DX]  = {
22825                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22826                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22827         },
22828         [TEMPLATE_INL_IMM] = {
22829                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22830                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22831         },
22832         [TEMPLATE_OUTB_DX] = { 
22833                 .rhs = {
22834                         [0] = { REG_AL,  REGCM_GPR8_LO },
22835                         [1] = { REG_DX, REGCM_GPR16 },
22836                 },
22837         },
22838         [TEMPLATE_OUTB_IMM] = { 
22839                 .rhs = {
22840                         [0] = { REG_AL,  REGCM_GPR8_LO },  
22841                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22842                 },
22843         },
22844         [TEMPLATE_OUTW_DX] = { 
22845                 .rhs = {
22846                         [0] = { REG_AX,  REGCM_GPR16 },
22847                         [1] = { REG_DX, REGCM_GPR16 },
22848                 },
22849         },
22850         [TEMPLATE_OUTW_IMM] = {
22851                 .rhs = {
22852                         [0] = { REG_AX,  REGCM_GPR16 }, 
22853                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22854                 },
22855         },
22856         [TEMPLATE_OUTL_DX] = { 
22857                 .rhs = {
22858                         [0] = { REG_EAX, REGCM_GPR32 },
22859                         [1] = { REG_DX, REGCM_GPR16 },
22860                 },
22861         },
22862         [TEMPLATE_OUTL_IMM] = { 
22863                 .rhs = {
22864                         [0] = { REG_EAX, REGCM_GPR32 }, 
22865                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22866                 },
22867         },
22868         [TEMPLATE_BSF] = {
22869                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22870                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22871         },
22872         [TEMPLATE_RDMSR] = {
22873                 .lhs = { 
22874                         [0] = { REG_EAX, REGCM_GPR32 },
22875                         [1] = { REG_EDX, REGCM_GPR32 },
22876                 },
22877                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22878         },
22879         [TEMPLATE_WRMSR] = {
22880                 .rhs = {
22881                         [0] = { REG_ECX, REGCM_GPR32 },
22882                         [1] = { REG_EAX, REGCM_GPR32 },
22883                         [2] = { REG_EDX, REGCM_GPR32 },
22884                 },
22885         },
22886         [TEMPLATE_UMUL8] = {
22887                 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22888                 .rhs = { 
22889                         [0] = { REG_AL, REGCM_GPR8_LO },
22890                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22891                 },
22892         },
22893         [TEMPLATE_UMUL16] = {
22894                 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22895                 .rhs = { 
22896                         [0] = { REG_AX, REGCM_GPR16 },
22897                         [1] = { REG_UNSET, REGCM_GPR16 },
22898                 },
22899         },
22900         [TEMPLATE_UMUL32] = {
22901                 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22902                 .rhs = { 
22903                         [0] = { REG_EAX, REGCM_GPR32 },
22904                         [1] = { REG_UNSET, REGCM_GPR32 },
22905                 },
22906         },
22907         [TEMPLATE_DIV8] = {
22908                 .lhs = { 
22909                         [0] = { REG_AL, REGCM_GPR8_LO },
22910                         [1] = { REG_AH, REGCM_GPR8 },
22911                 },
22912                 .rhs = {
22913                         [0] = { REG_AX, REGCM_GPR16 },
22914                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22915                 },
22916         },
22917         [TEMPLATE_DIV16] = {
22918                 .lhs = { 
22919                         [0] = { REG_AX, REGCM_GPR16 },
22920                         [1] = { REG_DX, REGCM_GPR16 },
22921                 },
22922                 .rhs = {
22923                         [0] = { REG_DXAX, REGCM_DIVIDEND32 },
22924                         [1] = { REG_UNSET, REGCM_GPR16 },
22925                 },
22926         },
22927         [TEMPLATE_DIV32] = {
22928                 .lhs = { 
22929                         [0] = { REG_EAX, REGCM_GPR32 },
22930                         [1] = { REG_EDX, REGCM_GPR32 },
22931                 },
22932                 .rhs = {
22933                         [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
22934                         [1] = { REG_UNSET, REGCM_GPR32 },
22935                 },
22936         },
22937 };
22938
22939 static void fixup_branch(struct compile_state *state,
22940         struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
22941         struct triple *left, struct triple *right)
22942 {
22943         struct triple *test;
22944         if (!left) {
22945                 internal_error(state, branch, "no branch test?");
22946         }
22947         test = pre_triple(state, branch,
22948                 cmp_op, cmp_type, left, right);
22949         test->template_id = TEMPLATE_TEST32; 
22950         if (cmp_op == OP_CMP) {
22951                 test->template_id = TEMPLATE_CMP32_REG;
22952                 if (get_imm32(test, &RHS(test, 1))) {
22953                         test->template_id = TEMPLATE_CMP32_IMM;
22954                 }
22955         }
22956         use_triple(RHS(test, 0), test);
22957         use_triple(RHS(test, 1), test);
22958         unuse_triple(RHS(branch, 0), branch);
22959         RHS(branch, 0) = test;
22960         branch->op = jmp_op;
22961         branch->template_id = TEMPLATE_JMP;
22962         use_triple(RHS(branch, 0), branch);
22963 }
22964
22965 static void fixup_branches(struct compile_state *state,
22966         struct triple *cmp, struct triple *use, int jmp_op)
22967 {
22968         struct triple_set *entry, *next;
22969         for(entry = use->use; entry; entry = next) {
22970                 next = entry->next;
22971                 if (entry->member->op == OP_COPY) {
22972                         fixup_branches(state, cmp, entry->member, jmp_op);
22973                 }
22974                 else if (entry->member->op == OP_CBRANCH) {
22975                         struct triple *branch;
22976                         struct triple *left, *right;
22977                         left = right = 0;
22978                         left = RHS(cmp, 0);
22979                         if (cmp->rhs > 1) {
22980                                 right = RHS(cmp, 1);
22981                         }
22982                         branch = entry->member;
22983                         fixup_branch(state, branch, jmp_op, 
22984                                 cmp->op, cmp->type, left, right);
22985                 }
22986         }
22987 }
22988
22989 static void bool_cmp(struct compile_state *state, 
22990         struct triple *ins, int cmp_op, int jmp_op, int set_op)
22991 {
22992         struct triple_set *entry, *next;
22993         struct triple *set, *convert;
22994
22995         /* Put a barrier up before the cmp which preceeds the
22996          * copy instruction.  If a set actually occurs this gives
22997          * us a chance to move variables in registers out of the way.
22998          */
22999
23000         /* Modify the comparison operator */
23001         ins->op = cmp_op;
23002         ins->template_id = TEMPLATE_TEST32;
23003         if (cmp_op == OP_CMP) {
23004                 ins->template_id = TEMPLATE_CMP32_REG;
23005                 if (get_imm32(ins, &RHS(ins, 1))) {
23006                         ins->template_id =  TEMPLATE_CMP32_IMM;
23007                 }
23008         }
23009         /* Generate the instruction sequence that will transform the
23010          * result of the comparison into a logical value.
23011          */
23012         set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
23013         use_triple(ins, set);
23014         set->template_id = TEMPLATE_SET;
23015
23016         convert = set;
23017         if (!equiv_types(ins->type, set->type)) {
23018                 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
23019                 use_triple(set, convert);
23020                 convert->template_id = TEMPLATE_COPY32_REG;
23021         }
23022
23023         for(entry = ins->use; entry; entry = next) {
23024                 next = entry->next;
23025                 if (entry->member == set) {
23026                         continue;
23027                 }
23028                 replace_rhs_use(state, ins, convert, entry->member);
23029         }
23030         fixup_branches(state, ins, convert, jmp_op);
23031 }
23032
23033 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
23034 {
23035         struct ins_template *template;
23036         struct reg_info result;
23037         int zlhs;
23038         if (ins->op == OP_PIECE) {
23039                 index = ins->u.cval;
23040                 ins = MISC(ins, 0);
23041         }
23042         zlhs = ins->lhs;
23043         if (triple_is_def(state, ins)) {
23044                 zlhs = 1;
23045         }
23046         if (index >= zlhs) {
23047                 internal_error(state, ins, "index %d out of range for %s",
23048                         index, tops(ins->op));
23049         }
23050         switch(ins->op) {
23051         case OP_ASM:
23052                 template = &ins->u.ainfo->tmpl;
23053                 break;
23054         default:
23055                 if (ins->template_id > LAST_TEMPLATE) {
23056                         internal_error(state, ins, "bad template number %d", 
23057                                 ins->template_id);
23058                 }
23059                 template = &templates[ins->template_id];
23060                 break;
23061         }
23062         result = template->lhs[index];
23063         result.regcm = arch_regcm_normalize(state, result.regcm);
23064         if (result.reg != REG_UNNEEDED) {
23065                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23066         }
23067         if (result.regcm == 0) {
23068                 internal_error(state, ins, "lhs %d regcm == 0", index);
23069         }
23070         return result;
23071 }
23072
23073 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23074 {
23075         struct reg_info result;
23076         struct ins_template *template;
23077         if ((index > ins->rhs) ||
23078                 (ins->op == OP_PIECE)) {
23079                 internal_error(state, ins, "index %d out of range for %s\n",
23080                         index, tops(ins->op));
23081         }
23082         switch(ins->op) {
23083         case OP_ASM:
23084                 template = &ins->u.ainfo->tmpl;
23085                 break;
23086         case OP_PHI:
23087                 index = 0;
23088                 /* Fall through */
23089         default:
23090                 if (ins->template_id > LAST_TEMPLATE) {
23091                         internal_error(state, ins, "bad template number %d", 
23092                                 ins->template_id);
23093                 }
23094                 template = &templates[ins->template_id];
23095                 break;
23096         }
23097         result = template->rhs[index];
23098         result.regcm = arch_regcm_normalize(state, result.regcm);
23099         if (result.regcm == 0) {
23100                 internal_error(state, ins, "rhs %d regcm == 0", index);
23101         }
23102         return result;
23103 }
23104
23105 static struct triple *mod_div(struct compile_state *state,
23106         struct triple *ins, int div_op, int index)
23107 {
23108         struct triple *div, *piece0, *piece1;
23109         
23110         /* Generate the appropriate division instruction */
23111         div = post_triple(state, ins, div_op, ins->type, 0, 0);
23112         RHS(div, 0) = RHS(ins, 0);
23113         RHS(div, 1) = RHS(ins, 1);
23114         piece0 = LHS(div, 0);
23115         piece1 = LHS(div, 1);
23116         div->template_id  = TEMPLATE_DIV32;
23117         use_triple(RHS(div, 0), div);
23118         use_triple(RHS(div, 1), div);
23119         use_triple(LHS(div, 0), div);
23120         use_triple(LHS(div, 1), div);
23121
23122         /* Replate uses of ins with the appropriate piece of the div */
23123         propogate_use(state, ins, LHS(div, index));
23124         release_triple(state, ins);
23125
23126         /* Return the address of the next instruction */
23127         return piece1->next;
23128 }
23129
23130 static int noop_adecl(struct triple *adecl)
23131 {
23132         struct triple_set *use;
23133         /* It's a noop if it doesn't specify stoorage */
23134         if (adecl->lhs == 0) {
23135                 return 1;
23136         }
23137         /* Is the adecl used? If not it's a noop */
23138         for(use = adecl->use; use ; use = use->next) {
23139                 if ((use->member->op != OP_PIECE) ||
23140                         (MISC(use->member, 0) != adecl)) {
23141                         return 0;
23142                 }
23143         }
23144         return 1;
23145 }
23146
23147 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23148 {
23149         struct triple *mask, *nmask, *shift;
23150         struct triple *val, *val_mask, *val_shift;
23151         struct triple *targ, *targ_mask;
23152         struct triple *new;
23153         ulong_t the_mask, the_nmask;
23154
23155         targ = RHS(ins, 0);
23156         val = RHS(ins, 1);
23157
23158         /* Get constant for the mask value */
23159         the_mask = 1;
23160         the_mask <<= ins->u.bitfield.size;
23161         the_mask -= 1;
23162         the_mask <<= ins->u.bitfield.offset;
23163         mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23164         mask->u.cval = the_mask;
23165
23166         /* Get the inverted mask value */
23167         the_nmask = ~the_mask;
23168         nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23169         nmask->u.cval = the_nmask;
23170
23171         /* Get constant for the shift value */
23172         shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23173         shift->u.cval = ins->u.bitfield.offset;
23174
23175         /* Shift and mask the source value */
23176         val_shift = val;
23177         if (shift->u.cval != 0) {
23178                 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23179                 use_triple(val, val_shift);
23180                 use_triple(shift, val_shift);
23181         }
23182         val_mask = val_shift;
23183         if (is_signed(val->type)) {
23184                 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23185                 use_triple(val_shift, val_mask);
23186                 use_triple(mask, val_mask);
23187         }
23188
23189         /* Mask the target value */
23190         targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23191         use_triple(targ, targ_mask);
23192         use_triple(nmask, targ_mask);
23193
23194         /* Now combined them together */
23195         new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23196         use_triple(targ_mask, new);
23197         use_triple(val_mask, new);
23198
23199         /* Move all of the users over to the new expression */
23200         propogate_use(state, ins, new);
23201
23202         /* Delete the original triple */
23203         release_triple(state, ins);
23204
23205         /* Restart the transformation at mask */
23206         return mask;
23207 }
23208
23209 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23210 {
23211         struct triple *mask, *shift;
23212         struct triple *val, *val_mask, *val_shift;
23213         ulong_t the_mask;
23214
23215         val = RHS(ins, 0);
23216
23217         /* Get constant for the mask value */
23218         the_mask = 1;
23219         the_mask <<= ins->u.bitfield.size;
23220         the_mask -= 1;
23221         mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23222         mask->u.cval = the_mask;
23223
23224         /* Get constant for the right shift value */
23225         shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23226         shift->u.cval = ins->u.bitfield.offset;
23227
23228         /* Shift arithmetic right, to correct the sign */
23229         val_shift = val;
23230         if (shift->u.cval != 0) {
23231                 int op;
23232                 if (ins->op == OP_SEXTRACT) {
23233                         op = OP_SSR;
23234                 } else {
23235                         op = OP_USR;
23236                 }
23237                 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23238                 use_triple(val, val_shift);
23239                 use_triple(shift, val_shift);
23240         }
23241
23242         /* Finally mask the value */
23243         val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23244         use_triple(val_shift, val_mask);
23245         use_triple(mask,      val_mask);
23246
23247         /* Move all of the users over to the new expression */
23248         propogate_use(state, ins, val_mask);
23249
23250         /* Release the original instruction */
23251         release_triple(state, ins);
23252
23253         return mask;
23254
23255 }
23256
23257 static struct triple *transform_to_arch_instruction(
23258         struct compile_state *state, struct triple *ins)
23259 {
23260         /* Transform from generic 3 address instructions
23261          * to archtecture specific instructions.
23262          * And apply architecture specific constraints to instructions.
23263          * Copies are inserted to preserve the register flexibility
23264          * of 3 address instructions.
23265          */
23266         struct triple *next, *value;
23267         size_t size;
23268         next = ins->next;
23269         switch(ins->op) {
23270         case OP_INTCONST:
23271                 ins->template_id = TEMPLATE_INTCONST32;
23272                 if (ins->u.cval < 256) {
23273                         ins->template_id = TEMPLATE_INTCONST8;
23274                 }
23275                 break;
23276         case OP_ADDRCONST:
23277                 ins->template_id = TEMPLATE_INTCONST32;
23278                 break;
23279         case OP_UNKNOWNVAL:
23280                 ins->template_id = TEMPLATE_UNKNOWNVAL;
23281                 break;
23282         case OP_NOOP:
23283         case OP_SDECL:
23284         case OP_BLOBCONST:
23285         case OP_LABEL:
23286                 ins->template_id = TEMPLATE_NOP;
23287                 break;
23288         case OP_COPY:
23289         case OP_CONVERT:
23290                 size = size_of(state, ins->type);
23291                 value = RHS(ins, 0);
23292                 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23293                         ins->template_id = TEMPLATE_COPY_IMM8;
23294                 }
23295                 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23296                         ins->template_id = TEMPLATE_COPY_IMM16;
23297                 }
23298                 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23299                         ins->template_id = TEMPLATE_COPY_IMM32;
23300                 }
23301                 else if (is_const(value)) {
23302                         internal_error(state, ins, "bad constant passed to copy");
23303                 }
23304                 else if (size <= SIZEOF_I8) {
23305                         ins->template_id = TEMPLATE_COPY8_REG;
23306                 }
23307                 else if (size <= SIZEOF_I16) {
23308                         ins->template_id = TEMPLATE_COPY16_REG;
23309                 }
23310                 else if (size <= SIZEOF_I32) {
23311                         ins->template_id = TEMPLATE_COPY32_REG;
23312                 }
23313                 else {
23314                         internal_error(state, ins, "bad type passed to copy");
23315                 }
23316                 break;
23317         case OP_PHI:
23318                 size = size_of(state, ins->type);
23319                 if (size <= SIZEOF_I8) {
23320                         ins->template_id = TEMPLATE_PHI8;
23321                 }
23322                 else if (size <= SIZEOF_I16) {
23323                         ins->template_id = TEMPLATE_PHI16;
23324                 }
23325                 else if (size <= SIZEOF_I32) {
23326                         ins->template_id = TEMPLATE_PHI32;
23327                 }
23328                 else {
23329                         internal_error(state, ins, "bad type passed to phi");
23330                 }
23331                 break;
23332         case OP_ADECL:
23333                 /* Adecls should always be treated as dead code and
23334                  * removed.  If we are not optimizing they may linger.
23335                  */
23336                 if (!noop_adecl(ins)) {
23337                         internal_error(state, ins, "adecl remains?");
23338                 }
23339                 ins->template_id = TEMPLATE_NOP;
23340                 next = after_lhs(state, ins);
23341                 break;
23342         case OP_STORE:
23343                 switch(ins->type->type & TYPE_MASK) {
23344                 case TYPE_CHAR:    case TYPE_UCHAR:
23345                         ins->template_id = TEMPLATE_STORE8;
23346                         break;
23347                 case TYPE_SHORT:   case TYPE_USHORT:
23348                         ins->template_id = TEMPLATE_STORE16;
23349                         break;
23350                 case TYPE_INT:     case TYPE_UINT:
23351                 case TYPE_LONG:    case TYPE_ULONG:
23352                 case TYPE_POINTER:
23353                         ins->template_id = TEMPLATE_STORE32;
23354                         break;
23355                 default:
23356                         internal_error(state, ins, "unknown type in store");
23357                         break;
23358                 }
23359                 break;
23360         case OP_LOAD:
23361                 switch(ins->type->type & TYPE_MASK) {
23362                 case TYPE_CHAR:   case TYPE_UCHAR:
23363                 case TYPE_SHORT:  case TYPE_USHORT:
23364                 case TYPE_INT:    case TYPE_UINT:
23365                 case TYPE_LONG:   case TYPE_ULONG:
23366                 case TYPE_POINTER:
23367                         break;
23368                 default:
23369                         internal_error(state, ins, "unknown type in load");
23370                         break;
23371                 }
23372                 ins->template_id = TEMPLATE_LOAD32;
23373                 break;
23374         case OP_ADD:
23375         case OP_SUB:
23376         case OP_AND:
23377         case OP_XOR:
23378         case OP_OR:
23379         case OP_SMUL:
23380                 ins->template_id = TEMPLATE_BINARY32_REG;
23381                 if (get_imm32(ins, &RHS(ins, 1))) {
23382                         ins->template_id = TEMPLATE_BINARY32_IMM;
23383                 }
23384                 break;
23385         case OP_SDIVT:
23386         case OP_UDIVT:
23387                 ins->template_id = TEMPLATE_DIV32;
23388                 next = after_lhs(state, ins);
23389                 break;
23390         case OP_UMUL:
23391                 ins->template_id = TEMPLATE_UMUL32;
23392                 break;
23393         case OP_UDIV:
23394                 next = mod_div(state, ins, OP_UDIVT, 0);
23395                 break;
23396         case OP_SDIV:
23397                 next = mod_div(state, ins, OP_SDIVT, 0);
23398                 break;
23399         case OP_UMOD:
23400                 next = mod_div(state, ins, OP_UDIVT, 1);
23401                 break;
23402         case OP_SMOD:
23403                 next = mod_div(state, ins, OP_SDIVT, 1);
23404                 break;
23405         case OP_SL:
23406         case OP_SSR:
23407         case OP_USR:
23408                 ins->template_id = TEMPLATE_SL32_CL;
23409                 if (get_imm8(ins, &RHS(ins, 1))) {
23410                         ins->template_id = TEMPLATE_SL32_IMM;
23411                 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23412                         typed_pre_copy(state, &uchar_type, ins, 1);
23413                 }
23414                 break;
23415         case OP_INVERT:
23416         case OP_NEG:
23417                 ins->template_id = TEMPLATE_UNARY32;
23418                 break;
23419         case OP_EQ: 
23420                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
23421                 break;
23422         case OP_NOTEQ:
23423                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23424                 break;
23425         case OP_SLESS:
23426                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23427                 break;
23428         case OP_ULESS:
23429                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23430                 break;
23431         case OP_SMORE:
23432                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23433                 break;
23434         case OP_UMORE:
23435                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23436                 break;
23437         case OP_SLESSEQ:
23438                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23439                 break;
23440         case OP_ULESSEQ:
23441                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23442                 break;
23443         case OP_SMOREEQ:
23444                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23445                 break;
23446         case OP_UMOREEQ:
23447                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23448                 break;
23449         case OP_LTRUE:
23450                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23451                 break;
23452         case OP_LFALSE:
23453                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23454                 break;
23455         case OP_BRANCH:
23456                 ins->op = OP_JMP;
23457                 ins->template_id = TEMPLATE_NOP;
23458                 break;
23459         case OP_CBRANCH:
23460                 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST, 
23461                         RHS(ins, 0)->type, RHS(ins, 0), 0);
23462                 break;
23463         case OP_CALL:
23464                 ins->template_id = TEMPLATE_NOP;
23465                 break;
23466         case OP_RET:
23467                 ins->template_id = TEMPLATE_RET;
23468                 break;
23469         case OP_INB:
23470         case OP_INW:
23471         case OP_INL:
23472                 switch(ins->op) {
23473                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23474                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23475                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23476                 }
23477                 if (get_imm8(ins, &RHS(ins, 0))) {
23478                         ins->template_id += 1;
23479                 }
23480                 break;
23481         case OP_OUTB:
23482         case OP_OUTW:
23483         case OP_OUTL:
23484                 switch(ins->op) {
23485                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23486                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23487                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23488                 }
23489                 if (get_imm8(ins, &RHS(ins, 1))) {
23490                         ins->template_id += 1;
23491                 }
23492                 break;
23493         case OP_BSF:
23494         case OP_BSR:
23495                 ins->template_id = TEMPLATE_BSF;
23496                 break;
23497         case OP_RDMSR:
23498                 ins->template_id = TEMPLATE_RDMSR;
23499                 next = after_lhs(state, ins);
23500                 break;
23501         case OP_WRMSR:
23502                 ins->template_id = TEMPLATE_WRMSR;
23503                 break;
23504         case OP_HLT:
23505                 ins->template_id = TEMPLATE_NOP;
23506                 break;
23507         case OP_ASM:
23508                 ins->template_id = TEMPLATE_NOP;
23509                 next = after_lhs(state, ins);
23510                 break;
23511                 /* Already transformed instructions */
23512         case OP_TEST:
23513                 ins->template_id = TEMPLATE_TEST32;
23514                 break;
23515         case OP_CMP:
23516                 ins->template_id = TEMPLATE_CMP32_REG;
23517                 if (get_imm32(ins, &RHS(ins, 1))) {
23518                         ins->template_id = TEMPLATE_CMP32_IMM;
23519                 }
23520                 break;
23521         case OP_JMP:
23522                 ins->template_id = TEMPLATE_NOP;
23523                 break;
23524         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
23525         case OP_JMP_SLESS:   case OP_JMP_ULESS:
23526         case OP_JMP_SMORE:   case OP_JMP_UMORE:
23527         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23528         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23529                 ins->template_id = TEMPLATE_JMP;
23530                 break;
23531         case OP_SET_EQ:      case OP_SET_NOTEQ:
23532         case OP_SET_SLESS:   case OP_SET_ULESS:
23533         case OP_SET_SMORE:   case OP_SET_UMORE:
23534         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23535         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23536                 ins->template_id = TEMPLATE_SET;
23537                 break;
23538         case OP_DEPOSIT:
23539                 next = x86_deposit(state, ins);
23540                 break;
23541         case OP_SEXTRACT:
23542         case OP_UEXTRACT:
23543                 next = x86_extract(state, ins);
23544                 break;
23545                 /* Unhandled instructions */
23546         case OP_PIECE:
23547         default:
23548                 internal_error(state, ins, "unhandled ins: %d %s",
23549                         ins->op, tops(ins->op));
23550                 break;
23551         }
23552         return next;
23553 }
23554
23555 static long next_label(struct compile_state *state)
23556 {
23557         static long label_counter = 1000;
23558         return ++label_counter;
23559 }
23560 static void generate_local_labels(struct compile_state *state)
23561 {
23562         struct triple *first, *label;
23563         first = state->first;
23564         label = first;
23565         do {
23566                 if ((label->op == OP_LABEL) || 
23567                         (label->op == OP_SDECL)) {
23568                         if (label->use) {
23569                                 label->u.cval = next_label(state);
23570                         } else {
23571                                 label->u.cval = 0;
23572                         }
23573                         
23574                 }
23575                 label = label->next;
23576         } while(label != first);
23577 }
23578
23579 static int check_reg(struct compile_state *state, 
23580         struct triple *triple, int classes)
23581 {
23582         unsigned mask;
23583         int reg;
23584         reg = ID_REG(triple->id);
23585         if (reg == REG_UNSET) {
23586                 internal_error(state, triple, "register not set");
23587         }
23588         mask = arch_reg_regcm(state, reg);
23589         if (!(classes & mask)) {
23590                 internal_error(state, triple, "reg %d in wrong class",
23591                         reg);
23592         }
23593         return reg;
23594 }
23595
23596
23597 #if REG_XMM7 != 44
23598 #error "Registers have renumberd fix arch_reg_str"
23599 #endif
23600 static const char *arch_regs[] = {
23601         "%unset",
23602         "%unneeded",
23603         "%eflags",
23604         "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23605         "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23606         "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23607         "%edx:%eax",
23608         "%dx:%ax",
23609         "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23610         "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
23611         "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23612 };
23613 static const char *arch_reg_str(int reg)
23614 {
23615         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23616                 reg = 0;
23617         }
23618         return arch_regs[reg];
23619 }
23620
23621 static const char *reg(struct compile_state *state, struct triple *triple,
23622         int classes)
23623 {
23624         int reg;
23625         reg = check_reg(state, triple, classes);
23626         return arch_reg_str(reg);
23627 }
23628
23629 static int arch_reg_size(int reg)
23630 {
23631         int size;
23632         size = 0;
23633         if (reg == REG_EFLAGS) {
23634                 size = 32;
23635         }
23636         else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23637                 size = 8;
23638         }
23639         else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23640                 size = 16;
23641         }
23642         else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23643                 size = 32;
23644         }
23645         else if (reg == REG_EDXEAX) {
23646                 size = 64;
23647         }
23648         else if (reg == REG_DXAX) {
23649                 size = 32;
23650         }
23651         else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23652                 size = 64;
23653         }
23654         else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23655                 size = 128;
23656         }
23657         return size;
23658 }
23659
23660 static int reg_size(struct compile_state *state, struct triple *ins)
23661 {
23662         int reg;
23663         reg = ID_REG(ins->id);
23664         if (reg == REG_UNSET) {
23665                 internal_error(state, ins, "register not set");
23666         }
23667         return arch_reg_size(reg);
23668 }
23669         
23670
23671
23672 const char *type_suffix(struct compile_state *state, struct type *type)
23673 {
23674         const char *suffix;
23675         switch(size_of(state, type)) {
23676         case SIZEOF_I8:  suffix = "b"; break;
23677         case SIZEOF_I16: suffix = "w"; break;
23678         case SIZEOF_I32: suffix = "l"; break;
23679         default:
23680                 internal_error(state, 0, "unknown suffix");
23681                 suffix = 0;
23682                 break;
23683         }
23684         return suffix;
23685 }
23686
23687 static void print_const_val(
23688         struct compile_state *state, struct triple *ins, FILE *fp)
23689 {
23690         switch(ins->op) {
23691         case OP_INTCONST:
23692                 fprintf(fp, " $%ld ", 
23693                         (long)(ins->u.cval));
23694                 break;
23695         case OP_ADDRCONST:
23696                 if ((MISC(ins, 0)->op != OP_SDECL) &&
23697                         (MISC(ins, 0)->op != OP_LABEL))
23698                 {
23699                         internal_error(state, ins, "bad base for addrconst");
23700                 }
23701                 if (MISC(ins, 0)->u.cval <= 0) {
23702                         internal_error(state, ins, "unlabeled constant");
23703                 }
23704                 fprintf(fp, " $L%s%lu+%lu ",
23705                         state->compiler->label_prefix, 
23706                         (unsigned long)(MISC(ins, 0)->u.cval),
23707                         (unsigned long)(ins->u.cval));
23708                 break;
23709         default:
23710                 internal_error(state, ins, "unknown constant type");
23711                 break;
23712         }
23713 }
23714
23715 static void print_const(struct compile_state *state,
23716         struct triple *ins, FILE *fp)
23717 {
23718         switch(ins->op) {
23719         case OP_INTCONST:
23720                 switch(ins->type->type & TYPE_MASK) {
23721                 case TYPE_CHAR:
23722                 case TYPE_UCHAR:
23723                         fprintf(fp, ".byte 0x%02lx\n", 
23724                                 (unsigned long)(ins->u.cval));
23725                         break;
23726                 case TYPE_SHORT:
23727                 case TYPE_USHORT:
23728                         fprintf(fp, ".short 0x%04lx\n", 
23729                                 (unsigned long)(ins->u.cval));
23730                         break;
23731                 case TYPE_INT:
23732                 case TYPE_UINT:
23733                 case TYPE_LONG:
23734                 case TYPE_ULONG:
23735                 case TYPE_POINTER:
23736                         fprintf(fp, ".int %lu\n", 
23737                                 (unsigned long)(ins->u.cval));
23738                         break;
23739                 default:
23740                         fprintf(state->errout, "type: ");
23741                         name_of(state->errout, ins->type);
23742                         fprintf(state->errout, "\n");
23743                         internal_error(state, ins, "Unknown constant type. Val: %lu",
23744                                 (unsigned long)(ins->u.cval));
23745                 }
23746                 
23747                 break;
23748         case OP_ADDRCONST:
23749                 if ((MISC(ins, 0)->op != OP_SDECL) &&
23750                         (MISC(ins, 0)->op != OP_LABEL)) {
23751                         internal_error(state, ins, "bad base for addrconst");
23752                 }
23753                 if (MISC(ins, 0)->u.cval <= 0) {
23754                         internal_error(state, ins, "unlabeled constant");
23755                 }
23756                 fprintf(fp, ".int L%s%lu+%lu\n",
23757                         state->compiler->label_prefix,
23758                         (unsigned long)(MISC(ins, 0)->u.cval),
23759                         (unsigned long)(ins->u.cval));
23760                 break;
23761         case OP_BLOBCONST:
23762         {
23763                 unsigned char *blob;
23764                 size_t size, i;
23765                 size = size_of_in_bytes(state, ins->type);
23766                 blob = ins->u.blob;
23767                 for(i = 0; i < size; i++) {
23768                         fprintf(fp, ".byte 0x%02x\n",
23769                                 blob[i]);
23770                 }
23771                 break;
23772         }
23773         default:
23774                 internal_error(state, ins, "Unknown constant type");
23775                 break;
23776         }
23777 }
23778
23779 #define TEXT_SECTION ".rom.text"
23780 #define DATA_SECTION ".rom.data"
23781
23782 static long get_const_pool_ref(
23783         struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23784 {
23785         size_t fill_bytes;
23786         long ref;
23787         ref = next_label(state);
23788         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23789         fprintf(fp, ".balign %d\n", align_of_in_bytes(state, ins->type));
23790         fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23791         print_const(state, ins, fp);
23792         fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23793         if (fill_bytes) {
23794                 fprintf(fp, ".fill %d, 1, 0\n", fill_bytes);
23795         }
23796         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23797         return ref;
23798 }
23799
23800 static long get_mask_pool_ref(
23801         struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23802 {
23803         long ref;
23804         if (mask == 0xff) {
23805                 ref = 1;
23806         }
23807         else if (mask == 0xffff) {
23808                 ref = 2;
23809         }
23810         else {
23811                 ref = 0;
23812                 internal_error(state, ins, "unhandled mask value");
23813         }
23814         return ref;
23815 }
23816
23817 static void print_binary_op(struct compile_state *state,
23818         const char *op, struct triple *ins, FILE *fp) 
23819 {
23820         unsigned mask;
23821         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23822         if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23823                 internal_error(state, ins, "invalid register assignment");
23824         }
23825         if (is_const(RHS(ins, 1))) {
23826                 fprintf(fp, "\t%s ", op);
23827                 print_const_val(state, RHS(ins, 1), fp);
23828                 fprintf(fp, ", %s\n",
23829                         reg(state, RHS(ins, 0), mask));
23830         }
23831         else {
23832                 unsigned lmask, rmask;
23833                 int lreg, rreg;
23834                 lreg = check_reg(state, RHS(ins, 0), mask);
23835                 rreg = check_reg(state, RHS(ins, 1), mask);
23836                 lmask = arch_reg_regcm(state, lreg);
23837                 rmask = arch_reg_regcm(state, rreg);
23838                 mask = lmask & rmask;
23839                 fprintf(fp, "\t%s %s, %s\n",
23840                         op,
23841                         reg(state, RHS(ins, 1), mask),
23842                         reg(state, RHS(ins, 0), mask));
23843         }
23844 }
23845 static void print_unary_op(struct compile_state *state, 
23846         const char *op, struct triple *ins, FILE *fp)
23847 {
23848         unsigned mask;
23849         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23850         fprintf(fp, "\t%s %s\n",
23851                 op,
23852                 reg(state, RHS(ins, 0), mask));
23853 }
23854
23855 static void print_op_shift(struct compile_state *state,
23856         const char *op, struct triple *ins, FILE *fp)
23857 {
23858         unsigned mask;
23859         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23860         if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23861                 internal_error(state, ins, "invalid register assignment");
23862         }
23863         if (is_const(RHS(ins, 1))) {
23864                 fprintf(fp, "\t%s ", op);
23865                 print_const_val(state, RHS(ins, 1), fp);
23866                 fprintf(fp, ", %s\n",
23867                         reg(state, RHS(ins, 0), mask));
23868         }
23869         else {
23870                 fprintf(fp, "\t%s %s, %s\n",
23871                         op,
23872                         reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23873                         reg(state, RHS(ins, 0), mask));
23874         }
23875 }
23876
23877 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23878 {
23879         const char *op;
23880         int mask;
23881         int dreg;
23882         mask = 0;
23883         switch(ins->op) {
23884         case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23885         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23886         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23887         default:
23888                 internal_error(state, ins, "not an in operation");
23889                 op = 0;
23890                 break;
23891         }
23892         dreg = check_reg(state, ins, mask);
23893         if (!reg_is_reg(state, dreg, REG_EAX)) {
23894                 internal_error(state, ins, "dst != %%eax");
23895         }
23896         if (is_const(RHS(ins, 0))) {
23897                 fprintf(fp, "\t%s ", op);
23898                 print_const_val(state, RHS(ins, 0), fp);
23899                 fprintf(fp, ", %s\n",
23900                         reg(state, ins, mask));
23901         }
23902         else {
23903                 int addr_reg;
23904                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23905                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23906                         internal_error(state, ins, "src != %%dx");
23907                 }
23908                 fprintf(fp, "\t%s %s, %s\n",
23909                         op, 
23910                         reg(state, RHS(ins, 0), REGCM_GPR16),
23911                         reg(state, ins, mask));
23912         }
23913 }
23914
23915 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
23916 {
23917         const char *op;
23918         int mask;
23919         int lreg;
23920         mask = 0;
23921         switch(ins->op) {
23922         case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
23923         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
23924         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
23925         default:
23926                 internal_error(state, ins, "not an out operation");
23927                 op = 0;
23928                 break;
23929         }
23930         lreg = check_reg(state, RHS(ins, 0), mask);
23931         if (!reg_is_reg(state, lreg, REG_EAX)) {
23932                 internal_error(state, ins, "src != %%eax");
23933         }
23934         if (is_const(RHS(ins, 1))) {
23935                 fprintf(fp, "\t%s %s,", 
23936                         op, reg(state, RHS(ins, 0), mask));
23937                 print_const_val(state, RHS(ins, 1), fp);
23938                 fprintf(fp, "\n");
23939         }
23940         else {
23941                 int addr_reg;
23942                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
23943                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23944                         internal_error(state, ins, "dst != %%dx");
23945                 }
23946                 fprintf(fp, "\t%s %s, %s\n",
23947                         op, 
23948                         reg(state, RHS(ins, 0), mask),
23949                         reg(state, RHS(ins, 1), REGCM_GPR16));
23950         }
23951 }
23952
23953 static void print_op_move(struct compile_state *state,
23954         struct triple *ins, FILE *fp)
23955 {
23956         /* op_move is complex because there are many types
23957          * of registers we can move between.
23958          * Because OP_COPY will be introduced in arbitrary locations
23959          * OP_COPY must not affect flags.
23960          * OP_CONVERT can change the flags and it is the only operation
23961          * where it is expected the types in the registers can change.
23962          */
23963         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
23964         struct triple *dst, *src;
23965         if (state->arch->features & X86_NOOP_COPY) {
23966                 omit_copy = 0;
23967         }
23968         if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
23969                 src = RHS(ins, 0);
23970                 dst = ins;
23971         }
23972         else {
23973                 internal_error(state, ins, "unknown move operation");
23974                 src = dst = 0;
23975         }
23976         if (reg_size(state, dst) < size_of(state, dst->type)) {
23977                 internal_error(state, ins, "Invalid destination register");
23978         }
23979         if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
23980                 fprintf(state->errout, "src type: ");
23981                 name_of(state->errout, src->type);
23982                 fprintf(state->errout, "\n");
23983                 fprintf(state->errout, "dst type: ");
23984                 name_of(state->errout, dst->type);
23985                 fprintf(state->errout, "\n");
23986                 internal_error(state, ins, "Type mismatch for OP_COPY");
23987         }
23988
23989         if (!is_const(src)) {
23990                 int src_reg, dst_reg;
23991                 int src_regcm, dst_regcm;
23992                 src_reg   = ID_REG(src->id);
23993                 dst_reg   = ID_REG(dst->id);
23994                 src_regcm = arch_reg_regcm(state, src_reg);
23995                 dst_regcm = arch_reg_regcm(state, dst_reg);
23996                 /* If the class is the same just move the register */
23997                 if (src_regcm & dst_regcm & 
23998                         (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
23999                         if ((src_reg != dst_reg) || !omit_copy) {
24000                                 fprintf(fp, "\tmov %s, %s\n",
24001                                         reg(state, src, src_regcm),
24002                                         reg(state, dst, dst_regcm));
24003                         }
24004                 }
24005                 /* Move 32bit to 16bit */
24006                 else if ((src_regcm & REGCM_GPR32) &&
24007                         (dst_regcm & REGCM_GPR16)) {
24008                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
24009                         if ((src_reg != dst_reg) || !omit_copy) {
24010                                 fprintf(fp, "\tmovw %s, %s\n",
24011                                         arch_reg_str(src_reg), 
24012                                         arch_reg_str(dst_reg));
24013                         }
24014                 }
24015                 /* Move from 32bit gprs to 16bit gprs */
24016                 else if ((src_regcm & REGCM_GPR32) &&
24017                         (dst_regcm & REGCM_GPR16)) {
24018                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24019                         if ((src_reg != dst_reg) || !omit_copy) {
24020                                 fprintf(fp, "\tmov %s, %s\n",
24021                                         arch_reg_str(src_reg),
24022                                         arch_reg_str(dst_reg));
24023                         }
24024                 }
24025                 /* Move 32bit to 8bit */
24026                 else if ((src_regcm & REGCM_GPR32_8) &&
24027                         (dst_regcm & REGCM_GPR8_LO))
24028                 {
24029                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
24030                         if ((src_reg != dst_reg) || !omit_copy) {
24031                                 fprintf(fp, "\tmovb %s, %s\n",
24032                                         arch_reg_str(src_reg),
24033                                         arch_reg_str(dst_reg));
24034                         }
24035                 }
24036                 /* Move 16bit to 8bit */
24037                 else if ((src_regcm & REGCM_GPR16_8) &&
24038                         (dst_regcm & REGCM_GPR8_LO))
24039                 {
24040                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24041                         if ((src_reg != dst_reg) || !omit_copy) {
24042                                 fprintf(fp, "\tmovb %s, %s\n",
24043                                         arch_reg_str(src_reg),
24044                                         arch_reg_str(dst_reg));
24045                         }
24046                 }
24047                 /* Move 8/16bit to 16/32bit */
24048                 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) && 
24049                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24050                         const char *op;
24051                         op = is_signed(src->type)? "movsx": "movzx";
24052                         fprintf(fp, "\t%s %s, %s\n",
24053                                 op,
24054                                 reg(state, src, src_regcm),
24055                                 reg(state, dst, dst_regcm));
24056                 }
24057                 /* Move between sse registers */
24058                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24059                         if ((src_reg != dst_reg) || !omit_copy) {
24060                                 fprintf(fp, "\tmovdqa %s, %s\n",
24061                                         reg(state, src, src_regcm),
24062                                         reg(state, dst, dst_regcm));
24063                         }
24064                 }
24065                 /* Move between mmx registers */
24066                 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24067                         if ((src_reg != dst_reg) || !omit_copy) {
24068                                 fprintf(fp, "\tmovq %s, %s\n",
24069                                         reg(state, src, src_regcm),
24070                                         reg(state, dst, dst_regcm));
24071                         }
24072                 }
24073                 /* Move from sse to mmx registers */
24074                 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24075                         fprintf(fp, "\tmovdq2q %s, %s\n",
24076                                 reg(state, src, src_regcm),
24077                                 reg(state, dst, dst_regcm));
24078                 }
24079                 /* Move from mmx to sse registers */
24080                 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24081                         fprintf(fp, "\tmovq2dq %s, %s\n",
24082                                 reg(state, src, src_regcm),
24083                                 reg(state, dst, dst_regcm));
24084                 }
24085                 /* Move between 32bit gprs & mmx/sse registers */
24086                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24087                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24088                         fprintf(fp, "\tmovd %s, %s\n",
24089                                 reg(state, src, src_regcm),
24090                                 reg(state, dst, dst_regcm));
24091                 }
24092                 /* Move from 16bit gprs &  mmx/sse registers */
24093                 else if ((src_regcm & REGCM_GPR16) &&
24094                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24095                         const char *op;
24096                         int mid_reg;
24097                         op = is_signed(src->type)? "movsx":"movzx";
24098                         mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24099                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24100                                 op,
24101                                 arch_reg_str(src_reg),
24102                                 arch_reg_str(mid_reg),
24103                                 arch_reg_str(mid_reg),
24104                                 arch_reg_str(dst_reg));
24105                 }
24106                 /* Move from mmx/sse registers to 16bit gprs */
24107                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24108                         (dst_regcm & REGCM_GPR16)) {
24109                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24110                         fprintf(fp, "\tmovd %s, %s\n",
24111                                 arch_reg_str(src_reg),
24112                                 arch_reg_str(dst_reg));
24113                 }
24114                 /* Move from gpr to 64bit dividend */
24115                 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))  &&
24116                         (dst_regcm & REGCM_DIVIDEND64)) {
24117                         const char *extend;
24118                         extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24119                         fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24120                                 arch_reg_str(src_reg), 
24121                                 extend);
24122                 }
24123                 /* Move from 64bit gpr to gpr */
24124                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24125                         (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24126                         if (dst_regcm & REGCM_GPR32) {
24127                                 src_reg = REG_EAX;
24128                         } 
24129                         else if (dst_regcm & REGCM_GPR16) {
24130                                 src_reg = REG_AX;
24131                         }
24132                         else if (dst_regcm & REGCM_GPR8_LO) {
24133                                 src_reg = REG_AL;
24134                         }
24135                         fprintf(fp, "\tmov %s, %s\n",
24136                                 arch_reg_str(src_reg),
24137                                 arch_reg_str(dst_reg));
24138                 }
24139                 /* Move from mmx/sse registers to 64bit gpr */
24140                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24141                         (dst_regcm & REGCM_DIVIDEND64)) {
24142                         const char *extend;
24143                         extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24144                         fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24145                                 arch_reg_str(src_reg),
24146                                 extend);
24147                 }
24148                 /* Move from 64bit gpr to mmx/sse register */
24149                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24150                         (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24151                         fprintf(fp, "\tmovd %%eax, %s\n",
24152                                 arch_reg_str(dst_reg));
24153                 }
24154 #if X86_4_8BIT_GPRS
24155                 /* Move from 8bit gprs to  mmx/sse registers */
24156                 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24157                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24158                         const char *op;
24159                         int mid_reg;
24160                         op = is_signed(src->type)? "movsx":"movzx";
24161                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24162                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24163                                 op,
24164                                 reg(state, src, src_regcm),
24165                                 arch_reg_str(mid_reg),
24166                                 arch_reg_str(mid_reg),
24167                                 reg(state, dst, dst_regcm));
24168                 }
24169                 /* Move from mmx/sse registers and 8bit gprs */
24170                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24171                         (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24172                         int mid_reg;
24173                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24174                         fprintf(fp, "\tmovd %s, %s\n",
24175                                 reg(state, src, src_regcm),
24176                                 arch_reg_str(mid_reg));
24177                 }
24178                 /* Move from 32bit gprs to 8bit gprs */
24179                 else if ((src_regcm & REGCM_GPR32) &&
24180                         (dst_regcm & REGCM_GPR8_LO)) {
24181                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24182                         if ((src_reg != dst_reg) || !omit_copy) {
24183                                 fprintf(fp, "\tmov %s, %s\n",
24184                                         arch_reg_str(src_reg),
24185                                         arch_reg_str(dst_reg));
24186                         }
24187                 }
24188                 /* Move from 16bit gprs to 8bit gprs */
24189                 else if ((src_regcm & REGCM_GPR16) &&
24190                         (dst_regcm & REGCM_GPR8_LO)) {
24191                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24192                         if ((src_reg != dst_reg) || !omit_copy) {
24193                                 fprintf(fp, "\tmov %s, %s\n",
24194                                         arch_reg_str(src_reg),
24195                                         arch_reg_str(dst_reg));
24196                         }
24197                 }
24198 #endif /* X86_4_8BIT_GPRS */
24199                 /* Move from %eax:%edx to %eax:%edx */
24200                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24201                         (dst_regcm & REGCM_DIVIDEND64) &&
24202                         (src_reg == dst_reg)) {
24203                         if (!omit_copy) {
24204                                 fprintf(fp, "\t/*mov %s, %s*/\n",
24205                                         arch_reg_str(src_reg),
24206                                         arch_reg_str(dst_reg));
24207                         }
24208                 }
24209                 else {
24210                         if ((src_regcm & ~REGCM_FLAGS) == 0) {
24211                                 internal_error(state, ins, "attempt to copy from %%eflags!");
24212                         }
24213                         internal_error(state, ins, "unknown copy type");
24214                 }
24215         }
24216         else {
24217                 size_t dst_size;
24218                 int dst_reg;
24219                 int dst_regcm;
24220                 dst_size = size_of(state, dst->type);
24221                 dst_reg = ID_REG(dst->id);
24222                 dst_regcm = arch_reg_regcm(state, dst_reg);
24223                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24224                         fprintf(fp, "\tmov ");
24225                         print_const_val(state, src, fp);
24226                         fprintf(fp, ", %s\n",
24227                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24228                 }
24229                 else if (dst_regcm & REGCM_DIVIDEND64) {
24230                         if (dst_size > SIZEOF_I32) {
24231                                 internal_error(state, ins, "%dbit constant...", dst_size);
24232                         }
24233                         fprintf(fp, "\tmov $0, %%edx\n");
24234                         fprintf(fp, "\tmov ");
24235                         print_const_val(state, src, fp);
24236                         fprintf(fp, ", %%eax\n");
24237                 }
24238                 else if (dst_regcm & REGCM_DIVIDEND32) {
24239                         if (dst_size > SIZEOF_I16) {
24240                                 internal_error(state, ins, "%dbit constant...", dst_size);
24241                         }
24242                         fprintf(fp, "\tmov $0, %%dx\n");
24243                         fprintf(fp, "\tmov ");
24244                         print_const_val(state, src, fp);
24245                         fprintf(fp, ", %%ax");
24246                 }
24247                 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24248                         long ref;
24249                         if (dst_size > SIZEOF_I32) {
24250                                 internal_error(state, ins, "%d bit constant...", dst_size);
24251                         }
24252                         ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24253                         fprintf(fp, "\tmovd L%s%lu, %s\n",
24254                                 state->compiler->label_prefix, ref,
24255                                 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24256                 }
24257                 else {
24258                         internal_error(state, ins, "unknown copy immediate type");
24259                 }
24260         }
24261         /* Leave now if this is not a type conversion */
24262         if (ins->op != OP_CONVERT) {
24263                 return;
24264         }
24265         /* Now make certain I have not logically overflowed the destination */
24266         if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24267                 (size_of(state, dst->type) < reg_size(state, dst)))
24268         {
24269                 unsigned long mask;
24270                 int dst_reg;
24271                 int dst_regcm;
24272                 if (size_of(state, dst->type) >= 32) {
24273                         fprintf(state->errout, "dst type: ");
24274                         name_of(state->errout, dst->type);
24275                         fprintf(state->errout, "\n");
24276                         internal_error(state, dst, "unhandled dst type size");
24277                 }
24278                 mask = 1;
24279                 mask <<= size_of(state, dst->type);
24280                 mask -= 1;
24281
24282                 dst_reg = ID_REG(dst->id);
24283                 dst_regcm = arch_reg_regcm(state, dst_reg);
24284
24285                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24286                         fprintf(fp, "\tand $0x%lx, %s\n",
24287                                 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24288                 }
24289                 else if (dst_regcm & REGCM_MMX) {
24290                         long ref;
24291                         ref = get_mask_pool_ref(state, dst, mask, fp);
24292                         fprintf(fp, "\tpand L%s%lu, %s\n",
24293                                 state->compiler->label_prefix, ref,
24294                                 reg(state, dst, REGCM_MMX));
24295                 }
24296                 else if (dst_regcm & REGCM_XMM) {
24297                         long ref;
24298                         ref = get_mask_pool_ref(state, dst, mask, fp);
24299                         fprintf(fp, "\tpand L%s%lu, %s\n",
24300                                 state->compiler->label_prefix, ref,
24301                                 reg(state, dst, REGCM_XMM));
24302                 }
24303                 else {
24304                         fprintf(state->errout, "dst type: ");
24305                         name_of(state->errout, dst->type);
24306                         fprintf(state->errout, "\n");
24307                         fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24308                         internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24309                 }
24310         }
24311         /* Make certain I am properly sign extended */
24312         if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24313                 (is_signed(src->type)))
24314         {
24315                 int bits, reg_bits, shift_bits;
24316                 int dst_reg;
24317                 int dst_regcm;
24318
24319                 bits = size_of(state, src->type);
24320                 reg_bits = reg_size(state, dst);
24321                 if (reg_bits > 32) {
24322                         reg_bits = 32;
24323                 }
24324                 shift_bits = reg_bits - size_of(state, src->type);
24325                 dst_reg = ID_REG(dst->id);
24326                 dst_regcm = arch_reg_regcm(state, dst_reg);
24327
24328                 if (shift_bits < 0) {
24329                         internal_error(state, dst, "negative shift?");
24330                 }
24331
24332                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24333                         fprintf(fp, "\tshl $%d, %s\n", 
24334                                 shift_bits, 
24335                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24336                         fprintf(fp, "\tsar $%d, %s\n", 
24337                                 shift_bits, 
24338                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24339                 }
24340                 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24341                         fprintf(fp, "\tpslld $%d, %s\n",
24342                                 shift_bits, 
24343                                 reg(state, dst, REGCM_MMX | REGCM_XMM));
24344                         fprintf(fp, "\tpsrad $%d, %s\n",
24345                                 shift_bits, 
24346                                 reg(state, dst, REGCM_MMX | REGCM_XMM));
24347                 }
24348                 else {
24349                         fprintf(state->errout, "dst type: ");
24350                         name_of(state->errout, dst->type);
24351                         fprintf(state->errout, "\n");
24352                         fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24353                         internal_error(state, dst, "failed to signed extend value");
24354                 }
24355         }
24356 }
24357
24358 static void print_op_load(struct compile_state *state,
24359         struct triple *ins, FILE *fp)
24360 {
24361         struct triple *dst, *src;
24362         const char *op;
24363         dst = ins;
24364         src = RHS(ins, 0);
24365         if (is_const(src) || is_const(dst)) {
24366                 internal_error(state, ins, "unknown load operation");
24367         }
24368         switch(ins->type->type & TYPE_MASK) {
24369         case TYPE_CHAR:   op = "movsbl"; break;
24370         case TYPE_UCHAR:  op = "movzbl"; break;
24371         case TYPE_SHORT:  op = "movswl"; break;
24372         case TYPE_USHORT: op = "movzwl"; break;
24373         case TYPE_INT:    case TYPE_UINT:
24374         case TYPE_LONG:   case TYPE_ULONG:
24375         case TYPE_POINTER:
24376                 op = "movl"; 
24377                 break;
24378         default:
24379                 internal_error(state, ins, "unknown type in load");
24380                 op = "<invalid opcode>";
24381                 break;
24382         }
24383         fprintf(fp, "\t%s (%s), %s\n",
24384                 op, 
24385                 reg(state, src, REGCM_GPR32),
24386                 reg(state, dst, REGCM_GPR32));
24387 }
24388
24389
24390 static void print_op_store(struct compile_state *state,
24391         struct triple *ins, FILE *fp)
24392 {
24393         struct triple *dst, *src;
24394         dst = RHS(ins, 0);
24395         src = RHS(ins, 1);
24396         if (is_const(src) && (src->op == OP_INTCONST)) {
24397                 long_t value;
24398                 value = (long_t)(src->u.cval);
24399                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24400                         type_suffix(state, src->type),
24401                         (long)(value),
24402                         reg(state, dst, REGCM_GPR32));
24403         }
24404         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24405                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24406                         type_suffix(state, src->type),
24407                         reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24408                         (unsigned long)(dst->u.cval));
24409         }
24410         else {
24411                 if (is_const(src) || is_const(dst)) {
24412                         internal_error(state, ins, "unknown store operation");
24413                 }
24414                 fprintf(fp, "\tmov%s %s, (%s)\n",
24415                         type_suffix(state, src->type),
24416                         reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24417                         reg(state, dst, REGCM_GPR32));
24418         }
24419         
24420         
24421 }
24422
24423 static void print_op_smul(struct compile_state *state,
24424         struct triple *ins, FILE *fp)
24425 {
24426         if (!is_const(RHS(ins, 1))) {
24427                 fprintf(fp, "\timul %s, %s\n",
24428                         reg(state, RHS(ins, 1), REGCM_GPR32),
24429                         reg(state, RHS(ins, 0), REGCM_GPR32));
24430         }
24431         else {
24432                 fprintf(fp, "\timul ");
24433                 print_const_val(state, RHS(ins, 1), fp);
24434                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24435         }
24436 }
24437
24438 static void print_op_cmp(struct compile_state *state,
24439         struct triple *ins, FILE *fp)
24440 {
24441         unsigned mask;
24442         int dreg;
24443         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24444         dreg = check_reg(state, ins, REGCM_FLAGS);
24445         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24446                 internal_error(state, ins, "bad dest register for cmp");
24447         }
24448         if (is_const(RHS(ins, 1))) {
24449                 fprintf(fp, "\tcmp ");
24450                 print_const_val(state, RHS(ins, 1), fp);
24451                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24452         }
24453         else {
24454                 unsigned lmask, rmask;
24455                 int lreg, rreg;
24456                 lreg = check_reg(state, RHS(ins, 0), mask);
24457                 rreg = check_reg(state, RHS(ins, 1), mask);
24458                 lmask = arch_reg_regcm(state, lreg);
24459                 rmask = arch_reg_regcm(state, rreg);
24460                 mask = lmask & rmask;
24461                 fprintf(fp, "\tcmp %s, %s\n",
24462                         reg(state, RHS(ins, 1), mask),
24463                         reg(state, RHS(ins, 0), mask));
24464         }
24465 }
24466
24467 static void print_op_test(struct compile_state *state,
24468         struct triple *ins, FILE *fp)
24469 {
24470         unsigned mask;
24471         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24472         fprintf(fp, "\ttest %s, %s\n",
24473                 reg(state, RHS(ins, 0), mask),
24474                 reg(state, RHS(ins, 0), mask));
24475 }
24476
24477 static void print_op_branch(struct compile_state *state,
24478         struct triple *branch, FILE *fp)
24479 {
24480         const char *bop = "j";
24481         if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24482                 if (branch->rhs != 0) {
24483                         internal_error(state, branch, "jmp with condition?");
24484                 }
24485                 bop = "jmp";
24486         }
24487         else {
24488                 struct triple *ptr;
24489                 if (branch->rhs != 1) {
24490                         internal_error(state, branch, "jmpcc without condition?");
24491                 }
24492                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24493                 if ((RHS(branch, 0)->op != OP_CMP) &&
24494                         (RHS(branch, 0)->op != OP_TEST)) {
24495                         internal_error(state, branch, "bad branch test");
24496                 }
24497 #warning "FIXME I have observed instructions between the test and branch instructions"
24498                 ptr = RHS(branch, 0);
24499                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24500                         if (ptr->op != OP_COPY) {
24501                                 internal_error(state, branch, "branch does not follow test");
24502                         }
24503                 }
24504                 switch(branch->op) {
24505                 case OP_JMP_EQ:       bop = "jz";  break;
24506                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
24507                 case OP_JMP_SLESS:    bop = "jl";  break;
24508                 case OP_JMP_ULESS:    bop = "jb";  break;
24509                 case OP_JMP_SMORE:    bop = "jg";  break;
24510                 case OP_JMP_UMORE:    bop = "ja";  break;
24511                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
24512                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
24513                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
24514                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
24515                 default:
24516                         internal_error(state, branch, "Invalid branch op");
24517                         break;
24518                 }
24519                 
24520         }
24521 #if 1
24522         if (branch->op == OP_CALL) {
24523                 fprintf(fp, "\t/* call */\n");
24524         }
24525 #endif
24526         fprintf(fp, "\t%s L%s%lu\n",
24527                 bop, 
24528                 state->compiler->label_prefix,
24529                 (unsigned long)(TARG(branch, 0)->u.cval));
24530 }
24531
24532 static void print_op_ret(struct compile_state *state,
24533         struct triple *branch, FILE *fp)
24534 {
24535         fprintf(fp, "\tjmp *%s\n",
24536                 reg(state, RHS(branch, 0), REGCM_GPR32));
24537 }
24538
24539 static void print_op_set(struct compile_state *state,
24540         struct triple *set, FILE *fp)
24541 {
24542         const char *sop = "set";
24543         if (set->rhs != 1) {
24544                 internal_error(state, set, "setcc without condition?");
24545         }
24546         check_reg(state, RHS(set, 0), REGCM_FLAGS);
24547         if ((RHS(set, 0)->op != OP_CMP) &&
24548                 (RHS(set, 0)->op != OP_TEST)) {
24549                 internal_error(state, set, "bad set test");
24550         }
24551         if (RHS(set, 0)->next != set) {
24552                 internal_error(state, set, "set does not follow test");
24553         }
24554         switch(set->op) {
24555         case OP_SET_EQ:       sop = "setz";  break;
24556         case OP_SET_NOTEQ:    sop = "setnz"; break;
24557         case OP_SET_SLESS:    sop = "setl";  break;
24558         case OP_SET_ULESS:    sop = "setb";  break;
24559         case OP_SET_SMORE:    sop = "setg";  break;
24560         case OP_SET_UMORE:    sop = "seta";  break;
24561         case OP_SET_SLESSEQ:  sop = "setle"; break;
24562         case OP_SET_ULESSEQ:  sop = "setbe"; break;
24563         case OP_SET_SMOREEQ:  sop = "setge"; break;
24564         case OP_SET_UMOREEQ:  sop = "setae"; break;
24565         default:
24566                 internal_error(state, set, "Invalid set op");
24567                 break;
24568         }
24569         fprintf(fp, "\t%s %s\n",
24570                 sop, reg(state, set, REGCM_GPR8_LO));
24571 }
24572
24573 static void print_op_bit_scan(struct compile_state *state, 
24574         struct triple *ins, FILE *fp) 
24575 {
24576         const char *op;
24577         switch(ins->op) {
24578         case OP_BSF: op = "bsf"; break;
24579         case OP_BSR: op = "bsr"; break;
24580         default: 
24581                 internal_error(state, ins, "unknown bit scan");
24582                 op = 0;
24583                 break;
24584         }
24585         fprintf(fp, 
24586                 "\t%s %s, %s\n"
24587                 "\tjnz 1f\n"
24588                 "\tmovl $-1, %s\n"
24589                 "1:\n",
24590                 op,
24591                 reg(state, RHS(ins, 0), REGCM_GPR32),
24592                 reg(state, ins, REGCM_GPR32),
24593                 reg(state, ins, REGCM_GPR32));
24594 }
24595
24596
24597 static void print_sdecl(struct compile_state *state,
24598         struct triple *ins, FILE *fp)
24599 {
24600         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24601         fprintf(fp, ".balign %d\n", align_of_in_bytes(state, ins->type));
24602         fprintf(fp, "L%s%lu:\n", 
24603                 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24604         print_const(state, MISC(ins, 0), fp);
24605         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24606                 
24607 }
24608
24609 static void print_instruction(struct compile_state *state,
24610         struct triple *ins, FILE *fp)
24611 {
24612         /* Assumption: after I have exted the register allocator
24613          * everything is in a valid register. 
24614          */
24615         switch(ins->op) {
24616         case OP_ASM:
24617                 print_op_asm(state, ins, fp);
24618                 break;
24619         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
24620         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
24621         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
24622         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
24623         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
24624         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
24625         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
24626         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
24627         case OP_POS:    break;
24628         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
24629         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24630         case OP_NOOP:
24631         case OP_INTCONST:
24632         case OP_ADDRCONST:
24633         case OP_BLOBCONST:
24634                 /* Don't generate anything here for constants */
24635         case OP_PHI:
24636                 /* Don't generate anything for variable declarations. */
24637                 break;
24638         case OP_UNKNOWNVAL:
24639                 fprintf(fp, " /* unknown %s */\n",
24640                         reg(state, ins, REGCM_ALL));
24641                 break;
24642         case OP_SDECL:
24643                 print_sdecl(state, ins, fp);
24644                 break;
24645         case OP_COPY:   
24646         case OP_CONVERT:
24647                 print_op_move(state, ins, fp);
24648                 break;
24649         case OP_LOAD:
24650                 print_op_load(state, ins, fp);
24651                 break;
24652         case OP_STORE:
24653                 print_op_store(state, ins, fp);
24654                 break;
24655         case OP_SMUL:
24656                 print_op_smul(state, ins, fp);
24657                 break;
24658         case OP_CMP:    print_op_cmp(state, ins, fp); break;
24659         case OP_TEST:   print_op_test(state, ins, fp); break;
24660         case OP_JMP:
24661         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
24662         case OP_JMP_SLESS:   case OP_JMP_ULESS:
24663         case OP_JMP_SMORE:   case OP_JMP_UMORE:
24664         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24665         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24666         case OP_CALL:
24667                 print_op_branch(state, ins, fp);
24668                 break;
24669         case OP_RET:
24670                 print_op_ret(state, ins, fp);
24671                 break;
24672         case OP_SET_EQ:      case OP_SET_NOTEQ:
24673         case OP_SET_SLESS:   case OP_SET_ULESS:
24674         case OP_SET_SMORE:   case OP_SET_UMORE:
24675         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24676         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24677                 print_op_set(state, ins, fp);
24678                 break;
24679         case OP_INB:  case OP_INW:  case OP_INL:
24680                 print_op_in(state, ins, fp); 
24681                 break;
24682         case OP_OUTB: case OP_OUTW: case OP_OUTL:
24683                 print_op_out(state, ins, fp); 
24684                 break;
24685         case OP_BSF:
24686         case OP_BSR:
24687                 print_op_bit_scan(state, ins, fp);
24688                 break;
24689         case OP_RDMSR:
24690                 after_lhs(state, ins);
24691                 fprintf(fp, "\trdmsr\n");
24692                 break;
24693         case OP_WRMSR:
24694                 fprintf(fp, "\twrmsr\n");
24695                 break;
24696         case OP_HLT:
24697                 fprintf(fp, "\thlt\n");
24698                 break;
24699         case OP_SDIVT:
24700                 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24701                 break;
24702         case OP_UDIVT:
24703                 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24704                 break;
24705         case OP_UMUL:
24706                 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24707                 break;
24708         case OP_LABEL:
24709                 if (!ins->use) {
24710                         return;
24711                 }
24712                 fprintf(fp, "L%s%lu:\n", 
24713                         state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24714                 break;
24715         case OP_ADECL:
24716                 /* Ignore adecls with no registers error otherwise */
24717                 if (!noop_adecl(ins)) {
24718                         internal_error(state, ins, "adecl remains?");
24719                 }
24720                 break;
24721                 /* Ignore OP_PIECE */
24722         case OP_PIECE:
24723                 break;
24724                 /* Operations that should never get here */
24725         case OP_SDIV: case OP_UDIV:
24726         case OP_SMOD: case OP_UMOD:
24727         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
24728         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
24729         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24730         default:
24731                 internal_error(state, ins, "unknown op: %d %s",
24732                         ins->op, tops(ins->op));
24733                 break;
24734         }
24735 }
24736
24737 static void print_instructions(struct compile_state *state)
24738 {
24739         struct triple *first, *ins;
24740         int print_location;
24741         struct occurance *last_occurance;
24742         FILE *fp;
24743         int max_inline_depth;
24744         max_inline_depth = 0;
24745         print_location = 1;
24746         last_occurance = 0;
24747         fp = state->output;
24748         /* Masks for common sizes */
24749         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24750         fprintf(fp, ".balign 16\n");
24751         fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24752         fprintf(fp, ".int 0xff, 0, 0, 0\n");
24753         fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24754         fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24755         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24756         first = state->first;
24757         ins = first;
24758         do {
24759                 if (print_location && 
24760                         last_occurance != ins->occurance) {
24761                         if (!ins->occurance->parent) {
24762                                 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24763                                         ins->occurance->function,
24764                                         ins->occurance->filename,
24765                                         ins->occurance->line,
24766                                         ins->occurance->col);
24767                         }
24768                         else {
24769                                 struct occurance *ptr;
24770                                 int inline_depth;
24771                                 fprintf(fp, "\t/*\n");
24772                                 inline_depth = 0;
24773                                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24774                                         inline_depth++;
24775                                         fprintf(fp, "\t * %s,%s:%d.%d\n",
24776                                                 ptr->function,
24777                                                 ptr->filename,
24778                                                 ptr->line,
24779                                                 ptr->col);
24780                                 }
24781                                 fprintf(fp, "\t */\n");
24782                                 if (inline_depth > max_inline_depth) {
24783                                         max_inline_depth = inline_depth;
24784                                 }
24785                         }
24786                         if (last_occurance) {
24787                                 put_occurance(last_occurance);
24788                         }
24789                         get_occurance(ins->occurance);
24790                         last_occurance = ins->occurance;
24791                 }
24792
24793                 print_instruction(state, ins, fp);
24794                 ins = ins->next;
24795         } while(ins != first);
24796         if (print_location) {
24797                 fprintf(fp, "/* max inline depth %d */\n",
24798                         max_inline_depth);
24799         }
24800 }
24801
24802 static void generate_code(struct compile_state *state)
24803 {
24804         generate_local_labels(state);
24805         print_instructions(state);
24806         
24807 }
24808
24809 static void print_preprocessed_tokens(struct compile_state *state)
24810 {
24811         struct token *tk;
24812         int tok;
24813         FILE *fp;
24814         int line;
24815         const char *filename;
24816         fp = state->output;
24817         tk = &state->token[0];
24818         filename = 0;
24819         line = 0;
24820         for(;;) {
24821                 const char *token_str;
24822                 tok = peek(state);
24823                 if (tok == TOK_EOF) {
24824                         break;
24825                 }
24826                 eat(state, tok);
24827                 token_str = 
24828                         tk->ident ? tk->ident->name :
24829                         tk->str_len ? tk->val.str :
24830                         tokens[tk->tok];
24831                 
24832                 if ((state->file->line != line) || 
24833                         (state->file->basename != filename)) {
24834                         int i, col;
24835                         if ((state->file->basename == filename) &&
24836                                 (line < state->file->line)) {
24837                                 while(line < state->file->line) {
24838                                         fprintf(fp, "\n");
24839                                         line++;
24840                                 }
24841                         }
24842                         else {
24843                                 fprintf(fp, "\n#line %d \"%s\"\n",
24844                                         state->file->line, state->file->basename);
24845                         }
24846                         line = state->file->line;
24847                         filename = state->file->basename;
24848                         col = get_col(state->file) - strlen(token_str);
24849                         for(i = 0; i < col; i++) {
24850                                 fprintf(fp, " ");
24851                         }
24852                 }
24853                 
24854                 fprintf(fp, "%s ", token_str);
24855                 
24856                 if (state->compiler->debug & DEBUG_TOKENS) {
24857                         loc(state->dbgout, state, 0);
24858                         fprintf(state->dbgout, "%s <- `%s'\n",
24859                                 tokens[tok], token_str);
24860                 }
24861         }
24862 }
24863
24864 static void compile(const char *filename, 
24865         struct compiler_state *compiler, struct arch_state *arch)
24866 {
24867         int i;
24868         struct compile_state state;
24869         struct triple *ptr;
24870         memset(&state, 0, sizeof(state));
24871         state.compiler = compiler;
24872         state.arch     = arch;
24873         state.file = 0;
24874         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24875                 memset(&state.token[i], 0, sizeof(state.token[i]));
24876                 state.token[i].tok = -1;
24877         }
24878         /* Remember the output descriptors */
24879         state.errout = stderr;
24880         state.dbgout = stdout;
24881         /* Remember the output filename */
24882         state.output    = fopen(state.compiler->ofilename, "w");
24883         if (!state.output) {
24884                 error(&state, 0, "Cannot open output file %s\n",
24885                         state.compiler->ofilename);
24886         }
24887         /* Make certain a good cleanup happens */
24888         exit_state = &state;
24889         atexit(exit_cleanup);
24890
24891         /* Prep the preprocessor */
24892         state.if_depth = 0;
24893         memset(state.if_bytes, 0, sizeof(state.if_bytes));
24894         /* register the C keywords */
24895         register_keywords(&state);
24896         /* register the keywords the macro preprocessor knows */
24897         register_macro_keywords(&state);
24898         /* generate some builtin macros */
24899         register_builtin_macros(&state);
24900         /* Memorize where some special keywords are. */
24901         state.i_switch        = lookup(&state, "switch", 6);
24902         state.i_case          = lookup(&state, "case", 4);
24903         state.i_continue      = lookup(&state, "continue", 8);
24904         state.i_break         = lookup(&state, "break", 5);
24905         state.i_default       = lookup(&state, "default", 7);
24906         state.i_return        = lookup(&state, "return", 6);
24907         /* Memorize where predefined macros are. */
24908         state.i_defined       = lookup(&state, "defined", 7);
24909         state.i___VA_ARGS__   = lookup(&state, "__VA_ARGS__", 11);
24910         state.i___FILE__      = lookup(&state, "__FILE__", 8);
24911         state.i___LINE__      = lookup(&state, "__LINE__", 8);
24912         /* Memorize where predefined identifiers are. */
24913         state.i___func__      = lookup(&state, "__func__", 8);
24914         /* Memorize where some attribute keywords are. */
24915         state.i_noinline      = lookup(&state, "noinline", 8);
24916         state.i_always_inline = lookup(&state, "always_inline", 13);
24917
24918         /* Process the command line macros */
24919         process_cmdline_macros(&state);
24920
24921         /* Allocate beginning bounding labels for the function list */
24922         state.first = label(&state);
24923         state.first->id |= TRIPLE_FLAG_VOLATILE;
24924         use_triple(state.first, state.first);
24925         ptr = label(&state);
24926         ptr->id |= TRIPLE_FLAG_VOLATILE;
24927         use_triple(ptr, ptr);
24928         flatten(&state, state.first, ptr);
24929
24930         /* Allocate a label for the pool of global variables */
24931         state.global_pool = label(&state);
24932         state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
24933         flatten(&state, state.first, state.global_pool);
24934
24935         /* Enter the globl definition scope */
24936         start_scope(&state);
24937         register_builtins(&state);
24938         compile_file(&state, filename, 1);
24939
24940         /* Stop if all we want is preprocessor output */
24941         if (state.compiler->flags & COMPILER_CPP_ONLY) {
24942                 print_preprocessed_tokens(&state);
24943                 return;
24944         }
24945
24946         decls(&state);
24947
24948         /* Exit the global definition scope */
24949         end_scope(&state);
24950
24951         /* Now that basic compilation has happened 
24952          * optimize the intermediate code 
24953          */
24954         optimize(&state);
24955
24956         generate_code(&state);
24957         if (state.compiler->debug) {
24958                 fprintf(state.errout, "done\n");
24959         }
24960         exit_state = 0;
24961 }
24962
24963 static void version(FILE *fp)
24964 {
24965         fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
24966 }
24967
24968 static void usage(void)
24969 {
24970         FILE *fp = stdout;
24971         version(fp);
24972         fprintf(fp,
24973                 "\nUsage: romcc [options] <source>.c\n"
24974                 "Compile a C source file generating a binary that does not implicilty use RAM\n"
24975                 "Options: \n"
24976                 "-o <output file name>\n"
24977                 "-f<option>            Specify a generic compiler option\n"
24978                 "-m<option>            Specify a arch dependent option\n"
24979                 "--                    Specify this is the last option\n"
24980                 "\nGeneric compiler options:\n"
24981         );
24982         compiler_usage(fp);
24983         fprintf(fp,
24984                 "\nArchitecture compiler options:\n"
24985         );
24986         arch_usage(fp);
24987         fprintf(fp,
24988                 "\n"
24989         );
24990 }
24991
24992 static void arg_error(char *fmt, ...)
24993 {
24994         va_list args;
24995         va_start(args, fmt);
24996         vfprintf(stderr, fmt, args);
24997         va_end(args);
24998         usage();
24999         exit(1);
25000 }
25001
25002 int main(int argc, char **argv)
25003 {
25004         const char *filename;
25005         struct compiler_state compiler;
25006         struct arch_state arch;
25007         int all_opts;
25008         
25009         
25010         /* I don't want any surprises */
25011         setlocale(LC_ALL, "C");
25012
25013         init_compiler_state(&compiler);
25014         init_arch_state(&arch);
25015         filename = 0;
25016         all_opts = 0;
25017         while(argc > 1) {
25018                 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
25019                         compiler.ofilename = argv[2];
25020                         argv += 2;
25021                         argc -= 2;
25022                 }
25023                 else if (!all_opts && argv[1][0] == '-') {
25024                         int result;
25025                         result = -1;
25026                         if (strcmp(argv[1], "--") == 0) {
25027                                 result = 0;
25028                                 all_opts = 1;
25029                         }
25030                         else if (strncmp(argv[1], "-E", 2) == 0) {
25031                                 result = compiler_encode_flag(&compiler, argv[1]);
25032                         }
25033                         else if (strncmp(argv[1], "-O", 2) == 0) {
25034                                 result = compiler_encode_flag(&compiler, argv[1]);
25035                         }
25036                         else if (strncmp(argv[1], "-I", 2) == 0) {
25037                                 result = compiler_encode_flag(&compiler, argv[1]);
25038                         }
25039                         else if (strncmp(argv[1], "-D", 2) == 0) {
25040                                 result = compiler_encode_flag(&compiler, argv[1]);
25041                         }
25042                         else if (strncmp(argv[1], "-U", 2) == 0) {
25043                                 result = compiler_encode_flag(&compiler, argv[1]);
25044                         }
25045                         else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25046                                 result = compiler_encode_flag(&compiler, argv[1]+2);
25047                         }
25048                         else if (strncmp(argv[1], "-f", 2) == 0) {
25049                                 result = compiler_encode_flag(&compiler, argv[1]+2);
25050                         }
25051                         else if (strncmp(argv[1], "-m", 2) == 0) {
25052                                 result = arch_encode_flag(&arch, argv[1]+2);
25053                         }
25054                         if (result < 0) {
25055                                 arg_error("Invalid option specified: %s\n",
25056                                         argv[1]);
25057                         }
25058                         argv++;
25059                         argc--;
25060                 }
25061                 else {
25062                         if (filename) {
25063                                 arg_error("Only one filename may be specified\n");
25064                         }
25065                         filename = argv[1];
25066                         argv++;
25067                         argc--;
25068                 }
25069         }
25070         if (!filename) {
25071                 arg_error("No filename specified\n");
25072         }
25073         compile(filename, &compiler, &arch);
25074
25075         return 0;
25076 }