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;
222 struct hash_entry *ident;
230 /* I have two classes of types:
232 * Logical types. (The type the C standard says the operation is of)
234 * The operational types are:
249 * No memory is useable by the compiler.
250 * There is no floating point support.
251 * All operations take place in general purpose registers.
252 * There is one type of general purpose register.
253 * Unsigned longs are stored in that general purpose register.
256 /* Operations on general purpose registers.
273 #define OP_POS 14 /* Dummy positive operator don't use it */
283 #define OP_SLESSEQ 26
284 #define OP_ULESSEQ 27
285 #define OP_SMOREEQ 28
286 #define OP_UMOREEQ 29
288 #define OP_LFALSE 30 /* Test if the expression is logically false */
289 #define OP_LTRUE 31 /* Test if the expression is logcially true */
296 #define OP_MIN_CONST 50
297 #define OP_MAX_CONST 59
298 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
299 #define OP_INTCONST 50
300 #define OP_BLOBCONST 51
301 /* For OP_BLOBCONST ->type holds the layout and size
302 * information. u.blob holds a pointer to the raw binary
303 * data for the constant initializer.
305 #define OP_ADDRCONST 52
306 /* For OP_ADDRCONST ->type holds the type.
307 * MISC(0) holds the reference to the static variable.
308 * ->u.cval holds an offset from that value.
312 /* OP_WRITE moves one pseudo register to another.
313 * LHS(0) holds the destination pseudo register, which must be an OP_DECL.
314 * RHS(0) holds the psuedo to move.
318 /* OP_READ reads the value of a variable and makes
319 * it available for the pseudo operation.
320 * Useful for things like def-use chains.
321 * RHS(0) holds points to the triple to read from.
324 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
327 /* OP_PIECE returns one piece of a instruction that returns a structure.
328 * MISC(0) is the instruction
329 * u.cval is the LHS piece of the instruction to return.
332 /* OP_ASM holds a sequence of assembly instructions, the result
333 * of a C asm directive.
334 * RHS(x) holds input value x to the assembly sequence.
335 * LHS(x) holds the output value x from the assembly sequence.
336 * u.blob holds the string of assembly instructions.
340 /* OP_DEREF generates an lvalue from a pointer.
341 * RHS(0) holds the pointer value.
342 * OP_DEREF serves as a place holder to indicate all necessary
343 * checks have been done to indicate a value is an lvalue.
346 /* OP_DOT references a submember of a structure lvalue.
347 * RHS(0) holds the lvalue.
348 * ->u.field holds the name of the field we want.
350 * Not seen outside of expressions.
353 /* OP_VAL returns the value of a subexpression of the current expression.
354 * Useful for operators that have side effects.
355 * RHS(0) holds the expression.
356 * MISC(0) holds the subexpression of RHS(0) that is the
357 * value of the expression.
359 * Not seen outside of expressions.
362 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
363 * Not seen outside of expressions.
366 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
367 * Not seen outside of expressions.
370 /* OP_CODE performas a C ? : operation.
371 * RHS(0) holds the test.
372 * RHS(1) holds the expression to evaluate if the test returns true.
373 * RHS(2) holds the expression to evaluate if the test returns false.
374 * Not seen outside of expressions.
377 /* OP_COMMA performacs a C comma operation.
378 * That is RHS(0) is evaluated, then RHS(1)
379 * and the value of RHS(1) is returned.
380 * Not seen outside of expressions.
384 /* OP_CALL performs a procedure call.
385 * MISC(0) holds a pointer to the OP_LIST of a function
386 * RHS(x) holds argument x of a function
388 * Currently not seen outside of expressions.
390 #define OP_VAL_VEC 74
391 /* OP_VAL_VEC is an array of triples that are either variable
392 * or values for a structure or an array.
393 * RHS(x) holds element x of the vector.
394 * triple->type->elements holds the size of the vector.
399 /* OP_LIST Holds a list of statements, and a result value.
400 * RHS(0) holds the list of statements.
401 * MISC(0) holds the value of the statements.
404 #define OP_BRANCH 81 /* branch */
405 /* For branch instructions
406 * TARG(0) holds the branch target.
407 * RHS(0) if present holds the branch condition.
408 * ->next holds where to branch to if the branch is not taken.
409 * The branch target can only be a decl...
413 /* OP_LABEL is a triple that establishes an target for branches.
414 * ->use is the list of all branches that use this label.
418 /* OP_DECL is a triple that establishes an lvalue for assignments.
419 * ->use is a list of statements that use the variable.
423 /* OP_SDECL is a triple that establishes a variable of static
425 * ->use is a list of statements that use the variable.
426 * MISC(0) holds the initializer expression.
431 /* OP_PHI is a triple used in SSA form code.
432 * It is used when multiple code paths merge and a variable needs
433 * a single assignment from any of those code paths.
434 * The operation is a cross between OP_DECL and OP_WRITE, which
435 * is what OP_PHI is geneared from.
437 * RHS(x) points to the value from code path x
438 * The number of RHS entries is the number of control paths into the block
439 * in which OP_PHI resides. The elements of the array point to point
440 * to the variables OP_PHI is derived from.
442 * MISC(0) holds a pointer to the orginal OP_DECL node.
445 /* Architecture specific instructions */
448 #define OP_SET_EQ 102
449 #define OP_SET_NOTEQ 103
450 #define OP_SET_SLESS 104
451 #define OP_SET_ULESS 105
452 #define OP_SET_SMORE 106
453 #define OP_SET_UMORE 107
454 #define OP_SET_SLESSEQ 108
455 #define OP_SET_ULESSEQ 109
456 #define OP_SET_SMOREEQ 110
457 #define OP_SET_UMOREEQ 111
460 #define OP_JMP_EQ 113
461 #define OP_JMP_NOTEQ 114
462 #define OP_JMP_SLESS 115
463 #define OP_JMP_ULESS 116
464 #define OP_JMP_SMORE 117
465 #define OP_JMP_UMORE 118
466 #define OP_JMP_SLESSEQ 119
467 #define OP_JMP_ULESSEQ 120
468 #define OP_JMP_SMOREEQ 121
469 #define OP_JMP_UMOREEQ 122
471 /* Builtin operators that it is just simpler to use the compiler for */
489 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
491 #define BLOCK 8 /* Triple stores the current block */
492 unsigned char lhs, rhs, misc, targ;
495 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
503 static const struct op_info table_ops[] = {
504 [OP_SMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smul"),
505 [OP_UMUL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umul"),
506 [OP_SDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
507 [OP_UDIV ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "udiv"),
508 [OP_SMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smod"),
509 [OP_UMOD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umod"),
510 [OP_ADD ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "add"),
511 [OP_SUB ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sub"),
512 [OP_SL ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sl"),
513 [OP_USR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "usr"),
514 [OP_SSR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ssr"),
515 [OP_AND ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "and"),
516 [OP_XOR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "xor"),
517 [OP_OR ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "or"),
518 [OP_POS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "pos"),
519 [OP_NEG ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "neg"),
520 [OP_INVERT ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "invert"),
522 [OP_EQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "eq"),
523 [OP_NOTEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "noteq"),
524 [OP_SLESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "sless"),
525 [OP_ULESS ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "uless"),
526 [OP_SMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smore"),
527 [OP_UMORE ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umore"),
528 [OP_SLESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
529 [OP_ULESSEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
530 [OP_SMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
531 [OP_UMOREEQ ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
532 [OP_LFALSE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
533 [OP_LTRUE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
535 [OP_LOAD ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "load"),
536 [OP_STORE ] = OP( 1, 1, 0, 0, IMPURE | BLOCK , "store"),
538 [OP_NOOP ] = OP( 0, 0, 0, 0, PURE | BLOCK, "noop"),
540 [OP_INTCONST ] = OP( 0, 0, 0, 0, PURE | DEF, "intconst"),
541 [OP_BLOBCONST ] = OP( 0, 0, 0, 0, PURE, "blobconst"),
542 [OP_ADDRCONST ] = OP( 0, 0, 1, 0, PURE | DEF, "addrconst"),
544 [OP_WRITE ] = OP( 1, 1, 0, 0, PURE | BLOCK, "write"),
545 [OP_READ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "read"),
546 [OP_COPY ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "copy"),
547 [OP_PIECE ] = OP( 0, 0, 1, 0, PURE | DEF, "piece"),
548 [OP_ASM ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
549 [OP_DEREF ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "deref"),
550 [OP_DOT ] = OP( 0, 1, 0, 0, 0 | DEF | BLOCK, "dot"),
552 [OP_VAL ] = OP( 0, 1, 1, 0, 0 | DEF | BLOCK, "val"),
553 [OP_LAND ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "land"),
554 [OP_LOR ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "lor"),
555 [OP_COND ] = OP( 0, 3, 0, 0, 0 | DEF | BLOCK, "cond"),
556 [OP_COMMA ] = OP( 0, 2, 0, 0, 0 | DEF | BLOCK, "comma"),
557 /* Call is special most it can stand in for anything so it depends on context */
558 [OP_CALL ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
559 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
560 [OP_VAL_VEC ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
562 [OP_LIST ] = OP( 0, 1, 1, 0, 0 | DEF, "list"),
563 /* The number of targets for OP_BRANCH depends on context */
564 [OP_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
565 [OP_LABEL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "label"),
566 [OP_ADECL ] = OP( 0, 0, 0, 0, PURE | BLOCK, "adecl"),
567 [OP_SDECL ] = OP( 0, 0, 1, 0, PURE | BLOCK, "sdecl"),
568 /* The number of RHS elements of OP_PHI depend upon context */
569 [OP_PHI ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
571 [OP_CMP ] = OP( 0, 2, 0, 0, PURE | DEF | BLOCK, "cmp"),
572 [OP_TEST ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "test"),
573 [OP_SET_EQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
574 [OP_SET_NOTEQ ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
575 [OP_SET_SLESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
576 [OP_SET_ULESS ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
577 [OP_SET_SMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
578 [OP_SET_UMORE ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
579 [OP_SET_SLESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
580 [OP_SET_ULESSEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
581 [OP_SET_SMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
582 [OP_SET_UMOREEQ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
583 [OP_JMP ] = OP( 0, 0, 0, 1, PURE | BLOCK, "jmp"),
584 [OP_JMP_EQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_eq"),
585 [OP_JMP_NOTEQ ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_noteq"),
586 [OP_JMP_SLESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_sless"),
587 [OP_JMP_ULESS ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_uless"),
588 [OP_JMP_SMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smore"),
589 [OP_JMP_UMORE ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umore"),
590 [OP_JMP_SLESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
591 [OP_JMP_ULESSEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
592 [OP_JMP_SMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
593 [OP_JMP_UMOREEQ] = OP( 0, 1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
595 [OP_INB ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
596 [OP_INW ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
597 [OP_INL ] = OP( 0, 1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
598 [OP_OUTB ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outb"),
599 [OP_OUTW ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outw"),
600 [OP_OUTL ] = OP( 0, 2, 0, 0, IMPURE| BLOCK, "__outl"),
601 [OP_BSF ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
602 [OP_BSR ] = OP( 0, 1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
603 [OP_RDMSR ] = OP( 2, 1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
604 [OP_WRMSR ] = OP( 0, 3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
605 [OP_HLT ] = OP( 0, 0, 0, 0, IMPURE | BLOCK, "__hlt"),
608 #define OP_MAX (sizeof(table_ops)/sizeof(table_ops[0]))
610 static const char *tops(int index)
612 static const char unknown[] = "unknown op";
616 if (index > OP_MAX) {
619 return table_ops[index].name;
626 struct triple_set *next;
627 struct triple *member;
636 struct triple *next, *prev;
637 struct triple_set *use;
640 unsigned char template_id;
641 unsigned short sizes;
642 #define TRIPLE_LHS(SIZES) (((SIZES) >> 0) & 0x0f)
643 #define TRIPLE_RHS(SIZES) (((SIZES) >> 4) & 0x0f)
644 #define TRIPLE_MISC(SIZES) (((SIZES) >> 8) & 0x0f)
645 #define TRIPLE_TARG(SIZES) (((SIZES) >> 12) & 0x0f)
646 #define TRIPLE_SIZE(SIZES) \
647 ((((SIZES) >> 0) & 0x0f) + \
648 (((SIZES) >> 4) & 0x0f) + \
649 (((SIZES) >> 8) & 0x0f) + \
650 (((SIZES) >> 12) & 0x0f))
651 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
652 ((((LHS) & 0x0f) << 0) | \
653 (((RHS) & 0x0f) << 4) | \
654 (((MISC) & 0x0f) << 8) | \
655 (((TARG) & 0x0f) << 12))
656 #define TRIPLE_LHS_OFF(SIZES) (0)
657 #define TRIPLE_RHS_OFF(SIZES) (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
658 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
659 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
660 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
661 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
662 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
663 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
664 unsigned id; /* A scratch value and finally the register */
665 #define TRIPLE_FLAG_FLATTENED (1 << 31)
666 #define TRIPLE_FLAG_PRE_SPLIT (1 << 30)
667 #define TRIPLE_FLAG_POST_SPLIT (1 << 29)
668 const char *filename;
675 struct hash_entry *field;
676 struct asm_info *ainfo;
678 struct triple *param[2];
685 struct ins_template {
686 struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
690 struct ins_template tmpl;
695 struct block_set *next;
696 struct block *member;
699 struct block *work_next;
700 struct block *left, *right;
701 struct triple *first, *last;
703 struct block_set *use;
704 struct block_set *idominates;
705 struct block_set *domfrontier;
707 struct block_set *ipdominates;
708 struct block_set *ipdomfrontier;
716 struct hash_entry *ident;
723 struct hash_entry *ident;
729 struct hash_entry *next;
733 struct macro *sym_define;
734 struct symbol *sym_label;
735 struct symbol *sym_struct;
736 struct symbol *sym_ident;
739 #define HASH_TABLE_SIZE 2048
741 struct compile_state {
742 const char *label_prefix;
743 const char *ofilename;
746 struct file_state *file;
747 struct token token[4];
748 struct hash_entry *hash_table[HASH_TABLE_SIZE];
749 struct hash_entry *i_continue;
750 struct hash_entry *i_break;
752 int if_depth, if_value;
754 struct file_state *macro_file;
755 struct triple *main_function;
756 struct block *first_block, *last_block;
763 /* visibility global/local */
764 /* static/auto duration */
765 /* typedef, register, inline */
767 #define STOR_MASK 0x000f
769 #define STOR_GLOBAL 0x0001
771 #define STOR_PERM 0x0002
772 /* Storage specifiers */
773 #define STOR_AUTO 0x0000
774 #define STOR_STATIC 0x0002
775 #define STOR_EXTERN 0x0003
776 #define STOR_REGISTER 0x0004
777 #define STOR_TYPEDEF 0x0008
778 #define STOR_INLINE 0x000c
781 #define QUAL_MASK 0x0070
782 #define QUAL_NONE 0x0000
783 #define QUAL_CONST 0x0010
784 #define QUAL_VOLATILE 0x0020
785 #define QUAL_RESTRICT 0x0040
788 #define TYPE_MASK 0x1f00
789 #define TYPE_INTEGER(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
790 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
791 #define TYPE_UNSIGNED(TYPE) ((TYPE) & 0x0100)
792 #define TYPE_SIGNED(TYPE) (!TYPE_UNSIGNED(TYPE))
793 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
794 #define TYPE_RANK(TYPE) ((TYPE) & ~0x0100)
795 #define TYPE_PTR(TYPE) (((TYPE) & TYPE_MASK) == TYPE_POINTER)
796 #define TYPE_DEFAULT 0x0000
797 #define TYPE_VOID 0x0100
798 #define TYPE_CHAR 0x0200
799 #define TYPE_UCHAR 0x0300
800 #define TYPE_SHORT 0x0400
801 #define TYPE_USHORT 0x0500
802 #define TYPE_INT 0x0600
803 #define TYPE_UINT 0x0700
804 #define TYPE_LONG 0x0800
805 #define TYPE_ULONG 0x0900
806 #define TYPE_LLONG 0x0a00 /* long long */
807 #define TYPE_ULLONG 0x0b00
808 #define TYPE_FLOAT 0x0c00
809 #define TYPE_DOUBLE 0x0d00
810 #define TYPE_LDOUBLE 0x0e00 /* long double */
811 #define TYPE_STRUCT 0x1000
812 #define TYPE_ENUM 0x1100
813 #define TYPE_POINTER 0x1200
815 * type->left holds the type pointed to.
817 #define TYPE_FUNCTION 0x1300
818 /* For TYPE_FUNCTION:
819 * type->left holds the return type.
820 * type->right holds the...
822 #define TYPE_PRODUCT 0x1400
823 /* TYPE_PRODUCT is a basic building block when defining structures
824 * type->left holds the type that appears first in memory.
825 * type->right holds the type that appears next in memory.
827 #define TYPE_OVERLAP 0x1500
828 /* TYPE_OVERLAP is a basic building block when defining unions
829 * type->left and type->right holds to types that overlap
830 * each other in memory.
832 #define TYPE_ARRAY 0x1600
833 /* TYPE_ARRAY is a basic building block when definitng arrays.
834 * type->left holds the type we are an array of.
835 * type-> holds the number of elements.
838 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
842 struct type *left, *right;
844 struct hash_entry *field_ident;
845 struct hash_entry *type_ident;
848 #define MAX_REGISTERS 75
849 #define MAX_REG_EQUIVS 16
851 #define REGISTER_BITS 16
853 #define REGISTER_BITS 28
855 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
856 #define TEMPLATE_BITS 6
857 #define MAX_TEMPLATES (1<<TEMPLATE_BITS)
860 #define REG_UNNEEDED 1
861 #define REG_VIRT0 (MAX_REGISTERS + 0)
862 #define REG_VIRT1 (MAX_REGISTERS + 1)
863 #define REG_VIRT2 (MAX_REGISTERS + 2)
864 #define REG_VIRT3 (MAX_REGISTERS + 3)
865 #define REG_VIRT4 (MAX_REGISTERS + 4)
866 #define REG_VIRT5 (MAX_REGISTERS + 5)
867 #define REG_VIRT6 (MAX_REGISTERS + 5)
868 #define REG_VIRT7 (MAX_REGISTERS + 5)
869 #define REG_VIRT8 (MAX_REGISTERS + 5)
870 #define REG_VIRT9 (MAX_REGISTERS + 5)
872 /* Provision for 8 register classes */
875 #define REGC_SHIFT REGISTER_BITS
876 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
877 #define REG_MASK (MAX_VIRT_REGISTERS -1)
878 #define ID_REG(ID) ((ID) & REG_MASK)
879 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
880 #define ID_REGCM(ID) (((ID) & REGC_MASK) >> REGC_SHIFT)
881 #define SET_REGCM(ID, REGCM) ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
882 #define SET_INFO(ID, INFO) ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
883 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
885 #define REG_MASK (MAX_VIRT_REGISTERS -1)
886 #define ID_REG(ID) ((ID) & REG_MASK)
887 #define SET_REG(ID, REG) ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
890 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
891 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
892 static void arch_reg_equivs(
893 struct compile_state *state, unsigned *equiv, int reg);
894 static int arch_select_free_register(
895 struct compile_state *state, char *used, int classes);
896 static unsigned arch_regc_size(struct compile_state *state, int class);
897 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
898 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
899 static const char *arch_reg_str(int reg);
900 static struct reg_info arch_reg_constraint(
901 struct compile_state *state, struct type *type, const char *constraint);
902 static struct reg_info arch_reg_clobber(
903 struct compile_state *state, const char *clobber);
904 static struct reg_info arch_reg_lhs(struct compile_state *state,
905 struct triple *ins, int index);
906 static struct reg_info arch_reg_rhs(struct compile_state *state,
907 struct triple *ins, int index);
908 static struct triple *transform_to_arch_instruction(
909 struct compile_state *state, struct triple *ins);
913 #define DEBUG_ABORT_ON_ERROR 0x0001
914 #define DEBUG_INTERMEDIATE_CODE 0x0002
915 #define DEBUG_CONTROL_FLOW 0x0004
916 #define DEBUG_BASIC_BLOCKS 0x0008
917 #define DEBUG_FDOMINATORS 0x0010
918 #define DEBUG_RDOMINATORS 0x0020
919 #define DEBUG_TRIPLES 0x0040
920 #define DEBUG_INTERFERENCE 0x0080
921 #define DEBUG_ARCH_CODE 0x0100
922 #define DEBUG_CODE_ELIMINATION 0x0200
923 #define DEBUG_INSERTED_COPIES 0x0400
925 #define GLOBAL_SCOPE_DEPTH 1
927 static void compile_file(struct compile_state *old_state, const char *filename, int local);
929 static void do_cleanup(struct compile_state *state)
932 fclose(state->output);
933 unlink(state->ofilename);
937 static int get_col(struct file_state *file)
941 ptr = file->line_start;
943 for(col = 0; ptr < end; ptr++) {
948 col = (col & ~7) + 8;
954 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
958 fprintf(fp, "%s:%d.%d: ",
959 triple->filename, triple->line, triple->col);
965 col = get_col(state->file);
966 fprintf(fp, "%s:%d.%d: ",
967 state->file->basename, state->file->line, col);
970 static void __internal_error(struct compile_state *state, struct triple *ptr,
975 loc(stderr, state, ptr);
977 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
979 fprintf(stderr, "Internal compiler error: ");
980 vfprintf(stderr, fmt, args);
981 fprintf(stderr, "\n");
988 static void __internal_warning(struct compile_state *state, struct triple *ptr,
993 loc(stderr, state, ptr);
994 fprintf(stderr, "Internal compiler warning: ");
995 vfprintf(stderr, fmt, args);
996 fprintf(stderr, "\n");
1002 static void __error(struct compile_state *state, struct triple *ptr,
1006 va_start(args, fmt);
1007 loc(stderr, state, ptr);
1008 vfprintf(stderr, fmt, args);
1010 fprintf(stderr, "\n");
1012 if (state->debug & DEBUG_ABORT_ON_ERROR) {
1018 static void __warning(struct compile_state *state, struct triple *ptr,
1022 va_start(args, fmt);
1023 loc(stderr, state, ptr);
1024 fprintf(stderr, "warning: ");
1025 vfprintf(stderr, fmt, args);
1026 fprintf(stderr, "\n");
1030 #if DEBUG_ERROR_MESSAGES
1031 # define internal_error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1032 # define internal_warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1033 # define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1034 # define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1036 # define internal_error __internal_error
1037 # define internal_warning __internal_warning
1038 # define error __error
1039 # define warning __warning
1041 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1043 static void valid_op(struct compile_state *state, int op)
1045 char *fmt = "invalid op: %d";
1047 internal_error(state, 0, fmt, op);
1050 internal_error(state, 0, fmt, op);
1054 static void valid_ins(struct compile_state *state, struct triple *ptr)
1056 valid_op(state, ptr->op);
1059 static void process_trigraphs(struct compile_state *state)
1061 char *src, *dest, *end;
1062 struct file_state *file;
1064 src = dest = file->buf;
1065 end = file->buf + file->size;
1066 while((end - src) >= 3) {
1067 if ((src[0] == '?') && (src[1] == '?')) {
1070 case '=': c = '#'; break;
1071 case '/': c = '\\'; break;
1072 case '\'': c = '^'; break;
1073 case '(': c = '['; break;
1074 case ')': c = ']'; break;
1075 case '!': c = '!'; break;
1076 case '<': c = '{'; break;
1077 case '>': c = '}'; break;
1078 case '-': c = '~'; break;
1095 file->size = dest - file->buf;
1098 static void splice_lines(struct compile_state *state)
1100 char *src, *dest, *end;
1101 struct file_state *file;
1103 src = dest = file->buf;
1104 end = file->buf + file->size;
1105 while((end - src) >= 2) {
1106 if ((src[0] == '\\') && (src[1] == '\n')) {
1116 file->size = dest - file->buf;
1119 static struct type void_type;
1120 static void use_triple(struct triple *used, struct triple *user)
1122 struct triple_set **ptr, *new;
1129 if ((*ptr)->member == user) {
1132 ptr = &(*ptr)->next;
1134 /* Append new to the head of the list,
1135 * copy_func and rename_block_variables
1138 new = xcmalloc(sizeof(*new), "triple_set");
1140 new->next = used->use;
1144 static void unuse_triple(struct triple *used, struct triple *unuser)
1146 struct triple_set *use, **ptr;
1153 if (use->member == unuser) {
1163 static void push_triple(struct triple *used, struct triple *user)
1165 struct triple_set *new;
1170 /* Append new to the head of the list,
1171 * it's the only sensible behavoir for a stack.
1173 new = xcmalloc(sizeof(*new), "triple_set");
1175 new->next = used->use;
1179 static void pop_triple(struct triple *used, struct triple *unuser)
1181 struct triple_set *use, **ptr;
1185 if (use->member == unuser) {
1188 /* Only free one occurance from the stack */
1198 /* The zero triple is used as a place holder when we are removing pointers
1199 * from a triple. Having allows certain sanity checks to pass even
1200 * when the original triple that was pointed to is gone.
1202 static struct triple zero_triple = {
1203 .next = &zero_triple,
1204 .prev = &zero_triple,
1207 .sizes = TRIPLE_SIZES(0, 0, 0, 0),
1208 .id = -1, /* An invalid id */
1209 .u = { .cval = 0, },
1210 .filename = __FILE__,
1213 .param { [0] = 0, [1] = 0, },
1217 static unsigned short triple_sizes(struct compile_state *state,
1218 int op, struct type *type, int lhs_wanted, int rhs_wanted)
1220 int lhs, rhs, misc, targ;
1221 valid_op(state, op);
1222 lhs = table_ops[op].lhs;
1223 rhs = table_ops[op].rhs;
1224 misc = table_ops[op].misc;
1225 targ = table_ops[op].targ;
1228 if (op == OP_CALL) {
1231 param = type->right;
1232 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1234 param = param->right;
1236 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1240 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1241 lhs = type->left->elements;
1244 else if (op == OP_VAL_VEC) {
1245 rhs = type->elements;
1247 else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1250 else if (op == OP_ASM) {
1254 if ((rhs < 0) || (rhs > MAX_RHS)) {
1255 internal_error(state, 0, "bad rhs");
1257 if ((lhs < 0) || (lhs > MAX_LHS)) {
1258 internal_error(state, 0, "bad lhs");
1260 if ((misc < 0) || (misc > MAX_MISC)) {
1261 internal_error(state, 0, "bad misc");
1263 if ((targ < 0) || (targ > MAX_TARG)) {
1264 internal_error(state, 0, "bad targs");
1266 return TRIPLE_SIZES(lhs, rhs, misc, targ);
1269 static struct triple *alloc_triple(struct compile_state *state,
1270 int op, struct type *type, int lhs, int rhs,
1271 const char *filename, int line, int col)
1273 size_t size, sizes, extra_count, min_count;
1275 sizes = triple_sizes(state, op, type, lhs, rhs);
1277 min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1278 extra_count = TRIPLE_SIZE(sizes);
1279 extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1281 size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1282 ret = xcmalloc(size, "tripple");
1288 ret->filename = filename;
1294 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1297 int src_lhs, src_rhs, src_size;
1298 src_lhs = TRIPLE_LHS(src->sizes);
1299 src_rhs = TRIPLE_RHS(src->sizes);
1300 src_size = TRIPLE_SIZE(src->sizes);
1301 dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1302 src->filename, src->line, src->col);
1303 memcpy(dup, src, sizeof(*src));
1304 memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1308 static struct triple *new_triple(struct compile_state *state,
1309 int op, struct type *type, int lhs, int rhs)
1312 const char *filename;
1318 filename = state->file->basename;
1319 line = state->file->line;
1320 col = get_col(state->file);
1322 ret = alloc_triple(state, op, type, lhs, rhs,
1323 filename, line, col);
1327 static struct triple *build_triple(struct compile_state *state,
1328 int op, struct type *type, struct triple *left, struct triple *right,
1329 const char *filename, int line, int col)
1333 ret = alloc_triple(state, op, type, -1, -1, filename, line, col);
1334 count = TRIPLE_SIZE(ret->sizes);
1336 ret->param[0] = left;
1339 ret->param[1] = right;
1344 static struct triple *triple(struct compile_state *state,
1345 int op, struct type *type, struct triple *left, struct triple *right)
1349 ret = new_triple(state, op, type, -1, -1);
1350 count = TRIPLE_SIZE(ret->sizes);
1352 ret->param[0] = left;
1355 ret->param[1] = right;
1360 static struct triple *branch(struct compile_state *state,
1361 struct triple *targ, struct triple *test)
1364 ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1368 TARG(ret, 0) = targ;
1369 /* record the branch target was used */
1370 if (!targ || (targ->op != OP_LABEL)) {
1371 internal_error(state, 0, "branch not to label");
1372 use_triple(targ, ret);
1378 static void insert_triple(struct compile_state *state,
1379 struct triple *first, struct triple *ptr)
1382 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1383 internal_error(state, ptr, "expression already used");
1386 ptr->prev = first->prev;
1387 ptr->prev->next = ptr;
1388 ptr->next->prev = ptr;
1389 if ((ptr->prev->op == OP_BRANCH) &&
1390 TRIPLE_RHS(ptr->prev->sizes)) {
1391 unuse_triple(first, ptr->prev);
1392 use_triple(ptr, ptr->prev);
1397 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1399 /* This function is used to determine if u.block
1400 * is utilized to store the current block number.
1403 valid_ins(state, ins);
1404 stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1405 return stores_block;
1408 static struct block *block_of_triple(struct compile_state *state,
1411 struct triple *first;
1412 first = RHS(state->main_function, 0);
1413 while(ins != first && !triple_stores_block(state, ins)) {
1414 if (ins == ins->prev) {
1415 internal_error(state, 0, "ins == ins->prev?");
1419 if (!triple_stores_block(state, ins)) {
1420 internal_error(state, ins, "Cannot find block");
1422 return ins->u.block;
1425 static struct triple *pre_triple(struct compile_state *state,
1426 struct triple *base,
1427 int op, struct type *type, struct triple *left, struct triple *right)
1429 struct block *block;
1431 /* If I am an OP_PIECE jump to the real instruction */
1432 if (base->op == OP_PIECE) {
1433 base = MISC(base, 0);
1435 block = block_of_triple(state, base);
1436 ret = build_triple(state, op, type, left, right,
1437 base->filename, base->line, base->col);
1438 if (triple_stores_block(state, ret)) {
1439 ret->u.block = block;
1441 insert_triple(state, base, ret);
1442 if (block->first == base) {
1448 static struct triple *post_triple(struct compile_state *state,
1449 struct triple *base,
1450 int op, struct type *type, struct triple *left, struct triple *right)
1452 struct block *block;
1455 /* If I am an OP_PIECE jump to the real instruction */
1456 if (base->op == OP_PIECE) {
1457 base = MISC(base, 0);
1459 /* If I have a left hand side skip over it */
1460 zlhs = TRIPLE_LHS(base->sizes);
1461 if (zlhs && (base->op != OP_WRITE) && (base->op != OP_STORE)) {
1462 base = LHS(base, zlhs - 1);
1465 block = block_of_triple(state, base);
1466 ret = build_triple(state, op, type, left, right,
1467 base->filename, base->line, base->col);
1468 if (triple_stores_block(state, ret)) {
1469 ret->u.block = block;
1471 insert_triple(state, base->next, ret);
1472 if (block->last == base) {
1478 static struct triple *label(struct compile_state *state)
1480 /* Labels don't get a type */
1481 struct triple *result;
1482 result = triple(state, OP_LABEL, &void_type, 0, 0);
1486 static void display_triple(FILE *fp, struct triple *ins)
1488 if (ins->op == OP_INTCONST) {
1489 fprintf(fp, "(%p) %3d %-2d %-10s <0x%08lx> @ %s:%d.%d\n",
1490 ins, ID_REG(ins->id), ins->template_id, tops(ins->op),
1492 ins->filename, ins->line, ins->col);
1494 else if (ins->op == OP_ADDRCONST) {
1495 fprintf(fp, "(%p) %3d %-2d %-10s %-10p <0x%08lx> @ %s:%d.%d\n",
1496 ins, ID_REG(ins->id), ins->template_id, tops(ins->op),
1497 MISC(ins, 0), ins->u.cval,
1498 ins->filename, ins->line, ins->col);
1502 fprintf(fp, "(%p) %3d %-2d %-10s",
1503 ins, ID_REG(ins->id), ins->template_id, tops(ins->op));
1504 count = TRIPLE_SIZE(ins->sizes);
1505 for(i = 0; i < count; i++) {
1506 fprintf(fp, " %-10p", ins->param[i]);
1511 fprintf(fp, " @ %s:%d.%d\n",
1512 ins->filename, ins->line, ins->col);
1517 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1519 /* Does the triple have no side effects.
1520 * I.e. Rexecuting the triple with the same arguments
1521 * gives the same value.
1524 valid_ins(state, ins);
1525 pure = PURE_BITS(table_ops[ins->op].flags);
1526 if ((pure != PURE) && (pure != IMPURE)) {
1527 internal_error(state, 0, "Purity of %s not known\n",
1530 return pure == PURE;
1533 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1535 /* This function is used to determine which triples need
1539 valid_ins(state, ins);
1540 is_branch = (table_ops[ins->op].targ != 0);
1544 static int triple_is_def(struct compile_state *state, struct triple *ins)
1546 /* This function is used to determine which triples need
1550 valid_ins(state, ins);
1551 is_def = (table_ops[ins->op].flags & DEF) == DEF;
1555 static struct triple **triple_iter(struct compile_state *state,
1556 size_t count, struct triple **vector,
1557 struct triple *ins, struct triple **last)
1559 struct triple **ret;
1565 else if ((last >= vector) && (last < (vector + count - 1))) {
1573 static struct triple **triple_lhs(struct compile_state *state,
1574 struct triple *ins, struct triple **last)
1576 return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0),
1580 static struct triple **triple_rhs(struct compile_state *state,
1581 struct triple *ins, struct triple **last)
1583 return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0),
1587 static struct triple **triple_misc(struct compile_state *state,
1588 struct triple *ins, struct triple **last)
1590 return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0),
1594 static struct triple **triple_targ(struct compile_state *state,
1595 struct triple *ins, struct triple **last)
1598 struct triple **ret, **vector;
1600 count = TRIPLE_TARG(ins->sizes);
1601 vector = &TARG(ins, 0);
1606 else if ((last >= vector) && (last < (vector + count - 1))) {
1609 else if ((last == (vector + count - 1)) &&
1610 TRIPLE_RHS(ins->sizes)) {
1618 static void verify_use(struct compile_state *state,
1619 struct triple *user, struct triple *used)
1622 size = TRIPLE_SIZE(user->sizes);
1623 for(i = 0; i < size; i++) {
1624 if (user->param[i] == used) {
1628 if (triple_is_branch(state, user)) {
1629 if (user->next == used) {
1634 internal_error(state, user, "%s(%p) does not use %s(%p)",
1635 tops(user->op), user, tops(used->op), used);
1639 static int find_rhs_use(struct compile_state *state,
1640 struct triple *user, struct triple *used)
1642 struct triple **param;
1644 verify_use(state, user, used);
1645 size = TRIPLE_RHS(user->sizes);
1646 param = &RHS(user, 0);
1647 for(i = 0; i < size; i++) {
1648 if (param[i] == used) {
1655 static void free_triple(struct compile_state *state, struct triple *ptr)
1658 size = sizeof(*ptr) - sizeof(ptr->param) +
1659 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1660 ptr->prev->next = ptr->next;
1661 ptr->next->prev = ptr->prev;
1663 internal_error(state, ptr, "ptr->use != 0");
1665 memset(ptr, -1, size);
1669 static void release_triple(struct compile_state *state, struct triple *ptr)
1671 struct triple_set *set, *next;
1672 struct triple **expr;
1673 /* Remove ptr from use chains where it is the user */
1674 expr = triple_rhs(state, ptr, 0);
1675 for(; expr; expr = triple_rhs(state, ptr, expr)) {
1677 unuse_triple(*expr, ptr);
1680 expr = triple_lhs(state, ptr, 0);
1681 for(; expr; expr = triple_lhs(state, ptr, expr)) {
1683 unuse_triple(*expr, ptr);
1686 expr = triple_misc(state, ptr, 0);
1687 for(; expr; expr = triple_misc(state, ptr, expr)) {
1689 unuse_triple(*expr, ptr);
1692 expr = triple_targ(state, ptr, 0);
1693 for(; expr; expr = triple_targ(state, ptr, expr)) {
1695 unuse_triple(*expr, ptr);
1698 /* Reomve ptr from use chains where it is used */
1699 for(set = ptr->use; set; set = next) {
1701 expr = triple_rhs(state, set->member, 0);
1702 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1704 *expr = &zero_triple;
1707 expr = triple_lhs(state, set->member, 0);
1708 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1710 *expr = &zero_triple;
1713 expr = triple_misc(state, set->member, 0);
1714 for(; expr; expr = triple_misc(state, set->member, expr)) {
1716 *expr = &zero_triple;
1719 expr = triple_targ(state, set->member, 0);
1720 for(; expr; expr = triple_targ(state, set->member, expr)) {
1722 *expr = &zero_triple;
1725 unuse_triple(ptr, set->member);
1727 free_triple(state, ptr);
1730 static void print_triple(struct compile_state *state, struct triple *ptr);
1732 #define TOK_UNKNOWN 0
1735 #define TOK_LBRACE 3
1736 #define TOK_RBRACE 4
1740 #define TOK_LBRACKET 8
1741 #define TOK_RBRACKET 9
1742 #define TOK_LPAREN 10
1743 #define TOK_RPAREN 11
1748 #define TOK_TIMESEQ 16
1749 #define TOK_DIVEQ 17
1750 #define TOK_MODEQ 18
1751 #define TOK_PLUSEQ 19
1752 #define TOK_MINUSEQ 20
1755 #define TOK_ANDEQ 23
1756 #define TOK_XOREQ 24
1759 #define TOK_NOTEQ 27
1760 #define TOK_QUEST 28
1761 #define TOK_LOGOR 29
1762 #define TOK_LOGAND 30
1766 #define TOK_LESSEQ 34
1767 #define TOK_MOREEQ 35
1771 #define TOK_MINUS 39
1774 #define TOK_PLUSPLUS 42
1775 #define TOK_MINUSMINUS 43
1777 #define TOK_ARROW 45
1779 #define TOK_TILDE 47
1780 #define TOK_LIT_STRING 48
1781 #define TOK_LIT_CHAR 49
1782 #define TOK_LIT_INT 50
1783 #define TOK_LIT_FLOAT 51
1784 #define TOK_MACRO 52
1785 #define TOK_CONCATENATE 53
1787 #define TOK_IDENT 54
1788 #define TOK_STRUCT_NAME 55
1789 #define TOK_ENUM_CONST 56
1790 #define TOK_TYPE_NAME 57
1793 #define TOK_BREAK 59
1796 #define TOK_CONST 62
1797 #define TOK_CONTINUE 63
1798 #define TOK_DEFAULT 64
1800 #define TOK_DOUBLE 66
1803 #define TOK_EXTERN 69
1804 #define TOK_FLOAT 70
1808 #define TOK_INLINE 74
1811 #define TOK_REGISTER 77
1812 #define TOK_RESTRICT 78
1813 #define TOK_RETURN 79
1814 #define TOK_SHORT 80
1815 #define TOK_SIGNED 81
1816 #define TOK_SIZEOF 82
1817 #define TOK_STATIC 83
1818 #define TOK_STRUCT 84
1819 #define TOK_SWITCH 85
1820 #define TOK_TYPEDEF 86
1821 #define TOK_UNION 87
1822 #define TOK_UNSIGNED 88
1824 #define TOK_VOLATILE 90
1825 #define TOK_WHILE 91
1827 #define TOK_ATTRIBUTE 93
1828 #define TOK_ALIGNOF 94
1829 #define TOK_FIRST_KEYWORD TOK_AUTO
1830 #define TOK_LAST_KEYWORD TOK_ALIGNOF
1832 #define TOK_DEFINE 100
1833 #define TOK_UNDEF 101
1834 #define TOK_INCLUDE 102
1835 #define TOK_LINE 103
1836 #define TOK_ERROR 104
1837 #define TOK_WARNING 105
1838 #define TOK_PRAGMA 106
1839 #define TOK_IFDEF 107
1840 #define TOK_IFNDEF 108
1841 #define TOK_ELIF 109
1842 #define TOK_ENDIF 110
1844 #define TOK_FIRST_MACRO TOK_DEFINE
1845 #define TOK_LAST_MACRO TOK_ENDIF
1849 static const char *tokens[] = {
1850 [TOK_UNKNOWN ] = "unknown",
1851 [TOK_SPACE ] = ":space:",
1853 [TOK_LBRACE ] = "{",
1854 [TOK_RBRACE ] = "}",
1858 [TOK_LBRACKET ] = "[",
1859 [TOK_RBRACKET ] = "]",
1860 [TOK_LPAREN ] = "(",
1861 [TOK_RPAREN ] = ")",
1863 [TOK_DOTS ] = "...",
1866 [TOK_TIMESEQ ] = "*=",
1867 [TOK_DIVEQ ] = "/=",
1868 [TOK_MODEQ ] = "%=",
1869 [TOK_PLUSEQ ] = "+=",
1870 [TOK_MINUSEQ ] = "-=",
1871 [TOK_SLEQ ] = "<<=",
1872 [TOK_SREQ ] = ">>=",
1873 [TOK_ANDEQ ] = "&=",
1874 [TOK_XOREQ ] = "^=",
1877 [TOK_NOTEQ ] = "!=",
1879 [TOK_LOGOR ] = "||",
1880 [TOK_LOGAND ] = "&&",
1884 [TOK_LESSEQ ] = "<=",
1885 [TOK_MOREEQ ] = ">=",
1892 [TOK_PLUSPLUS ] = "++",
1893 [TOK_MINUSMINUS ] = "--",
1895 [TOK_ARROW ] = "->",
1898 [TOK_LIT_STRING ] = ":string:",
1899 [TOK_IDENT ] = ":ident:",
1900 [TOK_TYPE_NAME ] = ":typename:",
1901 [TOK_LIT_CHAR ] = ":char:",
1902 [TOK_LIT_INT ] = ":integer:",
1903 [TOK_LIT_FLOAT ] = ":float:",
1905 [TOK_CONCATENATE ] = "##",
1907 [TOK_AUTO ] = "auto",
1908 [TOK_BREAK ] = "break",
1909 [TOK_CASE ] = "case",
1910 [TOK_CHAR ] = "char",
1911 [TOK_CONST ] = "const",
1912 [TOK_CONTINUE ] = "continue",
1913 [TOK_DEFAULT ] = "default",
1915 [TOK_DOUBLE ] = "double",
1916 [TOK_ELSE ] = "else",
1917 [TOK_ENUM ] = "enum",
1918 [TOK_EXTERN ] = "extern",
1919 [TOK_FLOAT ] = "float",
1921 [TOK_GOTO ] = "goto",
1923 [TOK_INLINE ] = "inline",
1925 [TOK_LONG ] = "long",
1926 [TOK_REGISTER ] = "register",
1927 [TOK_RESTRICT ] = "restrict",
1928 [TOK_RETURN ] = "return",
1929 [TOK_SHORT ] = "short",
1930 [TOK_SIGNED ] = "signed",
1931 [TOK_SIZEOF ] = "sizeof",
1932 [TOK_STATIC ] = "static",
1933 [TOK_STRUCT ] = "struct",
1934 [TOK_SWITCH ] = "switch",
1935 [TOK_TYPEDEF ] = "typedef",
1936 [TOK_UNION ] = "union",
1937 [TOK_UNSIGNED ] = "unsigned",
1938 [TOK_VOID ] = "void",
1939 [TOK_VOLATILE ] = "volatile",
1940 [TOK_WHILE ] = "while",
1942 [TOK_ATTRIBUTE ] = "__attribute__",
1943 [TOK_ALIGNOF ] = "__alignof__",
1945 [TOK_DEFINE ] = "define",
1946 [TOK_UNDEF ] = "undef",
1947 [TOK_INCLUDE ] = "include",
1948 [TOK_LINE ] = "line",
1949 [TOK_ERROR ] = "error",
1950 [TOK_WARNING ] = "warning",
1951 [TOK_PRAGMA ] = "pragma",
1952 [TOK_IFDEF ] = "ifdef",
1953 [TOK_IFNDEF ] = "ifndef",
1954 [TOK_ELIF ] = "elif",
1955 [TOK_ENDIF ] = "endif",
1960 static unsigned int hash(const char *str, int str_len)
1964 end = str + str_len;
1966 for(; str < end; str++) {
1967 hash = (hash *263) + *str;
1969 hash = hash & (HASH_TABLE_SIZE -1);
1973 static struct hash_entry *lookup(
1974 struct compile_state *state, const char *name, int name_len)
1976 struct hash_entry *entry;
1978 index = hash(name, name_len);
1979 entry = state->hash_table[index];
1981 ((entry->name_len != name_len) ||
1982 (memcmp(entry->name, name, name_len) != 0))) {
1983 entry = entry->next;
1987 /* Get a private copy of the name */
1988 new_name = xmalloc(name_len + 1, "hash_name");
1989 memcpy(new_name, name, name_len);
1990 new_name[name_len] = '\0';
1992 /* Create a new hash entry */
1993 entry = xcmalloc(sizeof(*entry), "hash_entry");
1994 entry->next = state->hash_table[index];
1995 entry->name = new_name;
1996 entry->name_len = name_len;
1998 /* Place the new entry in the hash table */
1999 state->hash_table[index] = entry;
2004 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2006 struct hash_entry *entry;
2008 if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2009 (entry->tok == TOK_ENUM_CONST) ||
2010 ((entry->tok >= TOK_FIRST_KEYWORD) &&
2011 (entry->tok <= TOK_LAST_KEYWORD)))) {
2012 tk->tok = entry->tok;
2016 static void ident_to_macro(struct compile_state *state, struct token *tk)
2018 struct hash_entry *entry;
2021 (entry->tok >= TOK_FIRST_MACRO) &&
2022 (entry->tok <= TOK_LAST_MACRO)) {
2023 tk->tok = entry->tok;
2027 static void hash_keyword(
2028 struct compile_state *state, const char *keyword, int tok)
2030 struct hash_entry *entry;
2031 entry = lookup(state, keyword, strlen(keyword));
2032 if (entry && entry->tok != TOK_UNKNOWN) {
2033 die("keyword %s already hashed", keyword);
2039 struct compile_state *state, struct hash_entry *ident,
2040 struct symbol **chain, struct triple *def, struct type *type)
2043 if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2044 error(state, 0, "%s already defined", ident->name);
2046 sym = xcmalloc(sizeof(*sym), "symbol");
2050 sym->scope_depth = state->scope_depth;
2055 static void start_scope(struct compile_state *state)
2057 state->scope_depth++;
2060 static void end_scope_syms(struct symbol **chain, int depth)
2062 struct symbol *sym, *next;
2064 while(sym && (sym->scope_depth == depth)) {
2072 static void end_scope(struct compile_state *state)
2076 /* Walk through the hash table and remove all symbols
2077 * in the current scope.
2079 depth = state->scope_depth;
2080 for(i = 0; i < HASH_TABLE_SIZE; i++) {
2081 struct hash_entry *entry;
2082 entry = state->hash_table[i];
2084 end_scope_syms(&entry->sym_label, depth);
2085 end_scope_syms(&entry->sym_struct, depth);
2086 end_scope_syms(&entry->sym_ident, depth);
2087 entry = entry->next;
2090 state->scope_depth = depth - 1;
2093 static void register_keywords(struct compile_state *state)
2095 hash_keyword(state, "auto", TOK_AUTO);
2096 hash_keyword(state, "break", TOK_BREAK);
2097 hash_keyword(state, "case", TOK_CASE);
2098 hash_keyword(state, "char", TOK_CHAR);
2099 hash_keyword(state, "const", TOK_CONST);
2100 hash_keyword(state, "continue", TOK_CONTINUE);
2101 hash_keyword(state, "default", TOK_DEFAULT);
2102 hash_keyword(state, "do", TOK_DO);
2103 hash_keyword(state, "double", TOK_DOUBLE);
2104 hash_keyword(state, "else", TOK_ELSE);
2105 hash_keyword(state, "enum", TOK_ENUM);
2106 hash_keyword(state, "extern", TOK_EXTERN);
2107 hash_keyword(state, "float", TOK_FLOAT);
2108 hash_keyword(state, "for", TOK_FOR);
2109 hash_keyword(state, "goto", TOK_GOTO);
2110 hash_keyword(state, "if", TOK_IF);
2111 hash_keyword(state, "inline", TOK_INLINE);
2112 hash_keyword(state, "int", TOK_INT);
2113 hash_keyword(state, "long", TOK_LONG);
2114 hash_keyword(state, "register", TOK_REGISTER);
2115 hash_keyword(state, "restrict", TOK_RESTRICT);
2116 hash_keyword(state, "return", TOK_RETURN);
2117 hash_keyword(state, "short", TOK_SHORT);
2118 hash_keyword(state, "signed", TOK_SIGNED);
2119 hash_keyword(state, "sizeof", TOK_SIZEOF);
2120 hash_keyword(state, "static", TOK_STATIC);
2121 hash_keyword(state, "struct", TOK_STRUCT);
2122 hash_keyword(state, "switch", TOK_SWITCH);
2123 hash_keyword(state, "typedef", TOK_TYPEDEF);
2124 hash_keyword(state, "union", TOK_UNION);
2125 hash_keyword(state, "unsigned", TOK_UNSIGNED);
2126 hash_keyword(state, "void", TOK_VOID);
2127 hash_keyword(state, "volatile", TOK_VOLATILE);
2128 hash_keyword(state, "__volatile__", TOK_VOLATILE);
2129 hash_keyword(state, "while", TOK_WHILE);
2130 hash_keyword(state, "asm", TOK_ASM);
2131 hash_keyword(state, "__asm__", TOK_ASM);
2132 hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2133 hash_keyword(state, "__alignof__", TOK_ALIGNOF);
2136 static void register_macro_keywords(struct compile_state *state)
2138 hash_keyword(state, "define", TOK_DEFINE);
2139 hash_keyword(state, "undef", TOK_UNDEF);
2140 hash_keyword(state, "include", TOK_INCLUDE);
2141 hash_keyword(state, "line", TOK_LINE);
2142 hash_keyword(state, "error", TOK_ERROR);
2143 hash_keyword(state, "warning", TOK_WARNING);
2144 hash_keyword(state, "pragma", TOK_PRAGMA);
2145 hash_keyword(state, "ifdef", TOK_IFDEF);
2146 hash_keyword(state, "ifndef", TOK_IFNDEF);
2147 hash_keyword(state, "elif", TOK_ELIF);
2148 hash_keyword(state, "endif", TOK_ENDIF);
2151 static int spacep(int c)
2167 static int digitp(int c)
2171 case '0': case '1': case '2': case '3': case '4':
2172 case '5': case '6': case '7': case '8': case '9':
2178 static int digval(int c)
2181 if ((c >= '0') && (c <= '9')) {
2187 static int hexdigitp(int c)
2191 case '0': case '1': case '2': case '3': case '4':
2192 case '5': case '6': case '7': case '8': case '9':
2193 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2194 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2200 static int hexdigval(int c)
2203 if ((c >= '0') && (c <= '9')) {
2206 else if ((c >= 'A') && (c <= 'F')) {
2207 val = 10 + (c - 'A');
2209 else if ((c >= 'a') && (c <= 'f')) {
2210 val = 10 + (c - 'a');
2215 static int octdigitp(int c)
2219 case '0': case '1': case '2': case '3':
2220 case '4': case '5': case '6': case '7':
2226 static int octdigval(int c)
2229 if ((c >= '0') && (c <= '7')) {
2235 static int letterp(int c)
2239 case 'a': case 'b': case 'c': case 'd': case 'e':
2240 case 'f': case 'g': case 'h': case 'i': case 'j':
2241 case 'k': case 'l': case 'm': case 'n': case 'o':
2242 case 'p': case 'q': case 'r': case 's': case 't':
2243 case 'u': case 'v': case 'w': case 'x': case 'y':
2245 case 'A': case 'B': case 'C': case 'D': case 'E':
2246 case 'F': case 'G': case 'H': case 'I': case 'J':
2247 case 'K': case 'L': case 'M': case 'N': case 'O':
2248 case 'P': case 'Q': case 'R': case 'S': case 'T':
2249 case 'U': case 'V': case 'W': case 'X': case 'Y':
2258 static int char_value(struct compile_state *state,
2259 const signed char **strp, const signed char *end)
2261 const signed char *str;
2265 if ((c == '\\') && (str < end)) {
2267 case 'n': c = '\n'; str++; break;
2268 case 't': c = '\t'; str++; break;
2269 case 'v': c = '\v'; str++; break;
2270 case 'b': c = '\b'; str++; break;
2271 case 'r': c = '\r'; str++; break;
2272 case 'f': c = '\f'; str++; break;
2273 case 'a': c = '\a'; str++; break;
2274 case '\\': c = '\\'; str++; break;
2275 case '?': c = '?'; str++; break;
2276 case '\'': c = '\''; str++; break;
2277 case '"': c = '"'; break;
2281 while((str < end) && hexdigitp(*str)) {
2283 c += hexdigval(*str);
2287 case '0': case '1': case '2': case '3':
2288 case '4': case '5': case '6': case '7':
2290 while((str < end) && octdigitp(*str)) {
2292 c += octdigval(*str);
2297 error(state, 0, "Invalid character constant");
2305 static char *after_digits(char *ptr, char *end)
2307 while((ptr < end) && digitp(*ptr)) {
2313 static char *after_octdigits(char *ptr, char *end)
2315 while((ptr < end) && octdigitp(*ptr)) {
2321 static char *after_hexdigits(char *ptr, char *end)
2323 while((ptr < end) && hexdigitp(*ptr)) {
2329 static void save_string(struct compile_state *state,
2330 struct token *tk, char *start, char *end, const char *id)
2334 /* Create a private copy of the string */
2335 str_len = end - start + 1;
2336 str = xmalloc(str_len + 1, id);
2337 memcpy(str, start, str_len);
2338 str[str_len] = '\0';
2340 /* Store the copy in the token */
2342 tk->str_len = str_len;
2344 static void next_token(struct compile_state *state, int index)
2346 struct file_state *file;
2354 tk = &state->token[index];
2357 token = tokp = file->pos;
2358 end = file->buf + file->size;
2365 if ((tokp + 1) < end) {
2369 if ((tokp + 2) < end) {
2373 if ((tokp + 3) < end) {
2381 else if (spacep(c)) {
2383 while ((tokp < end) && spacep(c)) {
2386 file->line_start = tokp + 1;
2395 else if ((c == '/') && (c1 == '/')) {
2397 for(tokp += 2; tokp < end; tokp++) {
2401 file->line_start = tokp +1;
2407 else if ((c == '/') && (c1 == '*')) {
2411 line_start = file->line_start;
2412 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2416 line_start = tokp +1;
2418 else if ((c == '*') && (tokp[1] == '/')) {
2424 if (tok == TOK_UNKNOWN) {
2425 error(state, 0, "unterminated comment");
2428 file->line_start = line_start;
2430 /* string constants */
2431 else if ((c == '"') ||
2432 ((c == 'L') && (c1 == '"'))) {
2437 line_start = file->line_start;
2443 for(tokp += 1; tokp < end; tokp++) {
2447 line_start = tokp + 1;
2449 else if ((c == '\\') && (tokp +1 < end)) {
2452 else if (c == '"') {
2453 tok = TOK_LIT_STRING;
2457 if (tok == TOK_UNKNOWN) {
2458 error(state, 0, "unterminated string constant");
2460 if (line != file->line) {
2461 warning(state, 0, "multiline string constant");
2464 file->line_start = line_start;
2466 /* Save the string value */
2467 save_string(state, tk, token, tokp, "literal string");
2469 /* character constants */
2470 else if ((c == '\'') ||
2471 ((c == 'L') && (c1 == '\''))) {
2476 line_start = file->line_start;
2482 for(tokp += 1; tokp < end; tokp++) {
2486 line_start = tokp + 1;
2488 else if ((c == '\\') && (tokp +1 < end)) {
2491 else if (c == '\'') {
2496 if (tok == TOK_UNKNOWN) {
2497 error(state, 0, "unterminated character constant");
2499 if (line != file->line) {
2500 warning(state, 0, "multiline character constant");
2503 file->line_start = line_start;
2505 /* Save the character value */
2506 save_string(state, tk, token, tokp, "literal character");
2508 /* integer and floating constants
2514 * Floating constants
2515 * {digits}.{digits}[Ee][+-]?{digits}
2517 * {digits}[Ee][+-]?{digits}
2518 * .{digits}[Ee][+-]?{digits}
2522 else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2527 next = after_digits(tokp, end);
2532 if (next[0] == '.') {
2533 new = after_digits(next, end);
2534 is_float = (new != next);
2537 if ((next[0] == 'e') || (next[0] == 'E')) {
2538 if (((next + 1) < end) &&
2539 ((next[1] == '+') || (next[1] == '-'))) {
2542 new = after_digits(next, end);
2543 is_float = (new != next);
2547 tok = TOK_LIT_FLOAT;
2548 if ((next < end) && (
2557 if (!is_float && digitp(c)) {
2559 if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2560 next = after_hexdigits(tokp + 2, end);
2562 else if (c == '0') {
2563 next = after_octdigits(tokp, end);
2566 next = after_digits(tokp, end);
2568 /* crazy integer suffixes */
2570 ((next[0] == 'u') || (next[0] == 'U'))) {
2573 ((next[0] == 'l') || (next[0] == 'L'))) {
2577 else if ((next < end) &&
2578 ((next[0] == 'l') || (next[0] == 'L'))) {
2581 ((next[0] == 'u') || (next[0] == 'U'))) {
2588 /* Save the integer/floating point value */
2589 save_string(state, tk, token, tokp, "literal number");
2592 else if (letterp(c)) {
2594 for(tokp += 1; tokp < end; tokp++) {
2596 if (!letterp(c) && !digitp(c)) {
2601 tk->ident = lookup(state, token, tokp +1 - token);
2603 /* C99 alternate macro characters */
2604 else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
2606 tok = TOK_CONCATENATE;
2608 else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2609 else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2610 else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2611 else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2612 else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2613 else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2614 else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2615 else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2616 else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2617 else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2618 else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2619 else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2620 else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2621 else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2622 else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2623 else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2624 else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2625 else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2626 else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2627 else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2628 else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2629 else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2630 else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2631 else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2632 else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2633 else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2634 else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2635 else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2636 else if (c == ';') { tok = TOK_SEMI; }
2637 else if (c == '{') { tok = TOK_LBRACE; }
2638 else if (c == '}') { tok = TOK_RBRACE; }
2639 else if (c == ',') { tok = TOK_COMMA; }
2640 else if (c == '=') { tok = TOK_EQ; }
2641 else if (c == ':') { tok = TOK_COLON; }
2642 else if (c == '[') { tok = TOK_LBRACKET; }
2643 else if (c == ']') { tok = TOK_RBRACKET; }
2644 else if (c == '(') { tok = TOK_LPAREN; }
2645 else if (c == ')') { tok = TOK_RPAREN; }
2646 else if (c == '*') { tok = TOK_STAR; }
2647 else if (c == '>') { tok = TOK_MORE; }
2648 else if (c == '<') { tok = TOK_LESS; }
2649 else if (c == '?') { tok = TOK_QUEST; }
2650 else if (c == '|') { tok = TOK_OR; }
2651 else if (c == '&') { tok = TOK_AND; }
2652 else if (c == '^') { tok = TOK_XOR; }
2653 else if (c == '+') { tok = TOK_PLUS; }
2654 else if (c == '-') { tok = TOK_MINUS; }
2655 else if (c == '/') { tok = TOK_DIV; }
2656 else if (c == '%') { tok = TOK_MOD; }
2657 else if (c == '!') { tok = TOK_BANG; }
2658 else if (c == '.') { tok = TOK_DOT; }
2659 else if (c == '~') { tok = TOK_TILDE; }
2660 else if (c == '#') { tok = TOK_MACRO; }
2661 if (tok == TOK_MACRO) {
2662 /* Only match preprocessor directives at the start of a line */
2664 for(ptr = file->line_start; spacep(*ptr); ptr++)
2670 if (tok == TOK_UNKNOWN) {
2671 error(state, 0, "unknown token");
2674 file->pos = tokp + 1;
2676 if (tok == TOK_IDENT) {
2677 ident_to_keyword(state, tk);
2679 /* Don't return space tokens. */
2680 if (tok == TOK_SPACE) {
2685 static void compile_macro(struct compile_state *state, struct token *tk)
2687 struct file_state *file;
2688 struct hash_entry *ident;
2690 file = xmalloc(sizeof(*file), "file_state");
2691 file->basename = xstrdup(tk->ident->name);
2692 file->dirname = xstrdup("");
2693 file->size = ident->sym_define->buf_len;
2694 file->buf = xmalloc(file->size +2, file->basename);
2695 memcpy(file->buf, ident->sym_define->buf, file->size);
2696 file->buf[file->size] = '\n';
2697 file->buf[file->size + 1] = '\0';
2698 file->pos = file->buf;
2699 file->line_start = file->pos;
2701 file->prev = state->file;
2706 static int mpeek(struct compile_state *state, int index)
2710 tk = &state->token[index + 1];
2711 if (tk->tok == -1) {
2712 next_token(state, index + 1);
2716 if ((tk->tok == TOK_EOF) &&
2717 (state->file != state->macro_file) &&
2718 (state->file->prev)) {
2719 struct file_state *file = state->file;
2720 state->file = file->prev;
2721 /* file->basename is used keep it */
2722 xfree(file->dirname);
2725 next_token(state, index + 1);
2728 else if (tk->ident && tk->ident->sym_define) {
2729 compile_macro(state, tk);
2730 next_token(state, index + 1);
2734 /* Don't show the token on the next line */
2735 if (state->macro_line < state->macro_file->line) {
2738 return state->token[index +1].tok;
2741 static void meat(struct compile_state *state, int index, int tok)
2745 next_tok = mpeek(state, index);
2746 if (next_tok != tok) {
2747 const char *name1, *name2;
2748 name1 = tokens[next_tok];
2750 if (next_tok == TOK_IDENT) {
2751 name2 = state->token[index + 1].ident->name;
2753 error(state, 0, "found %s %s expected %s",
2754 name1, name2, tokens[tok]);
2756 /* Free the old token value */
2757 if (state->token[index].str_len) {
2758 memset((void *)(state->token[index].val.str), -1,
2759 state->token[index].str_len);
2760 xfree(state->token[index].val.str);
2762 for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2763 state->token[i] = state->token[i + 1];
2765 memset(&state->token[i], 0, sizeof(state->token[i]));
2766 state->token[i].tok = -1;
2769 static long_t mcexpr(struct compile_state *state, int index);
2771 static long_t mprimary_expr(struct compile_state *state, int index)
2775 tok = mpeek(state, index);
2776 while(state->token[index + 1].ident &&
2777 state->token[index + 1].ident->sym_define) {
2778 meat(state, index, tok);
2779 compile_macro(state, &state->token[index]);
2780 tok = mpeek(state, index);
2784 meat(state, index, TOK_LPAREN);
2785 val = mcexpr(state, index);
2786 meat(state, index, TOK_RPAREN);
2791 meat(state, index, TOK_LIT_INT);
2793 val = strtol(state->token[index].val.str, &end, 0);
2794 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2795 (errno == ERANGE)) {
2796 error(state, 0, "Integer constant to large");
2801 meat(state, index, TOK_LIT_INT);
2806 static long_t munary_expr(struct compile_state *state, int index)
2809 switch(mpeek(state, index)) {
2811 meat(state, index, TOK_PLUS);
2812 val = munary_expr(state, index);
2816 meat(state, index, TOK_MINUS);
2817 val = munary_expr(state, index);
2821 meat(state, index, TOK_BANG);
2822 val = munary_expr(state, index);
2826 meat(state, index, TOK_BANG);
2827 val = munary_expr(state, index);
2831 val = mprimary_expr(state, index);
2837 static long_t mmul_expr(struct compile_state *state, int index)
2841 val = munary_expr(state, index);
2845 switch(mpeek(state, index)) {
2847 meat(state, index, TOK_STAR);
2848 right = munary_expr(state, index);
2852 meat(state, index, TOK_DIV);
2853 right = munary_expr(state, index);
2857 meat(state, index, TOK_MOD);
2858 right = munary_expr(state, index);
2870 static long_t madd_expr(struct compile_state *state, int index)
2874 val = mmul_expr(state, index);
2878 switch(mpeek(state, index)) {
2880 meat(state, index, TOK_PLUS);
2881 right = mmul_expr(state, index);
2885 meat(state, index, TOK_MINUS);
2886 right = mmul_expr(state, index);
2898 static long_t mshift_expr(struct compile_state *state, int index)
2902 val = madd_expr(state, index);
2906 switch(mpeek(state, index)) {
2908 meat(state, index, TOK_SL);
2909 right = madd_expr(state, index);
2913 meat(state, index, TOK_SR);
2914 right = madd_expr(state, index);
2926 static long_t mrel_expr(struct compile_state *state, int index)
2930 val = mshift_expr(state, index);
2934 switch(mpeek(state, index)) {
2936 meat(state, index, TOK_LESS);
2937 right = mshift_expr(state, index);
2941 meat(state, index, TOK_MORE);
2942 right = mshift_expr(state, index);
2946 meat(state, index, TOK_LESSEQ);
2947 right = mshift_expr(state, index);
2951 meat(state, index, TOK_MOREEQ);
2952 right = mshift_expr(state, index);
2963 static long_t meq_expr(struct compile_state *state, int index)
2967 val = mrel_expr(state, index);
2971 switch(mpeek(state, index)) {
2973 meat(state, index, TOK_EQEQ);
2974 right = mrel_expr(state, index);
2978 meat(state, index, TOK_NOTEQ);
2979 right = mrel_expr(state, index);
2990 static long_t mand_expr(struct compile_state *state, int index)
2993 val = meq_expr(state, index);
2994 if (mpeek(state, index) == TOK_AND) {
2996 meat(state, index, TOK_AND);
2997 right = meq_expr(state, index);
3003 static long_t mxor_expr(struct compile_state *state, int index)
3006 val = mand_expr(state, index);
3007 if (mpeek(state, index) == TOK_XOR) {
3009 meat(state, index, TOK_XOR);
3010 right = mand_expr(state, index);
3016 static long_t mor_expr(struct compile_state *state, int index)
3019 val = mxor_expr(state, index);
3020 if (mpeek(state, index) == TOK_OR) {
3022 meat(state, index, TOK_OR);
3023 right = mxor_expr(state, index);
3029 static long_t mland_expr(struct compile_state *state, int index)
3032 val = mor_expr(state, index);
3033 if (mpeek(state, index) == TOK_LOGAND) {
3035 meat(state, index, TOK_LOGAND);
3036 right = mor_expr(state, index);
3041 static long_t mlor_expr(struct compile_state *state, int index)
3044 val = mland_expr(state, index);
3045 if (mpeek(state, index) == TOK_LOGOR) {
3047 meat(state, index, TOK_LOGOR);
3048 right = mland_expr(state, index);
3054 static long_t mcexpr(struct compile_state *state, int index)
3056 return mlor_expr(state, index);
3058 static void preprocess(struct compile_state *state, int index)
3060 /* Doing much more with the preprocessor would require
3061 * a parser and a major restructuring.
3062 * Postpone that for later.
3064 struct file_state *file;
3070 tk = &state->token[index];
3071 state->macro_line = line = file->line;
3072 state->macro_file = file;
3074 next_token(state, index);
3075 ident_to_macro(state, tk);
3076 if (tk->tok == TOK_IDENT) {
3077 error(state, 0, "undefined preprocessing directive `%s'",
3084 if (state->if_value < 0) {
3087 warning(state, 0, "Ignoring preprocessor directive: %s",
3091 error(state, 0, "#elif not supported");
3092 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3093 if (state->if_depth == 0) {
3094 error(state, 0, "#elif without #if");
3096 /* If the #if was taken the #elif just disables the following code */
3097 if (state->if_value >= 0) {
3098 state->if_value = - state->if_value;
3100 /* If the previous #if was not taken see if the #elif enables the
3103 else if ((state->if_value < 0) &&
3104 (state->if_depth == - state->if_value))
3106 if (mcexpr(state, index) != 0) {
3107 state->if_value = state->if_depth;
3110 state->if_value = - state->if_depth;
3116 if (state->if_value < 0) {
3119 if (mcexpr(state, index) != 0) {
3120 state->if_value = state->if_depth;
3123 state->if_value = - state->if_depth;
3128 if (state->if_value < 0) {
3131 next_token(state, index);
3132 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3133 error(state, 0, "Invalid macro name");
3135 if (tk->ident->sym_define == 0) {
3136 state->if_value = state->if_depth;
3139 state->if_value = - state->if_depth;
3144 if (state->if_value < 0) {
3147 next_token(state, index);
3148 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3149 error(state, 0, "Invalid macro name");
3151 if (tk->ident->sym_define != 0) {
3152 state->if_value = state->if_depth;
3155 state->if_value = - state->if_depth;
3159 if (state->if_depth == 0) {
3160 error(state, 0, "#else without #if");
3162 if ((state->if_value >= 0) ||
3163 ((state->if_value < 0) &&
3164 (state->if_depth == -state->if_value)))
3166 state->if_value = - state->if_value;
3170 if (state->if_depth == 0) {
3171 error(state, 0, "#endif without #if");
3173 if ((state->if_value >= 0) ||
3174 ((state->if_value < 0) &&
3175 (state->if_depth == -state->if_value)))
3177 state->if_value = state->if_depth - 1;
3183 struct hash_entry *ident;
3184 struct macro *macro;
3187 if (state->if_value < 0) /* quit early when #if'd out */
3190 meat(state, index, TOK_IDENT);
3194 if (*file->pos == '(') {
3195 #warning "FIXME macros with arguments not supported"
3196 error(state, 0, "Macros with arguments not supported");
3199 /* Find the end of the line to get an estimate of
3200 * the macro's length.
3202 for(ptr = file->pos; *ptr != '\n'; ptr++)
3205 if (ident->sym_define != 0) {
3206 error(state, 0, "macro %s already defined\n", ident->name);
3208 macro = xmalloc(sizeof(*macro), "macro");
3209 macro->ident = ident;
3210 macro->buf_len = ptr - file->pos +1;
3211 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3213 memcpy(macro->buf, file->pos, macro->buf_len);
3214 macro->buf[macro->buf_len] = '\n';
3215 macro->buf[macro->buf_len +1] = '\0';
3217 ident->sym_define = macro;
3224 /* Find the end of the line */
3225 for(end = file->pos; *end != '\n'; end++)
3227 len = (end - file->pos);
3228 if (state->if_value >= 0) {
3229 error(state, 0, "%*.*s", len, len, file->pos);
3238 /* Find the end of the line */
3239 for(end = file->pos; *end != '\n'; end++)
3241 len = (end - file->pos);
3242 if (state->if_value >= 0) {
3243 warning(state, 0, "%*.*s", len, len, file->pos);
3255 next_token(state, index);
3256 if (tk->tok == TOK_LIT_STRING) {
3259 name = xmalloc(tk->str_len, "include");
3260 token = tk->val.str +1;
3261 name_len = tk->str_len -2;
3262 if (*token == '"') {
3266 memcpy(name, token, name_len);
3267 name[name_len] = '\0';
3270 else if (tk->tok == TOK_LESS) {
3273 for(end = start; *end != '\n'; end++) {
3279 error(state, 0, "Unterminated included directive");
3281 name = xmalloc(end - start + 1, "include");
3282 memcpy(name, start, end - start);
3283 name[end - start] = '\0';
3288 error(state, 0, "Invalid include directive");
3290 /* Error if there are any characters after the include */
3291 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3298 error(state, 0, "garbage after include directive");
3301 if (state->if_value >= 0) {
3302 compile_file(state, name, local);
3305 next_token(state, index);
3309 /* Ignore # without a following ident */
3310 if (tk->tok == TOK_IDENT) {
3311 error(state, 0, "Invalid preprocessor directive: %s",
3316 /* Consume the rest of the macro line */
3318 tok = mpeek(state, index);
3319 meat(state, index, tok);
3320 } while(tok != TOK_EOF);
3324 static void token(struct compile_state *state, int index)
3326 struct file_state *file;
3330 tk = &state->token[index];
3331 next_token(state, index);
3335 if (tk->tok == TOK_EOF && file->prev) {
3336 state->file = file->prev;
3337 /* file->basename is used keep it */
3338 xfree(file->dirname);
3341 next_token(state, index);
3344 else if (tk->tok == TOK_MACRO) {
3345 preprocess(state, index);
3348 else if (tk->ident && tk->ident->sym_define) {
3349 compile_macro(state, tk);
3350 next_token(state, index);
3353 else if (state->if_value < 0) {
3354 next_token(state, index);
3360 static int peek(struct compile_state *state)
3362 if (state->token[1].tok == -1) {
3365 return state->token[1].tok;
3368 static int peek2(struct compile_state *state)
3370 if (state->token[1].tok == -1) {
3373 if (state->token[2].tok == -1) {
3376 return state->token[2].tok;
3379 static void eat(struct compile_state *state, int tok)
3383 next_tok = peek(state);
3384 if (next_tok != tok) {
3385 const char *name1, *name2;
3386 name1 = tokens[next_tok];
3388 if (next_tok == TOK_IDENT) {
3389 name2 = state->token[1].ident->name;
3391 error(state, 0, "\tfound %s %s expected %s",
3392 name1, name2 ,tokens[tok]);
3394 /* Free the old token value */
3395 if (state->token[0].str_len) {
3396 xfree((void *)(state->token[0].val.str));
3398 for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3399 state->token[i] = state->token[i + 1];
3401 memset(&state->token[i], 0, sizeof(state->token[i]));
3402 state->token[i].tok = -1;
3405 #warning "FIXME do not hardcode the include paths"
3406 static char *include_paths[] = {
3407 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3408 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3409 "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3413 static void compile_file(struct compile_state *state, const char *filename, int local)
3416 const char *subdir, *base;
3418 struct file_state *file;
3420 file = xmalloc(sizeof(*file), "file_state");
3422 base = strrchr(filename, '/');
3425 subdir_len = base - filename;
3432 basename = xmalloc(strlen(base) +1, "basename");
3433 strcpy(basename, base);
3434 file->basename = basename;
3436 if (getcwd(cwd, sizeof(cwd)) == 0) {
3437 die("cwd buffer to small");
3440 if (subdir[0] == '/') {
3441 file->dirname = xmalloc(subdir_len + 1, "dirname");
3442 memcpy(file->dirname, subdir, subdir_len);
3443 file->dirname[subdir_len] = '\0';
3449 /* Find the appropriate directory... */
3451 if (!state->file && exists(cwd, filename)) {
3454 if (local && state->file && exists(state->file->dirname, filename)) {
3455 dir = state->file->dirname;
3457 for(path = include_paths; !dir && *path; path++) {
3458 if (exists(*path, filename)) {
3463 error(state, 0, "Cannot find `%s'\n", filename);
3465 dirlen = strlen(dir);
3466 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3467 memcpy(file->dirname, dir, dirlen);
3468 file->dirname[dirlen] = '/';
3469 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3470 file->dirname[dirlen + 1 + subdir_len] = '\0';
3472 file->buf = slurp_file(file->dirname, file->basename, &file->size);
3475 file->pos = file->buf;
3476 file->line_start = file->pos;
3479 file->prev = state->file;
3482 process_trigraphs(state);
3483 splice_lines(state);
3486 /* Type helper functions */
3488 static struct type *new_type(
3489 unsigned int type, struct type *left, struct type *right)
3491 struct type *result;
3492 result = xmalloc(sizeof(*result), "type");
3493 result->type = type;
3494 result->left = left;
3495 result->right = right;
3496 result->field_ident = 0;
3497 result->type_ident = 0;
3501 static struct type *clone_type(unsigned int specifiers, struct type *old)
3503 struct type *result;
3504 result = xmalloc(sizeof(*result), "type");
3505 memcpy(result, old, sizeof(*result));
3506 result->type &= TYPE_MASK;
3507 result->type |= specifiers;
3511 #define SIZEOF_SHORT 2
3512 #define SIZEOF_INT 4
3513 #define SIZEOF_LONG (sizeof(long_t))
3515 #define ALIGNOF_SHORT 2
3516 #define ALIGNOF_INT 4
3517 #define ALIGNOF_LONG (sizeof(long_t))
3519 #define MASK_UCHAR(X) ((X) & ((ulong_t)0xff))
3520 #define MASK_USHORT(X) ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3521 static inline ulong_t mask_uint(ulong_t x)
3523 if (SIZEOF_INT < SIZEOF_LONG) {
3524 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3529 #define MASK_UINT(X) (mask_uint(X))
3530 #define MASK_ULONG(X) (X)
3532 static struct type void_type = { .type = TYPE_VOID };
3533 static struct type char_type = { .type = TYPE_CHAR };
3534 static struct type uchar_type = { .type = TYPE_UCHAR };
3535 static struct type short_type = { .type = TYPE_SHORT };
3536 static struct type ushort_type = { .type = TYPE_USHORT };
3537 static struct type int_type = { .type = TYPE_INT };
3538 static struct type uint_type = { .type = TYPE_UINT };
3539 static struct type long_type = { .type = TYPE_LONG };
3540 static struct type ulong_type = { .type = TYPE_ULONG };
3542 static struct triple *variable(struct compile_state *state, struct type *type)
3544 struct triple *result;
3545 if ((type->type & STOR_MASK) != STOR_PERM) {
3546 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3547 result = triple(state, OP_ADECL, type, 0, 0);
3550 struct triple **vector;
3552 result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3553 vector = &result->param[0];
3557 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3558 vector[index] = variable(state, field->left);
3559 field = field->right;
3562 vector[index] = variable(state, field);
3566 result = triple(state, OP_SDECL, type, 0, 0);
3571 static void stor_of(FILE *fp, struct type *type)
3573 switch(type->type & STOR_MASK) {
3575 fprintf(fp, "auto ");
3578 fprintf(fp, "static ");
3581 fprintf(fp, "extern ");
3584 fprintf(fp, "register ");
3587 fprintf(fp, "typedef ");
3590 fprintf(fp, "inline ");
3594 static void qual_of(FILE *fp, struct type *type)
3596 if (type->type & QUAL_CONST) {
3597 fprintf(fp, " const");
3599 if (type->type & QUAL_VOLATILE) {
3600 fprintf(fp, " volatile");
3602 if (type->type & QUAL_RESTRICT) {
3603 fprintf(fp, " restrict");
3607 static void name_of(FILE *fp, struct type *type)
3610 switch(type->type & TYPE_MASK) {
3612 fprintf(fp, "void");
3616 fprintf(fp, "signed char");
3620 fprintf(fp, "unsigned char");
3624 fprintf(fp, "signed short");
3628 fprintf(fp, "unsigned short");
3632 fprintf(fp, "signed int");
3636 fprintf(fp, "unsigned int");
3640 fprintf(fp, "signed long");
3644 fprintf(fp, "unsigned long");
3648 name_of(fp, type->left);
3654 name_of(fp, type->left);
3656 name_of(fp, type->right);
3659 fprintf(fp, "enum %s", type->type_ident->name);
3663 fprintf(fp, "struct %s", type->type_ident->name);
3668 name_of(fp, type->left);
3669 fprintf(fp, " (*)(");
3670 name_of(fp, type->right);
3675 name_of(fp, type->left);
3676 fprintf(fp, " [%ld]", type->elements);
3679 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3684 static size_t align_of(struct compile_state *state, struct type *type)
3688 switch(type->type & TYPE_MASK) {
3698 align = ALIGNOF_SHORT;
3703 align = ALIGNOF_INT;
3708 align = ALIGNOF_LONG;
3713 size_t left_align, right_align;
3714 left_align = align_of(state, type->left);
3715 right_align = align_of(state, type->right);
3716 align = (left_align >= right_align) ? left_align : right_align;
3720 align = align_of(state, type->left);
3723 align = align_of(state, type->left);
3726 error(state, 0, "alignof not yet defined for type\n");
3732 static size_t size_of(struct compile_state *state, struct type *type)
3736 switch(type->type & TYPE_MASK) {
3746 size = SIZEOF_SHORT;
3761 size = size_of(state, type->left);
3762 while((type->right->type & TYPE_MASK) == TYPE_PRODUCT) {
3764 align = align_of(state, type->left);
3765 pad = align - (size % align);
3766 size = size + pad + size_of(state, type->left);
3768 align = align_of(state, type->right);
3769 pad = align - (size % align);
3770 size = size + pad + sizeof(type->right);
3775 size_t size_left, size_right;
3776 size_left = size_of(state, type->left);
3777 size_right = size_of(state, type->right);
3778 size = (size_left >= size_right)? size_left : size_right;
3782 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3783 internal_error(state, 0, "Invalid array type");
3785 size = size_of(state, type->left) * type->elements;
3789 size = size_of(state, type->left);
3792 error(state, 0, "sizeof not yet defined for type\n");
3798 static size_t field_offset(struct compile_state *state,
3799 struct type *type, struct hash_entry *field)
3801 size_t size, align, pad;
3802 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3803 internal_error(state, 0, "field_offset only works on structures");
3807 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3808 if (type->left->field_ident == field) {
3811 size += size_of(state, type->left);
3813 align = align_of(state, type->left);
3814 pad = align - (size % align);
3817 if (type->field_ident != field) {
3818 internal_error(state, 0, "field_offset: member %s not present",
3824 static struct type *field_type(struct compile_state *state,
3825 struct type *type, struct hash_entry *field)
3827 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3828 internal_error(state, 0, "field_type only works on structures");
3831 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3832 if (type->left->field_ident == field) {
3838 if (type->field_ident != field) {
3839 internal_error(state, 0, "field_type: member %s not present",
3845 static struct triple *struct_field(struct compile_state *state,
3846 struct triple *decl, struct hash_entry *field)
3848 struct triple **vector;
3852 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3855 if (decl->op != OP_VAL_VEC) {
3856 internal_error(state, 0, "Invalid struct variable");
3859 internal_error(state, 0, "Missing structure field");
3862 vector = &RHS(decl, 0);
3864 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
3865 if (type->left->field_ident == field) {
3872 if (type->field_ident != field) {
3873 internal_error(state, 0, "field %s not found?", field->name);
3875 return vector[index];
3878 static void arrays_complete(struct compile_state *state, struct type *type)
3880 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
3881 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
3882 error(state, 0, "array size not specified");
3884 arrays_complete(state, type->left);
3888 static unsigned int do_integral_promotion(unsigned int type)
3891 if (TYPE_INTEGER(type) &&
3892 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
3898 static unsigned int do_arithmetic_conversion(
3899 unsigned int left, unsigned int right)
3903 if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
3904 return TYPE_LDOUBLE;
3906 else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
3909 else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
3912 left = do_integral_promotion(left);
3913 right = do_integral_promotion(right);
3914 /* If both operands have the same size done */
3915 if (left == right) {
3918 /* If both operands have the same signedness pick the larger */
3919 else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
3920 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
3922 /* If the signed type can hold everything use it */
3923 else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
3926 else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
3929 /* Convert to the unsigned type with the same rank as the signed type */
3930 else if (TYPE_SIGNED(left)) {
3931 return TYPE_MKUNSIGNED(left);
3934 return TYPE_MKUNSIGNED(right);
3938 /* see if two types are the same except for qualifiers */
3939 static int equiv_types(struct type *left, struct type *right)
3942 /* Error if the basic types do not match */
3943 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3946 type = left->type & TYPE_MASK;
3947 /* if the basic types match and it is an arithmetic type we are done */
3948 if (TYPE_ARITHMETIC(type)) {
3951 /* If it is a pointer type recurse and keep testing */
3952 if (type == TYPE_POINTER) {
3953 return equiv_types(left->left, right->left);
3955 else if (type == TYPE_ARRAY) {
3956 return (left->elements == right->elements) &&
3957 equiv_types(left->left, right->left);
3959 /* test for struct/union equality */
3960 else if (type == TYPE_STRUCT) {
3961 return left->type_ident == right->type_ident;
3963 /* Test for equivalent functions */
3964 else if (type == TYPE_FUNCTION) {
3965 return equiv_types(left->left, right->left) &&
3966 equiv_types(left->right, right->right);
3968 /* We only see TYPE_PRODUCT as part of function equivalence matching */
3969 else if (type == TYPE_PRODUCT) {
3970 return equiv_types(left->left, right->left) &&
3971 equiv_types(left->right, right->right);
3973 /* We should see TYPE_OVERLAP */
3979 static int equiv_ptrs(struct type *left, struct type *right)
3981 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
3982 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
3985 return equiv_types(left->left, right->left);
3988 static struct type *compatible_types(struct type *left, struct type *right)
3990 struct type *result;
3991 unsigned int type, qual_type;
3992 /* Error if the basic types do not match */
3993 if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
3996 type = left->type & TYPE_MASK;
3997 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
3999 /* if the basic types match and it is an arithmetic type we are done */
4000 if (TYPE_ARITHMETIC(type)) {
4001 result = new_type(qual_type, 0, 0);
4003 /* If it is a pointer type recurse and keep testing */
4004 else if (type == TYPE_POINTER) {
4005 result = compatible_types(left->left, right->left);
4007 result = new_type(qual_type, result, 0);
4010 /* test for struct/union equality */
4011 else if (type == TYPE_STRUCT) {
4012 if (left->type_ident == right->type_ident) {
4016 /* Test for equivalent functions */
4017 else if (type == TYPE_FUNCTION) {
4018 struct type *lf, *rf;
4019 lf = compatible_types(left->left, right->left);
4020 rf = compatible_types(left->right, right->right);
4022 result = new_type(qual_type, lf, rf);
4025 /* We only see TYPE_PRODUCT as part of function equivalence matching */
4026 else if (type == TYPE_PRODUCT) {
4027 struct type *lf, *rf;
4028 lf = compatible_types(left->left, right->left);
4029 rf = compatible_types(left->right, right->right);
4031 result = new_type(qual_type, lf, rf);
4035 /* Nothing else is compatible */
4040 static struct type *compatible_ptrs(struct type *left, struct type *right)
4042 struct type *result;
4043 if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4044 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4047 result = compatible_types(left->left, right->left);
4049 unsigned int qual_type;
4050 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4051 result = new_type(qual_type, result, 0);
4056 static struct triple *integral_promotion(
4057 struct compile_state *state, struct triple *def)
4061 /* As all operations are carried out in registers
4062 * the values are converted on load I just convert
4063 * logical type of the operand.
4065 if (TYPE_INTEGER(type->type)) {
4066 unsigned int int_type;
4067 int_type = type->type & ~TYPE_MASK;
4068 int_type |= do_integral_promotion(type->type);
4069 if (int_type != type->type) {
4070 def->type = new_type(int_type, 0, 0);
4077 static void arithmetic(struct compile_state *state, struct triple *def)
4079 if (!TYPE_ARITHMETIC(def->type->type)) {
4080 error(state, 0, "arithmetic type expexted");
4084 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4086 if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4087 error(state, def, "pointer or arithmetic type expected");
4091 static int is_integral(struct triple *ins)
4093 return TYPE_INTEGER(ins->type->type);
4096 static void integral(struct compile_state *state, struct triple *def)
4098 if (!is_integral(def)) {
4099 error(state, 0, "integral type expected");
4104 static void bool(struct compile_state *state, struct triple *def)
4106 if (!TYPE_ARITHMETIC(def->type->type) &&
4107 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4108 error(state, 0, "arithmetic or pointer type expected");
4112 static int is_signed(struct type *type)
4114 return !!TYPE_SIGNED(type->type);
4117 /* Is this value located in a register otherwise it must be in memory */
4118 static int is_in_reg(struct compile_state *state, struct triple *def)
4121 if (def->op == OP_ADECL) {
4124 else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4127 else if (def->op == OP_VAL_VEC) {
4128 in_reg = is_in_reg(state, RHS(def, 0));
4130 else if (def->op == OP_DOT) {
4131 in_reg = is_in_reg(state, RHS(def, 0));
4134 internal_error(state, 0, "unknown expr storage location");
4140 /* Is this a stable variable location otherwise it must be a temporary */
4141 static int is_stable(struct compile_state *state, struct triple *def)
4148 if ((def->op == OP_ADECL) ||
4149 (def->op == OP_SDECL) ||
4150 (def->op == OP_DEREF) ||
4151 (def->op == OP_BLOBCONST)) {
4154 else if (def->op == OP_DOT) {
4155 ret = is_stable(state, RHS(def, 0));
4157 else if (def->op == OP_VAL_VEC) {
4158 struct triple **vector;
4161 vector = &RHS(def, 0);
4162 for(i = 0; i < def->type->elements; i++) {
4163 if (!is_stable(state, vector[i])) {
4172 static int is_lvalue(struct compile_state *state, struct triple *def)
4179 if (!is_stable(state, def)) {
4182 if (def->type->type & QUAL_CONST) {
4185 else if (def->op == OP_DOT) {
4186 ret = is_lvalue(state, RHS(def, 0));
4191 static void lvalue(struct compile_state *state, struct triple *def)
4194 internal_error(state, def, "nothing where lvalue expected?");
4196 if (!is_lvalue(state, def)) {
4197 error(state, def, "lvalue expected");
4201 static int is_pointer(struct triple *def)
4203 return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4206 static void pointer(struct compile_state *state, struct triple *def)
4208 if (!is_pointer(def)) {
4209 error(state, def, "pointer expected");
4213 static struct triple *int_const(
4214 struct compile_state *state, struct type *type, ulong_t value)
4216 struct triple *result;
4217 switch(type->type & TYPE_MASK) {
4219 case TYPE_INT: case TYPE_UINT:
4220 case TYPE_LONG: case TYPE_ULONG:
4223 internal_error(state, 0, "constant for unkown type");
4225 result = triple(state, OP_INTCONST, type, 0, 0);
4226 result->u.cval = value;
4231 static struct triple *do_mk_addr_expr(struct compile_state *state,
4232 struct triple *expr, struct type *type, ulong_t offset)
4234 struct triple *result;
4235 lvalue(state, expr);
4238 if (expr->op == OP_ADECL) {
4239 error(state, expr, "address of auto variables not supported");
4241 else if (expr->op == OP_SDECL) {
4242 result = triple(state, OP_ADDRCONST, type, 0, 0);
4243 MISC(result, 0) = expr;
4244 result->u.cval = offset;
4246 else if (expr->op == OP_DEREF) {
4247 result = triple(state, OP_ADD, type,
4249 int_const(state, &ulong_type, offset));
4254 static struct triple *mk_addr_expr(
4255 struct compile_state *state, struct triple *expr, ulong_t offset)
4260 TYPE_POINTER | (expr->type->type & QUAL_MASK),
4263 return do_mk_addr_expr(state, expr, type, offset);
4266 static struct triple *mk_deref_expr(
4267 struct compile_state *state, struct triple *expr)
4269 struct type *base_type;
4270 pointer(state, expr);
4271 base_type = expr->type->left;
4272 if (!TYPE_PTR(base_type->type) && !TYPE_ARITHMETIC(base_type->type)) {
4274 "Only pointer and arithmetic values can be dereferenced");
4276 return triple(state, OP_DEREF, base_type, expr, 0);
4279 static struct triple *deref_field(
4280 struct compile_state *state, struct triple *expr, struct hash_entry *field)
4282 struct triple *result;
4283 struct type *type, *member;
4285 internal_error(state, 0, "No field passed to deref_field");
4289 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4290 error(state, 0, "request for member %s in something not a struct or union",
4293 member = type->left;
4294 while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4295 if (member->left->field_ident == field) {
4296 member = member->left;
4299 member = member->right;
4301 if (member->field_ident != field) {
4302 error(state, 0, "%s is not a member", field->name);
4304 if ((type->type & STOR_MASK) == STOR_PERM) {
4305 /* Do the pointer arithmetic to get a deref the field */
4307 offset = field_offset(state, type, field);
4308 result = do_mk_addr_expr(state, expr, member, offset);
4309 result = mk_deref_expr(state, result);
4312 /* Find the variable for the field I want. */
4313 result = triple(state, OP_DOT,
4314 field_type(state, type, field), expr, 0);
4315 result->u.field = field;
4320 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4326 if (!is_stable(state, def)) {
4329 /* Tranform an array to a pointer to the first element */
4330 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4331 if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4333 struct triple *result;
4335 TYPE_POINTER | (def->type->type & QUAL_MASK),
4336 def->type->left, 0);
4337 result = triple(state, OP_ADDRCONST, type, 0, 0);
4338 MISC(result, 0) = def;
4341 if (is_in_reg(state, def)) {
4346 return triple(state, op, def->type, def, 0);
4349 static void write_compatible(struct compile_state *state,
4350 struct type *dest, struct type *rval)
4353 /* Both operands have arithmetic type */
4354 if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4357 /* One operand is a pointer and the other is a pointer to void */
4358 else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4359 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4360 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4361 ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4364 /* If both types are the same without qualifiers we are good */
4365 else if (equiv_ptrs(dest, rval)) {
4368 /* test for struct/union equality */
4369 else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4370 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4371 (dest->type_ident == rval->type_ident)) {
4375 error(state, 0, "Incompatible types in assignment");
4379 static struct triple *write_expr(
4380 struct compile_state *state, struct triple *dest, struct triple *rval)
4387 internal_error(state, 0, "missing rval");
4390 if (rval->op == OP_LIST) {
4391 internal_error(state, 0, "expression of type OP_LIST?");
4393 if (!is_lvalue(state, dest)) {
4394 internal_error(state, 0, "writing to a non lvalue?");
4397 write_compatible(state, dest->type, rval->type);
4399 /* Now figure out which assignment operator to use */
4401 if (is_in_reg(state, dest)) {
4406 def = triple(state, op, dest->type, dest, rval);
4410 static struct triple *init_expr(
4411 struct compile_state *state, struct triple *dest, struct triple *rval)
4417 internal_error(state, 0, "missing rval");
4419 if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4420 rval = read_expr(state, rval);
4421 def = write_expr(state, dest, rval);
4424 /* Fill in the array size if necessary */
4425 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4426 ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4427 if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4428 dest->type->elements = rval->type->elements;
4431 if (!equiv_types(dest->type, rval->type)) {
4432 error(state, 0, "Incompatible types in inializer");
4434 MISC(dest, 0) = rval;
4435 insert_triple(state, dest, rval);
4436 rval->id |= TRIPLE_FLAG_FLATTENED;
4437 use_triple(MISC(dest, 0), dest);
4442 struct type *arithmetic_result(
4443 struct compile_state *state, struct triple *left, struct triple *right)
4446 /* Sanity checks to ensure I am working with arithmetic types */
4447 arithmetic(state, left);
4448 arithmetic(state, right);
4450 do_arithmetic_conversion(
4452 right->type->type), 0, 0);
4456 struct type *ptr_arithmetic_result(
4457 struct compile_state *state, struct triple *left, struct triple *right)
4460 /* Sanity checks to ensure I am working with the proper types */
4461 ptr_arithmetic(state, left);
4462 arithmetic(state, right);
4463 if (TYPE_ARITHMETIC(left->type->type) &&
4464 TYPE_ARITHMETIC(right->type->type)) {
4465 type = arithmetic_result(state, left, right);
4467 else if (TYPE_PTR(left->type->type)) {
4471 internal_error(state, 0, "huh?");
4478 /* boolean helper function */
4480 static struct triple *ltrue_expr(struct compile_state *state,
4481 struct triple *expr)
4484 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
4485 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
4486 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4487 /* If the expression is already boolean do nothing */
4490 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4496 static struct triple *lfalse_expr(struct compile_state *state,
4497 struct triple *expr)
4499 return triple(state, OP_LFALSE, &int_type, expr, 0);
4502 static struct triple *cond_expr(
4503 struct compile_state *state,
4504 struct triple *test, struct triple *left, struct triple *right)
4507 struct type *result_type;
4508 unsigned int left_type, right_type;
4510 left_type = left->type->type;
4511 right_type = right->type->type;
4513 /* Both operands have arithmetic type */
4514 if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4515 result_type = arithmetic_result(state, left, right);
4517 /* Both operands have void type */
4518 else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4519 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4520 result_type = &void_type;
4522 /* pointers to the same type... */
4523 else if ((result_type = compatible_ptrs(left->type, right->type))) {
4526 /* Both operands are pointers and left is a pointer to void */
4527 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4528 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4529 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4530 result_type = right->type;
4532 /* Both operands are pointers and right is a pointer to void */
4533 else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4534 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4535 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4536 result_type = left->type;
4539 error(state, 0, "Incompatible types in conditional expression");
4541 /* Cleanup and invert the test */
4542 test = lfalse_expr(state, read_expr(state, test));
4543 def = new_triple(state, OP_COND, result_type, 0, 3);
4544 def->param[0] = test;
4545 def->param[1] = left;
4546 def->param[2] = right;
4551 static int expr_depth(struct compile_state *state, struct triple *ins)
4555 if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4558 else if (ins->op == OP_DEREF) {
4559 count = expr_depth(state, RHS(ins, 0)) - 1;
4561 else if (ins->op == OP_VAL) {
4562 count = expr_depth(state, RHS(ins, 0)) - 1;
4564 else if (ins->op == OP_COMMA) {
4566 ldepth = expr_depth(state, RHS(ins, 0));
4567 rdepth = expr_depth(state, RHS(ins, 1));
4568 count = (ldepth >= rdepth)? ldepth : rdepth;
4570 else if (ins->op == OP_CALL) {
4571 /* Don't figure the depth of a call just guess it is huge */
4575 struct triple **expr;
4576 expr = triple_rhs(state, ins, 0);
4577 for(;expr; expr = triple_rhs(state, ins, expr)) {
4580 depth = expr_depth(state, *expr);
4581 if (depth > count) {
4590 static struct triple *flatten(
4591 struct compile_state *state, struct triple *first, struct triple *ptr);
4593 static struct triple *flatten_generic(
4594 struct compile_state *state, struct triple *first, struct triple *ptr)
4598 struct triple **ins;
4601 /* Only operations with just a rhs should come here */
4602 rhs = TRIPLE_RHS(ptr->sizes);
4603 lhs = TRIPLE_LHS(ptr->sizes);
4604 if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4605 internal_error(state, ptr, "unexpected args for: %d %s",
4606 ptr->op, tops(ptr->op));
4608 /* Find the depth of the rhs elements */
4609 for(i = 0; i < rhs; i++) {
4610 vector[i].ins = &RHS(ptr, i);
4611 vector[i].depth = expr_depth(state, *vector[i].ins);
4613 /* Selection sort the rhs */
4614 for(i = 0; i < rhs; i++) {
4616 for(j = i + 1; j < rhs; j++ ) {
4617 if (vector[j].depth > vector[max].depth) {
4622 struct rhs_vector tmp;
4624 vector[i] = vector[max];
4628 /* Now flatten the rhs elements */
4629 for(i = 0; i < rhs; i++) {
4630 *vector[i].ins = flatten(state, first, *vector[i].ins);
4631 use_triple(*vector[i].ins, ptr);
4634 /* Now flatten the lhs elements */
4635 for(i = 0; i < lhs; i++) {
4636 struct triple **ins = &LHS(ptr, i);
4637 *ins = flatten(state, first, *ins);
4638 use_triple(*ins, ptr);
4643 static struct triple *flatten_land(
4644 struct compile_state *state, struct triple *first, struct triple *ptr)
4646 struct triple *left, *right;
4647 struct triple *val, *test, *jmp, *label1, *end;
4649 /* Find the triples */
4651 right = RHS(ptr, 1);
4653 /* Generate the needed triples */
4656 /* Thread the triples together */
4657 val = flatten(state, first, variable(state, ptr->type));
4658 left = flatten(state, first, write_expr(state, val, left));
4659 test = flatten(state, first,
4660 lfalse_expr(state, read_expr(state, val)));
4661 jmp = flatten(state, first, branch(state, end, test));
4662 label1 = flatten(state, first, label(state));
4663 right = flatten(state, first, write_expr(state, val, right));
4664 TARG(jmp, 0) = flatten(state, first, end);
4666 /* Now give the caller something to chew on */
4667 return read_expr(state, val);
4670 static struct triple *flatten_lor(
4671 struct compile_state *state, struct triple *first, struct triple *ptr)
4673 struct triple *left, *right;
4674 struct triple *val, *jmp, *label1, *end;
4676 /* Find the triples */
4678 right = RHS(ptr, 1);
4680 /* Generate the needed triples */
4683 /* Thread the triples together */
4684 val = flatten(state, first, variable(state, ptr->type));
4685 left = flatten(state, first, write_expr(state, val, left));
4686 jmp = flatten(state, first, branch(state, end, left));
4687 label1 = flatten(state, first, label(state));
4688 right = flatten(state, first, write_expr(state, val, right));
4689 TARG(jmp, 0) = flatten(state, first, end);
4692 /* Now give the caller something to chew on */
4693 return read_expr(state, val);
4696 static struct triple *flatten_cond(
4697 struct compile_state *state, struct triple *first, struct triple *ptr)
4699 struct triple *test, *left, *right;
4700 struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4702 /* Find the triples */
4705 right = RHS(ptr, 2);
4707 /* Generate the needed triples */
4709 middle = label(state);
4711 /* Thread the triples together */
4712 val = flatten(state, first, variable(state, ptr->type));
4713 test = flatten(state, first, test);
4714 jmp1 = flatten(state, first, branch(state, middle, test));
4715 label1 = flatten(state, first, label(state));
4716 left = flatten(state, first, left);
4717 mv1 = flatten(state, first, write_expr(state, val, left));
4718 jmp2 = flatten(state, first, branch(state, end, 0));
4719 TARG(jmp1, 0) = flatten(state, first, middle);
4720 right = flatten(state, first, right);
4721 mv2 = flatten(state, first, write_expr(state, val, right));
4722 TARG(jmp2, 0) = flatten(state, first, end);
4724 /* Now give the caller something to chew on */
4725 return read_expr(state, val);
4728 struct triple *copy_func(struct compile_state *state, struct triple *ofunc)
4730 struct triple *nfunc;
4731 struct triple *nfirst, *ofirst;
4732 struct triple *new, *old;
4735 fprintf(stdout, "\n");
4736 loc(stdout, state, 0);
4737 fprintf(stdout, "\n__________ copy_func _________\n");
4738 print_triple(state, ofunc);
4739 fprintf(stdout, "__________ copy_func _________ done\n\n");
4742 /* Make a new copy of the old function */
4743 nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
4745 ofirst = old = RHS(ofunc, 0);
4748 int old_lhs, old_rhs;
4749 old_lhs = TRIPLE_LHS(old->sizes);
4750 old_rhs = TRIPLE_RHS(old->sizes);
4751 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
4752 old->filename, old->line, old->col);
4753 if (!triple_stores_block(state, new)) {
4754 memcpy(&new->u, &old->u, sizeof(new->u));
4757 RHS(nfunc, 0) = nfirst = new;
4760 insert_triple(state, nfirst, new);
4762 new->id |= TRIPLE_FLAG_FLATTENED;
4764 /* During the copy remember new as user of old */
4765 use_triple(old, new);
4767 /* Populate the return type if present */
4768 if (old == MISC(ofunc, 0)) {
4769 MISC(nfunc, 0) = new;
4772 } while(old != ofirst);
4774 /* Make a second pass to fix up any unresolved references */
4778 struct triple **oexpr, **nexpr;
4780 /* Lookup where the copy is, to join pointers */
4781 count = TRIPLE_SIZE(old->sizes);
4782 for(i = 0; i < count; i++) {
4783 oexpr = &old->param[i];
4784 nexpr = &new->param[i];
4785 if (!*nexpr && *oexpr && (*oexpr)->use) {
4786 *nexpr = (*oexpr)->use->member;
4787 if (*nexpr == old) {
4788 internal_error(state, 0, "new == old?");
4790 use_triple(*nexpr, new);
4792 if (!*nexpr && *oexpr) {
4793 internal_error(state, 0, "Could not copy %d\n", i);
4798 } while((old != ofirst) && (new != nfirst));
4800 /* Make a third pass to cleanup the extra useses */
4804 unuse_triple(old, new);
4807 } while ((old != ofirst) && (new != nfirst));
4811 static struct triple *flatten_call(
4812 struct compile_state *state, struct triple *first, struct triple *ptr)
4814 /* Inline the function call */
4816 struct triple *ofunc, *nfunc, *nfirst, *param, *result;
4817 struct triple *end, *nend;
4820 /* Find the triples */
4821 ofunc = MISC(ptr, 0);
4822 if (ofunc->op != OP_LIST) {
4823 internal_error(state, 0, "improper function");
4825 nfunc = copy_func(state, ofunc);
4826 nfirst = RHS(nfunc, 0)->next;
4827 /* Prepend the parameter reading into the new function list */
4828 ptype = nfunc->type->right;
4829 param = RHS(nfunc, 0)->next;
4830 pvals = TRIPLE_RHS(ptr->sizes);
4831 for(i = 0; i < pvals; i++) {
4835 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
4836 atype = ptype->left;
4838 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
4839 param = param->next;
4842 flatten(state, nfirst, write_expr(state, param, arg));
4843 ptype = ptype->right;
4844 param = param->next;
4847 if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
4848 result = read_expr(state, MISC(nfunc,0));
4851 fprintf(stdout, "\n");
4852 loc(stdout, state, 0);
4853 fprintf(stdout, "\n__________ flatten_call _________\n");
4854 print_triple(state, nfunc);
4855 fprintf(stdout, "__________ flatten_call _________ done\n\n");
4858 /* Get rid of the extra triples */
4859 nfirst = RHS(nfunc, 0)->next;
4860 free_triple(state, RHS(nfunc, 0));
4862 free_triple(state, nfunc);
4864 /* Append the new function list onto the return list */
4866 nend = nfirst->prev;
4875 static struct triple *flatten(
4876 struct compile_state *state, struct triple *first, struct triple *ptr)
4878 struct triple *orig_ptr;
4883 /* Only flatten triples once */
4884 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
4890 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4891 LHS(ptr, 0) = flatten(state, first, LHS(ptr, 0));
4892 use_triple(LHS(ptr, 0), ptr);
4893 use_triple(RHS(ptr, 0), ptr);
4896 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4900 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4901 return MISC(ptr, 0);
4904 ptr = flatten_land(state, first, ptr);
4907 ptr = flatten_lor(state, first, ptr);
4910 ptr = flatten_cond(state, first, ptr);
4913 ptr = flatten_call(state, first, ptr);
4917 RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
4918 use_triple(RHS(ptr, 0), ptr);
4921 use_triple(TARG(ptr, 0), ptr);
4922 if (TRIPLE_RHS(ptr->sizes)) {
4923 use_triple(RHS(ptr, 0), ptr);
4924 if (ptr->next != ptr) {
4925 use_triple(ptr->next, ptr);
4930 insert_triple(state, first, ptr);
4931 ptr->id |= TRIPLE_FLAG_FLATTENED;
4932 ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
4933 use_triple(MISC(ptr, 0), ptr);
4936 /* Since OP_DEREF is just a marker delete it when I flatten it */
4938 RHS(orig_ptr, 0) = 0;
4939 free_triple(state, orig_ptr);
4943 struct triple *base;
4945 base = flatten(state, first, base);
4946 if (base->op == OP_VAL_VEC) {
4947 ptr = struct_field(state, base, ptr->u.field);
4952 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4953 use_triple(MISC(ptr, 0), ptr);
4954 use_triple(ptr, MISC(ptr, 0));
4958 MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
4959 use_triple(MISC(ptr, 0), ptr);
4964 /* Flatten the easy cases we don't override */
4965 ptr = flatten_generic(state, first, ptr);
4968 } while(ptr && (ptr != orig_ptr));
4970 insert_triple(state, first, ptr);
4971 ptr->id |= TRIPLE_FLAG_FLATTENED;
4976 static void release_expr(struct compile_state *state, struct triple *expr)
4978 struct triple *head;
4979 head = label(state);
4980 flatten(state, head, expr);
4981 while(head->next != head) {
4982 release_triple(state, head->next);
4984 free_triple(state, head);
4987 static int replace_rhs_use(struct compile_state *state,
4988 struct triple *orig, struct triple *new, struct triple *use)
4990 struct triple **expr;
4993 expr = triple_rhs(state, use, 0);
4994 for(;expr; expr = triple_rhs(state, use, expr)) {
4995 if (*expr == orig) {
5001 unuse_triple(orig, use);
5002 use_triple(new, use);
5007 static int replace_lhs_use(struct compile_state *state,
5008 struct triple *orig, struct triple *new, struct triple *use)
5010 struct triple **expr;
5013 expr = triple_lhs(state, use, 0);
5014 for(;expr; expr = triple_lhs(state, use, expr)) {
5015 if (*expr == orig) {
5021 unuse_triple(orig, use);
5022 use_triple(new, use);
5027 static void propogate_use(struct compile_state *state,
5028 struct triple *orig, struct triple *new)
5030 struct triple_set *user, *next;
5031 for(user = orig->use; user; user = next) {
5037 found |= replace_rhs_use(state, orig, new, use);
5038 found |= replace_lhs_use(state, orig, new, use);
5040 internal_error(state, use, "use without use");
5044 internal_error(state, orig, "used after propogate_use");
5050 * ===========================
5053 static struct triple *mk_add_expr(
5054 struct compile_state *state, struct triple *left, struct triple *right)
5056 struct type *result_type;
5057 /* Put pointer operands on the left */
5058 if (is_pointer(right)) {
5064 left = read_expr(state, left);
5065 right = read_expr(state, right);
5066 result_type = ptr_arithmetic_result(state, left, right);
5067 if (is_pointer(left)) {
5068 right = triple(state,
5069 is_signed(right->type)? OP_SMUL : OP_UMUL,
5072 int_const(state, &ulong_type,
5073 size_of(state, left->type->left)));
5075 return triple(state, OP_ADD, result_type, left, right);
5078 static struct triple *mk_sub_expr(
5079 struct compile_state *state, struct triple *left, struct triple *right)
5081 struct type *result_type;
5082 result_type = ptr_arithmetic_result(state, left, right);
5083 left = read_expr(state, left);
5084 right = read_expr(state, right);
5085 if (is_pointer(left)) {
5086 right = triple(state,
5087 is_signed(right->type)? OP_SMUL : OP_UMUL,
5090 int_const(state, &ulong_type,
5091 size_of(state, left->type->left)));
5093 return triple(state, OP_SUB, result_type, left, right);
5096 static struct triple *mk_pre_inc_expr(
5097 struct compile_state *state, struct triple *def)
5101 val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5102 return triple(state, OP_VAL, def->type,
5103 write_expr(state, def, val),
5107 static struct triple *mk_pre_dec_expr(
5108 struct compile_state *state, struct triple *def)
5112 val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5113 return triple(state, OP_VAL, def->type,
5114 write_expr(state, def, val),
5118 static struct triple *mk_post_inc_expr(
5119 struct compile_state *state, struct triple *def)
5123 val = read_expr(state, def);
5124 return triple(state, OP_VAL, def->type,
5125 write_expr(state, def,
5126 mk_add_expr(state, val, int_const(state, &int_type, 1)))
5130 static struct triple *mk_post_dec_expr(
5131 struct compile_state *state, struct triple *def)
5135 val = read_expr(state, def);
5136 return triple(state, OP_VAL, def->type,
5137 write_expr(state, def,
5138 mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5142 static struct triple *mk_subscript_expr(
5143 struct compile_state *state, struct triple *left, struct triple *right)
5145 left = read_expr(state, left);
5146 right = read_expr(state, right);
5147 if (!is_pointer(left) && !is_pointer(right)) {
5148 error(state, left, "subscripted value is not a pointer");
5150 return mk_deref_expr(state, mk_add_expr(state, left, right));
5154 * Compile time evaluation
5155 * ===========================
5157 static int is_const(struct triple *ins)
5159 return IS_CONST_OP(ins->op);
5162 static int constants_equal(struct compile_state *state,
5163 struct triple *left, struct triple *right)
5166 if (!is_const(left) || !is_const(right)) {
5169 else if (left->op != right->op) {
5172 else if (!equiv_types(left->type, right->type)) {
5179 if (left->u.cval == right->u.cval) {
5185 size_t lsize, rsize;
5186 lsize = size_of(state, left->type);
5187 rsize = size_of(state, right->type);
5188 if (lsize != rsize) {
5191 if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5197 if ((MISC(left, 0) == MISC(right, 0)) &&
5198 (left->u.cval == right->u.cval)) {
5203 internal_error(state, left, "uknown constant type");
5210 static int is_zero(struct triple *ins)
5212 return is_const(ins) && (ins->u.cval == 0);
5215 static int is_one(struct triple *ins)
5217 return is_const(ins) && (ins->u.cval == 1);
5220 static long_t bsr(ulong_t value)
5223 for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5234 static long_t bsf(ulong_t value)
5237 for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5248 static long_t log2(ulong_t value)
5253 static long_t tlog2(struct triple *ins)
5255 return log2(ins->u.cval);
5258 static int is_pow2(struct triple *ins)
5260 ulong_t value, mask;
5262 if (!is_const(ins)) {
5265 value = ins->u.cval;
5272 return ((value & mask) == value);
5275 static ulong_t read_const(struct compile_state *state,
5276 struct triple *ins, struct triple **expr)
5280 switch(rhs->type->type &TYPE_MASK) {
5292 internal_error(state, rhs, "bad type to read_const\n");
5298 static long_t read_sconst(struct triple *ins, struct triple **expr)
5302 return (long_t)(rhs->u.cval);
5305 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5307 struct triple **expr;
5308 expr = triple_rhs(state, ins, 0);
5309 for(;expr;expr = triple_rhs(state, ins, expr)) {
5311 unuse_triple(*expr, ins);
5317 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5319 struct triple **expr;
5320 expr = triple_lhs(state, ins, 0);
5321 for(;expr;expr = triple_lhs(state, ins, expr)) {
5322 unuse_triple(*expr, ins);
5327 static void check_lhs(struct compile_state *state, struct triple *ins)
5329 struct triple **expr;
5330 expr = triple_lhs(state, ins, 0);
5331 for(;expr;expr = triple_lhs(state, ins, expr)) {
5332 internal_error(state, ins, "unexpected lhs");
5336 static void check_targ(struct compile_state *state, struct triple *ins)
5338 struct triple **expr;
5339 expr = triple_targ(state, ins, 0);
5340 for(;expr;expr = triple_targ(state, ins, expr)) {
5341 internal_error(state, ins, "unexpected targ");
5345 static void wipe_ins(struct compile_state *state, struct triple *ins)
5347 /* Becareful which instructions you replace the wiped
5348 * instruction with, as there are not enough slots
5349 * in all instructions to hold all others.
5351 check_targ(state, ins);
5352 unuse_rhs(state, ins);
5353 unuse_lhs(state, ins);
5356 static void mkcopy(struct compile_state *state,
5357 struct triple *ins, struct triple *rhs)
5359 wipe_ins(state, ins);
5361 ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5363 use_triple(RHS(ins, 0), ins);
5366 static void mkconst(struct compile_state *state,
5367 struct triple *ins, ulong_t value)
5369 if (!is_integral(ins) && !is_pointer(ins)) {
5370 internal_error(state, ins, "unknown type to make constant\n");
5372 wipe_ins(state, ins);
5373 ins->op = OP_INTCONST;
5374 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5375 ins->u.cval = value;
5378 static void mkaddr_const(struct compile_state *state,
5379 struct triple *ins, struct triple *sdecl, ulong_t value)
5381 wipe_ins(state, ins);
5382 ins->op = OP_ADDRCONST;
5383 ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5384 MISC(ins, 0) = sdecl;
5385 ins->u.cval = value;
5386 use_triple(sdecl, ins);
5389 /* Transform multicomponent variables into simple register variables */
5390 static void flatten_structures(struct compile_state *state)
5392 struct triple *ins, *first;
5393 first = RHS(state->main_function, 0);
5395 /* Pass one expand structure values into valvecs.
5399 struct triple *next;
5401 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5402 if (ins->op == OP_VAL_VEC) {
5405 else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5406 struct triple *def, **vector;
5413 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5414 ins->filename, ins->line, ins->col);
5416 vector = &RHS(next, 0);
5417 tptr = next->type->left;
5418 for(i = 0; i < next->type->elements; i++) {
5419 struct triple *sfield;
5422 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5423 mtype = mtype->left;
5425 sfield = deref_field(state, def, mtype->field_ident);
5428 state, op, mtype, sfield, 0);
5429 vector[i]->filename = next->filename;
5430 vector[i]->line = next->line;
5431 vector[i]->col = next->col;
5434 propogate_use(state, ins, next);
5435 flatten(state, ins, next);
5436 free_triple(state, ins);
5438 else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5439 struct triple *src, *dst, **vector;
5447 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5448 ins->filename, ins->line, ins->col);
5450 vector = &RHS(next, 0);
5451 tptr = next->type->left;
5452 for(i = 0; i < ins->type->elements; i++) {
5453 struct triple *dfield, *sfield;
5456 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5457 mtype = mtype->left;
5459 sfield = deref_field(state, src, mtype->field_ident);
5460 dfield = deref_field(state, dst, mtype->field_ident);
5462 state, op, mtype, dfield, sfield);
5463 vector[i]->filename = next->filename;
5464 vector[i]->line = next->line;
5465 vector[i]->col = next->col;
5468 propogate_use(state, ins, next);
5469 flatten(state, ins, next);
5470 free_triple(state, ins);
5474 } while(ins != first);
5475 /* Pass two flatten the valvecs.
5479 struct triple *next;
5481 if (ins->op == OP_VAL_VEC) {
5482 release_triple(state, ins);
5485 } while(ins != first);
5486 /* Pass three verify the state and set ->id to 0.
5490 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5491 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5492 internal_error(state, 0, "STRUCT_TYPE remains?");
5494 if (ins->op == OP_DOT) {
5495 internal_error(state, 0, "OP_DOT remains?");
5497 if (ins->op == OP_VAL_VEC) {
5498 internal_error(state, 0, "OP_VAL_VEC remains?");
5501 } while(ins != first);
5504 /* For those operations that cannot be simplified */
5505 static void simplify_noop(struct compile_state *state, struct triple *ins)
5510 static void simplify_smul(struct compile_state *state, struct triple *ins)
5512 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5515 RHS(ins, 0) = RHS(ins, 1);
5518 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5520 left = read_sconst(ins, &RHS(ins, 0));
5521 right = read_sconst(ins, &RHS(ins, 1));
5522 mkconst(state, ins, left * right);
5524 else if (is_zero(RHS(ins, 1))) {
5525 mkconst(state, ins, 0);
5527 else if (is_one(RHS(ins, 1))) {
5528 mkcopy(state, ins, RHS(ins, 0));
5530 else if (is_pow2(RHS(ins, 1))) {
5532 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5534 insert_triple(state, ins, val);
5535 unuse_triple(RHS(ins, 1), ins);
5536 use_triple(val, ins);
5541 static void simplify_umul(struct compile_state *state, struct triple *ins)
5543 if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5546 RHS(ins, 0) = RHS(ins, 1);
5549 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5550 ulong_t left, right;
5551 left = read_const(state, ins, &RHS(ins, 0));
5552 right = read_const(state, ins, &RHS(ins, 1));
5553 mkconst(state, ins, left * right);
5555 else if (is_zero(RHS(ins, 1))) {
5556 mkconst(state, ins, 0);
5558 else if (is_one(RHS(ins, 1))) {
5559 mkcopy(state, ins, RHS(ins, 0));
5561 else if (is_pow2(RHS(ins, 1))) {
5563 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5565 insert_triple(state, ins, val);
5566 unuse_triple(RHS(ins, 1), ins);
5567 use_triple(val, ins);
5572 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5574 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5576 left = read_sconst(ins, &RHS(ins, 0));
5577 right = read_sconst(ins, &RHS(ins, 1));
5578 mkconst(state, ins, left / right);
5580 else if (is_zero(RHS(ins, 0))) {
5581 mkconst(state, ins, 0);
5583 else if (is_zero(RHS(ins, 1))) {
5584 error(state, ins, "division by zero");
5586 else if (is_one(RHS(ins, 1))) {
5587 mkcopy(state, ins, RHS(ins, 0));
5589 else if (is_pow2(RHS(ins, 1))) {
5591 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5593 insert_triple(state, ins, val);
5594 unuse_triple(RHS(ins, 1), ins);
5595 use_triple(val, ins);
5600 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5602 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5603 ulong_t left, right;
5604 left = read_const(state, ins, &RHS(ins, 0));
5605 right = read_const(state, ins, &RHS(ins, 1));
5606 mkconst(state, ins, left / right);
5608 else if (is_zero(RHS(ins, 0))) {
5609 mkconst(state, ins, 0);
5611 else if (is_zero(RHS(ins, 1))) {
5612 error(state, ins, "division by zero");
5614 else if (is_one(RHS(ins, 1))) {
5615 mkcopy(state, ins, RHS(ins, 0));
5617 else if (is_pow2(RHS(ins, 1))) {
5619 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5621 insert_triple(state, ins, val);
5622 unuse_triple(RHS(ins, 1), ins);
5623 use_triple(val, ins);
5628 static void simplify_smod(struct compile_state *state, struct triple *ins)
5630 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5632 left = read_const(state, ins, &RHS(ins, 0));
5633 right = read_const(state, ins, &RHS(ins, 1));
5634 mkconst(state, ins, left % right);
5636 else if (is_zero(RHS(ins, 0))) {
5637 mkconst(state, ins, 0);
5639 else if (is_zero(RHS(ins, 1))) {
5640 error(state, ins, "division by zero");
5642 else if (is_one(RHS(ins, 1))) {
5643 mkconst(state, ins, 0);
5645 else if (is_pow2(RHS(ins, 1))) {
5647 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5649 insert_triple(state, ins, val);
5650 unuse_triple(RHS(ins, 1), ins);
5651 use_triple(val, ins);
5655 static void simplify_umod(struct compile_state *state, struct triple *ins)
5657 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5658 ulong_t left, right;
5659 left = read_const(state, ins, &RHS(ins, 0));
5660 right = read_const(state, ins, &RHS(ins, 1));
5661 mkconst(state, ins, left % right);
5663 else if (is_zero(RHS(ins, 0))) {
5664 mkconst(state, ins, 0);
5666 else if (is_zero(RHS(ins, 1))) {
5667 error(state, ins, "division by zero");
5669 else if (is_one(RHS(ins, 1))) {
5670 mkconst(state, ins, 0);
5672 else if (is_pow2(RHS(ins, 1))) {
5674 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5676 insert_triple(state, ins, val);
5677 unuse_triple(RHS(ins, 1), ins);
5678 use_triple(val, ins);
5683 static void simplify_add(struct compile_state *state, struct triple *ins)
5685 /* start with the pointer on the left */
5686 if (is_pointer(RHS(ins, 1))) {
5689 RHS(ins, 0) = RHS(ins, 1);
5692 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5693 if (!is_pointer(RHS(ins, 0))) {
5694 ulong_t left, right;
5695 left = read_const(state, ins, &RHS(ins, 0));
5696 right = read_const(state, ins, &RHS(ins, 1));
5697 mkconst(state, ins, left + right);
5699 else /* op == OP_ADDRCONST */ {
5700 struct triple *sdecl;
5701 ulong_t left, right;
5702 sdecl = MISC(RHS(ins, 0), 0);
5703 left = RHS(ins, 0)->u.cval;
5704 right = RHS(ins, 1)->u.cval;
5705 mkaddr_const(state, ins, sdecl, left + right);
5708 else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5711 RHS(ins, 1) = RHS(ins, 0);
5716 static void simplify_sub(struct compile_state *state, struct triple *ins)
5718 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5719 if (!is_pointer(RHS(ins, 0))) {
5720 ulong_t left, right;
5721 left = read_const(state, ins, &RHS(ins, 0));
5722 right = read_const(state, ins, &RHS(ins, 1));
5723 mkconst(state, ins, left - right);
5725 else /* op == OP_ADDRCONST */ {
5726 struct triple *sdecl;
5727 ulong_t left, right;
5728 sdecl = MISC(RHS(ins, 0), 0);
5729 left = RHS(ins, 0)->u.cval;
5730 right = RHS(ins, 1)->u.cval;
5731 mkaddr_const(state, ins, sdecl, left - right);
5736 static void simplify_sl(struct compile_state *state, struct triple *ins)
5738 if (is_const(RHS(ins, 1))) {
5740 right = read_const(state, ins, &RHS(ins, 1));
5741 if (right >= (size_of(state, ins->type)*8)) {
5742 warning(state, ins, "left shift count >= width of type");
5745 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5746 ulong_t left, right;
5747 left = read_const(state, ins, &RHS(ins, 0));
5748 right = read_const(state, ins, &RHS(ins, 1));
5749 mkconst(state, ins, left << right);
5753 static void simplify_usr(struct compile_state *state, struct triple *ins)
5755 if (is_const(RHS(ins, 1))) {
5757 right = read_const(state, ins, &RHS(ins, 1));
5758 if (right >= (size_of(state, ins->type)*8)) {
5759 warning(state, ins, "right shift count >= width of type");
5762 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5763 ulong_t left, right;
5764 left = read_const(state, ins, &RHS(ins, 0));
5765 right = read_const(state, ins, &RHS(ins, 1));
5766 mkconst(state, ins, left >> right);
5770 static void simplify_ssr(struct compile_state *state, struct triple *ins)
5772 if (is_const(RHS(ins, 1))) {
5774 right = read_const(state, ins, &RHS(ins, 1));
5775 if (right >= (size_of(state, ins->type)*8)) {
5776 warning(state, ins, "right shift count >= width of type");
5779 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5781 left = read_sconst(ins, &RHS(ins, 0));
5782 right = read_sconst(ins, &RHS(ins, 1));
5783 mkconst(state, ins, left >> right);
5787 static void simplify_and(struct compile_state *state, struct triple *ins)
5789 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5790 ulong_t left, right;
5791 left = read_const(state, ins, &RHS(ins, 0));
5792 right = read_const(state, ins, &RHS(ins, 1));
5793 mkconst(state, ins, left & right);
5797 static void simplify_or(struct compile_state *state, struct triple *ins)
5799 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5800 ulong_t left, right;
5801 left = read_const(state, ins, &RHS(ins, 0));
5802 right = read_const(state, ins, &RHS(ins, 1));
5803 mkconst(state, ins, left | right);
5807 static void simplify_xor(struct compile_state *state, struct triple *ins)
5809 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5810 ulong_t left, right;
5811 left = read_const(state, ins, &RHS(ins, 0));
5812 right = read_const(state, ins, &RHS(ins, 1));
5813 mkconst(state, ins, left ^ right);
5817 static void simplify_pos(struct compile_state *state, struct triple *ins)
5819 if (is_const(RHS(ins, 0))) {
5820 mkconst(state, ins, RHS(ins, 0)->u.cval);
5823 mkcopy(state, ins, RHS(ins, 0));
5827 static void simplify_neg(struct compile_state *state, struct triple *ins)
5829 if (is_const(RHS(ins, 0))) {
5831 left = read_const(state, ins, &RHS(ins, 0));
5832 mkconst(state, ins, -left);
5834 else if (RHS(ins, 0)->op == OP_NEG) {
5835 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
5839 static void simplify_invert(struct compile_state *state, struct triple *ins)
5841 if (is_const(RHS(ins, 0))) {
5843 left = read_const(state, ins, &RHS(ins, 0));
5844 mkconst(state, ins, ~left);
5848 static void simplify_eq(struct compile_state *state, struct triple *ins)
5850 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5851 ulong_t left, right;
5852 left = read_const(state, ins, &RHS(ins, 0));
5853 right = read_const(state, ins, &RHS(ins, 1));
5854 mkconst(state, ins, left == right);
5856 else if (RHS(ins, 0) == RHS(ins, 1)) {
5857 mkconst(state, ins, 1);
5861 static void simplify_noteq(struct compile_state *state, struct triple *ins)
5863 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5864 ulong_t left, right;
5865 left = read_const(state, ins, &RHS(ins, 0));
5866 right = read_const(state, ins, &RHS(ins, 1));
5867 mkconst(state, ins, left != right);
5869 else if (RHS(ins, 0) == RHS(ins, 1)) {
5870 mkconst(state, ins, 0);
5874 static void simplify_sless(struct compile_state *state, struct triple *ins)
5876 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5878 left = read_sconst(ins, &RHS(ins, 0));
5879 right = read_sconst(ins, &RHS(ins, 1));
5880 mkconst(state, ins, left < right);
5882 else if (RHS(ins, 0) == RHS(ins, 1)) {
5883 mkconst(state, ins, 0);
5887 static void simplify_uless(struct compile_state *state, struct triple *ins)
5889 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5890 ulong_t left, right;
5891 left = read_const(state, ins, &RHS(ins, 0));
5892 right = read_const(state, ins, &RHS(ins, 1));
5893 mkconst(state, ins, left < right);
5895 else if (is_zero(RHS(ins, 0))) {
5896 mkconst(state, ins, 1);
5898 else if (RHS(ins, 0) == RHS(ins, 1)) {
5899 mkconst(state, ins, 0);
5903 static void simplify_smore(struct compile_state *state, struct triple *ins)
5905 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5907 left = read_sconst(ins, &RHS(ins, 0));
5908 right = read_sconst(ins, &RHS(ins, 1));
5909 mkconst(state, ins, left > right);
5911 else if (RHS(ins, 0) == RHS(ins, 1)) {
5912 mkconst(state, ins, 0);
5916 static void simplify_umore(struct compile_state *state, struct triple *ins)
5918 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5919 ulong_t left, right;
5920 left = read_const(state, ins, &RHS(ins, 0));
5921 right = read_const(state, ins, &RHS(ins, 1));
5922 mkconst(state, ins, left > right);
5924 else if (is_zero(RHS(ins, 1))) {
5925 mkconst(state, ins, 1);
5927 else if (RHS(ins, 0) == RHS(ins, 1)) {
5928 mkconst(state, ins, 0);
5933 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
5935 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5937 left = read_sconst(ins, &RHS(ins, 0));
5938 right = read_sconst(ins, &RHS(ins, 1));
5939 mkconst(state, ins, left <= right);
5941 else if (RHS(ins, 0) == RHS(ins, 1)) {
5942 mkconst(state, ins, 1);
5946 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
5948 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5949 ulong_t left, right;
5950 left = read_const(state, ins, &RHS(ins, 0));
5951 right = read_const(state, ins, &RHS(ins, 1));
5952 mkconst(state, ins, left <= right);
5954 else if (is_zero(RHS(ins, 0))) {
5955 mkconst(state, ins, 1);
5957 else if (RHS(ins, 0) == RHS(ins, 1)) {
5958 mkconst(state, ins, 1);
5962 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
5964 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
5966 left = read_sconst(ins, &RHS(ins, 0));
5967 right = read_sconst(ins, &RHS(ins, 1));
5968 mkconst(state, ins, left >= right);
5970 else if (RHS(ins, 0) == RHS(ins, 1)) {
5971 mkconst(state, ins, 1);
5975 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
5977 if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5978 ulong_t left, right;
5979 left = read_const(state, ins, &RHS(ins, 0));
5980 right = read_const(state, ins, &RHS(ins, 1));
5981 mkconst(state, ins, left >= right);
5983 else if (is_zero(RHS(ins, 1))) {
5984 mkconst(state, ins, 1);
5986 else if (RHS(ins, 0) == RHS(ins, 1)) {
5987 mkconst(state, ins, 1);
5991 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
5993 if (is_const(RHS(ins, 0))) {
5995 left = read_const(state, ins, &RHS(ins, 0));
5996 mkconst(state, ins, left == 0);
5998 /* Otherwise if I am the only user... */
5999 else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6001 /* Invert a boolean operation */
6002 switch(RHS(ins, 0)->op) {
6003 case OP_LTRUE: RHS(ins, 0)->op = OP_LFALSE; break;
6004 case OP_LFALSE: RHS(ins, 0)->op = OP_LTRUE; break;
6005 case OP_EQ: RHS(ins, 0)->op = OP_NOTEQ; break;
6006 case OP_NOTEQ: RHS(ins, 0)->op = OP_EQ; break;
6007 case OP_SLESS: RHS(ins, 0)->op = OP_SMOREEQ; break;
6008 case OP_ULESS: RHS(ins, 0)->op = OP_UMOREEQ; break;
6009 case OP_SMORE: RHS(ins, 0)->op = OP_SLESSEQ; break;
6010 case OP_UMORE: RHS(ins, 0)->op = OP_ULESSEQ; break;
6011 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE; break;
6012 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE; break;
6013 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS; break;
6014 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS; break;
6020 mkcopy(state, ins, RHS(ins, 0));
6025 static void simplify_ltrue (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 != 0);
6032 else switch(RHS(ins, 0)->op) {
6033 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
6034 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
6035 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6036 mkcopy(state, ins, RHS(ins, 0));
6041 static void simplify_copy(struct compile_state *state, struct triple *ins)
6043 if (is_const(RHS(ins, 0))) {
6044 switch(RHS(ins, 0)->op) {
6048 left = read_const(state, ins, &RHS(ins, 0));
6049 mkconst(state, ins, left);
6054 struct triple *sdecl;
6056 sdecl = MISC(RHS(ins, 0), 0);
6057 offset = RHS(ins, 0)->u.cval;
6058 mkaddr_const(state, ins, sdecl, offset);
6062 internal_error(state, ins, "uknown constant");
6068 static void simplify_branch(struct compile_state *state, struct triple *ins)
6070 struct block *block;
6071 if (ins->op != OP_BRANCH) {
6072 internal_error(state, ins, "not branch");
6074 if (ins->use != 0) {
6075 internal_error(state, ins, "branch use");
6077 #warning "FIXME implement simplify branch."
6078 /* The challenge here with simplify branch is that I need to
6079 * make modifications to the control flow graph as well
6080 * as to the branch instruction itself.
6082 block = ins->u.block;
6084 if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6085 struct triple *targ;
6087 value = read_const(state, ins, &RHS(ins, 0));
6088 unuse_triple(RHS(ins, 0), ins);
6089 targ = TARG(ins, 0);
6090 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6092 unuse_triple(ins->next, ins);
6093 TARG(ins, 0) = targ;
6096 unuse_triple(targ, ins);
6097 TARG(ins, 0) = ins->next;
6099 #warning "FIXME handle the case of making a branch unconditional"
6101 if (TARG(ins, 0) == ins->next) {
6102 unuse_triple(ins->next, ins);
6103 if (TRIPLE_RHS(ins->sizes)) {
6104 unuse_triple(RHS(ins, 0), ins);
6105 unuse_triple(ins->next, ins);
6107 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6110 internal_error(state, ins, "noop use != 0");
6112 #warning "FIXME handle the case of killing a branch"
6116 static void simplify_phi(struct compile_state *state, struct triple *ins)
6118 struct triple **expr;
6120 expr = triple_rhs(state, ins, 0);
6121 if (!*expr || !is_const(*expr)) {
6124 value = read_const(state, ins, expr);
6125 for(;expr;expr = triple_rhs(state, ins, expr)) {
6126 if (!*expr || !is_const(*expr)) {
6129 if (value != read_const(state, ins, expr)) {
6133 mkconst(state, ins, value);
6137 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6139 if (is_const(RHS(ins, 0))) {
6141 left = read_const(state, ins, &RHS(ins, 0));
6142 mkconst(state, ins, bsf(left));
6146 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6148 if (is_const(RHS(ins, 0))) {
6150 left = read_const(state, ins, &RHS(ins, 0));
6151 mkconst(state, ins, bsr(left));
6156 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6157 static const simplify_t table_simplify[] = {
6159 #define simplify_smul simplify_noop
6160 #define simplify_umul simplify_noop
6161 #define simplify_sdiv simplify_noop
6162 #define simplify_udiv simplify_noop
6163 #define simplify_smod simplify_noop
6164 #define simplify_umod simplify_noop
6167 #define simplify_add simplify_noop
6168 #define simplify_sub simplify_noop
6171 #define simplify_sl simplify_noop
6172 #define simplify_usr simplify_noop
6173 #define simplify_ssr simplify_noop
6176 #define simplify_and simplify_noop
6177 #define simplify_xor simplify_noop
6178 #define simplify_or simplify_noop
6181 #define simplify_pos simplify_noop
6182 #define simplify_neg simplify_noop
6183 #define simplify_invert simplify_noop
6187 #define simplify_eq simplify_noop
6188 #define simplify_noteq simplify_noop
6191 #define simplify_sless simplify_noop
6192 #define simplify_uless simplify_noop
6193 #define simplify_smore simplify_noop
6194 #define simplify_umore simplify_noop
6197 #define simplify_slesseq simplify_noop
6198 #define simplify_ulesseq simplify_noop
6199 #define simplify_smoreeq simplify_noop
6200 #define simplify_umoreeq simplify_noop
6203 #define simplify_lfalse simplify_noop
6206 #define simplify_ltrue simplify_noop
6210 #define simplify_copy simplify_noop
6214 #define simplify_branch simplify_noop
6218 #define simplify_phi simplify_noop
6222 #define simplify_bsf simplify_noop
6223 #define simplify_bsr simplify_noop
6226 [OP_SMUL ] = simplify_smul,
6227 [OP_UMUL ] = simplify_umul,
6228 [OP_SDIV ] = simplify_sdiv,
6229 [OP_UDIV ] = simplify_udiv,
6230 [OP_SMOD ] = simplify_smod,
6231 [OP_UMOD ] = simplify_umod,
6232 [OP_ADD ] = simplify_add,
6233 [OP_SUB ] = simplify_sub,
6234 [OP_SL ] = simplify_sl,
6235 [OP_USR ] = simplify_usr,
6236 [OP_SSR ] = simplify_ssr,
6237 [OP_AND ] = simplify_and,
6238 [OP_XOR ] = simplify_xor,
6239 [OP_OR ] = simplify_or,
6240 [OP_POS ] = simplify_pos,
6241 [OP_NEG ] = simplify_neg,
6242 [OP_INVERT ] = simplify_invert,
6244 [OP_EQ ] = simplify_eq,
6245 [OP_NOTEQ ] = simplify_noteq,
6246 [OP_SLESS ] = simplify_sless,
6247 [OP_ULESS ] = simplify_uless,
6248 [OP_SMORE ] = simplify_smore,
6249 [OP_UMORE ] = simplify_umore,
6250 [OP_SLESSEQ ] = simplify_slesseq,
6251 [OP_ULESSEQ ] = simplify_ulesseq,
6252 [OP_SMOREEQ ] = simplify_smoreeq,
6253 [OP_UMOREEQ ] = simplify_umoreeq,
6254 [OP_LFALSE ] = simplify_lfalse,
6255 [OP_LTRUE ] = simplify_ltrue,
6257 [OP_LOAD ] = simplify_noop,
6258 [OP_STORE ] = simplify_noop,
6260 [OP_NOOP ] = simplify_noop,
6262 [OP_INTCONST ] = simplify_noop,
6263 [OP_BLOBCONST ] = simplify_noop,
6264 [OP_ADDRCONST ] = simplify_noop,
6266 [OP_WRITE ] = simplify_noop,
6267 [OP_READ ] = simplify_noop,
6268 [OP_COPY ] = simplify_copy,
6269 [OP_PIECE ] = simplify_noop,
6270 [OP_ASM ] = simplify_noop,
6272 [OP_DOT ] = simplify_noop,
6273 [OP_VAL_VEC ] = simplify_noop,
6275 [OP_LIST ] = simplify_noop,
6276 [OP_BRANCH ] = simplify_branch,
6277 [OP_LABEL ] = simplify_noop,
6278 [OP_ADECL ] = simplify_noop,
6279 [OP_SDECL ] = simplify_noop,
6280 [OP_PHI ] = simplify_phi,
6282 [OP_INB ] = simplify_noop,
6283 [OP_INW ] = simplify_noop,
6284 [OP_INL ] = simplify_noop,
6285 [OP_OUTB ] = simplify_noop,
6286 [OP_OUTW ] = simplify_noop,
6287 [OP_OUTL ] = simplify_noop,
6288 [OP_BSF ] = simplify_bsf,
6289 [OP_BSR ] = simplify_bsr,
6290 [OP_RDMSR ] = simplify_noop,
6291 [OP_WRMSR ] = simplify_noop,
6292 [OP_HLT ] = simplify_noop,
6295 static void simplify(struct compile_state *state, struct triple *ins)
6298 simplify_t do_simplify;
6302 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6306 do_simplify = table_simplify[op];
6309 internal_error(state, ins, "cannot simplify op: %d %s\n",
6313 do_simplify(state, ins);
6314 } while(ins->op != op);
6317 static void simplify_all(struct compile_state *state)
6319 struct triple *ins, *first;
6320 first = RHS(state->main_function, 0);
6323 simplify(state, ins);
6325 } while(ins != first);
6330 * ============================
6333 static void register_builtin_function(struct compile_state *state,
6334 const char *name, int op, struct type *rtype, ...)
6336 struct type *ftype, *atype, *param, **next;
6337 struct triple *def, *arg, *result, *work, *last, *first;
6338 struct hash_entry *ident;
6339 struct file_state file;
6345 /* Dummy file state to get debug handling right */
6346 memset(&file, 0, sizeof(file));
6347 file.basename = name;
6349 file.prev = state->file;
6350 state->file = &file;
6352 /* Find the Parameter count */
6353 valid_op(state, op);
6354 parameters = table_ops[op].rhs;
6355 if (parameters < 0 ) {
6356 internal_error(state, 0, "Invalid builtin parameter count");
6359 /* Find the function type */
6360 ftype = new_type(TYPE_FUNCTION, rtype, 0);
6361 next = &ftype->right;
6362 va_start(args, rtype);
6363 for(i = 0; i < parameters; i++) {
6364 atype = va_arg(args, struct type *);
6368 *next = new_type(TYPE_PRODUCT, *next, atype);
6369 next = &((*next)->right);
6377 /* Generate the needed triples */
6378 def = triple(state, OP_LIST, ftype, 0, 0);
6379 first = label(state);
6380 RHS(def, 0) = first;
6382 /* Now string them together */
6383 param = ftype->right;
6384 for(i = 0; i < parameters; i++) {
6385 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6386 atype = param->left;
6390 arg = flatten(state, first, variable(state, atype));
6391 param = param->right;
6394 if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6395 result = flatten(state, first, variable(state, rtype));
6397 MISC(def, 0) = result;
6398 work = new_triple(state, op, rtype, -1, parameters);
6399 for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6400 RHS(work, i) = read_expr(state, arg);
6402 if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6404 /* Populate the LHS with the target registers */
6405 work = flatten(state, first, work);
6406 work->type = &void_type;
6407 param = rtype->left;
6408 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6409 internal_error(state, 0, "Invalid result type");
6411 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6412 for(i = 0; i < rtype->elements; i++) {
6413 struct triple *piece;
6415 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6416 atype = param->left;
6418 if (!TYPE_ARITHMETIC(atype->type) &&
6419 !TYPE_PTR(atype->type)) {
6420 internal_error(state, 0, "Invalid lhs type");
6422 piece = triple(state, OP_PIECE, atype, work, 0);
6424 LHS(work, i) = piece;
6425 RHS(val, i) = piece;
6430 work = write_expr(state, result, work);
6432 work = flatten(state, first, work);
6433 last = flatten(state, first, label(state));
6434 name_len = strlen(name);
6435 ident = lookup(state, name, name_len);
6436 symbol(state, ident, &ident->sym_ident, def, ftype);
6438 state->file = file.prev;
6440 fprintf(stdout, "\n");
6441 loc(stdout, state, 0);
6442 fprintf(stdout, "\n__________ builtin_function _________\n");
6443 print_triple(state, def);
6444 fprintf(stdout, "__________ builtin_function _________ done\n\n");
6448 static struct type *partial_struct(struct compile_state *state,
6449 const char *field_name, struct type *type, struct type *rest)
6451 struct hash_entry *field_ident;
6452 struct type *result;
6455 field_name_len = strlen(field_name);
6456 field_ident = lookup(state, field_name, field_name_len);
6458 result = clone_type(0, type);
6459 result->field_ident = field_ident;
6462 result = new_type(TYPE_PRODUCT, result, rest);
6467 static struct type *register_builtin_type(struct compile_state *state,
6468 const char *name, struct type *type)
6470 struct hash_entry *ident;
6473 name_len = strlen(name);
6474 ident = lookup(state, name, name_len);
6476 if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6477 ulong_t elements = 0;
6479 type = new_type(TYPE_STRUCT, type, 0);
6481 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6483 field = field->right;
6486 symbol(state, ident, &ident->sym_struct, 0, type);
6487 type->type_ident = ident;
6488 type->elements = elements;
6490 symbol(state, ident, &ident->sym_ident, 0, type);
6491 ident->tok = TOK_TYPE_NAME;
6496 static void register_builtins(struct compile_state *state)
6498 struct type *msr_type;
6500 register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
6502 register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6504 register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
6507 register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
6508 &uchar_type, &ushort_type);
6509 register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
6510 &ushort_type, &ushort_type);
6511 register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
6512 &uint_type, &ushort_type);
6514 register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
6516 register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
6519 msr_type = register_builtin_type(state, "__builtin_msr_t",
6520 partial_struct(state, "lo", &ulong_type,
6521 partial_struct(state, "hi", &ulong_type, 0)));
6523 register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6525 register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6526 &ulong_type, &ulong_type, &ulong_type);
6528 register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
6532 static struct type *declarator(
6533 struct compile_state *state, struct type *type,
6534 struct hash_entry **ident, int need_ident);
6535 static void decl(struct compile_state *state, struct triple *first);
6536 static struct type *specifier_qualifier_list(struct compile_state *state);
6537 static int isdecl_specifier(int tok);
6538 static struct type *decl_specifiers(struct compile_state *state);
6539 static int istype(int tok);
6540 static struct triple *expr(struct compile_state *state);
6541 static struct triple *assignment_expr(struct compile_state *state);
6542 static struct type *type_name(struct compile_state *state);
6543 static void statement(struct compile_state *state, struct triple *fist);
6545 static struct triple *call_expr(
6546 struct compile_state *state, struct triple *func)
6549 struct type *param, *type;
6550 ulong_t pvals, index;
6552 if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6553 error(state, 0, "Called object is not a function");
6555 if (func->op != OP_LIST) {
6556 internal_error(state, 0, "improper function");
6558 eat(state, TOK_LPAREN);
6559 /* Find the return type without any specifiers */
6560 type = clone_type(0, func->type->left);
6561 def = new_triple(state, OP_CALL, func->type, -1, -1);
6564 pvals = TRIPLE_RHS(def->sizes);
6565 MISC(def, 0) = func;
6567 param = func->type->right;
6568 for(index = 0; index < pvals; index++) {
6570 struct type *arg_type;
6571 val = read_expr(state, assignment_expr(state));
6573 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6574 arg_type = param->left;
6576 write_compatible(state, arg_type, val->type);
6577 RHS(def, index) = val;
6578 if (index != (pvals - 1)) {
6579 eat(state, TOK_COMMA);
6580 param = param->right;
6583 eat(state, TOK_RPAREN);
6588 static struct triple *character_constant(struct compile_state *state)
6592 const signed char *str, *end;
6595 eat(state, TOK_LIT_CHAR);
6596 tk = &state->token[0];
6597 str = tk->val.str + 1;
6598 str_len = tk->str_len - 2;
6600 error(state, 0, "empty character constant");
6602 end = str + str_len;
6603 c = char_value(state, &str, end);
6605 error(state, 0, "multibyte character constant not supported");
6607 def = int_const(state, &char_type, (ulong_t)((long_t)c));
6611 static struct triple *string_constant(struct compile_state *state)
6616 const signed char *str, *end;
6617 signed char *buf, *ptr;
6621 type = new_type(TYPE_ARRAY, &char_type, 0);
6623 /* The while loop handles string concatenation */
6625 eat(state, TOK_LIT_STRING);
6626 tk = &state->token[0];
6627 str = tk->val.str + 1;
6628 str_len = tk->str_len - 2;
6630 error(state, 0, "negative string constant length");
6632 end = str + str_len;
6634 buf = xmalloc(type->elements + str_len + 1, "string_constant");
6635 memcpy(buf, ptr, type->elements);
6636 ptr = buf + type->elements;
6638 *ptr++ = char_value(state, &str, end);
6640 type->elements = ptr - buf;
6641 } while(peek(state) == TOK_LIT_STRING);
6643 type->elements += 1;
6644 def = triple(state, OP_BLOBCONST, type, 0, 0);
6650 static struct triple *integer_constant(struct compile_state *state)
6659 eat(state, TOK_LIT_INT);
6660 tk = &state->token[0];
6662 decimal = (tk->val.str[0] != '0');
6663 val = strtoul(tk->val.str, &end, 0);
6664 if ((val == ULONG_MAX) && (errno == ERANGE)) {
6665 error(state, 0, "Integer constant to large");
6668 if ((*end == 'u') || (*end == 'U')) {
6672 if ((*end == 'l') || (*end == 'L')) {
6676 if ((*end == 'u') || (*end == 'U')) {
6681 error(state, 0, "Junk at end of integer constant");
6688 if (!decimal && (val > LONG_MAX)) {
6694 if (val > UINT_MAX) {
6700 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
6703 else if (!decimal && (val > LONG_MAX)) {
6706 else if (val > INT_MAX) {
6710 def = int_const(state, type, val);
6714 static struct triple *primary_expr(struct compile_state *state)
6722 struct hash_entry *ident;
6723 /* Here ident is either:
6726 * an enumeration constant.
6728 eat(state, TOK_IDENT);
6729 ident = state->token[0].ident;
6730 if (!ident->sym_ident) {
6731 error(state, 0, "%s undeclared", ident->name);
6733 def = ident->sym_ident->def;
6736 case TOK_ENUM_CONST:
6737 /* Here ident is an enumeration constant */
6738 eat(state, TOK_ENUM_CONST);
6743 eat(state, TOK_LPAREN);
6745 eat(state, TOK_RPAREN);
6748 def = integer_constant(state);
6751 eat(state, TOK_LIT_FLOAT);
6752 error(state, 0, "Floating point constants not supported");
6757 def = character_constant(state);
6759 case TOK_LIT_STRING:
6760 def = string_constant(state);
6764 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
6769 static struct triple *postfix_expr(struct compile_state *state)
6773 def = primary_expr(state);
6775 struct triple *left;
6779 switch((tok = peek(state))) {
6781 eat(state, TOK_LBRACKET);
6782 def = mk_subscript_expr(state, left, expr(state));
6783 eat(state, TOK_RBRACKET);
6786 def = call_expr(state, def);
6790 struct hash_entry *field;
6791 eat(state, TOK_DOT);
6792 eat(state, TOK_IDENT);
6793 field = state->token[0].ident;
6794 def = deref_field(state, def, field);
6799 struct hash_entry *field;
6800 eat(state, TOK_ARROW);
6801 eat(state, TOK_IDENT);
6802 field = state->token[0].ident;
6803 def = mk_deref_expr(state, read_expr(state, def));
6804 def = deref_field(state, def, field);
6808 eat(state, TOK_PLUSPLUS);
6809 def = mk_post_inc_expr(state, left);
6811 case TOK_MINUSMINUS:
6812 eat(state, TOK_MINUSMINUS);
6813 def = mk_post_dec_expr(state, left);
6823 static struct triple *cast_expr(struct compile_state *state);
6825 static struct triple *unary_expr(struct compile_state *state)
6827 struct triple *def, *right;
6829 switch((tok = peek(state))) {
6831 eat(state, TOK_PLUSPLUS);
6832 def = mk_pre_inc_expr(state, unary_expr(state));
6834 case TOK_MINUSMINUS:
6835 eat(state, TOK_MINUSMINUS);
6836 def = mk_pre_dec_expr(state, unary_expr(state));
6839 eat(state, TOK_AND);
6840 def = mk_addr_expr(state, cast_expr(state), 0);
6843 eat(state, TOK_STAR);
6844 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
6847 eat(state, TOK_PLUS);
6848 right = read_expr(state, cast_expr(state));
6849 arithmetic(state, right);
6850 def = integral_promotion(state, right);
6853 eat(state, TOK_MINUS);
6854 right = read_expr(state, cast_expr(state));
6855 arithmetic(state, right);
6856 def = integral_promotion(state, right);
6857 def = triple(state, OP_NEG, def->type, def, 0);
6860 eat(state, TOK_TILDE);
6861 right = read_expr(state, cast_expr(state));
6862 integral(state, right);
6863 def = integral_promotion(state, right);
6864 def = triple(state, OP_INVERT, def->type, def, 0);
6867 eat(state, TOK_BANG);
6868 right = read_expr(state, cast_expr(state));
6870 def = lfalse_expr(state, right);
6876 eat(state, TOK_SIZEOF);
6878 tok2 = peek2(state);
6879 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6880 eat(state, TOK_LPAREN);
6881 type = type_name(state);
6882 eat(state, TOK_RPAREN);
6885 struct triple *expr;
6886 expr = unary_expr(state);
6888 release_expr(state, expr);
6890 def = int_const(state, &ulong_type, size_of(state, type));
6897 eat(state, TOK_ALIGNOF);
6899 tok2 = peek2(state);
6900 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6901 eat(state, TOK_LPAREN);
6902 type = type_name(state);
6903 eat(state, TOK_RPAREN);
6906 struct triple *expr;
6907 expr = unary_expr(state);
6909 release_expr(state, expr);
6911 def = int_const(state, &ulong_type, align_of(state, type));
6915 def = postfix_expr(state);
6921 static struct triple *cast_expr(struct compile_state *state)
6926 tok2 = peek2(state);
6927 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
6929 eat(state, TOK_LPAREN);
6930 type = type_name(state);
6931 eat(state, TOK_RPAREN);
6932 def = read_expr(state, cast_expr(state));
6933 def = triple(state, OP_COPY, type, def, 0);
6936 def = unary_expr(state);
6941 static struct triple *mult_expr(struct compile_state *state)
6945 def = cast_expr(state);
6947 struct triple *left, *right;
6948 struct type *result_type;
6951 switch(tok = (peek(state))) {
6955 left = read_expr(state, def);
6956 arithmetic(state, left);
6960 right = read_expr(state, cast_expr(state));
6961 arithmetic(state, right);
6963 result_type = arithmetic_result(state, left, right);
6964 sign = is_signed(result_type);
6967 case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
6968 case TOK_DIV: op = sign? OP_SDIV : OP_UDIV; break;
6969 case TOK_MOD: op = sign? OP_SMOD : OP_UMOD; break;
6971 def = triple(state, op, result_type, left, right);
6981 static struct triple *add_expr(struct compile_state *state)
6985 def = mult_expr(state);
6988 switch( peek(state)) {
6990 eat(state, TOK_PLUS);
6991 def = mk_add_expr(state, def, mult_expr(state));
6994 eat(state, TOK_MINUS);
6995 def = mk_sub_expr(state, def, mult_expr(state));
7005 static struct triple *shift_expr(struct compile_state *state)
7009 def = add_expr(state);
7011 struct triple *left, *right;
7014 switch((tok = peek(state))) {
7017 left = read_expr(state, def);
7018 integral(state, left);
7019 left = integral_promotion(state, left);
7023 right = read_expr(state, add_expr(state));
7024 integral(state, right);
7025 right = integral_promotion(state, right);
7027 op = (tok == TOK_SL)? OP_SL :
7028 is_signed(left->type)? OP_SSR: OP_USR;
7030 def = triple(state, op, left->type, left, right);
7040 static struct triple *relational_expr(struct compile_state *state)
7042 #warning "Extend relational exprs to work on more than arithmetic types"
7045 def = shift_expr(state);
7047 struct triple *left, *right;
7048 struct type *arg_type;
7051 switch((tok = peek(state))) {
7056 left = read_expr(state, def);
7057 arithmetic(state, left);
7061 right = read_expr(state, shift_expr(state));
7062 arithmetic(state, right);
7064 arg_type = arithmetic_result(state, left, right);
7065 sign = is_signed(arg_type);
7068 case TOK_LESS: op = sign? OP_SLESS : OP_ULESS; break;
7069 case TOK_MORE: op = sign? OP_SMORE : OP_UMORE; break;
7070 case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7071 case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7073 def = triple(state, op, &int_type, left, right);
7083 static struct triple *equality_expr(struct compile_state *state)
7085 #warning "Extend equality exprs to work on more than arithmetic types"
7088 def = relational_expr(state);
7090 struct triple *left, *right;
7093 switch((tok = peek(state))) {
7096 left = read_expr(state, def);
7097 arithmetic(state, left);
7099 right = read_expr(state, relational_expr(state));
7100 arithmetic(state, right);
7101 op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7102 def = triple(state, op, &int_type, left, right);
7112 static struct triple *and_expr(struct compile_state *state)
7115 def = equality_expr(state);
7116 while(peek(state) == TOK_AND) {
7117 struct triple *left, *right;
7118 struct type *result_type;
7119 left = read_expr(state, def);
7120 integral(state, left);
7121 eat(state, TOK_AND);
7122 right = read_expr(state, equality_expr(state));
7123 integral(state, right);
7124 result_type = arithmetic_result(state, left, right);
7125 def = triple(state, OP_AND, result_type, left, right);
7130 static struct triple *xor_expr(struct compile_state *state)
7133 def = and_expr(state);
7134 while(peek(state) == TOK_XOR) {
7135 struct triple *left, *right;
7136 struct type *result_type;
7137 left = read_expr(state, def);
7138 integral(state, left);
7139 eat(state, TOK_XOR);
7140 right = read_expr(state, and_expr(state));
7141 integral(state, right);
7142 result_type = arithmetic_result(state, left, right);
7143 def = triple(state, OP_XOR, result_type, left, right);
7148 static struct triple *or_expr(struct compile_state *state)
7151 def = xor_expr(state);
7152 while(peek(state) == TOK_OR) {
7153 struct triple *left, *right;
7154 struct type *result_type;
7155 left = read_expr(state, def);
7156 integral(state, left);
7158 right = read_expr(state, xor_expr(state));
7159 integral(state, right);
7160 result_type = arithmetic_result(state, left, right);
7161 def = triple(state, OP_OR, result_type, left, right);
7166 static struct triple *land_expr(struct compile_state *state)
7169 def = or_expr(state);
7170 while(peek(state) == TOK_LOGAND) {
7171 struct triple *left, *right;
7172 left = read_expr(state, def);
7174 eat(state, TOK_LOGAND);
7175 right = read_expr(state, or_expr(state));
7178 def = triple(state, OP_LAND, &int_type,
7179 ltrue_expr(state, left),
7180 ltrue_expr(state, right));
7185 static struct triple *lor_expr(struct compile_state *state)
7188 def = land_expr(state);
7189 while(peek(state) == TOK_LOGOR) {
7190 struct triple *left, *right;
7191 left = read_expr(state, def);
7193 eat(state, TOK_LOGOR);
7194 right = read_expr(state, land_expr(state));
7197 def = triple(state, OP_LOR, &int_type,
7198 ltrue_expr(state, left),
7199 ltrue_expr(state, right));
7204 static struct triple *conditional_expr(struct compile_state *state)
7207 def = lor_expr(state);
7208 if (peek(state) == TOK_QUEST) {
7209 struct triple *test, *left, *right;
7211 test = ltrue_expr(state, read_expr(state, def));
7212 eat(state, TOK_QUEST);
7213 left = read_expr(state, expr(state));
7214 eat(state, TOK_COLON);
7215 right = read_expr(state, conditional_expr(state));
7217 def = cond_expr(state, test, left, right);
7222 static struct triple *eval_const_expr(
7223 struct compile_state *state, struct triple *expr)
7226 struct triple *head, *ptr;
7227 head = label(state); /* dummy initial triple */
7228 flatten(state, head, expr);
7229 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7230 simplify(state, ptr);
7232 /* Remove the constant value the tail of the list */
7234 def->prev->next = def->next;
7235 def->next->prev = def->prev;
7236 def->next = def->prev = def;
7237 if (!is_const(def)) {
7238 internal_error(state, 0, "Not a constant expression");
7240 /* Free the intermediate expressions */
7241 while(head->next != head) {
7242 release_triple(state, head->next);
7244 free_triple(state, head);
7248 static struct triple *constant_expr(struct compile_state *state)
7250 return eval_const_expr(state, conditional_expr(state));
7253 static struct triple *assignment_expr(struct compile_state *state)
7255 struct triple *def, *left, *right;
7257 /* The C grammer in K&R shows assignment expressions
7258 * only taking unary expressions as input on their
7259 * left hand side. But specifies the precedence of
7260 * assignemnt as the lowest operator except for comma.
7262 * Allowing conditional expressions on the left hand side
7263 * of an assignement results in a grammar that accepts
7264 * a larger set of statements than standard C. As long
7265 * as the subset of the grammar that is standard C behaves
7266 * correctly this should cause no problems.
7268 * For the extra token strings accepted by the grammar
7269 * none of them should produce a valid lvalue, so they
7270 * should not produce functioning programs.
7272 * GCC has this bug as well, so surprises should be minimal.
7274 def = conditional_expr(state);
7276 switch((tok = peek(state))) {
7278 lvalue(state, left);
7280 def = write_expr(state, left,
7281 read_expr(state, assignment_expr(state)));
7286 lvalue(state, left);
7287 arithmetic(state, left);
7289 right = read_expr(state, assignment_expr(state));
7290 arithmetic(state, right);
7292 sign = is_signed(left->type);
7295 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7296 case TOK_DIVEQ: op = sign? OP_SDIV : OP_UDIV; break;
7297 case TOK_MODEQ: op = sign? OP_SMOD : OP_UMOD; break;
7299 def = write_expr(state, left,
7300 triple(state, op, left->type,
7301 read_expr(state, left), right));
7304 lvalue(state, left);
7305 eat(state, TOK_PLUSEQ);
7306 def = write_expr(state, left,
7307 mk_add_expr(state, left, assignment_expr(state)));
7310 lvalue(state, left);
7311 eat(state, TOK_MINUSEQ);
7312 def = write_expr(state, left,
7313 mk_sub_expr(state, left, assignment_expr(state)));
7320 lvalue(state, left);
7321 integral(state, left);
7323 right = read_expr(state, assignment_expr(state));
7324 integral(state, right);
7325 right = integral_promotion(state, right);
7326 sign = is_signed(left->type);
7329 case TOK_SLEQ: op = OP_SL; break;
7330 case TOK_SREQ: op = sign? OP_SSR: OP_USR; break;
7331 case TOK_ANDEQ: op = OP_AND; break;
7332 case TOK_XOREQ: op = OP_XOR; break;
7333 case TOK_OREQ: op = OP_OR; break;
7335 def = write_expr(state, left,
7336 triple(state, op, left->type,
7337 read_expr(state, left), right));
7343 static struct triple *expr(struct compile_state *state)
7346 def = assignment_expr(state);
7347 while(peek(state) == TOK_COMMA) {
7348 struct triple *left, *right;
7350 eat(state, TOK_COMMA);
7351 right = assignment_expr(state);
7352 def = triple(state, OP_COMMA, right->type, left, right);
7357 static void expr_statement(struct compile_state *state, struct triple *first)
7359 if (peek(state) != TOK_SEMI) {
7360 flatten(state, first, expr(state));
7362 eat(state, TOK_SEMI);
7365 static void if_statement(struct compile_state *state, struct triple *first)
7367 struct triple *test, *jmp1, *jmp2, *middle, *end;
7369 jmp1 = jmp2 = middle = 0;
7371 eat(state, TOK_LPAREN);
7374 /* Cleanup and invert the test */
7375 test = lfalse_expr(state, read_expr(state, test));
7376 eat(state, TOK_RPAREN);
7377 /* Generate the needed pieces */
7378 middle = label(state);
7379 jmp1 = branch(state, middle, test);
7380 /* Thread the pieces together */
7381 flatten(state, first, test);
7382 flatten(state, first, jmp1);
7383 flatten(state, first, label(state));
7384 statement(state, first);
7385 if (peek(state) == TOK_ELSE) {
7386 eat(state, TOK_ELSE);
7387 /* Generate the rest of the pieces */
7389 jmp2 = branch(state, end, 0);
7390 /* Thread them together */
7391 flatten(state, first, jmp2);
7392 flatten(state, first, middle);
7393 statement(state, first);
7394 flatten(state, first, end);
7397 flatten(state, first, middle);
7401 static void for_statement(struct compile_state *state, struct triple *first)
7403 struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7404 struct triple *label1, *label2, *label3;
7405 struct hash_entry *ident;
7407 eat(state, TOK_FOR);
7408 eat(state, TOK_LPAREN);
7409 head = test = tail = jmp1 = jmp2 = 0;
7410 if (peek(state) != TOK_SEMI) {
7413 eat(state, TOK_SEMI);
7414 if (peek(state) != TOK_SEMI) {
7417 test = ltrue_expr(state, read_expr(state, test));
7419 eat(state, TOK_SEMI);
7420 if (peek(state) != TOK_RPAREN) {
7423 eat(state, TOK_RPAREN);
7424 /* Generate the needed pieces */
7425 label1 = label(state);
7426 label2 = label(state);
7427 label3 = label(state);
7429 jmp1 = branch(state, label3, 0);
7430 jmp2 = branch(state, label1, test);
7433 jmp2 = branch(state, label1, 0);
7436 /* Remember where break and continue go */
7438 ident = state->i_break;
7439 symbol(state, ident, &ident->sym_ident, end, end->type);
7440 ident = state->i_continue;
7441 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7442 /* Now include the body */
7443 flatten(state, first, head);
7444 flatten(state, first, jmp1);
7445 flatten(state, first, label1);
7446 statement(state, first);
7447 flatten(state, first, label2);
7448 flatten(state, first, tail);
7449 flatten(state, first, label3);
7450 flatten(state, first, test);
7451 flatten(state, first, jmp2);
7452 flatten(state, first, end);
7453 /* Cleanup the break/continue scope */
7457 static void while_statement(struct compile_state *state, struct triple *first)
7459 struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7460 struct hash_entry *ident;
7461 eat(state, TOK_WHILE);
7462 eat(state, TOK_LPAREN);
7465 test = ltrue_expr(state, read_expr(state, test));
7466 eat(state, TOK_RPAREN);
7467 /* Generate the needed pieces */
7468 label1 = label(state);
7469 label2 = label(state);
7470 jmp1 = branch(state, label2, 0);
7471 jmp2 = branch(state, label1, test);
7473 /* Remember where break and continue go */
7475 ident = state->i_break;
7476 symbol(state, ident, &ident->sym_ident, end, end->type);
7477 ident = state->i_continue;
7478 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7479 /* Thread them together */
7480 flatten(state, first, jmp1);
7481 flatten(state, first, label1);
7482 statement(state, first);
7483 flatten(state, first, label2);
7484 flatten(state, first, test);
7485 flatten(state, first, jmp2);
7486 flatten(state, first, end);
7487 /* Cleanup the break/continue scope */
7491 static void do_statement(struct compile_state *state, struct triple *first)
7493 struct triple *label1, *label2, *test, *end;
7494 struct hash_entry *ident;
7496 /* Generate the needed pieces */
7497 label1 = label(state);
7498 label2 = label(state);
7500 /* Remember where break and continue go */
7502 ident = state->i_break;
7503 symbol(state, ident, &ident->sym_ident, end, end->type);
7504 ident = state->i_continue;
7505 symbol(state, ident, &ident->sym_ident, label2, label2->type);
7506 /* Now include the body */
7507 flatten(state, first, label1);
7508 statement(state, first);
7509 /* Cleanup the break/continue scope */
7511 /* Eat the rest of the loop */
7512 eat(state, TOK_WHILE);
7513 eat(state, TOK_LPAREN);
7514 test = read_expr(state, expr(state));
7516 eat(state, TOK_RPAREN);
7517 eat(state, TOK_SEMI);
7518 /* Thread the pieces together */
7519 test = ltrue_expr(state, test);
7520 flatten(state, first, label2);
7521 flatten(state, first, test);
7522 flatten(state, first, branch(state, label1, test));
7523 flatten(state, first, end);
7527 static void return_statement(struct compile_state *state, struct triple *first)
7529 struct triple *jmp, *mv, *dest, *var, *val;
7531 eat(state, TOK_RETURN);
7533 #warning "FIXME implement a more general excess branch elimination"
7535 /* If we have a return value do some more work */
7536 if (peek(state) != TOK_SEMI) {
7537 val = read_expr(state, expr(state));
7539 eat(state, TOK_SEMI);
7541 /* See if this last statement in a function */
7542 last = ((peek(state) == TOK_RBRACE) &&
7543 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7545 /* Find the return variable */
7546 var = MISC(state->main_function, 0);
7547 /* Find the return destination */
7548 dest = RHS(state->main_function, 0)->prev;
7550 /* If needed generate a jump instruction */
7552 jmp = branch(state, dest, 0);
7554 /* If needed generate an assignment instruction */
7556 mv = write_expr(state, var, val);
7558 /* Now put the code together */
7560 flatten(state, first, mv);
7561 flatten(state, first, jmp);
7564 flatten(state, first, jmp);
7568 static void break_statement(struct compile_state *state, struct triple *first)
7570 struct triple *dest;
7571 eat(state, TOK_BREAK);
7572 eat(state, TOK_SEMI);
7573 if (!state->i_break->sym_ident) {
7574 error(state, 0, "break statement not within loop or switch");
7576 dest = state->i_break->sym_ident->def;
7577 flatten(state, first, branch(state, dest, 0));
7580 static void continue_statement(struct compile_state *state, struct triple *first)
7582 struct triple *dest;
7583 eat(state, TOK_CONTINUE);
7584 eat(state, TOK_SEMI);
7585 if (!state->i_continue->sym_ident) {
7586 error(state, 0, "continue statement outside of a loop");
7588 dest = state->i_continue->sym_ident->def;
7589 flatten(state, first, branch(state, dest, 0));
7592 static void goto_statement(struct compile_state *state, struct triple *first)
7595 eat(state, TOK_GOTO);
7596 eat(state, TOK_IDENT);
7597 eat(state, TOK_SEMI);
7598 error(state, 0, "goto is not implemeted");
7602 static void labeled_statement(struct compile_state *state, struct triple *first)
7605 eat(state, TOK_IDENT);
7606 eat(state, TOK_COLON);
7607 statement(state, first);
7608 error(state, 0, "labeled statements are not implemented");
7612 static void switch_statement(struct compile_state *state, struct triple *first)
7615 eat(state, TOK_SWITCH);
7616 eat(state, TOK_LPAREN);
7618 eat(state, TOK_RPAREN);
7619 statement(state, first);
7620 error(state, 0, "switch statements are not implemented");
7624 static void case_statement(struct compile_state *state, struct triple *first)
7627 eat(state, TOK_CASE);
7628 constant_expr(state);
7629 eat(state, TOK_COLON);
7630 statement(state, first);
7631 error(state, 0, "case statements are not implemented");
7635 static void default_statement(struct compile_state *state, struct triple *first)
7638 eat(state, TOK_DEFAULT);
7639 eat(state, TOK_COLON);
7640 statement(state, first);
7641 error(state, 0, "default statements are not implemented");
7645 static void asm_statement(struct compile_state *state, struct triple *first)
7647 struct asm_info *info;
7649 struct triple *constraint;
7650 struct triple *expr;
7651 } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
7652 struct triple *def, *asm_str;
7653 int out, in, clobbers, more, colons, i;
7655 eat(state, TOK_ASM);
7656 /* For now ignore the qualifiers */
7657 switch(peek(state)) {
7659 eat(state, TOK_CONST);
7662 eat(state, TOK_VOLATILE);
7665 eat(state, TOK_LPAREN);
7666 asm_str = string_constant(state);
7669 out = in = clobbers = 0;
7671 if ((colons == 0) && (peek(state) == TOK_COLON)) {
7672 eat(state, TOK_COLON);
7674 more = (peek(state) == TOK_LIT_STRING);
7677 struct triple *constraint;
7680 if (out > MAX_LHS) {
7681 error(state, 0, "Maximum output count exceeded.");
7683 constraint = string_constant(state);
7684 str = constraint->u.blob;
7685 if (str[0] != '=') {
7686 error(state, 0, "Output constraint does not start with =");
7688 constraint->u.blob = str + 1;
7689 eat(state, TOK_LPAREN);
7690 var = conditional_expr(state);
7691 eat(state, TOK_RPAREN);
7694 out_param[out].constraint = constraint;
7695 out_param[out].expr = var;
7696 if (peek(state) == TOK_COMMA) {
7697 eat(state, TOK_COMMA);
7704 if ((colons == 1) && (peek(state) == TOK_COLON)) {
7705 eat(state, TOK_COLON);
7707 more = (peek(state) == TOK_LIT_STRING);
7710 struct triple *constraint;
7714 error(state, 0, "Maximum input count exceeded.");
7716 constraint = string_constant(state);
7717 str = constraint->u.blob;
7718 if (digitp(str[0] && str[1] == '\0')) {
7720 val = digval(str[0]);
7721 if ((val < 0) || (val >= out)) {
7722 error(state, 0, "Invalid input constraint %d", val);
7725 eat(state, TOK_LPAREN);
7726 val = conditional_expr(state);
7727 eat(state, TOK_RPAREN);
7729 in_param[in].constraint = constraint;
7730 in_param[in].expr = val;
7731 if (peek(state) == TOK_COMMA) {
7732 eat(state, TOK_COMMA);
7740 if ((colons == 2) && (peek(state) == TOK_COLON)) {
7741 eat(state, TOK_COLON);
7743 more = (peek(state) == TOK_LIT_STRING);
7745 struct triple *clobber;
7747 if ((clobbers + out) > MAX_LHS) {
7748 error(state, 0, "Maximum clobber limit exceeded.");
7750 clobber = string_constant(state);
7751 eat(state, TOK_RPAREN);
7753 clob_param[clobbers].constraint = clobber;
7754 if (peek(state) == TOK_COMMA) {
7755 eat(state, TOK_COMMA);
7761 eat(state, TOK_RPAREN);
7762 eat(state, TOK_SEMI);
7765 info = xcmalloc(sizeof(*info), "asm_info");
7766 info->str = asm_str->u.blob;
7767 free_triple(state, asm_str);
7769 def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
7770 def->u.ainfo = info;
7772 /* Find the register constraints */
7773 for(i = 0; i < out; i++) {
7774 struct triple *constraint;
7775 constraint = out_param[i].constraint;
7776 info->tmpl.lhs[i] = arch_reg_constraint(state,
7777 out_param[i].expr->type, constraint->u.blob);
7778 free_triple(state, constraint);
7780 for(; i - out < clobbers; i++) {
7781 struct triple *constraint;
7782 constraint = clob_param[i - out].constraint;
7783 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
7784 free_triple(state, constraint);
7786 for(i = 0; i < in; i++) {
7787 struct triple *constraint;
7789 constraint = in_param[i].constraint;
7790 str = constraint->u.blob;
7791 if (digitp(str[0]) && str[1] == '\0') {
7792 struct reg_info cinfo;
7794 val = digval(str[0]);
7795 cinfo.reg = info->tmpl.lhs[val].reg;
7796 cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
7797 cinfo.regcm &= info->tmpl.lhs[val].regcm;
7798 if (cinfo.reg == REG_UNSET) {
7799 cinfo.reg = REG_VIRT0 + val;
7801 if (cinfo.regcm == 0) {
7802 error(state, 0, "No registers for %d", val);
7804 info->tmpl.lhs[val] = cinfo;
7805 info->tmpl.rhs[i] = cinfo;
7808 info->tmpl.rhs[i] = arch_reg_constraint(state,
7809 in_param[i].expr->type, str);
7811 free_triple(state, constraint);
7814 /* Now build the helper expressions */
7815 for(i = 0; i < in; i++) {
7816 RHS(def, i) = read_expr(state,in_param[i].expr);
7818 flatten(state, first, def);
7819 for(i = 0; i < out; i++) {
7820 struct triple *piece;
7821 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
7823 LHS(def, i) = piece;
7824 flatten(state, first,
7825 write_expr(state, out_param[i].expr, piece));
7827 for(; i - out < clobbers; i++) {
7828 struct triple *piece;
7829 piece = triple(state, OP_PIECE, &void_type, def, 0);
7831 LHS(def, i) = piece;
7832 flatten(state, first, piece);
7837 static int isdecl(int tok)
7860 case TOK_TYPE_NAME: /* typedef name */
7867 static void compound_statement(struct compile_state *state, struct triple *first)
7869 eat(state, TOK_LBRACE);
7872 /* statement-list opt */
7873 while (peek(state) != TOK_RBRACE) {
7874 statement(state, first);
7877 eat(state, TOK_RBRACE);
7880 static void statement(struct compile_state *state, struct triple *first)
7884 if (tok == TOK_LBRACE) {
7885 compound_statement(state, first);
7887 else if (tok == TOK_IF) {
7888 if_statement(state, first);
7890 else if (tok == TOK_FOR) {
7891 for_statement(state, first);
7893 else if (tok == TOK_WHILE) {
7894 while_statement(state, first);
7896 else if (tok == TOK_DO) {
7897 do_statement(state, first);
7899 else if (tok == TOK_RETURN) {
7900 return_statement(state, first);
7902 else if (tok == TOK_BREAK) {
7903 break_statement(state, first);
7905 else if (tok == TOK_CONTINUE) {
7906 continue_statement(state, first);
7908 else if (tok == TOK_GOTO) {
7909 goto_statement(state, first);
7911 else if (tok == TOK_SWITCH) {
7912 switch_statement(state, first);
7914 else if (tok == TOK_ASM) {
7915 asm_statement(state, first);
7917 else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
7918 labeled_statement(state, first);
7920 else if (tok == TOK_CASE) {
7921 case_statement(state, first);
7923 else if (tok == TOK_DEFAULT) {
7924 default_statement(state, first);
7926 else if (isdecl(tok)) {
7927 /* This handles C99 intermixing of statements and decls */
7931 expr_statement(state, first);
7935 static struct type *param_decl(struct compile_state *state)
7938 struct hash_entry *ident;
7939 /* Cheat so the declarator will know we are not global */
7942 type = decl_specifiers(state);
7943 type = declarator(state, type, &ident, 0);
7944 type->field_ident = ident;
7949 static struct type *param_type_list(struct compile_state *state, struct type *type)
7951 struct type *ftype, **next;
7952 ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
7953 next = &ftype->right;
7954 while(peek(state) == TOK_COMMA) {
7955 eat(state, TOK_COMMA);
7956 if (peek(state) == TOK_DOTS) {
7957 eat(state, TOK_DOTS);
7958 error(state, 0, "variadic functions not supported");
7961 *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
7962 next = &((*next)->right);
7969 static struct type *type_name(struct compile_state *state)
7972 type = specifier_qualifier_list(state);
7973 /* abstract-declarator (may consume no tokens) */
7974 type = declarator(state, type, 0, 0);
7978 static struct type *direct_declarator(
7979 struct compile_state *state, struct type *type,
7980 struct hash_entry **ident, int need_ident)
7985 arrays_complete(state, type);
7986 switch(peek(state)) {
7988 eat(state, TOK_IDENT);
7990 error(state, 0, "Unexpected identifier found");
7992 /* The name of what we are declaring */
7993 *ident = state->token[0].ident;
7996 eat(state, TOK_LPAREN);
7997 outer = declarator(state, type, ident, need_ident);
7998 eat(state, TOK_RPAREN);
8002 error(state, 0, "Identifier expected");
8008 arrays_complete(state, type);
8009 switch(peek(state)) {
8011 eat(state, TOK_LPAREN);
8012 type = param_type_list(state, type);
8013 eat(state, TOK_RPAREN);
8017 unsigned int qualifiers;
8018 struct triple *value;
8020 eat(state, TOK_LBRACKET);
8021 if (peek(state) != TOK_RBRACKET) {
8022 value = constant_expr(state);
8023 integral(state, value);
8025 eat(state, TOK_RBRACKET);
8027 qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8028 type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8030 type->elements = value->u.cval;
8031 free_triple(state, value);
8033 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8045 arrays_complete(state, type);
8047 for(inner = outer; inner->left; inner = inner->left)
8055 static struct type *declarator(
8056 struct compile_state *state, struct type *type,
8057 struct hash_entry **ident, int need_ident)
8059 while(peek(state) == TOK_STAR) {
8060 eat(state, TOK_STAR);
8061 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8063 type = direct_declarator(state, type, ident, need_ident);
8068 static struct type *typedef_name(
8069 struct compile_state *state, unsigned int specifiers)
8071 struct hash_entry *ident;
8073 eat(state, TOK_TYPE_NAME);
8074 ident = state->token[0].ident;
8075 type = ident->sym_ident->type;
8076 specifiers |= type->type & QUAL_MASK;
8077 if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
8078 (type->type & (STOR_MASK | QUAL_MASK))) {
8079 type = clone_type(specifiers, type);
8084 static struct type *enum_specifier(
8085 struct compile_state *state, unsigned int specifiers)
8091 eat(state, TOK_ENUM);
8093 if (tok == TOK_IDENT) {
8094 eat(state, TOK_IDENT);
8096 if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8097 eat(state, TOK_LBRACE);
8099 eat(state, TOK_IDENT);
8100 if (peek(state) == TOK_EQ) {
8102 constant_expr(state);
8104 if (peek(state) == TOK_COMMA) {
8105 eat(state, TOK_COMMA);
8107 } while(peek(state) != TOK_RBRACE);
8108 eat(state, TOK_RBRACE);
8115 static struct type *struct_declarator(
8116 struct compile_state *state, struct type *type, struct hash_entry **ident)
8119 #warning "struct_declarator is complicated because of bitfields, kill them?"
8121 if (tok != TOK_COLON) {
8122 type = declarator(state, type, ident, 1);
8124 if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8125 eat(state, TOK_COLON);
8126 constant_expr(state);
8133 static struct type *struct_or_union_specifier(
8134 struct compile_state *state, unsigned int specifiers)
8136 struct type *struct_type;
8137 struct hash_entry *ident;
8138 unsigned int type_join;
8142 switch(peek(state)) {
8144 eat(state, TOK_STRUCT);
8145 type_join = TYPE_PRODUCT;
8148 eat(state, TOK_UNION);
8149 type_join = TYPE_OVERLAP;
8150 error(state, 0, "unions not yet supported\n");
8153 eat(state, TOK_STRUCT);
8154 type_join = TYPE_PRODUCT;
8158 if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8160 ident = state->token[0].ident;
8162 if (!ident || (peek(state) == TOK_LBRACE)) {
8165 eat(state, TOK_LBRACE);
8167 struct type *base_type;
8170 base_type = specifier_qualifier_list(state);
8171 next = &struct_type;
8174 struct hash_entry *fident;
8176 type = declarator(state, base_type, &fident, 1);
8178 if (peek(state) == TOK_COMMA) {
8180 eat(state, TOK_COMMA);
8182 type = clone_type(0, type);
8183 type->field_ident = fident;
8185 *next = new_type(type_join, *next, type);
8186 next = &((*next)->right);
8191 eat(state, TOK_SEMI);
8192 } while(peek(state) != TOK_RBRACE);
8193 eat(state, TOK_RBRACE);
8194 struct_type = new_type(TYPE_STRUCT, struct_type, 0);
8195 struct_type->type_ident = ident;
8196 struct_type->elements = elements;
8197 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8199 if (ident && ident->sym_struct) {
8200 struct_type = ident->sym_struct->type;
8202 else if (ident && !ident->sym_struct) {
8203 error(state, 0, "struct %s undeclared", ident->name);
8208 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8210 unsigned int specifiers;
8211 switch(peek(state)) {
8213 eat(state, TOK_AUTO);
8214 specifiers = STOR_AUTO;
8217 eat(state, TOK_REGISTER);
8218 specifiers = STOR_REGISTER;
8221 eat(state, TOK_STATIC);
8222 specifiers = STOR_STATIC;
8225 eat(state, TOK_EXTERN);
8226 specifiers = STOR_EXTERN;
8229 eat(state, TOK_TYPEDEF);
8230 specifiers = STOR_TYPEDEF;
8233 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8234 specifiers = STOR_STATIC;
8237 specifiers = STOR_AUTO;
8243 static unsigned int function_specifier_opt(struct compile_state *state)
8245 /* Ignore the inline keyword */
8246 unsigned int specifiers;
8248 switch(peek(state)) {
8250 eat(state, TOK_INLINE);
8251 specifiers = STOR_INLINE;
8256 static unsigned int type_qualifiers(struct compile_state *state)
8258 unsigned int specifiers;
8261 specifiers = QUAL_NONE;
8263 switch(peek(state)) {
8265 eat(state, TOK_CONST);
8266 specifiers = QUAL_CONST;
8269 eat(state, TOK_VOLATILE);
8270 specifiers = QUAL_VOLATILE;
8273 eat(state, TOK_RESTRICT);
8274 specifiers = QUAL_RESTRICT;
8284 static struct type *type_specifier(
8285 struct compile_state *state, unsigned int spec)
8289 switch(peek(state)) {
8291 eat(state, TOK_VOID);
8292 type = new_type(TYPE_VOID | spec, 0, 0);
8295 eat(state, TOK_CHAR);
8296 type = new_type(TYPE_CHAR | spec, 0, 0);
8299 eat(state, TOK_SHORT);
8300 if (peek(state) == TOK_INT) {
8301 eat(state, TOK_INT);
8303 type = new_type(TYPE_SHORT | spec, 0, 0);
8306 eat(state, TOK_INT);
8307 type = new_type(TYPE_INT | spec, 0, 0);
8310 eat(state, TOK_LONG);
8311 switch(peek(state)) {
8313 eat(state, TOK_LONG);
8314 error(state, 0, "long long not supported");
8317 eat(state, TOK_DOUBLE);
8318 error(state, 0, "long double not supported");
8321 eat(state, TOK_INT);
8322 type = new_type(TYPE_LONG | spec, 0, 0);
8325 type = new_type(TYPE_LONG | spec, 0, 0);
8330 eat(state, TOK_FLOAT);
8331 error(state, 0, "type float not supported");
8334 eat(state, TOK_DOUBLE);
8335 error(state, 0, "type double not supported");
8338 eat(state, TOK_SIGNED);
8339 switch(peek(state)) {
8341 eat(state, TOK_LONG);
8342 switch(peek(state)) {
8344 eat(state, TOK_LONG);
8345 error(state, 0, "type long long not supported");
8348 eat(state, TOK_INT);
8349 type = new_type(TYPE_LONG | spec, 0, 0);
8352 type = new_type(TYPE_LONG | spec, 0, 0);
8357 eat(state, TOK_INT);
8358 type = new_type(TYPE_INT | spec, 0, 0);
8361 eat(state, TOK_SHORT);
8362 type = new_type(TYPE_SHORT | spec, 0, 0);
8365 eat(state, TOK_CHAR);
8366 type = new_type(TYPE_CHAR | spec, 0, 0);
8369 type = new_type(TYPE_INT | spec, 0, 0);
8374 eat(state, TOK_UNSIGNED);
8375 switch(peek(state)) {
8377 eat(state, TOK_LONG);
8378 switch(peek(state)) {
8380 eat(state, TOK_LONG);
8381 error(state, 0, "unsigned long long not supported");
8384 eat(state, TOK_INT);
8385 type = new_type(TYPE_ULONG | spec, 0, 0);
8388 type = new_type(TYPE_ULONG | spec, 0, 0);
8393 eat(state, TOK_INT);
8394 type = new_type(TYPE_UINT | spec, 0, 0);
8397 eat(state, TOK_SHORT);
8398 type = new_type(TYPE_USHORT | spec, 0, 0);
8401 eat(state, TOK_CHAR);
8402 type = new_type(TYPE_UCHAR | spec, 0, 0);
8405 type = new_type(TYPE_UINT | spec, 0, 0);
8409 /* struct or union specifier */
8412 type = struct_or_union_specifier(state, spec);
8414 /* enum-spefifier */
8416 type = enum_specifier(state, spec);
8420 type = typedef_name(state, spec);
8423 error(state, 0, "bad type specifier %s",
8424 tokens[peek(state)]);
8430 static int istype(int tok)
8456 static struct type *specifier_qualifier_list(struct compile_state *state)
8459 unsigned int specifiers = 0;
8461 /* type qualifiers */
8462 specifiers |= type_qualifiers(state);
8464 /* type specifier */
8465 type = type_specifier(state, specifiers);
8470 static int isdecl_specifier(int tok)
8473 /* storage class specifier */
8479 /* type qualifier */
8483 /* type specifiers */
8493 /* struct or union specifier */
8496 /* enum-spefifier */
8500 /* function specifiers */
8508 static struct type *decl_specifiers(struct compile_state *state)
8511 unsigned int specifiers;
8512 /* I am overly restrictive in the arragement of specifiers supported.
8513 * C is overly flexible in this department it makes interpreting
8514 * the parse tree difficult.
8518 /* storage class specifier */
8519 specifiers |= storage_class_specifier_opt(state);
8521 /* function-specifier */
8522 specifiers |= function_specifier_opt(state);
8524 /* type qualifier */
8525 specifiers |= type_qualifiers(state);
8527 /* type specifier */
8528 type = type_specifier(state, specifiers);
8532 static unsigned designator(struct compile_state *state)
8538 switch(peek(state)) {
8541 struct triple *value;
8542 eat(state, TOK_LBRACKET);
8543 value = constant_expr(state);
8544 eat(state, TOK_RBRACKET);
8545 index = value->u.cval;
8549 eat(state, TOK_DOT);
8550 eat(state, TOK_IDENT);
8551 error(state, 0, "Struct Designators not currently supported");
8554 error(state, 0, "Invalid designator");
8557 } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
8562 static struct triple *initializer(
8563 struct compile_state *state, struct type *type)
8565 struct triple *result;
8566 if (peek(state) != TOK_LBRACE) {
8567 result = assignment_expr(state);
8571 unsigned index, max_index;
8573 max_index = index = 0;
8574 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8575 max_index = type->elements;
8576 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
8580 error(state, 0, "Struct initializers not currently supported");
8582 buf = xcmalloc(size_of(state, type), "initializer");
8583 eat(state, TOK_LBRACE);
8585 struct triple *value;
8586 struct type *value_type;
8591 if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
8592 index = designator(state);
8594 if ((max_index != ELEMENT_COUNT_UNSPECIFIED) &&
8595 (index > max_index)) {
8596 error(state, 0, "element beyond bounds");
8599 if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
8600 value_type = type->left;
8602 value = eval_const_expr(state, initializer(state, value_type));
8603 value_size = size_of(state, value_type);
8604 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
8605 (max_index == ELEMENT_COUNT_UNSPECIFIED) &&
8606 (type->elements <= index)) {
8610 old_size = size_of(state, type);
8611 type->elements = index + 1;
8612 buf = xmalloc(size_of(state, type), "initializer");
8613 memcpy(buf, old_buf, old_size);
8616 if (value->op == OP_BLOBCONST) {
8617 memcpy((char *)buf + index * value_size, value->u.blob, value_size);
8619 else if ((value->op == OP_INTCONST) && (value_size == 1)) {
8620 *(((uint8_t *)buf) + index) = value->u.cval & 0xff;
8622 else if ((value->op == OP_INTCONST) && (value_size == 2)) {
8623 *(((uint16_t *)buf) + index) = value->u.cval & 0xffff;
8625 else if ((value->op == OP_INTCONST) && (value_size == 4)) {
8626 *(((uint32_t *)buf) + index) = value->u.cval & 0xffffffff;
8629 fprintf(stderr, "%d %d\n",
8630 value->op, value_size);
8631 internal_error(state, 0, "unhandled constant initializer");
8633 if (peek(state) == TOK_COMMA) {
8634 eat(state, TOK_COMMA);
8638 } while(comma && (peek(state) != TOK_RBRACE));
8639 eat(state, TOK_RBRACE);
8640 result = triple(state, OP_BLOBCONST, type, 0, 0);
8641 result->u.blob = buf;
8646 static struct triple *function_definition(
8647 struct compile_state *state, struct type *type)
8649 struct triple *def, *tmp, *first, *end;
8650 struct hash_entry *ident;
8653 if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
8654 error(state, 0, "Invalid function header");
8657 /* Verify the function type */
8658 if (((type->right->type & TYPE_MASK) != TYPE_VOID) &&
8659 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
8660 (type->right->field_ident == 0)) {
8661 error(state, 0, "Invalid function parameters");
8663 param = type->right;
8665 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8667 if (!param->left->field_ident) {
8668 error(state, 0, "No identifier for parameter %d\n", i);
8670 param = param->right;
8673 if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
8674 error(state, 0, "No identifier for paramter %d\n", i);
8677 /* Get a list of statements for this function. */
8678 def = triple(state, OP_LIST, type, 0, 0);
8680 /* Start a new scope for the passed parameters */
8683 /* Put a label at the very start of a function */
8684 first = label(state);
8685 RHS(def, 0) = first;
8687 /* Put a label at the very end of a function */
8689 flatten(state, first, end);
8691 /* Walk through the parameters and create symbol table entries
8694 param = type->right;
8695 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
8696 ident = param->left->field_ident;
8697 tmp = variable(state, param->left);
8698 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8699 flatten(state, end, tmp);
8700 param = param->right;
8702 if ((param->type & TYPE_MASK) != TYPE_VOID) {
8703 /* And don't forget the last parameter */
8704 ident = param->field_ident;
8705 tmp = variable(state, param);
8706 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
8707 flatten(state, end, tmp);
8709 /* Add a variable for the return value */
8711 if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
8712 /* Remove all type qualifiers from the return type */
8713 tmp = variable(state, clone_type(0, type->left));
8714 flatten(state, end, tmp);
8715 /* Remember where the return value is */
8719 /* Remember which function I am compiling.
8720 * Also assume the last defined function is the main function.
8722 state->main_function = def;
8724 /* Now get the actual function definition */
8725 compound_statement(state, end);
8727 /* Remove the parameter scope */
8730 fprintf(stdout, "\n");
8731 loc(stdout, state, 0);
8732 fprintf(stdout, "\n__________ function_definition _________\n");
8733 print_triple(state, def);
8734 fprintf(stdout, "__________ function_definition _________ done\n\n");
8740 static struct triple *do_decl(struct compile_state *state,
8741 struct type *type, struct hash_entry *ident)
8745 /* Clean up the storage types used */
8746 switch (type->type & STOR_MASK) {
8749 /* These are the good types I am aiming for */
8752 type->type &= ~STOR_MASK;
8753 type->type |= STOR_AUTO;
8756 type->type &= ~STOR_MASK;
8757 type->type |= STOR_STATIC;
8761 error(state, 0, "typedef without name");
8763 symbol(state, ident, &ident->sym_ident, 0, type);
8764 ident->tok = TOK_TYPE_NAME;
8768 internal_error(state, 0, "Undefined storage class");
8770 if (((type->type & STOR_MASK) == STOR_STATIC) &&
8771 ((type->type & QUAL_CONST) == 0)) {
8772 error(state, 0, "non const static variables not supported");
8775 def = variable(state, type);
8776 symbol(state, ident, &ident->sym_ident, def, type);
8781 static void decl(struct compile_state *state, struct triple *first)
8783 struct type *base_type, *type;
8784 struct hash_entry *ident;
8787 global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
8788 base_type = decl_specifiers(state);
8790 type = declarator(state, base_type, &ident, 0);
8791 if (global && ident && (peek(state) == TOK_LBRACE)) {
8793 def = function_definition(state, type);
8794 symbol(state, ident, &ident->sym_ident, def, type);
8798 flatten(state, first, do_decl(state, type, ident));
8799 /* type or variable definition */
8802 if (peek(state) == TOK_EQ) {
8804 error(state, 0, "cannot assign to a type");
8807 flatten(state, first,
8809 ident->sym_ident->def,
8810 initializer(state, type)));
8812 arrays_complete(state, type);
8813 if (peek(state) == TOK_COMMA) {
8814 eat(state, TOK_COMMA);
8816 type = declarator(state, base_type, &ident, 0);
8817 flatten(state, first, do_decl(state, type, ident));
8821 eat(state, TOK_SEMI);
8825 static void decls(struct compile_state *state)
8827 struct triple *list;
8829 list = label(state);
8832 if (tok == TOK_EOF) {
8835 if (tok == TOK_SPACE) {
8836 eat(state, TOK_SPACE);
8839 if (list->next != list) {
8840 error(state, 0, "global variables not supported");
8846 * Data structurs for optimation.
8849 static void do_use_block(
8850 struct block *used, struct block_set **head, struct block *user,
8853 struct block_set **ptr, *new;
8860 if ((*ptr)->member == user) {
8863 ptr = &(*ptr)->next;
8865 new = xcmalloc(sizeof(*new), "block_set");
8876 static void do_unuse_block(
8877 struct block *used, struct block_set **head, struct block *unuser)
8879 struct block_set *use, **ptr;
8883 if (use->member == unuser) {
8885 memset(use, -1, sizeof(*use));
8894 static void use_block(struct block *used, struct block *user)
8896 /* Append new to the head of the list, print_block
8899 do_use_block(used, &used->use, user, 1);
8902 static void unuse_block(struct block *used, struct block *unuser)
8904 do_unuse_block(used, &used->use, unuser);
8908 static void idom_block(struct block *idom, struct block *user)
8910 do_use_block(idom, &idom->idominates, user, 0);
8913 static void unidom_block(struct block *idom, struct block *unuser)
8915 do_unuse_block(idom, &idom->idominates, unuser);
8918 static void domf_block(struct block *block, struct block *domf)
8920 do_use_block(block, &block->domfrontier, domf, 0);
8923 static void undomf_block(struct block *block, struct block *undomf)
8925 do_unuse_block(block, &block->domfrontier, undomf);
8928 static void ipdom_block(struct block *ipdom, struct block *user)
8930 do_use_block(ipdom, &ipdom->ipdominates, user, 0);
8933 static void unipdom_block(struct block *ipdom, struct block *unuser)
8935 do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
8938 static void ipdomf_block(struct block *block, struct block *ipdomf)
8940 do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
8943 static void unipdomf_block(struct block *block, struct block *unipdomf)
8945 do_unuse_block(block, &block->ipdomfrontier, unipdomf);
8950 static int do_walk_triple(struct compile_state *state,
8951 struct triple *ptr, int depth,
8952 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8955 result = cb(state, ptr, depth);
8956 if ((result == 0) && (ptr->op == OP_LIST)) {
8957 struct triple *list;
8961 result = do_walk_triple(state, ptr, depth + 1, cb);
8962 if (ptr->next->prev != ptr) {
8963 internal_error(state, ptr->next, "bad prev");
8967 } while((result == 0) && (ptr != RHS(list, 0)));
8972 static int walk_triple(
8973 struct compile_state *state,
8975 int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
8977 return do_walk_triple(state, ptr, 0, cb);
8980 static void do_print_prefix(int depth)
8983 for(i = 0; i < depth; i++) {
8988 #define PRINT_LIST 1
8989 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
8993 if (op == OP_LIST) {
8998 if ((op == OP_LABEL) && (ins->use)) {
8999 printf("\n%p:\n", ins);
9001 do_print_prefix(depth);
9002 display_triple(stdout, ins);
9004 if ((ins->op == OP_BRANCH) && ins->use) {
9005 internal_error(state, ins, "branch used?");
9009 struct triple_set *user;
9010 for(user = ins->use; user; user = user->next) {
9011 printf("use: %p\n", user->member);
9015 if (triple_is_branch(state, ins)) {
9021 static void print_triple(struct compile_state *state, struct triple *ins)
9023 walk_triple(state, ins, do_print_triple);
9026 static void print_triples(struct compile_state *state)
9028 print_triple(state, state->main_function);
9032 struct block *block;
9034 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9036 if (!block || (cf[block->vertex].block == block)) {
9039 cf[block->vertex].block = block;
9040 find_cf_blocks(cf, block->left);
9041 find_cf_blocks(cf, block->right);
9044 static void print_control_flow(struct compile_state *state)
9046 struct cf_block *cf;
9048 printf("\ncontrol flow\n");
9049 cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9050 find_cf_blocks(cf, state->first_block);
9052 for(i = 1; i <= state->last_vertex; i++) {
9053 struct block *block;
9054 block = cf[i].block;
9057 printf("(%p) %d:", block, block->vertex);
9059 printf(" %d", block->left->vertex);
9061 if (block->right && (block->right != block->left)) {
9062 printf(" %d", block->right->vertex);
9071 static struct block *basic_block(struct compile_state *state,
9072 struct triple *first)
9074 struct block *block;
9077 if (first->op != OP_LABEL) {
9078 internal_error(state, 0, "block does not start with a label");
9080 /* See if this basic block has already been setup */
9081 if (first->u.block != 0) {
9082 return first->u.block;
9084 /* Allocate another basic block structure */
9085 state->last_vertex += 1;
9086 block = xcmalloc(sizeof(*block), "block");
9087 block->first = block->last = first;
9088 block->vertex = state->last_vertex;
9091 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9095 /* If ptr->u is not used remember where the baic block is */
9096 if (triple_stores_block(state, ptr)) {
9097 ptr->u.block = block;
9099 if (ptr->op == OP_BRANCH) {
9103 } while (ptr != RHS(state->main_function, 0));
9104 if (ptr == RHS(state->main_function, 0))
9107 if (op == OP_LABEL) {
9108 block->left = basic_block(state, ptr);
9110 use_block(block->left, block);
9112 else if (op == OP_BRANCH) {
9114 /* Trace the branch target */
9115 block->right = basic_block(state, TARG(ptr, 0));
9116 use_block(block->right, block);
9117 /* If there is a test trace the branch as well */
9118 if (TRIPLE_RHS(ptr->sizes)) {
9119 block->left = basic_block(state, ptr->next);
9120 use_block(block->left, block);
9124 internal_error(state, 0, "Bad basic block split");
9130 static void walk_blocks(struct compile_state *state,
9131 void (*cb)(struct compile_state *state, struct block *block, void *arg),
9134 struct triple *ptr, *first;
9135 struct block *last_block;
9137 first = RHS(state->main_function, 0);
9140 struct block *block;
9141 if (ptr->op == OP_LABEL) {
9142 block = ptr->u.block;
9143 if (block && (block != last_block)) {
9144 cb(state, block, arg);
9149 } while(ptr != first);
9152 static void print_block(
9153 struct compile_state *state, struct block *block, void *arg)
9158 fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n",
9162 block->left && block->left->use?block->left->use->member : 0,
9164 block->right && block->right->use?block->right->use->member : 0);
9165 if (block->first->op == OP_LABEL) {
9166 fprintf(fp, "%p:\n", block->first);
9168 for(ptr = block->first; ; ptr = ptr->next) {
9169 struct triple_set *user;
9172 if (triple_stores_block(state, ptr)) {
9173 if (ptr->u.block != block) {
9174 internal_error(state, ptr,
9175 "Wrong block pointer: %p\n",
9179 if (op == OP_ADECL) {
9180 for(user = ptr->use; user; user = user->next) {
9181 if (!user->member->u.block) {
9182 internal_error(state, user->member,
9183 "Use %p not in a block?\n",
9188 display_triple(fp, ptr);
9191 for(user = ptr->use; user; user = user->next) {
9192 fprintf(fp, "use: %p\n", user->member);
9196 /* Sanity checks... */
9197 valid_ins(state, ptr);
9198 for(user = ptr->use; user; user = user->next) {
9201 valid_ins(state, use);
9202 if (triple_stores_block(state, user->member) &&
9203 !user->member->u.block) {
9204 internal_error(state, user->member,
9205 "Use %p not in a block?",
9210 if (ptr == block->last)
9217 static void print_blocks(struct compile_state *state, FILE *fp)
9219 fprintf(fp, "--------------- blocks ---------------\n");
9220 walk_blocks(state, print_block, fp);
9223 static void prune_nonblock_triples(struct compile_state *state)
9225 struct block *block;
9226 struct triple *first, *ins, *next;
9227 /* Delete the triples not in a basic block */
9228 first = RHS(state->main_function, 0);
9233 if (ins->op == OP_LABEL) {
9234 block = ins->u.block;
9237 release_triple(state, ins);
9240 } while(ins != first);
9243 static void setup_basic_blocks(struct compile_state *state)
9245 if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9246 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9247 internal_error(state, 0, "ins will not store block?");
9249 /* Find the basic blocks */
9250 state->last_vertex = 0;
9251 state->first_block = basic_block(state, RHS(state->main_function,0));
9252 /* Delete the triples not in a basic block */
9253 prune_nonblock_triples(state);
9254 /* Find the last basic block */
9255 state->last_block = RHS(state->main_function, 0)->prev->u.block;
9256 if (!state->last_block) {
9257 internal_error(state, 0, "end not used?");
9259 /* Insert an extra unused edge from start to the end
9260 * This helps with reverse control flow calculations.
9262 use_block(state->first_block, state->last_block);
9263 /* If we are debugging print what I have just done */
9264 if (state->debug & DEBUG_BASIC_BLOCKS) {
9265 print_blocks(state, stdout);
9266 print_control_flow(state);
9270 static void free_basic_block(struct compile_state *state, struct block *block)
9272 struct block_set *entry, *next;
9273 struct block *child;
9277 if (block->vertex == -1) {
9282 unuse_block(block->left, block);
9285 unuse_block(block->right, block);
9288 unidom_block(block->idom, block);
9292 unipdom_block(block->ipdom, block);
9295 for(entry = block->use; entry; entry = next) {
9297 child = entry->member;
9298 unuse_block(block, child);
9299 if (child->left == block) {
9302 if (child->right == block) {
9306 for(entry = block->idominates; entry; entry = next) {
9308 child = entry->member;
9309 unidom_block(block, child);
9312 for(entry = block->domfrontier; entry; entry = next) {
9314 child = entry->member;
9315 undomf_block(block, child);
9317 for(entry = block->ipdominates; entry; entry = next) {
9319 child = entry->member;
9320 unipdom_block(block, child);
9323 for(entry = block->ipdomfrontier; entry; entry = next) {
9325 child = entry->member;
9326 unipdomf_block(block, child);
9328 if (block->users != 0) {
9329 internal_error(state, 0, "block still has users");
9331 free_basic_block(state, block->left);
9333 free_basic_block(state, block->right);
9335 memset(block, -1, sizeof(*block));
9339 static void free_basic_blocks(struct compile_state *state)
9341 struct triple *first, *ins;
9342 free_basic_block(state, state->first_block);
9343 state->last_vertex = 0;
9344 state->first_block = state->last_block = 0;
9345 first = RHS(state->main_function, 0);
9348 if (triple_stores_block(state, ins)) {
9352 } while(ins != first);
9357 struct block *block;
9358 struct sdom_block *sdominates;
9359 struct sdom_block *sdom_next;
9360 struct sdom_block *sdom;
9361 struct sdom_block *label;
9362 struct sdom_block *parent;
9363 struct sdom_block *ancestor;
9368 static void unsdom_block(struct sdom_block *block)
9370 struct sdom_block **ptr;
9371 if (!block->sdom_next) {
9374 ptr = &block->sdom->sdominates;
9376 if ((*ptr) == block) {
9377 *ptr = block->sdom_next;
9380 ptr = &(*ptr)->sdom_next;
9384 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9386 unsdom_block(block);
9388 block->sdom_next = sdom->sdominates;
9389 sdom->sdominates = block;
9394 static int initialize_sdblock(struct sdom_block *sd,
9395 struct block *parent, struct block *block, int vertex)
9397 if (!block || (sd[block->vertex].block == block)) {
9401 /* Renumber the blocks in a convinient fashion */
9402 block->vertex = vertex;
9403 sd[vertex].block = block;
9404 sd[vertex].sdom = &sd[vertex];
9405 sd[vertex].label = &sd[vertex];
9406 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9407 sd[vertex].ancestor = 0;
9408 sd[vertex].vertex = vertex;
9409 vertex = initialize_sdblock(sd, block, block->left, vertex);
9410 vertex = initialize_sdblock(sd, block, block->right, vertex);
9414 static int initialize_sdpblock(struct sdom_block *sd,
9415 struct block *parent, struct block *block, int vertex)
9417 struct block_set *user;
9418 if (!block || (sd[block->vertex].block == block)) {
9422 /* Renumber the blocks in a convinient fashion */
9423 block->vertex = vertex;
9424 sd[vertex].block = block;
9425 sd[vertex].sdom = &sd[vertex];
9426 sd[vertex].label = &sd[vertex];
9427 sd[vertex].parent = parent? &sd[parent->vertex] : 0;
9428 sd[vertex].ancestor = 0;
9429 sd[vertex].vertex = vertex;
9430 for(user = block->use; user; user = user->next) {
9431 vertex = initialize_sdpblock(sd, block, user->member, vertex);
9436 static void compress_ancestors(struct sdom_block *v)
9438 /* This procedure assumes ancestor(v) != 0 */
9439 /* if (ancestor(ancestor(v)) != 0) {
9440 * compress(ancestor(ancestor(v)));
9441 * if (semi(label(ancestor(v))) < semi(label(v))) {
9442 * label(v) = label(ancestor(v));
9444 * ancestor(v) = ancestor(ancestor(v));
9450 if (v->ancestor->ancestor) {
9451 compress_ancestors(v->ancestor->ancestor);
9452 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9453 v->label = v->ancestor->label;
9455 v->ancestor = v->ancestor->ancestor;
9459 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9463 * for each v <= pred(w) {
9465 * if (semi[u] < semi[w] {
9466 * semi[w] = semi[u];
9469 * add w to bucket(vertex(semi[w]));
9470 * LINK(parent(w), w);
9473 * for each v <= bucket(parent(w)) {
9474 * delete v from bucket(parent(w));
9476 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9479 for(i = state->last_vertex; i >= 2; i--) {
9480 struct sdom_block *v, *parent, *next;
9481 struct block_set *user;
9482 struct block *block;
9483 block = sd[i].block;
9484 parent = sd[i].parent;
9486 for(user = block->use; user; user = user->next) {
9487 struct sdom_block *v, *u;
9488 v = &sd[user->member->vertex];
9489 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9490 if (u->sdom->vertex < sd[i].sdom->vertex) {
9491 sd[i].sdom = u->sdom;
9494 sdom_block(sd[i].sdom, &sd[i]);
9495 sd[i].ancestor = parent;
9497 for(v = parent->sdominates; v; v = next) {
9498 struct sdom_block *u;
9499 next = v->sdom_next;
9501 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9502 v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
9503 u->block : parent->block;
9508 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
9512 * for each v <= pred(w) {
9514 * if (semi[u] < semi[w] {
9515 * semi[w] = semi[u];
9518 * add w to bucket(vertex(semi[w]));
9519 * LINK(parent(w), w);
9522 * for each v <= bucket(parent(w)) {
9523 * delete v from bucket(parent(w));
9525 * dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9528 for(i = state->last_vertex; i >= 2; i--) {
9529 struct sdom_block *u, *v, *parent, *next;
9530 struct block *block;
9531 block = sd[i].block;
9532 parent = sd[i].parent;
9535 v = &sd[block->left->vertex];
9536 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9537 if (u->sdom->vertex < sd[i].sdom->vertex) {
9538 sd[i].sdom = u->sdom;
9541 if (block->right && (block->right != block->left)) {
9542 v = &sd[block->right->vertex];
9543 u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
9544 if (u->sdom->vertex < sd[i].sdom->vertex) {
9545 sd[i].sdom = u->sdom;
9548 sdom_block(sd[i].sdom, &sd[i]);
9549 sd[i].ancestor = parent;
9551 for(v = parent->sdominates; v; v = next) {
9552 struct sdom_block *u;
9553 next = v->sdom_next;
9555 u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
9556 v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
9557 u->block : parent->block;
9562 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
9565 for(i = 2; i <= state->last_vertex; i++) {
9566 struct block *block;
9567 block = sd[i].block;
9568 if (block->idom->vertex != sd[i].sdom->vertex) {
9569 block->idom = block->idom->idom;
9571 idom_block(block->idom, block);
9573 sd[1].block->idom = 0;
9576 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
9579 for(i = 2; i <= state->last_vertex; i++) {
9580 struct block *block;
9581 block = sd[i].block;
9582 if (block->ipdom->vertex != sd[i].sdom->vertex) {
9583 block->ipdom = block->ipdom->ipdom;
9585 ipdom_block(block->ipdom, block);
9587 sd[1].block->ipdom = 0;
9591 * Every vertex of a flowgraph G = (V, E, r) except r has
9592 * a unique immediate dominator.
9593 * The edges {(idom(w), w) |w <= V - {r}} form a directed tree
9594 * rooted at r, called the dominator tree of G, such that
9595 * v dominates w if and only if v is a proper ancestor of w in
9596 * the dominator tree.
9599 * If v and w are vertices of G such that v <= w,
9600 * than any path from v to w must contain a common ancestor
9603 /* Lemma 2: For any vertex w != r, idom(w) -> w */
9604 /* Lemma 3: For any vertex w != r, sdom(w) -> w */
9605 /* Lemma 4: For any vertex w != r, idom(w) -> sdom(w) */
9607 * Let w != r. Suppose every u for which sdom(w) -> u -> w satisfies
9608 * sdom(u) >= sdom(w). Then idom(w) = sdom(w).
9611 * Let w != r and let u be a vertex for which sdom(u) is
9612 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9613 * Then sdom(u) <= sdom(w) and idom(u) = idom(w).
9615 /* Lemma 5: Let vertices v,w satisfy v -> w.
9616 * Then v -> idom(w) or idom(w) -> idom(v)
9619 static void find_immediate_dominators(struct compile_state *state)
9621 struct sdom_block *sd;
9622 /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
9623 * vi > w for (1 <= i <= k - 1}
9626 * For any vertex w != r.
9628 * {v|(v,w) <= E and v < w } U
9629 * {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
9632 * Let w != r and let u be a vertex for which sdom(u) is
9633 * minimum amoung vertices u satisfying sdom(w) -> u -> w.
9635 * { sdom(w) if sdom(w) = sdom(u),
9637 * { idom(u) otherwise
9639 /* The algorithm consists of the following 4 steps.
9640 * Step 1. Carry out a depth-first search of the problem graph.
9641 * Number the vertices from 1 to N as they are reached during
9642 * the search. Initialize the variables used in succeeding steps.
9643 * Step 2. Compute the semidominators of all vertices by applying
9644 * theorem 4. Carry out the computation vertex by vertex in
9645 * decreasing order by number.
9646 * Step 3. Implicitly define the immediate dominator of each vertex
9647 * by applying Corollary 1.
9648 * Step 4. Explicitly define the immediate dominator of each vertex,
9649 * carrying out the computation vertex by vertex in increasing order
9652 /* Step 1 initialize the basic block information */
9653 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9654 initialize_sdblock(sd, 0, state->first_block, 0);
9660 /* Step 2 compute the semidominators */
9661 /* Step 3 implicitly define the immediate dominator of each vertex */
9662 compute_sdom(state, sd);
9663 /* Step 4 explicitly define the immediate dominator of each vertex */
9664 compute_idom(state, sd);
9668 static void find_post_dominators(struct compile_state *state)
9670 struct sdom_block *sd;
9671 /* Step 1 initialize the basic block information */
9672 sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
9674 initialize_sdpblock(sd, 0, state->last_block, 0);
9676 /* Step 2 compute the semidominators */
9677 /* Step 3 implicitly define the immediate dominator of each vertex */
9678 compute_spdom(state, sd);
9679 /* Step 4 explicitly define the immediate dominator of each vertex */
9680 compute_ipdom(state, sd);
9686 static void find_block_domf(struct compile_state *state, struct block *block)
9688 struct block *child;
9689 struct block_set *user;
9690 if (block->domfrontier != 0) {
9691 internal_error(state, block->first, "domfrontier present?");
9693 for(user = block->idominates; user; user = user->next) {
9694 child = user->member;
9695 if (child->idom != block) {
9696 internal_error(state, block->first, "bad idom");
9698 find_block_domf(state, child);
9700 if (block->left && block->left->idom != block) {
9701 domf_block(block, block->left);
9703 if (block->right && block->right->idom != block) {
9704 domf_block(block, block->right);
9706 for(user = block->idominates; user; user = user->next) {
9707 struct block_set *frontier;
9708 child = user->member;
9709 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
9710 if (frontier->member->idom != block) {
9711 domf_block(block, frontier->member);
9717 static void find_block_ipdomf(struct compile_state *state, struct block *block)
9719 struct block *child;
9720 struct block_set *user;
9721 if (block->ipdomfrontier != 0) {
9722 internal_error(state, block->first, "ipdomfrontier present?");
9724 for(user = block->ipdominates; user; user = user->next) {
9725 child = user->member;
9726 if (child->ipdom != block) {
9727 internal_error(state, block->first, "bad ipdom");
9729 find_block_ipdomf(state, child);
9731 if (block->left && block->left->ipdom != block) {
9732 ipdomf_block(block, block->left);
9734 if (block->right && block->right->ipdom != block) {
9735 ipdomf_block(block, block->right);
9737 for(user = block->idominates; user; user = user->next) {
9738 struct block_set *frontier;
9739 child = user->member;
9740 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
9741 if (frontier->member->ipdom != block) {
9742 ipdomf_block(block, frontier->member);
9748 static void print_dominated(
9749 struct compile_state *state, struct block *block, void *arg)
9751 struct block_set *user;
9754 fprintf(fp, "%d:", block->vertex);
9755 for(user = block->idominates; user; user = user->next) {
9756 fprintf(fp, " %d", user->member->vertex);
9757 if (user->member->idom != block) {
9758 internal_error(state, user->member->first, "bad idom");
9764 static void print_dominators(struct compile_state *state, FILE *fp)
9766 fprintf(fp, "\ndominates\n");
9767 walk_blocks(state, print_dominated, fp);
9771 static int print_frontiers(
9772 struct compile_state *state, struct block *block, int vertex)
9774 struct block_set *user;
9776 if (!block || (block->vertex != vertex + 1)) {
9781 printf("%d:", block->vertex);
9782 for(user = block->domfrontier; user; user = user->next) {
9783 printf(" %d", user->member->vertex);
9787 vertex = print_frontiers(state, block->left, vertex);
9788 vertex = print_frontiers(state, block->right, vertex);
9791 static void print_dominance_frontiers(struct compile_state *state)
9793 printf("\ndominance frontiers\n");
9794 print_frontiers(state, state->first_block, 0);
9798 static void analyze_idominators(struct compile_state *state)
9800 /* Find the immediate dominators */
9801 find_immediate_dominators(state);
9802 /* Find the dominance frontiers */
9803 find_block_domf(state, state->first_block);
9804 /* If debuging print the print what I have just found */
9805 if (state->debug & DEBUG_FDOMINATORS) {
9806 print_dominators(state, stdout);
9807 print_dominance_frontiers(state);
9808 print_control_flow(state);
9814 static void print_ipdominated(
9815 struct compile_state *state, struct block *block, void *arg)
9817 struct block_set *user;
9820 fprintf(fp, "%d:", block->vertex);
9821 for(user = block->ipdominates; user; user = user->next) {
9822 fprintf(fp, " %d", user->member->vertex);
9823 if (user->member->ipdom != block) {
9824 internal_error(state, user->member->first, "bad ipdom");
9830 static void print_ipdominators(struct compile_state *state, FILE *fp)
9832 fprintf(fp, "\nipdominates\n");
9833 walk_blocks(state, print_ipdominated, fp);
9836 static int print_pfrontiers(
9837 struct compile_state *state, struct block *block, int vertex)
9839 struct block_set *user;
9841 if (!block || (block->vertex != vertex + 1)) {
9846 printf("%d:", block->vertex);
9847 for(user = block->ipdomfrontier; user; user = user->next) {
9848 printf(" %d", user->member->vertex);
9851 for(user = block->use; user; user = user->next) {
9852 vertex = print_pfrontiers(state, user->member, vertex);
9856 static void print_ipdominance_frontiers(struct compile_state *state)
9858 printf("\nipdominance frontiers\n");
9859 print_pfrontiers(state, state->last_block, 0);
9863 static void analyze_ipdominators(struct compile_state *state)
9865 /* Find the post dominators */
9866 find_post_dominators(state);
9867 /* Find the control dependencies (post dominance frontiers) */
9868 find_block_ipdomf(state, state->last_block);
9869 /* If debuging print the print what I have just found */
9870 if (state->debug & DEBUG_RDOMINATORS) {
9871 print_ipdominators(state, stdout);
9872 print_ipdominance_frontiers(state);
9873 print_control_flow(state);
9877 static int bdominates(struct compile_state *state,
9878 struct block *dom, struct block *sub)
9880 while(sub && (sub != dom)) {
9886 static int tdominates(struct compile_state *state,
9887 struct triple *dom, struct triple *sub)
9889 struct block *bdom, *bsub;
9891 bdom = block_of_triple(state, dom);
9892 bsub = block_of_triple(state, sub);
9894 result = bdominates(state, bdom, bsub);
9899 while((ins != bsub->first) && (ins != dom)) {
9902 result = (ins == dom);
9907 static void insert_phi_operations(struct compile_state *state)
9910 struct triple *first;
9911 int *has_already, *work;
9912 struct block *work_list, **work_list_tail;
9916 size = sizeof(int) * (state->last_vertex + 1);
9917 has_already = xcmalloc(size, "has_already");
9918 work = xcmalloc(size, "work");
9921 first = RHS(state->main_function, 0);
9922 for(var = first->next; var != first ; var = var->next) {
9923 struct block *block;
9924 struct triple_set *user;
9925 if ((var->op != OP_ADECL) || !var->use) {
9930 work_list_tail = &work_list;
9931 for(user = var->use; user; user = user->next) {
9932 if (user->member->op == OP_READ) {
9935 if (user->member->op != OP_WRITE) {
9936 internal_error(state, user->member,
9937 "bad variable access");
9939 block = user->member->u.block;
9941 warning(state, user->member, "dead code");
9943 if (work[block->vertex] >= iter) {
9946 work[block->vertex] = iter;
9947 *work_list_tail = block;
9948 block->work_next = 0;
9949 work_list_tail = &block->work_next;
9951 for(block = work_list; block; block = block->work_next) {
9952 struct block_set *df;
9953 for(df = block->domfrontier; df; df = df->next) {
9955 struct block *front;
9959 if (has_already[front->vertex] >= iter) {
9962 /* Count how many edges flow into this block */
9963 in_edges = front->users;
9964 /* Insert a phi function for this variable */
9966 state, OP_PHI, var->type, -1, in_edges,
9967 front->first->filename,
9970 phi->u.block = front;
9972 use_triple(var, phi);
9973 /* Insert the phi functions immediately after the label */
9974 insert_triple(state, front->first->next, phi);
9975 if (front->first == front->last) {
9976 front->last = front->first->next;
9978 has_already[front->vertex] = iter;
9980 /* If necessary plan to visit the basic block */
9981 if (work[front->vertex] >= iter) {
9984 work[front->vertex] = iter;
9985 *work_list_tail = front;
9986 front->work_next = 0;
9987 work_list_tail = &front->work_next;
9999 static void fixup_block_phi_variables(
10000 struct compile_state *state, struct block *parent, struct block *block)
10002 struct block_set *set;
10003 struct triple *ptr;
10005 if (!parent || !block)
10007 /* Find the edge I am coming in on */
10009 for(set = block->use; set; set = set->next, edge++) {
10010 if (set->member == parent) {
10015 internal_error(state, 0, "phi input is not on a control predecessor");
10017 for(ptr = block->first; ; ptr = ptr->next) {
10018 if (ptr->op == OP_PHI) {
10019 struct triple *var, *val, **slot;
10020 var = MISC(ptr, 0);
10022 internal_error(state, ptr, "no var???");
10024 /* Find the current value of the variable */
10025 val = var->use->member;
10026 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10027 internal_error(state, val, "bad value in phi");
10029 if (edge >= TRIPLE_RHS(ptr->sizes)) {
10030 internal_error(state, ptr, "edges > phi rhs");
10032 slot = &RHS(ptr, edge);
10033 if ((*slot != 0) && (*slot != val)) {
10034 internal_error(state, ptr, "phi already bound on this edge");
10037 use_triple(val, ptr);
10039 if (ptr == block->last) {
10046 static void rename_block_variables(
10047 struct compile_state *state, struct block *block)
10049 struct block_set *user;
10050 struct triple *ptr, *next, *last;
10054 last = block->first;
10056 for(ptr = block->first; !done; ptr = next) {
10058 if (ptr == block->last) {
10062 if (ptr->op == OP_READ) {
10063 struct triple *var, *val;
10065 unuse_triple(var, ptr);
10067 error(state, ptr, "variable used without being set");
10069 /* Find the current value of the variable */
10070 val = var->use->member;
10071 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10072 internal_error(state, val, "bad value in read");
10074 propogate_use(state, ptr, val);
10075 release_triple(state, ptr);
10079 if (ptr->op == OP_WRITE) {
10080 struct triple *var, *val;
10083 if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10084 internal_error(state, val, "bad value in write");
10086 propogate_use(state, ptr, val);
10087 unuse_triple(var, ptr);
10088 /* Push OP_WRITE ptr->right onto a stack of variable uses */
10089 push_triple(var, val);
10091 if (ptr->op == OP_PHI) {
10092 struct triple *var;
10093 var = MISC(ptr, 0);
10094 /* Push OP_PHI onto a stack of variable uses */
10095 push_triple(var, ptr);
10099 block->last = last;
10101 /* Fixup PHI functions in the cf successors */
10102 fixup_block_phi_variables(state, block, block->left);
10103 fixup_block_phi_variables(state, block, block->right);
10104 /* rename variables in the dominated nodes */
10105 for(user = block->idominates; user; user = user->next) {
10106 rename_block_variables(state, user->member);
10108 /* pop the renamed variable stack */
10109 last = block->first;
10111 for(ptr = block->first; !done ; ptr = next) {
10113 if (ptr == block->last) {
10116 if (ptr->op == OP_WRITE) {
10117 struct triple *var;
10119 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10120 pop_triple(var, RHS(ptr, 0));
10121 release_triple(state, ptr);
10124 if (ptr->op == OP_PHI) {
10125 struct triple *var;
10126 var = MISC(ptr, 0);
10127 /* Pop OP_WRITE ptr->right from the stack of variable uses */
10128 pop_triple(var, ptr);
10132 block->last = last;
10135 static void prune_block_variables(struct compile_state *state,
10136 struct block *block)
10138 struct block_set *user;
10139 struct triple *next, *last, *ptr;
10141 last = block->first;
10143 for(ptr = block->first; !done; ptr = next) {
10145 if (ptr == block->last) {
10148 if (ptr->op == OP_ADECL) {
10149 struct triple_set *user, *next;
10150 for(user = ptr->use; user; user = next) {
10151 struct triple *use;
10153 use = user->member;
10154 if (use->op != OP_PHI) {
10155 internal_error(state, use, "decl still used");
10157 if (MISC(use, 0) != ptr) {
10158 internal_error(state, use, "bad phi use of decl");
10160 unuse_triple(ptr, use);
10163 release_triple(state, ptr);
10168 block->last = last;
10169 for(user = block->idominates; user; user = user->next) {
10170 prune_block_variables(state, user->member);
10174 static void transform_to_ssa_form(struct compile_state *state)
10176 insert_phi_operations(state);
10178 printf("@%s:%d\n", __FILE__, __LINE__);
10179 print_blocks(state, stdout);
10181 rename_block_variables(state, state->first_block);
10182 prune_block_variables(state, state->first_block);
10186 static void clear_vertex(
10187 struct compile_state *state, struct block *block, void *arg)
10192 static void mark_live_block(
10193 struct compile_state *state, struct block *block, int *next_vertex)
10195 /* See if this is a block that has not been marked */
10196 if (block->vertex != 0) {
10199 block->vertex = *next_vertex;
10201 if (triple_is_branch(state, block->last)) {
10202 struct triple **targ;
10203 targ = triple_targ(state, block->last, 0);
10204 for(; targ; targ = triple_targ(state, block->last, targ)) {
10208 if (!triple_stores_block(state, *targ)) {
10209 internal_error(state, 0, "bad targ");
10211 mark_live_block(state, (*targ)->u.block, next_vertex);
10214 else if (block->last->next != RHS(state->main_function, 0)) {
10215 struct triple *ins;
10216 ins = block->last->next;
10217 if (!triple_stores_block(state, ins)) {
10218 internal_error(state, 0, "bad block start");
10220 mark_live_block(state, ins->u.block, next_vertex);
10224 static void transform_from_ssa_form(struct compile_state *state)
10226 /* To get out of ssa form we insert moves on the incoming
10227 * edges to blocks containting phi functions.
10229 struct triple *first;
10230 struct triple *phi, *next;
10233 /* Walk the control flow to see which blocks remain alive */
10234 walk_blocks(state, clear_vertex, 0);
10236 mark_live_block(state, state->first_block, &next_vertex);
10238 /* Walk all of the operations to find the phi functions */
10239 first = RHS(state->main_function, 0);
10240 for(phi = first->next; phi != first ; phi = next) {
10241 struct block_set *set;
10242 struct block *block;
10243 struct triple **slot;
10244 struct triple *var, *read;
10245 struct triple_set *use, *use_next;
10248 if (phi->op != OP_PHI) {
10251 block = phi->u.block;
10252 slot = &RHS(phi, 0);
10254 /* Forget uses from code in dead blocks */
10255 for(use = phi->use; use; use = use_next) {
10256 struct block *ublock;
10257 struct triple **expr;
10258 use_next = use->next;
10259 ublock = block_of_triple(state, use->member);
10260 if ((use->member == phi) || (ublock->vertex != 0)) {
10263 expr = triple_rhs(state, use->member, 0);
10264 for(; expr; expr = triple_rhs(state, use->member, expr)) {
10265 if (*expr == phi) {
10269 unuse_triple(phi, use->member);
10272 /* A variable to replace the phi function */
10273 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10274 /* A read of the single value that is set into the variable */
10275 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10276 use_triple(var, read);
10278 /* Replaces uses of the phi with variable reads */
10279 propogate_use(state, phi, read);
10281 /* Walk all of the incoming edges/blocks and insert moves.
10283 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10284 struct block *eblock;
10285 struct triple *move;
10286 struct triple *val;
10287 eblock = set->member;
10290 unuse_triple(val, phi);
10292 if (!val || (val == &zero_triple) ||
10293 (block->vertex == 0) || (eblock->vertex == 0) ||
10294 (val == phi) || (val == read)) {
10298 move = post_triple(state,
10299 val, OP_WRITE, phi->type, var, val);
10300 use_triple(val, move);
10301 use_triple(var, move);
10303 /* See if there are any writers of var */
10305 for(use = var->use; use; use = use->next) {
10306 struct triple **expr;
10307 expr = triple_lhs(state, use->member, 0);
10308 for(; expr; expr = triple_lhs(state, use->member, expr)) {
10309 if (*expr == var) {
10314 /* If var is not used free it */
10316 unuse_triple(var, read);
10317 free_triple(state, read);
10318 free_triple(state, var);
10321 /* Release the phi function */
10322 release_triple(state, phi);
10329 * Register conflict resolution
10330 * =========================================================
10333 static struct reg_info find_def_color(
10334 struct compile_state *state, struct triple *def)
10336 struct triple_set *set;
10337 struct reg_info info;
10338 info.reg = REG_UNSET;
10340 if (!triple_is_def(state, def)) {
10343 info = arch_reg_lhs(state, def, 0);
10344 if (info.reg >= MAX_REGISTERS) {
10345 info.reg = REG_UNSET;
10347 for(set = def->use; set; set = set->next) {
10348 struct reg_info tinfo;
10350 i = find_rhs_use(state, set->member, def);
10354 tinfo = arch_reg_rhs(state, set->member, i);
10355 if (tinfo.reg >= MAX_REGISTERS) {
10356 tinfo.reg = REG_UNSET;
10358 if ((tinfo.reg != REG_UNSET) &&
10359 (info.reg != REG_UNSET) &&
10360 (tinfo.reg != info.reg)) {
10361 internal_error(state, def, "register conflict");
10363 if ((info.regcm & tinfo.regcm) == 0) {
10364 internal_error(state, def, "regcm conflict %x & %x == 0",
10365 info.regcm, tinfo.regcm);
10367 if (info.reg == REG_UNSET) {
10368 info.reg = tinfo.reg;
10370 info.regcm &= tinfo.regcm;
10372 if (info.reg >= MAX_REGISTERS) {
10373 internal_error(state, def, "register out of range");
10378 static struct reg_info find_lhs_pre_color(
10379 struct compile_state *state, struct triple *ins, int index)
10381 struct reg_info info;
10383 zrhs = TRIPLE_RHS(ins->sizes);
10384 zlhs = TRIPLE_LHS(ins->sizes);
10385 if (!zlhs && triple_is_def(state, ins)) {
10388 if (index >= zlhs) {
10389 internal_error(state, ins, "Bad lhs %d", index);
10391 info = arch_reg_lhs(state, ins, index);
10392 for(i = 0; i < zrhs; i++) {
10393 struct reg_info rinfo;
10394 rinfo = arch_reg_rhs(state, ins, i);
10395 if ((info.reg == rinfo.reg) &&
10396 (rinfo.reg >= MAX_REGISTERS)) {
10397 struct reg_info tinfo;
10398 tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10399 info.reg = tinfo.reg;
10400 info.regcm &= tinfo.regcm;
10404 if (info.reg >= MAX_REGISTERS) {
10405 info.reg = REG_UNSET;
10410 static struct reg_info find_rhs_post_color(
10411 struct compile_state *state, struct triple *ins, int index);
10413 static struct reg_info find_lhs_post_color(
10414 struct compile_state *state, struct triple *ins, int index)
10416 struct triple_set *set;
10417 struct reg_info info;
10418 struct triple *lhs;
10420 fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10423 if ((index == 0) && triple_is_def(state, ins)) {
10426 else if (index < TRIPLE_LHS(ins->sizes)) {
10427 lhs = LHS(ins, index);
10430 internal_error(state, ins, "Bad lhs %d", index);
10433 info = arch_reg_lhs(state, ins, index);
10434 if (info.reg >= MAX_REGISTERS) {
10435 info.reg = REG_UNSET;
10437 for(set = lhs->use; set; set = set->next) {
10438 struct reg_info rinfo;
10439 struct triple *user;
10441 user = set->member;
10442 zrhs = TRIPLE_RHS(user->sizes);
10443 for(i = 0; i < zrhs; i++) {
10444 if (RHS(user, i) != lhs) {
10447 rinfo = find_rhs_post_color(state, user, i);
10448 if ((info.reg != REG_UNSET) &&
10449 (rinfo.reg != REG_UNSET) &&
10450 (info.reg != rinfo.reg)) {
10451 internal_error(state, ins, "register conflict");
10453 if ((info.regcm & rinfo.regcm) == 0) {
10454 internal_error(state, ins, "regcm conflict %x & %x == 0",
10455 info.regcm, rinfo.regcm);
10457 if (info.reg == REG_UNSET) {
10458 info.reg = rinfo.reg;
10460 info.regcm &= rinfo.regcm;
10464 fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
10465 ins, index, info.reg, info.regcm);
10470 static struct reg_info find_rhs_post_color(
10471 struct compile_state *state, struct triple *ins, int index)
10473 struct reg_info info, rinfo;
10476 fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
10479 rinfo = arch_reg_rhs(state, ins, index);
10480 zlhs = TRIPLE_LHS(ins->sizes);
10481 if (!zlhs && triple_is_def(state, ins)) {
10485 if (info.reg >= MAX_REGISTERS) {
10486 info.reg = REG_UNSET;
10488 for(i = 0; i < zlhs; i++) {
10489 struct reg_info linfo;
10490 linfo = arch_reg_lhs(state, ins, i);
10491 if ((linfo.reg == rinfo.reg) &&
10492 (linfo.reg >= MAX_REGISTERS)) {
10493 struct reg_info tinfo;
10494 tinfo = find_lhs_post_color(state, ins, i);
10495 if (tinfo.reg >= MAX_REGISTERS) {
10496 tinfo.reg = REG_UNSET;
10498 info.regcm &= linfo.reg;
10499 info.regcm &= tinfo.regcm;
10500 if (info.reg != REG_UNSET) {
10501 internal_error(state, ins, "register conflict");
10503 if (info.regcm == 0) {
10504 internal_error(state, ins, "regcm conflict");
10506 info.reg = tinfo.reg;
10510 fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
10511 ins, index, info.reg, info.regcm);
10516 static struct reg_info find_lhs_color(
10517 struct compile_state *state, struct triple *ins, int index)
10519 struct reg_info pre, post, info;
10521 fprintf(stderr, "find_lhs_color(%p, %d)\n",
10524 pre = find_lhs_pre_color(state, ins, index);
10525 post = find_lhs_post_color(state, ins, index);
10526 if ((pre.reg != post.reg) &&
10527 (pre.reg != REG_UNSET) &&
10528 (post.reg != REG_UNSET)) {
10529 internal_error(state, ins, "register conflict");
10531 info.regcm = pre.regcm & post.regcm;
10532 info.reg = pre.reg;
10533 if (info.reg == REG_UNSET) {
10534 info.reg = post.reg;
10537 fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x)\n",
10538 ins, index, info.reg, info.regcm);
10543 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
10545 struct triple_set *entry, *next;
10546 struct triple *out;
10547 struct reg_info info, rinfo;
10549 info = arch_reg_lhs(state, ins, 0);
10550 out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
10551 use_triple(RHS(out, 0), out);
10552 /* Get the users of ins to use out instead */
10553 for(entry = ins->use; entry; entry = next) {
10555 next = entry->next;
10556 if (entry->member == out) {
10559 i = find_rhs_use(state, entry->member, ins);
10563 rinfo = arch_reg_rhs(state, entry->member, i);
10564 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
10567 replace_rhs_use(state, ins, out, entry->member);
10569 transform_to_arch_instruction(state, out);
10573 static struct triple *pre_copy(
10574 struct compile_state *state, struct triple *ins, int index)
10576 /* Carefully insert enough operations so that I can
10577 * enter any operation with a GPR32.
10580 struct triple **expr;
10581 expr = &RHS(ins, index);
10582 in = pre_triple(state, ins, OP_COPY, (*expr)->type, *expr, 0);
10583 unuse_triple(*expr, ins);
10585 use_triple(RHS(in, 0), in);
10586 use_triple(in, ins);
10587 transform_to_arch_instruction(state, in);
10592 static void insert_copies_to_phi(struct compile_state *state)
10594 /* To get out of ssa form we insert moves on the incoming
10595 * edges to blocks containting phi functions.
10597 struct triple *first;
10598 struct triple *phi;
10600 /* Walk all of the operations to find the phi functions */
10601 first = RHS(state->main_function, 0);
10602 for(phi = first->next; phi != first ; phi = phi->next) {
10603 struct block_set *set;
10604 struct block *block;
10605 struct triple **slot;
10607 if (phi->op != OP_PHI) {
10610 phi->id |= TRIPLE_FLAG_POST_SPLIT;
10611 block = phi->u.block;
10612 slot = &RHS(phi, 0);
10613 /* Walk all of the incoming edges/blocks and insert moves.
10615 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10616 struct block *eblock;
10617 struct triple *move;
10618 struct triple *val;
10619 struct triple *ptr;
10620 eblock = set->member;
10627 move = build_triple(state, OP_COPY, phi->type, val, 0,
10628 val->filename, val->line, val->col);
10629 move->u.block = eblock;
10630 move->id |= TRIPLE_FLAG_PRE_SPLIT;
10631 use_triple(val, move);
10634 unuse_triple(val, phi);
10635 use_triple(move, phi);
10637 /* Walk through the block backwards to find
10638 * an appropriate location for the OP_COPY.
10640 for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
10641 struct triple **expr;
10642 if ((ptr == phi) || (ptr == val)) {
10645 expr = triple_rhs(state, ptr, 0);
10646 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10647 if ((*expr) == phi) {
10653 if (triple_is_branch(state, ptr)) {
10654 internal_error(state, ptr,
10655 "Could not insert write to phi");
10657 insert_triple(state, ptr->next, move);
10658 if (eblock->last == ptr) {
10659 eblock->last = move;
10661 transform_to_arch_instruction(state, move);
10666 struct triple_reg_set {
10667 struct triple_reg_set *next;
10668 struct triple *member;
10669 struct triple *new;
10673 struct block *block;
10674 struct triple_reg_set *in;
10675 struct triple_reg_set *out;
10679 static int do_triple_set(struct triple_reg_set **head,
10680 struct triple *member, struct triple *new_member)
10682 struct triple_reg_set **ptr, *new;
10687 if ((*ptr)->member == member) {
10690 ptr = &(*ptr)->next;
10692 new = xcmalloc(sizeof(*new), "triple_set");
10693 new->member = member;
10694 new->new = new_member;
10700 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
10702 struct triple_reg_set *entry, **ptr;
10706 if (entry->member == member) {
10707 *ptr = entry->next;
10712 ptr = &entry->next;
10717 static int in_triple(struct reg_block *rb, struct triple *in)
10719 return do_triple_set(&rb->in, in, 0);
10721 static void unin_triple(struct reg_block *rb, struct triple *unin)
10723 do_triple_unset(&rb->in, unin);
10726 static int out_triple(struct reg_block *rb, struct triple *out)
10728 return do_triple_set(&rb->out, out, 0);
10730 static void unout_triple(struct reg_block *rb, struct triple *unout)
10732 do_triple_unset(&rb->out, unout);
10735 static int initialize_regblock(struct reg_block *blocks,
10736 struct block *block, int vertex)
10738 struct block_set *user;
10739 if (!block || (blocks[block->vertex].block == block)) {
10743 /* Renumber the blocks in a convinient fashion */
10744 block->vertex = vertex;
10745 blocks[vertex].block = block;
10746 blocks[vertex].vertex = vertex;
10747 for(user = block->use; user; user = user->next) {
10748 vertex = initialize_regblock(blocks, user->member, vertex);
10753 static int phi_in(struct compile_state *state, struct reg_block *blocks,
10754 struct reg_block *rb, struct block *suc)
10756 /* Read the conditional input set of a successor block
10757 * (i.e. the input to the phi nodes) and place it in the
10758 * current blocks output set.
10760 struct block_set *set;
10761 struct triple *ptr;
10765 /* Find the edge I am coming in on */
10766 for(edge = 0, set = suc->use; set; set = set->next, edge++) {
10767 if (set->member == rb->block) {
10772 internal_error(state, 0, "Not coming on a control edge?");
10774 for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
10775 struct triple **slot, *expr, *ptr2;
10776 int out_change, done2;
10777 done = (ptr == suc->last);
10778 if (ptr->op != OP_PHI) {
10781 slot = &RHS(ptr, 0);
10783 out_change = out_triple(rb, expr);
10787 /* If we don't define the variable also plast it
10788 * in the current blocks input set.
10790 ptr2 = rb->block->first;
10791 for(done2 = 0; !done2; ptr2 = ptr2->next) {
10792 if (ptr2 == expr) {
10795 done2 = (ptr2 == rb->block->last);
10800 change |= in_triple(rb, expr);
10805 static int reg_in(struct compile_state *state, struct reg_block *blocks,
10806 struct reg_block *rb, struct block *suc)
10808 struct triple_reg_set *in_set;
10811 /* Read the input set of a successor block
10812 * and place it in the current blocks output set.
10814 in_set = blocks[suc->vertex].in;
10815 for(; in_set; in_set = in_set->next) {
10816 int out_change, done;
10817 struct triple *first, *last, *ptr;
10818 out_change = out_triple(rb, in_set->member);
10822 /* If we don't define the variable also place it
10823 * in the current blocks input set.
10825 first = rb->block->first;
10826 last = rb->block->last;
10828 for(ptr = first; !done; ptr = ptr->next) {
10829 if (ptr == in_set->member) {
10832 done = (ptr == last);
10837 change |= in_triple(rb, in_set->member);
10839 change |= phi_in(state, blocks, rb, suc);
10844 static int use_in(struct compile_state *state, struct reg_block *rb)
10846 /* Find the variables we use but don't define and add
10847 * it to the current blocks input set.
10849 #warning "FIXME is this O(N^2) algorithm bad?"
10850 struct block *block;
10851 struct triple *ptr;
10856 for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
10857 struct triple **expr;
10858 done = (ptr == block->first);
10859 /* The variable a phi function uses depends on the
10860 * control flow, and is handled in phi_in, not
10863 if (ptr->op == OP_PHI) {
10866 expr = triple_rhs(state, ptr, 0);
10867 for(;expr; expr = triple_rhs(state, ptr, expr)) {
10868 struct triple *rhs, *test;
10874 /* See if rhs is defined in this block */
10875 for(tdone = 0, test = ptr; !tdone; test = test->prev) {
10876 tdone = (test == block->first);
10882 /* If I still have a valid rhs add it to in */
10883 change |= in_triple(rb, rhs);
10889 static struct reg_block *compute_variable_lifetimes(
10890 struct compile_state *state)
10892 struct reg_block *blocks;
10895 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
10896 initialize_regblock(blocks, state->last_block, 0);
10900 for(i = 1; i <= state->last_vertex; i++) {
10901 struct reg_block *rb;
10903 /* Add the left successor's input set to in */
10904 if (rb->block->left) {
10905 change |= reg_in(state, blocks, rb, rb->block->left);
10907 /* Add the right successor's input set to in */
10908 if ((rb->block->right) &&
10909 (rb->block->right != rb->block->left)) {
10910 change |= reg_in(state, blocks, rb, rb->block->right);
10912 /* Add use to in... */
10913 change |= use_in(state, rb);
10919 static void free_variable_lifetimes(
10920 struct compile_state *state, struct reg_block *blocks)
10923 /* free in_set && out_set on each block */
10924 for(i = 1; i <= state->last_vertex; i++) {
10925 struct triple_reg_set *entry, *next;
10926 struct reg_block *rb;
10928 for(entry = rb->in; entry ; entry = next) {
10929 next = entry->next;
10930 do_triple_unset(&rb->in, entry->member);
10932 for(entry = rb->out; entry; entry = next) {
10933 next = entry->next;
10934 do_triple_unset(&rb->out, entry->member);
10941 typedef void (*wvl_cb_t)(
10942 struct compile_state *state,
10943 struct reg_block *blocks, struct triple_reg_set *live,
10944 struct reg_block *rb, struct triple *ins, void *arg);
10946 static void walk_variable_lifetimes(struct compile_state *state,
10947 struct reg_block *blocks, wvl_cb_t cb, void *arg)
10951 for(i = 1; i <= state->last_vertex; i++) {
10952 struct triple_reg_set *live;
10953 struct triple_reg_set *entry, *next;
10954 struct triple *ptr, *prev;
10955 struct reg_block *rb;
10956 struct block *block;
10959 /* Get the blocks */
10963 /* Copy out into live */
10965 for(entry = rb->out; entry; entry = next) {
10966 next = entry->next;
10967 do_triple_set(&live, entry->member, entry->new);
10969 /* Walk through the basic block calculating live */
10970 for(done = 0, ptr = block->last; !done; ptr = prev) {
10971 struct triple **expr;
10974 done = (ptr == block->first);
10976 /* Ensure the current definition is in live */
10977 if (triple_is_def(state, ptr)) {
10978 do_triple_set(&live, ptr, 0);
10981 /* Inform the callback function of what is
10984 cb(state, blocks, live, rb, ptr, arg);
10986 /* Remove the current definition from live */
10987 do_triple_unset(&live, ptr);
10989 /* Add the current uses to live.
10991 * It is safe to skip phi functions because they do
10992 * not have any block local uses, and the block
10993 * output sets already properly account for what
10994 * control flow depedent uses phi functions do have.
10996 if (ptr->op == OP_PHI) {
10999 expr = triple_rhs(state, ptr, 0);
11000 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11001 /* If the triple is not a definition skip it. */
11002 if (!*expr || !triple_is_def(state, *expr)) {
11005 do_triple_set(&live, *expr, 0);
11009 for(entry = live; entry; entry = next) {
11010 next = entry->next;
11011 do_triple_unset(&live, entry->member);
11016 static int count_triples(struct compile_state *state)
11018 struct triple *first, *ins;
11020 first = RHS(state->main_function, 0);
11025 } while (ins != first);
11028 struct dead_triple {
11029 struct triple *triple;
11030 struct dead_triple *work_next;
11031 struct block *block;
11034 #define TRIPLE_FLAG_ALIVE 1
11038 static void awaken(
11039 struct compile_state *state,
11040 struct dead_triple *dtriple, struct triple **expr,
11041 struct dead_triple ***work_list_tail)
11043 struct triple *triple;
11044 struct dead_triple *dt;
11052 if (triple->id <= 0) {
11053 internal_error(state, triple, "bad triple id: %d",
11056 if (triple->op == OP_NOOP) {
11057 internal_warning(state, triple, "awakening noop?");
11060 dt = &dtriple[triple->id];
11061 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11062 dt->flags |= TRIPLE_FLAG_ALIVE;
11063 if (!dt->work_next) {
11064 **work_list_tail = dt;
11065 *work_list_tail = &dt->work_next;
11070 static void eliminate_inefectual_code(struct compile_state *state)
11072 struct block *block;
11073 struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11075 struct triple *first, *ins;
11077 /* Setup the work list */
11079 work_list_tail = &work_list;
11081 first = RHS(state->main_function, 0);
11083 /* Count how many triples I have */
11084 triples = count_triples(state);
11086 /* Now put then in an array and mark all of the triples dead */
11087 dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11093 if (ins->op == OP_LABEL) {
11094 block = ins->u.block;
11096 dtriple[i].triple = ins;
11097 dtriple[i].block = block;
11098 dtriple[i].flags = 0;
11099 dtriple[i].color = ins->id;
11101 /* See if it is an operation we always keep */
11102 #warning "FIXME handle the case of killing a branch instruction"
11103 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11104 awaken(state, dtriple, &ins, &work_list_tail);
11108 } while(ins != first);
11110 struct dead_triple *dt;
11111 struct block_set *user;
11112 struct triple **expr;
11114 work_list = dt->work_next;
11116 work_list_tail = &work_list;
11118 /* Wake up the data depencencies of this triple */
11121 expr = triple_rhs(state, dt->triple, expr);
11122 awaken(state, dtriple, expr, &work_list_tail);
11125 expr = triple_lhs(state, dt->triple, expr);
11126 awaken(state, dtriple, expr, &work_list_tail);
11129 expr = triple_misc(state, dt->triple, expr);
11130 awaken(state, dtriple, expr, &work_list_tail);
11132 /* Wake up the forward control dependencies */
11134 expr = triple_targ(state, dt->triple, expr);
11135 awaken(state, dtriple, expr, &work_list_tail);
11137 /* Wake up the reverse control dependencies of this triple */
11138 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11139 awaken(state, dtriple, &user->member->last, &work_list_tail);
11142 for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11143 if ((dt->triple->op == OP_NOOP) &&
11144 (dt->flags & TRIPLE_FLAG_ALIVE)) {
11145 internal_error(state, dt->triple, "noop effective?");
11147 dt->triple->id = dt->color; /* Restore the color */
11148 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11149 #warning "FIXME handle the case of killing a basic block"
11150 if (dt->block->first == dt->triple) {
11153 if (dt->block->last == dt->triple) {
11154 dt->block->last = dt->triple->prev;
11156 release_triple(state, dt->triple);
11163 static void insert_mandatory_copies(struct compile_state *state)
11165 struct triple *ins, *first;
11167 /* The object is with a minimum of inserted copies,
11168 * to resolve in fundamental register conflicts between
11169 * register value producers and consumers.
11170 * Theoretically we may be greater than minimal when we
11171 * are inserting copies before instructions but that
11172 * case should be rare.
11174 first = RHS(state->main_function, 0);
11177 struct triple_set *entry, *next;
11178 struct triple *tmp;
11179 struct reg_info info;
11180 unsigned reg, regcm;
11181 int do_post_copy, do_pre_copy;
11183 if (!triple_is_def(state, ins)) {
11186 /* Find the architecture specific color information */
11187 info = arch_reg_lhs(state, ins, 0);
11188 if (info.reg >= MAX_REGISTERS) {
11189 info.reg = REG_UNSET;
11193 regcm = arch_type_to_regcm(state, ins->type);
11194 do_post_copy = do_pre_copy = 0;
11196 /* Walk through the uses of ins and check for conflicts */
11197 for(entry = ins->use; entry; entry = next) {
11198 struct reg_info rinfo;
11200 next = entry->next;
11201 i = find_rhs_use(state, entry->member, ins);
11206 /* Find the users color requirements */
11207 rinfo = arch_reg_rhs(state, entry->member, i);
11208 if (rinfo.reg >= MAX_REGISTERS) {
11209 rinfo.reg = REG_UNSET;
11212 /* See if I need a pre_copy */
11213 if (rinfo.reg != REG_UNSET) {
11214 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11219 regcm &= rinfo.regcm;
11220 regcm = arch_regcm_normalize(state, regcm);
11227 (((info.reg != REG_UNSET) &&
11228 (reg != REG_UNSET) &&
11229 (info.reg != reg)) ||
11230 ((info.regcm & regcm) == 0));
11233 regcm = info.regcm;
11234 /* Walk through the uses of insert and do a pre_copy or see if a post_copy is warranted */
11235 for(entry = ins->use; entry; entry = next) {
11236 struct reg_info rinfo;
11238 next = entry->next;
11239 i = find_rhs_use(state, entry->member, ins);
11244 /* Find the users color requirements */
11245 rinfo = arch_reg_rhs(state, entry->member, i);
11246 if (rinfo.reg >= MAX_REGISTERS) {
11247 rinfo.reg = REG_UNSET;
11250 /* Now see if it is time to do the pre_copy */
11251 if (rinfo.reg != REG_UNSET) {
11252 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11253 ((regcm & rinfo.regcm) == 0) ||
11254 /* Don't let a mandatory coalesce sneak
11255 * into a operation that is marked to prevent
11258 ((reg != REG_UNNEEDED) &&
11259 ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11260 (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11263 struct triple *user;
11264 user = entry->member;
11265 if (RHS(user, i) != ins) {
11266 internal_error(state, user, "bad rhs");
11268 tmp = pre_copy(state, user, i);
11276 if ((regcm & rinfo.regcm) == 0) {
11278 struct triple *user;
11279 user = entry->member;
11280 if (RHS(user, i) != ins) {
11281 internal_error(state, user, "bad rhs");
11283 tmp = pre_copy(state, user, i);
11289 regcm &= rinfo.regcm;
11292 if (do_post_copy) {
11293 struct reg_info pre, post;
11294 tmp = post_copy(state, ins);
11295 pre = arch_reg_lhs(state, ins, 0);
11296 post = arch_reg_lhs(state, tmp, 0);
11297 if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11298 internal_error(state, tmp, "useless copy");
11303 } while(ins != first);
11307 struct live_range_edge;
11308 struct live_range_def;
11309 struct live_range {
11310 struct live_range_edge *edges;
11311 struct live_range_def *defs;
11312 /* Note. The list pointed to by defs is kept in order.
11313 * That is baring splits in the flow control
11314 * defs dominates defs->next wich dominates defs->next->next
11321 struct live_range *group_next, **group_prev;
11324 struct live_range_edge {
11325 struct live_range_edge *next;
11326 struct live_range *node;
11329 struct live_range_def {
11330 struct live_range_def *next;
11331 struct live_range_def *prev;
11332 struct live_range *lr;
11333 struct triple *def;
11337 #define LRE_HASH_SIZE 2048
11339 struct lre_hash *next;
11340 struct live_range *left;
11341 struct live_range *right;
11346 struct lre_hash *hash[LRE_HASH_SIZE];
11347 struct reg_block *blocks;
11348 struct live_range_def *lrd;
11349 struct live_range *lr;
11350 struct live_range *low, **low_tail;
11351 struct live_range *high, **high_tail;
11354 int passes, max_passes;
11355 #define MAX_ALLOCATION_PASSES 100
11359 static unsigned regc_max_size(struct compile_state *state, int classes)
11364 for(i = 0; i < MAX_REGC; i++) {
11365 if (classes & (1 << i)) {
11367 size = arch_regc_size(state, i);
11368 if (size > max_size) {
11376 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
11378 unsigned equivs[MAX_REG_EQUIVS];
11380 if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
11381 internal_error(state, 0, "invalid register");
11383 if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
11384 internal_error(state, 0, "invalid register");
11386 arch_reg_equivs(state, equivs, reg1);
11387 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11388 if (equivs[i] == reg2) {
11395 static void reg_fill_used(struct compile_state *state, char *used, int reg)
11397 unsigned equivs[MAX_REG_EQUIVS];
11399 if (reg == REG_UNNEEDED) {
11402 arch_reg_equivs(state, equivs, reg);
11403 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11404 used[equivs[i]] = 1;
11409 static void reg_inc_used(struct compile_state *state, char *used, int reg)
11411 unsigned equivs[MAX_REG_EQUIVS];
11413 if (reg == REG_UNNEEDED) {
11416 arch_reg_equivs(state, equivs, reg);
11417 for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
11418 used[equivs[i]] += 1;
11423 static unsigned int hash_live_edge(
11424 struct live_range *left, struct live_range *right)
11426 unsigned int hash, val;
11427 unsigned long lval, rval;
11428 lval = ((unsigned long)left)/sizeof(struct live_range);
11429 rval = ((unsigned long)right)/sizeof(struct live_range);
11434 hash = (hash *263) + val;
11439 hash = (hash *263) + val;
11441 hash = hash & (LRE_HASH_SIZE - 1);
11445 static struct lre_hash **lre_probe(struct reg_state *rstate,
11446 struct live_range *left, struct live_range *right)
11448 struct lre_hash **ptr;
11449 unsigned int index;
11450 /* Ensure left <= right */
11451 if (left > right) {
11452 struct live_range *tmp;
11457 index = hash_live_edge(left, right);
11459 ptr = &rstate->hash[index];
11460 while((*ptr) && ((*ptr)->left != left) && ((*ptr)->right != right)) {
11461 ptr = &(*ptr)->next;
11466 static int interfere(struct reg_state *rstate,
11467 struct live_range *left, struct live_range *right)
11469 struct lre_hash **ptr;
11470 ptr = lre_probe(rstate, left, right);
11471 return ptr && *ptr;
11474 static void add_live_edge(struct reg_state *rstate,
11475 struct live_range *left, struct live_range *right)
11477 /* FIXME the memory allocation overhead is noticeable here... */
11478 struct lre_hash **ptr, *new_hash;
11479 struct live_range_edge *edge;
11481 if (left == right) {
11484 if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
11487 /* Ensure left <= right */
11488 if (left > right) {
11489 struct live_range *tmp;
11494 ptr = lre_probe(rstate, left, right);
11498 new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
11499 new_hash->next = *ptr;
11500 new_hash->left = left;
11501 new_hash->right = right;
11504 edge = xmalloc(sizeof(*edge), "live_range_edge");
11505 edge->next = left->edges;
11506 edge->node = right;
11507 left->edges = edge;
11510 edge = xmalloc(sizeof(*edge), "live_range_edge");
11511 edge->next = right->edges;
11513 right->edges = edge;
11514 right->degree += 1;
11517 static void remove_live_edge(struct reg_state *rstate,
11518 struct live_range *left, struct live_range *right)
11520 struct live_range_edge *edge, **ptr;
11521 struct lre_hash **hptr, *entry;
11522 hptr = lre_probe(rstate, left, right);
11523 if (!hptr || !*hptr) {
11527 *hptr = entry->next;
11530 for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
11532 if (edge->node == right) {
11534 memset(edge, 0, sizeof(*edge));
11539 for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
11541 if (edge->node == left) {
11543 memset(edge, 0, sizeof(*edge));
11550 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
11552 struct live_range_edge *edge, *next;
11553 for(edge = range->edges; edge; edge = next) {
11555 remove_live_edge(rstate, range, edge->node);
11560 /* Interference graph...
11562 * new(n) --- Return a graph with n nodes but no edges.
11563 * add(g,x,y) --- Return a graph including g with an between x and y
11564 * interfere(g, x, y) --- Return true if there exists an edge between the nodes
11565 * x and y in the graph g
11566 * degree(g, x) --- Return the degree of the node x in the graph g
11567 * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
11569 * Implement with a hash table && a set of adjcency vectors.
11570 * The hash table supports constant time implementations of add and interfere.
11571 * The adjacency vectors support an efficient implementation of neighbors.
11575 * +---------------------------------------------------+
11576 * | +--------------+ |
11578 * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
11580 * -- In simplify implment optimistic coloring... (No backtracking)
11581 * -- Implement Rematerialization it is the only form of spilling we can perform
11582 * Essentially this means dropping a constant from a register because
11583 * we can regenerate it later.
11585 * --- Very conservative colalescing (don't colalesce just mark the opportunities)
11586 * coalesce at phi points...
11587 * --- Bias coloring if at all possible do the coalesing a compile time.
11592 static void different_colored(
11593 struct compile_state *state, struct reg_state *rstate,
11594 struct triple *parent, struct triple *ins)
11596 struct live_range *lr;
11597 struct triple **expr;
11598 lr = rstate->lrd[ins->id].lr;
11599 expr = triple_rhs(state, ins, 0);
11600 for(;expr; expr = triple_rhs(state, ins, expr)) {
11601 struct live_range *lr2;
11602 if (!*expr || (*expr == parent) || (*expr == ins)) {
11605 lr2 = rstate->lrd[(*expr)->id].lr;
11606 if (lr->color == lr2->color) {
11607 internal_error(state, ins, "live range too big");
11613 static struct live_range *coalesce_ranges(
11614 struct compile_state *state, struct reg_state *rstate,
11615 struct live_range *lr1, struct live_range *lr2)
11617 struct live_range_def *head, *mid1, *mid2, *end, *lrd;
11623 if (!lr1->defs || !lr2->defs) {
11624 internal_error(state, 0,
11625 "cannot coalese dead live ranges");
11627 if ((lr1->color == REG_UNNEEDED) ||
11628 (lr2->color == REG_UNNEEDED)) {
11629 internal_error(state, 0,
11630 "cannot coalesce live ranges without a possible color");
11632 if ((lr1->color != lr2->color) &&
11633 (lr1->color != REG_UNSET) &&
11634 (lr2->color != REG_UNSET)) {
11635 internal_error(state, lr1->defs->def,
11636 "cannot coalesce live ranges of different colors");
11638 color = lr1->color;
11639 if (color == REG_UNSET) {
11640 color = lr2->color;
11642 classes = lr1->classes & lr2->classes;
11644 internal_error(state, lr1->defs->def,
11645 "cannot coalesce live ranges with dissimilar register classes");
11647 /* If there is a clear dominate live range put it in lr1,
11648 * For purposes of this test phi functions are
11649 * considered dominated by the definitions that feed into
11652 if ((lr1->defs->prev->def->op == OP_PHI) ||
11653 ((lr2->defs->prev->def->op != OP_PHI) &&
11654 tdominates(state, lr2->defs->def, lr1->defs->def))) {
11655 struct live_range *tmp;
11661 if (lr1->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11662 fprintf(stderr, "lr1 post\n");
11664 if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11665 fprintf(stderr, "lr1 pre\n");
11667 if (lr2->defs->orig_id & TRIPLE_FLAG_POST_SPLIT) {
11668 fprintf(stderr, "lr2 post\n");
11670 if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
11671 fprintf(stderr, "lr2 pre\n");
11675 fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
11682 lr1->classes = classes;
11683 /* Append lr2 onto lr1 */
11684 #warning "FIXME should this be a merge instead of a splice?"
11686 mid1 = lr1->defs->prev;
11688 end = lr2->defs->prev;
11696 /* Fixup the live range in the added live range defs */
11701 } while(lrd != head);
11703 /* Mark lr2 as free. */
11705 lr2->color = REG_UNNEEDED;
11709 internal_error(state, 0, "lr1->defs == 0 ?");
11712 lr1->color = color;
11713 lr1->classes = classes;
11718 static struct live_range_def *live_range_head(
11719 struct compile_state *state, struct live_range *lr,
11720 struct live_range_def *last)
11722 struct live_range_def *result;
11727 else if (!tdominates(state, lr->defs->def, last->next->def)) {
11728 result = last->next;
11733 static struct live_range_def *live_range_end(
11734 struct compile_state *state, struct live_range *lr,
11735 struct live_range_def *last)
11737 struct live_range_def *result;
11740 result = lr->defs->prev;
11742 else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
11743 result = last->prev;
11749 static void initialize_live_ranges(
11750 struct compile_state *state, struct reg_state *rstate)
11752 struct triple *ins, *first;
11753 size_t count, size;
11756 first = RHS(state->main_function, 0);
11757 /* First count how many instructions I have.
11759 count = count_triples(state);
11760 /* Potentially I need one live range definitions for each
11761 * instruction, plus an extra for the split routines.
11763 rstate->defs = count + 1;
11764 /* Potentially I need one live range for each instruction
11765 * plus an extra for the dummy live range.
11767 rstate->ranges = count + 1;
11768 size = sizeof(rstate->lrd[0]) * rstate->defs;
11769 rstate->lrd = xcmalloc(size, "live_range_def");
11770 size = sizeof(rstate->lr[0]) * rstate->ranges;
11771 rstate->lr = xcmalloc(size, "live_range");
11773 /* Setup the dummy live range */
11774 rstate->lr[0].classes = 0;
11775 rstate->lr[0].color = REG_UNSET;
11776 rstate->lr[0].defs = 0;
11780 /* If the triple is a variable give it a live range */
11781 if (triple_is_def(state, ins)) {
11782 struct reg_info info;
11783 /* Find the architecture specific color information */
11784 info = find_def_color(state, ins);
11787 rstate->lr[i].defs = &rstate->lrd[j];
11788 rstate->lr[i].color = info.reg;
11789 rstate->lr[i].classes = info.regcm;
11790 rstate->lr[i].degree = 0;
11791 rstate->lrd[j].lr = &rstate->lr[i];
11793 /* Otherwise give the triple the dummy live range. */
11795 rstate->lrd[j].lr = &rstate->lr[0];
11798 /* Initalize the live_range_def */
11799 rstate->lrd[j].next = &rstate->lrd[j];
11800 rstate->lrd[j].prev = &rstate->lrd[j];
11801 rstate->lrd[j].def = ins;
11802 rstate->lrd[j].orig_id = ins->id;
11807 } while(ins != first);
11808 rstate->ranges = i;
11811 /* Make a second pass to handle achitecture specific register
11816 int zlhs, zrhs, i, j;
11817 if (ins->id > rstate->defs) {
11818 internal_error(state, ins, "bad id");
11821 /* Walk through the template of ins and coalesce live ranges */
11822 zlhs = TRIPLE_LHS(ins->sizes);
11823 if ((zlhs == 0) && triple_is_def(state, ins)) {
11826 zrhs = TRIPLE_RHS(ins->sizes);
11828 for(i = 0; i < zlhs; i++) {
11829 struct reg_info linfo;
11830 struct live_range_def *lhs;
11831 linfo = arch_reg_lhs(state, ins, i);
11832 if (linfo.reg < MAX_REGISTERS) {
11835 if (triple_is_def(state, ins)) {
11836 lhs = &rstate->lrd[ins->id];
11838 lhs = &rstate->lrd[LHS(ins, i)->id];
11840 for(j = 0; j < zrhs; j++) {
11841 struct reg_info rinfo;
11842 struct live_range_def *rhs;
11843 rinfo = arch_reg_rhs(state, ins, j);
11844 if (rinfo.reg < MAX_REGISTERS) {
11847 rhs = &rstate->lrd[RHS(ins, i)->id];
11848 if (rinfo.reg == linfo.reg) {
11849 coalesce_ranges(state, rstate,
11855 } while(ins != first);
11858 static void graph_ins(
11859 struct compile_state *state,
11860 struct reg_block *blocks, struct triple_reg_set *live,
11861 struct reg_block *rb, struct triple *ins, void *arg)
11863 struct reg_state *rstate = arg;
11864 struct live_range *def;
11865 struct triple_reg_set *entry;
11867 /* If the triple is not a definition
11868 * we do not have a definition to add to
11869 * the interference graph.
11871 if (!triple_is_def(state, ins)) {
11874 def = rstate->lrd[ins->id].lr;
11876 /* Create an edge between ins and everything that is
11877 * alive, unless the live_range cannot share
11878 * a physical register with ins.
11880 for(entry = live; entry; entry = entry->next) {
11881 struct live_range *lr;
11882 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
11883 internal_error(state, 0, "bad entry?");
11885 lr = rstate->lrd[entry->member->id].lr;
11889 if (!arch_regcm_intersect(def->classes, lr->classes)) {
11892 add_live_edge(rstate, def, lr);
11898 static void print_interference_ins(
11899 struct compile_state *state,
11900 struct reg_block *blocks, struct triple_reg_set *live,
11901 struct reg_block *rb, struct triple *ins, void *arg)
11903 struct reg_state *rstate = arg;
11904 struct live_range *lr;
11906 lr = rstate->lrd[ins->id].lr;
11907 display_triple(stdout, ins);
11910 struct live_range_def *lrd;
11914 printf(" %-10p", lrd->def);
11916 } while(lrd != lr->defs);
11920 struct triple_reg_set *entry;
11922 for(entry = live; entry; entry = entry->next) {
11923 printf(" %-10p", entry->member);
11928 struct live_range_edge *entry;
11930 for(entry = lr->edges; entry; entry = entry->next) {
11931 struct live_range_def *lrd;
11932 lrd = entry->node->defs;
11934 printf(" %-10p", lrd->def);
11936 } while(lrd != entry->node->defs);
11941 if (triple_is_branch(state, ins)) {
11947 static int coalesce_live_ranges(
11948 struct compile_state *state, struct reg_state *rstate)
11950 /* At the point where a value is moved from one
11951 * register to another that value requires two
11952 * registers, thus increasing register pressure.
11953 * Live range coaleescing reduces the register
11954 * pressure by keeping a value in one register
11957 * In the case of a phi function all paths leading
11958 * into it must be allocated to the same register
11959 * otherwise the phi function may not be removed.
11961 * Forcing a value to stay in a single register
11962 * for an extended period of time does have
11963 * limitations when applied to non homogenous
11966 * The two cases I have identified are:
11967 * 1) Two forced register assignments may
11969 * 2) Registers may go unused because they
11970 * are only good for storing the value
11971 * and not manipulating it.
11973 * Because of this I need to split live ranges,
11974 * even outside of the context of coalesced live
11975 * ranges. The need to split live ranges does
11976 * impose some constraints on live range coalescing.
11978 * - Live ranges may not be coalesced across phi
11979 * functions. This creates a 2 headed live
11980 * range that cannot be sanely split.
11982 * - phi functions (coalesced in initialize_live_ranges)
11983 * are handled as pre split live ranges so we will
11984 * never attempt to split them.
11990 for(i = 0; i <= rstate->ranges; i++) {
11991 struct live_range *lr1;
11992 struct live_range_def *lrd1;
11993 lr1 = &rstate->lr[i];
11997 lrd1 = live_range_end(state, lr1, 0);
11998 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
11999 struct triple_set *set;
12000 if (lrd1->def->op != OP_COPY) {
12003 /* Skip copies that are the result of a live range split. */
12004 if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12007 for(set = lrd1->def->use; set; set = set->next) {
12008 struct live_range_def *lrd2;
12009 struct live_range *lr2, *res;
12011 lrd2 = &rstate->lrd[set->member->id];
12013 /* Don't coalesce with instructions
12014 * that are the result of a live range
12017 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12020 lr2 = rstate->lrd[set->member->id].lr;
12024 if ((lr1->color != lr2->color) &&
12025 (lr1->color != REG_UNSET) &&
12026 (lr2->color != REG_UNSET)) {
12029 if ((lr1->classes & lr2->classes) == 0) {
12033 if (interfere(rstate, lr1, lr2)) {
12037 res = coalesce_ranges(state, rstate, lr1, lr2);
12051 static void fix_coalesce_conflicts(struct compile_state *state,
12052 struct reg_block *blocks, struct triple_reg_set *live,
12053 struct reg_block *rb, struct triple *ins, void *arg)
12055 int zlhs, zrhs, i, j;
12057 /* See if we have a mandatory coalesce operation between
12058 * a lhs and a rhs value. If so and the rhs value is also
12059 * alive then this triple needs to be pre copied. Otherwise
12060 * we would have two definitions in the same live range simultaneously
12063 zlhs = TRIPLE_LHS(ins->sizes);
12064 if ((zlhs == 0) && triple_is_def(state, ins)) {
12067 zrhs = TRIPLE_RHS(ins->sizes);
12068 for(i = 0; i < zlhs; i++) {
12069 struct reg_info linfo;
12070 linfo = arch_reg_lhs(state, ins, i);
12071 if (linfo.reg < MAX_REGISTERS) {
12074 for(j = 0; j < zrhs; j++) {
12075 struct reg_info rinfo;
12076 struct triple *rhs;
12077 struct triple_reg_set *set;
12080 rinfo = arch_reg_rhs(state, ins, j);
12081 if (rinfo.reg != linfo.reg) {
12085 for(set = live; set && !found; set = set->next) {
12086 if (set->member == rhs) {
12091 struct triple *copy;
12092 copy = pre_copy(state, ins, j);
12093 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12100 static void replace_set_use(struct compile_state *state,
12101 struct triple_reg_set *head, struct triple *orig, struct triple *new)
12103 struct triple_reg_set *set;
12104 for(set = head; set; set = set->next) {
12105 if (set->member == orig) {
12111 static void replace_block_use(struct compile_state *state,
12112 struct reg_block *blocks, struct triple *orig, struct triple *new)
12115 #warning "WISHLIST visit just those blocks that need it *"
12116 for(i = 1; i <= state->last_vertex; i++) {
12117 struct reg_block *rb;
12119 replace_set_use(state, rb->in, orig, new);
12120 replace_set_use(state, rb->out, orig, new);
12124 static void color_instructions(struct compile_state *state)
12126 struct triple *ins, *first;
12127 first = RHS(state->main_function, 0);
12130 if (triple_is_def(state, ins)) {
12131 struct reg_info info;
12132 info = find_lhs_color(state, ins, 0);
12133 if (info.reg >= MAX_REGISTERS) {
12134 info.reg = REG_UNSET;
12136 SET_INFO(ins->id, info);
12139 } while(ins != first);
12142 static struct reg_info read_lhs_color(
12143 struct compile_state *state, struct triple *ins, int index)
12145 struct reg_info info;
12146 if ((index == 0) && triple_is_def(state, ins)) {
12147 info.reg = ID_REG(ins->id);
12148 info.regcm = ID_REGCM(ins->id);
12150 else if (index < TRIPLE_LHS(ins->sizes)) {
12151 info = read_lhs_color(state, LHS(ins, index), 0);
12154 internal_error(state, ins, "Bad lhs %d", index);
12155 info.reg = REG_UNSET;
12161 static struct triple *resolve_tangle(
12162 struct compile_state *state, struct triple *tangle)
12164 struct reg_info info, uinfo;
12165 struct triple_set *set, *next;
12166 struct triple *copy;
12168 #warning "WISHLIST recalculate all affected instructions colors"
12169 info = find_lhs_color(state, tangle, 0);
12170 for(set = tangle->use; set; set = next) {
12171 struct triple *user;
12174 user = set->member;
12175 zrhs = TRIPLE_RHS(user->sizes);
12176 for(i = 0; i < zrhs; i++) {
12177 if (RHS(user, i) != tangle) {
12180 uinfo = find_rhs_post_color(state, user, i);
12181 if (uinfo.reg == info.reg) {
12182 copy = pre_copy(state, user, i);
12183 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12184 SET_INFO(copy->id, uinfo);
12189 uinfo = find_lhs_pre_color(state, tangle, 0);
12190 if (uinfo.reg == info.reg) {
12191 struct reg_info linfo;
12192 copy = post_copy(state, tangle);
12193 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12194 linfo = find_lhs_color(state, copy, 0);
12195 SET_INFO(copy->id, linfo);
12197 info = find_lhs_color(state, tangle, 0);
12198 SET_INFO(tangle->id, info);
12204 static void fix_tangles(struct compile_state *state,
12205 struct reg_block *blocks, struct triple_reg_set *live,
12206 struct reg_block *rb, struct triple *ins, void *arg)
12208 struct triple *tangle;
12210 char used[MAX_REGISTERS];
12211 struct triple_reg_set *set;
12214 /* Find out which registers have multiple uses at this point */
12215 memset(used, 0, sizeof(used));
12216 for(set = live; set; set = set->next) {
12217 struct reg_info info;
12218 info = read_lhs_color(state, set->member, 0);
12219 if (info.reg == REG_UNSET) {
12222 reg_inc_used(state, used, info.reg);
12225 /* Now find the least dominated definition of a register in
12226 * conflict I have seen so far.
12228 for(set = live; set; set = set->next) {
12229 struct reg_info info;
12230 info = read_lhs_color(state, set->member, 0);
12231 if (used[info.reg] < 2) {
12234 if (!tangle || tdominates(state, set->member, tangle)) {
12235 tangle = set->member;
12238 /* If I have found a tangle resolve it */
12240 struct triple *post_copy;
12241 post_copy = resolve_tangle(state, tangle);
12243 replace_block_use(state, blocks, tangle, post_copy);
12245 if (post_copy && (tangle != ins)) {
12246 replace_set_use(state, live, tangle, post_copy);
12253 static void correct_tangles(
12254 struct compile_state *state, struct reg_block *blocks)
12256 color_instructions(state);
12257 walk_variable_lifetimes(state, blocks, fix_tangles, 0);
12260 struct least_conflict {
12261 struct reg_state *rstate;
12262 struct live_range *ref_range;
12263 struct triple *ins;
12264 struct triple_reg_set *live;
12268 static void least_conflict(struct compile_state *state,
12269 struct reg_block *blocks, struct triple_reg_set *live,
12270 struct reg_block *rb, struct triple *ins, void *arg)
12272 struct least_conflict *conflict = arg;
12273 struct live_range_edge *edge;
12274 struct triple_reg_set *set;
12278 #warning "FIXME handle instructions with left hand sides..."
12279 /* Only instructions that introduce a new definition
12280 * can be the conflict instruction.
12282 if (!triple_is_def(state, ins)) {
12286 /* See if live ranges at this instruction are a
12287 * strict subset of the live ranges that are in conflict.
12290 for(set = live; set; set = set->next) {
12291 struct live_range *lr;
12292 lr = conflict->rstate->lrd[set->member->id].lr;
12293 /* Ignore it if there cannot be an edge between these two nodes */
12294 if (!arch_regcm_intersect(conflict->ref_range->classes, lr->classes)) {
12297 for(edge = conflict->ref_range->edges; edge; edge = edge->next) {
12298 if (edge->node == lr) {
12302 if (!edge && (lr != conflict->ref_range)) {
12312 /* See if there is an uncolored member in this subset.
12314 for(set = live; set; set = set->next) {
12315 struct live_range *lr;
12316 lr = conflict->rstate->lrd[set->member->id].lr;
12317 if (lr->color == REG_UNSET) {
12321 if (!set && (conflict->ref_range != REG_UNSET)) {
12326 /* See if any of the live registers are constrained,
12327 * if not it won't be productive to pick this as
12328 * a conflict instruction.
12331 for(set = live; set; set = set->next) {
12332 struct triple_set *uset;
12333 struct reg_info info;
12335 unsigned cur_size, size;
12336 /* Skip this instruction */
12337 if (set->member == ins) {
12340 /* Find how many registers this value can potentially
12343 classes = arch_type_to_regcm(state, set->member->type);
12344 size = regc_max_size(state, classes);
12346 /* Find how many registers we allow this value to
12349 info = arch_reg_lhs(state, set->member, 0);
12351 /* If the value does not live in a register it
12352 * isn't constrained.
12354 if (info.reg == REG_UNNEEDED) {
12358 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12359 cur_size = regc_max_size(state, info.regcm);
12364 /* If there is no difference between potential and
12365 * actual register count there is not a constraint
12367 if (cur_size >= size) {
12371 /* If this live_range feeds into conflict->inds
12372 * it isn't a constraint we can relieve.
12374 for(uset = set->member->use; uset; uset = uset->next) {
12375 if (uset->member == ins) {
12385 /* Don't drop canidates with constraints */
12386 if (conflict->constraints && !constraints) {
12392 fprintf(stderr, "conflict ins? %p %s count: %d constraints: %d\n",
12393 ins, tops(ins->op), count, constraints);
12395 /* Find the instruction with the largest possible subset of
12396 * conflict ranges and that dominates any other instruction
12397 * with an equal sized set of conflicting ranges.
12399 if ((count > conflict->count) ||
12400 ((count == conflict->count) &&
12401 tdominates(state, ins, conflict->ins))) {
12402 struct triple_reg_set *next;
12403 /* Remember the canidate instruction */
12404 conflict->ins = ins;
12405 conflict->count = count;
12406 conflict->constraints = constraints;
12407 /* Free the old collection of live registers */
12408 for(set = conflict->live; set; set = next) {
12410 do_triple_unset(&conflict->live, set->member);
12412 conflict->live = 0;
12413 /* Rember the registers that are alive but do not feed
12414 * into or out of conflict->ins.
12416 for(set = live; set; set = set->next) {
12417 struct triple **expr;
12418 if (set->member == ins) {
12421 expr = triple_rhs(state, ins, 0);
12422 for(;expr; expr = triple_rhs(state, ins, expr)) {
12423 if (*expr == set->member) {
12427 expr = triple_lhs(state, ins, 0);
12428 for(; expr; expr = triple_lhs(state, ins, expr)) {
12429 if (*expr == set->member) {
12433 do_triple_set(&conflict->live, set->member, set->new);
12441 static void find_range_conflict(struct compile_state *state,
12442 struct reg_state *rstate, char *used, struct live_range *ref_range,
12443 struct least_conflict *conflict)
12446 /* there are 3 kinds ways conflicts can occure.
12447 * 1) the life time of 2 values simply overlap.
12448 * 2) the 2 values feed into the same instruction.
12449 * 3) the 2 values feed into a phi function.
12452 /* find the instruction where the problematic conflict comes
12453 * into existance. that the instruction where all of
12454 * the values are alive, and among such instructions it is
12455 * the least dominated one.
12457 * a value is alive an an instruction if either;
12458 * 1) the value defintion dominates the instruction and there
12459 * is a use at or after that instrction
12460 * 2) the value definition feeds into a phi function in the
12461 * same block as the instruction. and the phi function
12462 * is at or after the instruction.
12464 memset(conflict, 0, sizeof(*conflict));
12465 conflict->rstate = rstate;
12466 conflict->ref_range = ref_range;
12468 conflict->live = 0;
12469 conflict->count = 0;
12470 conflict->constraints = 0;
12471 walk_variable_lifetimes(state, rstate->blocks, least_conflict, conflict);
12473 if (!conflict->ins) {
12474 internal_error(state, ref_range->defs->def, "No conflict ins?");
12476 if (!conflict->live) {
12477 internal_error(state, ref_range->defs->def, "No conflict live?");
12480 fprintf(stderr, "conflict ins: %p %s count: %d constraints: %d\n",
12481 conflict->ins, tops(conflict->ins->op),
12482 conflict->count, conflict->constraints);
12487 static struct triple *split_constrained_range(struct compile_state *state,
12488 struct reg_state *rstate, char *used, struct least_conflict *conflict)
12490 unsigned constrained_size;
12491 struct triple *new, *constrained;
12492 struct triple_reg_set *cset;
12493 /* Find a range that is having problems because it is
12494 * artificially constrained.
12496 constrained_size = ~0;
12499 for(cset = conflict->live; cset; cset = cset->next) {
12500 struct triple_set *set;
12501 struct reg_info info;
12503 unsigned cur_size, size;
12504 /* Skip the live range that starts with conflict->ins */
12505 if (cset->member == conflict->ins) {
12508 /* Find how many registers this value can potentially
12511 classes = arch_type_to_regcm(state, cset->member->type);
12512 size = regc_max_size(state, classes);
12514 /* Find how many registers we allow this value to
12517 info = arch_reg_lhs(state, cset->member, 0);
12519 /* If the register doesn't need a register
12520 * splitting it can't help.
12522 if (info.reg == REG_UNNEEDED) {
12525 #warning "FIXME do I need a call to arch_reg_rhs around here somewhere?"
12526 if ((info.reg == REG_UNSET) || (info.reg >= MAX_REGISTERS)) {
12527 cur_size = regc_max_size(state, info.regcm);
12531 /* If this live_range feeds into conflict->ins
12532 * splitting it is unlikely to help.
12534 for(set = cset->member->use; set; set = set->next) {
12535 if (set->member == conflict->ins) {
12540 /* If there is no difference between potential and
12541 * actual register count there is nothing to do.
12543 if (cur_size >= size) {
12546 /* Of the constrained registers deal with the
12547 * most constrained one first.
12549 if (!constrained ||
12550 (size < constrained_size)) {
12551 constrained = cset->member;
12552 constrained_size = size;
12558 new = post_copy(state, constrained);
12559 new->id |= TRIPLE_FLAG_POST_SPLIT;
12564 static int split_ranges(
12565 struct compile_state *state, struct reg_state *rstate,
12566 char *used, struct live_range *range)
12568 struct triple *new;
12571 fprintf(stderr, "split_ranges %d %s %p\n",
12572 rstate->passes, tops(range->defs->def->op), range->defs->def);
12574 if ((range->color == REG_UNNEEDED) ||
12575 (rstate->passes >= rstate->max_passes)) {
12579 /* If I can't allocate a register something needs to be split */
12580 if (arch_select_free_register(state, used, range->classes) == REG_UNSET) {
12581 struct least_conflict conflict;
12584 fprintf(stderr, "find_range_conflict\n");
12586 /* Find where in the set of registers the conflict
12589 find_range_conflict(state, rstate, used, range, &conflict);
12591 /* If a range has been artifically constrained split it */
12592 new = split_constrained_range(state, rstate, used, &conflict);
12595 /* Ideally I would split the live range that will not be used
12596 * for the longest period of time in hopes that this will
12597 * (a) allow me to spill a register or
12598 * (b) allow me to place a value in another register.
12600 * So far I don't have a test case for this, the resolving
12601 * of mandatory constraints has solved all of my
12602 * know issues. So I have choosen not to write any
12603 * code until I cat get a better feel for cases where
12604 * it would be useful to have.
12607 #warning "WISHLIST implement live range splitting..."
12609 print_blocks(state, stderr);
12610 print_dominators(state, stderr);
12617 rstate->lrd[rstate->defs].orig_id = new->id;
12618 new->id = rstate->defs;
12621 fprintf(stderr, "new: %p old: %s %p\n",
12622 new, tops(RHS(new, 0)->op), RHS(new, 0));
12625 print_blocks(state, stderr);
12626 print_dominators(state, stderr);
12634 #if DEBUG_COLOR_GRAPH > 1
12635 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
12636 #define cgdebug_flush() fflush(stdout)
12637 #elif DEBUG_COLOR_GRAPH == 1
12638 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
12639 #define cgdebug_flush() fflush(stderr)
12641 #define cgdebug_printf(...)
12642 #define cgdebug_flush()
12646 static int select_free_color(struct compile_state *state,
12647 struct reg_state *rstate, struct live_range *range)
12649 struct triple_set *entry;
12650 struct live_range_def *lrd;
12651 struct live_range_def *phi;
12652 struct live_range_edge *edge;
12653 char used[MAX_REGISTERS];
12654 struct triple **expr;
12656 /* Instead of doing just the trivial color select here I try
12657 * a few extra things because a good color selection will help reduce
12661 /* Find the registers currently in use */
12662 memset(used, 0, sizeof(used));
12663 for(edge = range->edges; edge; edge = edge->next) {
12664 if (edge->node->color == REG_UNSET) {
12667 reg_fill_used(state, used, edge->node->color);
12669 #if DEBUG_COLOR_GRAPH > 1
12673 for(edge = range->edges; edge; edge = edge->next) {
12676 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n",
12677 tops(range->def->op), i,
12678 range->def->filename, range->def->line, range->def->col);
12679 for(i = 0; i < MAX_REGISTERS; i++) {
12681 cgdebug_printf("used: %s\n",
12688 #warning "FIXME detect conflicts caused by the source and destination being the same register"
12690 /* If a color is already assigned see if it will work */
12691 if (range->color != REG_UNSET) {
12692 struct live_range_def *lrd;
12693 if (!used[range->color]) {
12696 for(edge = range->edges; edge; edge = edge->next) {
12697 if (edge->node->color != range->color) {
12700 warning(state, edge->node->defs->def, "edge: ");
12701 lrd = edge->node->defs;
12703 warning(state, lrd->def, " %p %s",
12704 lrd->def, tops(lrd->def->op));
12706 } while(lrd != edge->node->defs);
12709 warning(state, range->defs->def, "def: ");
12711 warning(state, lrd->def, " %p %s",
12712 lrd->def, tops(lrd->def->op));
12714 } while(lrd != range->defs);
12715 internal_error(state, range->defs->def,
12716 "live range with already used color %s",
12717 arch_reg_str(range->color));
12720 /* If I feed into an expression reuse it's color.
12721 * This should help remove copies in the case of 2 register instructions
12722 * and phi functions.
12725 lrd = live_range_end(state, range, 0);
12726 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
12727 entry = lrd->def->use;
12728 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
12729 struct live_range_def *insd;
12730 insd = &rstate->lrd[entry->member->id];
12731 if (insd->lr->defs == 0) {
12734 if (!phi && (insd->def->op == OP_PHI) &&
12735 !interfere(rstate, range, insd->lr)) {
12738 if ((insd->lr->color == REG_UNSET) ||
12739 ((insd->lr->classes & range->classes) == 0) ||
12740 (used[insd->lr->color])) {
12743 if (interfere(rstate, range, insd->lr)) {
12746 range->color = insd->lr->color;
12749 /* If I feed into a phi function reuse it's color or the color
12750 * of something else that feeds into the phi function.
12753 if (phi->lr->color != REG_UNSET) {
12754 if (used[phi->lr->color]) {
12755 range->color = phi->lr->color;
12759 expr = triple_rhs(state, phi->def, 0);
12760 for(; expr; expr = triple_rhs(state, phi->def, expr)) {
12761 struct live_range *lr;
12765 lr = rstate->lrd[(*expr)->id].lr;
12766 if ((lr->color == REG_UNSET) ||
12767 ((lr->classes & range->classes) == 0) ||
12768 (used[lr->color])) {
12771 if (interfere(rstate, range, lr)) {
12774 range->color = lr->color;
12778 /* If I don't interfere with a rhs node reuse it's color */
12779 lrd = live_range_head(state, range, 0);
12780 for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
12781 expr = triple_rhs(state, lrd->def, 0);
12782 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
12783 struct live_range *lr;
12787 lr = rstate->lrd[(*expr)->id].lr;
12788 if ((lr->color == -1) ||
12789 ((lr->classes & range->classes) == 0) ||
12790 (used[lr->color])) {
12793 if (interfere(rstate, range, lr)) {
12796 range->color = lr->color;
12800 /* If I have not opportunitically picked a useful color
12801 * pick the first color that is free.
12803 if (range->color == REG_UNSET) {
12805 arch_select_free_register(state, used, range->classes);
12807 if (range->color == REG_UNSET) {
12808 struct live_range_def *lrd;
12810 if (split_ranges(state, rstate, used, range)) {
12813 for(edge = range->edges; edge; edge = edge->next) {
12814 warning(state, edge->node->defs->def, "edge reg %s",
12815 arch_reg_str(edge->node->color));
12816 lrd = edge->node->defs;
12818 warning(state, lrd->def, " %s",
12819 tops(lrd->def->op));
12821 } while(lrd != edge->node->defs);
12823 warning(state, range->defs->def, "range: ");
12826 warning(state, lrd->def, " %s",
12827 tops(lrd->def->op));
12829 } while(lrd != range->defs);
12831 warning(state, range->defs->def, "classes: %x",
12833 for(i = 0; i < MAX_REGISTERS; i++) {
12835 warning(state, range->defs->def, "used: %s",
12839 #if DEBUG_COLOR_GRAPH < 2
12840 error(state, range->defs->def, "too few registers");
12842 internal_error(state, range->defs->def, "too few registers");
12845 range->classes = arch_reg_regcm(state, range->color);
12846 if (range->color == -1) {
12847 internal_error(state, range->defs->def, "select_free_color did not?");
12852 static int color_graph(struct compile_state *state, struct reg_state *rstate)
12855 struct live_range_edge *edge;
12856 struct live_range *range;
12858 cgdebug_printf("Lo: ");
12859 range = rstate->low;
12860 if (*range->group_prev != range) {
12861 internal_error(state, 0, "lo: *prev != range?");
12863 *range->group_prev = range->group_next;
12864 if (range->group_next) {
12865 range->group_next->group_prev = range->group_prev;
12867 if (&range->group_next == rstate->low_tail) {
12868 rstate->low_tail = range->group_prev;
12870 if (rstate->low == range) {
12871 internal_error(state, 0, "low: next != prev?");
12874 else if (rstate->high) {
12875 cgdebug_printf("Hi: ");
12876 range = rstate->high;
12877 if (*range->group_prev != range) {
12878 internal_error(state, 0, "hi: *prev != range?");
12880 *range->group_prev = range->group_next;
12881 if (range->group_next) {
12882 range->group_next->group_prev = range->group_prev;
12884 if (&range->group_next == rstate->high_tail) {
12885 rstate->high_tail = range->group_prev;
12887 if (rstate->high == range) {
12888 internal_error(state, 0, "high: next != prev?");
12894 cgdebug_printf(" %d\n", range - rstate->lr);
12895 range->group_prev = 0;
12896 for(edge = range->edges; edge; edge = edge->next) {
12897 struct live_range *node;
12899 /* Move nodes from the high to the low list */
12900 if (node->group_prev && (node->color == REG_UNSET) &&
12901 (node->degree == regc_max_size(state, node->classes))) {
12902 if (*node->group_prev != node) {
12903 internal_error(state, 0, "move: *prev != node?");
12905 *node->group_prev = node->group_next;
12906 if (node->group_next) {
12907 node->group_next->group_prev = node->group_prev;
12909 if (&node->group_next == rstate->high_tail) {
12910 rstate->high_tail = node->group_prev;
12912 cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
12913 node->group_prev = rstate->low_tail;
12914 node->group_next = 0;
12915 *rstate->low_tail = node;
12916 rstate->low_tail = &node->group_next;
12917 if (*node->group_prev != node) {
12918 internal_error(state, 0, "move2: *prev != node?");
12923 colored = color_graph(state, rstate);
12925 cgdebug_printf("Coloring %d @%s:%d.%d:",
12926 range - rstate->lr,
12927 range->def->filename, range->def->line, range->def->col);
12929 colored = select_free_color(state, rstate, range);
12930 cgdebug_printf(" %s\n", arch_reg_str(range->color));
12935 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
12937 struct live_range *lr;
12938 struct live_range_edge *edge;
12939 struct triple *ins, *first;
12940 char used[MAX_REGISTERS];
12941 first = RHS(state->main_function, 0);
12944 if (triple_is_def(state, ins)) {
12945 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12946 internal_error(state, ins,
12947 "triple without a live range def");
12949 lr = rstate->lrd[ins->id].lr;
12950 if (lr->color == REG_UNSET) {
12951 internal_error(state, ins,
12952 "triple without a color");
12954 /* Find the registers used by the edges */
12955 memset(used, 0, sizeof(used));
12956 for(edge = lr->edges; edge; edge = edge->next) {
12957 if (edge->node->color == REG_UNSET) {
12958 internal_error(state, 0,
12959 "live range without a color");
12961 reg_fill_used(state, used, edge->node->color);
12963 if (used[lr->color]) {
12964 internal_error(state, ins,
12965 "triple with already used color");
12969 } while(ins != first);
12972 static void color_triples(struct compile_state *state, struct reg_state *rstate)
12974 struct live_range *lr;
12975 struct triple *first, *ins;
12976 first = RHS(state->main_function, 0);
12979 if ((ins->id < 0) || (ins->id > rstate->defs)) {
12980 internal_error(state, ins,
12981 "triple without a live range");
12983 lr = rstate->lrd[ins->id].lr;
12984 SET_REG(ins->id, lr->color);
12986 } while (ins != first);
12989 static void print_interference_block(
12990 struct compile_state *state, struct block *block, void *arg)
12993 struct reg_state *rstate = arg;
12994 struct reg_block *rb;
12995 struct triple *ptr;
12998 rb = &rstate->blocks[block->vertex];
13000 printf("\nblock: %p (%d), %p<-%p %p<-%p\n",
13004 block->left && block->left->use?block->left->use->member : 0,
13006 block->right && block->right->use?block->right->use->member : 0);
13008 struct triple_reg_set *in_set;
13010 for(in_set = rb->in; in_set; in_set = in_set->next) {
13011 printf(" %-10p", in_set->member);
13016 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13017 done = (ptr == block->last);
13018 if (ptr->op == OP_PHI) {
13025 for(edge = 0; edge < block->users; edge++) {
13026 printf(" in(%d):", edge);
13027 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13028 struct triple **slot;
13029 done = (ptr == block->last);
13030 if (ptr->op != OP_PHI) {
13033 slot = &RHS(ptr, 0);
13034 printf(" %-10p", slot[edge]);
13039 if (block->first->op == OP_LABEL) {
13040 printf("%p:\n", block->first);
13042 for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
13043 struct triple_set *user;
13044 struct live_range *lr;
13048 done = (ptr == block->last);
13049 lr = rstate->lrd[ptr->id].lr;
13051 if (triple_stores_block(state, ptr)) {
13052 if (ptr->u.block != block) {
13053 internal_error(state, ptr,
13054 "Wrong block pointer: %p",
13058 if (op == OP_ADECL) {
13059 for(user = ptr->use; user; user = user->next) {
13060 if (!user->member->u.block) {
13061 internal_error(state, user->member,
13062 "Use %p not in a block?",
13069 SET_REG(ptr->id, lr->color);
13070 display_triple(stdout, ptr);
13073 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
13074 internal_error(state, ptr, "lr has no defs!");
13078 struct live_range_def *lrd;
13082 printf(" %-10p", lrd->def);
13084 } while(lrd != lr->defs);
13087 if (lr->edges > 0) {
13088 struct live_range_edge *edge;
13090 for(edge = lr->edges; edge; edge = edge->next) {
13091 struct live_range_def *lrd;
13092 lrd = edge->node->defs;
13094 printf(" %-10p", lrd->def);
13096 } while(lrd != edge->node->defs);
13101 /* Do a bunch of sanity checks */
13102 valid_ins(state, ptr);
13103 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
13104 internal_error(state, ptr, "Invalid triple id: %d",
13107 for(user = ptr->use; user; user = user->next) {
13108 struct triple *use;
13109 struct live_range *ulr;
13110 use = user->member;
13111 valid_ins(state, use);
13112 if ((use->id < 0) || (use->id > rstate->defs)) {
13113 internal_error(state, use, "Invalid triple id: %d",
13116 ulr = rstate->lrd[user->member->id].lr;
13117 if (triple_stores_block(state, user->member) &&
13118 !user->member->u.block) {
13119 internal_error(state, user->member,
13120 "Use %p not in a block?",
13126 struct triple_reg_set *out_set;
13128 for(out_set = rb->out; out_set; out_set = out_set->next) {
13129 printf(" %-10p", out_set->member);
13136 static struct live_range *merge_sort_lr(
13137 struct live_range *first, struct live_range *last)
13139 struct live_range *mid, *join, **join_tail, *pick;
13141 size = (last - first) + 1;
13143 mid = first + size/2;
13144 first = merge_sort_lr(first, mid -1);
13145 mid = merge_sort_lr(mid, last);
13149 /* merge the two lists */
13150 while(first && mid) {
13151 if ((first->degree < mid->degree) ||
13152 ((first->degree == mid->degree) &&
13153 (first->length < mid->length))) {
13155 first = first->group_next;
13157 first->group_prev = 0;
13162 mid = mid->group_next;
13164 mid->group_prev = 0;
13167 pick->group_next = 0;
13168 pick->group_prev = join_tail;
13170 join_tail = &pick->group_next;
13172 /* Splice the remaining list */
13173 pick = (first)? first : mid;
13176 pick->group_prev = join_tail;
13180 if (!first->defs) {
13188 static void ids_from_rstate(struct compile_state *state,
13189 struct reg_state *rstate)
13191 struct triple *ins, *first;
13192 if (!rstate->defs) {
13195 /* Display the graph if desired */
13196 if (state->debug & DEBUG_INTERFERENCE) {
13197 print_blocks(state, stdout);
13198 print_control_flow(state);
13200 first = RHS(state->main_function, 0);
13204 struct live_range_def *lrd;
13205 lrd = &rstate->lrd[ins->id];
13206 ins->id = lrd->orig_id;
13209 } while(ins != first);
13212 static void cleanup_live_edges(struct reg_state *rstate)
13215 /* Free the edges on each node */
13216 for(i = 1; i <= rstate->ranges; i++) {
13217 remove_live_edges(rstate, &rstate->lr[i]);
13221 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13223 cleanup_live_edges(rstate);
13224 xfree(rstate->lrd);
13227 /* Free the variable lifetime information */
13228 if (rstate->blocks) {
13229 free_variable_lifetimes(state, rstate->blocks);
13232 rstate->ranges = 0;
13235 rstate->blocks = 0;
13238 static void allocate_registers(struct compile_state *state)
13240 struct reg_state rstate;
13243 /* Clear out the reg_state */
13244 memset(&rstate, 0, sizeof(rstate));
13245 rstate.max_passes = MAX_ALLOCATION_PASSES;
13248 struct live_range **point, **next;
13252 ids_from_rstate(state, &rstate);
13254 /* Cleanup the temporary data structures */
13255 cleanup_rstate(state, &rstate);
13257 /* Compute the variable lifetimes */
13258 rstate.blocks = compute_variable_lifetimes(state);
13260 /* Fix invalid mandatory live range coalesce conflicts */
13261 walk_variable_lifetimes(
13262 state, rstate.blocks, fix_coalesce_conflicts, 0);
13264 /* Fix two simultaneous uses of the same register */
13265 correct_tangles(state, rstate.blocks);
13267 if (state->debug & DEBUG_INSERTED_COPIES) {
13268 printf("After resolve_tangles\n");
13269 print_blocks(state, stdout);
13270 print_control_flow(state);
13274 /* Allocate and initialize the live ranges */
13275 initialize_live_ranges(state, &rstate);
13278 /* Forget previous live range edge calculations */
13279 cleanup_live_edges(&rstate);
13281 /* Compute the interference graph */
13282 walk_variable_lifetimes(
13283 state, rstate.blocks, graph_ins, &rstate);
13285 /* Display the interference graph if desired */
13286 if (state->debug & DEBUG_INTERFERENCE) {
13287 printf("\nlive variables by block\n");
13288 walk_blocks(state, print_interference_block, &rstate);
13289 printf("\nlive variables by instruction\n");
13290 walk_variable_lifetimes(
13291 state, rstate.blocks,
13292 print_interference_ins, &rstate);
13295 coalesced = coalesce_live_ranges(state, &rstate);
13296 } while(coalesced);
13298 /* Build the groups low and high. But with the nodes
13299 * first sorted by degree order.
13301 rstate.low_tail = &rstate.low;
13302 rstate.high_tail = &rstate.high;
13303 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13305 rstate.high->group_prev = &rstate.high;
13307 for(point = &rstate.high; *point; point = &(*point)->group_next)
13309 rstate.high_tail = point;
13310 /* Walk through the high list and move everything that needs
13313 for(point = &rstate.high; *point; point = next) {
13314 struct live_range *range;
13315 next = &(*point)->group_next;
13318 /* If it has a low degree or it already has a color
13319 * place the node in low.
13321 if ((range->degree < regc_max_size(state, range->classes)) ||
13322 (range->color != REG_UNSET)) {
13323 cgdebug_printf("Lo: %5d degree %5d%s\n",
13324 range - rstate.lr, range->degree,
13325 (range->color != REG_UNSET) ? " (colored)": "");
13326 *range->group_prev = range->group_next;
13327 if (range->group_next) {
13328 range->group_next->group_prev = range->group_prev;
13330 if (&range->group_next == rstate.high_tail) {
13331 rstate.high_tail = range->group_prev;
13333 range->group_prev = rstate.low_tail;
13334 range->group_next = 0;
13335 *rstate.low_tail = range;
13336 rstate.low_tail = &range->group_next;
13340 cgdebug_printf("hi: %5d degree %5d%s\n",
13341 range - rstate.lr, range->degree,
13342 (range->color != REG_UNSET) ? " (colored)": "");
13345 /* Color the live_ranges */
13346 colored = color_graph(state, &rstate);
13348 } while (!colored);
13350 /* Verify the graph was properly colored */
13351 verify_colors(state, &rstate);
13353 /* Move the colors from the graph to the triples */
13354 color_triples(state, &rstate);
13356 /* Cleanup the temporary data structures */
13357 cleanup_rstate(state, &rstate);
13360 /* Sparce Conditional Constant Propogation
13361 * =========================================
13365 struct lattice_node {
13367 struct triple *def;
13368 struct ssa_edge *out;
13369 struct flow_block *fblock;
13370 struct triple *val;
13371 /* lattice high val && !is_const(val)
13372 * lattice const is_const(val)
13373 * lattice low val == 0
13377 struct lattice_node *src;
13378 struct lattice_node *dst;
13379 struct ssa_edge *work_next;
13380 struct ssa_edge *work_prev;
13381 struct ssa_edge *out_next;
13384 struct flow_block *src;
13385 struct flow_block *dst;
13386 struct flow_edge *work_next;
13387 struct flow_edge *work_prev;
13388 struct flow_edge *in_next;
13389 struct flow_edge *out_next;
13392 struct flow_block {
13393 struct block *block;
13394 struct flow_edge *in;
13395 struct flow_edge *out;
13396 struct flow_edge left, right;
13401 struct lattice_node *lattice;
13402 struct ssa_edge *ssa_edges;
13403 struct flow_block *flow_blocks;
13404 struct flow_edge *flow_work_list;
13405 struct ssa_edge *ssa_work_list;
13409 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
13410 struct flow_edge *fedge)
13412 if (!scc->flow_work_list) {
13413 scc->flow_work_list = fedge;
13414 fedge->work_next = fedge->work_prev = fedge;
13417 struct flow_edge *ftail;
13418 ftail = scc->flow_work_list->work_prev;
13419 fedge->work_next = ftail->work_next;
13420 fedge->work_prev = ftail;
13421 fedge->work_next->work_prev = fedge;
13422 fedge->work_prev->work_next = fedge;
13426 static struct flow_edge *scc_next_fedge(
13427 struct compile_state *state, struct scc_state *scc)
13429 struct flow_edge *fedge;
13430 fedge = scc->flow_work_list;
13432 fedge->work_next->work_prev = fedge->work_prev;
13433 fedge->work_prev->work_next = fedge->work_next;
13434 if (fedge->work_next != fedge) {
13435 scc->flow_work_list = fedge->work_next;
13437 scc->flow_work_list = 0;
13443 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13444 struct ssa_edge *sedge)
13446 if (!scc->ssa_work_list) {
13447 scc->ssa_work_list = sedge;
13448 sedge->work_next = sedge->work_prev = sedge;
13451 struct ssa_edge *stail;
13452 stail = scc->ssa_work_list->work_prev;
13453 sedge->work_next = stail->work_next;
13454 sedge->work_prev = stail;
13455 sedge->work_next->work_prev = sedge;
13456 sedge->work_prev->work_next = sedge;
13460 static struct ssa_edge *scc_next_sedge(
13461 struct compile_state *state, struct scc_state *scc)
13463 struct ssa_edge *sedge;
13464 sedge = scc->ssa_work_list;
13466 sedge->work_next->work_prev = sedge->work_prev;
13467 sedge->work_prev->work_next = sedge->work_next;
13468 if (sedge->work_next != sedge) {
13469 scc->ssa_work_list = sedge->work_next;
13471 scc->ssa_work_list = 0;
13477 static void initialize_scc_state(
13478 struct compile_state *state, struct scc_state *scc)
13480 int ins_count, ssa_edge_count;
13481 int ins_index, ssa_edge_index, fblock_index;
13482 struct triple *first, *ins;
13483 struct block *block;
13484 struct flow_block *fblock;
13486 memset(scc, 0, sizeof(*scc));
13488 /* Inialize pass zero find out how much memory we need */
13489 first = RHS(state->main_function, 0);
13491 ins_count = ssa_edge_count = 0;
13493 struct triple_set *edge;
13495 for(edge = ins->use; edge; edge = edge->next) {
13499 } while(ins != first);
13501 fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
13502 ins_count, ssa_edge_count, state->last_vertex);
13504 scc->ins_count = ins_count;
13506 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
13508 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
13510 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1),
13513 /* Initialize pass one collect up the nodes */
13516 ins_index = ssa_edge_index = fblock_index = 0;
13519 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13520 block = ins->u.block;
13522 internal_error(state, ins, "label without block");
13525 block->vertex = fblock_index;
13526 fblock = &scc->flow_blocks[fblock_index];
13527 fblock->block = block;
13530 struct lattice_node *lnode;
13532 lnode = &scc->lattice[ins_index];
13535 lnode->fblock = fblock;
13536 lnode->val = ins; /* LATTICE HIGH */
13537 lnode->old_id = ins->id;
13538 ins->id = ins_index;
13541 } while(ins != first);
13542 /* Initialize pass two collect up the edges */
13547 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
13548 struct flow_edge *fedge, **ftail;
13549 struct block_set *bedge;
13550 block = ins->u.block;
13551 fblock = &scc->flow_blocks[block->vertex];
13554 ftail = &fblock->out;
13556 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
13557 if (fblock->left.dst->block != block->left) {
13558 internal_error(state, 0, "block mismatch");
13560 fblock->left.out_next = 0;
13561 *ftail = &fblock->left;
13562 ftail = &fblock->left.out_next;
13564 if (block->right) {
13565 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
13566 if (fblock->right.dst->block != block->right) {
13567 internal_error(state, 0, "block mismatch");
13569 fblock->right.out_next = 0;
13570 *ftail = &fblock->right;
13571 ftail = &fblock->right.out_next;
13573 for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
13574 fedge->src = fblock;
13575 fedge->work_next = fedge->work_prev = fedge;
13576 fedge->executable = 0;
13578 ftail = &fblock->in;
13579 for(bedge = block->use; bedge; bedge = bedge->next) {
13580 struct block *src_block;
13581 struct flow_block *sfblock;
13582 struct flow_edge *sfedge;
13583 src_block = bedge->member;
13584 sfblock = &scc->flow_blocks[src_block->vertex];
13586 if (src_block->left == block) {
13587 sfedge = &sfblock->left;
13589 sfedge = &sfblock->right;
13592 ftail = &sfedge->in_next;
13593 sfedge->in_next = 0;
13597 struct triple_set *edge;
13598 struct ssa_edge **stail;
13599 struct lattice_node *lnode;
13600 lnode = &scc->lattice[ins->id];
13602 stail = &lnode->out;
13603 for(edge = ins->use; edge; edge = edge->next) {
13604 struct ssa_edge *sedge;
13605 ssa_edge_index += 1;
13606 sedge = &scc->ssa_edges[ssa_edge_index];
13608 stail = &sedge->out_next;
13609 sedge->src = lnode;
13610 sedge->dst = &scc->lattice[edge->member->id];
13611 sedge->work_next = sedge->work_prev = sedge;
13612 sedge->out_next = 0;
13616 } while(ins != first);
13617 /* Setup a dummy block 0 as a node above the start node */
13619 struct flow_block *fblock, *dst;
13620 struct flow_edge *fedge;
13621 fblock = &scc->flow_blocks[0];
13624 fblock->out = &fblock->left;
13625 dst = &scc->flow_blocks[state->first_block->vertex];
13626 fedge = &fblock->left;
13627 fedge->src = fblock;
13629 fedge->work_next = fedge;
13630 fedge->work_prev = fedge;
13631 fedge->in_next = fedge->dst->in;
13632 fedge->out_next = 0;
13633 fedge->executable = 0;
13634 fedge->dst->in = fedge;
13636 /* Initialize the work lists */
13637 scc->flow_work_list = 0;
13638 scc->ssa_work_list = 0;
13639 scc_add_fedge(state, scc, fedge);
13642 fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
13643 ins_index, ssa_edge_index, fblock_index);
13648 static void free_scc_state(
13649 struct compile_state *state, struct scc_state *scc)
13651 xfree(scc->flow_blocks);
13652 xfree(scc->ssa_edges);
13653 xfree(scc->lattice);
13657 static struct lattice_node *triple_to_lattice(
13658 struct compile_state *state, struct scc_state *scc, struct triple *ins)
13660 if (ins->id <= 0) {
13661 internal_error(state, ins, "bad id");
13663 return &scc->lattice[ins->id];
13666 static struct triple *preserve_lval(
13667 struct compile_state *state, struct lattice_node *lnode)
13669 struct triple *old;
13670 /* Preserve the original value */
13672 old = dup_triple(state, lnode->val);
13673 if (lnode->val != lnode->def) {
13683 static int lval_changed(struct compile_state *state,
13684 struct triple *old, struct lattice_node *lnode)
13687 /* See if the lattice value has changed */
13689 if (!old && !lnode->val) {
13692 if (changed && lnode->val && !is_const(lnode->val)) {
13696 lnode->val && old &&
13697 (memcmp(lnode->val->param, old->param,
13698 TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
13699 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
13709 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
13710 struct lattice_node *lnode)
13712 struct lattice_node *tmp;
13713 struct triple **slot, *old;
13714 struct flow_edge *fedge;
13716 if (lnode->def->op != OP_PHI) {
13717 internal_error(state, lnode->def, "not phi");
13719 /* Store the original value */
13720 old = preserve_lval(state, lnode);
13722 /* default to lattice high */
13723 lnode->val = lnode->def;
13724 slot = &RHS(lnode->def, 0);
13726 for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
13727 if (!fedge->executable) {
13730 if (!slot[index]) {
13731 internal_error(state, lnode->def, "no phi value");
13733 tmp = triple_to_lattice(state, scc, slot[index]);
13734 /* meet(X, lattice low) = lattice low */
13738 /* meet(X, lattice high) = X */
13739 else if (!tmp->val) {
13740 lnode->val = lnode->val;
13742 /* meet(lattice high, X) = X */
13743 else if (!is_const(lnode->val)) {
13744 lnode->val = dup_triple(state, tmp->val);
13745 lnode->val->type = lnode->def->type;
13747 /* meet(const, const) = const or lattice low */
13748 else if (!constants_equal(state, lnode->val, tmp->val)) {
13756 fprintf(stderr, "phi: %d -> %s\n",
13758 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13760 /* If the lattice value has changed update the work lists. */
13761 if (lval_changed(state, old, lnode)) {
13762 struct ssa_edge *sedge;
13763 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13764 scc_add_sedge(state, scc, sedge);
13769 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
13770 struct lattice_node *lnode)
13773 struct triple *old, *scratch;
13774 struct triple **dexpr, **vexpr;
13777 /* Store the original value */
13778 old = preserve_lval(state, lnode);
13780 /* Reinitialize the value */
13781 lnode->val = scratch = dup_triple(state, lnode->def);
13782 scratch->id = lnode->old_id;
13783 scratch->next = scratch;
13784 scratch->prev = scratch;
13787 count = TRIPLE_SIZE(scratch->sizes);
13788 for(i = 0; i < count; i++) {
13789 dexpr = &lnode->def->param[i];
13790 vexpr = &scratch->param[i];
13792 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13793 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13795 struct lattice_node *tmp;
13796 tmp = triple_to_lattice(state, scc, *dexpr);
13797 *vexpr = (tmp->val)? tmp->val : tmp->def;
13800 if (scratch->op == OP_BRANCH) {
13801 scratch->next = lnode->def->next;
13803 /* Recompute the value */
13804 #warning "FIXME see if simplify does anything bad"
13805 /* So far it looks like only the strength reduction
13806 * optimization are things I need to worry about.
13808 simplify(state, scratch);
13809 /* Cleanup my value */
13810 if (scratch->use) {
13811 internal_error(state, lnode->def, "scratch used?");
13813 if ((scratch->prev != scratch) ||
13814 ((scratch->next != scratch) &&
13815 ((lnode->def->op != OP_BRANCH) ||
13816 (scratch->next != lnode->def->next)))) {
13817 internal_error(state, lnode->def, "scratch in list?");
13819 /* undo any uses... */
13820 count = TRIPLE_SIZE(scratch->sizes);
13821 for(i = 0; i < count; i++) {
13822 vexpr = &scratch->param[i];
13824 unuse_triple(*vexpr, scratch);
13827 if (!is_const(scratch)) {
13828 for(i = 0; i < count; i++) {
13829 dexpr = &lnode->def->param[i];
13830 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
13831 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
13833 struct lattice_node *tmp;
13834 tmp = triple_to_lattice(state, scc, *dexpr);
13842 (lnode->val->op == lnode->def->op) &&
13843 (memcmp(lnode->val->param, lnode->def->param,
13844 count * sizeof(lnode->val->param[0])) == 0) &&
13845 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
13846 lnode->val = lnode->def;
13848 /* Find the cases that are always lattice lo */
13850 triple_is_def(state, lnode->val) &&
13851 !triple_is_pure(state, lnode->val)) {
13855 (lnode->val->op == OP_SDECL) &&
13856 (lnode->val != lnode->def)) {
13857 internal_error(state, lnode->def, "bad sdecl");
13859 /* See if the lattice value has changed */
13860 changed = lval_changed(state, old, lnode);
13861 if (lnode->val != scratch) {
13867 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
13868 struct lattice_node *lnode)
13870 struct lattice_node *cond;
13873 struct flow_edge *fedge;
13874 fprintf(stderr, "branch: %d (",
13877 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
13878 fprintf(stderr, " %d", fedge->dst->block->vertex);
13880 fprintf(stderr, " )");
13881 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
13882 fprintf(stderr, " <- %d",
13883 RHS(lnode->def, 0)->id);
13885 fprintf(stderr, "\n");
13888 if (lnode->def->op != OP_BRANCH) {
13889 internal_error(state, lnode->def, "not branch");
13891 /* This only applies to conditional branches */
13892 if (TRIPLE_RHS(lnode->def->sizes) == 0) {
13895 cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
13896 if (cond->val && !is_const(cond->val)) {
13897 #warning "FIXME do I need to do something here?"
13898 warning(state, cond->def, "condition not constant?");
13901 if (cond->val == 0) {
13902 scc_add_fedge(state, scc, cond->fblock->out);
13903 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13905 else if (cond->val->u.cval) {
13906 scc_add_fedge(state, scc, cond->fblock->out->out_next);
13909 scc_add_fedge(state, scc, cond->fblock->out);
13914 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
13915 struct lattice_node *lnode)
13919 changed = compute_lnode_val(state, scc, lnode);
13922 struct triple **expr;
13923 fprintf(stderr, "expr: %3d %10s (",
13924 lnode->def->id, tops(lnode->def->op));
13925 expr = triple_rhs(state, lnode->def, 0);
13926 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
13928 fprintf(stderr, " %d", (*expr)->id);
13931 fprintf(stderr, " ) -> %s\n",
13932 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
13935 if (lnode->def->op == OP_BRANCH) {
13936 scc_visit_branch(state, scc, lnode);
13939 else if (changed) {
13940 struct ssa_edge *sedge;
13941 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
13942 scc_add_sedge(state, scc, sedge);
13947 static void scc_writeback_values(
13948 struct compile_state *state, struct scc_state *scc)
13950 struct triple *first, *ins;
13951 first = RHS(state->main_function, 0);
13954 struct lattice_node *lnode;
13955 lnode = triple_to_lattice(state, scc, ins);
13957 ins->id = lnode->old_id;
13959 if (lnode->val && !is_const(lnode->val)) {
13960 warning(state, lnode->def,
13961 "lattice node still high?");
13964 if (lnode->val && (lnode->val != ins)) {
13965 /* See if it something I know how to write back */
13966 switch(lnode->val->op) {
13968 mkconst(state, ins, lnode->val->u.cval);
13971 mkaddr_const(state, ins,
13972 MISC(lnode->val, 0), lnode->val->u.cval);
13975 /* By default don't copy the changes,
13976 * recompute them in place instead.
13978 simplify(state, ins);
13981 if (is_const(lnode->val) &&
13982 !constants_equal(state, lnode->val, ins)) {
13983 internal_error(state, 0, "constants not equal");
13985 /* Free the lattice nodes */
13990 } while(ins != first);
13993 static void scc_transform(struct compile_state *state)
13995 struct scc_state scc;
13997 initialize_scc_state(state, &scc);
13999 while(scc.flow_work_list || scc.ssa_work_list) {
14000 struct flow_edge *fedge;
14001 struct ssa_edge *sedge;
14002 struct flow_edge *fptr;
14003 while((fedge = scc_next_fedge(state, &scc))) {
14004 struct block *block;
14005 struct triple *ptr;
14006 struct flow_block *fblock;
14009 if (fedge->executable) {
14013 internal_error(state, 0, "fedge without dst");
14016 internal_error(state, 0, "fedge without src");
14018 fedge->executable = 1;
14019 fblock = fedge->dst;
14020 block = fblock->block;
14022 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14023 if (fptr->executable) {
14028 fprintf(stderr, "vertex: %d time: %d\n",
14029 block->vertex, time);
14033 for(ptr = block->first; !done; ptr = ptr->next) {
14034 struct lattice_node *lnode;
14035 done = (ptr == block->last);
14036 lnode = &scc.lattice[ptr->id];
14037 if (ptr->op == OP_PHI) {
14038 scc_visit_phi(state, &scc, lnode);
14040 else if (time == 1) {
14041 scc_visit_expr(state, &scc, lnode);
14044 if (fblock->out && !fblock->out->out_next) {
14045 scc_add_fedge(state, &scc, fblock->out);
14048 while((sedge = scc_next_sedge(state, &scc))) {
14049 struct lattice_node *lnode;
14050 struct flow_block *fblock;
14051 lnode = sedge->dst;
14052 fblock = lnode->fblock;
14054 fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14055 sedge - scc.ssa_edges,
14056 sedge->src->def->id,
14057 sedge->dst->def->id);
14059 if (lnode->def->op == OP_PHI) {
14060 scc_visit_phi(state, &scc, lnode);
14063 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14064 if (fptr->executable) {
14069 scc_visit_expr(state, &scc, lnode);
14075 scc_writeback_values(state, &scc);
14076 free_scc_state(state, &scc);
14080 static void transform_to_arch_instructions(struct compile_state *state)
14082 struct triple *ins, *first;
14083 first = RHS(state->main_function, 0);
14086 ins = transform_to_arch_instruction(state, ins);
14087 } while(ins != first);
14090 #if DEBUG_CONSISTENCY
14091 static void verify_uses(struct compile_state *state)
14093 struct triple *first, *ins;
14094 struct triple_set *set;
14095 first = RHS(state->main_function, 0);
14098 struct triple **expr;
14099 expr = triple_rhs(state, ins, 0);
14100 for(; expr; expr = triple_rhs(state, ins, expr)) {
14101 struct triple *rhs;
14103 for(set = rhs?rhs->use:0; set; set = set->next) {
14104 if (set->member == ins) {
14109 internal_error(state, ins, "rhs not used");
14112 expr = triple_lhs(state, ins, 0);
14113 for(; expr; expr = triple_lhs(state, ins, expr)) {
14114 struct triple *lhs;
14116 for(set = lhs?lhs->use:0; set; set = set->next) {
14117 if (set->member == ins) {
14122 internal_error(state, ins, "lhs not used");
14126 } while(ins != first);
14129 static void verify_blocks(struct compile_state *state)
14131 struct triple *ins;
14132 struct block *block;
14133 block = state->first_block;
14138 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14139 if (!triple_stores_block(state, ins)) {
14142 if (ins->u.block != block) {
14143 internal_error(state, ins, "inconsitent block specified");
14146 if (!triple_stores_block(state, block->last->next)) {
14147 internal_error(state, block->last->next,
14148 "cannot find next block");
14150 block = block->last->next->u.block;
14152 internal_error(state, block->last->next,
14155 } while(block != state->first_block);
14158 static void verify_domination(struct compile_state *state)
14160 struct triple *first, *ins;
14161 struct triple_set *set;
14162 if (!state->first_block) {
14166 first = RHS(state->main_function, 0);
14169 for(set = ins->use; set; set = set->next) {
14170 struct triple **expr;
14171 if (set->member->op == OP_PHI) {
14174 /* See if the use is on the righ hand side */
14175 expr = triple_rhs(state, set->member, 0);
14176 for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14177 if (*expr == ins) {
14182 !tdominates(state, ins, set->member)) {
14183 internal_error(state, set->member,
14184 "non dominated rhs use?");
14188 } while(ins != first);
14191 static void verify_piece(struct compile_state *state)
14193 struct triple *first, *ins;
14194 first = RHS(state->main_function, 0);
14197 struct triple *ptr;
14199 lhs = TRIPLE_LHS(ins->sizes);
14200 if ((ins->op == OP_WRITE) || (ins->op == OP_STORE)) {
14203 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14204 if (ptr != LHS(ins, i)) {
14205 internal_error(state, ins, "malformed lhs on %s",
14208 if (ptr->op != OP_PIECE) {
14209 internal_error(state, ins, "bad lhs op %s at %d on %s",
14210 tops(ptr->op), i, tops(ins->op));
14212 if (ptr->u.cval != i) {
14213 internal_error(state, ins, "bad u.cval of %d %d expected",
14218 } while(ins != first);
14220 static void verify_ins_colors(struct compile_state *state)
14222 struct triple *first, *ins;
14224 first = RHS(state->main_function, 0);
14228 } while(ins != first);
14230 static void verify_consistency(struct compile_state *state)
14232 verify_uses(state);
14233 verify_blocks(state);
14234 verify_domination(state);
14235 verify_piece(state);
14236 verify_ins_colors(state);
14239 #define verify_consistency(state) do {} while(0)
14240 #endif /* DEBUG_USES */
14242 static void optimize(struct compile_state *state)
14244 if (state->debug & DEBUG_TRIPLES) {
14245 print_triples(state);
14247 /* Replace structures with simpler data types */
14248 flatten_structures(state);
14249 if (state->debug & DEBUG_TRIPLES) {
14250 print_triples(state);
14252 verify_consistency(state);
14253 /* Analize the intermediate code */
14254 setup_basic_blocks(state);
14255 analyze_idominators(state);
14256 analyze_ipdominators(state);
14257 /* Transform the code to ssa form */
14258 transform_to_ssa_form(state);
14259 verify_consistency(state);
14260 if (state->debug & DEBUG_CODE_ELIMINATION) {
14261 fprintf(stdout, "After transform_to_ssa_form\n");
14262 print_blocks(state, stdout);
14264 /* Do strength reduction and simple constant optimizations */
14265 if (state->optimize >= 1) {
14266 simplify_all(state);
14268 verify_consistency(state);
14269 /* Propogate constants throughout the code */
14270 if (state->optimize >= 2) {
14271 #warning "FIXME fix scc_transform"
14272 scc_transform(state);
14273 transform_from_ssa_form(state);
14274 free_basic_blocks(state);
14275 setup_basic_blocks(state);
14276 analyze_idominators(state);
14277 analyze_ipdominators(state);
14278 transform_to_ssa_form(state);
14280 verify_consistency(state);
14281 #warning "WISHLIST implement single use constants (least possible register pressure)"
14282 #warning "WISHLIST implement induction variable elimination"
14283 /* Select architecture instructions and an initial partial
14284 * coloring based on architecture constraints.
14286 transform_to_arch_instructions(state);
14287 verify_consistency(state);
14288 if (state->debug & DEBUG_ARCH_CODE) {
14289 printf("After transform_to_arch_instructions\n");
14290 print_blocks(state, stdout);
14291 print_control_flow(state);
14293 eliminate_inefectual_code(state);
14294 verify_consistency(state);
14295 if (state->debug & DEBUG_CODE_ELIMINATION) {
14296 printf("After eliminate_inefectual_code\n");
14297 print_blocks(state, stdout);
14298 print_control_flow(state);
14300 verify_consistency(state);
14301 /* Color all of the variables to see if they will fit in registers */
14302 insert_copies_to_phi(state);
14303 if (state->debug & DEBUG_INSERTED_COPIES) {
14304 printf("After insert_copies_to_phi\n");
14305 print_blocks(state, stdout);
14306 print_control_flow(state);
14308 verify_consistency(state);
14309 insert_mandatory_copies(state);
14310 if (state->debug & DEBUG_INSERTED_COPIES) {
14311 printf("After insert_mandatory_copies\n");
14312 print_blocks(state, stdout);
14313 print_control_flow(state);
14315 verify_consistency(state);
14316 allocate_registers(state);
14317 verify_consistency(state);
14318 if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14319 print_blocks(state, stdout);
14321 if (state->debug & DEBUG_CONTROL_FLOW) {
14322 print_control_flow(state);
14324 /* Remove the optimization information.
14325 * This is more to check for memory consistency than to free memory.
14327 free_basic_blocks(state);
14330 static void print_op_asm(struct compile_state *state,
14331 struct triple *ins, FILE *fp)
14333 struct asm_info *info;
14335 unsigned lhs, rhs, i;
14336 info = ins->u.ainfo;
14337 lhs = TRIPLE_LHS(ins->sizes);
14338 rhs = TRIPLE_RHS(ins->sizes);
14339 /* Don't count the clobbers in lhs */
14340 for(i = 0; i < lhs; i++) {
14341 if (LHS(ins, i)->type == &void_type) {
14346 fprintf(fp, "#ASM\n");
14348 for(ptr = info->str; *ptr; ptr++) {
14350 unsigned long param;
14351 struct triple *piece;
14361 param = strtoul(ptr, &next, 10);
14363 error(state, ins, "Invalid asm template");
14365 if (param >= (lhs + rhs)) {
14366 error(state, ins, "Invalid param %%%u in asm template",
14369 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14371 arch_reg_str(ID_REG(piece->id)));
14374 fprintf(fp, "\n#NOT ASM\n");
14378 /* Only use the low x86 byte registers. This allows me
14379 * allocate the entire register when a byte register is used.
14381 #define X86_4_8BIT_GPRS 1
14383 /* Recognized x86 cpu variants */
14391 #define CPU_DEFAULT CPU_I386
14393 /* The x86 register classes */
14394 #define REGC_FLAGS 0
14395 #define REGC_GPR8 1
14396 #define REGC_GPR16 2
14397 #define REGC_GPR32 3
14398 #define REGC_GPR64 4
14401 #define REGC_GPR32_8 7
14402 #define REGC_GPR16_8 8
14403 #define REGC_IMM32 9
14404 #define REGC_IMM16 10
14405 #define REGC_IMM8 11
14406 #define LAST_REGC REGC_IMM8
14407 #if LAST_REGC >= MAX_REGC
14408 #error "MAX_REGC is to low"
14411 /* Register class masks */
14412 #define REGCM_FLAGS (1 << REGC_FLAGS)
14413 #define REGCM_GPR8 (1 << REGC_GPR8)
14414 #define REGCM_GPR16 (1 << REGC_GPR16)
14415 #define REGCM_GPR32 (1 << REGC_GPR32)
14416 #define REGCM_GPR64 (1 << REGC_GPR64)
14417 #define REGCM_MMX (1 << REGC_MMX)
14418 #define REGCM_XMM (1 << REGC_XMM)
14419 #define REGCM_GPR32_8 (1 << REGC_GPR32_8)
14420 #define REGCM_GPR16_8 (1 << REGC_GPR16_8)
14421 #define REGCM_IMM32 (1 << REGC_IMM32)
14422 #define REGCM_IMM16 (1 << REGC_IMM16)
14423 #define REGCM_IMM8 (1 << REGC_IMM8)
14424 #define REGCM_ALL ((1 << (LAST_REGC + 1)) - 1)
14426 /* The x86 registers */
14427 #define REG_EFLAGS 2
14428 #define REGC_FLAGS_FIRST REG_EFLAGS
14429 #define REGC_FLAGS_LAST REG_EFLAGS
14438 #define REGC_GPR8_FIRST REG_AL
14439 #if X86_4_8BIT_GPRS
14440 #define REGC_GPR8_LAST REG_DL
14442 #define REGC_GPR8_LAST REG_DH
14452 #define REGC_GPR16_FIRST REG_AX
14453 #define REGC_GPR16_LAST REG_SP
14462 #define REGC_GPR32_FIRST REG_EAX
14463 #define REGC_GPR32_LAST REG_ESP
14464 #define REG_EDXEAX 27
14465 #define REGC_GPR64_FIRST REG_EDXEAX
14466 #define REGC_GPR64_LAST REG_EDXEAX
14467 #define REG_MMX0 28
14468 #define REG_MMX1 29
14469 #define REG_MMX2 30
14470 #define REG_MMX3 31
14471 #define REG_MMX4 32
14472 #define REG_MMX5 33
14473 #define REG_MMX6 34
14474 #define REG_MMX7 35
14475 #define REGC_MMX_FIRST REG_MMX0
14476 #define REGC_MMX_LAST REG_MMX7
14477 #define REG_XMM0 36
14478 #define REG_XMM1 37
14479 #define REG_XMM2 38
14480 #define REG_XMM3 39
14481 #define REG_XMM4 40
14482 #define REG_XMM5 41
14483 #define REG_XMM6 42
14484 #define REG_XMM7 43
14485 #define REGC_XMM_FIRST REG_XMM0
14486 #define REGC_XMM_LAST REG_XMM7
14487 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
14488 #define LAST_REG REG_XMM7
14490 #define REGC_GPR32_8_FIRST REG_EAX
14491 #define REGC_GPR32_8_LAST REG_EDX
14492 #define REGC_GPR16_8_FIRST REG_AX
14493 #define REGC_GPR16_8_LAST REG_DX
14495 #define REGC_IMM8_FIRST -1
14496 #define REGC_IMM8_LAST -1
14497 #define REGC_IMM16_FIRST -2
14498 #define REGC_IMM16_LAST -1
14499 #define REGC_IMM32_FIRST -4
14500 #define REGC_IMM32_LAST -1
14502 #if LAST_REG >= MAX_REGISTERS
14503 #error "MAX_REGISTERS to low"
14507 static unsigned regc_size[LAST_REGC +1] = {
14508 [REGC_FLAGS] = REGC_FLAGS_LAST - REGC_FLAGS_FIRST + 1,
14509 [REGC_GPR8] = REGC_GPR8_LAST - REGC_GPR8_FIRST + 1,
14510 [REGC_GPR16] = REGC_GPR16_LAST - REGC_GPR16_FIRST + 1,
14511 [REGC_GPR32] = REGC_GPR32_LAST - REGC_GPR32_FIRST + 1,
14512 [REGC_GPR64] = REGC_GPR64_LAST - REGC_GPR64_FIRST + 1,
14513 [REGC_MMX] = REGC_MMX_LAST - REGC_MMX_FIRST + 1,
14514 [REGC_XMM] = REGC_XMM_LAST - REGC_XMM_FIRST + 1,
14515 [REGC_GPR32_8] = REGC_GPR32_8_LAST - REGC_GPR32_8_FIRST + 1,
14516 [REGC_GPR16_8] = REGC_GPR16_8_LAST - REGC_GPR16_8_FIRST + 1,
14522 static const struct {
14524 } regcm_bound[LAST_REGC + 1] = {
14525 [REGC_FLAGS] = { REGC_FLAGS_FIRST, REGC_FLAGS_LAST },
14526 [REGC_GPR8] = { REGC_GPR8_FIRST, REGC_GPR8_LAST },
14527 [REGC_GPR16] = { REGC_GPR16_FIRST, REGC_GPR16_LAST },
14528 [REGC_GPR32] = { REGC_GPR32_FIRST, REGC_GPR32_LAST },
14529 [REGC_GPR64] = { REGC_GPR64_FIRST, REGC_GPR64_LAST },
14530 [REGC_MMX] = { REGC_MMX_FIRST, REGC_MMX_LAST },
14531 [REGC_XMM] = { REGC_XMM_FIRST, REGC_XMM_LAST },
14532 [REGC_GPR32_8] = { REGC_GPR32_8_FIRST, REGC_GPR32_8_LAST },
14533 [REGC_GPR16_8] = { REGC_GPR16_8_FIRST, REGC_GPR16_8_LAST },
14534 [REGC_IMM32] = { REGC_IMM32_FIRST, REGC_IMM32_LAST },
14535 [REGC_IMM16] = { REGC_IMM16_FIRST, REGC_IMM16_LAST },
14536 [REGC_IMM8] = { REGC_IMM8_FIRST, REGC_IMM8_LAST },
14539 static int arch_encode_cpu(const char *cpu)
14545 { "i386", CPU_I386 },
14553 for(ptr = cpus; ptr->name; ptr++) {
14554 if (strcmp(ptr->name, cpu) == 0) {
14561 static unsigned arch_regc_size(struct compile_state *state, int class)
14563 if ((class < 0) || (class > LAST_REGC)) {
14566 return regc_size[class];
14568 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
14570 /* See if two register classes may have overlapping registers */
14571 unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14572 REGCM_GPR32_8 | REGCM_GPR32 | REGCM_GPR64;
14574 /* Special case for the immediates */
14575 if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14576 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
14577 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
14578 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
14581 return (regcm1 & regcm2) ||
14582 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
14585 static void arch_reg_equivs(
14586 struct compile_state *state, unsigned *equiv, int reg)
14588 if ((reg < 0) || (reg > LAST_REG)) {
14589 internal_error(state, 0, "invalid register");
14594 #if X86_4_8BIT_GPRS
14598 *equiv++ = REG_EAX;
14599 *equiv++ = REG_EDXEAX;
14602 #if X86_4_8BIT_GPRS
14606 *equiv++ = REG_EAX;
14607 *equiv++ = REG_EDXEAX;
14610 #if X86_4_8BIT_GPRS
14614 *equiv++ = REG_EBX;
14618 #if X86_4_8BIT_GPRS
14622 *equiv++ = REG_EBX;
14625 #if X86_4_8BIT_GPRS
14629 *equiv++ = REG_ECX;
14633 #if X86_4_8BIT_GPRS
14637 *equiv++ = REG_ECX;
14640 #if X86_4_8BIT_GPRS
14644 *equiv++ = REG_EDX;
14645 *equiv++ = REG_EDXEAX;
14648 #if X86_4_8BIT_GPRS
14652 *equiv++ = REG_EDX;
14653 *equiv++ = REG_EDXEAX;
14658 *equiv++ = REG_EAX;
14659 *equiv++ = REG_EDXEAX;
14664 *equiv++ = REG_EBX;
14669 *equiv++ = REG_ECX;
14674 *equiv++ = REG_EDX;
14675 *equiv++ = REG_EDXEAX;
14678 *equiv++ = REG_ESI;
14681 *equiv++ = REG_EDI;
14684 *equiv++ = REG_EBP;
14687 *equiv++ = REG_ESP;
14693 *equiv++ = REG_EDXEAX;
14709 *equiv++ = REG_EDXEAX;
14730 *equiv++ = REG_EAX;
14731 *equiv++ = REG_EDX;
14734 *equiv++ = REG_UNSET;
14737 static unsigned arch_avail_mask(struct compile_state *state)
14739 unsigned avail_mask;
14740 avail_mask = REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16 |
14741 REGCM_GPR32 | REGCM_GPR32_8 | REGCM_GPR64 |
14742 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
14743 switch(state->cpu) {
14746 avail_mask |= REGCM_MMX;
14750 avail_mask |= REGCM_MMX | REGCM_XMM;
14754 /* Don't enable 8 bit values until I can force both operands
14755 * to be 8bits simultaneously.
14757 avail_mask &= ~(REGCM_GPR8 | REGCM_GPR16_8 | REGCM_GPR16);
14762 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
14764 unsigned mask, result;
14767 result &= arch_avail_mask(state);
14769 for(class = 0, mask = 1; mask; mask <<= 1, class++) {
14770 if ((result & mask) == 0) {
14773 if (class > LAST_REGC) {
14776 for(class2 = 0; class2 <= LAST_REGC; class2++) {
14777 if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
14778 (regcm_bound[class2].last <= regcm_bound[class].last)) {
14779 result |= (1 << class2);
14786 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
14791 for(class = 0; class <= LAST_REGC; class++) {
14792 if ((reg >= regcm_bound[class].first) &&
14793 (reg <= regcm_bound[class].last)) {
14794 mask |= (1 << class);
14798 internal_error(state, 0, "reg %d not in any class", reg);
14803 static struct reg_info arch_reg_constraint(
14804 struct compile_state *state, struct type *type, const char *constraint)
14806 static const struct {
14810 } constraints[] = {
14811 { 'r', REGCM_GPR32, REG_UNSET },
14812 { 'g', REGCM_GPR32, REG_UNSET },
14813 { 'p', REGCM_GPR32, REG_UNSET },
14814 { 'q', REGCM_GPR8, REG_UNSET },
14815 { 'Q', REGCM_GPR32_8, REG_UNSET },
14816 { 'x', REGCM_XMM, REG_UNSET },
14817 { 'y', REGCM_MMX, REG_UNSET },
14818 { 'a', REGCM_GPR32, REG_EAX },
14819 { 'b', REGCM_GPR32, REG_EBX },
14820 { 'c', REGCM_GPR32, REG_ECX },
14821 { 'd', REGCM_GPR32, REG_EDX },
14822 { 'D', REGCM_GPR32, REG_EDI },
14823 { 'S', REGCM_GPR32, REG_ESI },
14824 { '\0', 0, REG_UNSET },
14826 unsigned int regcm;
14827 unsigned int mask, reg;
14828 struct reg_info result;
14830 regcm = arch_type_to_regcm(state, type);
14833 for(ptr = constraint; *ptr; ptr++) {
14838 for(i = 0; constraints[i].class != '\0'; i++) {
14839 if (constraints[i].class == *ptr) {
14843 if (constraints[i].class == '\0') {
14844 error(state, 0, "invalid register constraint ``%c''", *ptr);
14847 if ((constraints[i].mask & regcm) == 0) {
14848 error(state, 0, "invalid register class %c specified",
14851 mask |= constraints[i].mask;
14852 if (constraints[i].reg != REG_UNSET) {
14853 if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
14854 error(state, 0, "Only one register may be specified");
14856 reg = constraints[i].reg;
14860 result.regcm = mask;
14864 static struct reg_info arch_reg_clobber(
14865 struct compile_state *state, const char *clobber)
14867 struct reg_info result;
14868 if (strcmp(clobber, "memory") == 0) {
14869 result.reg = REG_UNSET;
14872 else if (strcmp(clobber, "%eax") == 0) {
14873 result.reg = REG_EAX;
14874 result.regcm = REGCM_GPR32;
14876 else if (strcmp(clobber, "%ebx") == 0) {
14877 result.reg = REG_EBX;
14878 result.regcm = REGCM_GPR32;
14880 else if (strcmp(clobber, "%ecx") == 0) {
14881 result.reg = REG_ECX;
14882 result.regcm = REGCM_GPR32;
14884 else if (strcmp(clobber, "%edx") == 0) {
14885 result.reg = REG_EDX;
14886 result.regcm = REGCM_GPR32;
14888 else if (strcmp(clobber, "%esi") == 0) {
14889 result.reg = REG_ESI;
14890 result.regcm = REGCM_GPR32;
14892 else if (strcmp(clobber, "%edi") == 0) {
14893 result.reg = REG_EDI;
14894 result.regcm = REGCM_GPR32;
14896 else if (strcmp(clobber, "%ebp") == 0) {
14897 result.reg = REG_EBP;
14898 result.regcm = REGCM_GPR32;
14900 else if (strcmp(clobber, "%esp") == 0) {
14901 result.reg = REG_ESP;
14902 result.regcm = REGCM_GPR32;
14904 else if (strcmp(clobber, "cc") == 0) {
14905 result.reg = REG_EFLAGS;
14906 result.regcm = REGCM_FLAGS;
14908 else if ((strncmp(clobber, "xmm", 3) == 0) &&
14909 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14910 result.reg = REG_XMM0 + octdigval(clobber[3]);
14911 result.regcm = REGCM_XMM;
14913 else if ((strncmp(clobber, "mmx", 3) == 0) &&
14914 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
14915 result.reg = REG_MMX0 + octdigval(clobber[3]);
14916 result.regcm = REGCM_MMX;
14919 error(state, 0, "Invalid register clobber");
14920 result.reg = REG_UNSET;
14926 static int do_select_reg(struct compile_state *state,
14927 char *used, int reg, unsigned classes)
14933 mask = arch_reg_regcm(state, reg);
14934 return (classes & mask) ? reg : REG_UNSET;
14937 static int arch_select_free_register(
14938 struct compile_state *state, char *used, int classes)
14940 /* Preference: flags, 8bit gprs, 32bit gprs, other 32bit reg
14941 * other types of registers.
14945 for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
14946 reg = do_select_reg(state, used, i, classes);
14948 for(i = REGC_GPR32_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR32_LAST); i++) {
14949 reg = do_select_reg(state, used, i, classes);
14951 for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
14952 reg = do_select_reg(state, used, i, classes);
14954 for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
14955 reg = do_select_reg(state, used, i, classes);
14957 for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
14958 reg = do_select_reg(state, used, i, classes);
14960 for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
14961 reg = do_select_reg(state, used, i, classes);
14963 for(i = REGC_GPR64_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR64_LAST); i++) {
14964 reg = do_select_reg(state, used, i, classes);
14970 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
14972 #warning "FIXME force types smaller (if legal) before I get here"
14973 unsigned avail_mask;
14976 avail_mask = arch_avail_mask(state);
14977 switch(type->type & TYPE_MASK) {
14984 mask = REGCM_GPR8 |
14985 REGCM_GPR16 | REGCM_GPR16_8 |
14986 REGCM_GPR32 | REGCM_GPR32_8 |
14988 REGCM_MMX | REGCM_XMM |
14989 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
14993 mask = REGCM_GPR16 | REGCM_GPR16_8 |
14994 REGCM_GPR32 | REGCM_GPR32_8 |
14996 REGCM_MMX | REGCM_XMM |
14997 REGCM_IMM32 | REGCM_IMM16;
15004 mask = REGCM_GPR32 | REGCM_GPR32_8 |
15005 REGCM_GPR64 | REGCM_MMX | REGCM_XMM |
15009 internal_error(state, 0, "no register class for type");
15012 mask &= avail_mask;
15016 static int is_imm32(struct triple *imm)
15018 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15019 (imm->op == OP_ADDRCONST);
15022 static int is_imm16(struct triple *imm)
15024 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15026 static int is_imm8(struct triple *imm)
15028 return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15031 static int get_imm32(struct triple *ins, struct triple **expr)
15033 struct triple *imm;
15035 while(imm->op == OP_COPY) {
15038 if (!is_imm32(imm)) {
15041 unuse_triple(*expr, ins);
15042 use_triple(imm, ins);
15047 static int get_imm8(struct triple *ins, struct triple **expr)
15049 struct triple *imm;
15051 while(imm->op == OP_COPY) {
15054 if (!is_imm8(imm)) {
15057 unuse_triple(*expr, ins);
15058 use_triple(imm, ins);
15063 #define TEMPLATE_NOP 0
15064 #define TEMPLATE_INTCONST8 1
15065 #define TEMPLATE_INTCONST32 2
15066 #define TEMPLATE_COPY_REG 3
15067 #define TEMPLATE_COPY_IMM32 4
15068 #define TEMPLATE_COPY_IMM16 5
15069 #define TEMPLATE_COPY_IMM8 6
15070 #define TEMPLATE_PHI 7
15071 #define TEMPLATE_STORE8 8
15072 #define TEMPLATE_STORE16 9
15073 #define TEMPLATE_STORE32 10
15074 #define TEMPLATE_LOAD8 11
15075 #define TEMPLATE_LOAD16 12
15076 #define TEMPLATE_LOAD32 13
15077 #define TEMPLATE_BINARY_REG 14
15078 #define TEMPLATE_BINARY_IMM 15
15079 #define TEMPLATE_SL_CL 16
15080 #define TEMPLATE_SL_IMM 17
15081 #define TEMPLATE_UNARY 18
15082 #define TEMPLATE_CMP_REG 19
15083 #define TEMPLATE_CMP_IMM 20
15084 #define TEMPLATE_TEST 21
15085 #define TEMPLATE_SET 22
15086 #define TEMPLATE_JMP 23
15087 #define TEMPLATE_INB_DX 24
15088 #define TEMPLATE_INB_IMM 25
15089 #define TEMPLATE_INW_DX 26
15090 #define TEMPLATE_INW_IMM 27
15091 #define TEMPLATE_INL_DX 28
15092 #define TEMPLATE_INL_IMM 29
15093 #define TEMPLATE_OUTB_DX 30
15094 #define TEMPLATE_OUTB_IMM 31
15095 #define TEMPLATE_OUTW_DX 32
15096 #define TEMPLATE_OUTW_IMM 33
15097 #define TEMPLATE_OUTL_DX 34
15098 #define TEMPLATE_OUTL_IMM 35
15099 #define TEMPLATE_BSF 36
15100 #define TEMPLATE_RDMSR 37
15101 #define TEMPLATE_WRMSR 38
15102 #define LAST_TEMPLATE TEMPLATE_WRMSR
15103 #if LAST_TEMPLATE >= MAX_TEMPLATES
15104 #error "MAX_TEMPLATES to low"
15107 #define COPY_REGCM (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8 | REGCM_MMX | REGCM_XMM)
15108 #define COPY32_REGCM (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15110 static struct ins_template templates[] = {
15111 [TEMPLATE_NOP] = {},
15112 [TEMPLATE_INTCONST8] = {
15113 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15115 [TEMPLATE_INTCONST32] = {
15116 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15118 [TEMPLATE_COPY_REG] = {
15119 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15120 .rhs = { [0] = { REG_UNSET, COPY_REGCM } },
15122 [TEMPLATE_COPY_IMM32] = {
15123 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15124 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15126 [TEMPLATE_COPY_IMM16] = {
15127 .lhs = { [0] = { REG_UNSET, COPY32_REGCM | REGCM_GPR16 } },
15128 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 } },
15130 [TEMPLATE_COPY_IMM8] = {
15131 .lhs = { [0] = { REG_UNSET, COPY_REGCM } },
15132 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15135 .lhs = { [0] = { REG_VIRT0, COPY_REGCM } },
15137 [ 0] = { REG_VIRT0, COPY_REGCM },
15138 [ 1] = { REG_VIRT0, COPY_REGCM },
15139 [ 2] = { REG_VIRT0, COPY_REGCM },
15140 [ 3] = { REG_VIRT0, COPY_REGCM },
15141 [ 4] = { REG_VIRT0, COPY_REGCM },
15142 [ 5] = { REG_VIRT0, COPY_REGCM },
15143 [ 6] = { REG_VIRT0, COPY_REGCM },
15144 [ 7] = { REG_VIRT0, COPY_REGCM },
15145 [ 8] = { REG_VIRT0, COPY_REGCM },
15146 [ 9] = { REG_VIRT0, COPY_REGCM },
15147 [10] = { REG_VIRT0, COPY_REGCM },
15148 [11] = { REG_VIRT0, COPY_REGCM },
15149 [12] = { REG_VIRT0, COPY_REGCM },
15150 [13] = { REG_VIRT0, COPY_REGCM },
15151 [14] = { REG_VIRT0, COPY_REGCM },
15152 [15] = { REG_VIRT0, COPY_REGCM },
15154 [TEMPLATE_STORE8] = {
15155 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15156 .rhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15158 [TEMPLATE_STORE16] = {
15159 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15160 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15162 [TEMPLATE_STORE32] = {
15163 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15164 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15166 [TEMPLATE_LOAD8] = {
15167 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15168 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15170 [TEMPLATE_LOAD16] = {
15171 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15172 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15174 [TEMPLATE_LOAD32] = {
15175 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15176 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15178 [TEMPLATE_BINARY_REG] = {
15179 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15181 [0] = { REG_VIRT0, REGCM_GPR32 },
15182 [1] = { REG_UNSET, REGCM_GPR32 },
15185 [TEMPLATE_BINARY_IMM] = {
15186 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15188 [0] = { REG_VIRT0, REGCM_GPR32 },
15189 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15192 [TEMPLATE_SL_CL] = {
15193 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15195 [0] = { REG_VIRT0, REGCM_GPR32 },
15196 [1] = { REG_CL, REGCM_GPR8 },
15199 [TEMPLATE_SL_IMM] = {
15200 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15202 [0] = { REG_VIRT0, REGCM_GPR32 },
15203 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15206 [TEMPLATE_UNARY] = {
15207 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15208 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15210 [TEMPLATE_CMP_REG] = {
15211 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15213 [0] = { REG_UNSET, REGCM_GPR32 },
15214 [1] = { REG_UNSET, REGCM_GPR32 },
15217 [TEMPLATE_CMP_IMM] = {
15218 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15220 [0] = { REG_UNSET, REGCM_GPR32 },
15221 [1] = { REG_UNNEEDED, REGCM_IMM32 },
15224 [TEMPLATE_TEST] = {
15225 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15226 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15229 .lhs = { [0] = { REG_UNSET, REGCM_GPR8 } },
15230 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15233 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
15235 [TEMPLATE_INB_DX] = {
15236 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15237 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15239 [TEMPLATE_INB_IMM] = {
15240 .lhs = { [0] = { REG_AL, REGCM_GPR8 } },
15241 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15243 [TEMPLATE_INW_DX] = {
15244 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15245 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15247 [TEMPLATE_INW_IMM] = {
15248 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
15249 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15251 [TEMPLATE_INL_DX] = {
15252 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15253 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
15255 [TEMPLATE_INL_IMM] = {
15256 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
15257 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15259 [TEMPLATE_OUTB_DX] = {
15261 [0] = { REG_AL, REGCM_GPR8 },
15262 [1] = { REG_DX, REGCM_GPR16 },
15265 [TEMPLATE_OUTB_IMM] = {
15267 [0] = { REG_AL, REGCM_GPR8 },
15268 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15271 [TEMPLATE_OUTW_DX] = {
15273 [0] = { REG_AX, REGCM_GPR16 },
15274 [1] = { REG_DX, REGCM_GPR16 },
15277 [TEMPLATE_OUTW_IMM] = {
15279 [0] = { REG_AX, REGCM_GPR16 },
15280 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15283 [TEMPLATE_OUTL_DX] = {
15285 [0] = { REG_EAX, REGCM_GPR32 },
15286 [1] = { REG_DX, REGCM_GPR16 },
15289 [TEMPLATE_OUTL_IMM] = {
15291 [0] = { REG_EAX, REGCM_GPR32 },
15292 [1] = { REG_UNNEEDED, REGCM_IMM8 },
15296 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15297 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15299 [TEMPLATE_RDMSR] = {
15301 [0] = { REG_EAX, REGCM_GPR32 },
15302 [1] = { REG_EDX, REGCM_GPR32 },
15304 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
15306 [TEMPLATE_WRMSR] = {
15308 [0] = { REG_ECX, REGCM_GPR32 },
15309 [1] = { REG_EAX, REGCM_GPR32 },
15310 [2] = { REG_EDX, REGCM_GPR32 },
15315 static void fixup_branches(struct compile_state *state,
15316 struct triple *cmp, struct triple *use, int jmp_op)
15318 struct triple_set *entry, *next;
15319 for(entry = use->use; entry; entry = next) {
15320 next = entry->next;
15321 if (entry->member->op == OP_COPY) {
15322 fixup_branches(state, cmp, entry->member, jmp_op);
15324 else if (entry->member->op == OP_BRANCH) {
15325 struct triple *branch, *test;
15326 struct triple *left, *right;
15328 left = RHS(cmp, 0);
15329 if (TRIPLE_RHS(cmp->sizes) > 1) {
15330 right = RHS(cmp, 1);
15332 branch = entry->member;
15333 test = pre_triple(state, branch,
15334 cmp->op, cmp->type, left, right);
15335 test->template_id = TEMPLATE_TEST;
15336 if (cmp->op == OP_CMP) {
15337 test->template_id = TEMPLATE_CMP_REG;
15338 if (get_imm32(test, &RHS(test, 1))) {
15339 test->template_id = TEMPLATE_CMP_IMM;
15342 use_triple(RHS(test, 0), test);
15343 use_triple(RHS(test, 1), test);
15344 unuse_triple(RHS(branch, 0), branch);
15345 RHS(branch, 0) = test;
15346 branch->op = jmp_op;
15347 branch->template_id = TEMPLATE_JMP;
15348 use_triple(RHS(branch, 0), branch);
15353 static void bool_cmp(struct compile_state *state,
15354 struct triple *ins, int cmp_op, int jmp_op, int set_op)
15356 struct triple_set *entry, *next;
15357 struct triple *set;
15359 /* Put a barrier up before the cmp which preceeds the
15360 * copy instruction. If a set actually occurs this gives
15361 * us a chance to move variables in registers out of the way.
15364 /* Modify the comparison operator */
15366 ins->template_id = TEMPLATE_TEST;
15367 if (cmp_op == OP_CMP) {
15368 ins->template_id = TEMPLATE_CMP_REG;
15369 if (get_imm32(ins, &RHS(ins, 1))) {
15370 ins->template_id = TEMPLATE_CMP_IMM;
15373 /* Generate the instruction sequence that will transform the
15374 * result of the comparison into a logical value.
15376 set = post_triple(state, ins, set_op, ins->type, ins, 0);
15377 use_triple(ins, set);
15378 set->template_id = TEMPLATE_SET;
15380 for(entry = ins->use; entry; entry = next) {
15381 next = entry->next;
15382 if (entry->member == set) {
15385 replace_rhs_use(state, ins, set, entry->member);
15387 fixup_branches(state, ins, set, jmp_op);
15390 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
15392 struct triple *next;
15394 lhs = TRIPLE_LHS(ins->sizes);
15395 for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
15396 if (next != LHS(ins, i)) {
15397 internal_error(state, ins, "malformed lhs on %s",
15400 if (next->op != OP_PIECE) {
15401 internal_error(state, ins, "bad lhs op %s at %d on %s",
15402 tops(next->op), i, tops(ins->op));
15404 if (next->u.cval != i) {
15405 internal_error(state, ins, "bad u.cval of %d %d expected",
15412 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
15414 struct ins_template *template;
15415 struct reg_info result;
15417 if (ins->op == OP_PIECE) {
15418 index = ins->u.cval;
15419 ins = MISC(ins, 0);
15421 zlhs = TRIPLE_LHS(ins->sizes);
15422 if (triple_is_def(state, ins)) {
15425 if (index >= zlhs) {
15426 internal_error(state, ins, "index %d out of range for %s\n",
15427 index, tops(ins->op));
15431 template = &ins->u.ainfo->tmpl;
15434 if (ins->template_id > LAST_TEMPLATE) {
15435 internal_error(state, ins, "bad template number %d",
15438 template = &templates[ins->template_id];
15441 result = template->lhs[index];
15442 result.regcm = arch_regcm_normalize(state, result.regcm);
15443 if (result.reg != REG_UNNEEDED) {
15444 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15446 if (result.regcm == 0) {
15447 internal_error(state, ins, "lhs %d regcm == 0", index);
15452 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
15454 struct reg_info result;
15455 struct ins_template *template;
15456 if ((index > TRIPLE_RHS(ins->sizes)) ||
15457 (ins->op == OP_PIECE)) {
15458 internal_error(state, ins, "index %d out of range for %s\n",
15459 index, tops(ins->op));
15463 template = &ins->u.ainfo->tmpl;
15466 if (ins->template_id > LAST_TEMPLATE) {
15467 internal_error(state, ins, "bad template number %d",
15470 template = &templates[ins->template_id];
15473 result = template->rhs[index];
15474 result.regcm = arch_regcm_normalize(state, result.regcm);
15475 if (result.regcm == 0) {
15476 internal_error(state, ins, "rhs %d regcm == 0", index);
15481 static struct triple *transform_to_arch_instruction(
15482 struct compile_state *state, struct triple *ins)
15484 /* Transform from generic 3 address instructions
15485 * to archtecture specific instructions.
15486 * And apply architecture specific constrains to instructions.
15487 * Copies are inserted to preserve the register flexibility
15488 * of 3 address instructions.
15490 struct triple *next;
15494 ins->template_id = TEMPLATE_INTCONST32;
15495 if (ins->u.cval < 256) {
15496 ins->template_id = TEMPLATE_INTCONST8;
15500 ins->template_id = TEMPLATE_INTCONST32;
15506 ins->template_id = TEMPLATE_NOP;
15509 ins->template_id = TEMPLATE_COPY_REG;
15510 if (is_imm8(RHS(ins, 0))) {
15511 ins->template_id = TEMPLATE_COPY_IMM8;
15513 else if (is_imm16(RHS(ins, 0))) {
15514 ins->template_id = TEMPLATE_COPY_IMM16;
15516 else if (is_imm32(RHS(ins, 0))) {
15517 ins->template_id = TEMPLATE_COPY_IMM32;
15519 else if (is_const(RHS(ins, 0))) {
15520 internal_error(state, ins, "bad constant passed to copy");
15524 ins->template_id = TEMPLATE_PHI;
15527 switch(ins->type->type & TYPE_MASK) {
15528 case TYPE_CHAR: case TYPE_UCHAR:
15529 ins->template_id = TEMPLATE_STORE8;
15531 case TYPE_SHORT: case TYPE_USHORT:
15532 ins->template_id = TEMPLATE_STORE16;
15534 case TYPE_INT: case TYPE_UINT:
15535 case TYPE_LONG: case TYPE_ULONG:
15537 ins->template_id = TEMPLATE_STORE32;
15540 internal_error(state, ins, "unknown type in store");
15545 switch(ins->type->type & TYPE_MASK) {
15546 case TYPE_CHAR: case TYPE_UCHAR:
15547 ins->template_id = TEMPLATE_LOAD8;
15551 ins->template_id = TEMPLATE_LOAD16;
15558 ins->template_id = TEMPLATE_LOAD32;
15561 internal_error(state, ins, "unknown type in load");
15571 ins->template_id = TEMPLATE_BINARY_REG;
15572 if (get_imm32(ins, &RHS(ins, 1))) {
15573 ins->template_id = TEMPLATE_BINARY_IMM;
15579 ins->template_id = TEMPLATE_SL_CL;
15580 if (get_imm8(ins, &RHS(ins, 1))) {
15581 ins->template_id = TEMPLATE_SL_IMM;
15586 ins->template_id = TEMPLATE_UNARY;
15589 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
15592 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15595 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
15598 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
15601 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
15604 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
15607 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
15610 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
15613 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
15616 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
15619 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
15622 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
15625 if (TRIPLE_RHS(ins->sizes) > 0) {
15626 internal_error(state, ins, "bad branch test");
15629 ins->template_id = TEMPLATE_NOP;
15635 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
15636 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
15637 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
15639 if (get_imm8(ins, &RHS(ins, 0))) {
15640 ins->template_id += 1;
15647 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
15648 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
15649 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
15651 if (get_imm8(ins, &RHS(ins, 1))) {
15652 ins->template_id += 1;
15657 ins->template_id = TEMPLATE_BSF;
15660 ins->template_id = TEMPLATE_RDMSR;
15661 next = after_lhs(state, ins);
15664 ins->template_id = TEMPLATE_WRMSR;
15667 ins->template_id = TEMPLATE_NOP;
15670 ins->template_id = TEMPLATE_NOP;
15671 next = after_lhs(state, ins);
15673 /* Already transformed instructions */
15675 ins->template_id = TEMPLATE_TEST;
15678 ins->template_id = TEMPLATE_CMP_REG;
15679 if (get_imm32(ins, &RHS(ins, 1))) {
15680 ins->template_id = TEMPLATE_CMP_IMM;
15683 case OP_JMP_EQ: case OP_JMP_NOTEQ:
15684 case OP_JMP_SLESS: case OP_JMP_ULESS:
15685 case OP_JMP_SMORE: case OP_JMP_UMORE:
15686 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
15687 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
15688 ins->template_id = TEMPLATE_JMP;
15690 case OP_SET_EQ: case OP_SET_NOTEQ:
15691 case OP_SET_SLESS: case OP_SET_ULESS:
15692 case OP_SET_SMORE: case OP_SET_UMORE:
15693 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
15694 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
15695 ins->template_id = TEMPLATE_SET;
15697 /* Unhandled instructions */
15700 internal_error(state, ins, "unhandled ins: %d %s\n",
15701 ins->op, tops(ins->op));
15707 static void generate_local_labels(struct compile_state *state)
15709 struct triple *first, *label;
15712 first = RHS(state->main_function, 0);
15715 if ((label->op == OP_LABEL) ||
15716 (label->op == OP_SDECL)) {
15718 label->u.cval = ++label_counter;
15724 label = label->next;
15725 } while(label != first);
15728 static int check_reg(struct compile_state *state,
15729 struct triple *triple, int classes)
15733 reg = ID_REG(triple->id);
15734 if (reg == REG_UNSET) {
15735 internal_error(state, triple, "register not set");
15737 mask = arch_reg_regcm(state, reg);
15738 if (!(classes & mask)) {
15739 internal_error(state, triple, "reg %d in wrong class",
15745 static const char *arch_reg_str(int reg)
15747 static const char *regs[] = {
15751 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
15752 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
15753 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
15755 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
15756 "%xmm0", "%xmm1", "%xmm2", "%xmm3",
15757 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
15759 if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
15766 static const char *reg(struct compile_state *state, struct triple *triple,
15770 reg = check_reg(state, triple, classes);
15771 return arch_reg_str(reg);
15774 const char *type_suffix(struct compile_state *state, struct type *type)
15776 const char *suffix;
15777 switch(size_of(state, type)) {
15778 case 1: suffix = "b"; break;
15779 case 2: suffix = "w"; break;
15780 case 4: suffix = "l"; break;
15782 internal_error(state, 0, "unknown suffix");
15789 static void print_const_val(
15790 struct compile_state *state, struct triple *ins, FILE *fp)
15794 fprintf(fp, " $%ld ",
15795 (long_t)(ins->u.cval));
15798 fprintf(fp, " $L%s%lu+%lu ",
15799 state->label_prefix,
15800 MISC(ins, 0)->u.cval,
15804 internal_error(state, ins, "unknown constant type");
15809 static void print_binary_op(struct compile_state *state,
15810 const char *op, struct triple *ins, FILE *fp)
15813 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15814 if (RHS(ins, 0)->id != ins->id) {
15815 internal_error(state, ins, "invalid register assignment");
15817 if (is_const(RHS(ins, 1))) {
15818 fprintf(fp, "\t%s ", op);
15819 print_const_val(state, RHS(ins, 1), fp);
15820 fprintf(fp, ", %s\n",
15821 reg(state, RHS(ins, 0), mask));
15824 unsigned lmask, rmask;
15826 lreg = check_reg(state, RHS(ins, 0), mask);
15827 rreg = check_reg(state, RHS(ins, 1), mask);
15828 lmask = arch_reg_regcm(state, lreg);
15829 rmask = arch_reg_regcm(state, rreg);
15830 mask = lmask & rmask;
15831 fprintf(fp, "\t%s %s, %s\n",
15833 reg(state, RHS(ins, 1), mask),
15834 reg(state, RHS(ins, 0), mask));
15837 static void print_unary_op(struct compile_state *state,
15838 const char *op, struct triple *ins, FILE *fp)
15841 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15842 fprintf(fp, "\t%s %s\n",
15844 reg(state, RHS(ins, 0), mask));
15847 static void print_op_shift(struct compile_state *state,
15848 const char *op, struct triple *ins, FILE *fp)
15851 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
15852 if (RHS(ins, 0)->id != ins->id) {
15853 internal_error(state, ins, "invalid register assignment");
15855 if (is_const(RHS(ins, 1))) {
15856 fprintf(fp, "\t%s ", op);
15857 print_const_val(state, RHS(ins, 1), fp);
15858 fprintf(fp, ", %s\n",
15859 reg(state, RHS(ins, 0), mask));
15862 fprintf(fp, "\t%s %s, %s\n",
15864 reg(state, RHS(ins, 1), REGCM_GPR8),
15865 reg(state, RHS(ins, 0), mask));
15869 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
15876 case OP_INB: op = "inb", mask = REGCM_GPR8; break;
15877 case OP_INW: op = "inw", mask = REGCM_GPR16; break;
15878 case OP_INL: op = "inl", mask = REGCM_GPR32; break;
15880 internal_error(state, ins, "not an in operation");
15884 dreg = check_reg(state, ins, mask);
15885 if (!reg_is_reg(state, dreg, REG_EAX)) {
15886 internal_error(state, ins, "dst != %%eax");
15888 if (is_const(RHS(ins, 0))) {
15889 fprintf(fp, "\t%s ", op);
15890 print_const_val(state, RHS(ins, 0), fp);
15891 fprintf(fp, ", %s\n",
15892 reg(state, ins, mask));
15896 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
15897 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15898 internal_error(state, ins, "src != %%dx");
15900 fprintf(fp, "\t%s %s, %s\n",
15902 reg(state, RHS(ins, 0), REGCM_GPR16),
15903 reg(state, ins, mask));
15907 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
15914 case OP_OUTB: op = "outb", mask = REGCM_GPR8; break;
15915 case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
15916 case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
15918 internal_error(state, ins, "not an out operation");
15922 lreg = check_reg(state, RHS(ins, 0), mask);
15923 if (!reg_is_reg(state, lreg, REG_EAX)) {
15924 internal_error(state, ins, "src != %%eax");
15926 if (is_const(RHS(ins, 1))) {
15927 fprintf(fp, "\t%s %s,",
15928 op, reg(state, RHS(ins, 0), mask));
15929 print_const_val(state, RHS(ins, 1), fp);
15934 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
15935 if (!reg_is_reg(state, addr_reg, REG_DX)) {
15936 internal_error(state, ins, "dst != %%dx");
15938 fprintf(fp, "\t%s %s, %s\n",
15940 reg(state, RHS(ins, 0), mask),
15941 reg(state, RHS(ins, 1), REGCM_GPR16));
15945 static void print_op_move(struct compile_state *state,
15946 struct triple *ins, FILE *fp)
15948 /* op_move is complex because there are many types
15949 * of registers we can move between.
15950 * Because OP_COPY will be introduced in arbitrary locations
15951 * OP_COPY must not affect flags.
15953 int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
15954 struct triple *dst, *src;
15955 if (ins->op == OP_COPY) {
15959 else if (ins->op == OP_WRITE) {
15964 internal_error(state, ins, "unknown move operation");
15967 if (!is_const(src)) {
15968 int src_reg, dst_reg;
15969 int src_regcm, dst_regcm;
15970 src_reg = ID_REG(src->id);
15971 dst_reg = ID_REG(dst->id);
15972 src_regcm = arch_reg_regcm(state, src_reg);
15973 dst_regcm = arch_reg_regcm(state, dst_reg);
15974 /* If the class is the same just move the register */
15975 if (src_regcm & dst_regcm &
15976 (REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32)) {
15977 if ((src_reg != dst_reg) || !omit_copy) {
15978 fprintf(fp, "\tmov %s, %s\n",
15979 reg(state, src, src_regcm),
15980 reg(state, dst, dst_regcm));
15983 /* Move 32bit to 16bit */
15984 else if ((src_regcm & REGCM_GPR32) &&
15985 (dst_regcm & REGCM_GPR16)) {
15986 src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
15987 if ((src_reg != dst_reg) || !omit_copy) {
15988 fprintf(fp, "\tmovw %s, %s\n",
15989 arch_reg_str(src_reg),
15990 arch_reg_str(dst_reg));
15993 /* Move 32bit to 8bit */
15994 else if ((src_regcm & REGCM_GPR32_8) &&
15995 (dst_regcm & REGCM_GPR8))
15997 src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
15998 if ((src_reg != dst_reg) || !omit_copy) {
15999 fprintf(fp, "\tmovb %s, %s\n",
16000 arch_reg_str(src_reg),
16001 arch_reg_str(dst_reg));
16004 /* Move 16bit to 8bit */
16005 else if ((src_regcm & REGCM_GPR16_8) &&
16006 (dst_regcm & REGCM_GPR8))
16008 src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
16009 if ((src_reg != dst_reg) || !omit_copy) {
16010 fprintf(fp, "\tmovb %s, %s\n",
16011 arch_reg_str(src_reg),
16012 arch_reg_str(dst_reg));
16015 /* Move 8/16bit to 16/32bit */
16016 else if ((src_regcm & (REGCM_GPR8 | REGCM_GPR16)) &&
16017 (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
16019 op = is_signed(src->type)? "movsx": "movzx";
16020 fprintf(fp, "\t%s %s, %s\n",
16022 reg(state, src, src_regcm),
16023 reg(state, dst, dst_regcm));
16025 /* Move between sse registers */
16026 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
16027 if ((src_reg != dst_reg) || !omit_copy) {
16028 fprintf(fp, "\tmovdqa %s, %s\n",
16029 reg(state, src, src_regcm),
16030 reg(state, dst, dst_regcm));
16033 /* Move between mmx registers or mmx & sse registers */
16034 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16035 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16036 if ((src_reg != dst_reg) || !omit_copy) {
16037 fprintf(fp, "\tmovq %s, %s\n",
16038 reg(state, src, src_regcm),
16039 reg(state, dst, dst_regcm));
16042 /* Move between 32bit gprs & mmx/sse registers */
16043 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
16044 (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
16045 fprintf(fp, "\tmovd %s, %s\n",
16046 reg(state, src, src_regcm),
16047 reg(state, dst, dst_regcm));
16049 #if X86_4_8BIT_GPRS
16050 /* Move from 8bit gprs to mmx/sse registers */
16051 else if ((src_regcm & REGCM_GPR8) && (src_reg <= REG_DL) &&
16052 (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
16055 op = is_signed(src->type)? "movsx":"movzx";
16056 mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16057 fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
16059 reg(state, src, src_regcm),
16060 arch_reg_str(mid_reg),
16061 arch_reg_str(mid_reg),
16062 reg(state, dst, dst_regcm));
16064 /* Move from mmx/sse registers and 8bit gprs */
16065 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
16066 (dst_regcm & REGCM_GPR8) && (dst_reg <= REG_DL)) {
16068 mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16069 fprintf(fp, "\tmovd %s, %s\n",
16070 reg(state, src, src_regcm),
16071 arch_reg_str(mid_reg));
16073 /* Move from 32bit gprs to 16bit gprs */
16074 else if ((src_regcm & REGCM_GPR32) &&
16075 (dst_regcm & REGCM_GPR16)) {
16076 dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
16077 if ((src_reg != dst_reg) || !omit_copy) {
16078 fprintf(fp, "\tmov %s, %s\n",
16079 arch_reg_str(src_reg),
16080 arch_reg_str(dst_reg));
16083 /* Move from 32bit gprs to 8bit gprs */
16084 else if ((src_regcm & REGCM_GPR32) &&
16085 (dst_regcm & REGCM_GPR8)) {
16086 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
16087 if ((src_reg != dst_reg) || !omit_copy) {
16088 fprintf(fp, "\tmov %s, %s\n",
16089 arch_reg_str(src_reg),
16090 arch_reg_str(dst_reg));
16093 /* Move from 16bit gprs to 8bit gprs */
16094 else if ((src_regcm & REGCM_GPR16) &&
16095 (dst_regcm & REGCM_GPR8)) {
16096 dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
16097 if ((src_reg != dst_reg) || !omit_copy) {
16098 fprintf(fp, "\tmov %s, %s\n",
16099 arch_reg_str(src_reg),
16100 arch_reg_str(dst_reg));
16103 #endif /* X86_4_8BIT_GPRS */
16105 internal_error(state, ins, "unknown copy type");
16109 fprintf(fp, "\tmov ");
16110 print_const_val(state, src, fp);
16111 fprintf(fp, ", %s\n",
16112 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8));
16116 static void print_op_load(struct compile_state *state,
16117 struct triple *ins, FILE *fp)
16119 struct triple *dst, *src;
16122 if (is_const(src) || is_const(dst)) {
16123 internal_error(state, ins, "unknown load operation");
16125 fprintf(fp, "\tmov (%s), %s\n",
16126 reg(state, src, REGCM_GPR32),
16127 reg(state, dst, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32));
16131 static void print_op_store(struct compile_state *state,
16132 struct triple *ins, FILE *fp)
16134 struct triple *dst, *src;
16137 if (is_const(src) && (src->op == OP_INTCONST)) {
16139 value = (long_t)(src->u.cval);
16140 fprintf(fp, "\tmov%s $%ld, (%s)\n",
16141 type_suffix(state, src->type),
16143 reg(state, dst, REGCM_GPR32));
16145 else if (is_const(dst) && (dst->op == OP_INTCONST)) {
16146 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
16147 type_suffix(state, src->type),
16148 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16152 if (is_const(src) || is_const(dst)) {
16153 internal_error(state, ins, "unknown store operation");
16155 fprintf(fp, "\tmov%s %s, (%s)\n",
16156 type_suffix(state, src->type),
16157 reg(state, src, REGCM_GPR8 | REGCM_GPR16 | REGCM_GPR32),
16158 reg(state, dst, REGCM_GPR32));
16164 static void print_op_smul(struct compile_state *state,
16165 struct triple *ins, FILE *fp)
16167 if (!is_const(RHS(ins, 1))) {
16168 fprintf(fp, "\timul %s, %s\n",
16169 reg(state, RHS(ins, 1), REGCM_GPR32),
16170 reg(state, RHS(ins, 0), REGCM_GPR32));
16173 fprintf(fp, "\timul ");
16174 print_const_val(state, RHS(ins, 1), fp);
16175 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
16179 static void print_op_cmp(struct compile_state *state,
16180 struct triple *ins, FILE *fp)
16184 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16185 dreg = check_reg(state, ins, REGCM_FLAGS);
16186 if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
16187 internal_error(state, ins, "bad dest register for cmp");
16189 if (is_const(RHS(ins, 1))) {
16190 fprintf(fp, "\tcmp ");
16191 print_const_val(state, RHS(ins, 1), fp);
16192 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
16195 unsigned lmask, rmask;
16197 lreg = check_reg(state, RHS(ins, 0), mask);
16198 rreg = check_reg(state, RHS(ins, 1), mask);
16199 lmask = arch_reg_regcm(state, lreg);
16200 rmask = arch_reg_regcm(state, rreg);
16201 mask = lmask & rmask;
16202 fprintf(fp, "\tcmp %s, %s\n",
16203 reg(state, RHS(ins, 1), mask),
16204 reg(state, RHS(ins, 0), mask));
16208 static void print_op_test(struct compile_state *state,
16209 struct triple *ins, FILE *fp)
16212 mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8;
16213 fprintf(fp, "\ttest %s, %s\n",
16214 reg(state, RHS(ins, 0), mask),
16215 reg(state, RHS(ins, 0), mask));
16218 static void print_op_branch(struct compile_state *state,
16219 struct triple *branch, FILE *fp)
16221 const char *bop = "j";
16222 if (branch->op == OP_JMP) {
16223 if (TRIPLE_RHS(branch->sizes) != 0) {
16224 internal_error(state, branch, "jmp with condition?");
16229 struct triple *ptr;
16230 if (TRIPLE_RHS(branch->sizes) != 1) {
16231 internal_error(state, branch, "jmpcc without condition?");
16233 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
16234 if ((RHS(branch, 0)->op != OP_CMP) &&
16235 (RHS(branch, 0)->op != OP_TEST)) {
16236 internal_error(state, branch, "bad branch test");
16238 #warning "FIXME I have observed instructions between the test and branch instructions"
16239 ptr = RHS(branch, 0);
16240 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
16241 if (ptr->op != OP_COPY) {
16242 internal_error(state, branch, "branch does not follow test");
16245 switch(branch->op) {
16246 case OP_JMP_EQ: bop = "jz"; break;
16247 case OP_JMP_NOTEQ: bop = "jnz"; break;
16248 case OP_JMP_SLESS: bop = "jl"; break;
16249 case OP_JMP_ULESS: bop = "jb"; break;
16250 case OP_JMP_SMORE: bop = "jg"; break;
16251 case OP_JMP_UMORE: bop = "ja"; break;
16252 case OP_JMP_SLESSEQ: bop = "jle"; break;
16253 case OP_JMP_ULESSEQ: bop = "jbe"; break;
16254 case OP_JMP_SMOREEQ: bop = "jge"; break;
16255 case OP_JMP_UMOREEQ: bop = "jae"; break;
16257 internal_error(state, branch, "Invalid branch op");
16262 fprintf(fp, "\t%s L%s%lu\n",
16264 state->label_prefix,
16265 TARG(branch, 0)->u.cval);
16268 static void print_op_set(struct compile_state *state,
16269 struct triple *set, FILE *fp)
16271 const char *sop = "set";
16272 if (TRIPLE_RHS(set->sizes) != 1) {
16273 internal_error(state, set, "setcc without condition?");
16275 check_reg(state, RHS(set, 0), REGCM_FLAGS);
16276 if ((RHS(set, 0)->op != OP_CMP) &&
16277 (RHS(set, 0)->op != OP_TEST)) {
16278 internal_error(state, set, "bad set test");
16280 if (RHS(set, 0)->next != set) {
16281 internal_error(state, set, "set does not follow test");
16284 case OP_SET_EQ: sop = "setz"; break;
16285 case OP_SET_NOTEQ: sop = "setnz"; break;
16286 case OP_SET_SLESS: sop = "setl"; break;
16287 case OP_SET_ULESS: sop = "setb"; break;
16288 case OP_SET_SMORE: sop = "setg"; break;
16289 case OP_SET_UMORE: sop = "seta"; break;
16290 case OP_SET_SLESSEQ: sop = "setle"; break;
16291 case OP_SET_ULESSEQ: sop = "setbe"; break;
16292 case OP_SET_SMOREEQ: sop = "setge"; break;
16293 case OP_SET_UMOREEQ: sop = "setae"; break;
16295 internal_error(state, set, "Invalid set op");
16298 fprintf(fp, "\t%s %s\n",
16299 sop, reg(state, set, REGCM_GPR8));
16302 static void print_op_bit_scan(struct compile_state *state,
16303 struct triple *ins, FILE *fp)
16307 case OP_BSF: op = "bsf"; break;
16308 case OP_BSR: op = "bsr"; break;
16310 internal_error(state, ins, "unknown bit scan");
16320 reg(state, RHS(ins, 0), REGCM_GPR32),
16321 reg(state, ins, REGCM_GPR32),
16322 reg(state, ins, REGCM_GPR32));
16325 static void print_const(struct compile_state *state,
16326 struct triple *ins, FILE *fp)
16330 switch(ins->type->type & TYPE_MASK) {
16333 fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16337 fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16343 fprintf(fp, ".int %lu\n", ins->u.cval);
16346 internal_error(state, ins, "Unknown constant type");
16351 unsigned char *blob;
16353 size = size_of(state, ins->type);
16354 blob = ins->u.blob;
16355 for(i = 0; i < size; i++) {
16356 fprintf(fp, ".byte 0x%02x\n",
16362 internal_error(state, ins, "Unknown constant type");
16367 #define TEXT_SECTION ".rom.text"
16368 #define DATA_SECTION ".rom.data"
16370 static void print_sdecl(struct compile_state *state,
16371 struct triple *ins, FILE *fp)
16373 fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16374 fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16375 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16376 print_const(state, MISC(ins, 0), fp);
16377 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16381 static void print_instruction(struct compile_state *state,
16382 struct triple *ins, FILE *fp)
16384 /* Assumption: after I have exted the register allocator
16385 * everything is in a valid register.
16389 print_op_asm(state, ins, fp);
16391 case OP_ADD: print_binary_op(state, "add", ins, fp); break;
16392 case OP_SUB: print_binary_op(state, "sub", ins, fp); break;
16393 case OP_AND: print_binary_op(state, "and", ins, fp); break;
16394 case OP_XOR: print_binary_op(state, "xor", ins, fp); break;
16395 case OP_OR: print_binary_op(state, "or", ins, fp); break;
16396 case OP_SL: print_op_shift(state, "shl", ins, fp); break;
16397 case OP_USR: print_op_shift(state, "shr", ins, fp); break;
16398 case OP_SSR: print_op_shift(state, "sar", ins, fp); break;
16399 case OP_POS: break;
16400 case OP_NEG: print_unary_op(state, "neg", ins, fp); break;
16401 case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
16405 /* Don't generate anything here for constants */
16407 /* Don't generate anything for variable declarations. */
16410 print_sdecl(state, ins, fp);
16414 print_op_move(state, ins, fp);
16417 print_op_load(state, ins, fp);
16420 print_op_store(state, ins, fp);
16423 print_op_smul(state, ins, fp);
16425 case OP_CMP: print_op_cmp(state, ins, fp); break;
16426 case OP_TEST: print_op_test(state, ins, fp); break;
16428 case OP_JMP_EQ: case OP_JMP_NOTEQ:
16429 case OP_JMP_SLESS: case OP_JMP_ULESS:
16430 case OP_JMP_SMORE: case OP_JMP_UMORE:
16431 case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16432 case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16433 print_op_branch(state, ins, fp);
16435 case OP_SET_EQ: case OP_SET_NOTEQ:
16436 case OP_SET_SLESS: case OP_SET_ULESS:
16437 case OP_SET_SMORE: case OP_SET_UMORE:
16438 case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16439 case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16440 print_op_set(state, ins, fp);
16442 case OP_INB: case OP_INW: case OP_INL:
16443 print_op_in(state, ins, fp);
16445 case OP_OUTB: case OP_OUTW: case OP_OUTL:
16446 print_op_out(state, ins, fp);
16450 print_op_bit_scan(state, ins, fp);
16453 after_lhs(state, ins);
16454 fprintf(fp, "\trdmsr\n");
16457 fprintf(fp, "\twrmsr\n");
16460 fprintf(fp, "\thlt\n");
16466 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
16468 /* Ignore OP_PIECE */
16471 /* Operations I am not yet certain how to handle */
16473 case OP_SDIV: case OP_UDIV:
16474 case OP_SMOD: case OP_UMOD:
16475 /* Operations that should never get here */
16476 case OP_LTRUE: case OP_LFALSE: case OP_EQ: case OP_NOTEQ:
16477 case OP_SLESS: case OP_ULESS: case OP_SMORE: case OP_UMORE:
16478 case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
16480 internal_error(state, ins, "unknown op: %d %s",
16481 ins->op, tops(ins->op));
16486 static void print_instructions(struct compile_state *state)
16488 struct triple *first, *ins;
16489 int print_location;
16492 const char *last_filename;
16494 print_location = 1;
16498 fp = state->output;
16499 fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16500 first = RHS(state->main_function, 0);
16503 if (print_location &&
16504 ((last_filename != ins->filename) ||
16505 (last_line != ins->line) ||
16506 (last_col != ins->col))) {
16507 fprintf(fp, "\t/* %s:%d */\n",
16508 ins->filename, ins->line);
16509 last_filename = ins->filename;
16510 last_line = ins->line;
16511 last_col = ins->col;
16514 print_instruction(state, ins, fp);
16516 } while(ins != first);
16519 static void generate_code(struct compile_state *state)
16521 generate_local_labels(state);
16522 print_instructions(state);
16526 static void print_tokens(struct compile_state *state)
16529 tk = &state->token[0];
16534 next_token(state, 0);
16536 loc(stdout, state, 0);
16537 printf("%s <- `%s'\n",
16539 tk->ident ? tk->ident->name :
16540 tk->str_len ? tk->val.str : "");
16542 } while(tk->tok != TOK_EOF);
16545 static void compile(const char *filename, const char *ofilename,
16546 int cpu, int debug, int opt, const char *label_prefix)
16549 struct compile_state state;
16550 memset(&state, 0, sizeof(state));
16552 for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
16553 memset(&state.token[i], 0, sizeof(state.token[i]));
16554 state.token[i].tok = -1;
16556 /* Remember the debug settings */
16558 state.debug = debug;
16559 state.optimize = opt;
16560 /* Remember the output filename */
16561 state.ofilename = ofilename;
16562 state.output = fopen(state.ofilename, "w");
16563 if (!state.output) {
16564 error(&state, 0, "Cannot open output file %s\n",
16567 /* Remember the label prefix */
16568 state.label_prefix = label_prefix;
16569 /* Prep the preprocessor */
16570 state.if_depth = 0;
16571 state.if_value = 0;
16572 /* register the C keywords */
16573 register_keywords(&state);
16574 /* register the keywords the macro preprocessor knows */
16575 register_macro_keywords(&state);
16576 /* Memorize where some special keywords are. */
16577 state.i_continue = lookup(&state, "continue", 8);
16578 state.i_break = lookup(&state, "break", 5);
16579 /* Enter the globl definition scope */
16580 start_scope(&state);
16581 register_builtins(&state);
16582 compile_file(&state, filename, 1);
16584 print_tokens(&state);
16587 /* Exit the global definition scope */
16590 /* Now that basic compilation has happened
16591 * optimize the intermediate code
16595 generate_code(&state);
16597 fprintf(stderr, "done\n");
16601 static void version(void)
16603 printf("romcc " VERSION " released " RELEASE_DATE "\n");
16606 static void usage(void)
16610 "Usage: romcc <source>.c\n"
16611 "Compile a C source file without using ram\n"
16615 static void arg_error(char *fmt, ...)
16618 va_start(args, fmt);
16619 vfprintf(stderr, fmt, args);
16625 int main(int argc, char **argv)
16627 const char *filename;
16628 const char *ofilename;
16629 const char *label_prefix;
16636 ofilename = "auto.inc";
16640 while((argc > 1) && (argc != last_argc)) {
16642 if (strncmp(argv[1], "--debug=", 8) == 0) {
16643 debug = atoi(argv[1] + 8);
16647 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
16648 label_prefix= argv[1] + 15;
16652 else if ((strcmp(argv[1],"-O") == 0) ||
16653 (strcmp(argv[1], "-O1") == 0)) {
16658 else if (strcmp(argv[1],"-O2") == 0) {
16663 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
16664 ofilename = argv[2];
16668 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
16669 cpu = arch_encode_cpu(argv[1] + 6);
16670 if (cpu == BAD_CPU) {
16671 arg_error("Invalid cpu specified: %s\n",
16679 arg_error("Wrong argument count %d\n", argc);
16681 filename = argv[1];
16682 compile(filename, ofilename, cpu, debug, optimize, label_prefix);