14 #define DEBUG_ERROR_MESSAGES 0
15 #define DEBUG_COLOR_GRAPH 0
17 #define DEBUG_CONSISTENCY 1
19 #warning "FIXME boundary cases with small types in larger registers"
20 #warning "FIXME give clear error messages about unused variables"
22 /* Control flow graph of a loop without goto.
33 * |\ GGG HHH | continue;
61 * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
62 * DFup(Z) = { Y <- DF(Z) | idom(Y) != X }
65 * [] == DFlocal(X) U DF(X)
68 * Dominator graph of the same nodes.
72 * BBB JJJ BBB: [ JJJ ] ( JJJ ) JJJ: [ ] ()
74 * CCC CCC: [ ] ( BBB, JJJ )
76 * DDD EEE DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
78 * FFF FFF: [ ] ( BBB )
80 * GGG HHH GGG: [ ] ( BBB ) HHH: [ BBB ] ()
85 * BBB and JJJ are definitely the dominance frontier.
86 * Where do I place phi functions and how do I make that decision.
89 static void die(char *fmt, ...)
94 vfprintf(stderr, fmt, args);
101 #define MALLOC_STRONG_DEBUG
102 static void *xmalloc(size_t size, const char *name)
107 die("Cannot malloc %ld bytes to hold %s: %s\n",
108 size + 0UL, name, strerror(errno));
113 static void *xcmalloc(size_t size, const char *name)
116 buf = xmalloc(size, name);
117 memset(buf, 0, size);
121 static void xfree(const void *ptr)
126 static char *xstrdup(const char *str)
131 new = xmalloc(len + 1, "xstrdup string");
132 memcpy(new, str, len);
137 static void xchdir(const char *path)
139 if (chdir(path) != 0) {
140 die("chdir to %s failed: %s\n",
141 path, strerror(errno));
145 static int exists(const char *dirname, const char *filename)
149 if (access(filename, O_RDONLY) < 0) {
150 if ((errno != EACCES) && (errno != EROFS)) {
158 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
162 off_t size, progress;
171 fd = open(filename, O_RDONLY);
173 die("Cannot open '%s' : %s\n",
174 filename, strerror(errno));
176 result = fstat(fd, &stats);
178 die("Cannot stat: %s: %s\n",
179 filename, strerror(errno));
181 size = stats.st_size;
183 buf = xmalloc(size +2, filename);
184 buf[size] = '\n'; /* Make certain the file is newline terminated */
185 buf[size+1] = '\0'; /* Null terminate the file for good measure */
187 while(progress < size) {
188 result = read(fd, buf + progress, size - progress);
190 if ((errno == EINTR) || (errno == EAGAIN))
192 die("read on %s of %ld bytes failed: %s\n",
193 filename, (size - progress)+ 0UL, strerror(errno));
199 die("Close of %s failed: %s\n",
200 filename, strerror(errno));
205 /* Long on the destination platform */
206 typedef unsigned long ulong_t;
210 struct file_state *prev;
211 const char *basename;
219 const char *report_name;
220 const char *report_dir;
225 struct hash_entry *ident;
233 /* I have two classes of types:
235 * Logical types. (The type the C standard says the operation is of)
237 * The operational types are:
252 * No memory is useable by the compiler.
253 * There is no floating point support.
254 * All operations take place in general purpose registers.
255 * There is one type of general purpose register.
256 * Unsigned longs are stored in that general purpose register.
259 /* Operations on general purpose registers.
276 #define OP_POS 14 /* Dummy positive operator don't use it */
286 #define OP_SLESSEQ 26
287 #define OP_ULESSEQ 27
288 #define OP_SMOREEQ 28
289 #define OP_UMOREEQ 29
291 #define OP_LFALSE 30 /* Test if the expression is logically false */
292 #define OP_LTRUE 31 /* Test if the expression is logcially true */
299 #define OP_MIN_CONST 50
300 #define OP_MAX_CONST 59
301 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
302 #define OP_INTCONST 50
303 #define OP_BLOBCONST 51
304 /* For OP_BLOBCONST ->type holds the layout and size
305 * information. u.blob holds a pointer to the raw binary
306 * data for the constant initializer.
308 #define OP_ADDRCONST 52
309 /* For OP_ADDRCONST ->type holds the type.
310 * MISC(0) holds the reference to the static variable.
311 * ->u.cval holds an offset from that value.
315 /* OP_WRITE moves one pseudo register to another.
316 * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
317 * RHS(0) holds the psuedo to move.
321 /* OP_READ reads the value of a variable and makes
322 * it available for the pseudo operation.
323 * Useful for things like def-use chains.
324 * RHS(0) holds points to the triple to read from.
327 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
330 /* OP_PIECE returns one piece of a instruction that returns a structure.
331 * MISC(0) is the instruction
332 * u.cval is the LHS piece of the instruction to return.
335 /* OP_ASM holds a sequence of assembly instructions, the result
336 * of a C asm directive.
337 * RHS(x) holds input value x to the assembly sequence.
338 * LHS(x) holds the output value x from the assembly sequence.
339 * u.blob holds the string of assembly instructions.
343 /* OP_DEREF generates an lvalue from a pointer.
344 * RHS(0) holds the pointer value.
345 * OP_DEREF serves as a place holder to indicate all necessary
346 * checks have been done to indicate a value is an lvalue.
349 /* OP_DOT references a submember of a structure lvalue.
350 * RHS(0) holds the lvalue.
351 * ->u.field holds the name of the field we want.
353 * Not seen outside of expressions.
356 /* OP_VAL returns the value of a subexpression of the current expression.
357 * Useful for operators that have side effects.
358 * RHS(0) holds the expression.
359 * MISC(0) holds the subexpression of RHS(0) that is the
360 * value of the expression.
362 * Not seen outside of expressions.
365 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
366 * Not seen outside of expressions.
369 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
370 * Not seen outside of expressions.
373 /* OP_CODE performas a C ? : operation.
374 * RHS(0) holds the test.
375 * RHS(1) holds the expression to evaluate if the test returns true.
376 * RHS(2) holds the expression to evaluate if the test returns false.
377 * Not seen outside of expressions.
380 /* OP_COMMA performacs a C comma operation.
381 * That is RHS(0) is evaluated, then RHS(1)
382 * and the value of RHS(1) is returned.
383 * Not seen outside of expressions.
387 /* OP_CALL performs a procedure call.
388 * MISC(0) holds a pointer to the OP_LIST of a function
389 * RHS(x) holds argument x of a function
391 * Currently not seen outside of expressions.
393 #define OP_VAL_VEC 74
394 /* OP_VAL_VEC is an array of triples that are either variable
395 * or values for a structure or an array.
396 * RHS(x) holds element x of the vector.
397 * triple->type->elements holds the size of the vector.
402 /* OP_LIST Holds a list of statements, and a result value.
403 * RHS(0) holds the list of statements.
404 * MISC(0) holds the value of the statements.
407 #define OP_BRANCH 81 /* branch */
408 /* For branch instructions
409 * TARG(0) holds the branch target.
410 * RHS(0) if present holds the branch condition.
411 * ->next holds where to branch to if the branch is not taken.
412 * The branch target can only be a decl...
416 /* OP_LABEL is a triple that establishes an target for branches.
417 * ->use is the list of all branches that use this label.
421 /* OP_DECL is a triple that establishes an lvalue for assignments.
422 * ->use is a list of statements that use the variable.
426 /* OP_SDECL is a triple that establishes a variable of static
428 * ->use is a list of statements that use the variable.
429 * MISC(0) holds the initializer expression.
434 /* OP_PHI is a triple used in SSA form code.
435 * It is used when multiple code paths merge and a variable needs
436 * a single assignment from any of those code paths.
437 * The operation is a cross between OP_DECL and OP_WRITE, which
438 * is what OP_PHI is geneared from.
440 * RHS(x) points to the value from code path x
441 * The number of RHS entries is the number of control paths into the block
442 * in which OP_PHI resides. The elements of the array point to point
443 * to the variables OP_PHI is derived from.
445 * MISC(0) holds a pointer to the orginal OP_DECL node.
448 /* Architecture specific instructions */
451 #define OP_SET_EQ 102
452 #define OP_SET_NOTEQ 103
453 #define OP_SET_SLESS 104
454 #define OP_SET_ULESS 105
455 #define OP_SET_SMORE 106
456 #define OP_SET_UMORE 107
457 #define OP_SET_SLESSEQ 108
458 #define OP_SET_ULESSEQ 109
459 #define OP_SET_SMOREEQ 110
460 #define OP_SET_UMOREEQ 111
463 #define OP_JMP_EQ 113
464 #define OP_JMP_NOTEQ 114
465 #define OP_JMP_SLESS 115
466 #define OP_JMP_ULESS 116
467 #define OP_JMP_SMORE 117
468 #define OP_JMP_UMORE 118
469 #define OP_JMP_SLESSEQ 119
470 #define OP_JMP_ULESSEQ 120
471 #define OP_JMP_SMOREEQ 121
472 #define OP_JMP_UMOREEQ 122
474 /* Builtin operators that it is just simpler to use the compiler for */
492 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
494 #define BLOCK 8 /* Triple stores the current block */
495 unsigned char lhs, rhs, misc, targ;
498 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
506 static const struct op_info table_ops[] = {
507 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
508 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
509 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
510 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
511 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
512 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
513 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
514 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
515 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
516 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
517 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
518 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
519 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
520 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
521 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
522 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
523 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
525 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
526 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
527 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
528 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
529 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
530 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
531 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
532 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
533 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
534 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
535 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
536 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
538 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "load"),
539 [OP_STORE ] = OP( 1, 1, 0, 0, IMPURE | BLOCK , "store"),
541 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK, "noop"),
543 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
544 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
545 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
547 [OP_WRITE ] = OP( 1, 1, 0, 0, PURE | BLOCK, "write"),
548 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
549 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
550 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF, "piece"),
551 [OP_ASM ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
552 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
553 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "dot"),
555 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
556 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "land"),
557 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "lor"),
558 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF | BLOCK, "cond"),
559 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "comma"),
560 /* Call is special most it can stand in for anything so it depends on context */
561 [OP_CALL ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
562 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
563 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
565 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
566 /* The number of targets for OP_BRANCH depends on context */
567 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
568 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "label"),
569 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "adecl"),
570 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK, "sdecl"),
571 /* The number of RHS elements of OP_PHI depend upon context */
572 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
574 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
575 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
576 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
577 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
578 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
579 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
580 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
581 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
582 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
583 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
584 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
585 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
586 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK, "jmp"),
587 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_eq"),
588 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_noteq"),
589 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_sless"),
590 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_uless"),
591 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smore"),
592 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umore"),
593 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
594 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
595 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
596 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
598 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
599 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
600 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
601 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
602 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
603 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
604 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
605 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
606 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
607 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
608 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
611 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
613 static const char *tops(int index)
615 static const char unknown[] = "unknown op";
619 if (index > OP_MAX) {
622 return table_ops[index].name;
629 struct triple_set *next;
630 struct triple *member;
640 const char *filename;
641 const char *function;
644 struct occurance *parent;
647 struct triple *next, *prev;
648 struct triple_set *use;
651 unsigned char template_id;
652 unsigned short sizes;
653 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
654 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0x0f)
655 #define TRIPLE_MISC(SIZES) (((SIZES) >> 8) & 0x0f)
656 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
657 #define TRIPLE_SIZE(SIZES) \
658 ((((SIZES) >> 0) & 0x0f) + \
659 (((SIZES) >> 4) & 0x0f) + \
660 (((SIZES) >> 8) & 0x0f) + \
661 (((SIZES) >> 12) & 0x0f))
662 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
663 ((((LHS) & 0x0f) << 0) | \
664 (((RHS) & 0x0f) << 4) | \
665 (((MISC) & 0x0f) << 8) | \
666 (((TARG) & 0x0f) << 12))
667 #define TRIPLE_LHS_OFF(SIZES) (0)
668 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
669 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
670 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
671 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
672 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
673 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
674 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
675 unsigned id; /* A scratch value and finally the register */
676 #define TRIPLE_FLAG_FLATTENED (1 << 31)
677 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
678 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
679 struct occurance *occurance;
684 struct hash_entry *field;
685 struct asm_info *ainfo;
687 struct triple *param[2];
694 struct ins_template {
695 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
699 struct ins_template tmpl;
704 struct block_set *next;
705 struct block *member;
708 struct block *work_next;
709 struct block *left, *right;
710 struct triple *first, *last;
712 struct block_set *use;
713 struct block_set *idominates;
714 struct block_set *domfrontier;
716 struct block_set *ipdominates;
717 struct block_set *ipdomfrontier;
725 struct hash_entry *ident;
732 struct hash_entry *ident;
738 struct hash_entry *next;
742 struct macro *sym_define;
743 struct symbol *sym_label;
744 struct symbol *sym_struct;
745 struct symbol *sym_ident;
748 #define HASH_TABLE_SIZE 2048
750 struct compile_state {
751 const char *label_prefix;
752 const char *ofilename;
755 struct file_state *file;
756 struct occurance *last_occurance;
757 const char *function;
758 struct token token[4];
759 struct hash_entry *hash_table[HASH_TABLE_SIZE];
760 struct hash_entry *i_continue;
761 struct hash_entry *i_break;
763 int if_depth, if_value;
765 struct file_state *macro_file;
766 struct triple *main_function;
767 struct block *first_block, *last_block;
774 /* visibility global/local */
775 /* static/auto duration */
776 /* typedef, register, inline */
778 #define STOR_MASK 0x000f
780 #define STOR_GLOBAL 0x0001
782 #define STOR_PERM 0x0002
783 /* Storage specifiers */
784 #define STOR_AUTO 0x0000
785 #define STOR_STATIC 0x0002
786 #define STOR_EXTERN 0x0003
787 #define STOR_REGISTER 0x0004
788 #define STOR_TYPEDEF 0x0008
789 #define STOR_INLINE 0x000c
792 #define QUAL_MASK 0x0070
793 #define QUAL_NONE 0x0000
794 #define QUAL_CONST 0x0010
795 #define QUAL_VOLATILE 0x0020
796 #define QUAL_RESTRICT 0x0040
799 #define TYPE_MASK 0x1f00
800 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
801 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
802 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
803 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
804 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
805 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
806 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
807 #define TYPE_DEFAULT 0x0000
808 #define TYPE_VOID 0x0100
809 #define TYPE_CHAR 0x0200
810 #define TYPE_UCHAR 0x0300
811 #define TYPE_SHORT 0x0400
812 #define TYPE_USHORT 0x0500
813 #define TYPE_INT 0x0600
814 #define TYPE_UINT 0x0700
815 #define TYPE_LONG 0x0800
816 #define TYPE_ULONG 0x0900
817 #define TYPE_LLONG 0x0a00 /* long long */
818 #define TYPE_ULLONG 0x0b00
819 #define TYPE_FLOAT 0x0c00
820 #define TYPE_DOUBLE 0x0d00
821 #define TYPE_LDOUBLE 0x0e00 /* long double */
822 #define TYPE_STRUCT 0x1000
823 #define TYPE_ENUM 0x1100
824 #define TYPE_POINTER 0x1200
826 * type->left holds the type pointed to.
828 #define TYPE_FUNCTION 0x1300
829 /* For TYPE_FUNCTION:
830 * type->left holds the return type.
831 * type->right holds the...
833 #define TYPE_PRODUCT 0x1400
834 /* TYPE_PRODUCT is a basic building block when defining structures
835 * type->left holds the type that appears first in memory.
836 * type->right holds the type that appears next in memory.
838 #define TYPE_OVERLAP 0x1500
839 /* TYPE_OVERLAP is a basic building block when defining unions
840 * type->left and type->right holds to types that overlap
841 * each other in memory.
843 #define TYPE_ARRAY 0x1600
844 /* TYPE_ARRAY is a basic building block when definitng arrays.
845 * type->left holds the type we are an array of.
846 * type-> holds the number of elements.
849 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
853 struct type *left, *right;
855 struct hash_entry *field_ident;
856 struct hash_entry *type_ident;
859 #define MAX_REGISTERS 75
860 #define MAX_REG_EQUIVS 16
862 #define REGISTER_BITS 16
864 #define REGISTER_BITS 28
866 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
867 #define TEMPLATE_BITS 6
868 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
871 #define REG_UNNEEDED 1
872 #define REG_VIRT0 (MAX_REGISTERS + 0)
873 #define REG_VIRT1 (MAX_REGISTERS + 1)
874 #define REG_VIRT2 (MAX_REGISTERS + 2)
875 #define REG_VIRT3 (MAX_REGISTERS + 3)
876 #define REG_VIRT4 (MAX_REGISTERS + 4)
877 #define REG_VIRT5 (MAX_REGISTERS + 5)
878 #define REG_VIRT6 (MAX_REGISTERS + 5)
879 #define REG_VIRT7 (MAX_REGISTERS + 5)
880 #define REG_VIRT8 (MAX_REGISTERS + 5)
881 #define REG_VIRT9 (MAX_REGISTERS + 5)
883 /* Provision for 8 register classes */
886 #define REGC_SHIFT REGISTER_BITS
887 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
888 #define REG_MASK (MAX_VIRT_REGISTERS -1)
889 #define ID_REG(ID) ((ID) & REG_MASK)
890 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
891 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
892 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
893 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
894 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
896 #define REG_MASK (MAX_VIRT_REGISTERS -1)
897 #define ID_REG(ID) ((ID) & REG_MASK)
898 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
901 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
902 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
903 static void arch_reg_equivs(
904 struct compile_state *state, unsigned *equiv, int reg);
905 static int arch_select_free_register(
906 struct compile_state *state, char *used, int classes);
907 static unsigned arch_regc_size(struct compile_state *state, int class);
908 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
909 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
910 static const char *arch_reg_str(int reg);
911 static struct reg_info arch_reg_constraint(
912 struct compile_state *state, struct type *type, const char *constraint);
913 static struct reg_info arch_reg_clobber(
914 struct compile_state *state, const char *clobber);
915 static struct reg_info arch_reg_lhs(struct compile_state *state,
916 struct triple *ins, int index);
917 static struct reg_info arch_reg_rhs(struct compile_state *state,
918 struct triple *ins, int index);
919 static struct triple *transform_to_arch_instruction(
920 struct compile_state *state, struct triple *ins);
924 #define DEBUG_ABORT_ON_ERROR 0x0001
925 #define DEBUG_INTERMEDIATE_CODE 0x0002
926 #define DEBUG_CONTROL_FLOW 0x0004
927 #define DEBUG_BASIC_BLOCKS 0x0008
928 #define DEBUG_FDOMINATORS 0x0010
929 #define DEBUG_RDOMINATORS 0x0020
930 #define DEBUG_TRIPLES 0x0040
931 #define DEBUG_INTERFERENCE 0x0080
932 #define DEBUG_ARCH_CODE 0x0100
933 #define DEBUG_CODE_ELIMINATION 0x0200
934 #define DEBUG_INSERTED_COPIES 0x0400
936 #define GLOBAL_SCOPE_DEPTH 1
938 static void compile_file(struct compile_state *old_state, const char *filename, int local);
940 static void do_cleanup(struct compile_state *state)
943 fclose(state->output);
944 unlink(state->ofilename);
948 static int get_col(struct file_state *file)
952 ptr = file->line_start;
954 for(col = 0; ptr < end; ptr++) {
959 col = (col & ~7) + 8;
965 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
969 fprintf(fp, "%s:%d.%d: ",
970 triple->occurance->filename,
971 triple->occurance->line,
972 triple->occurance->col);
978 col = get_col(state->file);
979 fprintf(fp, "%s:%d.%d: ",
980 state->file->report_name, state->file->report_line, col);
983 static void __internal_error(struct compile_state *state, struct triple *ptr,
988 loc(stderr, state, ptr);
990 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
992 fprintf(stderr, "Internal compiler error: ");
993 vfprintf(stderr, fmt, args);
994 fprintf(stderr, "\n");
1001 static void __internal_warning(struct compile_state *state, struct triple *ptr,
1005 va_start(args, fmt);
1006 loc(stderr, state, ptr);
1007 fprintf(stderr, "Internal compiler warning: ");
1008 vfprintf(stderr, fmt, args);
1009 fprintf(stderr, "\n");
1015 static void __error(struct compile_state *state, struct triple *ptr,
1019 va_start(args, fmt);
1020 loc(stderr, state, ptr);
1021 vfprintf(stderr, fmt, args);
1023 fprintf(stderr, "\n");
1025 if (state->debug & DEBUG_ABORT_ON_ERROR) {
1031 static void __warning(struct compile_state *state, struct triple *ptr,
1035 va_start(args, fmt);
1036 loc(stderr, state, ptr);
1037 fprintf(stderr, "warning: ");
1038 vfprintf(stderr, fmt, args);
1039 fprintf(stderr, "\n");
1043 #if DEBUG_ERROR_MESSAGES
1044 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1045 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1046 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1047 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1049 # define internal_error __internal_error
1050 # define internal_warning __internal_warning
1051 # define error __error
1052 # define warning __warning
1054 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1056 static void valid_op(struct compile_state *state, int op)
1058 char *fmt = "invalid op: %d";
1060 internal_error(state, 0, fmt, op);
1063 internal_error(state, 0, fmt, op);
1067 static void valid_ins(struct compile_state *state, struct triple *ptr)
1069 valid_op(state, ptr->op);
1072 static void process_trigraphs(struct compile_state *state)
1074 char *src, *dest, *end;
1075 struct file_state *file;
1077 src = dest = file->buf;
1078 end = file->buf + file->size;
1079 while((end - src) >= 3) {
1080 if ((src[0] == '?') && (src[1] == '?')) {
1083 case '=': c = '#'; break;
1084 case '/': c = '\\'; break;
1085 case '\'': c = '^'; break;
1086 case '(': c = '['; break;
1087 case ')': c = ']'; break;
1088 case '!': c = '!'; break;
1089 case '<': c = '{'; break;
1090 case '>': c = '}'; break;
1091 case '-': c = '~'; break;
1108 file->size = dest - file->buf;
1111 static void splice_lines(struct compile_state *state)
1113 char *src, *dest, *end;
1114 struct file_state *file;
1116 src = dest = file->buf;
1117 end = file->buf + file->size;
1118 while((end - src) >= 2) {
1119 if ((src[0] == '\\') && (src[1] == '\n')) {
1129 file->size = dest - file->buf;
1132 static struct type void_type;
1133 static void use_triple(struct triple *used, struct triple *user)
1135 struct triple_set **ptr, *new;
1142 if ((*ptr)->member == user) {
1145 ptr = &(*ptr)->next;
1147 /* Append new to the head of the list,
1148 * copy_func and rename_block_variables
1151 new = xcmalloc(sizeof(*new), "triple_set");
1153 new->next = used->use;
1157 static void unuse_triple(struct triple *used, struct triple *unuser)
1159 struct triple_set *use, **ptr;
1166 if (use->member == unuser) {
1176 static void push_triple(struct triple *used, struct triple *user)
1178 struct triple_set *new;
1183 /* Append new to the head of the list,
1184 * it's the only sensible behavoir for a stack.
1186 new = xcmalloc(sizeof(*new), "triple_set");
1188 new->next = used->use;
1192 static void pop_triple(struct triple *used, struct triple *unuser)
1194 struct triple_set *use, **ptr;
1198 if (use->member == unuser) {
1201 /* Only free one occurance from the stack */
1210 static void put_occurance(struct occurance *occurance)
1212 occurance->count -= 1;
1213 if (occurance->count <= 0) {
1214 if (occurance->parent) {
1215 put_occurance(occurance->parent);
1221 static void get_occurance(struct occurance *occurance)
1223 occurance->count += 1;
1227 static struct occurance *new_occurance(struct compile_state *state)
1229 struct occurance *result, *last;
1230 const char *filename;
1231 const char *function;
1239 filename = state->file->report_name;
1240 line = state->file->report_line;
1241 col = get_col(state->file);
1243 if (state->function) {
1244 function = state->function;
1246 last = state->last_occurance;
1248 (last->col == col) &&
1249 (last->line == line) &&
1250 (last->function == function) &&
1251 (strcmp(last->filename, filename) == 0)) {
1252 get_occurance(last);
1256 state->last_occurance = 0;
1257 put_occurance(last);
1259 result = xmalloc(sizeof(*result), "occurance");
1261 result->filename = filename;
1262 result->function = function;
1263 result->line = line;
1266 state->last_occurance = result;
1270 static struct occurance *inline_occurance(struct compile_state *state,
1271 struct occurance *new, struct occurance *orig)
1273 struct occurance *result, *last;
1274 last = state->last_occurance;
1276 (last->parent == orig) &&
1277 (last->col == new->col) &&
1278 (last->line == new->line) &&
1279 (last->function == new->function) &&
1280 (last->filename == new->filename)) {
1281 get_occurance(last);
1285 state->last_occurance = 0;
1286 put_occurance(last);
1288 get_occurance(orig);
1289 result = xmalloc(sizeof(*result), "occurance");
1291 result->filename = new->filename;
1292 result->function = new->function;
1293 result->line = new->line;
1294 result->col = new->col;
1295 result->parent = orig;
1296 state->last_occurance = result;
1301 static struct occurance dummy_occurance = {
1303 .filename = __FILE__,
1310 /* The zero triple is used as a place holder when we are removing pointers
1311 * from a triple. Having allows certain sanity checks to pass even
1312 * when the original triple that was pointed to is gone.
1314 static struct triple zero_triple = {
1315 .next = &zero_triple,
1316 .prev = &zero_triple,
1319 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1320 .id = -1, /* An invalid id */
1321 .u = { .cval = 0, },
1322 .occurance = &dummy_occurance,
1323 .param { [0] = 0, [1] = 0, },
1327 static unsigned short triple_sizes(struct compile_state *state,
1328 int op, struct type *type, int lhs_wanted, int rhs_wanted)
1330 int lhs, rhs, misc, targ;
1331 valid_op(state, op);
1332 lhs = table_ops[op].lhs;
1333 rhs = table_ops[op].rhs;
1334 misc = table_ops[op].misc;
1335 targ = table_ops[op].targ;
1338 if (op == OP_CALL) {
1341 param = type->right;
1342 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1344 param = param->right;
1346 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1350 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1351 lhs = type->left->elements;
1354 else if (op == OP_VAL_VEC) {
1355 rhs = type->elements;
1357 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1360 else if (op == OP_ASM) {
1364 if ((rhs < 0) || (rhs > MAX_RHS)) {
1365 internal_error(state, 0, "bad rhs");
1367 if ((lhs < 0) || (lhs > MAX_LHS)) {
1368 internal_error(state, 0, "bad lhs");
1370 if ((misc < 0) || (misc > MAX_MISC)) {
1371 internal_error(state, 0, "bad misc");
1373 if ((targ < 0) || (targ > MAX_TARG)) {
1374 internal_error(state, 0, "bad targs");
1376 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1379 static struct triple *alloc_triple(struct compile_state *state,
1380 int op, struct type *type, int lhs, int rhs,
1381 struct occurance *occurance)
1383 size_t size, sizes, extra_count, min_count;
1385 sizes = triple_sizes(state, op, type, lhs, rhs);
1387 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1388 extra_count = TRIPLE_SIZE(sizes);
1389 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1391 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1392 ret = xcmalloc(size, "tripple");
1398 ret->occurance = occurance;
1402 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1405 int src_lhs, src_rhs, src_size;
1406 src_lhs = TRIPLE_LHS(src->sizes);
1407 src_rhs = TRIPLE_RHS(src->sizes);
1408 src_size = TRIPLE_SIZE(src->sizes);
1409 get_occurance(src->occurance);
1410 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1412 memcpy(dup, src, sizeof(*src));
1413 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1417 static struct triple *new_triple(struct compile_state *state,
1418 int op, struct type *type, int lhs, int rhs)
1421 struct occurance *occurance;
1422 occurance = new_occurance(state);
1423 ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1427 static struct triple *build_triple(struct compile_state *state,
1428 int op, struct type *type, struct triple *left, struct triple *right,
1429 struct occurance *occurance)
1433 ret = alloc_triple(state, op, type, -1, -1, occurance);
1434 count = TRIPLE_SIZE(ret->sizes);
1436 ret->param[0] = left;
1439 ret->param[1] = right;
1444 static struct triple *triple(struct compile_state *state,
1445 int op, struct type *type, struct triple *left, struct triple *right)
1449 ret = new_triple(state, op, type, -1, -1);
1450 count = TRIPLE_SIZE(ret->sizes);
1452 ret->param[0] = left;
1455 ret->param[1] = right;
1460 static struct triple *branch(struct compile_state *state,
1461 struct triple *targ, struct triple *test)
1464 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1468 TARG(ret, 0) = targ;
1469 /* record the branch target was used */
1470 if (!targ || (targ->op != OP_LABEL)) {
1471 internal_error(state, 0, "branch not to label");
1472 use_triple(targ, ret);
1478 static void insert_triple(struct compile_state *state,
1479 struct triple *first, struct triple *ptr)
1482 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1483 internal_error(state, ptr, "expression already used");
1486 ptr->prev = first->prev;
1487 ptr->prev->next = ptr;
1488 ptr->next->prev = ptr;
1489 if ((ptr->prev->op == OP_BRANCH) &&
1490 TRIPLE_RHS(ptr->prev->sizes)) {
1491 unuse_triple(first, ptr->prev);
1492 use_triple(ptr, ptr->prev);
1497 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1499 /* This function is used to determine if u.block
1500 * is utilized to store the current block number.
1503 valid_ins(state, ins);
1504 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1505 return stores_block;
1508 static struct block *block_of_triple(struct compile_state *state,
1511 struct triple *first;
1512 first = RHS(state->main_function, 0);
1513 while(ins != first && !triple_stores_block(state, ins)) {
1514 if (ins == ins->prev) {
1515 internal_error(state, 0, "ins == ins->prev?");
1519 if (!triple_stores_block(state, ins)) {
1520 internal_error(state, ins, "Cannot find block");
1522 return ins->u.block;
1525 static struct triple *pre_triple(struct compile_state *state,
1526 struct triple *base,
1527 int op, struct type *type, struct triple *left, struct triple *right)
1529 struct block *block;
1531 /* If I am an OP_PIECE jump to the real instruction */
1532 if (base->op == OP_PIECE) {
1533 base = MISC(base, 0);
1535 block = block_of_triple(state, base);
1536 get_occurance(base->occurance);
1537 ret = build_triple(state, op, type, left, right, base->occurance);
1538 if (triple_stores_block(state, ret)) {
1539 ret->u.block = block;
1541 insert_triple(state, base, ret);
1542 if (block->first == base) {
1548 static struct triple *post_triple(struct compile_state *state,
1549 struct triple *base,
1550 int op, struct type *type, struct triple *left, struct triple *right)
1552 struct block *block;
1555 /* If I am an OP_PIECE jump to the real instruction */
1556 if (base->op == OP_PIECE) {
1557 base = MISC(base, 0);
1559 /* If I have a left hand side skip over it */
1560 zlhs = TRIPLE_LHS(base->sizes);
1561 if (zlhs && (base->op != OP_WRITE) && (base->op != OP_STORE)) {
1562 base = LHS(base, zlhs - 1);
1565 block = block_of_triple(state, base);
1566 get_occurance(base->occurance);
1567 ret = build_triple(state, op, type, left, right, base->occurance);
1568 if (triple_stores_block(state, ret)) {
1569 ret->u.block = block;
1571 insert_triple(state, base->next, ret);
1572 if (block->last == base) {
1578 static struct triple *label(struct compile_state *state)
1580 /* Labels don't get a type */
1581 struct triple *result;
1582 result = triple(state, OP_LABEL, &void_type, 0, 0);
1586 static void display_triple(FILE *fp, struct triple *ins)
1588 struct occurance *ptr;
1592 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1595 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1598 reg = arch_reg_str(ID_REG(ins->id));
1599 if (ins->op == OP_INTCONST) {
1600 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx> ",
1601 ins, pre, post, reg, ins->template_id, tops(ins->op),
1604 else if (ins->op == OP_ADDRCONST) {
1605 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1606 ins, pre, post, reg, ins->template_id, tops(ins->op),
1607 MISC(ins, 0), ins->u.cval);
1611 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s",
1612 ins, pre, post, reg, ins->template_id, tops(ins->op));
1613 count = TRIPLE_SIZE(ins->sizes);
1614 for(i = 0; i < count; i++) {
1615 fprintf(fp, " %-10p", ins->param[i]);
1622 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1623 fprintf(fp, " %s,%s:%d.%d",
1633 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1635 /* Does the triple have no side effects.
1636 * I.e. Rexecuting the triple with the same arguments
1637 * gives the same value.
1640 valid_ins(state, ins);
1641 pure = PURE_BITS(table_ops[ins->op].flags);
1642 if ((pure != PURE) && (pure != IMPURE)) {
1643 internal_error(state, 0, "Purity of %s not known\n",
1646 return pure == PURE;
1649 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1651 /* This function is used to determine which triples need
1655 valid_ins(state, ins);
1656 is_branch = (table_ops[ins->op].targ != 0);
1660 static int triple_is_def(struct compile_state *state, struct triple *ins)
1662 /* This function is used to determine which triples need
1666 valid_ins(state, ins);
1667 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1671 static struct triple **triple_iter(struct compile_state *state,
1672 size_t count, struct triple **vector,
1673 struct triple *ins, struct triple **last)
1675 struct triple **ret;
1681 else if ((last >= vector) && (last < (vector + count - 1))) {
1689 static struct triple **triple_lhs(struct compile_state *state,
1690 struct triple *ins, struct triple **last)
1692 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1696 static struct triple **triple_rhs(struct compile_state *state,
1697 struct triple *ins, struct triple **last)
1699 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1703 static struct triple **triple_misc(struct compile_state *state,
1704 struct triple *ins, struct triple **last)
1706 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1710 static struct triple **triple_targ(struct compile_state *state,
1711 struct triple *ins, struct triple **last)
1714 struct triple **ret, **vector;
1716 count = TRIPLE_TARG(ins->sizes);
1717 vector = &TARG(ins, 0);
1722 else if ((last >= vector) && (last < (vector + count - 1))) {
1725 else if ((last == (vector + count - 1)) &&
1726 TRIPLE_RHS(ins->sizes)) {
1734 static void verify_use(struct compile_state *state,
1735 struct triple *user, struct triple *used)
1738 size = TRIPLE_SIZE(user->sizes);
1739 for(i = 0; i < size; i++) {
1740 if (user->param[i] == used) {
1744 if (triple_is_branch(state, user)) {
1745 if (user->next == used) {
1750 internal_error(state, user, "%s(%p) does not use %s(%p)",
1751 tops(user->op), user, tops(used->op), used);
1755 static int find_rhs_use(struct compile_state *state,
1756 struct triple *user, struct triple *used)
1758 struct triple **param;
1760 verify_use(state, user, used);
1761 size = TRIPLE_RHS(user->sizes);
1762 param = &RHS(user, 0);
1763 for(i = 0; i < size; i++) {
1764 if (param[i] == used) {
1771 static void free_triple(struct compile_state *state, struct triple *ptr)
1774 size = sizeof(*ptr) - sizeof(ptr->param) +
1775 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1776 ptr->prev->next = ptr->next;
1777 ptr->next->prev = ptr->prev;
1779 internal_error(state, ptr, "ptr->use != 0");
1781 put_occurance(ptr->occurance);
1782 memset(ptr, -1, size);
1786 static void release_triple(struct compile_state *state, struct triple *ptr)
1788 struct triple_set *set, *next;
1789 struct triple **expr;
1790 /* Remove ptr from use chains where it is the user */
1791 expr = triple_rhs(state, ptr, 0);
1792 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1794 unuse_triple(*expr, ptr);
1797 expr = triple_lhs(state, ptr, 0);
1798 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1800 unuse_triple(*expr, ptr);
1803 expr = triple_misc(state, ptr, 0);
1804 for(; expr; expr = triple_misc(state, ptr, expr)) {
1806 unuse_triple(*expr, ptr);
1809 expr = triple_targ(state, ptr, 0);
1810 for(; expr; expr = triple_targ(state, ptr, expr)) {
1812 unuse_triple(*expr, ptr);
1815 /* Reomve ptr from use chains where it is used */
1816 for(set = ptr->use; set; set = next) {
1818 expr = triple_rhs(state, set->member, 0);
1819 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1821 *expr = &zero_triple;
1824 expr = triple_lhs(state, set->member, 0);
1825 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1827 *expr = &zero_triple;
1830 expr = triple_misc(state, set->member, 0);
1831 for(; expr; expr = triple_misc(state, set->member, expr)) {
1833 *expr = &zero_triple;
1836 expr = triple_targ(state, set->member, 0);
1837 for(; expr; expr = triple_targ(state, set->member, expr)) {
1839 *expr = &zero_triple;
1842 unuse_triple(ptr, set->member);
1844 free_triple(state, ptr);
1847 static void print_triple(struct compile_state *state, struct triple *ptr);
1849 #define TOK_UNKNOWN 0
1852 #define TOK_LBRACE 3
1853 #define TOK_RBRACE 4
1857 #define TOK_LBRACKET 8
1858 #define TOK_RBRACKET 9
1859 #define TOK_LPAREN 10
1860 #define TOK_RPAREN 11
1865 #define TOK_TIMESEQ 16
1866 #define TOK_DIVEQ 17
1867 #define TOK_MODEQ 18
1868 #define TOK_PLUSEQ 19
1869 #define TOK_MINUSEQ 20
1872 #define TOK_ANDEQ 23
1873 #define TOK_XOREQ 24
1876 #define TOK_NOTEQ 27
1877 #define TOK_QUEST 28
1878 #define TOK_LOGOR 29
1879 #define TOK_LOGAND 30
1883 #define TOK_LESSEQ 34
1884 #define TOK_MOREEQ 35
1888 #define TOK_MINUS 39
1891 #define TOK_PLUSPLUS 42
1892 #define TOK_MINUSMINUS 43
1894 #define TOK_ARROW 45
1896 #define TOK_TILDE 47
1897 #define TOK_LIT_STRING 48
1898 #define TOK_LIT_CHAR 49
1899 #define TOK_LIT_INT 50
1900 #define TOK_LIT_FLOAT 51
1901 #define TOK_MACRO 52
1902 #define TOK_CONCATENATE 53
1904 #define TOK_IDENT 54
1905 #define TOK_STRUCT_NAME 55
1906 #define TOK_ENUM_CONST 56
1907 #define TOK_TYPE_NAME 57
1910 #define TOK_BREAK 59
1913 #define TOK_CONST 62
1914 #define TOK_CONTINUE 63
1915 #define TOK_DEFAULT 64
1917 #define TOK_DOUBLE 66
1920 #define TOK_EXTERN 69
1921 #define TOK_FLOAT 70
1925 #define TOK_INLINE 74
1928 #define TOK_REGISTER 77
1929 #define TOK_RESTRICT 78
1930 #define TOK_RETURN 79
1931 #define TOK_SHORT 80
1932 #define TOK_SIGNED 81
1933 #define TOK_SIZEOF 82
1934 #define TOK_STATIC 83
1935 #define TOK_STRUCT 84
1936 #define TOK_SWITCH 85
1937 #define TOK_TYPEDEF 86
1938 #define TOK_UNION 87
1939 #define TOK_UNSIGNED 88
1941 #define TOK_VOLATILE 90
1942 #define TOK_WHILE 91
1944 #define TOK_ATTRIBUTE 93
1945 #define TOK_ALIGNOF 94
1946 #define TOK_FIRST_KEYWORD TOK_AUTO
1947 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1949 #define TOK_DEFINE 100
1950 #define TOK_UNDEF 101
1951 #define TOK_INCLUDE 102
1952 #define TOK_LINE 103
1953 #define TOK_ERROR 104
1954 #define TOK_WARNING 105
1955 #define TOK_PRAGMA 106
1956 #define TOK_IFDEF 107
1957 #define TOK_IFNDEF 108
1958 #define TOK_ELIF 109
1959 #define TOK_ENDIF 110
1961 #define TOK_FIRST_MACRO TOK_DEFINE
1962 #define TOK_LAST_MACRO TOK_ENDIF
1966 static const char *tokens[] = {
1967 [TOK_UNKNOWN ] = "unknown",
1968 [TOK_SPACE ] = ":space:",
1970 [TOK_LBRACE ] = "{",
1971 [TOK_RBRACE ] = "}",
1975 [TOK_LBRACKET ] = "[",
1976 [TOK_RBRACKET ] = "]",
1977 [TOK_LPAREN ] = "(",
1978 [TOK_RPAREN ] = ")",
1980 [TOK_DOTS ] = "...",
1983 [TOK_TIMESEQ ] = "*=",
1984 [TOK_DIVEQ ] = "/=",
1985 [TOK_MODEQ ] = "%=",
1986 [TOK_PLUSEQ ] = "+=",
1987 [TOK_MINUSEQ ] = "-=",
1988 [TOK_SLEQ ] = "<<=",
1989 [TOK_SREQ ] = ">>=",
1990 [TOK_ANDEQ ] = "&=",
1991 [TOK_XOREQ ] = "^=",
1994 [TOK_NOTEQ ] = "!=",
1996 [TOK_LOGOR ] = "||",
1997 [TOK_LOGAND ] = "&&",
2001 [TOK_LESSEQ ] = "<=",
2002 [TOK_MOREEQ ] = ">=",
2009 [TOK_PLUSPLUS ] = "++",
2010 [TOK_MINUSMINUS ] = "--",
2012 [TOK_ARROW ] = "->",
2015 [TOK_LIT_STRING ] = ":string:",
2016 [TOK_IDENT ] = ":ident:",
2017 [TOK_TYPE_NAME ] = ":typename:",
2018 [TOK_LIT_CHAR ] = ":char:",
2019 [TOK_LIT_INT ] = ":integer:",
2020 [TOK_LIT_FLOAT ] = ":float:",
2022 [TOK_CONCATENATE ] = "##",
2024 [TOK_AUTO ] = "auto",
2025 [TOK_BREAK ] = "break",
2026 [TOK_CASE ] = "case",
2027 [TOK_CHAR ] = "char",
2028 [TOK_CONST ] = "const",
2029 [TOK_CONTINUE ] = "continue",
2030 [TOK_DEFAULT ] = "default",
2032 [TOK_DOUBLE ] = "double",
2033 [TOK_ELSE ] = "else",
2034 [TOK_ENUM ] = "enum",
2035 [TOK_EXTERN ] = "extern",
2036 [TOK_FLOAT ] = "float",
2038 [TOK_GOTO ] = "goto",
2040 [TOK_INLINE ] = "inline",
2042 [TOK_LONG ] = "long",
2043 [TOK_REGISTER ] = "register",
2044 [TOK_RESTRICT ] = "restrict",
2045 [TOK_RETURN ] = "return",
2046 [TOK_SHORT ] = "short",
2047 [TOK_SIGNED ] = "signed",
2048 [TOK_SIZEOF ] = "sizeof",
2049 [TOK_STATIC ] = "static",
2050 [TOK_STRUCT ] = "struct",
2051 [TOK_SWITCH ] = "switch",
2052 [TOK_TYPEDEF ] = "typedef",
2053 [TOK_UNION ] = "union",
2054 [TOK_UNSIGNED ] = "unsigned",
2055 [TOK_VOID ] = "void",
2056 [TOK_VOLATILE ] = "volatile",
2057 [TOK_WHILE ] = "while",
2059 [TOK_ATTRIBUTE ] = "__attribute__",
2060 [TOK_ALIGNOF ] = "__alignof__",
2062 [TOK_DEFINE ] = "define",
2063 [TOK_UNDEF ] = "undef",
2064 [TOK_INCLUDE ] = "include",
2065 [TOK_LINE ] = "line",
2066 [TOK_ERROR ] = "error",
2067 [TOK_WARNING ] = "warning",
2068 [TOK_PRAGMA ] = "pragma",
2069 [TOK_IFDEF ] = "ifdef",
2070 [TOK_IFNDEF ] = "ifndef",
2071 [TOK_ELIF ] = "elif",
2072 [TOK_ENDIF ] = "endif",
2077 static unsigned int hash(const char *str, int str_len)
2081 end = str + str_len;
2083 for(; str < end; str++) {
2084 hash = (hash *263) + *str;
2086 hash = hash & (HASH_TABLE_SIZE -1);
2090 static struct hash_entry *lookup(
2091 struct compile_state *state, const char *name, int name_len)
2093 struct hash_entry *entry;
2095 index = hash(name, name_len);
2096 entry = state->hash_table[index];
2098 ((entry->name_len != name_len) ||
2099 (memcmp(entry->name, name, name_len) != 0))) {
2100 entry = entry->next;
2104 /* Get a private copy of the name */
2105 new_name = xmalloc(name_len + 1, "hash_name");
2106 memcpy(new_name, name, name_len);
2107 new_name[name_len] = '\0';
2109 /* Create a new hash entry */
2110 entry = xcmalloc(sizeof(*entry), "hash_entry");
2111 entry->next = state->hash_table[index];
2112 entry->name = new_name;
2113 entry->name_len = name_len;
2115 /* Place the new entry in the hash table */
2116 state->hash_table[index] = entry;
2121 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2123 struct hash_entry *entry;
2125 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2126 (entry->tok == TOK_ENUM_CONST) ||
2127 ((entry->tok >= TOK_FIRST_KEYWORD) &&
2128 (entry->tok <= TOK_LAST_KEYWORD)))) {
2129 tk->tok = entry->tok;
2133 static void ident_to_macro(struct compile_state *state, struct token *tk)
2135 struct hash_entry *entry;
2138 (entry->tok >= TOK_FIRST_MACRO) &&
2139 (entry->tok <= TOK_LAST_MACRO)) {
2140 tk->tok = entry->tok;
2144 static void hash_keyword(
2145 struct compile_state *state, const char *keyword, int tok)
2147 struct hash_entry *entry;
2148 entry = lookup(state, keyword, strlen(keyword));
2149 if (entry && entry->tok != TOK_UNKNOWN) {
2150 die("keyword %s already hashed", keyword);
2156 struct compile_state *state, struct hash_entry *ident,
2157 struct symbol **chain, struct triple *def, struct type *type)
2160 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2161 error(state, 0, "%s already defined", ident->name);
2163 sym = xcmalloc(sizeof(*sym), "symbol");
2167 sym->scope_depth = state->scope_depth;
2172 static void start_scope(struct compile_state *state)
2174 state->scope_depth++;
2177 static void end_scope_syms(struct symbol **chain, int depth)
2179 struct symbol *sym, *next;
2181 while(sym && (sym->scope_depth == depth)) {
2189 static void end_scope(struct compile_state *state)
2193 /* Walk through the hash table and remove all symbols
2194 * in the current scope.
2196 depth = state->scope_depth;
2197 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2198 struct hash_entry *entry;
2199 entry = state->hash_table[i];
2201 end_scope_syms(&entry->sym_label, depth);
2202 end_scope_syms(&entry->sym_struct, depth);
2203 end_scope_syms(&entry->sym_ident, depth);
2204 entry = entry->next;
2207 state->scope_depth = depth - 1;
2210 static void register_keywords(struct compile_state *state)
2212 hash_keyword(state, "auto", TOK_AUTO);
2213 hash_keyword(state, "break", TOK_BREAK);
2214 hash_keyword(state, "case", TOK_CASE);
2215 hash_keyword(state, "char", TOK_CHAR);
2216 hash_keyword(state, "const", TOK_CONST);
2217 hash_keyword(state, "continue", TOK_CONTINUE);
2218 hash_keyword(state, "default", TOK_DEFAULT);
2219 hash_keyword(state, "do", TOK_DO);
2220 hash_keyword(state, "double", TOK_DOUBLE);
2221 hash_keyword(state, "else", TOK_ELSE);
2222 hash_keyword(state, "enum", TOK_ENUM);
2223 hash_keyword(state, "extern", TOK_EXTERN);
2224 hash_keyword(state, "float", TOK_FLOAT);
2225 hash_keyword(state, "for", TOK_FOR);
2226 hash_keyword(state, "goto", TOK_GOTO);
2227 hash_keyword(state, "if", TOK_IF);
2228 hash_keyword(state, "inline", TOK_INLINE);
2229 hash_keyword(state, "int", TOK_INT);
2230 hash_keyword(state, "long", TOK_LONG);
2231 hash_keyword(state, "register", TOK_REGISTER);
2232 hash_keyword(state, "restrict", TOK_RESTRICT);
2233 hash_keyword(state, "return", TOK_RETURN);
2234 hash_keyword(state, "short", TOK_SHORT);
2235 hash_keyword(state, "signed", TOK_SIGNED);
2236 hash_keyword(state, "sizeof", TOK_SIZEOF);
2237 hash_keyword(state, "static", TOK_STATIC);
2238 hash_keyword(state, "struct", TOK_STRUCT);
2239 hash_keyword(state, "switch", TOK_SWITCH);
2240 hash_keyword(state, "typedef", TOK_TYPEDEF);
2241 hash_keyword(state, "union", TOK_UNION);
2242 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2243 hash_keyword(state, "void", TOK_VOID);
2244 hash_keyword(state, "volatile", TOK_VOLATILE);
2245 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2246 hash_keyword(state, "while", TOK_WHILE);
2247 hash_keyword(state, "asm", TOK_ASM);
2248 hash_keyword(state, "__asm__", TOK_ASM);
2249 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2250 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2253 static void register_macro_keywords(struct compile_state *state)
2255 hash_keyword(state, "define", TOK_DEFINE);
2256 hash_keyword(state, "undef", TOK_UNDEF);
2257 hash_keyword(state, "include", TOK_INCLUDE);
2258 hash_keyword(state, "line", TOK_LINE);
2259 hash_keyword(state, "error", TOK_ERROR);
2260 hash_keyword(state, "warning", TOK_WARNING);
2261 hash_keyword(state, "pragma", TOK_PRAGMA);
2262 hash_keyword(state, "ifdef", TOK_IFDEF);
2263 hash_keyword(state, "ifndef", TOK_IFNDEF);
2264 hash_keyword(state, "elif", TOK_ELIF);
2265 hash_keyword(state, "endif", TOK_ENDIF);
2268 static int spacep(int c)
2284 static int digitp(int c)
2288 case '0': case '1': case '2': case '3': case '4':
2289 case '5': case '6': case '7': case '8': case '9':
2295 static int digval(int c)
2298 if ((c >= '0') && (c <= '9')) {
2304 static int hexdigitp(int c)
2308 case '0': case '1': case '2': case '3': case '4':
2309 case '5': case '6': case '7': case '8': case '9':
2310 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2311 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2317 static int hexdigval(int c)
2320 if ((c >= '0') && (c <= '9')) {
2323 else if ((c >= 'A') && (c <= 'F')) {
2324 val = 10 + (c - 'A');
2326 else if ((c >= 'a') && (c <= 'f')) {
2327 val = 10 + (c - 'a');
2332 static int octdigitp(int c)
2336 case '0': case '1': case '2': case '3':
2337 case '4': case '5': case '6': case '7':
2343 static int octdigval(int c)
2346 if ((c >= '0') && (c <= '7')) {
2352 static int letterp(int c)
2356 case 'a': case 'b': case 'c': case 'd': case 'e':
2357 case 'f': case 'g': case 'h': case 'i': case 'j':
2358 case 'k': case 'l': case 'm': case 'n': case 'o':
2359 case 'p': case 'q': case 'r': case 's': case 't':
2360 case 'u': case 'v': case 'w': case 'x': case 'y':
2362 case 'A': case 'B': case 'C': case 'D': case 'E':
2363 case 'F': case 'G': case 'H': case 'I': case 'J':
2364 case 'K': case 'L': case 'M': case 'N': case 'O':
2365 case 'P': case 'Q': case 'R': case 'S': case 'T':
2366 case 'U': case 'V': case 'W': case 'X': case 'Y':
2375 static int char_value(struct compile_state *state,
2376 const signed char **strp, const signed char *end)
2378 const signed char *str;
2382 if ((c == '\\') && (str < end)) {
2384 case 'n': c = '\n'; str++; break;
2385 case 't': c = '\t'; str++; break;
2386 case 'v': c = '\v'; str++; break;
2387 case 'b': c = '\b'; str++; break;
2388 case 'r': c = '\r'; str++; break;
2389 case 'f': c = '\f'; str++; break;
2390 case 'a': c = '\a'; str++; break;
2391 case '\\': c = '\\'; str++; break;
2392 case '?': c = '?'; str++; break;
2393 case '\'': c = '\''; str++; break;
2394 case '"': c = '"'; break;
2398 while((str < end) && hexdigitp(*str)) {
2400 c += hexdigval(*str);
2404 case '0': case '1': case '2': case '3':
2405 case '4': case '5': case '6': case '7':
2407 while((str < end) && octdigitp(*str)) {
2409 c += octdigval(*str);
2414 error(state, 0, "Invalid character constant");
2422 static char *after_digits(char *ptr, char *end)
2424 while((ptr < end) && digitp(*ptr)) {
2430 static char *after_octdigits(char *ptr, char *end)
2432 while((ptr < end) && octdigitp(*ptr)) {
2438 static char *after_hexdigits(char *ptr, char *end)
2440 while((ptr < end) && hexdigitp(*ptr)) {
2446 static void save_string(struct compile_state *state,
2447 struct token *tk, char *start, char *end, const char *id)
2451 /* Create a private copy of the string */
2452 str_len = end - start + 1;
2453 str = xmalloc(str_len + 1, id);
2454 memcpy(str, start, str_len);
2455 str[str_len] = '\0';
2457 /* Store the copy in the token */
2459 tk->str_len = str_len;
2461 static void next_token(struct compile_state *state, int index)
2463 struct file_state *file;
2471 tk = &state->token[index];
2474 token = tokp = file->pos;
2475 end = file->buf + file->size;
2482 if ((tokp + 1) < end) {
2486 if ((tokp + 2) < end) {
2490 if ((tokp + 3) < end) {
2498 else if (spacep(c)) {
2500 while ((tokp < end) && spacep(c)) {
2503 file->report_line++;
2504 file->line_start = tokp + 1;
2513 else if ((c == '/') && (c1 == '/')) {
2515 for(tokp += 2; tokp < end; tokp++) {
2519 file->report_line++;
2520 file->line_start = tokp +1;
2526 else if ((c == '/') && (c1 == '*')) {
2530 line_start = file->line_start;
2531 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2535 line_start = tokp +1;
2537 else if ((c == '*') && (tokp[1] == '/')) {
2543 if (tok == TOK_UNKNOWN) {
2544 error(state, 0, "unterminated comment");
2546 file->report_line += line - file->line;
2548 file->line_start = line_start;
2550 /* string constants */
2551 else if ((c == '"') ||
2552 ((c == 'L') && (c1 == '"'))) {
2557 line_start = file->line_start;
2563 for(tokp += 1; tokp < end; tokp++) {
2567 line_start = tokp + 1;
2569 else if ((c == '\\') && (tokp +1 < end)) {
2572 else if (c == '"') {
2573 tok = TOK_LIT_STRING;
2577 if (tok == TOK_UNKNOWN) {
2578 error(state, 0, "unterminated string constant");
2580 if (line != file->line) {
2581 warning(state, 0, "multiline string constant");
2583 file->report_line += line - file->line;
2585 file->line_start = line_start;
2587 /* Save the string value */
2588 save_string(state, tk, token, tokp, "literal string");
2590 /* character constants */
2591 else if ((c == '\'') ||
2592 ((c == 'L') && (c1 == '\''))) {
2597 line_start = file->line_start;
2603 for(tokp += 1; tokp < end; tokp++) {
2607 line_start = tokp + 1;
2609 else if ((c == '\\') && (tokp +1 < end)) {
2612 else if (c == '\'') {
2617 if (tok == TOK_UNKNOWN) {
2618 error(state, 0, "unterminated character constant");
2620 if (line != file->line) {
2621 warning(state, 0, "multiline character constant");
2623 file->report_line += line - file->line;
2625 file->line_start = line_start;
2627 /* Save the character value */
2628 save_string(state, tk, token, tokp, "literal character");
2630 /* integer and floating constants
2636 * Floating constants
2637 * {digits}.{digits}[Ee][+-]?{digits}
2639 * {digits}[Ee][+-]?{digits}
2640 * .{digits}[Ee][+-]?{digits}
2644 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2649 next = after_digits(tokp, end);
2654 if (next[0] == '.') {
2655 new = after_digits(next, end);
2656 is_float = (new != next);
2659 if ((next[0] == 'e') || (next[0] == 'E')) {
2660 if (((next + 1) < end) &&
2661 ((next[1] == '+') || (next[1] == '-'))) {
2664 new = after_digits(next, end);
2665 is_float = (new != next);
2669 tok = TOK_LIT_FLOAT;
2670 if ((next < end) && (
2679 if (!is_float && digitp(c)) {
2681 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2682 next = after_hexdigits(tokp + 2, end);
2684 else if (c == '0') {
2685 next = after_octdigits(tokp, end);
2688 next = after_digits(tokp, end);
2690 /* crazy integer suffixes */
2692 ((next[0] == 'u') || (next[0] == 'U'))) {
2695 ((next[0] == 'l') || (next[0] == 'L'))) {
2699 else if ((next < end) &&
2700 ((next[0] == 'l') || (next[0] == 'L'))) {
2703 ((next[0] == 'u') || (next[0] == 'U'))) {
2710 /* Save the integer/floating point value */
2711 save_string(state, tk, token, tokp, "literal number");
2714 else if (letterp(c)) {
2716 for(tokp += 1; tokp < end; tokp++) {
2718 if (!letterp(c) && !digitp(c)) {
2723 tk->ident = lookup(state, token, tokp +1 - token);
2725 /* C99 alternate macro characters */
2726 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2728 tok = TOK_CONCATENATE;
2730 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2731 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2732 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2733 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2734 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2735 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2736 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2737 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2738 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2739 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2740 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2741 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2742 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2743 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2744 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2745 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2746 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2747 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2748 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2749 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2750 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2751 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2752 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2753 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2754 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2755 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2756 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2757 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2758 else if (c == ';') { tok = TOK_SEMI; }
2759 else if (c == '{') { tok = TOK_LBRACE; }
2760 else if (c == '}') { tok = TOK_RBRACE; }
2761 else if (c == ',') { tok = TOK_COMMA; }
2762 else if (c == '=') { tok = TOK_EQ; }
2763 else if (c == ':') { tok = TOK_COLON; }
2764 else if (c == '[') { tok = TOK_LBRACKET; }
2765 else if (c == ']') { tok = TOK_RBRACKET; }
2766 else if (c == '(') { tok = TOK_LPAREN; }
2767 else if (c == ')') { tok = TOK_RPAREN; }
2768 else if (c == '*') { tok = TOK_STAR; }
2769 else if (c == '>') { tok = TOK_MORE; }
2770 else if (c == '<') { tok = TOK_LESS; }
2771 else if (c == '?') { tok = TOK_QUEST; }
2772 else if (c == '|') { tok = TOK_OR; }
2773 else if (c == '&') { tok = TOK_AND; }
2774 else if (c == '^') { tok = TOK_XOR; }
2775 else if (c == '+') { tok = TOK_PLUS; }
2776 else if (c == '-') { tok = TOK_MINUS; }
2777 else if (c == '/') { tok = TOK_DIV; }
2778 else if (c == '%') { tok = TOK_MOD; }
2779 else if (c == '!') { tok = TOK_BANG; }
2780 else if (c == '.') { tok = TOK_DOT; }
2781 else if (c == '~') { tok = TOK_TILDE; }
2782 else if (c == '#') { tok = TOK_MACRO; }
2783 if (tok == TOK_MACRO) {
2784 /* Only match preprocessor directives at the start of a line */
2786 for(ptr = file->line_start; spacep(*ptr); ptr++)
2792 if (tok == TOK_UNKNOWN) {
2793 error(state, 0, "unknown token");
2796 file->pos = tokp + 1;
2798 if (tok == TOK_IDENT) {
2799 ident_to_keyword(state, tk);
2801 /* Don't return space tokens. */
2802 if (tok == TOK_SPACE) {
2807 static void compile_macro(struct compile_state *state, struct token *tk)
2809 struct file_state *file;
2810 struct hash_entry *ident;
2812 file = xmalloc(sizeof(*file), "file_state");
2813 file->basename = xstrdup(tk->ident->name);
2814 file->dirname = xstrdup("");
2815 file->size = ident->sym_define->buf_len;
2816 file->buf = xmalloc(file->size +2, file->basename);
2817 memcpy(file->buf, ident->sym_define->buf, file->size);
2818 file->buf[file->size] = '\n';
2819 file->buf[file->size + 1] = '\0';
2820 file->pos = file->buf;
2821 file->line_start = file->pos;
2823 file->report_line = 1;
2824 file->report_name = file->basename;
2825 file->report_dir = file->dirname;
2826 file->prev = state->file;
2831 static int mpeek(struct compile_state *state, int index)
2835 tk = &state->token[index + 1];
2836 if (tk->tok == -1) {
2837 next_token(state, index + 1);
2841 if ((tk->tok == TOK_EOF) &&
2842 (state->file != state->macro_file) &&
2843 (state->file->prev)) {
2844 struct file_state *file = state->file;
2845 state->file = file->prev;
2846 /* file->basename is used keep it */
2847 if (file->report_dir != file->dirname) {
2848 xfree(file->report_dir);
2850 xfree(file->dirname);
2853 next_token(state, index + 1);
2856 else if (tk->ident && tk->ident->sym_define) {
2857 compile_macro(state, tk);
2858 next_token(state, index + 1);
2862 /* Don't show the token on the next line */
2863 if (state->macro_line < state->macro_file->line) {
2866 return state->token[index +1].tok;
2869 static void meat(struct compile_state *state, int index, int tok)
2873 next_tok = mpeek(state, index);
2874 if (next_tok != tok) {
2875 const char *name1, *name2;
2876 name1 = tokens[next_tok];
2878 if (next_tok == TOK_IDENT) {
2879 name2 = state->token[index + 1].ident->name;
2881 error(state, 0, "found %s %s expected %s",
2882 name1, name2, tokens[tok]);
2884 /* Free the old token value */
2885 if (state->token[index].str_len) {
2886 memset((void *)(state->token[index].val.str), -1,
2887 state->token[index].str_len);
2888 xfree(state->token[index].val.str);
2890 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2891 state->token[i] = state->token[i + 1];
2893 memset(&state->token[i], 0, sizeof(state->token[i]));
2894 state->token[i].tok = -1;
2897 static long_t mcexpr(struct compile_state *state, int index);
2899 static long_t mprimary_expr(struct compile_state *state, int index)
2903 tok = mpeek(state, index);
2904 while(state->token[index + 1].ident &&
2905 state->token[index + 1].ident->sym_define) {
2906 meat(state, index, tok);
2907 compile_macro(state, &state->token[index]);
2908 tok = mpeek(state, index);
2912 meat(state, index, TOK_LPAREN);
2913 val = mcexpr(state, index);
2914 meat(state, index, TOK_RPAREN);
2919 meat(state, index, TOK_LIT_INT);
2921 val = strtol(state->token[index].val.str, &end, 0);
2922 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2923 (errno == ERANGE)) {
2924 error(state, 0, "Integer constant to large");
2929 meat(state, index, TOK_LIT_INT);
2934 static long_t munary_expr(struct compile_state *state, int index)
2937 switch(mpeek(state, index)) {
2939 meat(state, index, TOK_PLUS);
2940 val = munary_expr(state, index);
2944 meat(state, index, TOK_MINUS);
2945 val = munary_expr(state, index);
2949 meat(state, index, TOK_BANG);
2950 val = munary_expr(state, index);
2954 meat(state, index, TOK_BANG);
2955 val = munary_expr(state, index);
2959 val = mprimary_expr(state, index);
2965 static long_t mmul_expr(struct compile_state *state, int index)
2969 val = munary_expr(state, index);
2973 switch(mpeek(state, index)) {
2975 meat(state, index, TOK_STAR);
2976 right = munary_expr(state, index);
2980 meat(state, index, TOK_DIV);
2981 right = munary_expr(state, index);
2985 meat(state, index, TOK_MOD);
2986 right = munary_expr(state, index);
2998 static long_t madd_expr(struct compile_state *state, int index)
3002 val = mmul_expr(state, index);
3006 switch(mpeek(state, index)) {
3008 meat(state, index, TOK_PLUS);
3009 right = mmul_expr(state, index);
3013 meat(state, index, TOK_MINUS);
3014 right = mmul_expr(state, index);
3026 static long_t mshift_expr(struct compile_state *state, int index)
3030 val = madd_expr(state, index);
3034 switch(mpeek(state, index)) {
3036 meat(state, index, TOK_SL);
3037 right = madd_expr(state, index);
3041 meat(state, index, TOK_SR);
3042 right = madd_expr(state, index);
3054 static long_t mrel_expr(struct compile_state *state, int index)
3058 val = mshift_expr(state, index);
3062 switch(mpeek(state, index)) {
3064 meat(state, index, TOK_LESS);
3065 right = mshift_expr(state, index);
3069 meat(state, index, TOK_MORE);
3070 right = mshift_expr(state, index);
3074 meat(state, index, TOK_LESSEQ);
3075 right = mshift_expr(state, index);
3079 meat(state, index, TOK_MOREEQ);
3080 right = mshift_expr(state, index);
3091 static long_t meq_expr(struct compile_state *state, int index)
3095 val = mrel_expr(state, index);
3099 switch(mpeek(state, index)) {
3101 meat(state, index, TOK_EQEQ);
3102 right = mrel_expr(state, index);
3106 meat(state, index, TOK_NOTEQ);
3107 right = mrel_expr(state, index);
3118 static long_t mand_expr(struct compile_state *state, int index)
3121 val = meq_expr(state, index);
3122 if (mpeek(state, index) == TOK_AND) {
3124 meat(state, index, TOK_AND);
3125 right = meq_expr(state, index);
3131 static long_t mxor_expr(struct compile_state *state, int index)
3134 val = mand_expr(state, index);
3135 if (mpeek(state, index) == TOK_XOR) {
3137 meat(state, index, TOK_XOR);
3138 right = mand_expr(state, index);
3144 static long_t mor_expr(struct compile_state *state, int index)
3147 val = mxor_expr(state, index);
3148 if (mpeek(state, index) == TOK_OR) {
3150 meat(state, index, TOK_OR);
3151 right = mxor_expr(state, index);
3157 static long_t mland_expr(struct compile_state *state, int index)
3160 val = mor_expr(state, index);
3161 if (mpeek(state, index) == TOK_LOGAND) {
3163 meat(state, index, TOK_LOGAND);
3164 right = mor_expr(state, index);
3169 static long_t mlor_expr(struct compile_state *state, int index)
3172 val = mland_expr(state, index);
3173 if (mpeek(state, index) == TOK_LOGOR) {
3175 meat(state, index, TOK_LOGOR);
3176 right = mland_expr(state, index);
3182 static long_t mcexpr(struct compile_state *state, int index)
3184 return mlor_expr(state, index);
3186 static void preprocess(struct compile_state *state, int index)
3188 /* Doing much more with the preprocessor would require
3189 * a parser and a major restructuring.
3190 * Postpone that for later.
3192 struct file_state *file;
3198 tk = &state->token[index];
3199 state->macro_line = line = file->line;
3200 state->macro_file = file;
3202 next_token(state, index);
3203 ident_to_macro(state, tk);
3204 if (tk->tok == TOK_IDENT) {
3205 error(state, 0, "undefined preprocessing directive `%s'",
3212 override_line = strtoul(tk->val.str, 0, 10);
3213 next_token(state, index);
3214 /* I have a cpp line marker parse it */
3215 if (tk->tok == TOK_LIT_STRING) {
3216 const char *token, *base;
3218 int name_len, dir_len;
3219 name = xmalloc(tk->str_len, "report_name");
3220 token = tk->val.str + 1;
3221 base = strrchr(token, '/');
3222 name_len = tk->str_len -2;
3224 dir_len = base - token;
3226 name_len -= base - token;
3231 memcpy(name, base, name_len);
3232 name[name_len] = '\0';
3233 dir = xmalloc(dir_len + 1, "report_dir");
3234 memcpy(dir, token, dir_len);
3235 dir[dir_len] = '\0';
3236 file->report_line = override_line - 1;
3237 file->report_name = name;
3238 file->report_dir = dir;
3243 meat(state, index, TOK_LINE);
3244 meat(state, index, TOK_LIT_INT);
3245 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3246 if (mpeek(state, index) == TOK_LIT_STRING) {
3247 const char *token, *base;
3249 int name_len, dir_len;
3250 meat(state, index, TOK_LIT_STRING);
3251 name = xmalloc(tk->str_len, "report_name");
3252 token = tk->val.str + 1;
3253 name_len = tk->str_len - 2;
3255 dir_len = base - token;
3257 name_len -= base - token;
3262 memcpy(name, base, name_len);
3263 name[name_len] = '\0';
3264 dir = xmalloc(dir_len + 1, "report_dir");
3265 memcpy(dir, token, dir_len);
3266 dir[dir_len] = '\0';
3267 file->report_name = name;
3268 file->report_dir = dir;
3273 if (state->if_value < 0) {
3276 warning(state, 0, "Ignoring preprocessor directive: %s",
3280 error(state, 0, "#elif not supported");
3281 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3282 if (state->if_depth == 0) {
3283 error(state, 0, "#elif without #if");
3285 /* If the #if was taken the #elif just disables the following code */
3286 if (state->if_value >= 0) {
3287 state->if_value = - state->if_value;
3289 /* If the previous #if was not taken see if the #elif enables the
3292 else if ((state->if_value < 0) &&
3293 (state->if_depth == - state->if_value))
3295 if (mcexpr(state, index) != 0) {
3296 state->if_value = state->if_depth;
3299 state->if_value = - state->if_depth;
3305 if (state->if_value < 0) {
3308 if (mcexpr(state, index) != 0) {
3309 state->if_value = state->if_depth;
3312 state->if_value = - state->if_depth;
3317 if (state->if_value < 0) {
3320 next_token(state, index);
3321 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3322 error(state, 0, "Invalid macro name");
3324 if (tk->ident->sym_define == 0) {
3325 state->if_value = state->if_depth;
3328 state->if_value = - state->if_depth;
3333 if (state->if_value < 0) {
3336 next_token(state, index);
3337 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3338 error(state, 0, "Invalid macro name");
3340 if (tk->ident->sym_define != 0) {
3341 state->if_value = state->if_depth;
3344 state->if_value = - state->if_depth;
3348 if (state->if_depth == 0) {
3349 error(state, 0, "#else without #if");
3351 if ((state->if_value >= 0) ||
3352 ((state->if_value < 0) &&
3353 (state->if_depth == -state->if_value)))
3355 state->if_value = - state->if_value;
3359 if (state->if_depth == 0) {
3360 error(state, 0, "#endif without #if");
3362 if ((state->if_value >= 0) ||
3363 ((state->if_value < 0) &&
3364 (state->if_depth == -state->if_value)))
3366 state->if_value = state->if_depth - 1;
3372 struct hash_entry *ident;
3373 struct macro *macro;
3376 if (state->if_value < 0) /* quit early when #if'd out */
3379 meat(state, index, TOK_IDENT);
3383 if (*file->pos == '(') {
3384 #warning "FIXME macros with arguments not supported"
3385 error(state, 0, "Macros with arguments not supported");
3388 /* Find the end of the line to get an estimate of
3389 * the macro's length.
3391 for(ptr = file->pos; *ptr != '\n'; ptr++)
3394 if (ident->sym_define != 0) {
3395 error(state, 0, "macro %s already defined\n", ident->name);
3397 macro = xmalloc(sizeof(*macro), "macro");
3398 macro->ident = ident;
3399 macro->buf_len = ptr - file->pos +1;
3400 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3402 memcpy(macro->buf, file->pos, macro->buf_len);
3403 macro->buf[macro->buf_len] = '\n';
3404 macro->buf[macro->buf_len +1] = '\0';
3406 ident->sym_define = macro;
3413 /* Find the end of the line */
3414 for(end = file->pos; *end != '\n'; end++)
3416 len = (end - file->pos);
3417 if (state->if_value >= 0) {
3418 error(state, 0, "%*.*s", len, len, file->pos);
3427 /* Find the end of the line */
3428 for(end = file->pos; *end != '\n'; end++)
3430 len = (end - file->pos);
3431 if (state->if_value >= 0) {
3432 warning(state, 0, "%*.*s", len, len, file->pos);
3444 next_token(state, index);
3445 if (tk->tok == TOK_LIT_STRING) {
3448 name = xmalloc(tk->str_len, "include");
3449 token = tk->val.str +1;
3450 name_len = tk->str_len -2;
3451 if (*token == '"') {
3455 memcpy(name, token, name_len);
3456 name[name_len] = '\0';
3459 else if (tk->tok == TOK_LESS) {
3462 for(end = start; *end != '\n'; end++) {
3468 error(state, 0, "Unterminated included directive");
3470 name = xmalloc(end - start + 1, "include");
3471 memcpy(name, start, end - start);
3472 name[end - start] = '\0';
3477 error(state, 0, "Invalid include directive");
3479 /* Error if there are any characters after the include */
3480 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3487 error(state, 0, "garbage after include directive");
3490 if (state->if_value >= 0) {
3491 compile_file(state, name, local);
3494 next_token(state, index);
3498 /* Ignore # without a following ident */
3499 if (tk->tok == TOK_IDENT) {
3500 error(state, 0, "Invalid preprocessor directive: %s",
3505 /* Consume the rest of the macro line */
3507 tok = mpeek(state, index);
3508 meat(state, index, tok);
3509 } while(tok != TOK_EOF);
3513 static void token(struct compile_state *state, int index)
3515 struct file_state *file;
3519 tk = &state->token[index];
3520 next_token(state, index);
3524 if (tk->tok == TOK_EOF && file->prev) {
3525 state->file = file->prev;
3526 /* file->basename is used keep it */
3527 xfree(file->dirname);
3530 next_token(state, index);
3533 else if (tk->tok == TOK_MACRO) {
3534 preprocess(state, index);
3537 else if (tk->ident && tk->ident->sym_define) {
3538 compile_macro(state, tk);
3539 next_token(state, index);
3542 else if (state->if_value < 0) {
3543 next_token(state, index);
3549 static int peek(struct compile_state *state)
3551 if (state->token[1].tok == -1) {
3554 return state->token[1].tok;
3557 static int peek2(struct compile_state *state)
3559 if (state->token[1].tok == -1) {
3562 if (state->token[2].tok == -1) {
3565 return state->token[2].tok;
3568 static void eat(struct compile_state *state, int tok)
3572 next_tok = peek(state);
3573 if (next_tok != tok) {
3574 const char *name1, *name2;
3575 name1 = tokens[next_tok];
3577 if (next_tok == TOK_IDENT) {
3578 name2 = state->token[1].ident->name;
3580 error(state, 0, "\tfound %s %s expected %s",
3581 name1, name2 ,tokens[tok]);
3583 /* Free the old token value */
3584 if (state->token[0].str_len) {
3585 xfree((void *)(state->token[0].val.str));
3587 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3588 state->token[i] = state->token[i + 1];
3590 memset(&state->token[i], 0, sizeof(state->token[i]));
3591 state->token[i].tok = -1;
3594 #warning "FIXME do not hardcode the include paths"
3595 static char *include_paths[] = {
3596 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3597 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3598 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3602 static void compile_file(struct compile_state *state, const char *filename, int local)
3605 const char *subdir, *base;
3607 struct file_state *file;
3609 file = xmalloc(sizeof(*file), "file_state");
3611 base = strrchr(filename, '/');
3614 subdir_len = base - filename;
3621 basename = xmalloc(strlen(base) +1, "basename");
3622 strcpy(basename, base);
3623 file->basename = basename;
3625 if (getcwd(cwd, sizeof(cwd)) == 0) {
3626 die("cwd buffer to small");
3629 if (subdir[0] == '/') {
3630 file->dirname = xmalloc(subdir_len + 1, "dirname");
3631 memcpy(file->dirname, subdir, subdir_len);
3632 file->dirname[subdir_len] = '\0';
3638 /* Find the appropriate directory... */
3640 if (!state->file && exists(cwd, filename)) {
3643 if (local && state->file && exists(state->file->dirname, filename)) {
3644 dir = state->file->dirname;
3646 for(path = include_paths; !dir && *path; path++) {
3647 if (exists(*path, filename)) {
3652 error(state, 0, "Cannot find `%s'\n", filename);
3654 dirlen = strlen(dir);
3655 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3656 memcpy(file->dirname, dir, dirlen);
3657 file->dirname[dirlen] = '/';
3658 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3659 file->dirname[dirlen + 1 + subdir_len] = '\0';
3661 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3664 file->pos = file->buf;
3665 file->line_start = file->pos;
3668 file->report_line = 1;
3669 file->report_name = file->basename;
3670 file->report_dir = file->dirname;
3672 file->prev = state->file;
3675 process_trigraphs(state);
3676 splice_lines(state);
3679 /* Type helper functions */
3681 static struct type *new_type(
3682 unsigned int type, struct type *left, struct type *right)
3684 struct type *result;
3685 result = xmalloc(sizeof(*result), "type");
3686 result->type = type;
3687 result->left = left;
3688 result->right = right;
3689 result->field_ident = 0;
3690 result->type_ident = 0;
3694 static struct type *clone_type(unsigned int specifiers, struct type *old)
3696 struct type *result;
3697 result = xmalloc(sizeof(*result), "type");
3698 memcpy(result, old, sizeof(*result));
3699 result->type &= TYPE_MASK;
3700 result->type |= specifiers;
3704 #define SIZEOF_SHORT 2
3705 #define SIZEOF_INT 4
3706 #define SIZEOF_LONG (sizeof(long_t))
3708 #define ALIGNOF_SHORT 2
3709 #define ALIGNOF_INT 4
3710 #define ALIGNOF_LONG (sizeof(long_t))
3712 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3713 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3714 static inline ulong_t mask_uint(ulong_t x)
3716 if (SIZEOF_INT < SIZEOF_LONG) {
3717 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3722 #define MASK_UINT(X) (mask_uint(X))
3723 #define MASK_ULONG(X) (X)
3725 static struct type void_type = { .type = TYPE_VOID };
3726 static struct type char_type = { .type = TYPE_CHAR };
3727 static struct type uchar_type = { .type = TYPE_UCHAR };
3728 static struct type short_type = { .type = TYPE_SHORT };
3729 static struct type ushort_type = { .type = TYPE_USHORT };
3730 static struct type int_type = { .type = TYPE_INT };
3731 static struct type uint_type = { .type = TYPE_UINT };
3732 static struct type long_type = { .type = TYPE_LONG };
3733 static struct type ulong_type = { .type = TYPE_ULONG };
3735 static struct triple *variable(struct compile_state *state, struct type *type)
3737 struct triple *result;
3738 if ((type->type & STOR_MASK) != STOR_PERM) {
3739 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3740 result = triple(state, OP_ADECL, type, 0, 0);
3743 struct triple **vector;
3745 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3746 vector = &result->param[0];
3750 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3751 vector[index] = variable(state, field->left);
3752 field = field->right;
3755 vector[index] = variable(state, field);
3759 result = triple(state, OP_SDECL, type, 0, 0);
3764 static void stor_of(FILE *fp, struct type *type)
3766 switch(type->type & STOR_MASK) {
3768 fprintf(fp, "auto ");
3771 fprintf(fp, "static ");
3774 fprintf(fp, "extern ");
3777 fprintf(fp, "register ");
3780 fprintf(fp, "typedef ");
3783 fprintf(fp, "inline ");
3787 static void qual_of(FILE *fp, struct type *type)
3789 if (type->type & QUAL_CONST) {
3790 fprintf(fp, " const");
3792 if (type->type & QUAL_VOLATILE) {
3793 fprintf(fp, " volatile");
3795 if (type->type & QUAL_RESTRICT) {
3796 fprintf(fp, " restrict");
3800 static void name_of(FILE *fp, struct type *type)
3803 switch(type->type & TYPE_MASK) {
3805 fprintf(fp, "void");
3809 fprintf(fp, "signed char");
3813 fprintf(fp, "unsigned char");
3817 fprintf(fp, "signed short");
3821 fprintf(fp, "unsigned short");
3825 fprintf(fp, "signed int");
3829 fprintf(fp, "unsigned int");
3833 fprintf(fp, "signed long");
3837 fprintf(fp, "unsigned long");
3841 name_of(fp, type->left);
3847 name_of(fp, type->left);
3849 name_of(fp, type->right);
3852 fprintf(fp, "enum %s", type->type_ident->name);
3856 fprintf(fp, "struct %s", type->type_ident->name);
3861 name_of(fp, type->left);
3862 fprintf(fp, " (*)(");
3863 name_of(fp, type->right);
3868 name_of(fp, type->left);
3869 fprintf(fp, " [%ld]", type->elements);
3872 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3877 static size_t align_of(struct compile_state *state, struct type *type)
3881 switch(type->type & TYPE_MASK) {
3891 align = ALIGNOF_SHORT;
3896 align = ALIGNOF_INT;
3901 align = ALIGNOF_LONG;
3906 size_t left_align, right_align;
3907 left_align = align_of(state, type->left);
3908 right_align = align_of(state, type->right);
3909 align = (left_align >= right_align) ? left_align : right_align;
3913 align = align_of(state, type->left);
3916 align = align_of(state, type->left);
3919 error(state, 0, "alignof not yet defined for type\n");
3925 static size_t size_of(struct compile_state *state, struct type *type)
3929 switch(type->type & TYPE_MASK) {
3939 size = SIZEOF_SHORT;
3954 size = size_of(state, type->left);
3955 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3957 align = align_of(state, type->left);
3958 pad = align - (size % align);
3959 size = size + pad + size_of(state, type->left);
3961 align = align_of(state, type->right);
3962 pad = align - (size % align);
3963 size = size + pad + sizeof(type->right);
3968 size_t size_left, size_right;
3969 size_left = size_of(state, type->left);
3970 size_right = size_of(state, type->right);
3971 size = (size_left >= size_right)? size_left : size_right;
3975 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3976 internal_error(state, 0, "Invalid array type");
3978 size = size_of(state, type->left) * type->elements;
3982 size = size_of(state, type->left);
3985 error(state, 0, "sizeof not yet defined for type\n");
3991 static size_t field_offset(struct compile_state *state,
3992 struct type *type, struct hash_entry *field)
3994 size_t size, align, pad;
3995 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3996 internal_error(state, 0, "field_offset only works on structures");
4000 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4001 if (type->left->field_ident == field) {
4004 size += size_of(state, type->left);
4006 align = align_of(state, type->left);
4007 pad = align - (size % align);
4010 if (type->field_ident != field) {
4011 internal_error(state, 0, "field_offset: member %s not present",
4017 static struct type *field_type(struct compile_state *state,
4018 struct type *type, struct hash_entry *field)
4020 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4021 internal_error(state, 0, "field_type only works on structures");
4024 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4025 if (type->left->field_ident == field) {
4031 if (type->field_ident != field) {
4032 internal_error(state, 0, "field_type: member %s not present",
4038 static struct triple *struct_field(struct compile_state *state,
4039 struct triple *decl, struct hash_entry *field)
4041 struct triple **vector;
4045 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4048 if (decl->op != OP_VAL_VEC) {
4049 internal_error(state, 0, "Invalid struct variable");
4052 internal_error(state, 0, "Missing structure field");
4055 vector = &RHS(decl, 0);
4057 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4058 if (type->left->field_ident == field) {
4065 if (type->field_ident != field) {
4066 internal_error(state, 0, "field %s not found?", field->name);
4068 return vector[index];
4071 static void arrays_complete(struct compile_state *state, struct type *type)
4073 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4074 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4075 error(state, 0, "array size not specified");
4077 arrays_complete(state, type->left);
4081 static unsigned int do_integral_promotion(unsigned int type)
4084 if (TYPE_INTEGER(type) &&
4085 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4091 static unsigned int do_arithmetic_conversion(
4092 unsigned int left, unsigned int right)
4096 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4097 return TYPE_LDOUBLE;
4099 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4102 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4105 left = do_integral_promotion(left);
4106 right = do_integral_promotion(right);
4107 /* If both operands have the same size done */
4108 if (left == right) {
4111 /* If both operands have the same signedness pick the larger */
4112 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4113 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4115 /* If the signed type can hold everything use it */
4116 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4119 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4122 /* Convert to the unsigned type with the same rank as the signed type */
4123 else if (TYPE_SIGNED(left)) {
4124 return TYPE_MKUNSIGNED(left);
4127 return TYPE_MKUNSIGNED(right);
4131 /* see if two types are the same except for qualifiers */
4132 static int equiv_types(struct type *left, struct type *right)
4135 /* Error if the basic types do not match */
4136 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4139 type = left->type & TYPE_MASK;
4140 /* if the basic types match and it is an arithmetic type we are done */
4141 if (TYPE_ARITHMETIC(type)) {
4144 /* If it is a pointer type recurse and keep testing */
4145 if (type == TYPE_POINTER) {
4146 return equiv_types(left->left, right->left);
4148 else if (type == TYPE_ARRAY) {
4149 return (left->elements == right->elements) &&
4150 equiv_types(left->left, right->left);
4152 /* test for struct/union equality */
4153 else if (type == TYPE_STRUCT) {
4154 return left->type_ident == right->type_ident;
4156 /* Test for equivalent functions */
4157 else if (type == TYPE_FUNCTION) {
4158 return equiv_types(left->left, right->left) &&
4159 equiv_types(left->right, right->right);
4161 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4162 else if (type == TYPE_PRODUCT) {
4163 return equiv_types(left->left, right->left) &&
4164 equiv_types(left->right, right->right);
4166 /* We should see TYPE_OVERLAP */
4172 static int equiv_ptrs(struct type *left, struct type *right)
4174 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4175 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4178 return equiv_types(left->left, right->left);
4181 static struct type *compatible_types(struct type *left, struct type *right)
4183 struct type *result;
4184 unsigned int type, qual_type;
4185 /* Error if the basic types do not match */
4186 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4189 type = left->type & TYPE_MASK;
4190 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4192 /* if the basic types match and it is an arithmetic type we are done */
4193 if (TYPE_ARITHMETIC(type)) {
4194 result = new_type(qual_type, 0, 0);
4196 /* If it is a pointer type recurse and keep testing */
4197 else if (type == TYPE_POINTER) {
4198 result = compatible_types(left->left, right->left);
4200 result = new_type(qual_type, result, 0);
4203 /* test for struct/union equality */
4204 else if (type == TYPE_STRUCT) {
4205 if (left->type_ident == right->type_ident) {
4209 /* Test for equivalent functions */
4210 else if (type == TYPE_FUNCTION) {
4211 struct type *lf, *rf;
4212 lf = compatible_types(left->left, right->left);
4213 rf = compatible_types(left->right, right->right);
4215 result = new_type(qual_type, lf, rf);
4218 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4219 else if (type == TYPE_PRODUCT) {
4220 struct type *lf, *rf;
4221 lf = compatible_types(left->left, right->left);
4222 rf = compatible_types(left->right, right->right);
4224 result = new_type(qual_type, lf, rf);
4228 /* Nothing else is compatible */
4233 static struct type *compatible_ptrs(struct type *left, struct type *right)
4235 struct type *result;
4236 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4237 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4240 result = compatible_types(left->left, right->left);
4242 unsigned int qual_type;
4243 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4244 result = new_type(qual_type, result, 0);
4249 static struct triple *integral_promotion(
4250 struct compile_state *state, struct triple *def)
4254 /* As all operations are carried out in registers
4255 * the values are converted on load I just convert
4256 * logical type of the operand.
4258 if (TYPE_INTEGER(type->type)) {
4259 unsigned int int_type;
4260 int_type = type->type & ~TYPE_MASK;
4261 int_type |= do_integral_promotion(type->type);
4262 if (int_type != type->type) {
4263 def->type = new_type(int_type, 0, 0);
4270 static void arithmetic(struct compile_state *state, struct triple *def)
4272 if (!TYPE_ARITHMETIC(def->type->type)) {
4273 error(state, 0, "arithmetic type expexted");
4277 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4279 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4280 error(state, def, "pointer or arithmetic type expected");
4284 static int is_integral(struct triple *ins)
4286 return TYPE_INTEGER(ins->type->type);
4289 static void integral(struct compile_state *state, struct triple *def)
4291 if (!is_integral(def)) {
4292 error(state, 0, "integral type expected");
4297 static void bool(struct compile_state *state, struct triple *def)
4299 if (!TYPE_ARITHMETIC(def->type->type) &&
4300 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4301 error(state, 0, "arithmetic or pointer type expected");
4305 static int is_signed(struct type *type)
4307 return !!TYPE_SIGNED(type->type);
4310 /* Is this value located in a register otherwise it must be in memory */
4311 static int is_in_reg(struct compile_state *state, struct triple *def)
4314 if (def->op == OP_ADECL) {
4317 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4320 else if (def->op == OP_VAL_VEC) {
4321 in_reg = is_in_reg(state, RHS(def, 0));
4323 else if (def->op == OP_DOT) {
4324 in_reg = is_in_reg(state, RHS(def, 0));
4327 internal_error(state, 0, "unknown expr storage location");
4333 /* Is this a stable variable location otherwise it must be a temporary */
4334 static int is_stable(struct compile_state *state, struct triple *def)
4341 if ((def->op == OP_ADECL) ||
4342 (def->op == OP_SDECL) ||
4343 (def->op == OP_DEREF) ||
4344 (def->op == OP_BLOBCONST)) {
4347 else if (def->op == OP_DOT) {
4348 ret = is_stable(state, RHS(def, 0));
4350 else if (def->op == OP_VAL_VEC) {
4351 struct triple **vector;
4354 vector = &RHS(def, 0);
4355 for(i = 0; i < def->type->elements; i++) {
4356 if (!is_stable(state, vector[i])) {
4365 static int is_lvalue(struct compile_state *state, struct triple *def)
4372 if (!is_stable(state, def)) {
4375 if (def->type->type & QUAL_CONST) {
4378 else if (def->op == OP_DOT) {
4379 ret = is_lvalue(state, RHS(def, 0));
4384 static void lvalue(struct compile_state *state, struct triple *def)
4387 internal_error(state, def, "nothing where lvalue expected?");
4389 if (!is_lvalue(state, def)) {
4390 error(state, def, "lvalue expected");
4394 static int is_pointer(struct triple *def)
4396 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4399 static void pointer(struct compile_state *state, struct triple *def)
4401 if (!is_pointer(def)) {
4402 error(state, def, "pointer expected");
4406 static struct triple *int_const(
4407 struct compile_state *state, struct type *type, ulong_t value)
4409 struct triple *result;
4410 switch(type->type & TYPE_MASK) {
4412 case TYPE_INT: case TYPE_UINT:
4413 case TYPE_LONG: case TYPE_ULONG:
4416 internal_error(state, 0, "constant for unkown type");
4418 result = triple(state, OP_INTCONST, type, 0, 0);
4419 result->u.cval = value;
4424 static struct triple *do_mk_addr_expr(struct compile_state *state,
4425 struct triple *expr, struct type *type, ulong_t offset)
4427 struct triple *result;
4428 lvalue(state, expr);
4431 if (expr->op == OP_ADECL) {
4432 error(state, expr, "address of auto variables not supported");
4434 else if (expr->op == OP_SDECL) {
4435 result = triple(state, OP_ADDRCONST, type, 0, 0);
4436 MISC(result, 0) = expr;
4437 result->u.cval = offset;
4439 else if (expr->op == OP_DEREF) {
4440 result = triple(state, OP_ADD, type,
4442 int_const(state, &ulong_type, offset));
4447 static struct triple *mk_addr_expr(
4448 struct compile_state *state, struct triple *expr, ulong_t offset)
4453 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4456 return do_mk_addr_expr(state, expr, type, offset);
4459 static struct triple *mk_deref_expr(
4460 struct compile_state *state, struct triple *expr)
4462 struct type *base_type;
4463 pointer(state, expr);
4464 base_type = expr->type->left;
4465 if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4467 "Only pointer and arithmetic values can be dereferenced");
4469 return triple(state, OP_DEREF, base_type, expr, 0);
4472 static struct triple *deref_field(
4473 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4475 struct triple *result;
4476 struct type *type, *member;
4478 internal_error(state, 0, "No field passed to deref_field");
4482 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4483 error(state, 0, "request for member %s in something not a struct or union",
4486 member = type->left;
4487 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4488 if (member->left->field_ident == field) {
4489 member = member->left;
4492 member = member->right;
4494 if (member->field_ident != field) {
4495 error(state, 0, "%s is not a member", field->name);
4497 if ((type->type & STOR_MASK) == STOR_PERM) {
4498 /* Do the pointer arithmetic to get a deref the field */
4500 offset = field_offset(state, type, field);
4501 result = do_mk_addr_expr(state, expr, member, offset);
4502 result = mk_deref_expr(state, result);
4505 /* Find the variable for the field I want. */
4506 result = triple(state, OP_DOT,
4507 field_type(state, type, field), expr, 0);
4508 result->u.field = field;
4513 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4519 if (!is_stable(state, def)) {
4522 /* Tranform an array to a pointer to the first element */
4523 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4524 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4526 struct triple *result;
4528 TYPE_POINTER | (def->type->type & QUAL_MASK),
4529 def->type->left, 0);
4530 result = triple(state, OP_ADDRCONST, type, 0, 0);
4531 MISC(result, 0) = def;
4534 if (is_in_reg(state, def)) {
4539 return triple(state, op, def->type, def, 0);
4542 static void write_compatible(struct compile_state *state,
4543 struct type *dest, struct type *rval)
4546 /* Both operands have arithmetic type */
4547 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4550 /* One operand is a pointer and the other is a pointer to void */
4551 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4552 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4553 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4554 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4557 /* If both types are the same without qualifiers we are good */
4558 else if (equiv_ptrs(dest, rval)) {
4561 /* test for struct/union equality */
4562 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4563 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4564 (dest->type_ident == rval->type_ident)) {
4568 error(state, 0, "Incompatible types in assignment");
4572 static struct triple *write_expr(
4573 struct compile_state *state, struct triple *dest, struct triple *rval)
4580 internal_error(state, 0, "missing rval");
4583 if (rval->op == OP_LIST) {
4584 internal_error(state, 0, "expression of type OP_LIST?");
4586 if (!is_lvalue(state, dest)) {
4587 internal_error(state, 0, "writing to a non lvalue?");
4590 write_compatible(state, dest->type, rval->type);
4592 /* Now figure out which assignment operator to use */
4594 if (is_in_reg(state, dest)) {
4599 def = triple(state, op, dest->type, dest, rval);
4603 static struct triple *init_expr(
4604 struct compile_state *state, struct triple *dest, struct triple *rval)
4610 internal_error(state, 0, "missing rval");
4612 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4613 rval = read_expr(state, rval);
4614 def = write_expr(state, dest, rval);
4617 /* Fill in the array size if necessary */
4618 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4619 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4620 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4621 dest->type->elements = rval->type->elements;
4624 if (!equiv_types(dest->type, rval->type)) {
4625 error(state, 0, "Incompatible types in inializer");
4627 MISC(dest, 0) = rval;
4628 insert_triple(state, dest, rval);
4629 rval->id |= TRIPLE_FLAG_FLATTENED;
4630 use_triple(MISC(dest, 0), dest);
4635 struct type *arithmetic_result(
4636 struct compile_state *state, struct triple *left, struct triple *right)
4639 /* Sanity checks to ensure I am working with arithmetic types */
4640 arithmetic(state, left);
4641 arithmetic(state, right);
4643 do_arithmetic_conversion(
4645 right->type->type), 0, 0);
4649 struct type *ptr_arithmetic_result(
4650 struct compile_state *state, struct triple *left, struct triple *right)
4653 /* Sanity checks to ensure I am working with the proper types */
4654 ptr_arithmetic(state, left);
4655 arithmetic(state, right);
4656 if (TYPE_ARITHMETIC(left->type->type) &&
4657 TYPE_ARITHMETIC(right->type->type)) {
4658 type = arithmetic_result(state, left, right);
4660 else if (TYPE_PTR(left->type->type)) {
4664 internal_error(state, 0, "huh?");
4671 /* boolean helper function */
4673 static struct triple *ltrue_expr(struct compile_state *state,
4674 struct triple *expr)
4677 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4678 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4679 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4680 /* If the expression is already boolean do nothing */
4683 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4689 static struct triple *lfalse_expr(struct compile_state *state,
4690 struct triple *expr)
4692 return triple(state, OP_LFALSE, &int_type, expr, 0);
4695 static struct triple *cond_expr(
4696 struct compile_state *state,
4697 struct triple *test, struct triple *left, struct triple *right)
4700 struct type *result_type;
4701 unsigned int left_type, right_type;
4703 left_type = left->type->type;
4704 right_type = right->type->type;
4706 /* Both operands have arithmetic type */
4707 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4708 result_type = arithmetic_result(state, left, right);
4710 /* Both operands have void type */
4711 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4712 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4713 result_type = &void_type;
4715 /* pointers to the same type... */
4716 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4719 /* Both operands are pointers and left is a pointer to void */
4720 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4721 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4722 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4723 result_type = right->type;
4725 /* Both operands are pointers and right is a pointer to void */
4726 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4727 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4728 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4729 result_type = left->type;
4732 error(state, 0, "Incompatible types in conditional expression");
4734 /* Cleanup and invert the test */
4735 test = lfalse_expr(state, read_expr(state, test));
4736 def = new_triple(state, OP_COND, result_type, 0, 3);
4737 def->param[0] = test;
4738 def->param[1] = left;
4739 def->param[2] = right;
4744 static int expr_depth(struct compile_state *state, struct triple *ins)
4748 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4751 else if (ins->op == OP_DEREF) {
4752 count = expr_depth(state, RHS(ins, 0)) - 1;
4754 else if (ins->op == OP_VAL) {
4755 count = expr_depth(state, RHS(ins, 0)) - 1;
4757 else if (ins->op == OP_COMMA) {
4759 ldepth = expr_depth(state, RHS(ins, 0));
4760 rdepth = expr_depth(state, RHS(ins, 1));
4761 count = (ldepth >= rdepth)? ldepth : rdepth;
4763 else if (ins->op == OP_CALL) {
4764 /* Don't figure the depth of a call just guess it is huge */
4768 struct triple **expr;
4769 expr = triple_rhs(state, ins, 0);
4770 for(;expr; expr = triple_rhs(state, ins, expr)) {
4773 depth = expr_depth(state, *expr);
4774 if (depth > count) {
4783 static struct triple *flatten(
4784 struct compile_state *state, struct triple *first, struct triple *ptr);
4786 static struct triple *flatten_generic(
4787 struct compile_state *state, struct triple *first, struct triple *ptr)
4791 struct triple **ins;
4794 /* Only operations with just a rhs should come here */
4795 rhs = TRIPLE_RHS(ptr->sizes);
4796 lhs = TRIPLE_LHS(ptr->sizes);
4797 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4798 internal_error(state, ptr, "unexpected args for: %d %s",
4799 ptr->op, tops(ptr->op));
4801 /* Find the depth of the rhs elements */
4802 for(i = 0; i < rhs; i++) {
4803 vector[i].ins = &RHS(ptr, i);
4804 vector[i].depth = expr_depth(state, *vector[i].ins);
4806 /* Selection sort the rhs */
4807 for(i = 0; i < rhs; i++) {
4809 for(j = i + 1; j < rhs; j++ ) {
4810 if (vector[j].depth > vector[max].depth) {
4815 struct rhs_vector tmp;
4817 vector[i] = vector[max];
4821 /* Now flatten the rhs elements */
4822 for(i = 0; i < rhs; i++) {
4823 *vector[i].ins = flatten(state, first, *vector[i].ins);
4824 use_triple(*vector[i].ins, ptr);
4827 /* Now flatten the lhs elements */
4828 for(i = 0; i < lhs; i++) {
4829 struct triple **ins = &LHS(ptr, i);
4830 *ins = flatten(state, first, *ins);
4831 use_triple(*ins, ptr);
4836 static struct triple *flatten_land(
4837 struct compile_state *state, struct triple *first, struct triple *ptr)
4839 struct triple *left, *right;
4840 struct triple *val, *test, *jmp, *label1, *end;
4842 /* Find the triples */
4844 right = RHS(ptr, 1);
4846 /* Generate the needed triples */
4849 /* Thread the triples together */
4850 val = flatten(state, first, variable(state, ptr->type));
4851 left = flatten(state, first, write_expr(state, val, left));
4852 test = flatten(state, first,
4853 lfalse_expr(state, read_expr(state, val)));
4854 jmp = flatten(state, first, branch(state, end, test));
4855 label1 = flatten(state, first, label(state));
4856 right = flatten(state, first, write_expr(state, val, right));
4857 TARG(jmp, 0) = flatten(state, first, end);
4859 /* Now give the caller something to chew on */
4860 return read_expr(state, val);
4863 static struct triple *flatten_lor(
4864 struct compile_state *state, struct triple *first, struct triple *ptr)
4866 struct triple *left, *right;
4867 struct triple *val, *jmp, *label1, *end;
4869 /* Find the triples */
4871 right = RHS(ptr, 1);
4873 /* Generate the needed triples */
4876 /* Thread the triples together */
4877 val = flatten(state, first, variable(state, ptr->type));
4878 left = flatten(state, first, write_expr(state, val, left));
4879 jmp = flatten(state, first, branch(state, end, left));
4880 label1 = flatten(state, first, label(state));
4881 right = flatten(state, first, write_expr(state, val, right));
4882 TARG(jmp, 0) = flatten(state, first, end);
4885 /* Now give the caller something to chew on */
4886 return read_expr(state, val);
4889 static struct triple *flatten_cond(
4890 struct compile_state *state, struct triple *first, struct triple *ptr)
4892 struct triple *test, *left, *right;
4893 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4895 /* Find the triples */
4898 right = RHS(ptr, 2);
4900 /* Generate the needed triples */
4902 middle = label(state);
4904 /* Thread the triples together */
4905 val = flatten(state, first, variable(state, ptr->type));
4906 test = flatten(state, first, test);
4907 jmp1 = flatten(state, first, branch(state, middle, test));
4908 label1 = flatten(state, first, label(state));
4909 left = flatten(state, first, left);
4910 mv1 = flatten(state, first, write_expr(state, val, left));
4911 jmp2 = flatten(state, first, branch(state, end, 0));
4912 TARG(jmp1, 0) = flatten(state, first, middle);
4913 right = flatten(state, first, right);
4914 mv2 = flatten(state, first, write_expr(state, val, right));
4915 TARG(jmp2, 0) = flatten(state, first, end);
4917 /* Now give the caller something to chew on */
4918 return read_expr(state, val);
4921 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
4922 struct occurance *base_occurance)
4924 struct triple *nfunc;
4925 struct triple *nfirst, *ofirst;
4926 struct triple *new, *old;
4929 fprintf(stdout, "\n");
4930 loc(stdout, state, 0);
4931 fprintf(stdout, "\n__________ copy_func _________\n");
4932 print_triple(state, ofunc);
4933 fprintf(stdout, "__________ copy_func _________ done\n\n");
4936 /* Make a new copy of the old function */
4937 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4939 ofirst = old = RHS(ofunc, 0);
4942 struct occurance *occurance;
4943 int old_lhs, old_rhs;
4944 old_lhs = TRIPLE_LHS(old->sizes);
4945 old_rhs = TRIPLE_RHS(old->sizes);
4946 occurance = inline_occurance(state, base_occurance, old->occurance);
4947 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4949 if (!triple_stores_block(state, new)) {
4950 memcpy(&new->u, &old->u, sizeof(new->u));
4953 RHS(nfunc, 0) = nfirst = new;
4956 insert_triple(state, nfirst, new);
4958 new->id |= TRIPLE_FLAG_FLATTENED;
4960 /* During the copy remember new as user of old */
4961 use_triple(old, new);
4963 /* Populate the return type if present */
4964 if (old == MISC(ofunc, 0)) {
4965 MISC(nfunc, 0) = new;
4968 } while(old != ofirst);
4970 /* Make a second pass to fix up any unresolved references */
4974 struct triple **oexpr, **nexpr;
4976 /* Lookup where the copy is, to join pointers */
4977 count = TRIPLE_SIZE(old->sizes);
4978 for(i = 0; i < count; i++) {
4979 oexpr = &old->param[i];
4980 nexpr = &new->param[i];
4981 if (!*nexpr && *oexpr && (*oexpr)->use) {
4982 *nexpr = (*oexpr)->use->member;
4983 if (*nexpr == old) {
4984 internal_error(state, 0, "new == old?");
4986 use_triple(*nexpr, new);
4988 if (!*nexpr && *oexpr) {
4989 internal_error(state, 0, "Could not copy %d\n", i);
4994 } while((old != ofirst) && (new != nfirst));
4996 /* Make a third pass to cleanup the extra useses */
5000 unuse_triple(old, new);
5003 } while ((old != ofirst) && (new != nfirst));
5007 static struct triple *flatten_call(
5008 struct compile_state *state, struct triple *first, struct triple *ptr)
5010 /* Inline the function call */
5012 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5013 struct triple *end, *nend;
5016 /* Find the triples */
5017 ofunc = MISC(ptr, 0);
5018 if (ofunc->op != OP_LIST) {
5019 internal_error(state, 0, "improper function");
5021 nfunc = copy_func(state, ofunc, ptr->occurance);
5022 nfirst = RHS(nfunc, 0)->next;
5023 /* Prepend the parameter reading into the new function list */
5024 ptype = nfunc->type->right;
5025 param = RHS(nfunc, 0)->next;
5026 pvals = TRIPLE_RHS(ptr->sizes);
5027 for(i = 0; i < pvals; i++) {
5031 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5032 atype = ptype->left;
5034 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5035 param = param->next;
5038 flatten(state, nfirst, write_expr(state, param, arg));
5039 ptype = ptype->right;
5040 param = param->next;
5043 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5044 result = read_expr(state, MISC(nfunc,0));
5047 fprintf(stdout, "\n");
5048 loc(stdout, state, 0);
5049 fprintf(stdout, "\n__________ flatten_call _________\n");
5050 print_triple(state, nfunc);
5051 fprintf(stdout, "__________ flatten_call _________ done\n\n");
5054 /* Get rid of the extra triples */
5055 nfirst = RHS(nfunc, 0)->next;
5056 free_triple(state, RHS(nfunc, 0));
5058 free_triple(state, nfunc);
5060 /* Append the new function list onto the return list */
5062 nend = nfirst->prev;
5071 static struct triple *flatten(
5072 struct compile_state *state, struct triple *first, struct triple *ptr)
5074 struct triple *orig_ptr;
5079 /* Only flatten triples once */
5080 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5086 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5087 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
5088 use_triple(LHS(ptr, 0), ptr);
5089 use_triple(RHS(ptr, 0), ptr);
5092 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5096 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5097 return MISC(ptr, 0);
5100 ptr = flatten_land(state, first, ptr);
5103 ptr = flatten_lor(state, first, ptr);
5106 ptr = flatten_cond(state, first, ptr);
5109 ptr = flatten_call(state, first, ptr);
5113 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5114 use_triple(RHS(ptr, 0), ptr);
5117 use_triple(TARG(ptr, 0), ptr);
5118 if (TRIPLE_RHS(ptr->sizes)) {
5119 use_triple(RHS(ptr, 0), ptr);
5120 if (ptr->next != ptr) {
5121 use_triple(ptr->next, ptr);
5126 insert_triple(state, first, ptr);
5127 ptr->id |= TRIPLE_FLAG_FLATTENED;
5128 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5129 use_triple(MISC(ptr, 0), ptr);
5132 /* Since OP_DEREF is just a marker delete it when I flatten it */
5134 RHS(orig_ptr, 0) = 0;
5135 free_triple(state, orig_ptr);
5139 struct triple *base;
5141 base = flatten(state, first, base);
5142 if (base->op == OP_VAL_VEC) {
5143 ptr = struct_field(state, base, ptr->u.field);
5148 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5149 use_triple(MISC(ptr, 0), ptr);
5150 use_triple(ptr, MISC(ptr, 0));
5154 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5155 use_triple(MISC(ptr, 0), ptr);
5160 /* Flatten the easy cases we don't override */
5161 ptr = flatten_generic(state, first, ptr);
5164 } while(ptr && (ptr != orig_ptr));
5166 insert_triple(state, first, ptr);
5167 ptr->id |= TRIPLE_FLAG_FLATTENED;
5172 static void release_expr(struct compile_state *state, struct triple *expr)
5174 struct triple *head;
5175 head = label(state);
5176 flatten(state, head, expr);
5177 while(head->next != head) {
5178 release_triple(state, head->next);
5180 free_triple(state, head);
5183 static int replace_rhs_use(struct compile_state *state,
5184 struct triple *orig, struct triple *new, struct triple *use)
5186 struct triple **expr;
5189 expr = triple_rhs(state, use, 0);
5190 for(;expr; expr = triple_rhs(state, use, expr)) {
5191 if (*expr == orig) {
5197 unuse_triple(orig, use);
5198 use_triple(new, use);
5203 static int replace_lhs_use(struct compile_state *state,
5204 struct triple *orig, struct triple *new, struct triple *use)
5206 struct triple **expr;
5209 expr = triple_lhs(state, use, 0);
5210 for(;expr; expr = triple_lhs(state, use, expr)) {
5211 if (*expr == orig) {
5217 unuse_triple(orig, use);
5218 use_triple(new, use);
5223 static void propogate_use(struct compile_state *state,
5224 struct triple *orig, struct triple *new)
5226 struct triple_set *user, *next;
5227 for(user = orig->use; user; user = next) {
5233 found |= replace_rhs_use(state, orig, new, use);
5234 found |= replace_lhs_use(state, orig, new, use);
5236 internal_error(state, use, "use without use");
5240 internal_error(state, orig, "used after propogate_use");
5246 * ===========================
5249 static struct triple *mk_add_expr(
5250 struct compile_state *state, struct triple *left, struct triple *right)
5252 struct type *result_type;
5253 /* Put pointer operands on the left */
5254 if (is_pointer(right)) {
5260 left = read_expr(state, left);
5261 right = read_expr(state, right);
5262 result_type = ptr_arithmetic_result(state, left, right);
5263 if (is_pointer(left)) {
5264 right = triple(state,
5265 is_signed(right->type)? OP_SMUL : OP_UMUL,
5268 int_const(state, &ulong_type,
5269 size_of(state, left->type->left)));
5271 return triple(state, OP_ADD, result_type, left, right);
5274 static struct triple *mk_sub_expr(
5275 struct compile_state *state, struct triple *left, struct triple *right)
5277 struct type *result_type;
5278 result_type = ptr_arithmetic_result(state, left, right);
5279 left = read_expr(state, left);
5280 right = read_expr(state, right);
5281 if (is_pointer(left)) {
5282 right = triple(state,
5283 is_signed(right->type)? OP_SMUL : OP_UMUL,
5286 int_const(state, &ulong_type,
5287 size_of(state, left->type->left)));
5289 return triple(state, OP_SUB, result_type, left, right);
5292 static struct triple *mk_pre_inc_expr(
5293 struct compile_state *state, struct triple *def)
5297 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5298 return triple(state, OP_VAL, def->type,
5299 write_expr(state, def, val),
5303 static struct triple *mk_pre_dec_expr(
5304 struct compile_state *state, struct triple *def)
5308 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5309 return triple(state, OP_VAL, def->type,
5310 write_expr(state, def, val),
5314 static struct triple *mk_post_inc_expr(
5315 struct compile_state *state, struct triple *def)
5319 val = read_expr(state, def);
5320 return triple(state, OP_VAL, def->type,
5321 write_expr(state, def,
5322 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5326 static struct triple *mk_post_dec_expr(
5327 struct compile_state *state, struct triple *def)
5331 val = read_expr(state, def);
5332 return triple(state, OP_VAL, def->type,
5333 write_expr(state, def,
5334 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5338 static struct triple *mk_subscript_expr(
5339 struct compile_state *state, struct triple *left, struct triple *right)
5341 left = read_expr(state, left);
5342 right = read_expr(state, right);
5343 if (!is_pointer(left) && !is_pointer(right)) {
5344 error(state, left, "subscripted value is not a pointer");
5346 return mk_deref_expr(state, mk_add_expr(state, left, right));
5350 * Compile time evaluation
5351 * ===========================
5353 static int is_const(struct triple *ins)
5355 return IS_CONST_OP(ins->op);
5358 static int constants_equal(struct compile_state *state,
5359 struct triple *left, struct triple *right)
5362 if (!is_const(left) || !is_const(right)) {
5365 else if (left->op != right->op) {
5368 else if (!equiv_types(left->type, right->type)) {
5375 if (left->u.cval == right->u.cval) {
5381 size_t lsize, rsize;
5382 lsize = size_of(state, left->type);
5383 rsize = size_of(state, right->type);
5384 if (lsize != rsize) {
5387 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5393 if ((MISC(left, 0) == MISC(right, 0)) &&
5394 (left->u.cval == right->u.cval)) {
5399 internal_error(state, left, "uknown constant type");
5406 static int is_zero(struct triple *ins)
5408 return is_const(ins) && (ins->u.cval == 0);
5411 static int is_one(struct triple *ins)
5413 return is_const(ins) && (ins->u.cval == 1);
5416 static long_t bsr(ulong_t value)
5419 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5430 static long_t bsf(ulong_t value)
5433 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5444 static long_t log2(ulong_t value)
5449 static long_t tlog2(struct triple *ins)
5451 return log2(ins->u.cval);
5454 static int is_pow2(struct triple *ins)
5456 ulong_t value, mask;
5458 if (!is_const(ins)) {
5461 value = ins->u.cval;
5468 return ((value & mask) == value);
5471 static ulong_t read_const(struct compile_state *state,
5472 struct triple *ins, struct triple **expr)
5476 switch(rhs->type->type &TYPE_MASK) {
5488 internal_error(state, rhs, "bad type to read_const\n");
5494 static long_t read_sconst(struct triple *ins, struct triple **expr)
5498 return (long_t)(rhs->u.cval);
5501 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5503 struct triple **expr;
5504 expr = triple_rhs(state, ins, 0);
5505 for(;expr;expr = triple_rhs(state, ins, expr)) {
5507 unuse_triple(*expr, ins);
5513 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5515 struct triple **expr;
5516 expr = triple_lhs(state, ins, 0);
5517 for(;expr;expr = triple_lhs(state, ins, expr)) {
5518 unuse_triple(*expr, ins);
5523 static void check_lhs(struct compile_state *state, struct triple *ins)
5525 struct triple **expr;
5526 expr = triple_lhs(state, ins, 0);
5527 for(;expr;expr = triple_lhs(state, ins, expr)) {
5528 internal_error(state, ins, "unexpected lhs");
5532 static void check_targ(struct compile_state *state, struct triple *ins)
5534 struct triple **expr;
5535 expr = triple_targ(state, ins, 0);
5536 for(;expr;expr = triple_targ(state, ins, expr)) {
5537 internal_error(state, ins, "unexpected targ");
5541 static void wipe_ins(struct compile_state *state, struct triple *ins)
5543 /* Becareful which instructions you replace the wiped
5544 * instruction with, as there are not enough slots
5545 * in all instructions to hold all others.
5547 check_targ(state, ins);
5548 unuse_rhs(state, ins);
5549 unuse_lhs(state, ins);
5552 static void mkcopy(struct compile_state *state,
5553 struct triple *ins, struct triple *rhs)
5555 wipe_ins(state, ins);
5557 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5559 use_triple(RHS(ins, 0), ins);
5562 static void mkconst(struct compile_state *state,
5563 struct triple *ins, ulong_t value)
5565 if (!is_integral(ins) && !is_pointer(ins)) {
5566 internal_error(state, ins, "unknown type to make constant\n");
5568 wipe_ins(state, ins);
5569 ins->op = OP_INTCONST;
5570 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5571 ins->u.cval = value;
5574 static void mkaddr_const(struct compile_state *state,
5575 struct triple *ins, struct triple *sdecl, ulong_t value)
5577 wipe_ins(state, ins);
5578 ins->op = OP_ADDRCONST;
5579 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5580 MISC(ins, 0) = sdecl;
5581 ins->u.cval = value;
5582 use_triple(sdecl, ins);
5585 /* Transform multicomponent variables into simple register variables */
5586 static void flatten_structures(struct compile_state *state)
5588 struct triple *ins, *first;
5589 first = RHS(state->main_function, 0);
5591 /* Pass one expand structure values into valvecs.
5595 struct triple *next;
5597 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5598 if (ins->op == OP_VAL_VEC) {
5601 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5602 struct triple *def, **vector;
5609 get_occurance(ins->occurance);
5610 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5613 vector = &RHS(next, 0);
5614 tptr = next->type->left;
5615 for(i = 0; i < next->type->elements; i++) {
5616 struct triple *sfield;
5619 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5620 mtype = mtype->left;
5622 sfield = deref_field(state, def, mtype->field_ident);
5625 state, op, mtype, sfield, 0);
5626 put_occurance(vector[i]->occurance);
5627 get_occurance(next->occurance);
5628 vector[i]->occurance = next->occurance;
5631 propogate_use(state, ins, next);
5632 flatten(state, ins, next);
5633 free_triple(state, ins);
5635 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5636 struct triple *src, *dst, **vector;
5644 get_occurance(ins->occurance);
5645 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5648 vector = &RHS(next, 0);
5649 tptr = next->type->left;
5650 for(i = 0; i < ins->type->elements; i++) {
5651 struct triple *dfield, *sfield;
5654 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5655 mtype = mtype->left;
5657 sfield = deref_field(state, src, mtype->field_ident);
5658 dfield = deref_field(state, dst, mtype->field_ident);
5660 state, op, mtype, dfield, sfield);
5661 put_occurance(vector[i]->occurance);
5662 get_occurance(next->occurance);
5663 vector[i]->occurance = next->occurance;
5666 propogate_use(state, ins, next);
5667 flatten(state, ins, next);
5668 free_triple(state, ins);
5672 } while(ins != first);
5673 /* Pass two flatten the valvecs.
5677 struct triple *next;
5679 if (ins->op == OP_VAL_VEC) {
5680 release_triple(state, ins);
5683 } while(ins != first);
5684 /* Pass three verify the state and set ->id to 0.
5688 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5689 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5690 internal_error(state, 0, "STRUCT_TYPE remains?");
5692 if (ins->op == OP_DOT) {
5693 internal_error(state, 0, "OP_DOT remains?");
5695 if (ins->op == OP_VAL_VEC) {
5696 internal_error(state, 0, "OP_VAL_VEC remains?");
5699 } while(ins != first);
5702 /* For those operations that cannot be simplified */
5703 static void simplify_noop(struct compile_state *state, struct triple *ins)
5708 static void simplify_smul(struct compile_state *state, struct triple *ins)
5710 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5713 RHS(ins, 0) = RHS(ins, 1);
5716 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5718 left = read_sconst(ins, &RHS(ins, 0));
5719 right = read_sconst(ins, &RHS(ins, 1));
5720 mkconst(state, ins, left * right);
5722 else if (is_zero(RHS(ins, 1))) {
5723 mkconst(state, ins, 0);
5725 else if (is_one(RHS(ins, 1))) {
5726 mkcopy(state, ins, RHS(ins, 0));
5728 else if (is_pow2(RHS(ins, 1))) {
5730 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5732 insert_triple(state, ins, val);
5733 unuse_triple(RHS(ins, 1), ins);
5734 use_triple(val, ins);
5739 static void simplify_umul(struct compile_state *state, struct triple *ins)
5741 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5744 RHS(ins, 0) = RHS(ins, 1);
5747 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5748 ulong_t left, right;
5749 left = read_const(state, ins, &RHS(ins, 0));
5750 right = read_const(state, ins, &RHS(ins, 1));
5751 mkconst(state, ins, left * right);
5753 else if (is_zero(RHS(ins, 1))) {
5754 mkconst(state, ins, 0);
5756 else if (is_one(RHS(ins, 1))) {
5757 mkcopy(state, ins, RHS(ins, 0));
5759 else if (is_pow2(RHS(ins, 1))) {
5761 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5763 insert_triple(state, ins, val);
5764 unuse_triple(RHS(ins, 1), ins);
5765 use_triple(val, ins);
5770 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5772 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5774 left = read_sconst(ins, &RHS(ins, 0));
5775 right = read_sconst(ins, &RHS(ins, 1));
5776 mkconst(state, ins, left / right);
5778 else if (is_zero(RHS(ins, 0))) {
5779 mkconst(state, ins, 0);
5781 else if (is_zero(RHS(ins, 1))) {
5782 error(state, ins, "division by zero");
5784 else if (is_one(RHS(ins, 1))) {
5785 mkcopy(state, ins, RHS(ins, 0));
5787 else if (is_pow2(RHS(ins, 1))) {
5789 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5791 insert_triple(state, ins, val);
5792 unuse_triple(RHS(ins, 1), ins);
5793 use_triple(val, ins);
5798 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5800 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5801 ulong_t left, right;
5802 left = read_const(state, ins, &RHS(ins, 0));
5803 right = read_const(state, ins, &RHS(ins, 1));
5804 mkconst(state, ins, left / right);
5806 else if (is_zero(RHS(ins, 0))) {
5807 mkconst(state, ins, 0);
5809 else if (is_zero(RHS(ins, 1))) {
5810 error(state, ins, "division by zero");
5812 else if (is_one(RHS(ins, 1))) {
5813 mkcopy(state, ins, RHS(ins, 0));
5815 else if (is_pow2(RHS(ins, 1))) {
5817 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5819 insert_triple(state, ins, val);
5820 unuse_triple(RHS(ins, 1), ins);
5821 use_triple(val, ins);
5826 static void simplify_smod(struct compile_state *state, struct triple *ins)
5828 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5830 left = read_const(state, ins, &RHS(ins, 0));
5831 right = read_const(state, ins, &RHS(ins, 1));
5832 mkconst(state, ins, left % right);
5834 else if (is_zero(RHS(ins, 0))) {
5835 mkconst(state, ins, 0);
5837 else if (is_zero(RHS(ins, 1))) {
5838 error(state, ins, "division by zero");
5840 else if (is_one(RHS(ins, 1))) {
5841 mkconst(state, ins, 0);
5843 else if (is_pow2(RHS(ins, 1))) {
5845 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5847 insert_triple(state, ins, val);
5848 unuse_triple(RHS(ins, 1), ins);
5849 use_triple(val, ins);
5853 static void simplify_umod(struct compile_state *state, struct triple *ins)
5855 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5856 ulong_t left, right;
5857 left = read_const(state, ins, &RHS(ins, 0));
5858 right = read_const(state, ins, &RHS(ins, 1));
5859 mkconst(state, ins, left % right);
5861 else if (is_zero(RHS(ins, 0))) {
5862 mkconst(state, ins, 0);
5864 else if (is_zero(RHS(ins, 1))) {
5865 error(state, ins, "division by zero");
5867 else if (is_one(RHS(ins, 1))) {
5868 mkconst(state, ins, 0);
5870 else if (is_pow2(RHS(ins, 1))) {
5872 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5874 insert_triple(state, ins, val);
5875 unuse_triple(RHS(ins, 1), ins);
5876 use_triple(val, ins);
5881 static void simplify_add(struct compile_state *state, struct triple *ins)
5883 /* start with the pointer on the left */
5884 if (is_pointer(RHS(ins, 1))) {
5887 RHS(ins, 0) = RHS(ins, 1);
5890 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5891 if (!is_pointer(RHS(ins, 0))) {
5892 ulong_t left, right;
5893 left = read_const(state, ins, &RHS(ins, 0));
5894 right = read_const(state, ins, &RHS(ins, 1));
5895 mkconst(state, ins, left + right);
5897 else /* op == OP_ADDRCONST */ {
5898 struct triple *sdecl;
5899 ulong_t left, right;
5900 sdecl = MISC(RHS(ins, 0), 0);
5901 left = RHS(ins, 0)->u.cval;
5902 right = RHS(ins, 1)->u.cval;
5903 mkaddr_const(state, ins, sdecl, left + right);
5906 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5909 RHS(ins, 1) = RHS(ins, 0);
5914 static void simplify_sub(struct compile_state *state, struct triple *ins)
5916 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5917 if (!is_pointer(RHS(ins, 0))) {
5918 ulong_t left, right;
5919 left = read_const(state, ins, &RHS(ins, 0));
5920 right = read_const(state, ins, &RHS(ins, 1));
5921 mkconst(state, ins, left - right);
5923 else /* op == OP_ADDRCONST */ {
5924 struct triple *sdecl;
5925 ulong_t left, right;
5926 sdecl = MISC(RHS(ins, 0), 0);
5927 left = RHS(ins, 0)->u.cval;
5928 right = RHS(ins, 1)->u.cval;
5929 mkaddr_const(state, ins, sdecl, left - right);
5934 static void simplify_sl(struct compile_state *state, struct triple *ins)
5936 if (is_const(RHS(ins, 1))) {
5938 right = read_const(state, ins, &RHS(ins, 1));
5939 if (right >= (size_of(state, ins->type)*8)) {
5940 warning(state, ins, "left shift count >= width of type");
5943 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5944 ulong_t left, right;
5945 left = read_const(state, ins, &RHS(ins, 0));
5946 right = read_const(state, ins, &RHS(ins, 1));
5947 mkconst(state, ins, left << right);
5951 static void simplify_usr(struct compile_state *state, struct triple *ins)
5953 if (is_const(RHS(ins, 1))) {
5955 right = read_const(state, ins, &RHS(ins, 1));
5956 if (right >= (size_of(state, ins->type)*8)) {
5957 warning(state, ins, "right shift count >= width of type");
5960 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5961 ulong_t left, right;
5962 left = read_const(state, ins, &RHS(ins, 0));
5963 right = read_const(state, ins, &RHS(ins, 1));
5964 mkconst(state, ins, left >> right);
5968 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5970 if (is_const(RHS(ins, 1))) {
5972 right = read_const(state, ins, &RHS(ins, 1));
5973 if (right >= (size_of(state, ins->type)*8)) {
5974 warning(state, ins, "right shift count >= width of type");
5977 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5979 left = read_sconst(ins, &RHS(ins, 0));
5980 right = read_sconst(ins, &RHS(ins, 1));
5981 mkconst(state, ins, left >> right);
5985 static void simplify_and(struct compile_state *state, struct triple *ins)
5987 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5988 ulong_t left, right;
5989 left = read_const(state, ins, &RHS(ins, 0));
5990 right = read_const(state, ins, &RHS(ins, 1));
5991 mkconst(state, ins, left & right);
5995 static void simplify_or(struct compile_state *state, struct triple *ins)
5997 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5998 ulong_t left, right;
5999 left = read_const(state, ins, &RHS(ins, 0));
6000 right = read_const(state, ins, &RHS(ins, 1));
6001 mkconst(state, ins, left | right);
6005 static void simplify_xor(struct compile_state *state, struct triple *ins)
6007 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6008 ulong_t left, right;
6009 left = read_const(state, ins, &RHS(ins, 0));
6010 right = read_const(state, ins, &RHS(ins, 1));
6011 mkconst(state, ins, left ^ right);
6015 static void simplify_pos(struct compile_state *state, struct triple *ins)
6017 if (is_const(RHS(ins, 0))) {
6018 mkconst(state, ins, RHS(ins, 0)->u.cval);
6021 mkcopy(state, ins, RHS(ins, 0));
6025 static void simplify_neg(struct compile_state *state, struct triple *ins)
6027 if (is_const(RHS(ins, 0))) {
6029 left = read_const(state, ins, &RHS(ins, 0));
6030 mkconst(state, ins, -left);
6032 else if (RHS(ins, 0)->op == OP_NEG) {
6033 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6037 static void simplify_invert(struct compile_state *state, struct triple *ins)
6039 if (is_const(RHS(ins, 0))) {
6041 left = read_const(state, ins, &RHS(ins, 0));
6042 mkconst(state, ins, ~left);
6046 static void simplify_eq(struct compile_state *state, struct triple *ins)
6048 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6049 ulong_t left, right;
6050 left = read_const(state, ins, &RHS(ins, 0));
6051 right = read_const(state, ins, &RHS(ins, 1));
6052 mkconst(state, ins, left == right);
6054 else if (RHS(ins, 0) == RHS(ins, 1)) {
6055 mkconst(state, ins, 1);
6059 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6061 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6062 ulong_t left, right;
6063 left = read_const(state, ins, &RHS(ins, 0));
6064 right = read_const(state, ins, &RHS(ins, 1));
6065 mkconst(state, ins, left != right);
6067 else if (RHS(ins, 0) == RHS(ins, 1)) {
6068 mkconst(state, ins, 0);
6072 static void simplify_sless(struct compile_state *state, struct triple *ins)
6074 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6076 left = read_sconst(ins, &RHS(ins, 0));
6077 right = read_sconst(ins, &RHS(ins, 1));
6078 mkconst(state, ins, left < right);
6080 else if (RHS(ins, 0) == RHS(ins, 1)) {
6081 mkconst(state, ins, 0);
6085 static void simplify_uless(struct compile_state *state, struct triple *ins)
6087 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6088 ulong_t left, right;
6089 left = read_const(state, ins, &RHS(ins, 0));
6090 right = read_const(state, ins, &RHS(ins, 1));
6091 mkconst(state, ins, left < right);
6093 else if (is_zero(RHS(ins, 0))) {
6094 mkconst(state, ins, 1);
6096 else if (RHS(ins, 0) == RHS(ins, 1)) {
6097 mkconst(state, ins, 0);
6101 static void simplify_smore(struct compile_state *state, struct triple *ins)
6103 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6105 left = read_sconst(ins, &RHS(ins, 0));
6106 right = read_sconst(ins, &RHS(ins, 1));
6107 mkconst(state, ins, left > right);
6109 else if (RHS(ins, 0) == RHS(ins, 1)) {
6110 mkconst(state, ins, 0);
6114 static void simplify_umore(struct compile_state *state, struct triple *ins)
6116 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6117 ulong_t left, right;
6118 left = read_const(state, ins, &RHS(ins, 0));
6119 right = read_const(state, ins, &RHS(ins, 1));
6120 mkconst(state, ins, left > right);
6122 else if (is_zero(RHS(ins, 1))) {
6123 mkconst(state, ins, 1);
6125 else if (RHS(ins, 0) == RHS(ins, 1)) {
6126 mkconst(state, ins, 0);
6131 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6133 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6135 left = read_sconst(ins, &RHS(ins, 0));
6136 right = read_sconst(ins, &RHS(ins, 1));
6137 mkconst(state, ins, left <= right);
6139 else if (RHS(ins, 0) == RHS(ins, 1)) {
6140 mkconst(state, ins, 1);
6144 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6146 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6147 ulong_t left, right;
6148 left = read_const(state, ins, &RHS(ins, 0));
6149 right = read_const(state, ins, &RHS(ins, 1));
6150 mkconst(state, ins, left <= right);
6152 else if (is_zero(RHS(ins, 0))) {
6153 mkconst(state, ins, 1);
6155 else if (RHS(ins, 0) == RHS(ins, 1)) {
6156 mkconst(state, ins, 1);
6160 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6162 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6164 left = read_sconst(ins, &RHS(ins, 0));
6165 right = read_sconst(ins, &RHS(ins, 1));
6166 mkconst(state, ins, left >= right);
6168 else if (RHS(ins, 0) == RHS(ins, 1)) {
6169 mkconst(state, ins, 1);
6173 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6175 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6176 ulong_t left, right;
6177 left = read_const(state, ins, &RHS(ins, 0));
6178 right = read_const(state, ins, &RHS(ins, 1));
6179 mkconst(state, ins, left >= right);
6181 else if (is_zero(RHS(ins, 1))) {
6182 mkconst(state, ins, 1);
6184 else if (RHS(ins, 0) == RHS(ins, 1)) {
6185 mkconst(state, ins, 1);
6189 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6191 if (is_const(RHS(ins, 0))) {
6193 left = read_const(state, ins, &RHS(ins, 0));
6194 mkconst(state, ins, left == 0);
6196 /* Otherwise if I am the only user... */
6197 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6199 /* Invert a boolean operation */
6200 switch(RHS(ins, 0)->op) {
6201 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
6202 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
6203 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
6204 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
6205 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
6206 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
6207 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
6208 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
6209 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
6210 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
6211 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
6212 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
6218 mkcopy(state, ins, RHS(ins, 0));
6223 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6225 if (is_const(RHS(ins, 0))) {
6227 left = read_const(state, ins, &RHS(ins, 0));
6228 mkconst(state, ins, left != 0);
6230 else switch(RHS(ins, 0)->op) {
6231 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
6232 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
6233 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6234 mkcopy(state, ins, RHS(ins, 0));
6239 static void simplify_copy(struct compile_state *state, struct triple *ins)
6241 if (is_const(RHS(ins, 0))) {
6242 switch(RHS(ins, 0)->op) {
6246 left = read_const(state, ins, &RHS(ins, 0));
6247 mkconst(state, ins, left);
6252 struct triple *sdecl;
6254 sdecl = MISC(RHS(ins, 0), 0);
6255 offset = RHS(ins, 0)->u.cval;
6256 mkaddr_const(state, ins, sdecl, offset);
6260 internal_error(state, ins, "uknown constant");
6266 static void simplify_branch(struct compile_state *state, struct triple *ins)
6268 struct block *block;
6269 if (ins->op != OP_BRANCH) {
6270 internal_error(state, ins, "not branch");
6272 if (ins->use != 0) {
6273 internal_error(state, ins, "branch use");
6275 #warning "FIXME implement simplify branch."
6276 /* The challenge here with simplify branch is that I need to
6277 * make modifications to the control flow graph as well
6278 * as to the branch instruction itself.
6280 block = ins->u.block;
6282 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6283 struct triple *targ;
6285 value = read_const(state, ins, &RHS(ins, 0));
6286 unuse_triple(RHS(ins, 0), ins);
6287 targ = TARG(ins, 0);
6288 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6290 unuse_triple(ins->next, ins);
6291 TARG(ins, 0) = targ;
6294 unuse_triple(targ, ins);
6295 TARG(ins, 0) = ins->next;
6297 #warning "FIXME handle the case of making a branch unconditional"
6299 if (TARG(ins, 0) == ins->next) {
6300 unuse_triple(ins->next, ins);
6301 if (TRIPLE_RHS(ins->sizes)) {
6302 unuse_triple(RHS(ins, 0), ins);
6303 unuse_triple(ins->next, ins);
6305 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6308 internal_error(state, ins, "noop use != 0");
6310 #warning "FIXME handle the case of killing a branch"
6314 static void simplify_phi(struct compile_state *state, struct triple *ins)
6316 struct triple **expr;
6318 expr = triple_rhs(state, ins, 0);
6319 if (!*expr || !is_const(*expr)) {
6322 value = read_const(state, ins, expr);
6323 for(;expr;expr = triple_rhs(state, ins, expr)) {
6324 if (!*expr || !is_const(*expr)) {
6327 if (value != read_const(state, ins, expr)) {
6331 mkconst(state, ins, value);
6335 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6337 if (is_const(RHS(ins, 0))) {
6339 left = read_const(state, ins, &RHS(ins, 0));
6340 mkconst(state, ins, bsf(left));
6344 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6346 if (is_const(RHS(ins, 0))) {
6348 left = read_const(state, ins, &RHS(ins, 0));
6349 mkconst(state, ins, bsr(left));
6354 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6355 static const simplify_t table_simplify[] = {
6357 #define simplify_smul simplify_noop
6358 #define simplify_umul simplify_noop
6359 #define simplify_sdiv simplify_noop
6360 #define simplify_udiv simplify_noop
6361 #define simplify_smod simplify_noop
6362 #define simplify_umod simplify_noop
6365 #define simplify_add simplify_noop
6366 #define simplify_sub simplify_noop
6369 #define simplify_sl simplify_noop
6370 #define simplify_usr simplify_noop
6371 #define simplify_ssr simplify_noop
6374 #define simplify_and simplify_noop
6375 #define simplify_xor simplify_noop
6376 #define simplify_or simplify_noop
6379 #define simplify_pos simplify_noop
6380 #define simplify_neg simplify_noop
6381 #define simplify_invert simplify_noop
6385 #define simplify_eq simplify_noop
6386 #define simplify_noteq simplify_noop
6389 #define simplify_sless simplify_noop
6390 #define simplify_uless simplify_noop
6391 #define simplify_smore simplify_noop
6392 #define simplify_umore simplify_noop
6395 #define simplify_slesseq simplify_noop
6396 #define simplify_ulesseq simplify_noop
6397 #define simplify_smoreeq simplify_noop
6398 #define simplify_umoreeq simplify_noop
6401 #define simplify_lfalse simplify_noop
6404 #define simplify_ltrue simplify_noop
6408 #define simplify_copy simplify_noop
6412 #define simplify_branch simplify_noop
6416 #define simplify_phi simplify_noop
6420 #define simplify_bsf simplify_noop
6421 #define simplify_bsr simplify_noop
6424 [OP_SMUL ] = simplify_smul,
6425 [OP_UMUL ] = simplify_umul,
6426 [OP_SDIV ] = simplify_sdiv,
6427 [OP_UDIV ] = simplify_udiv,
6428 [OP_SMOD ] = simplify_smod,
6429 [OP_UMOD ] = simplify_umod,
6430 [OP_ADD ] = simplify_add,
6431 [OP_SUB ] = simplify_sub,
6432 [OP_SL ] = simplify_sl,
6433 [OP_USR ] = simplify_usr,
6434 [OP_SSR ] = simplify_ssr,
6435 [OP_AND ] = simplify_and,
6436 [OP_XOR ] = simplify_xor,
6437 [OP_OR ] = simplify_or,
6438 [OP_POS ] = simplify_pos,
6439 [OP_NEG ] = simplify_neg,
6440 [OP_INVERT ] = simplify_invert,
6442 [OP_EQ ] = simplify_eq,
6443 [OP_NOTEQ ] = simplify_noteq,
6444 [OP_SLESS ] = simplify_sless,
6445 [OP_ULESS ] = simplify_uless,
6446 [OP_SMORE ] = simplify_smore,
6447 [OP_UMORE ] = simplify_umore,
6448 [OP_SLESSEQ ] = simplify_slesseq,
6449 [OP_ULESSEQ ] = simplify_ulesseq,
6450 [OP_SMOREEQ ] = simplify_smoreeq,
6451 [OP_UMOREEQ ] = simplify_umoreeq,
6452 [OP_LFALSE ] = simplify_lfalse,
6453 [OP_LTRUE ] = simplify_ltrue,
6455 [OP_LOAD ] = simplify_noop,
6456 [OP_STORE ] = simplify_noop,
6458 [OP_NOOP ] = simplify_noop,
6460 [OP_INTCONST ] = simplify_noop,
6461 [OP_BLOBCONST ] = simplify_noop,
6462 [OP_ADDRCONST ] = simplify_noop,
6464 [OP_WRITE ] = simplify_noop,
6465 [OP_READ ] = simplify_noop,
6466 [OP_COPY ] = simplify_copy,
6467 [OP_PIECE ] = simplify_noop,
6468 [OP_ASM ] = simplify_noop,
6470 [OP_DOT ] = simplify_noop,
6471 [OP_VAL_VEC ] = simplify_noop,
6473 [OP_LIST ] = simplify_noop,
6474 [OP_BRANCH ] = simplify_branch,
6475 [OP_LABEL ] = simplify_noop,
6476 [OP_ADECL ] = simplify_noop,
6477 [OP_SDECL ] = simplify_noop,
6478 [OP_PHI ] = simplify_phi,
6480 [OP_INB ] = simplify_noop,
6481 [OP_INW ] = simplify_noop,
6482 [OP_INL ] = simplify_noop,
6483 [OP_OUTB ] = simplify_noop,
6484 [OP_OUTW ] = simplify_noop,
6485 [OP_OUTL ] = simplify_noop,
6486 [OP_BSF ] = simplify_bsf,
6487 [OP_BSR ] = simplify_bsr,
6488 [OP_RDMSR ] = simplify_noop,
6489 [OP_WRMSR ] = simplify_noop,
6490 [OP_HLT ] = simplify_noop,
6493 static void simplify(struct compile_state *state, struct triple *ins)
6496 simplify_t do_simplify;
6500 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6504 do_simplify = table_simplify[op];
6507 internal_error(state, ins, "cannot simplify op: %d %s\n",
6511 do_simplify(state, ins);
6512 } while(ins->op != op);
6515 static void simplify_all(struct compile_state *state)
6517 struct triple *ins, *first;
6518 first = RHS(state->main_function, 0);
6521 simplify(state, ins);
6523 } while(ins != first);
6528 * ============================
6531 static void register_builtin_function(struct compile_state *state,
6532 const char *name, int op, struct type *rtype, ...)
6534 struct type *ftype, *atype, *param, **next;
6535 struct triple *def, *arg, *result, *work, *last, *first;
6536 struct hash_entry *ident;
6537 struct file_state file;
6543 /* Dummy file state to get debug handling right */
6544 memset(&file, 0, sizeof(file));
6545 file.basename = "<built-in>";
6547 file.report_line = 1;
6548 file.report_name = file.basename;
6549 file.prev = state->file;
6550 state->file = &file;
6551 state->function = name;
6553 /* Find the Parameter count */
6554 valid_op(state, op);
6555 parameters = table_ops[op].rhs;
6556 if (parameters < 0 ) {
6557 internal_error(state, 0, "Invalid builtin parameter count");
6560 /* Find the function type */
6561 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6562 next = &ftype->right;
6563 va_start(args, rtype);
6564 for(i = 0; i < parameters; i++) {
6565 atype = va_arg(args, struct type *);
6569 *next = new_type(TYPE_PRODUCT, *next, atype);
6570 next = &((*next)->right);
6578 /* Generate the needed triples */
6579 def = triple(state, OP_LIST, ftype, 0, 0);
6580 first = label(state);
6581 RHS(def, 0) = first;
6583 /* Now string them together */
6584 param = ftype->right;
6585 for(i = 0; i < parameters; i++) {
6586 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6587 atype = param->left;
6591 arg = flatten(state, first, variable(state, atype));
6592 param = param->right;
6595 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6596 result = flatten(state, first, variable(state, rtype));
6598 MISC(def, 0) = result;
6599 work = new_triple(state, op, rtype, -1, parameters);
6600 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6601 RHS(work, i) = read_expr(state, arg);
6603 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6605 /* Populate the LHS with the target registers */
6606 work = flatten(state, first, work);
6607 work->type = &void_type;
6608 param = rtype->left;
6609 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6610 internal_error(state, 0, "Invalid result type");
6612 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6613 for(i = 0; i < rtype->elements; i++) {
6614 struct triple *piece;
6616 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6617 atype = param->left;
6619 if (!TYPE_ARITHMETIC(atype->type) &&
6620 !TYPE_PTR(atype->type)) {
6621 internal_error(state, 0, "Invalid lhs type");
6623 piece = triple(state, OP_PIECE, atype, work, 0);
6625 LHS(work, i) = piece;
6626 RHS(val, i) = piece;
6631 work = write_expr(state, result, work);
6633 work = flatten(state, first, work);
6634 last = flatten(state, first, label(state));
6635 name_len = strlen(name);
6636 ident = lookup(state, name, name_len);
6637 symbol(state, ident, &ident->sym_ident, def, ftype);
6639 state->file = file.prev;
6640 state->function = 0;
6642 fprintf(stdout, "\n");
6643 loc(stdout, state, 0);
6644 fprintf(stdout, "\n__________ builtin_function _________\n");
6645 print_triple(state, def);
6646 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6650 static struct type *partial_struct(struct compile_state *state,
6651 const char *field_name, struct type *type, struct type *rest)
6653 struct hash_entry *field_ident;
6654 struct type *result;
6657 field_name_len = strlen(field_name);
6658 field_ident = lookup(state, field_name, field_name_len);
6660 result = clone_type(0, type);
6661 result->field_ident = field_ident;
6664 result = new_type(TYPE_PRODUCT, result, rest);
6669 static struct type *register_builtin_type(struct compile_state *state,
6670 const char *name, struct type *type)
6672 struct hash_entry *ident;
6675 name_len = strlen(name);
6676 ident = lookup(state, name, name_len);
6678 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6679 ulong_t elements = 0;
6681 type = new_type(TYPE_STRUCT, type, 0);
6683 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6685 field = field->right;
6688 symbol(state, ident, &ident->sym_struct, 0, type);
6689 type->type_ident = ident;
6690 type->elements = elements;
6692 symbol(state, ident, &ident->sym_ident, 0, type);
6693 ident->tok = TOK_TYPE_NAME;
6698 static void register_builtins(struct compile_state *state)
6700 struct type *msr_type;
6702 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6704 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6706 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6709 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6710 &uchar_type, &ushort_type);
6711 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6712 &ushort_type, &ushort_type);
6713 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6714 &uint_type, &ushort_type);
6716 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6718 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6721 msr_type = register_builtin_type(state, "__builtin_msr_t",
6722 partial_struct(state, "lo", &ulong_type,
6723 partial_struct(state, "hi", &ulong_type, 0)));
6725 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6727 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6728 &ulong_type, &ulong_type, &ulong_type);
6730 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6734 static struct type *declarator(
6735 struct compile_state *state, struct type *type,
6736 struct hash_entry **ident, int need_ident);
6737 static void decl(struct compile_state *state, struct triple *first);
6738 static struct type *specifier_qualifier_list(struct compile_state *state);
6739 static int isdecl_specifier(int tok);
6740 static struct type *decl_specifiers(struct compile_state *state);
6741 static int istype(int tok);
6742 static struct triple *expr(struct compile_state *state);
6743 static struct triple *assignment_expr(struct compile_state *state);
6744 static struct type *type_name(struct compile_state *state);
6745 static void statement(struct compile_state *state, struct triple *fist);
6747 static struct triple *call_expr(
6748 struct compile_state *state, struct triple *func)
6751 struct type *param, *type;
6752 ulong_t pvals, index;
6754 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6755 error(state, 0, "Called object is not a function");
6757 if (func->op != OP_LIST) {
6758 internal_error(state, 0, "improper function");
6760 eat(state, TOK_LPAREN);
6761 /* Find the return type without any specifiers */
6762 type = clone_type(0, func->type->left);
6763 def = new_triple(state, OP_CALL, func->type, -1, -1);
6766 pvals = TRIPLE_RHS(def->sizes);
6767 MISC(def, 0) = func;
6769 param = func->type->right;
6770 for(index = 0; index < pvals; index++) {
6772 struct type *arg_type;
6773 val = read_expr(state, assignment_expr(state));
6775 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6776 arg_type = param->left;
6778 write_compatible(state, arg_type, val->type);
6779 RHS(def, index) = val;
6780 if (index != (pvals - 1)) {
6781 eat(state, TOK_COMMA);
6782 param = param->right;
6785 eat(state, TOK_RPAREN);
6790 static struct triple *character_constant(struct compile_state *state)
6794 const signed char *str, *end;
6797 eat(state, TOK_LIT_CHAR);
6798 tk = &state->token[0];
6799 str = tk->val.str + 1;
6800 str_len = tk->str_len - 2;
6802 error(state, 0, "empty character constant");
6804 end = str + str_len;
6805 c = char_value(state, &str, end);
6807 error(state, 0, "multibyte character constant not supported");
6809 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6813 static struct triple *string_constant(struct compile_state *state)
6818 const signed char *str, *end;
6819 signed char *buf, *ptr;
6823 type = new_type(TYPE_ARRAY, &char_type, 0);
6825 /* The while loop handles string concatenation */
6827 eat(state, TOK_LIT_STRING);
6828 tk = &state->token[0];
6829 str = tk->val.str + 1;
6830 str_len = tk->str_len - 2;
6832 error(state, 0, "negative string constant length");
6834 end = str + str_len;
6836 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6837 memcpy(buf, ptr, type->elements);
6838 ptr = buf + type->elements;
6840 *ptr++ = char_value(state, &str, end);
6842 type->elements = ptr - buf;
6843 } while(peek(state) == TOK_LIT_STRING);
6845 type->elements += 1;
6846 def = triple(state, OP_BLOBCONST, type, 0, 0);
6852 static struct triple *integer_constant(struct compile_state *state)
6861 eat(state, TOK_LIT_INT);
6862 tk = &state->token[0];
6864 decimal = (tk->val.str[0] != '0');
6865 val = strtoul(tk->val.str, &end, 0);
6866 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6867 error(state, 0, "Integer constant to large");
6870 if ((*end == 'u') || (*end == 'U')) {
6874 if ((*end == 'l') || (*end == 'L')) {
6878 if ((*end == 'u') || (*end == 'U')) {
6883 error(state, 0, "Junk at end of integer constant");
6890 if (!decimal && (val > LONG_MAX)) {
6896 if (val > UINT_MAX) {
6902 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6905 else if (!decimal && (val > LONG_MAX)) {
6908 else if (val > INT_MAX) {
6912 def = int_const(state, type, val);
6916 static struct triple *primary_expr(struct compile_state *state)
6924 struct hash_entry *ident;
6925 /* Here ident is either:
6928 * an enumeration constant.
6930 eat(state, TOK_IDENT);
6931 ident = state->token[0].ident;
6932 if (!ident->sym_ident) {
6933 error(state, 0, "%s undeclared", ident->name);
6935 def = ident->sym_ident->def;
6938 case TOK_ENUM_CONST:
6939 /* Here ident is an enumeration constant */
6940 eat(state, TOK_ENUM_CONST);
6945 eat(state, TOK_LPAREN);
6947 eat(state, TOK_RPAREN);
6950 def = integer_constant(state);
6953 eat(state, TOK_LIT_FLOAT);
6954 error(state, 0, "Floating point constants not supported");
6959 def = character_constant(state);
6961 case TOK_LIT_STRING:
6962 def = string_constant(state);
6966 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6971 static struct triple *postfix_expr(struct compile_state *state)
6975 def = primary_expr(state);
6977 struct triple *left;
6981 switch((tok = peek(state))) {
6983 eat(state, TOK_LBRACKET);
6984 def = mk_subscript_expr(state, left, expr(state));
6985 eat(state, TOK_RBRACKET);
6988 def = call_expr(state, def);
6992 struct hash_entry *field;
6993 eat(state, TOK_DOT);
6994 eat(state, TOK_IDENT);
6995 field = state->token[0].ident;
6996 def = deref_field(state, def, field);
7001 struct hash_entry *field;
7002 eat(state, TOK_ARROW);
7003 eat(state, TOK_IDENT);
7004 field = state->token[0].ident;
7005 def = mk_deref_expr(state, read_expr(state, def));
7006 def = deref_field(state, def, field);
7010 eat(state, TOK_PLUSPLUS);
7011 def = mk_post_inc_expr(state, left);
7013 case TOK_MINUSMINUS:
7014 eat(state, TOK_MINUSMINUS);
7015 def = mk_post_dec_expr(state, left);
7025 static struct triple *cast_expr(struct compile_state *state);
7027 static struct triple *unary_expr(struct compile_state *state)
7029 struct triple *def, *right;
7031 switch((tok = peek(state))) {
7033 eat(state, TOK_PLUSPLUS);
7034 def = mk_pre_inc_expr(state, unary_expr(state));
7036 case TOK_MINUSMINUS:
7037 eat(state, TOK_MINUSMINUS);
7038 def = mk_pre_dec_expr(state, unary_expr(state));
7041 eat(state, TOK_AND);
7042 def = mk_addr_expr(state, cast_expr(state), 0);
7045 eat(state, TOK_STAR);
7046 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7049 eat(state, TOK_PLUS);
7050 right = read_expr(state, cast_expr(state));
7051 arithmetic(state, right);
7052 def = integral_promotion(state, right);
7055 eat(state, TOK_MINUS);
7056 right = read_expr(state, cast_expr(state));
7057 arithmetic(state, right);
7058 def = integral_promotion(state, right);
7059 def = triple(state, OP_NEG, def->type, def, 0);
7062 eat(state, TOK_TILDE);
7063 right = read_expr(state, cast_expr(state));
7064 integral(state, right);
7065 def = integral_promotion(state, right);
7066 def = triple(state, OP_INVERT, def->type, def, 0);
7069 eat(state, TOK_BANG);
7070 right = read_expr(state, cast_expr(state));
7072 def = lfalse_expr(state, right);
7078 eat(state, TOK_SIZEOF);
7080 tok2 = peek2(state);
7081 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7082 eat(state, TOK_LPAREN);
7083 type = type_name(state);
7084 eat(state, TOK_RPAREN);
7087 struct triple *expr;
7088 expr = unary_expr(state);
7090 release_expr(state, expr);
7092 def = int_const(state, &ulong_type, size_of(state, type));
7099 eat(state, TOK_ALIGNOF);
7101 tok2 = peek2(state);
7102 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7103 eat(state, TOK_LPAREN);
7104 type = type_name(state);
7105 eat(state, TOK_RPAREN);
7108 struct triple *expr;
7109 expr = unary_expr(state);
7111 release_expr(state, expr);
7113 def = int_const(state, &ulong_type, align_of(state, type));
7117 def = postfix_expr(state);
7123 static struct triple *cast_expr(struct compile_state *state)
7128 tok2 = peek2(state);
7129 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7131 eat(state, TOK_LPAREN);
7132 type = type_name(state);
7133 eat(state, TOK_RPAREN);
7134 def = read_expr(state, cast_expr(state));
7135 def = triple(state, OP_COPY, type, def, 0);
7138 def = unary_expr(state);
7143 static struct triple *mult_expr(struct compile_state *state)
7147 def = cast_expr(state);
7149 struct triple *left, *right;
7150 struct type *result_type;
7153 switch(tok = (peek(state))) {
7157 left = read_expr(state, def);
7158 arithmetic(state, left);
7162 right = read_expr(state, cast_expr(state));
7163 arithmetic(state, right);
7165 result_type = arithmetic_result(state, left, right);
7166 sign = is_signed(result_type);
7169 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7170 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
7171 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
7173 def = triple(state, op, result_type, left, right);
7183 static struct triple *add_expr(struct compile_state *state)
7187 def = mult_expr(state);
7190 switch( peek(state)) {
7192 eat(state, TOK_PLUS);
7193 def = mk_add_expr(state, def, mult_expr(state));
7196 eat(state, TOK_MINUS);
7197 def = mk_sub_expr(state, def, mult_expr(state));
7207 static struct triple *shift_expr(struct compile_state *state)
7211 def = add_expr(state);
7213 struct triple *left, *right;
7216 switch((tok = peek(state))) {
7219 left = read_expr(state, def);
7220 integral(state, left);
7221 left = integral_promotion(state, left);
7225 right = read_expr(state, add_expr(state));
7226 integral(state, right);
7227 right = integral_promotion(state, right);
7229 op = (tok == TOK_SL)? OP_SL :
7230 is_signed(left->type)? OP_SSR: OP_USR;
7232 def = triple(state, op, left->type, left, right);
7242 static struct triple *relational_expr(struct compile_state *state)
7244 #warning "Extend relational exprs to work on more than arithmetic types"
7247 def = shift_expr(state);
7249 struct triple *left, *right;
7250 struct type *arg_type;
7253 switch((tok = peek(state))) {
7258 left = read_expr(state, def);
7259 arithmetic(state, left);
7263 right = read_expr(state, shift_expr(state));
7264 arithmetic(state, right);
7266 arg_type = arithmetic_result(state, left, right);
7267 sign = is_signed(arg_type);
7270 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7271 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7272 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7273 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7275 def = triple(state, op, &int_type, left, right);
7285 static struct triple *equality_expr(struct compile_state *state)
7287 #warning "Extend equality exprs to work on more than arithmetic types"
7290 def = relational_expr(state);
7292 struct triple *left, *right;
7295 switch((tok = peek(state))) {
7298 left = read_expr(state, def);
7299 arithmetic(state, left);
7301 right = read_expr(state, relational_expr(state));
7302 arithmetic(state, right);
7303 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7304 def = triple(state, op, &int_type, left, right);
7314 static struct triple *and_expr(struct compile_state *state)
7317 def = equality_expr(state);
7318 while(peek(state) == TOK_AND) {
7319 struct triple *left, *right;
7320 struct type *result_type;
7321 left = read_expr(state, def);
7322 integral(state, left);
7323 eat(state, TOK_AND);
7324 right = read_expr(state, equality_expr(state));
7325 integral(state, right);
7326 result_type = arithmetic_result(state, left, right);
7327 def = triple(state, OP_AND, result_type, left, right);
7332 static struct triple *xor_expr(struct compile_state *state)
7335 def = and_expr(state);
7336 while(peek(state) == TOK_XOR) {
7337 struct triple *left, *right;
7338 struct type *result_type;
7339 left = read_expr(state, def);
7340 integral(state, left);
7341 eat(state, TOK_XOR);
7342 right = read_expr(state, and_expr(state));
7343 integral(state, right);
7344 result_type = arithmetic_result(state, left, right);
7345 def = triple(state, OP_XOR, result_type, left, right);
7350 static struct triple *or_expr(struct compile_state *state)
7353 def = xor_expr(state);
7354 while(peek(state) == TOK_OR) {
7355 struct triple *left, *right;
7356 struct type *result_type;
7357 left = read_expr(state, def);
7358 integral(state, left);
7360 right = read_expr(state, xor_expr(state));
7361 integral(state, right);
7362 result_type = arithmetic_result(state, left, right);
7363 def = triple(state, OP_OR, result_type, left, right);
7368 static struct triple *land_expr(struct compile_state *state)
7371 def = or_expr(state);
7372 while(peek(state) == TOK_LOGAND) {
7373 struct triple *left, *right;
7374 left = read_expr(state, def);
7376 eat(state, TOK_LOGAND);
7377 right = read_expr(state, or_expr(state));
7380 def = triple(state, OP_LAND, &int_type,
7381 ltrue_expr(state, left),
7382 ltrue_expr(state, right));
7387 static struct triple *lor_expr(struct compile_state *state)
7390 def = land_expr(state);
7391 while(peek(state) == TOK_LOGOR) {
7392 struct triple *left, *right;
7393 left = read_expr(state, def);
7395 eat(state, TOK_LOGOR);
7396 right = read_expr(state, land_expr(state));
7399 def = triple(state, OP_LOR, &int_type,
7400 ltrue_expr(state, left),
7401 ltrue_expr(state, right));
7406 static struct triple *conditional_expr(struct compile_state *state)
7409 def = lor_expr(state);
7410 if (peek(state) == TOK_QUEST) {
7411 struct triple *test, *left, *right;
7413 test = ltrue_expr(state, read_expr(state, def));
7414 eat(state, TOK_QUEST);
7415 left = read_expr(state, expr(state));
7416 eat(state, TOK_COLON);
7417 right = read_expr(state, conditional_expr(state));
7419 def = cond_expr(state, test, left, right);
7424 static struct triple *eval_const_expr(
7425 struct compile_state *state, struct triple *expr)
7428 struct triple *head, *ptr;
7429 head = label(state); /* dummy initial triple */
7430 flatten(state, head, expr);
7431 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7432 simplify(state, ptr);
7434 /* Remove the constant value the tail of the list */
7436 def->prev->next = def->next;
7437 def->next->prev = def->prev;
7438 def->next = def->prev = def;
7439 if (!is_const(def)) {
7440 internal_error(state, 0, "Not a constant expression");
7442 /* Free the intermediate expressions */
7443 while(head->next != head) {
7444 release_triple(state, head->next);
7446 free_triple(state, head);
7450 static struct triple *constant_expr(struct compile_state *state)
7452 return eval_const_expr(state, conditional_expr(state));
7455 static struct triple *assignment_expr(struct compile_state *state)
7457 struct triple *def, *left, *right;
7459 /* The C grammer in K&R shows assignment expressions
7460 * only taking unary expressions as input on their
7461 * left hand side. But specifies the precedence of
7462 * assignemnt as the lowest operator except for comma.
7464 * Allowing conditional expressions on the left hand side
7465 * of an assignement results in a grammar that accepts
7466 * a larger set of statements than standard C. As long
7467 * as the subset of the grammar that is standard C behaves
7468 * correctly this should cause no problems.
7470 * For the extra token strings accepted by the grammar
7471 * none of them should produce a valid lvalue, so they
7472 * should not produce functioning programs.
7474 * GCC has this bug as well, so surprises should be minimal.
7476 def = conditional_expr(state);
7478 switch((tok = peek(state))) {
7480 lvalue(state, left);
7482 def = write_expr(state, left,
7483 read_expr(state, assignment_expr(state)));
7488 lvalue(state, left);
7489 arithmetic(state, left);
7491 right = read_expr(state, assignment_expr(state));
7492 arithmetic(state, right);
7494 sign = is_signed(left->type);
7497 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7498 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7499 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7501 def = write_expr(state, left,
7502 triple(state, op, left->type,
7503 read_expr(state, left), right));
7506 lvalue(state, left);
7507 eat(state, TOK_PLUSEQ);
7508 def = write_expr(state, left,
7509 mk_add_expr(state, left, assignment_expr(state)));
7512 lvalue(state, left);
7513 eat(state, TOK_MINUSEQ);
7514 def = write_expr(state, left,
7515 mk_sub_expr(state, left, assignment_expr(state)));
7522 lvalue(state, left);
7523 integral(state, left);
7525 right = read_expr(state, assignment_expr(state));
7526 integral(state, right);
7527 right = integral_promotion(state, right);
7528 sign = is_signed(left->type);
7531 case TOK_SLEQ: op = OP_SL; break;
7532 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7533 case TOK_ANDEQ: op = OP_AND; break;
7534 case TOK_XOREQ: op = OP_XOR; break;
7535 case TOK_OREQ: op = OP_OR; break;
7537 def = write_expr(state, left,
7538 triple(state, op, left->type,
7539 read_expr(state, left), right));
7545 static struct triple *expr(struct compile_state *state)
7548 def = assignment_expr(state);
7549 while(peek(state) == TOK_COMMA) {
7550 struct triple *left, *right;
7552 eat(state, TOK_COMMA);
7553 right = assignment_expr(state);
7554 def = triple(state, OP_COMMA, right->type, left, right);
7559 static void expr_statement(struct compile_state *state, struct triple *first)
7561 if (peek(state) != TOK_SEMI) {
7562 flatten(state, first, expr(state));
7564 eat(state, TOK_SEMI);
7567 static void if_statement(struct compile_state *state, struct triple *first)
7569 struct triple *test, *jmp1, *jmp2, *middle, *end;
7571 jmp1 = jmp2 = middle = 0;
7573 eat(state, TOK_LPAREN);
7576 /* Cleanup and invert the test */
7577 test = lfalse_expr(state, read_expr(state, test));
7578 eat(state, TOK_RPAREN);
7579 /* Generate the needed pieces */
7580 middle = label(state);
7581 jmp1 = branch(state, middle, test);
7582 /* Thread the pieces together */
7583 flatten(state, first, test);
7584 flatten(state, first, jmp1);
7585 flatten(state, first, label(state));
7586 statement(state, first);
7587 if (peek(state) == TOK_ELSE) {
7588 eat(state, TOK_ELSE);
7589 /* Generate the rest of the pieces */
7591 jmp2 = branch(state, end, 0);
7592 /* Thread them together */
7593 flatten(state, first, jmp2);
7594 flatten(state, first, middle);
7595 statement(state, first);
7596 flatten(state, first, end);
7599 flatten(state, first, middle);
7603 static void for_statement(struct compile_state *state, struct triple *first)
7605 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7606 struct triple *label1, *label2, *label3;
7607 struct hash_entry *ident;
7609 eat(state, TOK_FOR);
7610 eat(state, TOK_LPAREN);
7611 head = test = tail = jmp1 = jmp2 = 0;
7612 if (peek(state) != TOK_SEMI) {
7615 eat(state, TOK_SEMI);
7616 if (peek(state) != TOK_SEMI) {
7619 test = ltrue_expr(state, read_expr(state, test));
7621 eat(state, TOK_SEMI);
7622 if (peek(state) != TOK_RPAREN) {
7625 eat(state, TOK_RPAREN);
7626 /* Generate the needed pieces */
7627 label1 = label(state);
7628 label2 = label(state);
7629 label3 = label(state);
7631 jmp1 = branch(state, label3, 0);
7632 jmp2 = branch(state, label1, test);
7635 jmp2 = branch(state, label1, 0);
7638 /* Remember where break and continue go */
7640 ident = state->i_break;
7641 symbol(state, ident, &ident->sym_ident, end, end->type);
7642 ident = state->i_continue;
7643 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7644 /* Now include the body */
7645 flatten(state, first, head);
7646 flatten(state, first, jmp1);
7647 flatten(state, first, label1);
7648 statement(state, first);
7649 flatten(state, first, label2);
7650 flatten(state, first, tail);
7651 flatten(state, first, label3);
7652 flatten(state, first, test);
7653 flatten(state, first, jmp2);
7654 flatten(state, first, end);
7655 /* Cleanup the break/continue scope */
7659 static void while_statement(struct compile_state *state, struct triple *first)
7661 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7662 struct hash_entry *ident;
7663 eat(state, TOK_WHILE);
7664 eat(state, TOK_LPAREN);
7667 test = ltrue_expr(state, read_expr(state, test));
7668 eat(state, TOK_RPAREN);
7669 /* Generate the needed pieces */
7670 label1 = label(state);
7671 label2 = label(state);
7672 jmp1 = branch(state, label2, 0);
7673 jmp2 = branch(state, label1, test);
7675 /* Remember where break and continue go */
7677 ident = state->i_break;
7678 symbol(state, ident, &ident->sym_ident, end, end->type);
7679 ident = state->i_continue;
7680 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7681 /* Thread them together */
7682 flatten(state, first, jmp1);
7683 flatten(state, first, label1);
7684 statement(state, first);
7685 flatten(state, first, label2);
7686 flatten(state, first, test);
7687 flatten(state, first, jmp2);
7688 flatten(state, first, end);
7689 /* Cleanup the break/continue scope */
7693 static void do_statement(struct compile_state *state, struct triple *first)
7695 struct triple *label1, *label2, *test, *end;
7696 struct hash_entry *ident;
7698 /* Generate the needed pieces */
7699 label1 = label(state);
7700 label2 = label(state);
7702 /* Remember where break and continue go */
7704 ident = state->i_break;
7705 symbol(state, ident, &ident->sym_ident, end, end->type);
7706 ident = state->i_continue;
7707 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7708 /* Now include the body */
7709 flatten(state, first, label1);
7710 statement(state, first);
7711 /* Cleanup the break/continue scope */
7713 /* Eat the rest of the loop */
7714 eat(state, TOK_WHILE);
7715 eat(state, TOK_LPAREN);
7716 test = read_expr(state, expr(state));
7718 eat(state, TOK_RPAREN);
7719 eat(state, TOK_SEMI);
7720 /* Thread the pieces together */
7721 test = ltrue_expr(state, test);
7722 flatten(state, first, label2);
7723 flatten(state, first, test);
7724 flatten(state, first, branch(state, label1, test));
7725 flatten(state, first, end);
7729 static void return_statement(struct compile_state *state, struct triple *first)
7731 struct triple *jmp, *mv, *dest, *var, *val;
7733 eat(state, TOK_RETURN);
7735 #warning "FIXME implement a more general excess branch elimination"
7737 /* If we have a return value do some more work */
7738 if (peek(state) != TOK_SEMI) {
7739 val = read_expr(state, expr(state));
7741 eat(state, TOK_SEMI);
7743 /* See if this last statement in a function */
7744 last = ((peek(state) == TOK_RBRACE) &&
7745 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7747 /* Find the return variable */
7748 var = MISC(state->main_function, 0);
7749 /* Find the return destination */
7750 dest = RHS(state->main_function, 0)->prev;
7752 /* If needed generate a jump instruction */
7754 jmp = branch(state, dest, 0);
7756 /* If needed generate an assignment instruction */
7758 mv = write_expr(state, var, val);
7760 /* Now put the code together */
7762 flatten(state, first, mv);
7763 flatten(state, first, jmp);
7766 flatten(state, first, jmp);
7770 static void break_statement(struct compile_state *state, struct triple *first)
7772 struct triple *dest;
7773 eat(state, TOK_BREAK);
7774 eat(state, TOK_SEMI);
7775 if (!state->i_break->sym_ident) {
7776 error(state, 0, "break statement not within loop or switch");
7778 dest = state->i_break->sym_ident->def;
7779 flatten(state, first, branch(state, dest, 0));
7782 static void continue_statement(struct compile_state *state, struct triple *first)
7784 struct triple *dest;
7785 eat(state, TOK_CONTINUE);
7786 eat(state, TOK_SEMI);
7787 if (!state->i_continue->sym_ident) {
7788 error(state, 0, "continue statement outside of a loop");
7790 dest = state->i_continue->sym_ident->def;
7791 flatten(state, first, branch(state, dest, 0));
7794 static void goto_statement(struct compile_state *state, struct triple *first)
7797 eat(state, TOK_GOTO);
7798 eat(state, TOK_IDENT);
7799 eat(state, TOK_SEMI);
7800 error(state, 0, "goto is not implemeted");
7804 static void labeled_statement(struct compile_state *state, struct triple *first)
7807 eat(state, TOK_IDENT);
7808 eat(state, TOK_COLON);
7809 statement(state, first);
7810 error(state, 0, "labeled statements are not implemented");
7814 static void switch_statement(struct compile_state *state, struct triple *first)
7817 eat(state, TOK_SWITCH);
7818 eat(state, TOK_LPAREN);
7820 eat(state, TOK_RPAREN);
7821 statement(state, first);
7822 error(state, 0, "switch statements are not implemented");
7826 static void case_statement(struct compile_state *state, struct triple *first)
7829 eat(state, TOK_CASE);
7830 constant_expr(state);
7831 eat(state, TOK_COLON);
7832 statement(state, first);
7833 error(state, 0, "case statements are not implemented");
7837 static void default_statement(struct compile_state *state, struct triple *first)
7840 eat(state, TOK_DEFAULT);
7841 eat(state, TOK_COLON);
7842 statement(state, first);
7843 error(state, 0, "default statements are not implemented");
7847 static void asm_statement(struct compile_state *state, struct triple *first)
7849 struct asm_info *info;
7851 struct triple *constraint;
7852 struct triple *expr;
7853 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7854 struct triple *def, *asm_str;
7855 int out, in, clobbers, more, colons, i;
7857 eat(state, TOK_ASM);
7858 /* For now ignore the qualifiers */
7859 switch(peek(state)) {
7861 eat(state, TOK_CONST);
7864 eat(state, TOK_VOLATILE);
7867 eat(state, TOK_LPAREN);
7868 asm_str = string_constant(state);
7871 out = in = clobbers = 0;
7873 if ((colons == 0) && (peek(state) == TOK_COLON)) {
7874 eat(state, TOK_COLON);
7876 more = (peek(state) == TOK_LIT_STRING);
7879 struct triple *constraint;
7882 if (out > MAX_LHS) {
7883 error(state, 0, "Maximum output count exceeded.");
7885 constraint = string_constant(state);
7886 str = constraint->u.blob;
7887 if (str[0] != '=') {
7888 error(state, 0, "Output constraint does not start with =");
7890 constraint->u.blob = str + 1;
7891 eat(state, TOK_LPAREN);
7892 var = conditional_expr(state);
7893 eat(state, TOK_RPAREN);
7896 out_param[out].constraint = constraint;
7897 out_param[out].expr = var;
7898 if (peek(state) == TOK_COMMA) {
7899 eat(state, TOK_COMMA);
7906 if ((colons == 1) && (peek(state) == TOK_COLON)) {
7907 eat(state, TOK_COLON);
7909 more = (peek(state) == TOK_LIT_STRING);
7912 struct triple *constraint;
7916 error(state, 0, "Maximum input count exceeded.");
7918 constraint = string_constant(state);
7919 str = constraint->u.blob;
7920 if (digitp(str[0] && str[1] == '\0')) {
7922 val = digval(str[0]);
7923 if ((val < 0) || (val >= out)) {
7924 error(state, 0, "Invalid input constraint %d", val);
7927 eat(state, TOK_LPAREN);
7928 val = conditional_expr(state);
7929 eat(state, TOK_RPAREN);
7931 in_param[in].constraint = constraint;
7932 in_param[in].expr = val;
7933 if (peek(state) == TOK_COMMA) {
7934 eat(state, TOK_COMMA);
7942 if ((colons == 2) && (peek(state) == TOK_COLON)) {
7943 eat(state, TOK_COLON);
7945 more = (peek(state) == TOK_LIT_STRING);
7947 struct triple *clobber;
7949 if ((clobbers + out) > MAX_LHS) {
7950 error(state, 0, "Maximum clobber limit exceeded.");
7952 clobber = string_constant(state);
7953 eat(state, TOK_RPAREN);
7955 clob_param[clobbers].constraint = clobber;
7956 if (peek(state) == TOK_COMMA) {
7957 eat(state, TOK_COMMA);
7963 eat(state, TOK_RPAREN);
7964 eat(state, TOK_SEMI);
7967 info = xcmalloc(sizeof(*info), "asm_info");
7968 info->str = asm_str->u.blob;
7969 free_triple(state, asm_str);
7971 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
7972 def->u.ainfo = info;
7974 /* Find the register constraints */
7975 for(i = 0; i < out; i++) {
7976 struct triple *constraint;
7977 constraint = out_param[i].constraint;
7978 info->tmpl.lhs[i] = arch_reg_constraint(state,
7979 out_param[i].expr->type, constraint->u.blob);
7980 free_triple(state, constraint);
7982 for(; i - out < clobbers; i++) {
7983 struct triple *constraint;
7984 constraint = clob_param[i - out].constraint;
7985 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
7986 free_triple(state, constraint);
7988 for(i = 0; i < in; i++) {
7989 struct triple *constraint;
7991 constraint = in_param[i].constraint;
7992 str = constraint->u.blob;
7993 if (digitp(str[0]) && str[1] == '\0') {
7994 struct reg_info cinfo;
7996 val = digval(str[0]);
7997 cinfo.reg = info->tmpl.lhs[val].reg;
7998 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
7999 cinfo.regcm &= info->tmpl.lhs[val].regcm;
8000 if (cinfo.reg == REG_UNSET) {
8001 cinfo.reg = REG_VIRT0 + val;
8003 if (cinfo.regcm == 0) {
8004 error(state, 0, "No registers for %d", val);
8006 info->tmpl.lhs[val] = cinfo;
8007 info->tmpl.rhs[i] = cinfo;
8010 info->tmpl.rhs[i] = arch_reg_constraint(state,
8011 in_param[i].expr->type, str);
8013 free_triple(state, constraint);
8016 /* Now build the helper expressions */
8017 for(i = 0; i < in; i++) {
8018 RHS(def, i) = read_expr(state,in_param[i].expr);
8020 flatten(state, first, def);
8021 for(i = 0; i < out; i++) {
8022 struct triple *piece;
8023 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8025 LHS(def, i) = piece;
8026 flatten(state, first,
8027 write_expr(state, out_param[i].expr, piece));
8029 for(; i - out < clobbers; i++) {
8030 struct triple *piece;
8031 piece = triple(state, OP_PIECE, &void_type, def, 0);
8033 LHS(def, i) = piece;
8034 flatten(state, first, piece);
8039 static int isdecl(int tok)
8062 case TOK_TYPE_NAME: /* typedef name */
8069 static void compound_statement(struct compile_state *state, struct triple *first)
8071 eat(state, TOK_LBRACE);
8074 /* statement-list opt */
8075 while (peek(state) != TOK_RBRACE) {
8076 statement(state, first);
8079 eat(state, TOK_RBRACE);
8082 static void statement(struct compile_state *state, struct triple *first)
8086 if (tok == TOK_LBRACE) {
8087 compound_statement(state, first);
8089 else if (tok == TOK_IF) {
8090 if_statement(state, first);
8092 else if (tok == TOK_FOR) {
8093 for_statement(state, first);
8095 else if (tok == TOK_WHILE) {
8096 while_statement(state, first);
8098 else if (tok == TOK_DO) {
8099 do_statement(state, first);
8101 else if (tok == TOK_RETURN) {
8102 return_statement(state, first);
8104 else if (tok == TOK_BREAK) {
8105 break_statement(state, first);
8107 else if (tok == TOK_CONTINUE) {
8108 continue_statement(state, first);
8110 else if (tok == TOK_GOTO) {
8111 goto_statement(state, first);
8113 else if (tok == TOK_SWITCH) {
8114 switch_statement(state, first);
8116 else if (tok == TOK_ASM) {
8117 asm_statement(state, first);
8119 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8120 labeled_statement(state, first);
8122 else if (tok == TOK_CASE) {
8123 case_statement(state, first);
8125 else if (tok == TOK_DEFAULT) {
8126 default_statement(state, first);
8128 else if (isdecl(tok)) {
8129 /* This handles C99 intermixing of statements and decls */
8133 expr_statement(state, first);
8137 static struct type *param_decl(struct compile_state *state)
8140 struct hash_entry *ident;
8141 /* Cheat so the declarator will know we are not global */
8144 type = decl_specifiers(state);
8145 type = declarator(state, type, &ident, 0);
8146 type->field_ident = ident;
8151 static struct type *param_type_list(struct compile_state *state, struct type *type)
8153 struct type *ftype, **next;
8154 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8155 next = &ftype->right;
8156 while(peek(state) == TOK_COMMA) {
8157 eat(state, TOK_COMMA);
8158 if (peek(state) == TOK_DOTS) {
8159 eat(state, TOK_DOTS);
8160 error(state, 0, "variadic functions not supported");
8163 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8164 next = &((*next)->right);
8171 static struct type *type_name(struct compile_state *state)
8174 type = specifier_qualifier_list(state);
8175 /* abstract-declarator (may consume no tokens) */
8176 type = declarator(state, type, 0, 0);
8180 static struct type *direct_declarator(
8181 struct compile_state *state, struct type *type,
8182 struct hash_entry **ident, int need_ident)
8187 arrays_complete(state, type);
8188 switch(peek(state)) {
8190 eat(state, TOK_IDENT);
8192 error(state, 0, "Unexpected identifier found");
8194 /* The name of what we are declaring */
8195 *ident = state->token[0].ident;
8198 eat(state, TOK_LPAREN);
8199 outer = declarator(state, type, ident, need_ident);
8200 eat(state, TOK_RPAREN);
8204 error(state, 0, "Identifier expected");
8210 arrays_complete(state, type);
8211 switch(peek(state)) {
8213 eat(state, TOK_LPAREN);
8214 type = param_type_list(state, type);
8215 eat(state, TOK_RPAREN);
8219 unsigned int qualifiers;
8220 struct triple *value;
8222 eat(state, TOK_LBRACKET);
8223 if (peek(state) != TOK_RBRACKET) {
8224 value = constant_expr(state);
8225 integral(state, value);
8227 eat(state, TOK_RBRACKET);
8229 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8230 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8232 type->elements = value->u.cval;
8233 free_triple(state, value);
8235 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8247 arrays_complete(state, type);
8249 for(inner = outer; inner->left; inner = inner->left)
8257 static struct type *declarator(
8258 struct compile_state *state, struct type *type,
8259 struct hash_entry **ident, int need_ident)
8261 while(peek(state) == TOK_STAR) {
8262 eat(state, TOK_STAR);
8263 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8265 type = direct_declarator(state, type, ident, need_ident);
8270 static struct type *typedef_name(
8271 struct compile_state *state, unsigned int specifiers)
8273 struct hash_entry *ident;
8275 eat(state, TOK_TYPE_NAME);
8276 ident = state->token[0].ident;
8277 type = ident->sym_ident->type;
8278 specifiers |= type->type & QUAL_MASK;
8279 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8280 (type->type & (STOR_MASK | QUAL_MASK))) {
8281 type = clone_type(specifiers, type);
8286 static struct type *enum_specifier(
8287 struct compile_state *state, unsigned int specifiers)
8293 eat(state, TOK_ENUM);
8295 if (tok == TOK_IDENT) {
8296 eat(state, TOK_IDENT);
8298 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8299 eat(state, TOK_LBRACE);
8301 eat(state, TOK_IDENT);
8302 if (peek(state) == TOK_EQ) {
8304 constant_expr(state);
8306 if (peek(state) == TOK_COMMA) {
8307 eat(state, TOK_COMMA);
8309 } while(peek(state) != TOK_RBRACE);
8310 eat(state, TOK_RBRACE);
8317 static struct type *struct_declarator(
8318 struct compile_state *state, struct type *type, struct hash_entry **ident)
8321 #warning "struct_declarator is complicated because of bitfields, kill them?"
8323 if (tok != TOK_COLON) {
8324 type = declarator(state, type, ident, 1);
8326 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8327 eat(state, TOK_COLON);
8328 constant_expr(state);
8335 static struct type *struct_or_union_specifier(
8336 struct compile_state *state, unsigned int specifiers)
8338 struct type *struct_type;
8339 struct hash_entry *ident;
8340 unsigned int type_join;
8344 switch(peek(state)) {
8346 eat(state, TOK_STRUCT);
8347 type_join = TYPE_PRODUCT;
8350 eat(state, TOK_UNION);
8351 type_join = TYPE_OVERLAP;
8352 error(state, 0, "unions not yet supported\n");
8355 eat(state, TOK_STRUCT);
8356 type_join = TYPE_PRODUCT;
8360 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8362 ident = state->token[0].ident;
8364 if (!ident || (peek(state) == TOK_LBRACE)) {
8367 eat(state, TOK_LBRACE);
8369 struct type *base_type;
8372 base_type = specifier_qualifier_list(state);
8373 next = &struct_type;
8376 struct hash_entry *fident;
8378 type = declarator(state, base_type, &fident, 1);
8380 if (peek(state) == TOK_COMMA) {
8382 eat(state, TOK_COMMA);
8384 type = clone_type(0, type);
8385 type->field_ident = fident;
8387 *next = new_type(type_join, *next, type);
8388 next = &((*next)->right);
8393 eat(state, TOK_SEMI);
8394 } while(peek(state) != TOK_RBRACE);
8395 eat(state, TOK_RBRACE);
8396 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
8397 struct_type->type_ident = ident;
8398 struct_type->elements = elements;
8399 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8401 if (ident && ident->sym_struct) {
8402 struct_type = ident->sym_struct->type;
8404 else if (ident && !ident->sym_struct) {
8405 error(state, 0, "struct %s undeclared", ident->name);
8410 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8412 unsigned int specifiers;
8413 switch(peek(state)) {
8415 eat(state, TOK_AUTO);
8416 specifiers = STOR_AUTO;
8419 eat(state, TOK_REGISTER);
8420 specifiers = STOR_REGISTER;
8423 eat(state, TOK_STATIC);
8424 specifiers = STOR_STATIC;
8427 eat(state, TOK_EXTERN);
8428 specifiers = STOR_EXTERN;
8431 eat(state, TOK_TYPEDEF);
8432 specifiers = STOR_TYPEDEF;
8435 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8436 specifiers = STOR_STATIC;
8439 specifiers = STOR_AUTO;
8445 static unsigned int function_specifier_opt(struct compile_state *state)
8447 /* Ignore the inline keyword */
8448 unsigned int specifiers;
8450 switch(peek(state)) {
8452 eat(state, TOK_INLINE);
8453 specifiers = STOR_INLINE;
8458 static unsigned int type_qualifiers(struct compile_state *state)
8460 unsigned int specifiers;
8463 specifiers = QUAL_NONE;
8465 switch(peek(state)) {
8467 eat(state, TOK_CONST);
8468 specifiers = QUAL_CONST;
8471 eat(state, TOK_VOLATILE);
8472 specifiers = QUAL_VOLATILE;
8475 eat(state, TOK_RESTRICT);
8476 specifiers = QUAL_RESTRICT;
8486 static struct type *type_specifier(
8487 struct compile_state *state, unsigned int spec)
8491 switch(peek(state)) {
8493 eat(state, TOK_VOID);
8494 type = new_type(TYPE_VOID | spec, 0, 0);
8497 eat(state, TOK_CHAR);
8498 type = new_type(TYPE_CHAR | spec, 0, 0);
8501 eat(state, TOK_SHORT);
8502 if (peek(state) == TOK_INT) {
8503 eat(state, TOK_INT);
8505 type = new_type(TYPE_SHORT | spec, 0, 0);
8508 eat(state, TOK_INT);
8509 type = new_type(TYPE_INT | spec, 0, 0);
8512 eat(state, TOK_LONG);
8513 switch(peek(state)) {
8515 eat(state, TOK_LONG);
8516 error(state, 0, "long long not supported");
8519 eat(state, TOK_DOUBLE);
8520 error(state, 0, "long double not supported");
8523 eat(state, TOK_INT);
8524 type = new_type(TYPE_LONG | spec, 0, 0);
8527 type = new_type(TYPE_LONG | spec, 0, 0);
8532 eat(state, TOK_FLOAT);
8533 error(state, 0, "type float not supported");
8536 eat(state, TOK_DOUBLE);
8537 error(state, 0, "type double not supported");
8540 eat(state, TOK_SIGNED);
8541 switch(peek(state)) {
8543 eat(state, TOK_LONG);
8544 switch(peek(state)) {
8546 eat(state, TOK_LONG);
8547 error(state, 0, "type long long not supported");
8550 eat(state, TOK_INT);
8551 type = new_type(TYPE_LONG | spec, 0, 0);
8554 type = new_type(TYPE_LONG | spec, 0, 0);
8559 eat(state, TOK_INT);
8560 type = new_type(TYPE_INT | spec, 0, 0);
8563 eat(state, TOK_SHORT);
8564 type = new_type(TYPE_SHORT | spec, 0, 0);
8567 eat(state, TOK_CHAR);
8568 type = new_type(TYPE_CHAR | spec, 0, 0);
8571 type = new_type(TYPE_INT | spec, 0, 0);
8576 eat(state, TOK_UNSIGNED);
8577 switch(peek(state)) {
8579 eat(state, TOK_LONG);
8580 switch(peek(state)) {
8582 eat(state, TOK_LONG);
8583 error(state, 0, "unsigned long long not supported");
8586 eat(state, TOK_INT);
8587 type = new_type(TYPE_ULONG | spec, 0, 0);
8590 type = new_type(TYPE_ULONG | spec, 0, 0);
8595 eat(state, TOK_INT);
8596 type = new_type(TYPE_UINT | spec, 0, 0);
8599 eat(state, TOK_SHORT);
8600 type = new_type(TYPE_USHORT | spec, 0, 0);
8603 eat(state, TOK_CHAR);
8604 type = new_type(TYPE_UCHAR | spec, 0, 0);
8607 type = new_type(TYPE_UINT | spec, 0, 0);
8611 /* struct or union specifier */
8614 type = struct_or_union_specifier(state, spec);
8616 /* enum-spefifier */
8618 type = enum_specifier(state, spec);
8622 type = typedef_name(state, spec);
8625 error(state, 0, "bad type specifier %s",
8626 tokens[peek(state)]);
8632 static int istype(int tok)
8658 static struct type *specifier_qualifier_list(struct compile_state *state)
8661 unsigned int specifiers = 0;
8663 /* type qualifiers */
8664 specifiers |= type_qualifiers(state);
8666 /* type specifier */
8667 type = type_specifier(state, specifiers);
8672 static int isdecl_specifier(int tok)
8675 /* storage class specifier */
8681 /* type qualifier */
8685 /* type specifiers */
8695 /* struct or union specifier */
8698 /* enum-spefifier */
8702 /* function specifiers */
8710 static struct type *decl_specifiers(struct compile_state *state)
8713 unsigned int specifiers;
8714 /* I am overly restrictive in the arragement of specifiers supported.
8715 * C is overly flexible in this department it makes interpreting
8716 * the parse tree difficult.
8720 /* storage class specifier */
8721 specifiers |= storage_class_specifier_opt(state);
8723 /* function-specifier */
8724 specifiers |= function_specifier_opt(state);
8726 /* type qualifier */
8727 specifiers |= type_qualifiers(state);
8729 /* type specifier */
8730 type = type_specifier(state, specifiers);
8734 static unsigned designator(struct compile_state *state)
8740 switch(peek(state)) {
8743 struct triple *value;
8744 eat(state, TOK_LBRACKET);
8745 value = constant_expr(state);
8746 eat(state, TOK_RBRACKET);
8747 index = value->u.cval;
8751 eat(state, TOK_DOT);
8752 eat(state, TOK_IDENT);
8753 error(state, 0, "Struct Designators not currently supported");
8756 error(state, 0, "Invalid designator");
8759 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8764 static struct triple *initializer(
8765 struct compile_state *state, struct type *type)
8767 struct triple *result;
8768 if (peek(state) != TOK_LBRACE) {
8769 result = assignment_expr(state);
8773 unsigned index, max_index;
8775 max_index = index = 0;
8776 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8777 max_index = type->elements;
8778 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8782 error(state, 0, "Struct initializers not currently supported");
8784 buf = xcmalloc(size_of(state, type), "initializer");
8785 eat(state, TOK_LBRACE);
8787 struct triple *value;
8788 struct type *value_type;
8793 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8794 index = designator(state);
8796 if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8797 (index > max_index)) {
8798 error(state, 0, "element beyond bounds");
8801 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8802 value_type = type->left;
8804 value = eval_const_expr(state, initializer(state, value_type));
8805 value_size = size_of(state, value_type);
8806 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8807 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8808 (type->elements <= index)) {
8812 old_size = size_of(state, type);
8813 type->elements = index + 1;
8814 buf = xmalloc(size_of(state, type), "initializer");
8815 memcpy(buf, old_buf, old_size);
8818 if (value->op == OP_BLOBCONST) {
8819 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8821 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8822 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8824 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8825 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8827 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8828 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8831 fprintf(stderr, "%d %d\n",
8832 value->op, value_size);
8833 internal_error(state, 0, "unhandled constant initializer");
8835 if (peek(state) == TOK_COMMA) {
8836 eat(state, TOK_COMMA);
8840 } while(comma && (peek(state) != TOK_RBRACE));
8841 eat(state, TOK_RBRACE);
8842 result = triple(state, OP_BLOBCONST, type, 0, 0);
8843 result->u.blob = buf;
8848 static struct triple *function_definition(
8849 struct compile_state *state, struct type *type)
8851 struct triple *def, *tmp, *first, *end;
8852 struct hash_entry *ident;
8855 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8856 error(state, 0, "Invalid function header");
8859 /* Verify the function type */
8860 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8861 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8862 (type->right->field_ident == 0)) {
8863 error(state, 0, "Invalid function parameters");
8865 param = type->right;
8867 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8869 if (!param->left->field_ident) {
8870 error(state, 0, "No identifier for parameter %d\n", i);
8872 param = param->right;
8875 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8876 error(state, 0, "No identifier for paramter %d\n", i);
8879 /* Get a list of statements for this function. */
8880 def = triple(state, OP_LIST, type, 0, 0);
8882 /* Start a new scope for the passed parameters */
8885 /* Put a label at the very start of a function */
8886 first = label(state);
8887 RHS(def, 0) = first;
8889 /* Put a label at the very end of a function */
8891 flatten(state, first, end);
8893 /* Walk through the parameters and create symbol table entries
8896 param = type->right;
8897 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8898 ident = param->left->field_ident;
8899 tmp = variable(state, param->left);
8900 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8901 flatten(state, end, tmp);
8902 param = param->right;
8904 if ((param->type & TYPE_MASK) != TYPE_VOID) {
8905 /* And don't forget the last parameter */
8906 ident = param->field_ident;
8907 tmp = variable(state, param);
8908 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8909 flatten(state, end, tmp);
8911 /* Add a variable for the return value */
8913 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8914 /* Remove all type qualifiers from the return type */
8915 tmp = variable(state, clone_type(0, type->left));
8916 flatten(state, end, tmp);
8917 /* Remember where the return value is */
8921 /* Remember which function I am compiling.
8922 * Also assume the last defined function is the main function.
8924 state->main_function = def;
8926 /* Now get the actual function definition */
8927 compound_statement(state, end);
8929 /* Remove the parameter scope */
8932 fprintf(stdout, "\n");
8933 loc(stdout, state, 0);
8934 fprintf(stdout, "\n__________ function_definition _________\n");
8935 print_triple(state, def);
8936 fprintf(stdout, "__________ function_definition _________ done\n\n");
8942 static struct triple *do_decl(struct compile_state *state,
8943 struct type *type, struct hash_entry *ident)
8947 /* Clean up the storage types used */
8948 switch (type->type & STOR_MASK) {
8951 /* These are the good types I am aiming for */
8954 type->type &= ~STOR_MASK;
8955 type->type |= STOR_AUTO;
8958 type->type &= ~STOR_MASK;
8959 type->type |= STOR_STATIC;
8963 error(state, 0, "typedef without name");
8965 symbol(state, ident, &ident->sym_ident, 0, type);
8966 ident->tok = TOK_TYPE_NAME;
8970 internal_error(state, 0, "Undefined storage class");
8972 if (((type->type & STOR_MASK) == STOR_STATIC) &&
8973 ((type->type & QUAL_CONST) == 0)) {
8974 error(state, 0, "non const static variables not supported");
8977 def = variable(state, type);
8978 symbol(state, ident, &ident->sym_ident, def, type);
8983 static void decl(struct compile_state *state, struct triple *first)
8985 struct type *base_type, *type;
8986 struct hash_entry *ident;
8989 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8990 base_type = decl_specifiers(state);
8992 type = declarator(state, base_type, &ident, 0);
8993 if (global && ident && (peek(state) == TOK_LBRACE)) {
8995 state->function = ident->name;
8996 def = function_definition(state, type);
8997 symbol(state, ident, &ident->sym_ident, def, type);
8998 state->function = 0;
9002 flatten(state, first, do_decl(state, type, ident));
9003 /* type or variable definition */
9006 if (peek(state) == TOK_EQ) {
9008 error(state, 0, "cannot assign to a type");
9011 flatten(state, first,
9013 ident->sym_ident->def,
9014 initializer(state, type)));
9016 arrays_complete(state, type);
9017 if (peek(state) == TOK_COMMA) {
9018 eat(state, TOK_COMMA);
9020 type = declarator(state, base_type, &ident, 0);
9021 flatten(state, first, do_decl(state, type, ident));
9025 eat(state, TOK_SEMI);
9029 static void decls(struct compile_state *state)
9031 struct triple *list;
9033 list = label(state);
9036 if (tok == TOK_EOF) {
9039 if (tok == TOK_SPACE) {
9040 eat(state, TOK_SPACE);
9043 if (list->next != list) {
9044 error(state, 0, "global variables not supported");
9050 * Data structurs for optimation.
9053 static void do_use_block(
9054 struct block *used, struct block_set **head, struct block *user,
9057 struct block_set **ptr, *new;
9064 if ((*ptr)->member == user) {
9067 ptr = &(*ptr)->next;
9069 new = xcmalloc(sizeof(*new), "block_set");
9080 static void do_unuse_block(
9081 struct block *used, struct block_set **head, struct block *unuser)
9083 struct block_set *use, **ptr;
9087 if (use->member == unuser) {
9089 memset(use, -1, sizeof(*use));
9098 static void use_block(struct block *used, struct block *user)
9100 /* Append new to the head of the list, print_block
9103 do_use_block(used, &used->use, user, 1);
9106 static void unuse_block(struct block *used, struct block *unuser)
9108 do_unuse_block(used, &used->use, unuser);
9112 static void idom_block(struct block *idom, struct block *user)
9114 do_use_block(idom, &idom->idominates, user, 0);
9117 static void unidom_block(struct block *idom, struct block *unuser)
9119 do_unuse_block(idom, &idom->idominates, unuser);
9122 static void domf_block(struct block *block, struct block *domf)
9124 do_use_block(block, &block->domfrontier, domf, 0);
9127 static void undomf_block(struct block *block, struct block *undomf)
9129 do_unuse_block(block, &block->domfrontier, undomf);
9132 static void ipdom_block(struct block *ipdom, struct block *user)
9134 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9137 static void unipdom_block(struct block *ipdom, struct block *unuser)
9139 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9142 static void ipdomf_block(struct block *block, struct block *ipdomf)
9144 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9147 static void unipdomf_block(struct block *block, struct block *unipdomf)
9149 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9154 static int do_walk_triple(struct compile_state *state,
9155 struct triple *ptr, int depth,
9156 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9159 result = cb(state, ptr, depth);
9160 if ((result == 0) && (ptr->op == OP_LIST)) {
9161 struct triple *list;
9165 result = do_walk_triple(state, ptr, depth + 1, cb);
9166 if (ptr->next->prev != ptr) {
9167 internal_error(state, ptr->next, "bad prev");
9171 } while((result == 0) && (ptr != RHS(list, 0)));
9176 static int walk_triple(
9177 struct compile_state *state,
9179 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9181 return do_walk_triple(state, ptr, 0, cb);
9184 static void do_print_prefix(int depth)
9187 for(i = 0; i < depth; i++) {
9192 #define PRINT_LIST 1
9193 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9197 if (op == OP_LIST) {
9202 if ((op == OP_LABEL) && (ins->use)) {
9203 printf("\n%p:\n", ins);
9205 do_print_prefix(depth);
9206 display_triple(stdout, ins);
9208 if ((ins->op == OP_BRANCH) && ins->use) {
9209 internal_error(state, ins, "branch used?");
9213 struct triple_set *user;
9214 for(user = ins->use; user; user = user->next) {
9215 printf("use: %p\n", user->member);
9219 if (triple_is_branch(state, ins)) {
9225 static void print_triple(struct compile_state *state, struct triple *ins)
9227 walk_triple(state, ins, do_print_triple);
9230 static void print_triples(struct compile_state *state)
9232 print_triple(state, state->main_function);
9236 struct block *block;
9238 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9240 if (!block || (cf[block->vertex].block == block)) {
9243 cf[block->vertex].block = block;
9244 find_cf_blocks(cf, block->left);
9245 find_cf_blocks(cf, block->right);
9248 static void print_control_flow(struct compile_state *state)
9250 struct cf_block *cf;
9252 printf("\ncontrol flow\n");
9253 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9254 find_cf_blocks(cf, state->first_block);
9256 for(i = 1; i <= state->last_vertex; i++) {
9257 struct block *block;
9258 block = cf[i].block;
9261 printf("(%p) %d:", block, block->vertex);
9263 printf(" %d", block->left->vertex);
9265 if (block->right && (block->right != block->left)) {
9266 printf(" %d", block->right->vertex);
9275 static struct block *basic_block(struct compile_state *state,
9276 struct triple *first)
9278 struct block *block;
9281 if (first->op != OP_LABEL) {
9282 internal_error(state, 0, "block does not start with a label");
9284 /* See if this basic block has already been setup */
9285 if (first->u.block != 0) {
9286 return first->u.block;
9288 /* Allocate another basic block structure */
9289 state->last_vertex += 1;
9290 block = xcmalloc(sizeof(*block), "block");
9291 block->first = block->last = first;
9292 block->vertex = state->last_vertex;
9295 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9299 /* If ptr->u is not used remember where the baic block is */
9300 if (triple_stores_block(state, ptr)) {
9301 ptr->u.block = block;
9303 if (ptr->op == OP_BRANCH) {
9307 } while (ptr != RHS(state->main_function, 0));
9308 if (ptr == RHS(state->main_function, 0))
9311 if (op == OP_LABEL) {
9312 block->left = basic_block(state, ptr);
9314 use_block(block->left, block);
9316 else if (op == OP_BRANCH) {
9318 /* Trace the branch target */
9319 block->right = basic_block(state, TARG(ptr, 0));
9320 use_block(block->right, block);
9321 /* If there is a test trace the branch as well */
9322 if (TRIPLE_RHS(ptr->sizes)) {
9323 block->left = basic_block(state, ptr->next);
9324 use_block(block->left, block);
9328 internal_error(state, 0, "Bad basic block split");
9334 static void walk_blocks(struct compile_state *state,
9335 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9338 struct triple *ptr, *first;
9339 struct block *last_block;
9341 first = RHS(state->main_function, 0);
9344 struct block *block;
9345 if (ptr->op == OP_LABEL) {
9346 block = ptr->u.block;
9347 if (block && (block != last_block)) {
9348 cb(state, block, arg);
9353 } while(ptr != first);
9356 static void print_block(
9357 struct compile_state *state, struct block *block, void *arg)
9362 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
9366 block->left && block->left->use?block->left->use->member : 0,
9368 block->right && block->right->use?block->right->use->member : 0);
9369 if (block->first->op == OP_LABEL) {
9370 fprintf(fp, "%p:\n", block->first);
9372 for(ptr = block->first; ; ptr = ptr->next) {
9373 struct triple_set *user;
9376 if (triple_stores_block(state, ptr)) {
9377 if (ptr->u.block != block) {
9378 internal_error(state, ptr,
9379 "Wrong block pointer: %p\n",
9383 if (op == OP_ADECL) {
9384 for(user = ptr->use; user; user = user->next) {
9385 if (!user->member->u.block) {
9386 internal_error(state, user->member,
9387 "Use %p not in a block?\n",
9392 display_triple(fp, ptr);
9395 for(user = ptr->use; user; user = user->next) {
9396 fprintf(fp, "use: %p\n", user->member);
9400 /* Sanity checks... */
9401 valid_ins(state, ptr);
9402 for(user = ptr->use; user; user = user->next) {
9405 valid_ins(state, use);
9406 if (triple_stores_block(state, user->member) &&
9407 !user->member->u.block) {
9408 internal_error(state, user->member,
9409 "Use %p not in a block?",
9414 if (ptr == block->last)
9421 static void print_blocks(struct compile_state *state, FILE *fp)
9423 fprintf(fp, "--------------- blocks ---------------\n");
9424 walk_blocks(state, print_block, fp);
9427 static void prune_nonblock_triples(struct compile_state *state)
9429 struct block *block;
9430 struct triple *first, *ins, *next;
9431 /* Delete the triples not in a basic block */
9432 first = RHS(state->main_function, 0);
9437 if (ins->op == OP_LABEL) {
9438 block = ins->u.block;
9441 release_triple(state, ins);
9444 } while(ins != first);
9447 static void setup_basic_blocks(struct compile_state *state)
9449 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9450 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9451 internal_error(state, 0, "ins will not store block?");
9453 /* Find the basic blocks */
9454 state->last_vertex = 0;
9455 state->first_block = basic_block(state, RHS(state->main_function,0));
9456 /* Delete the triples not in a basic block */
9457 prune_nonblock_triples(state);
9458 /* Find the last basic block */
9459 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9460 if (!state->last_block) {
9461 internal_error(state, 0, "end not used?");
9463 /* Insert an extra unused edge from start to the end
9464 * This helps with reverse control flow calculations.
9466 use_block(state->first_block, state->last_block);
9467 /* If we are debugging print what I have just done */
9468 if (state->debug & DEBUG_BASIC_BLOCKS) {
9469 print_blocks(state, stdout);
9470 print_control_flow(state);
9474 static void free_basic_block(struct compile_state *state, struct block *block)
9476 struct block_set *entry, *next;
9477 struct block *child;
9481 if (block->vertex == -1) {
9486 unuse_block(block->left, block);
9489 unuse_block(block->right, block);
9492 unidom_block(block->idom, block);
9496 unipdom_block(block->ipdom, block);
9499 for(entry = block->use; entry; entry = next) {
9501 child = entry->member;
9502 unuse_block(block, child);
9503 if (child->left == block) {
9506 if (child->right == block) {
9510 for(entry = block->idominates; entry; entry = next) {
9512 child = entry->member;
9513 unidom_block(block, child);
9516 for(entry = block->domfrontier; entry; entry = next) {
9518 child = entry->member;
9519 undomf_block(block, child);
9521 for(entry = block->ipdominates; entry; entry = next) {
9523 child = entry->member;
9524 unipdom_block(block, child);
9527 for(entry = block->ipdomfrontier; entry; entry = next) {
9529 child = entry->member;
9530 unipdomf_block(block, child);
9532 if (block->users != 0) {
9533 internal_error(state, 0, "block still has users");
9535 free_basic_block(state, block->left);
9537 free_basic_block(state, block->right);
9539 memset(block, -1, sizeof(*block));
9543 static void free_basic_blocks(struct compile_state *state)
9545 struct triple *first, *ins;
9546 free_basic_block(state, state->first_block);
9547 state->last_vertex = 0;
9548 state->first_block = state->last_block = 0;
9549 first = RHS(state->main_function, 0);
9552 if (triple_stores_block(state, ins)) {
9556 } while(ins != first);
9561 struct block *block;
9562 struct sdom_block *sdominates;
9563 struct sdom_block *sdom_next;
9564 struct sdom_block *sdom;
9565 struct sdom_block *label;
9566 struct sdom_block *parent;
9567 struct sdom_block *ancestor;
9572 static void unsdom_block(struct sdom_block *block)
9574 struct sdom_block **ptr;
9575 if (!block->sdom_next) {
9578 ptr = &block->sdom->sdominates;
9580 if ((*ptr) == block) {
9581 *ptr = block->sdom_next;
9584 ptr = &(*ptr)->sdom_next;
9588 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9590 unsdom_block(block);
9592 block->sdom_next = sdom->sdominates;
9593 sdom->sdominates = block;
9598 static int initialize_sdblock(struct sdom_block *sd,
9599 struct block *parent, struct block *block, int vertex)
9601 if (!block || (sd[block->vertex].block == block)) {
9605 /* Renumber the blocks in a convinient fashion */
9606 block->vertex = vertex;
9607 sd[vertex].block = block;
9608 sd[vertex].sdom = &sd[vertex];
9609 sd[vertex].label = &sd[vertex];
9610 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9611 sd[vertex].ancestor = 0;
9612 sd[vertex].vertex = vertex;
9613 vertex = initialize_sdblock(sd, block, block->left, vertex);
9614 vertex = initialize_sdblock(sd, block, block->right, vertex);
9618 static int initialize_sdpblock(struct sdom_block *sd,
9619 struct block *parent, struct block *block, int vertex)
9621 struct block_set *user;
9622 if (!block || (sd[block->vertex].block == block)) {
9626 /* Renumber the blocks in a convinient fashion */
9627 block->vertex = vertex;
9628 sd[vertex].block = block;
9629 sd[vertex].sdom = &sd[vertex];
9630 sd[vertex].label = &sd[vertex];
9631 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9632 sd[vertex].ancestor = 0;
9633 sd[vertex].vertex = vertex;
9634 for(user = block->use; user; user = user->next) {
9635 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9640 static void compress_ancestors(struct sdom_block *v)
9642 /* This procedure assumes ancestor(v) != 0 */
9643 /* if (ancestor(ancestor(v)) != 0) {
9644 * compress(ancestor(ancestor(v)));
9645 * if (semi(label(ancestor(v))) < semi(label(v))) {
9646 * label(v) = label(ancestor(v));
9648 * ancestor(v) = ancestor(ancestor(v));
9654 if (v->ancestor->ancestor) {
9655 compress_ancestors(v->ancestor->ancestor);
9656 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9657 v->label = v->ancestor->label;
9659 v->ancestor = v->ancestor->ancestor;
9663 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9667 * for each v <= pred(w) {
9669 * if (semi[u] < semi[w] {
9670 * semi[w] = semi[u];
9673 * add w to bucket(vertex(semi[w]));
9674 * LINK(parent(w), w);
9677 * for each v <= bucket(parent(w)) {
9678 * delete v from bucket(parent(w));
9680 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9683 for(i = state->last_vertex; i >= 2; i--) {
9684 struct sdom_block *v, *parent, *next;
9685 struct block_set *user;
9686 struct block *block;
9687 block = sd[i].block;
9688 parent = sd[i].parent;
9690 for(user = block->use; user; user = user->next) {
9691 struct sdom_block *v, *u;
9692 v = &sd[user->member->vertex];
9693 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9694 if (u->sdom->vertex < sd[i].sdom->vertex) {
9695 sd[i].sdom = u->sdom;
9698 sdom_block(sd[i].sdom, &sd[i]);
9699 sd[i].ancestor = parent;
9701 for(v = parent->sdominates; v; v = next) {
9702 struct sdom_block *u;
9703 next = v->sdom_next;
9705 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9706 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9707 u->block : parent->block;
9712 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9716 * for each v <= pred(w) {
9718 * if (semi[u] < semi[w] {
9719 * semi[w] = semi[u];
9722 * add w to bucket(vertex(semi[w]));
9723 * LINK(parent(w), w);
9726 * for each v <= bucket(parent(w)) {
9727 * delete v from bucket(parent(w));
9729 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9732 for(i = state->last_vertex; i >= 2; i--) {
9733 struct sdom_block *u, *v, *parent, *next;
9734 struct block *block;
9735 block = sd[i].block;
9736 parent = sd[i].parent;
9739 v = &sd[block->left->vertex];
9740 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9741 if (u->sdom->vertex < sd[i].sdom->vertex) {
9742 sd[i].sdom = u->sdom;
9745 if (block->right && (block->right != block->left)) {
9746 v = &sd[block->right->vertex];
9747 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9748 if (u->sdom->vertex < sd[i].sdom->vertex) {
9749 sd[i].sdom = u->sdom;
9752 sdom_block(sd[i].sdom, &sd[i]);
9753 sd[i].ancestor = parent;
9755 for(v = parent->sdominates; v; v = next) {
9756 struct sdom_block *u;
9757 next = v->sdom_next;
9759 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9760 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9761 u->block : parent->block;
9766 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9769 for(i = 2; i <= state->last_vertex; i++) {
9770 struct block *block;
9771 block = sd[i].block;
9772 if (block->idom->vertex != sd[i].sdom->vertex) {
9773 block->idom = block->idom->idom;
9775 idom_block(block->idom, block);
9777 sd[1].block->idom = 0;
9780 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9783 for(i = 2; i <= state->last_vertex; i++) {
9784 struct block *block;
9785 block = sd[i].block;
9786 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9787 block->ipdom = block->ipdom->ipdom;
9789 ipdom_block(block->ipdom, block);
9791 sd[1].block->ipdom = 0;
9795 * Every vertex of a flowgraph G = (V, E, r) except r has
9796 * a unique immediate dominator.
9797 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9798 * rooted at r, called the dominator tree of G, such that
9799 * v dominates w if and only if v is a proper ancestor of w in
9800 * the dominator tree.
9803 * If v and w are vertices of G such that v <= w,
9804 * than any path from v to w must contain a common ancestor
9807 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9808 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9809 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9811 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9812 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9815 * Let w != r and let u be a vertex for which sdom(u) is
9816 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9817 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9819 /* Lemma 5: Let vertices v,w satisfy v -> w.
9820 * Then v -> idom(w) or idom(w) -> idom(v)
9823 static void find_immediate_dominators(struct compile_state *state)
9825 struct sdom_block *sd;
9826 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9827 * vi > w for (1 <= i <= k - 1}
9830 * For any vertex w != r.
9832 * {v|(v,w) <= E and v < w } U
9833 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9836 * Let w != r and let u be a vertex for which sdom(u) is
9837 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9839 * { sdom(w) if sdom(w) = sdom(u),
9841 * { idom(u) otherwise
9843 /* The algorithm consists of the following 4 steps.
9844 * Step 1. Carry out a depth-first search of the problem graph.
9845 * Number the vertices from 1 to N as they are reached during
9846 * the search. Initialize the variables used in succeeding steps.
9847 * Step 2. Compute the semidominators of all vertices by applying
9848 * theorem 4. Carry out the computation vertex by vertex in
9849 * decreasing order by number.
9850 * Step 3. Implicitly define the immediate dominator of each vertex
9851 * by applying Corollary 1.
9852 * Step 4. Explicitly define the immediate dominator of each vertex,
9853 * carrying out the computation vertex by vertex in increasing order
9856 /* Step 1 initialize the basic block information */
9857 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9858 initialize_sdblock(sd, 0, state->first_block, 0);
9864 /* Step 2 compute the semidominators */
9865 /* Step 3 implicitly define the immediate dominator of each vertex */
9866 compute_sdom(state, sd);
9867 /* Step 4 explicitly define the immediate dominator of each vertex */
9868 compute_idom(state, sd);
9872 static void find_post_dominators(struct compile_state *state)
9874 struct sdom_block *sd;
9875 /* Step 1 initialize the basic block information */
9876 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9878 initialize_sdpblock(sd, 0, state->last_block, 0);
9880 /* Step 2 compute the semidominators */
9881 /* Step 3 implicitly define the immediate dominator of each vertex */
9882 compute_spdom(state, sd);
9883 /* Step 4 explicitly define the immediate dominator of each vertex */
9884 compute_ipdom(state, sd);
9890 static void find_block_domf(struct compile_state *state, struct block *block)
9892 struct block *child;
9893 struct block_set *user;
9894 if (block->domfrontier != 0) {
9895 internal_error(state, block->first, "domfrontier present?");
9897 for(user = block->idominates; user; user = user->next) {
9898 child = user->member;
9899 if (child->idom != block) {
9900 internal_error(state, block->first, "bad idom");
9902 find_block_domf(state, child);
9904 if (block->left && block->left->idom != block) {
9905 domf_block(block, block->left);
9907 if (block->right && block->right->idom != block) {
9908 domf_block(block, block->right);
9910 for(user = block->idominates; user; user = user->next) {
9911 struct block_set *frontier;
9912 child = user->member;
9913 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9914 if (frontier->member->idom != block) {
9915 domf_block(block, frontier->member);
9921 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9923 struct block *child;
9924 struct block_set *user;
9925 if (block->ipdomfrontier != 0) {
9926 internal_error(state, block->first, "ipdomfrontier present?");
9928 for(user = block->ipdominates; user; user = user->next) {
9929 child = user->member;
9930 if (child->ipdom != block) {
9931 internal_error(state, block->first, "bad ipdom");
9933 find_block_ipdomf(state, child);
9935 if (block->left && block->left->ipdom != block) {
9936 ipdomf_block(block, block->left);
9938 if (block->right && block->right->ipdom != block) {
9939 ipdomf_block(block, block->right);
9941 for(user = block->idominates; user; user = user->next) {
9942 struct block_set *frontier;
9943 child = user->member;
9944 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9945 if (frontier->member->ipdom != block) {
9946 ipdomf_block(block, frontier->member);
9952 static void print_dominated(
9953 struct compile_state *state, struct block *block, void *arg)
9955 struct block_set *user;
9958 fprintf(fp, "%d:", block->vertex);
9959 for(user = block->idominates; user; user = user->next) {
9960 fprintf(fp, " %d", user->member->vertex);
9961 if (user->member->idom != block) {
9962 internal_error(state, user->member->first, "bad idom");
9968 static void print_dominators(struct compile_state *state, FILE *fp)
9970 fprintf(fp, "\ndominates\n");
9971 walk_blocks(state, print_dominated, fp);
9975 static int print_frontiers(
9976 struct compile_state *state, struct block *block, int vertex)
9978 struct block_set *user;
9980 if (!block || (block->vertex != vertex + 1)) {
9985 printf("%d:", block->vertex);
9986 for(user = block->domfrontier; user; user = user->next) {
9987 printf(" %d", user->member->vertex);
9991 vertex = print_frontiers(state, block->left, vertex);
9992 vertex = print_frontiers(state, block->right, vertex);
9995 static void print_dominance_frontiers(struct compile_state *state)
9997 printf("\ndominance frontiers\n");
9998 print_frontiers(state, state->first_block, 0);
10002 static void analyze_idominators(struct compile_state *state)
10004 /* Find the immediate dominators */
10005 find_immediate_dominators(state);
10006 /* Find the dominance frontiers */
10007 find_block_domf(state, state->first_block);
10008 /* If debuging print the print what I have just found */
10009 if (state->debug & DEBUG_FDOMINATORS) {
10010 print_dominators(state, stdout);
10011 print_dominance_frontiers(state);
10012 print_control_flow(state);
10018 static void print_ipdominated(
10019 struct compile_state *state, struct block *block, void *arg)
10021 struct block_set *user;
10024 fprintf(fp, "%d:", block->vertex);
10025 for(user = block->ipdominates; user; user = user->next) {
10026 fprintf(fp, " %d", user->member->vertex);
10027 if (user->member->ipdom != block) {
10028 internal_error(state, user->member->first, "bad ipdom");
10034 static void print_ipdominators(struct compile_state *state, FILE *fp)
10036 fprintf(fp, "\nipdominates\n");
10037 walk_blocks(state, print_ipdominated, fp);
10040 static int print_pfrontiers(
10041 struct compile_state *state, struct block *block, int vertex)
10043 struct block_set *user;
10045 if (!block || (block->vertex != vertex + 1)) {
10050 printf("%d:", block->vertex);
10051 for(user = block->ipdomfrontier; user; user = user->next) {
10052 printf(" %d", user->member->vertex);
10055 for(user = block->use; user; user = user->next) {
10056 vertex = print_pfrontiers(state, user->member, vertex);
10060 static void print_ipdominance_frontiers(struct compile_state *state)
10062 printf("\nipdominance frontiers\n");
10063 print_pfrontiers(state, state->last_block, 0);
10067 static void analyze_ipdominators(struct compile_state *state)
10069 /* Find the post dominators */
10070 find_post_dominators(state);
10071 /* Find the control dependencies (post dominance frontiers) */
10072 find_block_ipdomf(state, state->last_block);
10073 /* If debuging print the print what I have just found */
10074 if (state->debug & DEBUG_RDOMINATORS) {
10075 print_ipdominators(state, stdout);
10076 print_ipdominance_frontiers(state);
10077 print_control_flow(state);
10081 static int bdominates(struct compile_state *state,
10082 struct block *dom, struct block *sub)
10084 while(sub && (sub != dom)) {
10090 static int tdominates(struct compile_state *state,
10091 struct triple *dom, struct triple *sub)
10093 struct block *bdom, *bsub;
10095 bdom = block_of_triple(state, dom);
10096 bsub = block_of_triple(state, sub);
10097 if (bdom != bsub) {
10098 result = bdominates(state, bdom, bsub);
10101 struct triple *ins;
10103 while((ins != bsub->first) && (ins != dom)) {
10106 result = (ins == dom);
10111 static void insert_phi_operations(struct compile_state *state)
10114 struct triple *first;
10115 int *has_already, *work;
10116 struct block *work_list, **work_list_tail;
10118 struct triple *var;
10120 size = sizeof(int) * (state->last_vertex + 1);
10121 has_already = xcmalloc(size, "has_already");
10122 work = xcmalloc(size, "work");
10125 first = RHS(state->main_function, 0);
10126 for(var = first->next; var != first ; var = var->next) {
10127 struct block *block;
10128 struct triple_set *user;
10129 if ((var->op != OP_ADECL) || !var->use) {
10134 work_list_tail = &work_list;
10135 for(user = var->use; user; user = user->next) {
10136 if (user->member->op == OP_READ) {
10139 if (user->member->op != OP_WRITE) {
10140 internal_error(state, user->member,
10141 "bad variable access");
10143 block = user->member->u.block;
10145 warning(state, user->member, "dead code");
10147 if (work[block->vertex] >= iter) {
10150 work[block->vertex] = iter;
10151 *work_list_tail = block;
10152 block->work_next = 0;
10153 work_list_tail = &block->work_next;
10155 for(block = work_list; block; block = block->work_next) {
10156 struct block_set *df;
10157 for(df = block->domfrontier; df; df = df->next) {
10158 struct triple *phi;
10159 struct block *front;
10161 front = df->member;
10163 if (has_already[front->vertex] >= iter) {
10166 /* Count how many edges flow into this block */
10167 in_edges = front->users;
10168 /* Insert a phi function for this variable */
10169 get_occurance(front->first->occurance);
10170 phi = alloc_triple(
10171 state, OP_PHI, var->type, -1, in_edges,
10172 front->first->occurance);
10173 phi->u.block = front;
10174 MISC(phi, 0) = var;
10175 use_triple(var, phi);
10176 /* Insert the phi functions immediately after the label */
10177 insert_triple(state, front->first->next, phi);
10178 if (front->first == front->last) {
10179 front->last = front->first->next;
10181 has_already[front->vertex] = iter;
10183 /* If necessary plan to visit the basic block */
10184 if (work[front->vertex] >= iter) {
10187 work[front->vertex] = iter;
10188 *work_list_tail = front;
10189 front->work_next = 0;
10190 work_list_tail = &front->work_next;
10194 xfree(has_already);
10202 static void fixup_block_phi_variables(
10203 struct compile_state *state, struct block *parent, struct block *block)
10205 struct block_set *set;
10206 struct triple *ptr;
10208 if (!parent || !block)
10210 /* Find the edge I am coming in on */
10212 for(set = block->use; set; set = set->next, edge++) {
10213 if (set->member == parent) {
10218 internal_error(state, 0, "phi input is not on a control predecessor");
10220 for(ptr = block->first; ; ptr = ptr->next) {
10221 if (ptr->op == OP_PHI) {
10222 struct triple *var, *val, **slot;
10223 var = MISC(ptr, 0);
10225 internal_error(state, ptr, "no var???");
10227 /* Find the current value of the variable */
10228 val = var->use->member;
10229 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10230 internal_error(state, val, "bad value in phi");
10232 if (edge >= TRIPLE_RHS(ptr->sizes)) {
10233 internal_error(state, ptr, "edges > phi rhs");
10235 slot = &RHS(ptr, edge);
10236 if ((*slot != 0) && (*slot != val)) {
10237 internal_error(state, ptr, "phi already bound on this edge");
10240 use_triple(val, ptr);
10242 if (ptr == block->last) {
10249 static void rename_block_variables(
10250 struct compile_state *state, struct block *block)
10252 struct block_set *user;
10253 struct triple *ptr, *next, *last;
10257 last = block->first;
10259 for(ptr = block->first; !done; ptr = next) {
10261 if (ptr == block->last) {
10265 if (ptr->op == OP_READ) {
10266 struct triple *var, *val;
10268 unuse_triple(var, ptr);
10270 error(state, ptr, "variable used without being set");
10272 /* Find the current value of the variable */
10273 val = var->use->member;
10274 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10275 internal_error(state, val, "bad value in read");
10277 propogate_use(state, ptr, val);
10278 release_triple(state, ptr);
10282 if (ptr->op == OP_WRITE) {
10283 struct triple *var, *val;
10286 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10287 internal_error(state, val, "bad value in write");
10289 propogate_use(state, ptr, val);
10290 unuse_triple(var, ptr);
10291 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10292 push_triple(var, val);
10294 if (ptr->op == OP_PHI) {
10295 struct triple *var;
10296 var = MISC(ptr, 0);
10297 /* Push OP_PHI onto a stack of variable uses */
10298 push_triple(var, ptr);
10302 block->last = last;
10304 /* Fixup PHI functions in the cf successors */
10305 fixup_block_phi_variables(state, block, block->left);
10306 fixup_block_phi_variables(state, block, block->right);
10307 /* rename variables in the dominated nodes */
10308 for(user = block->idominates; user; user = user->next) {
10309 rename_block_variables(state, user->member);
10311 /* pop the renamed variable stack */
10312 last = block->first;
10314 for(ptr = block->first; !done ; ptr = next) {
10316 if (ptr == block->last) {
10319 if (ptr->op == OP_WRITE) {
10320 struct triple *var;
10322 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10323 pop_triple(var, RHS(ptr, 0));
10324 release_triple(state, ptr);
10327 if (ptr->op == OP_PHI) {
10328 struct triple *var;
10329 var = MISC(ptr, 0);
10330 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10331 pop_triple(var, ptr);
10335 block->last = last;
10338 static void prune_block_variables(struct compile_state *state,
10339 struct block *block)
10341 struct block_set *user;
10342 struct triple *next, *last, *ptr;
10344 last = block->first;
10346 for(ptr = block->first; !done; ptr = next) {
10348 if (ptr == block->last) {
10351 if (ptr->op == OP_ADECL) {
10352 struct triple_set *user, *next;
10353 for(user = ptr->use; user; user = next) {
10354 struct triple *use;
10356 use = user->member;
10357 if (use->op != OP_PHI) {
10358 internal_error(state, use, "decl still used");
10360 if (MISC(use, 0) != ptr) {
10361 internal_error(state, use, "bad phi use of decl");
10363 unuse_triple(ptr, use);
10366 release_triple(state, ptr);
10371 block->last = last;
10372 for(user = block->idominates; user; user = user->next) {
10373 prune_block_variables(state, user->member);
10377 static void transform_to_ssa_form(struct compile_state *state)
10379 insert_phi_operations(state);
10381 printf("@%s:%d\n", __FILE__, __LINE__);
10382 print_blocks(state, stdout);
10384 rename_block_variables(state, state->first_block);
10385 prune_block_variables(state, state->first_block);
10389 static void clear_vertex(
10390 struct compile_state *state, struct block *block, void *arg)
10395 static void mark_live_block(
10396 struct compile_state *state, struct block *block, int *next_vertex)
10398 /* See if this is a block that has not been marked */
10399 if (block->vertex != 0) {
10402 block->vertex = *next_vertex;
10404 if (triple_is_branch(state, block->last)) {
10405 struct triple **targ;
10406 targ = triple_targ(state, block->last, 0);
10407 for(; targ; targ = triple_targ(state, block->last, targ)) {
10411 if (!triple_stores_block(state, *targ)) {
10412 internal_error(state, 0, "bad targ");
10414 mark_live_block(state, (*targ)->u.block, next_vertex);
10417 else if (block->last->next != RHS(state->main_function, 0)) {
10418 struct triple *ins;
10419 ins = block->last->next;
10420 if (!triple_stores_block(state, ins)) {
10421 internal_error(state, 0, "bad block start");
10423 mark_live_block(state, ins->u.block, next_vertex);
10427 static void transform_from_ssa_form(struct compile_state *state)
10429 /* To get out of ssa form we insert moves on the incoming
10430 * edges to blocks containting phi functions.
10432 struct triple *first;
10433 struct triple *phi, *next;
10436 /* Walk the control flow to see which blocks remain alive */
10437 walk_blocks(state, clear_vertex, 0);
10439 mark_live_block(state, state->first_block, &next_vertex);
10441 /* Walk all of the operations to find the phi functions */
10442 first = RHS(state->main_function, 0);
10443 for(phi = first->next; phi != first ; phi = next) {
10444 struct block_set *set;
10445 struct block *block;
10446 struct triple **slot;
10447 struct triple *var, *read;
10448 struct triple_set *use, *use_next;
10451 if (phi->op != OP_PHI) {
10454 block = phi->u.block;
10455 slot = &RHS(phi, 0);
10457 /* Forget uses from code in dead blocks */
10458 for(use = phi->use; use; use = use_next) {
10459 struct block *ublock;
10460 struct triple **expr;
10461 use_next = use->next;
10462 ublock = block_of_triple(state, use->member);
10463 if ((use->member == phi) || (ublock->vertex != 0)) {
10466 expr = triple_rhs(state, use->member, 0);
10467 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10468 if (*expr == phi) {
10472 unuse_triple(phi, use->member);
10475 /* A variable to replace the phi function */
10476 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10477 /* A read of the single value that is set into the variable */
10478 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10479 use_triple(var, read);
10481 /* Replaces uses of the phi with variable reads */
10482 propogate_use(state, phi, read);
10484 /* Walk all of the incoming edges/blocks and insert moves.
10486 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10487 struct block *eblock;
10488 struct triple *move;
10489 struct triple *val;
10490 eblock = set->member;
10493 unuse_triple(val, phi);
10495 if (!val || (val == &zero_triple) ||
10496 (block->vertex == 0) || (eblock->vertex == 0) ||
10497 (val == phi) || (val == read)) {
10501 move = post_triple(state,
10502 val, OP_WRITE, phi->type, var, val);
10503 use_triple(val, move);
10504 use_triple(var, move);
10506 /* See if there are any writers of var */
10508 for(use = var->use; use; use = use->next) {
10509 struct triple **expr;
10510 expr = triple_lhs(state, use->member, 0);
10511 for(; expr; expr = triple_lhs(state, use->member, expr)) {
10512 if (*expr == var) {
10517 /* If var is not used free it */
10519 unuse_triple(var, read);
10520 free_triple(state, read);
10521 free_triple(state, var);
10524 /* Release the phi function */
10525 release_triple(state, phi);
10532 * Register conflict resolution
10533 * =========================================================
10536 static struct reg_info find_def_color(
10537 struct compile_state *state, struct triple *def)
10539 struct triple_set *set;
10540 struct reg_info info;
10541 info.reg = REG_UNSET;
10543 if (!triple_is_def(state, def)) {
10546 info = arch_reg_lhs(state, def, 0);
10547 if (info.reg >= MAX_REGISTERS) {
10548 info.reg = REG_UNSET;
10550 for(set = def->use; set; set = set->next) {
10551 struct reg_info tinfo;
10553 i = find_rhs_use(state, set->member, def);
10557 tinfo = arch_reg_rhs(state, set->member, i);
10558 if (tinfo.reg >= MAX_REGISTERS) {
10559 tinfo.reg = REG_UNSET;
10561 if ((tinfo.reg != REG_UNSET) &&
10562 (info.reg != REG_UNSET) &&
10563 (tinfo.reg != info.reg)) {
10564 internal_error(state, def, "register conflict");
10566 if ((info.regcm & tinfo.regcm) == 0) {
10567 internal_error(state, def, "regcm conflict %x & %x == 0",
10568 info.regcm, tinfo.regcm);
10570 if (info.reg == REG_UNSET) {
10571 info.reg = tinfo.reg;
10573 info.regcm &= tinfo.regcm;
10575 if (info.reg >= MAX_REGISTERS) {
10576 internal_error(state, def, "register out of range");
10581 static struct reg_info find_lhs_pre_color(
10582 struct compile_state *state, struct triple *ins, int index)
10584 struct reg_info info;
10586 zrhs = TRIPLE_RHS(ins->sizes);
10587 zlhs = TRIPLE_LHS(ins->sizes);
10588 if (!zlhs && triple_is_def(state, ins)) {
10591 if (index >= zlhs) {
10592 internal_error(state, ins, "Bad lhs %d", index);
10594 info = arch_reg_lhs(state, ins, index);
10595 for(i = 0; i < zrhs; i++) {
10596 struct reg_info rinfo;
10597 rinfo = arch_reg_rhs(state, ins, i);
10598 if ((info.reg == rinfo.reg) &&
10599 (rinfo.reg >= MAX_REGISTERS)) {
10600 struct reg_info tinfo;
10601 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10602 info.reg = tinfo.reg;
10603 info.regcm &= tinfo.regcm;
10607 if (info.reg >= MAX_REGISTERS) {
10608 info.reg = REG_UNSET;
10613 static struct reg_info find_rhs_post_color(
10614 struct compile_state *state, struct triple *ins, int index);
10616 static struct reg_info find_lhs_post_color(
10617 struct compile_state *state, struct triple *ins, int index)
10619 struct triple_set *set;
10620 struct reg_info info;
10621 struct triple *lhs;
10623 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10626 if ((index == 0) && triple_is_def(state, ins)) {
10629 else if (index < TRIPLE_LHS(ins->sizes)) {
10630 lhs = LHS(ins, index);
10633 internal_error(state, ins, "Bad lhs %d", index);
10636 info = arch_reg_lhs(state, ins, index);
10637 if (info.reg >= MAX_REGISTERS) {
10638 info.reg = REG_UNSET;
10640 for(set = lhs->use; set; set = set->next) {
10641 struct reg_info rinfo;
10642 struct triple *user;
10644 user = set->member;
10645 zrhs = TRIPLE_RHS(user->sizes);
10646 for(i = 0; i < zrhs; i++) {
10647 if (RHS(user, i) != lhs) {
10650 rinfo = find_rhs_post_color(state, user, i);
10651 if ((info.reg != REG_UNSET) &&
10652 (rinfo.reg != REG_UNSET) &&
10653 (info.reg != rinfo.reg)) {
10654 internal_error(state, ins, "register conflict");
10656 if ((info.regcm & rinfo.regcm) == 0) {
10657 internal_error(state, ins, "regcm conflict %x & %x == 0",
10658 info.regcm, rinfo.regcm);
10660 if (info.reg == REG_UNSET) {
10661 info.reg = rinfo.reg;
10663 info.regcm &= rinfo.regcm;
10667 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10668 ins, index, info.reg, info.regcm);
10673 static struct reg_info find_rhs_post_color(
10674 struct compile_state *state, struct triple *ins, int index)
10676 struct reg_info info, rinfo;
10679 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10682 rinfo = arch_reg_rhs(state, ins, index);
10683 zlhs = TRIPLE_LHS(ins->sizes);
10684 if (!zlhs && triple_is_def(state, ins)) {
10688 if (info.reg >= MAX_REGISTERS) {
10689 info.reg = REG_UNSET;
10691 for(i = 0; i < zlhs; i++) {
10692 struct reg_info linfo;
10693 linfo = arch_reg_lhs(state, ins, i);
10694 if ((linfo.reg == rinfo.reg) &&
10695 (linfo.reg >= MAX_REGISTERS)) {
10696 struct reg_info tinfo;
10697 tinfo = find_lhs_post_color(state, ins, i);
10698 if (tinfo.reg >= MAX_REGISTERS) {
10699 tinfo.reg = REG_UNSET;
10701 info.regcm &= linfo.reg;
10702 info.regcm &= tinfo.regcm;
10703 if (info.reg != REG_UNSET) {
10704 internal_error(state, ins, "register conflict");
10706 if (info.regcm == 0) {
10707 internal_error(state, ins, "regcm conflict");
10709 info.reg = tinfo.reg;
10713 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10714 ins, index, info.reg, info.regcm);
10719 static struct reg_info find_lhs_color(
10720 struct compile_state *state, struct triple *ins, int index)
10722 struct reg_info pre, post, info;
10724 fprintf(stderr, "find_lhs_color(%p, %d)\n",
10727 pre = find_lhs_pre_color(state, ins, index);
10728 post = find_lhs_post_color(state, ins, index);
10729 if ((pre.reg != post.reg) &&
10730 (pre.reg != REG_UNSET) &&
10731 (post.reg != REG_UNSET)) {
10732 internal_error(state, ins, "register conflict");
10734 info.regcm = pre.regcm & post.regcm;
10735 info.reg = pre.reg;
10736 if (info.reg == REG_UNSET) {
10737 info.reg = post.reg;
10740 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10741 ins, index, info.reg, info.regcm);
10746 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10748 struct triple_set *entry, *next;
10749 struct triple *out;
10750 struct reg_info info, rinfo;
10752 info = arch_reg_lhs(state, ins, 0);
10753 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10754 use_triple(RHS(out, 0), out);
10755 /* Get the users of ins to use out instead */
10756 for(entry = ins->use; entry; entry = next) {
10758 next = entry->next;
10759 if (entry->member == out) {
10762 i = find_rhs_use(state, entry->member, ins);
10766 rinfo = arch_reg_rhs(state, entry->member, i);
10767 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10770 replace_rhs_use(state, ins, out, entry->member);
10772 transform_to_arch_instruction(state, out);
10776 static struct triple *pre_copy(
10777 struct compile_state *state, struct triple *ins, int index)
10779 /* Carefully insert enough operations so that I can
10780 * enter any operation with a GPR32.
10783 struct triple **expr;
10784 expr = &RHS(ins, index);
10785 in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10786 unuse_triple(*expr, ins);
10788 use_triple(RHS(in, 0), in);
10789 use_triple(in, ins);
10790 transform_to_arch_instruction(state, in);
10795 static void insert_copies_to_phi(struct compile_state *state)
10797 /* To get out of ssa form we insert moves on the incoming
10798 * edges to blocks containting phi functions.
10800 struct triple *first;
10801 struct triple *phi;
10803 /* Walk all of the operations to find the phi functions */
10804 first = RHS(state->main_function, 0);
10805 for(phi = first->next; phi != first ; phi = phi->next) {
10806 struct block_set *set;
10807 struct block *block;
10808 struct triple **slot;
10810 if (phi->op != OP_PHI) {
10813 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10814 block = phi->u.block;
10815 slot = &RHS(phi, 0);
10816 /* Walk all of the incoming edges/blocks and insert moves.
10818 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10819 struct block *eblock;
10820 struct triple *move;
10821 struct triple *val;
10822 struct triple *ptr;
10823 eblock = set->member;
10830 get_occurance(val->occurance);
10831 move = build_triple(state, OP_COPY, phi->type, val, 0,
10833 move->u.block = eblock;
10834 move->id |= TRIPLE_FLAG_PRE_SPLIT;
10835 use_triple(val, move);
10838 unuse_triple(val, phi);
10839 use_triple(move, phi);
10841 /* Walk through the block backwards to find
10842 * an appropriate location for the OP_COPY.
10844 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10845 struct triple **expr;
10846 if ((ptr == phi) || (ptr == val)) {
10849 expr = triple_rhs(state, ptr, 0);
10850 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10851 if ((*expr) == phi) {
10857 if (triple_is_branch(state, ptr)) {
10858 internal_error(state, ptr,
10859 "Could not insert write to phi");
10861 insert_triple(state, ptr->next, move);
10862 if (eblock->last == ptr) {
10863 eblock->last = move;
10865 transform_to_arch_instruction(state, move);
10870 struct triple_reg_set {
10871 struct triple_reg_set *next;
10872 struct triple *member;
10873 struct triple *new;
10877 struct block *block;
10878 struct triple_reg_set *in;
10879 struct triple_reg_set *out;
10883 static int do_triple_set(struct triple_reg_set **head,
10884 struct triple *member, struct triple *new_member)
10886 struct triple_reg_set **ptr, *new;
10891 if ((*ptr)->member == member) {
10894 ptr = &(*ptr)->next;
10896 new = xcmalloc(sizeof(*new), "triple_set");
10897 new->member = member;
10898 new->new = new_member;
10904 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
10906 struct triple_reg_set *entry, **ptr;
10910 if (entry->member == member) {
10911 *ptr = entry->next;
10916 ptr = &entry->next;
10921 static int in_triple(struct reg_block *rb, struct triple *in)
10923 return do_triple_set(&rb->in, in, 0);
10925 static void unin_triple(struct reg_block *rb, struct triple *unin)
10927 do_triple_unset(&rb->in, unin);
10930 static int out_triple(struct reg_block *rb, struct triple *out)
10932 return do_triple_set(&rb->out, out, 0);
10934 static void unout_triple(struct reg_block *rb, struct triple *unout)
10936 do_triple_unset(&rb->out, unout);
10939 static int initialize_regblock(struct reg_block *blocks,
10940 struct block *block, int vertex)
10942 struct block_set *user;
10943 if (!block || (blocks[block->vertex].block == block)) {
10947 /* Renumber the blocks in a convinient fashion */
10948 block->vertex = vertex;
10949 blocks[vertex].block = block;
10950 blocks[vertex].vertex = vertex;
10951 for(user = block->use; user; user = user->next) {
10952 vertex = initialize_regblock(blocks, user->member, vertex);
10957 static int phi_in(struct compile_state *state, struct reg_block *blocks,
10958 struct reg_block *rb, struct block *suc)
10960 /* Read the conditional input set of a successor block
10961 * (i.e. the input to the phi nodes) and place it in the
10962 * current blocks output set.
10964 struct block_set *set;
10965 struct triple *ptr;
10969 /* Find the edge I am coming in on */
10970 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
10971 if (set->member == rb->block) {
10976 internal_error(state, 0, "Not coming on a control edge?");
10978 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
10979 struct triple **slot, *expr, *ptr2;
10980 int out_change, done2;
10981 done = (ptr == suc->last);
10982 if (ptr->op != OP_PHI) {
10985 slot = &RHS(ptr, 0);
10987 out_change = out_triple(rb, expr);
10991 /* If we don't define the variable also plast it
10992 * in the current blocks input set.
10994 ptr2 = rb->block->first;
10995 for(done2 = 0; !done2; ptr2 = ptr2->next) {
10996 if (ptr2 == expr) {
10999 done2 = (ptr2 == rb->block->last);
11004 change |= in_triple(rb, expr);
11009 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11010 struct reg_block *rb, struct block *suc)
11012 struct triple_reg_set *in_set;
11015 /* Read the input set of a successor block
11016 * and place it in the current blocks output set.
11018 in_set = blocks[suc->vertex].in;
11019 for(; in_set; in_set = in_set->next) {
11020 int out_change, done;
11021 struct triple *first, *last, *ptr;
11022 out_change = out_triple(rb, in_set->member);
11026 /* If we don't define the variable also place it
11027 * in the current blocks input set.
11029 first = rb->block->first;
11030 last = rb->block->last;
11032 for(ptr = first; !done; ptr = ptr->next) {
11033 if (ptr == in_set->member) {
11036 done = (ptr == last);
11041 change |= in_triple(rb, in_set->member);
11043 change |= phi_in(state, blocks, rb, suc);
11048 static int use_in(struct compile_state *state, struct reg_block *rb)
11050 /* Find the variables we use but don't define and add
11051 * it to the current blocks input set.
11053 #warning "FIXME is this O(N^2) algorithm bad?"
11054 struct block *block;
11055 struct triple *ptr;
11060 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11061 struct triple **expr;
11062 done = (ptr == block->first);
11063 /* The variable a phi function uses depends on the
11064 * control flow, and is handled in phi_in, not
11067 if (ptr->op == OP_PHI) {
11070 expr = triple_rhs(state, ptr, 0);
11071 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11072 struct triple *rhs, *test;
11078 /* See if rhs is defined in this block */
11079 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11080 tdone = (test == block->first);
11086 /* If I still have a valid rhs add it to in */
11087 change |= in_triple(rb, rhs);
11093 static struct reg_block *compute_variable_lifetimes(
11094 struct compile_state *state)
11096 struct reg_block *blocks;
11099 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11100 initialize_regblock(blocks, state->last_block, 0);
11104 for(i = 1; i <= state->last_vertex; i++) {
11105 struct reg_block *rb;
11107 /* Add the left successor's input set to in */
11108 if (rb->block->left) {
11109 change |= reg_in(state, blocks, rb, rb->block->left);
11111 /* Add the right successor's input set to in */
11112 if ((rb->block->right) &&
11113 (rb->block->right != rb->block->left)) {
11114 change |= reg_in(state, blocks, rb, rb->block->right);
11116 /* Add use to in... */
11117 change |= use_in(state, rb);
11123 static void free_variable_lifetimes(
11124 struct compile_state *state, struct reg_block *blocks)
11127 /* free in_set && out_set on each block */
11128 for(i = 1; i <= state->last_vertex; i++) {
11129 struct triple_reg_set *entry, *next;
11130 struct reg_block *rb;
11132 for(entry = rb->in; entry ; entry = next) {
11133 next = entry->next;
11134 do_triple_unset(&rb->in, entry->member);
11136 for(entry = rb->out; entry; entry = next) {
11137 next = entry->next;
11138 do_triple_unset(&rb->out, entry->member);
11145 typedef void (*wvl_cb_t)(
11146 struct compile_state *state,
11147 struct reg_block *blocks, struct triple_reg_set *live,
11148 struct reg_block *rb, struct triple *ins, void *arg);
11150 static void walk_variable_lifetimes(struct compile_state *state,
11151 struct reg_block *blocks, wvl_cb_t cb, void *arg)
11155 for(i = 1; i <= state->last_vertex; i++) {
11156 struct triple_reg_set *live;
11157 struct triple_reg_set *entry, *next;
11158 struct triple *ptr, *prev;
11159 struct reg_block *rb;
11160 struct block *block;
11163 /* Get the blocks */
11167 /* Copy out into live */
11169 for(entry = rb->out; entry; entry = next) {
11170 next = entry->next;
11171 do_triple_set(&live, entry->member, entry->new);
11173 /* Walk through the basic block calculating live */
11174 for(done = 0, ptr = block->last; !done; ptr = prev) {
11175 struct triple **expr;
11178 done = (ptr == block->first);
11180 /* Ensure the current definition is in live */
11181 if (triple_is_def(state, ptr)) {
11182 do_triple_set(&live, ptr, 0);
11185 /* Inform the callback function of what is
11188 cb(state, blocks, live, rb, ptr, arg);
11190 /* Remove the current definition from live */
11191 do_triple_unset(&live, ptr);
11193 /* Add the current uses to live.
11195 * It is safe to skip phi functions because they do
11196 * not have any block local uses, and the block
11197 * output sets already properly account for what
11198 * control flow depedent uses phi functions do have.
11200 if (ptr->op == OP_PHI) {
11203 expr = triple_rhs(state, ptr, 0);
11204 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11205 /* If the triple is not a definition skip it. */
11206 if (!*expr || !triple_is_def(state, *expr)) {
11209 do_triple_set(&live, *expr, 0);
11213 for(entry = live; entry; entry = next) {
11214 next = entry->next;
11215 do_triple_unset(&live, entry->member);
11220 static int count_triples(struct compile_state *state)
11222 struct triple *first, *ins;
11224 first = RHS(state->main_function, 0);
11229 } while (ins != first);
11232 struct dead_triple {
11233 struct triple *triple;
11234 struct dead_triple *work_next;
11235 struct block *block;
11238 #define TRIPLE_FLAG_ALIVE 1
11242 static void awaken(
11243 struct compile_state *state,
11244 struct dead_triple *dtriple, struct triple **expr,
11245 struct dead_triple ***work_list_tail)
11247 struct triple *triple;
11248 struct dead_triple *dt;
11256 if (triple->id <= 0) {
11257 internal_error(state, triple, "bad triple id: %d",
11260 if (triple->op == OP_NOOP) {
11261 internal_warning(state, triple, "awakening noop?");
11264 dt = &dtriple[triple->id];
11265 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11266 dt->flags |= TRIPLE_FLAG_ALIVE;
11267 if (!dt->work_next) {
11268 **work_list_tail = dt;
11269 *work_list_tail = &dt->work_next;
11274 static void eliminate_inefectual_code(struct compile_state *state)
11276 struct block *block;
11277 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11279 struct triple *first, *ins;
11281 /* Setup the work list */
11283 work_list_tail = &work_list;
11285 first = RHS(state->main_function, 0);
11287 /* Count how many triples I have */
11288 triples = count_triples(state);
11290 /* Now put then in an array and mark all of the triples dead */
11291 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11297 if (ins->op == OP_LABEL) {
11298 block = ins->u.block;
11300 dtriple[i].triple = ins;
11301 dtriple[i].block = block;
11302 dtriple[i].flags = 0;
11303 dtriple[i].color = ins->id;
11305 /* See if it is an operation we always keep */
11306 #warning "FIXME handle the case of killing a branch instruction"
11307 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11308 awaken(state, dtriple, &ins, &work_list_tail);
11312 } while(ins != first);
11314 struct dead_triple *dt;
11315 struct block_set *user;
11316 struct triple **expr;
11318 work_list = dt->work_next;
11320 work_list_tail = &work_list;
11322 /* Wake up the data depencencies of this triple */
11325 expr = triple_rhs(state, dt->triple, expr);
11326 awaken(state, dtriple, expr, &work_list_tail);
11329 expr = triple_lhs(state, dt->triple, expr);
11330 awaken(state, dtriple, expr, &work_list_tail);
11333 expr = triple_misc(state, dt->triple, expr);
11334 awaken(state, dtriple, expr, &work_list_tail);
11336 /* Wake up the forward control dependencies */
11338 expr = triple_targ(state, dt->triple, expr);
11339 awaken(state, dtriple, expr, &work_list_tail);
11341 /* Wake up the reverse control dependencies of this triple */
11342 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11343 awaken(state, dtriple, &user->member->last, &work_list_tail);
11346 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11347 if ((dt->triple->op == OP_NOOP) &&
11348 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11349 internal_error(state, dt->triple, "noop effective?");
11351 dt->triple->id = dt->color; /* Restore the color */
11352 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11353 #warning "FIXME handle the case of killing a basic block"
11354 if (dt->block->first == dt->triple) {
11357 if (dt->block->last == dt->triple) {
11358 dt->block->last = dt->triple->prev;
11360 release_triple(state, dt->triple);
11367 static void insert_mandatory_copies(struct compile_state *state)
11369 struct triple *ins, *first;
11371 /* The object is with a minimum of inserted copies,
11372 * to resolve in fundamental register conflicts between
11373 * register value producers and consumers.
11374 * Theoretically we may be greater than minimal when we
11375 * are inserting copies before instructions but that
11376 * case should be rare.
11378 first = RHS(state->main_function, 0);
11381 struct triple_set *entry, *next;
11382 struct triple *tmp;
11383 struct reg_info info;
11384 unsigned reg, regcm;
11385 int do_post_copy, do_pre_copy;
11387 if (!triple_is_def(state, ins)) {
11390 /* Find the architecture specific color information */
11391 info = arch_reg_lhs(state, ins, 0);
11392 if (info.reg >= MAX_REGISTERS) {
11393 info.reg = REG_UNSET;
11397 regcm = arch_type_to_regcm(state, ins->type);
11398 do_post_copy = do_pre_copy = 0;
11400 /* Walk through the uses of ins and check for conflicts */
11401 for(entry = ins->use; entry; entry = next) {
11402 struct reg_info rinfo;
11404 next = entry->next;
11405 i = find_rhs_use(state, entry->member, ins);
11410 /* Find the users color requirements */
11411 rinfo = arch_reg_rhs(state, entry->member, i);
11412 if (rinfo.reg >= MAX_REGISTERS) {
11413 rinfo.reg = REG_UNSET;
11416 /* See if I need a pre_copy */
11417 if (rinfo.reg != REG_UNSET) {
11418 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11423 regcm &= rinfo.regcm;
11424 regcm = arch_regcm_normalize(state, regcm);
11431 (((info.reg != REG_UNSET) &&
11432 (reg != REG_UNSET) &&
11433 (info.reg != reg)) ||
11434 ((info.regcm & regcm) == 0));
11437 regcm = info.regcm;
11438 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11439 for(entry = ins->use; entry; entry = next) {
11440 struct reg_info rinfo;
11442 next = entry->next;
11443 i = find_rhs_use(state, entry->member, ins);
11448 /* Find the users color requirements */
11449 rinfo = arch_reg_rhs(state, entry->member, i);
11450 if (rinfo.reg >= MAX_REGISTERS) {
11451 rinfo.reg = REG_UNSET;
11454 /* Now see if it is time to do the pre_copy */
11455 if (rinfo.reg != REG_UNSET) {
11456 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11457 ((regcm & rinfo.regcm) == 0) ||
11458 /* Don't let a mandatory coalesce sneak
11459 * into a operation that is marked to prevent
11462 ((reg != REG_UNNEEDED) &&
11463 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11464 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11467 struct triple *user;
11468 user = entry->member;
11469 if (RHS(user, i) != ins) {
11470 internal_error(state, user, "bad rhs");
11472 tmp = pre_copy(state, user, i);
11473 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11481 if ((regcm & rinfo.regcm) == 0) {
11483 struct triple *user;
11484 user = entry->member;
11485 if (RHS(user, i) != ins) {
11486 internal_error(state, user, "bad rhs");
11488 tmp = pre_copy(state, user, i);
11489 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11495 regcm &= rinfo.regcm;
11498 if (do_post_copy) {
11499 struct reg_info pre, post;
11500 tmp = post_copy(state, ins);
11501 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11502 pre = arch_reg_lhs(state, ins, 0);
11503 post = arch_reg_lhs(state, tmp, 0);
11504 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11505 internal_error(state, tmp, "useless copy");
11510 } while(ins != first);
11514 struct live_range_edge;
11515 struct live_range_def;
11516 struct live_range {
11517 struct live_range_edge *edges;
11518 struct live_range_def *defs;
11519 /* Note. The list pointed to by defs is kept in order.
11520 * That is baring splits in the flow control
11521 * defs dominates defs->next wich dominates defs->next->next
11528 struct live_range *group_next, **group_prev;
11531 struct live_range_edge {
11532 struct live_range_edge *next;
11533 struct live_range *node;
11536 struct live_range_def {
11537 struct live_range_def *next;
11538 struct live_range_def *prev;
11539 struct live_range *lr;
11540 struct triple *def;
11544 #define LRE_HASH_SIZE 2048
11546 struct lre_hash *next;
11547 struct live_range *left;
11548 struct live_range *right;
11553 struct lre_hash *hash[LRE_HASH_SIZE];
11554 struct reg_block *blocks;
11555 struct live_range_def *lrd;
11556 struct live_range *lr;
11557 struct live_range *low, **low_tail;
11558 struct live_range *high, **high_tail;
11561 int passes, max_passes;
11562 #define MAX_ALLOCATION_PASSES 100
11566 static unsigned regc_max_size(struct compile_state *state, int classes)
11571 for(i = 0; i < MAX_REGC; i++) {
11572 if (classes & (1 << i)) {
11574 size = arch_regc_size(state, i);
11575 if (size > max_size) {
11583 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11585 unsigned equivs[MAX_REG_EQUIVS];
11587 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11588 internal_error(state, 0, "invalid register");
11590 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11591 internal_error(state, 0, "invalid register");
11593 arch_reg_equivs(state, equivs, reg1);
11594 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11595 if (equivs[i] == reg2) {
11602 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11604 unsigned equivs[MAX_REG_EQUIVS];
11606 if (reg == REG_UNNEEDED) {
11609 arch_reg_equivs(state, equivs, reg);
11610 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11611 used[equivs[i]] = 1;
11616 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11618 unsigned equivs[MAX_REG_EQUIVS];
11620 if (reg == REG_UNNEEDED) {
11623 arch_reg_equivs(state, equivs, reg);
11624 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11625 used[equivs[i]] += 1;
11630 static unsigned int hash_live_edge(
11631 struct live_range *left, struct live_range *right)
11633 unsigned int hash, val;
11634 unsigned long lval, rval;
11635 lval = ((unsigned long)left)/sizeof(struct live_range);
11636 rval = ((unsigned long)right)/sizeof(struct live_range);
11641 hash = (hash *263) + val;
11646 hash = (hash *263) + val;
11648 hash = hash & (LRE_HASH_SIZE - 1);
11652 static struct lre_hash **lre_probe(struct reg_state *rstate,
11653 struct live_range *left, struct live_range *right)
11655 struct lre_hash **ptr;
11656 unsigned int index;
11657 /* Ensure left <= right */
11658 if (left > right) {
11659 struct live_range *tmp;
11664 index = hash_live_edge(left, right);
11666 ptr = &rstate->hash[index];
11668 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
11671 ptr = &(*ptr)->next;
11676 static int interfere(struct reg_state *rstate,
11677 struct live_range *left, struct live_range *right)
11679 struct lre_hash **ptr;
11680 ptr = lre_probe(rstate, left, right);
11681 return ptr && *ptr;
11684 static void add_live_edge(struct reg_state *rstate,
11685 struct live_range *left, struct live_range *right)
11687 /* FIXME the memory allocation overhead is noticeable here... */
11688 struct lre_hash **ptr, *new_hash;
11689 struct live_range_edge *edge;
11691 if (left == right) {
11694 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11697 /* Ensure left <= right */
11698 if (left > right) {
11699 struct live_range *tmp;
11704 ptr = lre_probe(rstate, left, right);
11709 fprintf(stderr, "new_live_edge(%p, %p)\n",
11712 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11713 new_hash->next = *ptr;
11714 new_hash->left = left;
11715 new_hash->right = right;
11718 edge = xmalloc(sizeof(*edge), "live_range_edge");
11719 edge->next = left->edges;
11720 edge->node = right;
11721 left->edges = edge;
11724 edge = xmalloc(sizeof(*edge), "live_range_edge");
11725 edge->next = right->edges;
11727 right->edges = edge;
11728 right->degree += 1;
11731 static void remove_live_edge(struct reg_state *rstate,
11732 struct live_range *left, struct live_range *right)
11734 struct live_range_edge *edge, **ptr;
11735 struct lre_hash **hptr, *entry;
11736 hptr = lre_probe(rstate, left, right);
11737 if (!hptr || !*hptr) {
11741 *hptr = entry->next;
11744 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11746 if (edge->node == right) {
11748 memset(edge, 0, sizeof(*edge));
11754 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11756 if (edge->node == left) {
11758 memset(edge, 0, sizeof(*edge));
11766 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11768 struct live_range_edge *edge, *next;
11769 for(edge = range->edges; edge; edge = next) {
11771 remove_live_edge(rstate, range, edge->node);
11776 /* Interference graph...
11778 * new(n) --- Return a graph with n nodes but no edges.
11779 * add(g,x,y) --- Return a graph including g with an between x and y
11780 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11781 * x and y in the graph g
11782 * degree(g, x) --- Return the degree of the node x in the graph g
11783 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11785 * Implement with a hash table && a set of adjcency vectors.
11786 * The hash table supports constant time implementations of add and interfere.
11787 * The adjacency vectors support an efficient implementation of neighbors.
11791 * +---------------------------------------------------+
11792 * | +--------------+ |
11794 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
11796 * -- In simplify implment optimistic coloring... (No backtracking)
11797 * -- Implement Rematerialization it is the only form of spilling we can perform
11798 * Essentially this means dropping a constant from a register because
11799 * we can regenerate it later.
11801 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11802 * coalesce at phi points...
11803 * --- Bias coloring if at all possible do the coalesing a compile time.
11808 static void different_colored(
11809 struct compile_state *state, struct reg_state *rstate,
11810 struct triple *parent, struct triple *ins)
11812 struct live_range *lr;
11813 struct triple **expr;
11814 lr = rstate->lrd[ins->id].lr;
11815 expr = triple_rhs(state, ins, 0);
11816 for(;expr; expr = triple_rhs(state, ins, expr)) {
11817 struct live_range *lr2;
11818 if (!*expr || (*expr == parent) || (*expr == ins)) {
11821 lr2 = rstate->lrd[(*expr)->id].lr;
11822 if (lr->color == lr2->color) {
11823 internal_error(state, ins, "live range too big");
11829 static struct live_range *coalesce_ranges(
11830 struct compile_state *state, struct reg_state *rstate,
11831 struct live_range *lr1, struct live_range *lr2)
11833 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11839 if (!lr1->defs || !lr2->defs) {
11840 internal_error(state, 0,
11841 "cannot coalese dead live ranges");
11843 if ((lr1->color == REG_UNNEEDED) ||
11844 (lr2->color == REG_UNNEEDED)) {
11845 internal_error(state, 0,
11846 "cannot coalesce live ranges without a possible color");
11848 if ((lr1->color != lr2->color) &&
11849 (lr1->color != REG_UNSET) &&
11850 (lr2->color != REG_UNSET)) {
11851 internal_error(state, lr1->defs->def,
11852 "cannot coalesce live ranges of different colors");
11854 color = lr1->color;
11855 if (color == REG_UNSET) {
11856 color = lr2->color;
11858 classes = lr1->classes & lr2->classes;
11860 internal_error(state, lr1->defs->def,
11861 "cannot coalesce live ranges with dissimilar register classes");
11863 /* If there is a clear dominate live range put it in lr1,
11864 * For purposes of this test phi functions are
11865 * considered dominated by the definitions that feed into
11868 if ((lr1->defs->prev->def->op == OP_PHI) ||
11869 ((lr2->defs->prev->def->op != OP_PHI) &&
11870 tdominates(state, lr2->defs->def, lr1->defs->def))) {
11871 struct live_range *tmp;
11877 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11878 fprintf(stderr, "lr1 post\n");
11880 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11881 fprintf(stderr, "lr1 pre\n");
11883 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11884 fprintf(stderr, "lr2 post\n");
11886 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11887 fprintf(stderr, "lr2 pre\n");
11891 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
11898 lr1->classes = classes;
11899 /* Append lr2 onto lr1 */
11900 #warning "FIXME should this be a merge instead of a splice?"
11902 mid1 = lr1->defs->prev;
11904 end = lr2->defs->prev;
11912 /* Fixup the live range in the added live range defs */
11917 } while(lrd != head);
11919 /* Mark lr2 as free. */
11921 lr2->color = REG_UNNEEDED;
11925 internal_error(state, 0, "lr1->defs == 0 ?");
11928 lr1->color = color;
11929 lr1->classes = classes;
11934 static struct live_range_def *live_range_head(
11935 struct compile_state *state, struct live_range *lr,
11936 struct live_range_def *last)
11938 struct live_range_def *result;
11943 else if (!tdominates(state, lr->defs->def, last->next->def)) {
11944 result = last->next;
11949 static struct live_range_def *live_range_end(
11950 struct compile_state *state, struct live_range *lr,
11951 struct live_range_def *last)
11953 struct live_range_def *result;
11956 result = lr->defs->prev;
11958 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
11959 result = last->prev;
11965 static void initialize_live_ranges(
11966 struct compile_state *state, struct reg_state *rstate)
11968 struct triple *ins, *first;
11969 size_t count, size;
11972 first = RHS(state->main_function, 0);
11973 /* First count how many instructions I have.
11975 count = count_triples(state);
11976 /* Potentially I need one live range definitions for each
11977 * instruction, plus an extra for the split routines.
11979 rstate->defs = count + 1;
11980 /* Potentially I need one live range for each instruction
11981 * plus an extra for the dummy live range.
11983 rstate->ranges = count + 1;
11984 size = sizeof(rstate->lrd[0]) * rstate->defs;
11985 rstate->lrd = xcmalloc(size, "live_range_def");
11986 size = sizeof(rstate->lr[0]) * rstate->ranges;
11987 rstate->lr = xcmalloc(size, "live_range");
11989 /* Setup the dummy live range */
11990 rstate->lr[0].classes = 0;
11991 rstate->lr[0].color = REG_UNSET;
11992 rstate->lr[0].defs = 0;
11996 /* If the triple is a variable give it a live range */
11997 if (triple_is_def(state, ins)) {
11998 struct reg_info info;
11999 /* Find the architecture specific color information */
12000 info = find_def_color(state, ins);
12003 rstate->lr[i].defs = &rstate->lrd[j];
12004 rstate->lr[i].color = info.reg;
12005 rstate->lr[i].classes = info.regcm;
12006 rstate->lr[i].degree = 0;
12007 rstate->lrd[j].lr = &rstate->lr[i];
12009 /* Otherwise give the triple the dummy live range. */
12011 rstate->lrd[j].lr = &rstate->lr[0];
12014 /* Initalize the live_range_def */
12015 rstate->lrd[j].next = &rstate->lrd[j];
12016 rstate->lrd[j].prev = &rstate->lrd[j];
12017 rstate->lrd[j].def = ins;
12018 rstate->lrd[j].orig_id = ins->id;
12023 } while(ins != first);
12024 rstate->ranges = i;
12027 /* Make a second pass to handle achitecture specific register
12032 int zlhs, zrhs, i, j;
12033 if (ins->id > rstate->defs) {
12034 internal_error(state, ins, "bad id");
12037 /* Walk through the template of ins and coalesce live ranges */
12038 zlhs = TRIPLE_LHS(ins->sizes);
12039 if ((zlhs == 0) && triple_is_def(state, ins)) {
12042 zrhs = TRIPLE_RHS(ins->sizes);
12044 for(i = 0; i < zlhs; i++) {
12045 struct reg_info linfo;
12046 struct live_range_def *lhs;
12047 linfo = arch_reg_lhs(state, ins, i);
12048 if (linfo.reg < MAX_REGISTERS) {
12051 if (triple_is_def(state, ins)) {
12052 lhs = &rstate->lrd[ins->id];
12054 lhs = &rstate->lrd[LHS(ins, i)->id];
12056 for(j = 0; j < zrhs; j++) {
12057 struct reg_info rinfo;
12058 struct live_range_def *rhs;
12059 rinfo = arch_reg_rhs(state, ins, j);
12060 if (rinfo.reg < MAX_REGISTERS) {
12063 rhs = &rstate->lrd[RHS(ins, i)->id];
12064 if (rinfo.reg == linfo.reg) {
12065 coalesce_ranges(state, rstate,
12071 } while(ins != first);
12074 static void graph_ins(
12075 struct compile_state *state,
12076 struct reg_block *blocks, struct triple_reg_set *live,
12077 struct reg_block *rb, struct triple *ins, void *arg)
12079 struct reg_state *rstate = arg;
12080 struct live_range *def;
12081 struct triple_reg_set *entry;
12083 /* If the triple is not a definition
12084 * we do not have a definition to add to
12085 * the interference graph.
12087 if (!triple_is_def(state, ins)) {
12090 def = rstate->lrd[ins->id].lr;
12092 /* Create an edge between ins and everything that is
12093 * alive, unless the live_range cannot share
12094 * a physical register with ins.
12096 for(entry = live; entry; entry = entry->next) {
12097 struct live_range *lr;
12098 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12099 internal_error(state, 0, "bad entry?");
12101 lr = rstate->lrd[entry->member->id].lr;
12105 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12108 add_live_edge(rstate, def, lr);
12113 static struct live_range *get_verify_live_range(
12114 struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12116 struct live_range *lr;
12117 struct live_range_def *lrd;
12119 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12120 internal_error(state, ins, "bad ins?");
12122 lr = rstate->lrd[ins->id].lr;
12126 if (lrd->def == ins) {
12130 } while(lrd != lr->defs);
12132 internal_error(state, ins, "ins not in live range");
12137 static void verify_graph_ins(
12138 struct compile_state *state,
12139 struct reg_block *blocks, struct triple_reg_set *live,
12140 struct reg_block *rb, struct triple *ins, void *arg)
12142 struct reg_state *rstate = arg;
12143 struct triple_reg_set *entry1, *entry2;
12146 /* Compare live against edges and make certain the code is working */
12147 for(entry1 = live; entry1; entry1 = entry1->next) {
12148 struct live_range *lr1;
12149 lr1 = get_verify_live_range(state, rstate, entry1->member);
12150 for(entry2 = live; entry2; entry2 = entry2->next) {
12151 struct live_range *lr2;
12152 struct live_range_edge *edge2;
12155 if (entry2 == entry1) {
12158 lr2 = get_verify_live_range(state, rstate, entry2->member);
12160 internal_error(state, entry2->member,
12161 "live range with 2 values simultaneously alive");
12163 if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12166 if (!interfere(rstate, lr1, lr2)) {
12167 internal_error(state, entry2->member,
12168 "edges don't interfere?");
12173 for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12175 if (edge2->node == lr1) {
12179 if (lr2_degree != lr2->degree) {
12180 internal_error(state, entry2->member,
12181 "computed degree: %d does not match reported degree: %d\n",
12182 lr2_degree, lr2->degree);
12185 internal_error(state, entry2->member, "missing edge");
12193 static void print_interference_ins(
12194 struct compile_state *state,
12195 struct reg_block *blocks, struct triple_reg_set *live,
12196 struct reg_block *rb, struct triple *ins, void *arg)
12198 struct reg_state *rstate = arg;
12199 struct live_range *lr;
12202 lr = rstate->lrd[ins->id].lr;
12204 ins->id = rstate->lrd[id].orig_id;
12205 SET_REG(ins->id, lr->color);
12206 display_triple(stdout, ins);
12210 struct live_range_def *lrd;
12214 printf(" %-10p", lrd->def);
12216 } while(lrd != lr->defs);
12220 struct triple_reg_set *entry;
12222 for(entry = live; entry; entry = entry->next) {
12223 printf(" %-10p", entry->member);
12228 struct live_range_edge *entry;
12230 for(entry = lr->edges; entry; entry = entry->next) {
12231 struct live_range_def *lrd;
12232 lrd = entry->node->defs;
12234 printf(" %-10p", lrd->def);
12236 } while(lrd != entry->node->defs);
12241 if (triple_is_branch(state, ins)) {
12247 static int coalesce_live_ranges(
12248 struct compile_state *state, struct reg_state *rstate)
12250 /* At the point where a value is moved from one
12251 * register to another that value requires two
12252 * registers, thus increasing register pressure.
12253 * Live range coaleescing reduces the register
12254 * pressure by keeping a value in one register
12257 * In the case of a phi function all paths leading
12258 * into it must be allocated to the same register
12259 * otherwise the phi function may not be removed.
12261 * Forcing a value to stay in a single register
12262 * for an extended period of time does have
12263 * limitations when applied to non homogenous
12266 * The two cases I have identified are:
12267 * 1) Two forced register assignments may
12269 * 2) Registers may go unused because they
12270 * are only good for storing the value
12271 * and not manipulating it.
12273 * Because of this I need to split live ranges,
12274 * even outside of the context of coalesced live
12275 * ranges. The need to split live ranges does
12276 * impose some constraints on live range coalescing.
12278 * - Live ranges may not be coalesced across phi
12279 * functions. This creates a 2 headed live
12280 * range that cannot be sanely split.
12282 * - phi functions (coalesced in initialize_live_ranges)
12283 * are handled as pre split live ranges so we will
12284 * never attempt to split them.
12290 for(i = 0; i <= rstate->ranges; i++) {
12291 struct live_range *lr1;
12292 struct live_range_def *lrd1;
12293 lr1 = &rstate->lr[i];
12297 lrd1 = live_range_end(state, lr1, 0);
12298 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12299 struct triple_set *set;
12300 if (lrd1->def->op != OP_COPY) {
12303 /* Skip copies that are the result of a live range split. */
12304 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12307 for(set = lrd1->def->use; set; set = set->next) {
12308 struct live_range_def *lrd2;
12309 struct live_range *lr2, *res;
12311 lrd2 = &rstate->lrd[set->member->id];
12313 /* Don't coalesce with instructions
12314 * that are the result of a live range
12317 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12320 lr2 = rstate->lrd[set->member->id].lr;
12324 if ((lr1->color != lr2->color) &&
12325 (lr1->color != REG_UNSET) &&
12326 (lr2->color != REG_UNSET)) {
12329 if ((lr1->classes & lr2->classes) == 0) {
12333 if (interfere(rstate, lr1, lr2)) {
12337 res = coalesce_ranges(state, rstate, lr1, lr2);
12351 static void fix_coalesce_conflicts(struct compile_state *state,
12352 struct reg_block *blocks, struct triple_reg_set *live,
12353 struct reg_block *rb, struct triple *ins, void *arg)
12355 int zlhs, zrhs, i, j;
12357 /* See if we have a mandatory coalesce operation between
12358 * a lhs and a rhs value. If so and the rhs value is also
12359 * alive then this triple needs to be pre copied. Otherwise
12360 * we would have two definitions in the same live range simultaneously
12363 zlhs = TRIPLE_LHS(ins->sizes);
12364 if ((zlhs == 0) && triple_is_def(state, ins)) {
12367 zrhs = TRIPLE_RHS(ins->sizes);
12368 for(i = 0; i < zlhs; i++) {
12369 struct reg_info linfo;
12370 linfo = arch_reg_lhs(state, ins, i);
12371 if (linfo.reg < MAX_REGISTERS) {
12374 for(j = 0; j < zrhs; j++) {
12375 struct reg_info rinfo;
12376 struct triple *rhs;
12377 struct triple_reg_set *set;
12380 rinfo = arch_reg_rhs(state, ins, j);
12381 if (rinfo.reg != linfo.reg) {
12385 for(set = live; set && !found; set = set->next) {
12386 if (set->member == rhs) {
12391 struct triple *copy;
12392 copy = pre_copy(state, ins, j);
12393 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12400 static void replace_set_use(struct compile_state *state,
12401 struct triple_reg_set *head, struct triple *orig, struct triple *new)
12403 struct triple_reg_set *set;
12404 for(set = head; set; set = set->next) {
12405 if (set->member == orig) {
12411 static void replace_block_use(struct compile_state *state,
12412 struct reg_block *blocks, struct triple *orig, struct triple *new)
12415 #warning "WISHLIST visit just those blocks that need it *"
12416 for(i = 1; i <= state->last_vertex; i++) {
12417 struct reg_block *rb;
12419 replace_set_use(state, rb->in, orig, new);
12420 replace_set_use(state, rb->out, orig, new);
12424 static void color_instructions(struct compile_state *state)
12426 struct triple *ins, *first;
12427 first = RHS(state->main_function, 0);
12430 if (triple_is_def(state, ins)) {
12431 struct reg_info info;
12432 info = find_lhs_color(state, ins, 0);
12433 if (info.reg >= MAX_REGISTERS) {
12434 info.reg = REG_UNSET;
12436 SET_INFO(ins->id, info);
12439 } while(ins != first);
12442 static struct reg_info read_lhs_color(
12443 struct compile_state *state, struct triple *ins, int index)
12445 struct reg_info info;
12446 if ((index == 0) && triple_is_def(state, ins)) {
12447 info.reg = ID_REG(ins->id);
12448 info.regcm = ID_REGCM(ins->id);
12450 else if (index < TRIPLE_LHS(ins->sizes)) {
12451 info = read_lhs_color(state, LHS(ins, index), 0);
12454 internal_error(state, ins, "Bad lhs %d", index);
12455 info.reg = REG_UNSET;
12461 static struct triple *resolve_tangle(
12462 struct compile_state *state, struct triple *tangle)
12464 struct reg_info info, uinfo;
12465 struct triple_set *set, *next;
12466 struct triple *copy;
12468 #warning "WISHLIST recalculate all affected instructions colors"
12469 info = find_lhs_color(state, tangle, 0);
12470 for(set = tangle->use; set; set = next) {
12471 struct triple *user;
12474 user = set->member;
12475 zrhs = TRIPLE_RHS(user->sizes);
12476 for(i = 0; i < zrhs; i++) {
12477 if (RHS(user, i) != tangle) {
12480 uinfo = find_rhs_post_color(state, user, i);
12481 if (uinfo.reg == info.reg) {
12482 copy = pre_copy(state, user, i);
12483 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12484 SET_INFO(copy->id, uinfo);
12489 uinfo = find_lhs_pre_color(state, tangle, 0);
12490 if (uinfo.reg == info.reg) {
12491 struct reg_info linfo;
12492 copy = post_copy(state, tangle);
12493 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12494 linfo = find_lhs_color(state, copy, 0);
12495 SET_INFO(copy->id, linfo);
12497 info = find_lhs_color(state, tangle, 0);
12498 SET_INFO(tangle->id, info);
12504 static void fix_tangles(struct compile_state *state,
12505 struct reg_block *blocks, struct triple_reg_set *live,
12506 struct reg_block *rb, struct triple *ins, void *arg)
12508 struct triple *tangle;
12510 char used[MAX_REGISTERS];
12511 struct triple_reg_set *set;
12514 /* Find out which registers have multiple uses at this point */
12515 memset(used, 0, sizeof(used));
12516 for(set = live; set; set = set->next) {
12517 struct reg_info info;
12518 info = read_lhs_color(state, set->member, 0);
12519 if (info.reg == REG_UNSET) {
12522 reg_inc_used(state, used, info.reg);
12525 /* Now find the least dominated definition of a register in
12526 * conflict I have seen so far.
12528 for(set = live; set; set = set->next) {
12529 struct reg_info info;
12530 info = read_lhs_color(state, set->member, 0);
12531 if (used[info.reg] < 2) {
12534 if (!tangle || tdominates(state, set->member, tangle)) {
12535 tangle = set->member;
12538 /* If I have found a tangle resolve it */
12540 struct triple *post_copy;
12541 post_copy = resolve_tangle(state, tangle);
12543 replace_block_use(state, blocks, tangle, post_copy);
12545 if (post_copy && (tangle != ins)) {
12546 replace_set_use(state, live, tangle, post_copy);
12553 static void correct_tangles(
12554 struct compile_state *state, struct reg_block *blocks)
12556 color_instructions(state);
12557 walk_variable_lifetimes(state, blocks, fix_tangles, 0);
12560 struct least_conflict {
12561 struct reg_state *rstate;
12562 struct live_range *ref_range;
12563 struct triple *ins;
12564 struct triple_reg_set *live;
12568 static void least_conflict(struct compile_state *state,
12569 struct reg_block *blocks, struct triple_reg_set *live,
12570 struct reg_block *rb, struct triple *ins, void *arg)
12572 struct least_conflict *conflict = arg;
12573 struct live_range_edge *edge;
12574 struct triple_reg_set *set;
12578 #warning "FIXME handle instructions with left hand sides..."
12579 /* Only instructions that introduce a new definition
12580 * can be the conflict instruction.
12582 if (!triple_is_def(state, ins)) {
12586 /* See if live ranges at this instruction are a
12587 * strict subset of the live ranges that are in conflict.
12590 for(set = live; set; set = set->next) {
12591 struct live_range *lr;
12592 lr = conflict->rstate->lrd[set->member->id].lr;
12593 /* Ignore it if there cannot be an edge between these two nodes */
12594 if (!arch_regcm_intersect(conflict->ref_range->classes, lr->classes)) {
12597 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12598 if (edge->node == lr) {
12602 if (!edge && (lr != conflict->ref_range)) {
12612 /* See if there is an uncolored member in this subset.
12614 for(set = live; set; set = set->next) {
12615 struct live_range *lr;
12616 lr = conflict->rstate->lrd[set->member->id].lr;
12617 if (lr->color == REG_UNSET) {
12621 if (!set && (conflict->ref_range != REG_UNSET)) {
12626 /* See if any of the live registers are constrained,
12627 * if not it won't be productive to pick this as
12628 * a conflict instruction.
12631 for(set = live; set; set = set->next) {
12632 struct triple_set *uset;
12633 struct reg_info info;
12635 unsigned cur_size, size;
12636 /* Skip this instruction */
12637 if (set->member == ins) {
12640 /* Find how many registers this value can potentially
12643 classes = arch_type_to_regcm(state, set->member->type);
12644 size = regc_max_size(state, classes);
12646 /* Find how many registers we allow this value to
12649 info = arch_reg_lhs(state, set->member, 0);
12651 /* If the value does not live in a register it
12652 * isn't constrained.
12654 if (info.reg == REG_UNNEEDED) {
12658 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12659 cur_size = regc_max_size(state, info.regcm);
12664 /* If there is no difference between potential and
12665 * actual register count there is not a constraint
12667 if (cur_size >= size) {
12671 /* If this live_range feeds into conflict->inds
12672 * it isn't a constraint we can relieve.
12674 for(uset = set->member->use; uset; uset = uset->next) {
12675 if (uset->member == ins) {
12685 /* Don't drop canidates with constraints */
12686 if (conflict->constraints && !constraints) {
12692 fprintf(stderr, "conflict ins? %p %s count: %d constraints: %d\n",
12693 ins, tops(ins->op), count, constraints);
12695 /* Find the instruction with the largest possible subset of
12696 * conflict ranges and that dominates any other instruction
12697 * with an equal sized set of conflicting ranges.
12699 if ((count > conflict->count) ||
12700 ((count == conflict->count) &&
12701 tdominates(state, ins, conflict->ins))) {
12702 struct triple_reg_set *next;
12703 /* Remember the canidate instruction */
12704 conflict->ins = ins;
12705 conflict->count = count;
12706 conflict->constraints = constraints;
12707 /* Free the old collection of live registers */
12708 for(set = conflict->live; set; set = next) {
12710 do_triple_unset(&conflict->live, set->member);
12712 conflict->live = 0;
12713 /* Rember the registers that are alive but do not feed
12714 * into or out of conflict->ins.
12716 for(set = live; set; set = set->next) {
12717 struct triple **expr;
12718 if (set->member == ins) {
12721 expr = triple_rhs(state, ins, 0);
12722 for(;expr; expr = triple_rhs(state, ins, expr)) {
12723 if (*expr == set->member) {
12727 expr = triple_lhs(state, ins, 0);
12728 for(; expr; expr = triple_lhs(state, ins, expr)) {
12729 if (*expr == set->member) {
12733 do_triple_set(&conflict->live, set->member, set->new);
12741 static void find_range_conflict(struct compile_state *state,
12742 struct reg_state *rstate, char *used, struct live_range *ref_range,
12743 struct least_conflict *conflict)
12746 /* there are 3 kinds ways conflicts can occure.
12747 * 1) the life time of 2 values simply overlap.
12748 * 2) the 2 values feed into the same instruction.
12749 * 3) the 2 values feed into a phi function.
12752 /* find the instruction where the problematic conflict comes
12753 * into existance. that the instruction where all of
12754 * the values are alive, and among such instructions it is
12755 * the least dominated one.
12757 * a value is alive an an instruction if either;
12758 * 1) the value defintion dominates the instruction and there
12759 * is a use at or after that instrction
12760 * 2) the value definition feeds into a phi function in the
12761 * same block as the instruction. and the phi function
12762 * is at or after the instruction.
12764 memset(conflict, 0, sizeof(*conflict));
12765 conflict->rstate = rstate;
12766 conflict->ref_range = ref_range;
12768 conflict->live = 0;
12769 conflict->count = 0;
12770 conflict->constraints = 0;
12771 walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12773 if (!conflict->ins) {
12774 internal_error(state, ref_range->defs->def, "No conflict ins?");
12776 if (!conflict->live) {
12777 internal_error(state, ref_range->defs->def, "No conflict live?");
12780 fprintf(stderr, "conflict ins: %p %s count: %d constraints: %d\n",
12781 conflict->ins, tops(conflict->ins->op),
12782 conflict->count, conflict->constraints);
12787 static struct triple *split_constrained_range(struct compile_state *state,
12788 struct reg_state *rstate, char *used, struct least_conflict *conflict)
12790 unsigned constrained_size;
12791 struct triple *new, *constrained;
12792 struct triple_reg_set *cset;
12793 /* Find a range that is having problems because it is
12794 * artificially constrained.
12796 constrained_size = ~0;
12799 for(cset = conflict->live; cset; cset = cset->next) {
12800 struct triple_set *set;
12801 struct reg_info info;
12803 unsigned cur_size, size;
12804 /* Skip the live range that starts with conflict->ins */
12805 if (cset->member == conflict->ins) {
12808 /* Find how many registers this value can potentially
12811 classes = arch_type_to_regcm(state, cset->member->type);
12812 size = regc_max_size(state, classes);
12814 /* Find how many registers we allow this value to
12817 info = arch_reg_lhs(state, cset->member, 0);
12819 /* If the register doesn't need a register
12820 * splitting it can't help.
12822 if (info.reg == REG_UNNEEDED) {
12825 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
12826 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12827 cur_size = regc_max_size(state, info.regcm);
12831 /* If this live_range feeds into conflict->ins
12832 * splitting it is unlikely to help.
12834 for(set = cset->member->use; set; set = set->next) {
12835 if (set->member == conflict->ins) {
12840 /* If there is no difference between potential and
12841 * actual register count there is nothing to do.
12843 if (cur_size >= size) {
12846 /* Of the constrained registers deal with the
12847 * most constrained one first.
12849 if (!constrained ||
12850 (size < constrained_size)) {
12851 constrained = cset->member;
12852 constrained_size = size;
12858 new = post_copy(state, constrained);
12859 new->id |= TRIPLE_FLAG_POST_SPLIT;
12864 static int split_ranges(
12865 struct compile_state *state, struct reg_state *rstate,
12866 char *used, struct live_range *range)
12868 struct triple *new;
12871 fprintf(stderr, "split_ranges %d %s %p\n",
12872 rstate->passes, tops(range->defs->def->op), range->defs->def);
12874 if ((range->color == REG_UNNEEDED) ||
12875 (rstate->passes >= rstate->max_passes)) {
12879 /* If I can't allocate a register something needs to be split */
12880 if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
12881 struct least_conflict conflict;
12884 fprintf(stderr, "find_range_conflict\n");
12886 /* Find where in the set of registers the conflict
12889 find_range_conflict(state, rstate, used, range, &conflict);
12891 /* If a range has been artifically constrained split it */
12892 new = split_constrained_range(state, rstate, used, &conflict);
12895 /* Ideally I would split the live range that will not be used
12896 * for the longest period of time in hopes that this will
12897 * (a) allow me to spill a register or
12898 * (b) allow me to place a value in another register.
12900 * So far I don't have a test case for this, the resolving
12901 * of mandatory constraints has solved all of my
12902 * know issues. So I have choosen not to write any
12903 * code until I cat get a better feel for cases where
12904 * it would be useful to have.
12907 #warning "WISHLIST implement live range splitting..."
12909 print_blocks(state, stderr);
12910 print_dominators(state, stderr);
12917 rstate->lrd[rstate->defs].orig_id = new->id;
12918 new->id = rstate->defs;
12921 fprintf(stderr, "new: %p old: %s %p\n",
12922 new, tops(RHS(new, 0)->op), RHS(new, 0));
12925 print_blocks(state, stderr);
12926 print_dominators(state, stderr);
12934 #if DEBUG_COLOR_GRAPH > 1
12935 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
12936 #define cgdebug_flush() fflush(stdout)
12937 #elif DEBUG_COLOR_GRAPH == 1
12938 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
12939 #define cgdebug_flush() fflush(stderr)
12941 #define cgdebug_printf(...)
12942 #define cgdebug_flush()
12946 static int select_free_color(struct compile_state *state,
12947 struct reg_state *rstate, struct live_range *range)
12949 struct triple_set *entry;
12950 struct live_range_def *lrd;
12951 struct live_range_def *phi;
12952 struct live_range_edge *edge;
12953 char used[MAX_REGISTERS];
12954 struct triple **expr;
12956 /* Instead of doing just the trivial color select here I try
12957 * a few extra things because a good color selection will help reduce
12961 /* Find the registers currently in use */
12962 memset(used, 0, sizeof(used));
12963 for(edge = range->edges; edge; edge = edge->next) {
12964 if (edge->node->color == REG_UNSET) {
12967 reg_fill_used(state, used, edge->node->color);
12969 #if DEBUG_COLOR_GRAPH > 1
12973 for(edge = range->edges; edge; edge = edge->next) {
12976 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
12977 tops(range->def->op), i,
12978 range->def->filename, range->def->line, range->def->col);
12979 for(i = 0; i < MAX_REGISTERS; i++) {
12981 cgdebug_printf("used: %s\n",
12988 #warning "FIXME detect conflicts caused by the source and destination being the same register"
12990 /* If a color is already assigned see if it will work */
12991 if (range->color != REG_UNSET) {
12992 struct live_range_def *lrd;
12993 if (!used[range->color]) {
12996 for(edge = range->edges; edge; edge = edge->next) {
12997 if (edge->node->color != range->color) {
13000 warning(state, edge->node->defs->def, "edge: ");
13001 lrd = edge->node->defs;
13003 warning(state, lrd->def, " %p %s",
13004 lrd->def, tops(lrd->def->op));
13006 } while(lrd != edge->node->defs);
13009 warning(state, range->defs->def, "def: ");
13011 warning(state, lrd->def, " %p %s",
13012 lrd->def, tops(lrd->def->op));
13014 } while(lrd != range->defs);
13015 internal_error(state, range->defs->def,
13016 "live range with already used color %s",
13017 arch_reg_str(range->color));
13020 /* If I feed into an expression reuse it's color.
13021 * This should help remove copies in the case of 2 register instructions
13022 * and phi functions.
13025 lrd = live_range_end(state, range, 0);
13026 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13027 entry = lrd->def->use;
13028 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13029 struct live_range_def *insd;
13030 insd = &rstate->lrd[entry->member->id];
13031 if (insd->lr->defs == 0) {
13034 if (!phi && (insd->def->op == OP_PHI) &&
13035 !interfere(rstate, range, insd->lr)) {
13038 if ((insd->lr->color == REG_UNSET) ||
13039 ((insd->lr->classes & range->classes) == 0) ||
13040 (used[insd->lr->color])) {
13043 if (interfere(rstate, range, insd->lr)) {
13046 range->color = insd->lr->color;
13049 /* If I feed into a phi function reuse it's color or the color
13050 * of something else that feeds into the phi function.
13053 if (phi->lr->color != REG_UNSET) {
13054 if (used[phi->lr->color]) {
13055 range->color = phi->lr->color;
13059 expr = triple_rhs(state, phi->def, 0);
13060 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13061 struct live_range *lr;
13065 lr = rstate->lrd[(*expr)->id].lr;
13066 if ((lr->color == REG_UNSET) ||
13067 ((lr->classes & range->classes) == 0) ||
13068 (used[lr->color])) {
13071 if (interfere(rstate, range, lr)) {
13074 range->color = lr->color;
13078 /* If I don't interfere with a rhs node reuse it's color */
13079 lrd = live_range_head(state, range, 0);
13080 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13081 expr = triple_rhs(state, lrd->def, 0);
13082 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13083 struct live_range *lr;
13087 lr = rstate->lrd[(*expr)->id].lr;
13088 if ((lr->color == -1) ||
13089 ((lr->classes & range->classes) == 0) ||
13090 (used[lr->color])) {
13093 if (interfere(rstate, range, lr)) {
13096 range->color = lr->color;
13100 /* If I have not opportunitically picked a useful color
13101 * pick the first color that is free.
13103 if (range->color == REG_UNSET) {
13105 arch_select_free_register(state, used, range->classes);
13107 if (range->color == REG_UNSET) {
13108 struct live_range_def *lrd;
13110 if (split_ranges(state, rstate, used, range)) {
13113 for(edge = range->edges; edge; edge = edge->next) {
13114 warning(state, edge->node->defs->def, "edge reg %s",
13115 arch_reg_str(edge->node->color));
13116 lrd = edge->node->defs;
13118 warning(state, lrd->def, " %s",
13119 tops(lrd->def->op));
13121 } while(lrd != edge->node->defs);
13123 warning(state, range->defs->def, "range: ");
13126 warning(state, lrd->def, " %s",
13127 tops(lrd->def->op));
13129 } while(lrd != range->defs);
13131 warning(state, range->defs->def, "classes: %x",
13133 for(i = 0; i < MAX_REGISTERS; i++) {
13135 warning(state, range->defs->def, "used: %s",
13139 #if DEBUG_COLOR_GRAPH < 2
13140 error(state, range->defs->def, "too few registers");
13142 internal_error(state, range->defs->def, "too few registers");
13145 range->classes = arch_reg_regcm(state, range->color);
13146 if (range->color == -1) {
13147 internal_error(state, range->defs->def, "select_free_color did not?");
13152 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13155 struct live_range_edge *edge;
13156 struct live_range *range;
13158 cgdebug_printf("Lo: ");
13159 range = rstate->low;
13160 if (*range->group_prev != range) {
13161 internal_error(state, 0, "lo: *prev != range?");
13163 *range->group_prev = range->group_next;
13164 if (range->group_next) {
13165 range->group_next->group_prev = range->group_prev;
13167 if (&range->group_next == rstate->low_tail) {
13168 rstate->low_tail = range->group_prev;
13170 if (rstate->low == range) {
13171 internal_error(state, 0, "low: next != prev?");
13174 else if (rstate->high) {
13175 cgdebug_printf("Hi: ");
13176 range = rstate->high;
13177 if (*range->group_prev != range) {
13178 internal_error(state, 0, "hi: *prev != range?");
13180 *range->group_prev = range->group_next;
13181 if (range->group_next) {
13182 range->group_next->group_prev = range->group_prev;
13184 if (&range->group_next == rstate->high_tail) {
13185 rstate->high_tail = range->group_prev;
13187 if (rstate->high == range) {
13188 internal_error(state, 0, "high: next != prev?");
13194 cgdebug_printf(" %d\n", range - rstate->lr);
13195 range->group_prev = 0;
13196 for(edge = range->edges; edge; edge = edge->next) {
13197 struct live_range *node;
13199 /* Move nodes from the high to the low list */
13200 if (node->group_prev && (node->color == REG_UNSET) &&
13201 (node->degree == regc_max_size(state, node->classes))) {
13202 if (*node->group_prev != node) {
13203 internal_error(state, 0, "move: *prev != node?");
13205 *node->group_prev = node->group_next;
13206 if (node->group_next) {
13207 node->group_next->group_prev = node->group_prev;
13209 if (&node->group_next == rstate->high_tail) {
13210 rstate->high_tail = node->group_prev;
13212 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13213 node->group_prev = rstate->low_tail;
13214 node->group_next = 0;
13215 *rstate->low_tail = node;
13216 rstate->low_tail = &node->group_next;
13217 if (*node->group_prev != node) {
13218 internal_error(state, 0, "move2: *prev != node?");
13223 colored = color_graph(state, rstate);
13225 cgdebug_printf("Coloring %d @%s:%d.%d:",
13226 range - rstate->lr,
13227 range->def->filename, range->def->line, range->def->col);
13229 colored = select_free_color(state, rstate, range);
13230 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13235 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13237 struct live_range *lr;
13238 struct live_range_edge *edge;
13239 struct triple *ins, *first;
13240 char used[MAX_REGISTERS];
13241 first = RHS(state->main_function, 0);
13244 if (triple_is_def(state, ins)) {
13245 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13246 internal_error(state, ins,
13247 "triple without a live range def");
13249 lr = rstate->lrd[ins->id].lr;
13250 if (lr->color == REG_UNSET) {
13251 internal_error(state, ins,
13252 "triple without a color");
13254 /* Find the registers used by the edges */
13255 memset(used, 0, sizeof(used));
13256 for(edge = lr->edges; edge; edge = edge->next) {
13257 if (edge->node->color == REG_UNSET) {
13258 internal_error(state, 0,
13259 "live range without a color");
13261 reg_fill_used(state, used, edge->node->color);
13263 if (used[lr->color]) {
13264 internal_error(state, ins,
13265 "triple with already used color");
13269 } while(ins != first);
13272 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13274 struct live_range *lr;
13275 struct triple *first, *ins;
13276 first = RHS(state->main_function, 0);
13279 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13280 internal_error(state, ins,
13281 "triple without a live range");
13283 lr = rstate->lrd[ins->id].lr;
13284 SET_REG(ins->id, lr->color);
13286 } while (ins != first);
13289 static void print_interference_block(
13290 struct compile_state *state, struct block *block, void *arg)
13293 struct reg_state *rstate = arg;
13294 struct reg_block *rb;
13295 struct triple *ptr;
13298 rb = &rstate->blocks[block->vertex];
13300 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
13304 block->left && block->left->use?block->left->use->member : 0,
13306 block->right && block->right->use?block->right->use->member : 0);
13308 struct triple_reg_set *in_set;
13310 for(in_set = rb->in; in_set; in_set = in_set->next) {
13311 printf(" %-10p", in_set->member);
13316 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13317 done = (ptr == block->last);
13318 if (ptr->op == OP_PHI) {
13325 for(edge = 0; edge < block->users; edge++) {
13326 printf(" in(%d):", edge);
13327 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13328 struct triple **slot;
13329 done = (ptr == block->last);
13330 if (ptr->op != OP_PHI) {
13333 slot = &RHS(ptr, 0);
13334 printf(" %-10p", slot[edge]);
13339 if (block->first->op == OP_LABEL) {
13340 printf("%p:\n", block->first);
13342 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13343 struct triple_set *user;
13344 struct live_range *lr;
13348 done = (ptr == block->last);
13349 lr = rstate->lrd[ptr->id].lr;
13351 if (triple_stores_block(state, ptr)) {
13352 if (ptr->u.block != block) {
13353 internal_error(state, ptr,
13354 "Wrong block pointer: %p",
13358 if (op == OP_ADECL) {
13359 for(user = ptr->use; user; user = user->next) {
13360 if (!user->member->u.block) {
13361 internal_error(state, user->member,
13362 "Use %p not in a block?",
13369 ptr->id = rstate->lrd[id].orig_id;
13370 SET_REG(ptr->id, lr->color);
13371 display_triple(stdout, ptr);
13374 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
13375 internal_error(state, ptr, "lr has no defs!");
13379 struct live_range_def *lrd;
13383 printf(" %-10p", lrd->def);
13385 } while(lrd != lr->defs);
13388 if (lr->edges > 0) {
13389 struct live_range_edge *edge;
13391 for(edge = lr->edges; edge; edge = edge->next) {
13392 struct live_range_def *lrd;
13393 lrd = edge->node->defs;
13395 printf(" %-10p", lrd->def);
13397 } while(lrd != edge->node->defs);
13402 /* Do a bunch of sanity checks */
13403 valid_ins(state, ptr);
13404 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
13405 internal_error(state, ptr, "Invalid triple id: %d",
13408 for(user = ptr->use; user; user = user->next) {
13409 struct triple *use;
13410 struct live_range *ulr;
13411 use = user->member;
13412 valid_ins(state, use);
13413 if ((use->id < 0) || (use->id > rstate->defs)) {
13414 internal_error(state, use, "Invalid triple id: %d",
13417 ulr = rstate->lrd[user->member->id].lr;
13418 if (triple_stores_block(state, user->member) &&
13419 !user->member->u.block) {
13420 internal_error(state, user->member,
13421 "Use %p not in a block?",
13427 struct triple_reg_set *out_set;
13429 for(out_set = rb->out; out_set; out_set = out_set->next) {
13430 printf(" %-10p", out_set->member);
13437 static struct live_range *merge_sort_lr(
13438 struct live_range *first, struct live_range *last)
13440 struct live_range *mid, *join, **join_tail, *pick;
13442 size = (last - first) + 1;
13444 mid = first + size/2;
13445 first = merge_sort_lr(first, mid -1);
13446 mid = merge_sort_lr(mid, last);
13450 /* merge the two lists */
13451 while(first && mid) {
13452 if ((first->degree < mid->degree) ||
13453 ((first->degree == mid->degree) &&
13454 (first->length < mid->length))) {
13456 first = first->group_next;
13458 first->group_prev = 0;
13463 mid = mid->group_next;
13465 mid->group_prev = 0;
13468 pick->group_next = 0;
13469 pick->group_prev = join_tail;
13471 join_tail = &pick->group_next;
13473 /* Splice the remaining list */
13474 pick = (first)? first : mid;
13477 pick->group_prev = join_tail;
13481 if (!first->defs) {
13489 static void ids_from_rstate(struct compile_state *state,
13490 struct reg_state *rstate)
13492 struct triple *ins, *first;
13493 if (!rstate->defs) {
13496 /* Display the graph if desired */
13497 if (state->debug & DEBUG_INTERFERENCE) {
13498 print_blocks(state, stdout);
13499 print_control_flow(state);
13501 first = RHS(state->main_function, 0);
13505 struct live_range_def *lrd;
13506 lrd = &rstate->lrd[ins->id];
13507 ins->id = lrd->orig_id;
13510 } while(ins != first);
13513 static void cleanup_live_edges(struct reg_state *rstate)
13516 /* Free the edges on each node */
13517 for(i = 1; i <= rstate->ranges; i++) {
13518 remove_live_edges(rstate, &rstate->lr[i]);
13522 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13524 cleanup_live_edges(rstate);
13525 xfree(rstate->lrd);
13528 /* Free the variable lifetime information */
13529 if (rstate->blocks) {
13530 free_variable_lifetimes(state, rstate->blocks);
13533 rstate->ranges = 0;
13536 rstate->blocks = 0;
13539 static void allocate_registers(struct compile_state *state)
13541 struct reg_state rstate;
13544 /* Clear out the reg_state */
13545 memset(&rstate, 0, sizeof(rstate));
13546 rstate.max_passes = MAX_ALLOCATION_PASSES;
13549 struct live_range **point, **next;
13553 ids_from_rstate(state, &rstate);
13555 /* Cleanup the temporary data structures */
13556 cleanup_rstate(state, &rstate);
13558 /* Compute the variable lifetimes */
13559 rstate.blocks = compute_variable_lifetimes(state);
13561 /* Fix invalid mandatory live range coalesce conflicts */
13562 walk_variable_lifetimes(
13563 state, rstate.blocks, fix_coalesce_conflicts, 0);
13565 /* Fix two simultaneous uses of the same register */
13566 correct_tangles(state, rstate.blocks);
13568 if (state->debug & DEBUG_INSERTED_COPIES) {
13569 printf("After resolve_tangles\n");
13570 print_blocks(state, stdout);
13571 print_control_flow(state);
13575 /* Allocate and initialize the live ranges */
13576 initialize_live_ranges(state, &rstate);
13579 /* Forget previous live range edge calculations */
13580 cleanup_live_edges(&rstate);
13583 fprintf(stderr, "coalescing\n");
13585 /* Compute the interference graph */
13586 walk_variable_lifetimes(
13587 state, rstate.blocks, graph_ins, &rstate);
13589 /* Display the interference graph if desired */
13590 if (state->debug & DEBUG_INTERFERENCE) {
13591 printf("\nlive variables by block\n");
13592 walk_blocks(state, print_interference_block, &rstate);
13593 printf("\nlive variables by instruction\n");
13594 walk_variable_lifetimes(
13595 state, rstate.blocks,
13596 print_interference_ins, &rstate);
13598 #if DEBUG_CONSISTENCY
13599 /* Verify the interference graph */
13600 walk_variable_lifetimes(
13601 state, rstate.blocks, verify_graph_ins, &rstate);
13604 coalesced = coalesce_live_ranges(state, &rstate);
13605 } while(coalesced);
13607 /* Build the groups low and high. But with the nodes
13608 * first sorted by degree order.
13610 rstate.low_tail = &rstate.low;
13611 rstate.high_tail = &rstate.high;
13612 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13614 rstate.high->group_prev = &rstate.high;
13616 for(point = &rstate.high; *point; point = &(*point)->group_next)
13618 rstate.high_tail = point;
13619 /* Walk through the high list and move everything that needs
13622 for(point = &rstate.high; *point; point = next) {
13623 struct live_range *range;
13624 next = &(*point)->group_next;
13627 /* If it has a low degree or it already has a color
13628 * place the node in low.
13630 if ((range->degree < regc_max_size(state, range->classes)) ||
13631 (range->color != REG_UNSET)) {
13632 cgdebug_printf("Lo: %5d degree %5d%s\n",
13633 range - rstate.lr, range->degree,
13634 (range->color != REG_UNSET) ? " (colored)": "");
13635 *range->group_prev = range->group_next;
13636 if (range->group_next) {
13637 range->group_next->group_prev = range->group_prev;
13639 if (&range->group_next == rstate.high_tail) {
13640 rstate.high_tail = range->group_prev;
13642 range->group_prev = rstate.low_tail;
13643 range->group_next = 0;
13644 *rstate.low_tail = range;
13645 rstate.low_tail = &range->group_next;
13649 cgdebug_printf("hi: %5d degree %5d%s\n",
13650 range - rstate.lr, range->degree,
13651 (range->color != REG_UNSET) ? " (colored)": "");
13654 /* Color the live_ranges */
13655 colored = color_graph(state, &rstate);
13657 } while (!colored);
13659 /* Verify the graph was properly colored */
13660 verify_colors(state, &rstate);
13662 /* Move the colors from the graph to the triples */
13663 color_triples(state, &rstate);
13665 /* Cleanup the temporary data structures */
13666 cleanup_rstate(state, &rstate);
13669 /* Sparce Conditional Constant Propogation
13670 * =========================================
13674 struct lattice_node {
13676 struct triple *def;
13677 struct ssa_edge *out;
13678 struct flow_block *fblock;
13679 struct triple *val;
13680 /* lattice high val && !is_const(val)
13681 * lattice const is_const(val)
13682 * lattice low val == 0
13686 struct lattice_node *src;
13687 struct lattice_node *dst;
13688 struct ssa_edge *work_next;
13689 struct ssa_edge *work_prev;
13690 struct ssa_edge *out_next;
13693 struct flow_block *src;
13694 struct flow_block *dst;
13695 struct flow_edge *work_next;
13696 struct flow_edge *work_prev;
13697 struct flow_edge *in_next;
13698 struct flow_edge *out_next;
13701 struct flow_block {
13702 struct block *block;
13703 struct flow_edge *in;
13704 struct flow_edge *out;
13705 struct flow_edge left, right;
13710 struct lattice_node *lattice;
13711 struct ssa_edge *ssa_edges;
13712 struct flow_block *flow_blocks;
13713 struct flow_edge *flow_work_list;
13714 struct ssa_edge *ssa_work_list;
13718 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13719 struct flow_edge *fedge)
13721 if (!scc->flow_work_list) {
13722 scc->flow_work_list = fedge;
13723 fedge->work_next = fedge->work_prev = fedge;
13726 struct flow_edge *ftail;
13727 ftail = scc->flow_work_list->work_prev;
13728 fedge->work_next = ftail->work_next;
13729 fedge->work_prev = ftail;
13730 fedge->work_next->work_prev = fedge;
13731 fedge->work_prev->work_next = fedge;
13735 static struct flow_edge *scc_next_fedge(
13736 struct compile_state *state, struct scc_state *scc)
13738 struct flow_edge *fedge;
13739 fedge = scc->flow_work_list;
13741 fedge->work_next->work_prev = fedge->work_prev;
13742 fedge->work_prev->work_next = fedge->work_next;
13743 if (fedge->work_next != fedge) {
13744 scc->flow_work_list = fedge->work_next;
13746 scc->flow_work_list = 0;
13752 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13753 struct ssa_edge *sedge)
13755 if (!scc->ssa_work_list) {
13756 scc->ssa_work_list = sedge;
13757 sedge->work_next = sedge->work_prev = sedge;
13760 struct ssa_edge *stail;
13761 stail = scc->ssa_work_list->work_prev;
13762 sedge->work_next = stail->work_next;
13763 sedge->work_prev = stail;
13764 sedge->work_next->work_prev = sedge;
13765 sedge->work_prev->work_next = sedge;
13769 static struct ssa_edge *scc_next_sedge(
13770 struct compile_state *state, struct scc_state *scc)
13772 struct ssa_edge *sedge;
13773 sedge = scc->ssa_work_list;
13775 sedge->work_next->work_prev = sedge->work_prev;
13776 sedge->work_prev->work_next = sedge->work_next;
13777 if (sedge->work_next != sedge) {
13778 scc->ssa_work_list = sedge->work_next;
13780 scc->ssa_work_list = 0;
13786 static void initialize_scc_state(
13787 struct compile_state *state, struct scc_state *scc)
13789 int ins_count, ssa_edge_count;
13790 int ins_index, ssa_edge_index, fblock_index;
13791 struct triple *first, *ins;
13792 struct block *block;
13793 struct flow_block *fblock;
13795 memset(scc, 0, sizeof(*scc));
13797 /* Inialize pass zero find out how much memory we need */
13798 first = RHS(state->main_function, 0);
13800 ins_count = ssa_edge_count = 0;
13802 struct triple_set *edge;
13804 for(edge = ins->use; edge; edge = edge->next) {
13808 } while(ins != first);
13810 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13811 ins_count, ssa_edge_count, state->last_vertex);
13813 scc->ins_count = ins_count;
13815 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13817 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13819 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
13822 /* Initialize pass one collect up the nodes */
13825 ins_index = ssa_edge_index = fblock_index = 0;
13828 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13829 block = ins->u.block;
13831 internal_error(state, ins, "label without block");
13834 block->vertex = fblock_index;
13835 fblock = &scc->flow_blocks[fblock_index];
13836 fblock->block = block;
13839 struct lattice_node *lnode;
13841 lnode = &scc->lattice[ins_index];
13844 lnode->fblock = fblock;
13845 lnode->val = ins; /* LATTICE HIGH */
13846 lnode->old_id = ins->id;
13847 ins->id = ins_index;
13850 } while(ins != first);
13851 /* Initialize pass two collect up the edges */
13856 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13857 struct flow_edge *fedge, **ftail;
13858 struct block_set *bedge;
13859 block = ins->u.block;
13860 fblock = &scc->flow_blocks[block->vertex];
13863 ftail = &fblock->out;
13865 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13866 if (fblock->left.dst->block != block->left) {
13867 internal_error(state, 0, "block mismatch");
13869 fblock->left.out_next = 0;
13870 *ftail = &fblock->left;
13871 ftail = &fblock->left.out_next;
13873 if (block->right) {
13874 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13875 if (fblock->right.dst->block != block->right) {
13876 internal_error(state, 0, "block mismatch");
13878 fblock->right.out_next = 0;
13879 *ftail = &fblock->right;
13880 ftail = &fblock->right.out_next;
13882 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13883 fedge->src = fblock;
13884 fedge->work_next = fedge->work_prev = fedge;
13885 fedge->executable = 0;
13887 ftail = &fblock->in;
13888 for(bedge = block->use; bedge; bedge = bedge->next) {
13889 struct block *src_block;
13890 struct flow_block *sfblock;
13891 struct flow_edge *sfedge;
13892 src_block = bedge->member;
13893 sfblock = &scc->flow_blocks[src_block->vertex];
13895 if (src_block->left == block) {
13896 sfedge = &sfblock->left;
13898 sfedge = &sfblock->right;
13901 ftail = &sfedge->in_next;
13902 sfedge->in_next = 0;
13906 struct triple_set *edge;
13907 struct ssa_edge **stail;
13908 struct lattice_node *lnode;
13909 lnode = &scc->lattice[ins->id];
13911 stail = &lnode->out;
13912 for(edge = ins->use; edge; edge = edge->next) {
13913 struct ssa_edge *sedge;
13914 ssa_edge_index += 1;
13915 sedge = &scc->ssa_edges[ssa_edge_index];
13917 stail = &sedge->out_next;
13918 sedge->src = lnode;
13919 sedge->dst = &scc->lattice[edge->member->id];
13920 sedge->work_next = sedge->work_prev = sedge;
13921 sedge->out_next = 0;
13925 } while(ins != first);
13926 /* Setup a dummy block 0 as a node above the start node */
13928 struct flow_block *fblock, *dst;
13929 struct flow_edge *fedge;
13930 fblock = &scc->flow_blocks[0];
13933 fblock->out = &fblock->left;
13934 dst = &scc->flow_blocks[state->first_block->vertex];
13935 fedge = &fblock->left;
13936 fedge->src = fblock;
13938 fedge->work_next = fedge;
13939 fedge->work_prev = fedge;
13940 fedge->in_next = fedge->dst->in;
13941 fedge->out_next = 0;
13942 fedge->executable = 0;
13943 fedge->dst->in = fedge;
13945 /* Initialize the work lists */
13946 scc->flow_work_list = 0;
13947 scc->ssa_work_list = 0;
13948 scc_add_fedge(state, scc, fedge);
13951 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
13952 ins_index, ssa_edge_index, fblock_index);
13957 static void free_scc_state(
13958 struct compile_state *state, struct scc_state *scc)
13960 xfree(scc->flow_blocks);
13961 xfree(scc->ssa_edges);
13962 xfree(scc->lattice);
13966 static struct lattice_node *triple_to_lattice(
13967 struct compile_state *state, struct scc_state *scc, struct triple *ins)
13969 if (ins->id <= 0) {
13970 internal_error(state, ins, "bad id");
13972 return &scc->lattice[ins->id];
13975 static struct triple *preserve_lval(
13976 struct compile_state *state, struct lattice_node *lnode)
13978 struct triple *old;
13979 /* Preserve the original value */
13981 old = dup_triple(state, lnode->val);
13982 if (lnode->val != lnode->def) {
13992 static int lval_changed(struct compile_state *state,
13993 struct triple *old, struct lattice_node *lnode)
13996 /* See if the lattice value has changed */
13998 if (!old && !lnode->val) {
14001 if (changed && lnode->val && !is_const(lnode->val)) {
14005 lnode->val && old &&
14006 (memcmp(lnode->val->param, old->param,
14007 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14008 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14018 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
14019 struct lattice_node *lnode)
14021 struct lattice_node *tmp;
14022 struct triple **slot, *old;
14023 struct flow_edge *fedge;
14025 if (lnode->def->op != OP_PHI) {
14026 internal_error(state, lnode->def, "not phi");
14028 /* Store the original value */
14029 old = preserve_lval(state, lnode);
14031 /* default to lattice high */
14032 lnode->val = lnode->def;
14033 slot = &RHS(lnode->def, 0);
14035 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14036 if (!fedge->executable) {
14039 if (!slot[index]) {
14040 internal_error(state, lnode->def, "no phi value");
14042 tmp = triple_to_lattice(state, scc, slot[index]);
14043 /* meet(X, lattice low) = lattice low */
14047 /* meet(X, lattice high) = X */
14048 else if (!tmp->val) {
14049 lnode->val = lnode->val;
14051 /* meet(lattice high, X) = X */
14052 else if (!is_const(lnode->val)) {
14053 lnode->val = dup_triple(state, tmp->val);
14054 lnode->val->type = lnode->def->type;
14056 /* meet(const, const) = const or lattice low */
14057 else if (!constants_equal(state, lnode->val, tmp->val)) {
14065 fprintf(stderr, "phi: %d -> %s\n",
14067 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14069 /* If the lattice value has changed update the work lists. */
14070 if (lval_changed(state, old, lnode)) {
14071 struct ssa_edge *sedge;
14072 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14073 scc_add_sedge(state, scc, sedge);
14078 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14079 struct lattice_node *lnode)
14082 struct triple *old, *scratch;
14083 struct triple **dexpr, **vexpr;
14086 /* Store the original value */
14087 old = preserve_lval(state, lnode);
14089 /* Reinitialize the value */
14090 lnode->val = scratch = dup_triple(state, lnode->def);
14091 scratch->id = lnode->old_id;
14092 scratch->next = scratch;
14093 scratch->prev = scratch;
14096 count = TRIPLE_SIZE(scratch->sizes);
14097 for(i = 0; i < count; i++) {
14098 dexpr = &lnode->def->param[i];
14099 vexpr = &scratch->param[i];
14101 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14102 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14104 struct lattice_node *tmp;
14105 tmp = triple_to_lattice(state, scc, *dexpr);
14106 *vexpr = (tmp->val)? tmp->val : tmp->def;
14109 if (scratch->op == OP_BRANCH) {
14110 scratch->next = lnode->def->next;
14112 /* Recompute the value */
14113 #warning "FIXME see if simplify does anything bad"
14114 /* So far it looks like only the strength reduction
14115 * optimization are things I need to worry about.
14117 simplify(state, scratch);
14118 /* Cleanup my value */
14119 if (scratch->use) {
14120 internal_error(state, lnode->def, "scratch used?");
14122 if ((scratch->prev != scratch) ||
14123 ((scratch->next != scratch) &&
14124 ((lnode->def->op != OP_BRANCH) ||
14125 (scratch->next != lnode->def->next)))) {
14126 internal_error(state, lnode->def, "scratch in list?");
14128 /* undo any uses... */
14129 count = TRIPLE_SIZE(scratch->sizes);
14130 for(i = 0; i < count; i++) {
14131 vexpr = &scratch->param[i];
14133 unuse_triple(*vexpr, scratch);
14136 if (!is_const(scratch)) {
14137 for(i = 0; i < count; i++) {
14138 dexpr = &lnode->def->param[i];
14139 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14140 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14142 struct lattice_node *tmp;
14143 tmp = triple_to_lattice(state, scc, *dexpr);
14151 (lnode->val->op == lnode->def->op) &&
14152 (memcmp(lnode->val->param, lnode->def->param,
14153 count * sizeof(lnode->val->param[0])) == 0) &&
14154 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14155 lnode->val = lnode->def;
14157 /* Find the cases that are always lattice lo */
14159 triple_is_def(state, lnode->val) &&
14160 !triple_is_pure(state, lnode->val)) {
14164 (lnode->val->op == OP_SDECL) &&
14165 (lnode->val != lnode->def)) {
14166 internal_error(state, lnode->def, "bad sdecl");
14168 /* See if the lattice value has changed */
14169 changed = lval_changed(state, old, lnode);
14170 if (lnode->val != scratch) {
14176 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14177 struct lattice_node *lnode)
14179 struct lattice_node *cond;
14182 struct flow_edge *fedge;
14183 fprintf(stderr, "branch: %d (",
14186 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14187 fprintf(stderr, " %d", fedge->dst->block->vertex);
14189 fprintf(stderr, " )");
14190 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14191 fprintf(stderr, " <- %d",
14192 RHS(lnode->def, 0)->id);
14194 fprintf(stderr, "\n");
14197 if (lnode->def->op != OP_BRANCH) {
14198 internal_error(state, lnode->def, "not branch");
14200 /* This only applies to conditional branches */
14201 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14204 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14205 if (cond->val && !is_const(cond->val)) {
14206 #warning "FIXME do I need to do something here?"
14207 warning(state, cond->def, "condition not constant?");
14210 if (cond->val == 0) {
14211 scc_add_fedge(state, scc, cond->fblock->out);
14212 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14214 else if (cond->val->u.cval) {
14215 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14218 scc_add_fedge(state, scc, cond->fblock->out);
14223 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14224 struct lattice_node *lnode)
14228 changed = compute_lnode_val(state, scc, lnode);
14231 struct triple **expr;
14232 fprintf(stderr, "expr: %3d %10s (",
14233 lnode->def->id, tops(lnode->def->op));
14234 expr = triple_rhs(state, lnode->def, 0);
14235 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14237 fprintf(stderr, " %d", (*expr)->id);
14240 fprintf(stderr, " ) -> %s\n",
14241 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14244 if (lnode->def->op == OP_BRANCH) {
14245 scc_visit_branch(state, scc, lnode);
14248 else if (changed) {
14249 struct ssa_edge *sedge;
14250 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14251 scc_add_sedge(state, scc, sedge);
14256 static void scc_writeback_values(
14257 struct compile_state *state, struct scc_state *scc)
14259 struct triple *first, *ins;
14260 first = RHS(state->main_function, 0);
14263 struct lattice_node *lnode;
14264 lnode = triple_to_lattice(state, scc, ins);
14266 ins->id = lnode->old_id;
14268 if (lnode->val && !is_const(lnode->val)) {
14269 warning(state, lnode->def,
14270 "lattice node still high?");
14273 if (lnode->val && (lnode->val != ins)) {
14274 /* See if it something I know how to write back */
14275 switch(lnode->val->op) {
14277 mkconst(state, ins, lnode->val->u.cval);
14280 mkaddr_const(state, ins,
14281 MISC(lnode->val, 0), lnode->val->u.cval);
14284 /* By default don't copy the changes,
14285 * recompute them in place instead.
14287 simplify(state, ins);
14290 if (is_const(lnode->val) &&
14291 !constants_equal(state, lnode->val, ins)) {
14292 internal_error(state, 0, "constants not equal");
14294 /* Free the lattice nodes */
14299 } while(ins != first);
14302 static void scc_transform(struct compile_state *state)
14304 struct scc_state scc;
14306 initialize_scc_state(state, &scc);
14308 while(scc.flow_work_list || scc.ssa_work_list) {
14309 struct flow_edge *fedge;
14310 struct ssa_edge *sedge;
14311 struct flow_edge *fptr;
14312 while((fedge = scc_next_fedge(state, &scc))) {
14313 struct block *block;
14314 struct triple *ptr;
14315 struct flow_block *fblock;
14318 if (fedge->executable) {
14322 internal_error(state, 0, "fedge without dst");
14325 internal_error(state, 0, "fedge without src");
14327 fedge->executable = 1;
14328 fblock = fedge->dst;
14329 block = fblock->block;
14331 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14332 if (fptr->executable) {
14337 fprintf(stderr, "vertex: %d time: %d\n",
14338 block->vertex, time);
14342 for(ptr = block->first; !done; ptr = ptr->next) {
14343 struct lattice_node *lnode;
14344 done = (ptr == block->last);
14345 lnode = &scc.lattice[ptr->id];
14346 if (ptr->op == OP_PHI) {
14347 scc_visit_phi(state, &scc, lnode);
14349 else if (time == 1) {
14350 scc_visit_expr(state, &scc, lnode);
14353 if (fblock->out && !fblock->out->out_next) {
14354 scc_add_fedge(state, &scc, fblock->out);
14357 while((sedge = scc_next_sedge(state, &scc))) {
14358 struct lattice_node *lnode;
14359 struct flow_block *fblock;
14360 lnode = sedge->dst;
14361 fblock = lnode->fblock;
14363 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14364 sedge - scc.ssa_edges,
14365 sedge->src->def->id,
14366 sedge->dst->def->id);
14368 if (lnode->def->op == OP_PHI) {
14369 scc_visit_phi(state, &scc, lnode);
14372 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14373 if (fptr->executable) {
14378 scc_visit_expr(state, &scc, lnode);
14384 scc_writeback_values(state, &scc);
14385 free_scc_state(state, &scc);
14389 static void transform_to_arch_instructions(struct compile_state *state)
14391 struct triple *ins, *first;
14392 first = RHS(state->main_function, 0);
14395 ins = transform_to_arch_instruction(state, ins);
14396 } while(ins != first);
14399 #if DEBUG_CONSISTENCY
14400 static void verify_uses(struct compile_state *state)
14402 struct triple *first, *ins;
14403 struct triple_set *set;
14404 first = RHS(state->main_function, 0);
14407 struct triple **expr;
14408 expr = triple_rhs(state, ins, 0);
14409 for(; expr; expr = triple_rhs(state, ins, expr)) {
14410 struct triple *rhs;
14412 for(set = rhs?rhs->use:0; set; set = set->next) {
14413 if (set->member == ins) {
14418 internal_error(state, ins, "rhs not used");
14421 expr = triple_lhs(state, ins, 0);
14422 for(; expr; expr = triple_lhs(state, ins, expr)) {
14423 struct triple *lhs;
14425 for(set = lhs?lhs->use:0; set; set = set->next) {
14426 if (set->member == ins) {
14431 internal_error(state, ins, "lhs not used");
14435 } while(ins != first);
14438 static void verify_blocks(struct compile_state *state)
14440 struct triple *ins;
14441 struct block *block;
14442 block = state->first_block;
14447 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14448 if (!triple_stores_block(state, ins)) {
14451 if (ins->u.block != block) {
14452 internal_error(state, ins, "inconsitent block specified");
14455 if (!triple_stores_block(state, block->last->next)) {
14456 internal_error(state, block->last->next,
14457 "cannot find next block");
14459 block = block->last->next->u.block;
14461 internal_error(state, block->last->next,
14464 } while(block != state->first_block);
14467 static void verify_domination(struct compile_state *state)
14469 struct triple *first, *ins;
14470 struct triple_set *set;
14471 if (!state->first_block) {
14475 first = RHS(state->main_function, 0);
14478 for(set = ins->use; set; set = set->next) {
14479 struct triple **expr;
14480 if (set->member->op == OP_PHI) {
14483 /* See if the use is on the righ hand side */
14484 expr = triple_rhs(state, set->member, 0);
14485 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14486 if (*expr == ins) {
14491 !tdominates(state, ins, set->member)) {
14492 internal_error(state, set->member,
14493 "non dominated rhs use?");
14497 } while(ins != first);
14500 static void verify_piece(struct compile_state *state)
14502 struct triple *first, *ins;
14503 first = RHS(state->main_function, 0);
14506 struct triple *ptr;
14508 lhs = TRIPLE_LHS(ins->sizes);
14509 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14512 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14513 if (ptr != LHS(ins, i)) {
14514 internal_error(state, ins, "malformed lhs on %s",
14517 if (ptr->op != OP_PIECE) {
14518 internal_error(state, ins, "bad lhs op %s at %d on %s",
14519 tops(ptr->op), i, tops(ins->op));
14521 if (ptr->u.cval != i) {
14522 internal_error(state, ins, "bad u.cval of %d %d expected",
14527 } while(ins != first);
14529 static void verify_ins_colors(struct compile_state *state)
14531 struct triple *first, *ins;
14533 first = RHS(state->main_function, 0);
14537 } while(ins != first);
14539 static void verify_consistency(struct compile_state *state)
14541 verify_uses(state);
14542 verify_blocks(state);
14543 verify_domination(state);
14544 verify_piece(state);
14545 verify_ins_colors(state);
14548 #define verify_consistency(state) do {} while(0)
14549 #endif /* DEBUG_USES */
14551 static void optimize(struct compile_state *state)
14553 if (state->debug & DEBUG_TRIPLES) {
14554 print_triples(state);
14556 /* Replace structures with simpler data types */
14557 flatten_structures(state);
14558 if (state->debug & DEBUG_TRIPLES) {
14559 print_triples(state);
14561 verify_consistency(state);
14562 /* Analize the intermediate code */
14563 setup_basic_blocks(state);
14564 analyze_idominators(state);
14565 analyze_ipdominators(state);
14566 /* Transform the code to ssa form */
14567 transform_to_ssa_form(state);
14568 verify_consistency(state);
14569 if (state->debug & DEBUG_CODE_ELIMINATION) {
14570 fprintf(stdout, "After transform_to_ssa_form\n");
14571 print_blocks(state, stdout);
14573 /* Do strength reduction and simple constant optimizations */
14574 if (state->optimize >= 1) {
14575 simplify_all(state);
14577 verify_consistency(state);
14578 /* Propogate constants throughout the code */
14579 if (state->optimize >= 2) {
14580 #warning "FIXME fix scc_transform"
14581 scc_transform(state);
14582 transform_from_ssa_form(state);
14583 free_basic_blocks(state);
14584 setup_basic_blocks(state);
14585 analyze_idominators(state);
14586 analyze_ipdominators(state);
14587 transform_to_ssa_form(state);
14589 verify_consistency(state);
14590 #warning "WISHLIST implement single use constants (least possible register pressure)"
14591 #warning "WISHLIST implement induction variable elimination"
14592 /* Select architecture instructions and an initial partial
14593 * coloring based on architecture constraints.
14595 transform_to_arch_instructions(state);
14596 verify_consistency(state);
14597 if (state->debug & DEBUG_ARCH_CODE) {
14598 printf("After transform_to_arch_instructions\n");
14599 print_blocks(state, stdout);
14600 print_control_flow(state);
14602 eliminate_inefectual_code(state);
14603 verify_consistency(state);
14604 if (state->debug & DEBUG_CODE_ELIMINATION) {
14605 printf("After eliminate_inefectual_code\n");
14606 print_blocks(state, stdout);
14607 print_control_flow(state);
14609 verify_consistency(state);
14610 /* Color all of the variables to see if they will fit in registers */
14611 insert_copies_to_phi(state);
14612 if (state->debug & DEBUG_INSERTED_COPIES) {
14613 printf("After insert_copies_to_phi\n");
14614 print_blocks(state, stdout);
14615 print_control_flow(state);
14617 verify_consistency(state);
14618 insert_mandatory_copies(state);
14619 if (state->debug & DEBUG_INSERTED_COPIES) {
14620 printf("After insert_mandatory_copies\n");
14621 print_blocks(state, stdout);
14622 print_control_flow(state);
14624 verify_consistency(state);
14625 allocate_registers(state);
14626 verify_consistency(state);
14627 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14628 print_blocks(state, stdout);
14630 if (state->debug & DEBUG_CONTROL_FLOW) {
14631 print_control_flow(state);
14633 /* Remove the optimization information.
14634 * This is more to check for memory consistency than to free memory.
14636 free_basic_blocks(state);
14639 static void print_op_asm(struct compile_state *state,
14640 struct triple *ins, FILE *fp)
14642 struct asm_info *info;
14644 unsigned lhs, rhs, i;
14645 info = ins->u.ainfo;
14646 lhs = TRIPLE_LHS(ins->sizes);
14647 rhs = TRIPLE_RHS(ins->sizes);
14648 /* Don't count the clobbers in lhs */
14649 for(i = 0; i < lhs; i++) {
14650 if (LHS(ins, i)->type == &void_type) {
14655 fprintf(fp, "#ASM\n");
14657 for(ptr = info->str; *ptr; ptr++) {
14659 unsigned long param;
14660 struct triple *piece;
14670 param = strtoul(ptr, &next, 10);
14672 error(state, ins, "Invalid asm template");
14674 if (param >= (lhs + rhs)) {
14675 error(state, ins, "Invalid param %%%u in asm template",
14678 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14680 arch_reg_str(ID_REG(piece->id)));
14683 fprintf(fp, "\n#NOT ASM\n");
14687 /* Only use the low x86 byte registers. This allows me
14688 * allocate the entire register when a byte register is used.
14690 #define X86_4_8BIT_GPRS 1
14692 /* Recognized x86 cpu variants */
14700 #define CPU_DEFAULT CPU_I386
14702 /* The x86 register classes */
14703 #define REGC_FLAGS 0
14704 #define REGC_GPR8 1
14705 #define REGC_GPR16 2
14706 #define REGC_GPR32 3
14707 #define REGC_GPR64 4
14710 #define REGC_GPR32_8 7
14711 #define REGC_GPR16_8 8
14712 #define REGC_IMM32 9
14713 #define REGC_IMM16 10
14714 #define REGC_IMM8 11
14715 #define LAST_REGC REGC_IMM8
14716 #if LAST_REGC >= MAX_REGC
14717 #error "MAX_REGC is to low"
14720 /* Register class masks */
14721 #define REGCM_FLAGS (1 << REGC_FLAGS)
14722 #define REGCM_GPR8 (1 << REGC_GPR8)
14723 #define REGCM_GPR16 (1 << REGC_GPR16)
14724 #define REGCM_GPR32 (1 << REGC_GPR32)
14725 #define REGCM_GPR64 (1 << REGC_GPR64)
14726 #define REGCM_MMX (1 << REGC_MMX)
14727 #define REGCM_XMM (1 << REGC_XMM)
14728 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14729 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14730 #define REGCM_IMM32 (1 << REGC_IMM32)
14731 #define REGCM_IMM16 (1 << REGC_IMM16)
14732 #define REGCM_IMM8 (1 << REGC_IMM8)
14733 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
14735 /* The x86 registers */
14736 #define REG_EFLAGS 2
14737 #define REGC_FLAGS_FIRST REG_EFLAGS
14738 #define REGC_FLAGS_LAST REG_EFLAGS
14747 #define REGC_GPR8_FIRST REG_AL
14748 #if X86_4_8BIT_GPRS
14749 #define REGC_GPR8_LAST REG_DL
14751 #define REGC_GPR8_LAST REG_DH
14761 #define REGC_GPR16_FIRST REG_AX
14762 #define REGC_GPR16_LAST REG_SP
14771 #define REGC_GPR32_FIRST REG_EAX
14772 #define REGC_GPR32_LAST REG_ESP
14773 #define REG_EDXEAX 27
14774 #define REGC_GPR64_FIRST REG_EDXEAX
14775 #define REGC_GPR64_LAST REG_EDXEAX
14776 #define REG_MMX0 28
14777 #define REG_MMX1 29
14778 #define REG_MMX2 30
14779 #define REG_MMX3 31
14780 #define REG_MMX4 32
14781 #define REG_MMX5 33
14782 #define REG_MMX6 34
14783 #define REG_MMX7 35
14784 #define REGC_MMX_FIRST REG_MMX0
14785 #define REGC_MMX_LAST REG_MMX7
14786 #define REG_XMM0 36
14787 #define REG_XMM1 37
14788 #define REG_XMM2 38
14789 #define REG_XMM3 39
14790 #define REG_XMM4 40
14791 #define REG_XMM5 41
14792 #define REG_XMM6 42
14793 #define REG_XMM7 43
14794 #define REGC_XMM_FIRST REG_XMM0
14795 #define REGC_XMM_LAST REG_XMM7
14796 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14797 #define LAST_REG REG_XMM7
14799 #define REGC_GPR32_8_FIRST REG_EAX
14800 #define REGC_GPR32_8_LAST REG_EDX
14801 #define REGC_GPR16_8_FIRST REG_AX
14802 #define REGC_GPR16_8_LAST REG_DX
14804 #define REGC_IMM8_FIRST -1
14805 #define REGC_IMM8_LAST -1
14806 #define REGC_IMM16_FIRST -2
14807 #define REGC_IMM16_LAST -1
14808 #define REGC_IMM32_FIRST -4
14809 #define REGC_IMM32_LAST -1
14811 #if LAST_REG >= MAX_REGISTERS
14812 #error "MAX_REGISTERS to low"
14816 static unsigned regc_size[LAST_REGC +1] = {
14817 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
14818 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
14819 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
14820 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
14821 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
14822 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
14823 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
14824 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14825 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14831 static const struct {
14833 } regcm_bound[LAST_REGC + 1] = {
14834 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
14835 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
14836 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
14837 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
14838 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
14839 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
14840 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
14841 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14842 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14843 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
14844 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
14845 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
14848 static int arch_encode_cpu(const char *cpu)
14854 { "i386", CPU_I386 },
14862 for(ptr = cpus; ptr->name; ptr++) {
14863 if (strcmp(ptr->name, cpu) == 0) {
14870 static unsigned arch_regc_size(struct compile_state *state, int class)
14872 if ((class < 0) || (class > LAST_REGC)) {
14875 return regc_size[class];
14877 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14879 /* See if two register classes may have overlapping registers */
14880 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14881 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14883 /* Special case for the immediates */
14884 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14885 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14886 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14887 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
14890 return (regcm1 & regcm2) ||
14891 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14894 static void arch_reg_equivs(
14895 struct compile_state *state, unsigned *equiv, int reg)
14897 if ((reg < 0) || (reg > LAST_REG)) {
14898 internal_error(state, 0, "invalid register");
14903 #if X86_4_8BIT_GPRS
14907 *equiv++ = REG_EAX;
14908 *equiv++ = REG_EDXEAX;
14911 #if X86_4_8BIT_GPRS
14915 *equiv++ = REG_EAX;
14916 *equiv++ = REG_EDXEAX;
14919 #if X86_4_8BIT_GPRS
14923 *equiv++ = REG_EBX;
14927 #if X86_4_8BIT_GPRS
14931 *equiv++ = REG_EBX;
14934 #if X86_4_8BIT_GPRS
14938 *equiv++ = REG_ECX;
14942 #if X86_4_8BIT_GPRS
14946 *equiv++ = REG_ECX;
14949 #if X86_4_8BIT_GPRS
14953 *equiv++ = REG_EDX;
14954 *equiv++ = REG_EDXEAX;
14957 #if X86_4_8BIT_GPRS
14961 *equiv++ = REG_EDX;
14962 *equiv++ = REG_EDXEAX;
14967 *equiv++ = REG_EAX;
14968 *equiv++ = REG_EDXEAX;
14973 *equiv++ = REG_EBX;
14978 *equiv++ = REG_ECX;
14983 *equiv++ = REG_EDX;
14984 *equiv++ = REG_EDXEAX;
14987 *equiv++ = REG_ESI;
14990 *equiv++ = REG_EDI;
14993 *equiv++ = REG_EBP;
14996 *equiv++ = REG_ESP;
15002 *equiv++ = REG_EDXEAX;
15018 *equiv++ = REG_EDXEAX;
15039 *equiv++ = REG_EAX;
15040 *equiv++ = REG_EDX;
15043 *equiv++ = REG_UNSET;
15046 static unsigned arch_avail_mask(struct compile_state *state)
15048 unsigned avail_mask;
15049 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
15050 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
15051 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15052 switch(state->cpu) {
15055 avail_mask |= REGCM_MMX;
15059 avail_mask |= REGCM_MMX | REGCM_XMM;
15063 /* Don't enable 8 bit values until I can force both operands
15064 * to be 8bits simultaneously.
15066 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
15071 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15073 unsigned mask, result;
15076 result &= arch_avail_mask(state);
15078 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15079 if ((result & mask) == 0) {
15082 if (class > LAST_REGC) {
15085 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15086 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15087 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15088 result |= (1 << class2);
15095 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15100 for(class = 0; class <= LAST_REGC; class++) {
15101 if ((reg >= regcm_bound[class].first) &&
15102 (reg <= regcm_bound[class].last)) {
15103 mask |= (1 << class);
15107 internal_error(state, 0, "reg %d not in any class", reg);
15112 static struct reg_info arch_reg_constraint(
15113 struct compile_state *state, struct type *type, const char *constraint)
15115 static const struct {
15119 } constraints[] = {
15120 { 'r', REGCM_GPR32, REG_UNSET },
15121 { 'g', REGCM_GPR32, REG_UNSET },
15122 { 'p', REGCM_GPR32, REG_UNSET },
15123 { 'q', REGCM_GPR8, REG_UNSET },
15124 { 'Q', REGCM_GPR32_8, REG_UNSET },
15125 { 'x', REGCM_XMM, REG_UNSET },
15126 { 'y', REGCM_MMX, REG_UNSET },
15127 { 'a', REGCM_GPR32, REG_EAX },
15128 { 'b', REGCM_GPR32, REG_EBX },
15129 { 'c', REGCM_GPR32, REG_ECX },
15130 { 'd', REGCM_GPR32, REG_EDX },
15131 { 'D', REGCM_GPR32, REG_EDI },
15132 { 'S', REGCM_GPR32, REG_ESI },
15133 { '\0', 0, REG_UNSET },
15135 unsigned int regcm;
15136 unsigned int mask, reg;
15137 struct reg_info result;
15139 regcm = arch_type_to_regcm(state, type);
15142 for(ptr = constraint; *ptr; ptr++) {
15147 for(i = 0; constraints[i].class != '\0'; i++) {
15148 if (constraints[i].class == *ptr) {
15152 if (constraints[i].class == '\0') {
15153 error(state, 0, "invalid register constraint ``%c''", *ptr);
15156 if ((constraints[i].mask & regcm) == 0) {
15157 error(state, 0, "invalid register class %c specified",
15160 mask |= constraints[i].mask;
15161 if (constraints[i].reg != REG_UNSET) {
15162 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15163 error(state, 0, "Only one register may be specified");
15165 reg = constraints[i].reg;
15169 result.regcm = mask;
15173 static struct reg_info arch_reg_clobber(
15174 struct compile_state *state, const char *clobber)
15176 struct reg_info result;
15177 if (strcmp(clobber, "memory") == 0) {
15178 result.reg = REG_UNSET;
15181 else if (strcmp(clobber, "%eax") == 0) {
15182 result.reg = REG_EAX;
15183 result.regcm = REGCM_GPR32;
15185 else if (strcmp(clobber, "%ebx") == 0) {
15186 result.reg = REG_EBX;
15187 result.regcm = REGCM_GPR32;
15189 else if (strcmp(clobber, "%ecx") == 0) {
15190 result.reg = REG_ECX;
15191 result.regcm = REGCM_GPR32;
15193 else if (strcmp(clobber, "%edx") == 0) {
15194 result.reg = REG_EDX;
15195 result.regcm = REGCM_GPR32;
15197 else if (strcmp(clobber, "%esi") == 0) {
15198 result.reg = REG_ESI;
15199 result.regcm = REGCM_GPR32;
15201 else if (strcmp(clobber, "%edi") == 0) {
15202 result.reg = REG_EDI;
15203 result.regcm = REGCM_GPR32;
15205 else if (strcmp(clobber, "%ebp") == 0) {
15206 result.reg = REG_EBP;
15207 result.regcm = REGCM_GPR32;
15209 else if (strcmp(clobber, "%esp") == 0) {
15210 result.reg = REG_ESP;
15211 result.regcm = REGCM_GPR32;
15213 else if (strcmp(clobber, "cc") == 0) {
15214 result.reg = REG_EFLAGS;
15215 result.regcm = REGCM_FLAGS;
15217 else if ((strncmp(clobber, "xmm", 3) == 0) &&
15218 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15219 result.reg = REG_XMM0 + octdigval(clobber[3]);
15220 result.regcm = REGCM_XMM;
15222 else if ((strncmp(clobber, "mmx", 3) == 0) &&
15223 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15224 result.reg = REG_MMX0 + octdigval(clobber[3]);
15225 result.regcm = REGCM_MMX;
15228 error(state, 0, "Invalid register clobber");
15229 result.reg = REG_UNSET;
15235 static int do_select_reg(struct compile_state *state,
15236 char *used, int reg, unsigned classes)
15242 mask = arch_reg_regcm(state, reg);
15243 return (classes & mask) ? reg : REG_UNSET;
15246 static int arch_select_free_register(
15247 struct compile_state *state, char *used, int classes)
15249 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
15250 * other types of registers.
15254 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15255 reg = do_select_reg(state, used, i, classes);
15257 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
15258 reg = do_select_reg(state, used, i, classes);
15260 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15261 reg = do_select_reg(state, used, i, classes);
15263 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15264 reg = do_select_reg(state, used, i, classes);
15266 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15267 reg = do_select_reg(state, used, i, classes);
15269 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15270 reg = do_select_reg(state, used, i, classes);
15272 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
15273 reg = do_select_reg(state, used, i, classes);
15279 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
15281 #warning "FIXME force types smaller (if legal) before I get here"
15282 unsigned avail_mask;
15285 avail_mask = arch_avail_mask(state);
15286 switch(type->type & TYPE_MASK) {
15293 mask = REGCM_GPR8 |
15294 REGCM_GPR16 | REGCM_GPR16_8 |
15295 REGCM_GPR32 | REGCM_GPR32_8 |
15297 REGCM_MMX | REGCM_XMM |
15298 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15302 mask = REGCM_GPR16 | REGCM_GPR16_8 |
15303 REGCM_GPR32 | REGCM_GPR32_8 |
15305 REGCM_MMX | REGCM_XMM |
15306 REGCM_IMM32 | REGCM_IMM16;
15313 mask = REGCM_GPR32 | REGCM_GPR32_8 |
15314 REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15318 internal_error(state, 0, "no register class for type");
15321 mask &= avail_mask;
15325 static int is_imm32(struct triple *imm)
15327 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15328 (imm->op == OP_ADDRCONST);
15331 static int is_imm16(struct triple *imm)
15333 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15335 static int is_imm8(struct triple *imm)
15337 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15340 static int get_imm32(struct triple *ins, struct triple **expr)
15342 struct triple *imm;
15344 while(imm->op == OP_COPY) {
15347 if (!is_imm32(imm)) {
15350 unuse_triple(*expr, ins);
15351 use_triple(imm, ins);
15356 static int get_imm8(struct triple *ins, struct triple **expr)
15358 struct triple *imm;
15360 while(imm->op == OP_COPY) {
15363 if (!is_imm8(imm)) {
15366 unuse_triple(*expr, ins);
15367 use_triple(imm, ins);
15372 #define TEMPLATE_NOP 0
15373 #define TEMPLATE_INTCONST8 1
15374 #define TEMPLATE_INTCONST32 2
15375 #define TEMPLATE_COPY_REG 3
15376 #define TEMPLATE_COPY_IMM32 4
15377 #define TEMPLATE_COPY_IMM16 5
15378 #define TEMPLATE_COPY_IMM8 6
15379 #define TEMPLATE_PHI 7
15380 #define TEMPLATE_STORE8 8
15381 #define TEMPLATE_STORE16 9
15382 #define TEMPLATE_STORE32 10
15383 #define TEMPLATE_LOAD8 11
15384 #define TEMPLATE_LOAD16 12
15385 #define TEMPLATE_LOAD32 13
15386 #define TEMPLATE_BINARY_REG 14
15387 #define TEMPLATE_BINARY_IMM 15
15388 #define TEMPLATE_SL_CL 16
15389 #define TEMPLATE_SL_IMM 17
15390 #define TEMPLATE_UNARY 18
15391 #define TEMPLATE_CMP_REG 19
15392 #define TEMPLATE_CMP_IMM 20
15393 #define TEMPLATE_TEST 21
15394 #define TEMPLATE_SET 22
15395 #define TEMPLATE_JMP 23
15396 #define TEMPLATE_INB_DX 24
15397 #define TEMPLATE_INB_IMM 25
15398 #define TEMPLATE_INW_DX 26
15399 #define TEMPLATE_INW_IMM 27
15400 #define TEMPLATE_INL_DX 28
15401 #define TEMPLATE_INL_IMM 29
15402 #define TEMPLATE_OUTB_DX 30
15403 #define TEMPLATE_OUTB_IMM 31
15404 #define TEMPLATE_OUTW_DX 32
15405 #define TEMPLATE_OUTW_IMM 33
15406 #define TEMPLATE_OUTL_DX 34
15407 #define TEMPLATE_OUTL_IMM 35
15408 #define TEMPLATE_BSF 36
15409 #define TEMPLATE_RDMSR 37
15410 #define TEMPLATE_WRMSR 38
15411 #define LAST_TEMPLATE TEMPLATE_WRMSR
15412 #if LAST_TEMPLATE >= MAX_TEMPLATES
15413 #error "MAX_TEMPLATES to low"
15416 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15417 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15419 static struct ins_template templates[] = {
15420 [TEMPLATE_NOP] = {},
15421 [TEMPLATE_INTCONST8] = {
15422 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15424 [TEMPLATE_INTCONST32] = {
15425 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15427 [TEMPLATE_COPY_REG] = {
15428 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15429 .rhs = { [0] = { REG_UNSET, COPY_REGCM } },
15431 [TEMPLATE_COPY_IMM32] = {
15432 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15433 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15435 [TEMPLATE_COPY_IMM16] = {
15436 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
15437 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
15439 [TEMPLATE_COPY_IMM8] = {
15440 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15441 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15444 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
15446 [ 0] = { REG_VIRT0, COPY_REGCM },
15447 [ 1] = { REG_VIRT0, COPY_REGCM },
15448 [ 2] = { REG_VIRT0, COPY_REGCM },
15449 [ 3] = { REG_VIRT0, COPY_REGCM },
15450 [ 4] = { REG_VIRT0, COPY_REGCM },
15451 [ 5] = { REG_VIRT0, COPY_REGCM },
15452 [ 6] = { REG_VIRT0, COPY_REGCM },
15453 [ 7] = { REG_VIRT0, COPY_REGCM },
15454 [ 8] = { REG_VIRT0, COPY_REGCM },
15455 [ 9] = { REG_VIRT0, COPY_REGCM },
15456 [10] = { REG_VIRT0, COPY_REGCM },
15457 [11] = { REG_VIRT0, COPY_REGCM },
15458 [12] = { REG_VIRT0, COPY_REGCM },
15459 [13] = { REG_VIRT0, COPY_REGCM },
15460 [14] = { REG_VIRT0, COPY_REGCM },
15461 [15] = { REG_VIRT0, COPY_REGCM },
15463 [TEMPLATE_STORE8] = {
15464 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15465 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15467 [TEMPLATE_STORE16] = {
15468 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15469 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15471 [TEMPLATE_STORE32] = {
15472 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15473 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15475 [TEMPLATE_LOAD8] = {
15476 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15477 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15479 [TEMPLATE_LOAD16] = {
15480 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15481 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15483 [TEMPLATE_LOAD32] = {
15484 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15485 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15487 [TEMPLATE_BINARY_REG] = {
15488 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15490 [0] = { REG_VIRT0, REGCM_GPR32 },
15491 [1] = { REG_UNSET, REGCM_GPR32 },
15494 [TEMPLATE_BINARY_IMM] = {
15495 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15497 [0] = { REG_VIRT0, REGCM_GPR32 },
15498 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15501 [TEMPLATE_SL_CL] = {
15502 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15504 [0] = { REG_VIRT0, REGCM_GPR32 },
15505 [1] = { REG_CL, REGCM_GPR8 },
15508 [TEMPLATE_SL_IMM] = {
15509 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15511 [0] = { REG_VIRT0, REGCM_GPR32 },
15512 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15515 [TEMPLATE_UNARY] = {
15516 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15517 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15519 [TEMPLATE_CMP_REG] = {
15520 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15522 [0] = { REG_UNSET, REGCM_GPR32 },
15523 [1] = { REG_UNSET, REGCM_GPR32 },
15526 [TEMPLATE_CMP_IMM] = {
15527 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15529 [0] = { REG_UNSET, REGCM_GPR32 },
15530 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15533 [TEMPLATE_TEST] = {
15534 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15535 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15538 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15539 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15542 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15544 [TEMPLATE_INB_DX] = {
15545 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15546 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15548 [TEMPLATE_INB_IMM] = {
15549 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15550 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15552 [TEMPLATE_INW_DX] = {
15553 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15554 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15556 [TEMPLATE_INW_IMM] = {
15557 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15558 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15560 [TEMPLATE_INL_DX] = {
15561 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15562 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15564 [TEMPLATE_INL_IMM] = {
15565 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15566 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15568 [TEMPLATE_OUTB_DX] = {
15570 [0] = { REG_AL, REGCM_GPR8 },
15571 [1] = { REG_DX, REGCM_GPR16 },
15574 [TEMPLATE_OUTB_IMM] = {
15576 [0] = { REG_AL, REGCM_GPR8 },
15577 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15580 [TEMPLATE_OUTW_DX] = {
15582 [0] = { REG_AX, REGCM_GPR16 },
15583 [1] = { REG_DX, REGCM_GPR16 },
15586 [TEMPLATE_OUTW_IMM] = {
15588 [0] = { REG_AX, REGCM_GPR16 },
15589 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15592 [TEMPLATE_OUTL_DX] = {
15594 [0] = { REG_EAX, REGCM_GPR32 },
15595 [1] = { REG_DX, REGCM_GPR16 },
15598 [TEMPLATE_OUTL_IMM] = {
15600 [0] = { REG_EAX, REGCM_GPR32 },
15601 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15605 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15606 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15608 [TEMPLATE_RDMSR] = {
15610 [0] = { REG_EAX, REGCM_GPR32 },
15611 [1] = { REG_EDX, REGCM_GPR32 },
15613 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15615 [TEMPLATE_WRMSR] = {
15617 [0] = { REG_ECX, REGCM_GPR32 },
15618 [1] = { REG_EAX, REGCM_GPR32 },
15619 [2] = { REG_EDX, REGCM_GPR32 },
15624 static void fixup_branches(struct compile_state *state,
15625 struct triple *cmp, struct triple *use, int jmp_op)
15627 struct triple_set *entry, *next;
15628 for(entry = use->use; entry; entry = next) {
15629 next = entry->next;
15630 if (entry->member->op == OP_COPY) {
15631 fixup_branches(state, cmp, entry->member, jmp_op);
15633 else if (entry->member->op == OP_BRANCH) {
15634 struct triple *branch, *test;
15635 struct triple *left, *right;
15637 left = RHS(cmp, 0);
15638 if (TRIPLE_RHS(cmp->sizes) > 1) {
15639 right = RHS(cmp, 1);
15641 branch = entry->member;
15642 test = pre_triple(state, branch,
15643 cmp->op, cmp->type, left, right);
15644 test->template_id = TEMPLATE_TEST;
15645 if (cmp->op == OP_CMP) {
15646 test->template_id = TEMPLATE_CMP_REG;
15647 if (get_imm32(test, &RHS(test, 1))) {
15648 test->template_id = TEMPLATE_CMP_IMM;
15651 use_triple(RHS(test, 0), test);
15652 use_triple(RHS(test, 1), test);
15653 unuse_triple(RHS(branch, 0), branch);
15654 RHS(branch, 0) = test;
15655 branch->op = jmp_op;
15656 branch->template_id = TEMPLATE_JMP;
15657 use_triple(RHS(branch, 0), branch);
15662 static void bool_cmp(struct compile_state *state,
15663 struct triple *ins, int cmp_op, int jmp_op, int set_op)
15665 struct triple_set *entry, *next;
15666 struct triple *set;
15668 /* Put a barrier up before the cmp which preceeds the
15669 * copy instruction. If a set actually occurs this gives
15670 * us a chance to move variables in registers out of the way.
15673 /* Modify the comparison operator */
15675 ins->template_id = TEMPLATE_TEST;
15676 if (cmp_op == OP_CMP) {
15677 ins->template_id = TEMPLATE_CMP_REG;
15678 if (get_imm32(ins, &RHS(ins, 1))) {
15679 ins->template_id = TEMPLATE_CMP_IMM;
15682 /* Generate the instruction sequence that will transform the
15683 * result of the comparison into a logical value.
15685 set = post_triple(state, ins, set_op, ins->type, ins, 0);
15686 use_triple(ins, set);
15687 set->template_id = TEMPLATE_SET;
15689 for(entry = ins->use; entry; entry = next) {
15690 next = entry->next;
15691 if (entry->member == set) {
15694 replace_rhs_use(state, ins, set, entry->member);
15696 fixup_branches(state, ins, set, jmp_op);
15699 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15701 struct triple *next;
15703 lhs = TRIPLE_LHS(ins->sizes);
15704 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15705 if (next != LHS(ins, i)) {
15706 internal_error(state, ins, "malformed lhs on %s",
15709 if (next->op != OP_PIECE) {
15710 internal_error(state, ins, "bad lhs op %s at %d on %s",
15711 tops(next->op), i, tops(ins->op));
15713 if (next->u.cval != i) {
15714 internal_error(state, ins, "bad u.cval of %d %d expected",
15721 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15723 struct ins_template *template;
15724 struct reg_info result;
15726 if (ins->op == OP_PIECE) {
15727 index = ins->u.cval;
15728 ins = MISC(ins, 0);
15730 zlhs = TRIPLE_LHS(ins->sizes);
15731 if (triple_is_def(state, ins)) {
15734 if (index >= zlhs) {
15735 internal_error(state, ins, "index %d out of range for %s\n",
15736 index, tops(ins->op));
15740 template = &ins->u.ainfo->tmpl;
15743 if (ins->template_id > LAST_TEMPLATE) {
15744 internal_error(state, ins, "bad template number %d",
15747 template = &templates[ins->template_id];
15750 result = template->lhs[index];
15751 result.regcm = arch_regcm_normalize(state, result.regcm);
15752 if (result.reg != REG_UNNEEDED) {
15753 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15755 if (result.regcm == 0) {
15756 internal_error(state, ins, "lhs %d regcm == 0", index);
15761 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15763 struct reg_info result;
15764 struct ins_template *template;
15765 if ((index > TRIPLE_RHS(ins->sizes)) ||
15766 (ins->op == OP_PIECE)) {
15767 internal_error(state, ins, "index %d out of range for %s\n",
15768 index, tops(ins->op));
15772 template = &ins->u.ainfo->tmpl;
15775 if (ins->template_id > LAST_TEMPLATE) {
15776 internal_error(state, ins, "bad template number %d",
15779 template = &templates[ins->template_id];
15782 result = template->rhs[index];
15783 result.regcm = arch_regcm_normalize(state, result.regcm);
15784 if (result.regcm == 0) {
15785 internal_error(state, ins, "rhs %d regcm == 0", index);
15790 static struct triple *transform_to_arch_instruction(
15791 struct compile_state *state, struct triple *ins)
15793 /* Transform from generic 3 address instructions
15794 * to archtecture specific instructions.
15795 * And apply architecture specific constrains to instructions.
15796 * Copies are inserted to preserve the register flexibility
15797 * of 3 address instructions.
15799 struct triple *next;
15803 ins->template_id = TEMPLATE_INTCONST32;
15804 if (ins->u.cval < 256) {
15805 ins->template_id = TEMPLATE_INTCONST8;
15809 ins->template_id = TEMPLATE_INTCONST32;
15815 ins->template_id = TEMPLATE_NOP;
15818 ins->template_id = TEMPLATE_COPY_REG;
15819 if (is_imm8(RHS(ins, 0))) {
15820 ins->template_id = TEMPLATE_COPY_IMM8;
15822 else if (is_imm16(RHS(ins, 0))) {
15823 ins->template_id = TEMPLATE_COPY_IMM16;
15825 else if (is_imm32(RHS(ins, 0))) {
15826 ins->template_id = TEMPLATE_COPY_IMM32;
15828 else if (is_const(RHS(ins, 0))) {
15829 internal_error(state, ins, "bad constant passed to copy");
15833 ins->template_id = TEMPLATE_PHI;
15836 switch(ins->type->type & TYPE_MASK) {
15837 case TYPE_CHAR: case TYPE_UCHAR:
15838 ins->template_id = TEMPLATE_STORE8;
15840 case TYPE_SHORT: case TYPE_USHORT:
15841 ins->template_id = TEMPLATE_STORE16;
15843 case TYPE_INT: case TYPE_UINT:
15844 case TYPE_LONG: case TYPE_ULONG:
15846 ins->template_id = TEMPLATE_STORE32;
15849 internal_error(state, ins, "unknown type in store");
15854 switch(ins->type->type & TYPE_MASK) {
15855 case TYPE_CHAR: case TYPE_UCHAR:
15856 ins->template_id = TEMPLATE_LOAD8;
15860 ins->template_id = TEMPLATE_LOAD16;
15867 ins->template_id = TEMPLATE_LOAD32;
15870 internal_error(state, ins, "unknown type in load");
15880 ins->template_id = TEMPLATE_BINARY_REG;
15881 if (get_imm32(ins, &RHS(ins, 1))) {
15882 ins->template_id = TEMPLATE_BINARY_IMM;
15888 ins->template_id = TEMPLATE_SL_CL;
15889 if (get_imm8(ins, &RHS(ins, 1))) {
15890 ins->template_id = TEMPLATE_SL_IMM;
15895 ins->template_id = TEMPLATE_UNARY;
15898 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
15901 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15904 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
15907 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
15910 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
15913 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
15916 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
15919 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
15922 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
15925 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
15928 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15931 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
15934 if (TRIPLE_RHS(ins->sizes) > 0) {
15935 internal_error(state, ins, "bad branch test");
15938 ins->template_id = TEMPLATE_NOP;
15944 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
15945 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
15946 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
15948 if (get_imm8(ins, &RHS(ins, 0))) {
15949 ins->template_id += 1;
15956 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
15957 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
15958 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
15960 if (get_imm8(ins, &RHS(ins, 1))) {
15961 ins->template_id += 1;
15966 ins->template_id = TEMPLATE_BSF;
15969 ins->template_id = TEMPLATE_RDMSR;
15970 next = after_lhs(state, ins);
15973 ins->template_id = TEMPLATE_WRMSR;
15976 ins->template_id = TEMPLATE_NOP;
15979 ins->template_id = TEMPLATE_NOP;
15980 next = after_lhs(state, ins);
15982 /* Already transformed instructions */
15984 ins->template_id = TEMPLATE_TEST;
15987 ins->template_id = TEMPLATE_CMP_REG;
15988 if (get_imm32(ins, &RHS(ins, 1))) {
15989 ins->template_id = TEMPLATE_CMP_IMM;
15992 case OP_JMP_EQ: case OP_JMP_NOTEQ:
15993 case OP_JMP_SLESS: case OP_JMP_ULESS:
15994 case OP_JMP_SMORE: case OP_JMP_UMORE:
15995 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
15996 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
15997 ins->template_id = TEMPLATE_JMP;
15999 case OP_SET_EQ: case OP_SET_NOTEQ:
16000 case OP_SET_SLESS: case OP_SET_ULESS:
16001 case OP_SET_SMORE: case OP_SET_UMORE:
16002 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16003 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16004 ins->template_id = TEMPLATE_SET;
16006 /* Unhandled instructions */
16009 internal_error(state, ins, "unhandled ins: %d %s\n",
16010 ins->op, tops(ins->op));
16016 static void generate_local_labels(struct compile_state *state)
16018 struct triple *first, *label;
16021 first = RHS(state->main_function, 0);
16024 if ((label->op == OP_LABEL) ||
16025 (label->op == OP_SDECL)) {
16027 label->u.cval = ++label_counter;
16033 label = label->next;
16034 } while(label != first);
16037 static int check_reg(struct compile_state *state,
16038 struct triple *triple, int classes)
16042 reg = ID_REG(triple->id);
16043 if (reg == REG_UNSET) {
16044 internal_error(state, triple, "register not set");
16046 mask = arch_reg_regcm(state, reg);
16047 if (!(classes & mask)) {
16048 internal_error(state, triple, "reg %d in wrong class",
16054 static const char *arch_reg_str(int reg)
16056 static const char *regs[] = {
16060 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16061 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16062 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16064 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16065 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
16066 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16068 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16075 static const char *reg(struct compile_state *state, struct triple *triple,
16079 reg = check_reg(state, triple, classes);
16080 return arch_reg_str(reg);
16083 const char *type_suffix(struct compile_state *state, struct type *type)
16085 const char *suffix;
16086 switch(size_of(state, type)) {
16087 case 1: suffix = "b"; break;
16088 case 2: suffix = "w"; break;
16089 case 4: suffix = "l"; break;
16091 internal_error(state, 0, "unknown suffix");
16098 static void print_const_val(
16099 struct compile_state *state, struct triple *ins, FILE *fp)
16103 fprintf(fp, " $%ld ",
16104 (long_t)(ins->u.cval));
16107 fprintf(fp, " $L%s%lu+%lu ",
16108 state->label_prefix,
16109 MISC(ins, 0)->u.cval,
16113 internal_error(state, ins, "unknown constant type");
16118 static void print_binary_op(struct compile_state *state,
16119 const char *op, struct triple *ins, FILE *fp)
16122 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16123 if (RHS(ins, 0)->id != ins->id) {
16124 internal_error(state, ins, "invalid register assignment");
16126 if (is_const(RHS(ins, 1))) {
16127 fprintf(fp, "\t%s ", op);
16128 print_const_val(state, RHS(ins, 1), fp);
16129 fprintf(fp, ", %s\n",
16130 reg(state, RHS(ins, 0), mask));
16133 unsigned lmask, rmask;
16135 lreg = check_reg(state, RHS(ins, 0), mask);
16136 rreg = check_reg(state, RHS(ins, 1), mask);
16137 lmask = arch_reg_regcm(state, lreg);
16138 rmask = arch_reg_regcm(state, rreg);
16139 mask = lmask & rmask;
16140 fprintf(fp, "\t%s %s, %s\n",
16142 reg(state, RHS(ins, 1), mask),
16143 reg(state, RHS(ins, 0), mask));
16146 static void print_unary_op(struct compile_state *state,
16147 const char *op, struct triple *ins, FILE *fp)
16150 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16151 fprintf(fp, "\t%s %s\n",
16153 reg(state, RHS(ins, 0), mask));
16156 static void print_op_shift(struct compile_state *state,
16157 const char *op, struct triple *ins, FILE *fp)
16160 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16161 if (RHS(ins, 0)->id != ins->id) {
16162 internal_error(state, ins, "invalid register assignment");
16164 if (is_const(RHS(ins, 1))) {
16165 fprintf(fp, "\t%s ", op);
16166 print_const_val(state, RHS(ins, 1), fp);
16167 fprintf(fp, ", %s\n",
16168 reg(state, RHS(ins, 0), mask));
16171 fprintf(fp, "\t%s %s, %s\n",
16173 reg(state, RHS(ins, 1), REGCM_GPR8),
16174 reg(state, RHS(ins, 0), mask));
16178 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16185 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
16186 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16187 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16189 internal_error(state, ins, "not an in operation");
16193 dreg = check_reg(state, ins, mask);
16194 if (!reg_is_reg(state, dreg, REG_EAX)) {
16195 internal_error(state, ins, "dst != %%eax");
16197 if (is_const(RHS(ins, 0))) {
16198 fprintf(fp, "\t%s ", op);
16199 print_const_val(state, RHS(ins, 0), fp);
16200 fprintf(fp, ", %s\n",
16201 reg(state, ins, mask));
16205 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16206 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16207 internal_error(state, ins, "src != %%dx");
16209 fprintf(fp, "\t%s %s, %s\n",
16211 reg(state, RHS(ins, 0), REGCM_GPR16),
16212 reg(state, ins, mask));
16216 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16223 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
16224 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16225 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16227 internal_error(state, ins, "not an out operation");
16231 lreg = check_reg(state, RHS(ins, 0), mask);
16232 if (!reg_is_reg(state, lreg, REG_EAX)) {
16233 internal_error(state, ins, "src != %%eax");
16235 if (is_const(RHS(ins, 1))) {
16236 fprintf(fp, "\t%s %s,",
16237 op, reg(state, RHS(ins, 0), mask));
16238 print_const_val(state, RHS(ins, 1), fp);
16243 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
16244 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16245 internal_error(state, ins, "dst != %%dx");
16247 fprintf(fp, "\t%s %s, %s\n",
16249 reg(state, RHS(ins, 0), mask),
16250 reg(state, RHS(ins, 1), REGCM_GPR16));
16254 static void print_op_move(struct compile_state *state,
16255 struct triple *ins, FILE *fp)
16257 /* op_move is complex because there are many types
16258 * of registers we can move between.
16259 * Because OP_COPY will be introduced in arbitrary locations
16260 * OP_COPY must not affect flags.
16262 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
16263 struct triple *dst, *src;
16264 if (ins->op == OP_COPY) {
16268 else if (ins->op == OP_WRITE) {
16273 internal_error(state, ins, "unknown move operation");
16276 if (!is_const(src)) {
16277 int src_reg, dst_reg;
16278 int src_regcm, dst_regcm;
16279 src_reg = ID_REG(src->id);
16280 dst_reg = ID_REG(dst->id);
16281 src_regcm = arch_reg_regcm(state, src_reg);
16282 dst_regcm = arch_reg_regcm(state, dst_reg);
16283 /* If the class is the same just move the register */
16284 if (src_regcm & dst_regcm &
16285 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
16286 if ((src_reg != dst_reg) || !omit_copy) {
16287 fprintf(fp, "\tmov %s, %s\n",
16288 reg(state, src, src_regcm),
16289 reg(state, dst, dst_regcm));
16292 /* Move 32bit to 16bit */
16293 else if ((src_regcm & REGCM_GPR32) &&
16294 (dst_regcm & REGCM_GPR16)) {
16295 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
16296 if ((src_reg != dst_reg) || !omit_copy) {
16297 fprintf(fp, "\tmovw %s, %s\n",
16298 arch_reg_str(src_reg),
16299 arch_reg_str(dst_reg));
16302 /* Move 32bit to 8bit */
16303 else if ((src_regcm & REGCM_GPR32_8) &&
16304 (dst_regcm & REGCM_GPR8))
16306 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
16307 if ((src_reg != dst_reg) || !omit_copy) {
16308 fprintf(fp, "\tmovb %s, %s\n",
16309 arch_reg_str(src_reg),
16310 arch_reg_str(dst_reg));
16313 /* Move 16bit to 8bit */
16314 else if ((src_regcm & REGCM_GPR16_8) &&
16315 (dst_regcm & REGCM_GPR8))
16317 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16318 if ((src_reg != dst_reg) || !omit_copy) {
16319 fprintf(fp, "\tmovb %s, %s\n",
16320 arch_reg_str(src_reg),
16321 arch_reg_str(dst_reg));
16324 /* Move 8/16bit to 16/32bit */
16325 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
16326 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16328 op = is_signed(src->type)? "movsx": "movzx";
16329 fprintf(fp, "\t%s %s, %s\n",
16331 reg(state, src, src_regcm),
16332 reg(state, dst, dst_regcm));
16334 /* Move between sse registers */
16335 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16336 if ((src_reg != dst_reg) || !omit_copy) {
16337 fprintf(fp, "\tmovdqa %s, %s\n",
16338 reg(state, src, src_regcm),
16339 reg(state, dst, dst_regcm));
16342 /* Move between mmx registers or mmx & sse registers */
16343 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16344 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16345 if ((src_reg != dst_reg) || !omit_copy) {
16346 fprintf(fp, "\tmovq %s, %s\n",
16347 reg(state, src, src_regcm),
16348 reg(state, dst, dst_regcm));
16351 /* Move between 32bit gprs & mmx/sse registers */
16352 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16353 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16354 fprintf(fp, "\tmovd %s, %s\n",
16355 reg(state, src, src_regcm),
16356 reg(state, dst, dst_regcm));
16358 #if X86_4_8BIT_GPRS
16359 /* Move from 8bit gprs to mmx/sse registers */
16360 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16361 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16364 op = is_signed(src->type)? "movsx":"movzx";
16365 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16366 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16368 reg(state, src, src_regcm),
16369 arch_reg_str(mid_reg),
16370 arch_reg_str(mid_reg),
16371 reg(state, dst, dst_regcm));
16373 /* Move from mmx/sse registers and 8bit gprs */
16374 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16375 (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16377 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16378 fprintf(fp, "\tmovd %s, %s\n",
16379 reg(state, src, src_regcm),
16380 arch_reg_str(mid_reg));
16382 /* Move from 32bit gprs to 16bit gprs */
16383 else if ((src_regcm & REGCM_GPR32) &&
16384 (dst_regcm & REGCM_GPR16)) {
16385 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16386 if ((src_reg != dst_reg) || !omit_copy) {
16387 fprintf(fp, "\tmov %s, %s\n",
16388 arch_reg_str(src_reg),
16389 arch_reg_str(dst_reg));
16392 /* Move from 32bit gprs to 8bit gprs */
16393 else if ((src_regcm & REGCM_GPR32) &&
16394 (dst_regcm & REGCM_GPR8)) {
16395 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16396 if ((src_reg != dst_reg) || !omit_copy) {
16397 fprintf(fp, "\tmov %s, %s\n",
16398 arch_reg_str(src_reg),
16399 arch_reg_str(dst_reg));
16402 /* Move from 16bit gprs to 8bit gprs */
16403 else if ((src_regcm & REGCM_GPR16) &&
16404 (dst_regcm & REGCM_GPR8)) {
16405 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16406 if ((src_reg != dst_reg) || !omit_copy) {
16407 fprintf(fp, "\tmov %s, %s\n",
16408 arch_reg_str(src_reg),
16409 arch_reg_str(dst_reg));
16412 #endif /* X86_4_8BIT_GPRS */
16414 internal_error(state, ins, "unknown copy type");
16418 fprintf(fp, "\tmov ");
16419 print_const_val(state, src, fp);
16420 fprintf(fp, ", %s\n",
16421 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16425 static void print_op_load(struct compile_state *state,
16426 struct triple *ins, FILE *fp)
16428 struct triple *dst, *src;
16431 if (is_const(src) || is_const(dst)) {
16432 internal_error(state, ins, "unknown load operation");
16434 fprintf(fp, "\tmov (%s), %s\n",
16435 reg(state, src, REGCM_GPR32),
16436 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16440 static void print_op_store(struct compile_state *state,
16441 struct triple *ins, FILE *fp)
16443 struct triple *dst, *src;
16446 if (is_const(src) && (src->op == OP_INTCONST)) {
16448 value = (long_t)(src->u.cval);
16449 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16450 type_suffix(state, src->type),
16452 reg(state, dst, REGCM_GPR32));
16454 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16455 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16456 type_suffix(state, src->type),
16457 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16461 if (is_const(src) || is_const(dst)) {
16462 internal_error(state, ins, "unknown store operation");
16464 fprintf(fp, "\tmov%s %s, (%s)\n",
16465 type_suffix(state, src->type),
16466 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16467 reg(state, dst, REGCM_GPR32));
16473 static void print_op_smul(struct compile_state *state,
16474 struct triple *ins, FILE *fp)
16476 if (!is_const(RHS(ins, 1))) {
16477 fprintf(fp, "\timul %s, %s\n",
16478 reg(state, RHS(ins, 1), REGCM_GPR32),
16479 reg(state, RHS(ins, 0), REGCM_GPR32));
16482 fprintf(fp, "\timul ");
16483 print_const_val(state, RHS(ins, 1), fp);
16484 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16488 static void print_op_cmp(struct compile_state *state,
16489 struct triple *ins, FILE *fp)
16493 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16494 dreg = check_reg(state, ins, REGCM_FLAGS);
16495 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16496 internal_error(state, ins, "bad dest register for cmp");
16498 if (is_const(RHS(ins, 1))) {
16499 fprintf(fp, "\tcmp ");
16500 print_const_val(state, RHS(ins, 1), fp);
16501 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16504 unsigned lmask, rmask;
16506 lreg = check_reg(state, RHS(ins, 0), mask);
16507 rreg = check_reg(state, RHS(ins, 1), mask);
16508 lmask = arch_reg_regcm(state, lreg);
16509 rmask = arch_reg_regcm(state, rreg);
16510 mask = lmask & rmask;
16511 fprintf(fp, "\tcmp %s, %s\n",
16512 reg(state, RHS(ins, 1), mask),
16513 reg(state, RHS(ins, 0), mask));
16517 static void print_op_test(struct compile_state *state,
16518 struct triple *ins, FILE *fp)
16521 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16522 fprintf(fp, "\ttest %s, %s\n",
16523 reg(state, RHS(ins, 0), mask),
16524 reg(state, RHS(ins, 0), mask));
16527 static void print_op_branch(struct compile_state *state,
16528 struct triple *branch, FILE *fp)
16530 const char *bop = "j";
16531 if (branch->op == OP_JMP) {
16532 if (TRIPLE_RHS(branch->sizes) != 0) {
16533 internal_error(state, branch, "jmp with condition?");
16538 struct triple *ptr;
16539 if (TRIPLE_RHS(branch->sizes) != 1) {
16540 internal_error(state, branch, "jmpcc without condition?");
16542 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16543 if ((RHS(branch, 0)->op != OP_CMP) &&
16544 (RHS(branch, 0)->op != OP_TEST)) {
16545 internal_error(state, branch, "bad branch test");
16547 #warning "FIXME I have observed instructions between the test and branch instructions"
16548 ptr = RHS(branch, 0);
16549 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16550 if (ptr->op != OP_COPY) {
16551 internal_error(state, branch, "branch does not follow test");
16554 switch(branch->op) {
16555 case OP_JMP_EQ: bop = "jz"; break;
16556 case OP_JMP_NOTEQ: bop = "jnz"; break;
16557 case OP_JMP_SLESS: bop = "jl"; break;
16558 case OP_JMP_ULESS: bop = "jb"; break;
16559 case OP_JMP_SMORE: bop = "jg"; break;
16560 case OP_JMP_UMORE: bop = "ja"; break;
16561 case OP_JMP_SLESSEQ: bop = "jle"; break;
16562 case OP_JMP_ULESSEQ: bop = "jbe"; break;
16563 case OP_JMP_SMOREEQ: bop = "jge"; break;
16564 case OP_JMP_UMOREEQ: bop = "jae"; break;
16566 internal_error(state, branch, "Invalid branch op");
16571 fprintf(fp, "\t%s L%s%lu\n",
16573 state->label_prefix,
16574 TARG(branch, 0)->u.cval);
16577 static void print_op_set(struct compile_state *state,
16578 struct triple *set, FILE *fp)
16580 const char *sop = "set";
16581 if (TRIPLE_RHS(set->sizes) != 1) {
16582 internal_error(state, set, "setcc without condition?");
16584 check_reg(state, RHS(set, 0), REGCM_FLAGS);
16585 if ((RHS(set, 0)->op != OP_CMP) &&
16586 (RHS(set, 0)->op != OP_TEST)) {
16587 internal_error(state, set, "bad set test");
16589 if (RHS(set, 0)->next != set) {
16590 internal_error(state, set, "set does not follow test");
16593 case OP_SET_EQ: sop = "setz"; break;
16594 case OP_SET_NOTEQ: sop = "setnz"; break;
16595 case OP_SET_SLESS: sop = "setl"; break;
16596 case OP_SET_ULESS: sop = "setb"; break;
16597 case OP_SET_SMORE: sop = "setg"; break;
16598 case OP_SET_UMORE: sop = "seta"; break;
16599 case OP_SET_SLESSEQ: sop = "setle"; break;
16600 case OP_SET_ULESSEQ: sop = "setbe"; break;
16601 case OP_SET_SMOREEQ: sop = "setge"; break;
16602 case OP_SET_UMOREEQ: sop = "setae"; break;
16604 internal_error(state, set, "Invalid set op");
16607 fprintf(fp, "\t%s %s\n",
16608 sop, reg(state, set, REGCM_GPR8));
16611 static void print_op_bit_scan(struct compile_state *state,
16612 struct triple *ins, FILE *fp)
16616 case OP_BSF: op = "bsf"; break;
16617 case OP_BSR: op = "bsr"; break;
16619 internal_error(state, ins, "unknown bit scan");
16629 reg(state, RHS(ins, 0), REGCM_GPR32),
16630 reg(state, ins, REGCM_GPR32),
16631 reg(state, ins, REGCM_GPR32));
16634 static void print_const(struct compile_state *state,
16635 struct triple *ins, FILE *fp)
16639 switch(ins->type->type & TYPE_MASK) {
16642 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16646 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16652 fprintf(fp, ".int %lu\n", ins->u.cval);
16655 internal_error(state, ins, "Unknown constant type");
16660 unsigned char *blob;
16662 size = size_of(state, ins->type);
16663 blob = ins->u.blob;
16664 for(i = 0; i < size; i++) {
16665 fprintf(fp, ".byte 0x%02x\n",
16671 internal_error(state, ins, "Unknown constant type");
16676 #define TEXT_SECTION ".rom.text"
16677 #define DATA_SECTION ".rom.data"
16679 static void print_sdecl(struct compile_state *state,
16680 struct triple *ins, FILE *fp)
16682 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16683 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16684 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16685 print_const(state, MISC(ins, 0), fp);
16686 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16690 static void print_instruction(struct compile_state *state,
16691 struct triple *ins, FILE *fp)
16693 /* Assumption: after I have exted the register allocator
16694 * everything is in a valid register.
16698 print_op_asm(state, ins, fp);
16700 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
16701 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
16702 case OP_AND: print_binary_op(state, "and", ins, fp); break;
16703 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
16704 case OP_OR: print_binary_op(state, "or", ins, fp); break;
16705 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
16706 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
16707 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
16708 case OP_POS: break;
16709 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
16710 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16714 /* Don't generate anything here for constants */
16716 /* Don't generate anything for variable declarations. */
16719 print_sdecl(state, ins, fp);
16723 print_op_move(state, ins, fp);
16726 print_op_load(state, ins, fp);
16729 print_op_store(state, ins, fp);
16732 print_op_smul(state, ins, fp);
16734 case OP_CMP: print_op_cmp(state, ins, fp); break;
16735 case OP_TEST: print_op_test(state, ins, fp); break;
16737 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16738 case OP_JMP_SLESS: case OP_JMP_ULESS:
16739 case OP_JMP_SMORE: case OP_JMP_UMORE:
16740 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16741 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16742 print_op_branch(state, ins, fp);
16744 case OP_SET_EQ: case OP_SET_NOTEQ:
16745 case OP_SET_SLESS: case OP_SET_ULESS:
16746 case OP_SET_SMORE: case OP_SET_UMORE:
16747 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16748 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16749 print_op_set(state, ins, fp);
16751 case OP_INB: case OP_INW: case OP_INL:
16752 print_op_in(state, ins, fp);
16754 case OP_OUTB: case OP_OUTW: case OP_OUTL:
16755 print_op_out(state, ins, fp);
16759 print_op_bit_scan(state, ins, fp);
16762 after_lhs(state, ins);
16763 fprintf(fp, "\trdmsr\n");
16766 fprintf(fp, "\twrmsr\n");
16769 fprintf(fp, "\thlt\n");
16775 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16777 /* Ignore OP_PIECE */
16780 /* Operations I am not yet certain how to handle */
16782 case OP_SDIV: case OP_UDIV:
16783 case OP_SMOD: case OP_UMOD:
16784 /* Operations that should never get here */
16785 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
16786 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
16787 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16789 internal_error(state, ins, "unknown op: %d %s",
16790 ins->op, tops(ins->op));
16795 static void print_instructions(struct compile_state *state)
16797 struct triple *first, *ins;
16798 int print_location;
16799 struct occurance *last_occurance;
16801 print_location = 1;
16802 last_occurance = 0;
16803 fp = state->output;
16804 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16805 first = RHS(state->main_function, 0);
16808 if (print_location &&
16809 last_occurance != ins->occurance) {
16810 if (!ins->occurance->parent) {
16811 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
16812 ins->occurance->function,
16813 ins->occurance->filename,
16814 ins->occurance->line,
16815 ins->occurance->col);
16818 struct occurance *ptr;
16819 fprintf(fp, "\t/*\n");
16820 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
16821 fprintf(fp, "\t * %s,%s:%d.%d\n",
16827 fprintf(fp, "\t */\n");
16830 if (last_occurance) {
16831 put_occurance(last_occurance);
16833 get_occurance(ins->occurance);
16834 last_occurance = ins->occurance;
16837 print_instruction(state, ins, fp);
16839 } while(ins != first);
16842 static void generate_code(struct compile_state *state)
16844 generate_local_labels(state);
16845 print_instructions(state);
16849 static void print_tokens(struct compile_state *state)
16852 tk = &state->token[0];
16857 next_token(state, 0);
16859 loc(stdout, state, 0);
16860 printf("%s <- `%s'\n",
16862 tk->ident ? tk->ident->name :
16863 tk->str_len ? tk->val.str : "");
16865 } while(tk->tok != TOK_EOF);
16868 static void compile(const char *filename, const char *ofilename,
16869 int cpu, int debug, int opt, const char *label_prefix)
16872 struct compile_state state;
16873 memset(&state, 0, sizeof(state));
16875 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
16876 memset(&state.token[i], 0, sizeof(state.token[i]));
16877 state.token[i].tok = -1;
16879 /* Remember the debug settings */
16881 state.debug = debug;
16882 state.optimize = opt;
16883 /* Remember the output filename */
16884 state.ofilename = ofilename;
16885 state.output = fopen(state.ofilename, "w");
16886 if (!state.output) {
16887 error(&state, 0, "Cannot open output file %s\n",
16890 /* Remember the label prefix */
16891 state.label_prefix = label_prefix;
16892 /* Prep the preprocessor */
16893 state.if_depth = 0;
16894 state.if_value = 0;
16895 /* register the C keywords */
16896 register_keywords(&state);
16897 /* register the keywords the macro preprocessor knows */
16898 register_macro_keywords(&state);
16899 /* Memorize where some special keywords are. */
16900 state.i_continue = lookup(&state, "continue", 8);
16901 state.i_break = lookup(&state, "break", 5);
16902 /* Enter the globl definition scope */
16903 start_scope(&state);
16904 register_builtins(&state);
16905 compile_file(&state, filename, 1);
16907 print_tokens(&state);
16910 /* Exit the global definition scope */
16913 /* Now that basic compilation has happened
16914 * optimize the intermediate code
16918 generate_code(&state);
16920 fprintf(stderr, "done\n");
16924 static void version(void)
16926 printf("romcc " VERSION " released " RELEASE_DATE "\n");
16929 static void usage(void)
16933 "Usage: romcc <source>.c\n"
16934 "Compile a C source file without using ram\n"
16938 static void arg_error(char *fmt, ...)
16941 va_start(args, fmt);
16942 vfprintf(stderr, fmt, args);
16948 int main(int argc, char **argv)
16950 const char *filename;
16951 const char *ofilename;
16952 const char *label_prefix;
16959 ofilename = "auto.inc";
16963 while((argc > 1) && (argc != last_argc)) {
16965 if (strncmp(argv[1], "--debug=", 8) == 0) {
16966 debug = atoi(argv[1] + 8);
16970 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
16971 label_prefix= argv[1] + 15;
16975 else if ((strcmp(argv[1],"-O") == 0) ||
16976 (strcmp(argv[1], "-O1") == 0)) {
16981 else if (strcmp(argv[1],"-O2") == 0) {
16986 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
16987 ofilename = argv[2];
16991 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
16992 cpu = arch_encode_cpu(argv[1] + 6);
16993 if (cpu == BAD_CPU) {
16994 arg_error("Invalid cpu specified: %s\n",
17002 arg_error("Wrong argument count %d\n", argc);
17004 filename = argv[1];
17005 compile(filename, ofilename, cpu, debug, optimize, label_prefix);